Bitcoin Core 29.99.0
P2P Digital Currency
wallet_tests.cpp
Go to the documentation of this file.
1// Copyright (c) 2012-2022 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 <future>
8#include <memory>
9#include <stdint.h>
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 <policy/policy.h>
17#include <rpc/server.h>
18#include <script/solver.h>
19#include <test/util/logging.h>
20#include <test/util/random.h>
22#include <util/translation.h>
23#include <validation.h>
24#include <validationinterface.h>
25#include <wallet/coincontrol.h>
26#include <wallet/context.h>
27#include <wallet/receive.h>
28#include <wallet/spend.h>
29#include <wallet/test/util.h>
31
32#include <boost/test/unit_test.hpp>
33#include <univalue.h>
34
36
37namespace wallet {
38
39// Ensure that fee levels defined in the wallet are at least as high
40// as the default levels for node policy.
41static_assert(DEFAULT_TRANSACTION_MINFEE >= DEFAULT_MIN_RELAY_TX_FEE, "wallet minimum fee is smaller than default relay fee");
42static_assert(WALLET_INCREMENTAL_RELAY_FEE >= DEFAULT_INCREMENTAL_RELAY_FEE, "wallet incremental fee is smaller than default incremental relay fee");
43
44BOOST_FIXTURE_TEST_SUITE(wallet_tests, WalletTestingSetup)
45
46static CMutableTransaction TestSimpleSpend(const CTransaction& from, uint32_t index, const CKey& key, const CScript& pubkey)
47{
49 mtx.vout.emplace_back(from.vout[index].nValue - DEFAULT_TRANSACTION_MAXFEE, pubkey);
50 mtx.vin.push_back({CTxIn{from.GetHash(), index}});
52 keystore.AddKey(key);
53 std::map<COutPoint, Coin> coins;
54 coins[mtx.vin[0].prevout].out = from.vout[index];
55 std::map<int, bilingual_str> input_errors;
56 BOOST_CHECK(SignTransaction(mtx, &keystore, coins, SIGHASH_ALL, input_errors));
57 return mtx;
58}
59
60static void AddKey(CWallet& wallet, const CKey& key)
61{
62 LOCK(wallet.cs_wallet);
63 FlatSigningProvider provider;
64 std::string error;
65 auto descs = Parse("combo(" + EncodeSecret(key) + ")", provider, error, /* require_checksum=*/ false);
66 assert(descs.size() == 1);
67 auto& desc = descs.at(0);
68 WalletDescriptor w_desc(std::move(desc), 0, 0, 1, 1);
69 Assert(wallet.AddWalletDescriptor(w_desc, provider, "", false));
70}
71
72BOOST_FIXTURE_TEST_CASE(update_non_range_descriptor, TestingSetup)
73{
75 {
76 LOCK(wallet.cs_wallet);
77 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
78 auto key{GenerateRandomKey()};
79 auto desc_str{"combo(" + EncodeSecret(key) + ")"};
80 FlatSigningProvider provider;
81 std::string error;
82 auto descs{Parse(desc_str, provider, error, /* require_checksum=*/ false)};
83 auto& desc{descs.at(0)};
84 WalletDescriptor w_desc{std::move(desc), 0, 0, 0, 0};
85 BOOST_CHECK(wallet.AddWalletDescriptor(w_desc, provider, "", false));
86 // Wallet should update the non-range descriptor successfully
87 BOOST_CHECK(wallet.AddWalletDescriptor(w_desc, provider, "", false));
88 }
89}
90
91BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions, TestChain100Setup)
92{
93 // Cap last block file size, and mine new block in a new block file.
94 CBlockIndex* oldTip = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip());
95 WITH_LOCK(::cs_main, m_node.chainman->m_blockman.GetBlockFileInfo(oldTip->GetBlockPos().nFile)->nSize = MAX_BLOCKFILE_SIZE);
96 CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
97 CBlockIndex* newTip = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip());
98
99 // Verify ScanForWalletTransactions fails to read an unknown start block.
100 {
102 {
103 LOCK(wallet.cs_wallet);
104 LOCK(Assert(m_node.chainman)->GetMutex());
105 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
106 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
107 }
108 AddKey(wallet, coinbaseKey);
110 reserver.reserve();
111 CWallet::ScanResult result = wallet.ScanForWalletTransactions(/*start_block=*/{}, /*start_height=*/0, /*max_height=*/{}, reserver, /*fUpdate=*/false, /*save_progress=*/false);
116 BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 0);
117 }
118
119 // Verify ScanForWalletTransactions picks up transactions in both the old
120 // and new block files.
121 {
123 {
124 LOCK(wallet.cs_wallet);
125 LOCK(Assert(m_node.chainman)->GetMutex());
126 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
127 wallet.SetLastBlockProcessed(newTip->nHeight, newTip->GetBlockHash());
128 }
129 AddKey(wallet, coinbaseKey);
131 std::chrono::steady_clock::time_point fake_time;
132 reserver.setNow([&] { fake_time += 60s; return fake_time; });
133 reserver.reserve();
134
135 {
136 CBlockLocator locator;
137 BOOST_CHECK(WalletBatch{wallet.GetDatabase()}.ReadBestBlock(locator));
138 BOOST_CHECK(!locator.IsNull() && locator.vHave.front() == newTip->GetBlockHash());
139 }
140
141 CWallet::ScanResult result = wallet.ScanForWalletTransactions(/*start_block=*/oldTip->GetBlockHash(), /*start_height=*/oldTip->nHeight, /*max_height=*/{}, reserver, /*fUpdate=*/false, /*save_progress=*/true);
144 BOOST_CHECK_EQUAL(result.last_scanned_block, newTip->GetBlockHash());
145 BOOST_CHECK_EQUAL(*result.last_scanned_height, newTip->nHeight);
146 BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 100 * COIN);
147
148 {
149 CBlockLocator locator;
150 BOOST_CHECK(WalletBatch{wallet.GetDatabase()}.ReadBestBlock(locator));
151 BOOST_CHECK(!locator.IsNull() && locator.vHave.front() == newTip->GetBlockHash());
152 }
153 }
154
155 // Prune the older block file.
156 int file_number;
157 {
158 LOCK(cs_main);
159 file_number = oldTip->GetBlockPos().nFile;
160 Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
161 }
162 m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
163
164 // Verify ScanForWalletTransactions only picks transactions in the new block
165 // file.
166 {
168 {
169 LOCK(wallet.cs_wallet);
170 LOCK(Assert(m_node.chainman)->GetMutex());
171 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
172 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
173 }
174 AddKey(wallet, coinbaseKey);
176 reserver.reserve();
177 CWallet::ScanResult result = wallet.ScanForWalletTransactions(/*start_block=*/oldTip->GetBlockHash(), /*start_height=*/oldTip->nHeight, /*max_height=*/{}, reserver, /*fUpdate=*/false, /*save_progress=*/false);
180 BOOST_CHECK_EQUAL(result.last_scanned_block, newTip->GetBlockHash());
181 BOOST_CHECK_EQUAL(*result.last_scanned_height, newTip->nHeight);
182 BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 50 * COIN);
183 }
184
185 // Prune the remaining block file.
186 {
187 LOCK(cs_main);
188 file_number = newTip->GetBlockPos().nFile;
189 Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
190 }
191 m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
192
193 // Verify ScanForWalletTransactions scans no blocks.
194 {
196 {
197 LOCK(wallet.cs_wallet);
198 LOCK(Assert(m_node.chainman)->GetMutex());
199 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
200 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
201 }
202 AddKey(wallet, coinbaseKey);
204 reserver.reserve();
205 CWallet::ScanResult result = wallet.ScanForWalletTransactions(/*start_block=*/oldTip->GetBlockHash(), /*start_height=*/oldTip->nHeight, /*max_height=*/{}, reserver, /*fUpdate=*/false, /*save_progress=*/false);
207 BOOST_CHECK_EQUAL(result.last_failed_block, newTip->GetBlockHash());
210 BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 0);
211 }
212}
213
214// This test verifies that wallet settings can be added and removed
215// concurrently, ensuring no race conditions occur during either process.
216BOOST_FIXTURE_TEST_CASE(write_wallet_settings_concurrently, TestingSetup)
217{
218 auto chain = m_node.chain.get();
219 const auto NUM_WALLETS{5};
220
221 // Since we're counting the number of wallets, ensure we start without any.
222 BOOST_REQUIRE(chain->getRwSetting("wallet").isNull());
223
224 const auto& check_concurrent_wallet = [&](const auto& settings_function, int num_expected_wallets) {
225 std::vector<std::thread> threads;
226 threads.reserve(NUM_WALLETS);
227 for (auto i{0}; i < NUM_WALLETS; ++i) threads.emplace_back(settings_function, i);
228 for (auto& t : threads) t.join();
229
230 auto wallets = chain->getRwSetting("wallet");
231 BOOST_CHECK_EQUAL(wallets.getValues().size(), num_expected_wallets);
232 };
233
234 // Add NUM_WALLETS wallets concurrently, ensure we end up with NUM_WALLETS stored.
235 check_concurrent_wallet([&chain](int i) {
236 Assert(AddWalletSetting(*chain, strprintf("wallet_%d", i)));
237 },
238 /*num_expected_wallets=*/NUM_WALLETS);
239
240 // Remove NUM_WALLETS wallets concurrently, ensure we end up with 0 wallets.
241 check_concurrent_wallet([&chain](int i) {
242 Assert(RemoveWalletSetting(*chain, strprintf("wallet_%d", i)));
243 },
244 /*num_expected_wallets=*/0);
245}
246
247// Check that GetImmatureCredit() returns a newly calculated value instead of
248// the cached value after a MarkDirty() call.
249//
250// This is a regression test written to verify a bugfix for the immature credit
251// function. Similar tests probably should be written for the other credit and
252// debit functions.
253BOOST_FIXTURE_TEST_CASE(coin_mark_dirty_immature_credit, TestChain100Setup)
254{
256
257 LOCK(wallet.cs_wallet);
258 LOCK(Assert(m_node.chainman)->GetMutex());
259 CWalletTx wtx{m_coinbase_txns.back(), TxStateConfirmed{m_node.chainman->ActiveChain().Tip()->GetBlockHash(), m_node.chainman->ActiveChain().Height(), /*index=*/0}};
260 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
261 wallet.SetupDescriptorScriptPubKeyMans();
262
263 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
264
265 // Call GetImmatureCredit() once before adding the key to the wallet to
266 // cache the current immature credit amount, which is 0.
268
269 // Invalidate the cached value, add the key, and make sure a new immature
270 // credit amount is calculated.
271 wtx.MarkDirty();
272 AddKey(wallet, coinbaseKey);
274}
275
276static int64_t AddTx(ChainstateManager& chainman, CWallet& wallet, uint32_t lockTime, int64_t mockTime, int64_t blockTime)
277{
279 TxState state = TxStateInactive{};
280 tx.nLockTime = lockTime;
281 SetMockTime(mockTime);
282 CBlockIndex* block = nullptr;
283 if (blockTime > 0) {
284 LOCK(cs_main);
285 auto inserted = chainman.BlockIndex().emplace(std::piecewise_construct, std::make_tuple(GetRandHash()), std::make_tuple());
286 assert(inserted.second);
287 const uint256& hash = inserted.first->first;
288 block = &inserted.first->second;
289 block->nTime = blockTime;
290 block->phashBlock = &hash;
291 state = TxStateConfirmed{hash, block->nHeight, /*index=*/0};
292 }
293 return wallet.AddToWallet(MakeTransactionRef(tx), state, [&](CWalletTx& wtx, bool /* new_tx */) {
294 // Assign wtx.m_state to simplify test and avoid the need to simulate
295 // reorg events. Without this, AddToWallet asserts false when the same
296 // transaction is confirmed in different blocks.
297 wtx.m_state = state;
298 return true;
299 })->nTimeSmart;
300}
301
302// Simple test to verify assignment of CWalletTx::nSmartTime value. Could be
303// expanded to cover more corner cases of smart time logic.
304BOOST_AUTO_TEST_CASE(ComputeTimeSmart)
305{
306 // New transaction should use clock time if lower than block time.
307 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 100, 120), 100);
308
309 // Test that updating existing transaction does not change smart time.
310 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 200, 220), 100);
311
312 // New transaction should use clock time if there's no block time.
313 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 2, 300, 0), 300);
314
315 // New transaction should use block time if lower than clock time.
316 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 3, 420, 400), 400);
317
318 // New transaction should use latest entry time if higher than
319 // min(block time, clock time).
320 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 4, 500, 390), 400);
321
322 // If there are future entries, new transaction should use time of the
323 // newest entry that is no more than 300 seconds ahead of the clock time.
324 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 5, 50, 600), 300);
325}
326
327void TestLoadWallet(const std::string& name, DatabaseFormat format, std::function<void(std::shared_ptr<CWallet>)> f)
328{
330 auto chain{interfaces::MakeChain(node)};
331 DatabaseOptions options;
332 options.require_format = format;
333 DatabaseStatus status;
334 bilingual_str error;
335 std::vector<bilingual_str> warnings;
336 auto database{MakeWalletDatabase(name, options, status, error)};
337 auto wallet{std::make_shared<CWallet>(chain.get(), "", std::move(database))};
339 WITH_LOCK(wallet->cs_wallet, f(wallet));
340}
341
343{
345 const std::string name{strprintf("receive-requests-%i", format)};
346 TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
347 BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash()));
348 WalletBatch batch{wallet->GetDatabase()};
349 BOOST_CHECK(batch.WriteAddressPreviouslySpent(PKHash(), true));
350 BOOST_CHECK(batch.WriteAddressPreviouslySpent(ScriptHash(), true));
351 BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "0", "val_rr00"));
352 BOOST_CHECK(wallet->EraseAddressReceiveRequest(batch, PKHash(), "0"));
353 BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "1", "val_rr10"));
354 BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "1", "val_rr11"));
355 BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, ScriptHash(), "2", "val_rr20"));
356 });
357 TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
358 BOOST_CHECK(wallet->IsAddressPreviouslySpent(PKHash()));
359 BOOST_CHECK(wallet->IsAddressPreviouslySpent(ScriptHash()));
360 auto requests = wallet->GetAddressReceiveRequests();
361 auto erequests = {"val_rr11", "val_rr20"};
362 BOOST_CHECK_EQUAL_COLLECTIONS(requests.begin(), requests.end(), std::begin(erequests), std::end(erequests));
363 RunWithinTxn(wallet->GetDatabase(), /*process_desc*/"test", [](WalletBatch& batch){
364 BOOST_CHECK(batch.WriteAddressPreviouslySpent(PKHash(), false));
365 BOOST_CHECK(batch.EraseAddressData(ScriptHash()));
366 return true;
367 });
368 });
369 TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
370 BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash()));
371 BOOST_CHECK(!wallet->IsAddressPreviouslySpent(ScriptHash()));
372 auto requests = wallet->GetAddressReceiveRequests();
373 auto erequests = {"val_rr11"};
374 BOOST_CHECK_EQUAL_COLLECTIONS(requests.begin(), requests.end(), std::begin(erequests), std::end(erequests));
375 });
376 }
377}
378
380{
381public:
383 {
384 CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
385 wallet = CreateSyncedWallet(*m_node.chain, WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain()), coinbaseKey);
386 }
387
389 {
390 wallet.reset();
391 }
392
394 {
396 CCoinControl dummy;
397 {
398 auto res = CreateTransaction(*wallet, {recipient}, /*change_pos=*/std::nullopt, dummy);
399 BOOST_CHECK(res);
400 tx = res->tx;
401 }
402 wallet->CommitTransaction(tx, {}, {});
403 CMutableTransaction blocktx;
404 {
405 LOCK(wallet->cs_wallet);
406 blocktx = CMutableTransaction(*wallet->mapWallet.at(tx->GetHash()).tx);
407 }
408 CreateAndProcessBlock({CMutableTransaction(blocktx)}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
409
410 LOCK(wallet->cs_wallet);
411 LOCK(Assert(m_node.chainman)->GetMutex());
412 wallet->SetLastBlockProcessed(wallet->GetLastBlockHeight() + 1, m_node.chainman->ActiveChain().Tip()->GetBlockHash());
413 auto it = wallet->mapWallet.find(tx->GetHash());
414 BOOST_CHECK(it != wallet->mapWallet.end());
415 it->second.m_state = TxStateConfirmed{m_node.chainman->ActiveChain().Tip()->GetBlockHash(), m_node.chainman->ActiveChain().Height(), /*index=*/1};
416 return it->second;
417 }
418
419 std::unique_ptr<CWallet> wallet;
420};
421
423{
424 std::string coinbaseAddress = coinbaseKey.GetPubKey().GetID().ToString();
425
426 // Confirm ListCoins initially returns 1 coin grouped under coinbaseKey
427 // address.
428 std::map<CTxDestination, std::vector<COutput>> list;
429 {
430 LOCK(wallet->cs_wallet);
431 list = ListCoins(*wallet);
432 }
433 BOOST_CHECK_EQUAL(list.size(), 1U);
434 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
435 BOOST_CHECK_EQUAL(list.begin()->second.size(), 1U);
436
437 // Check initial balance from one mature coinbase transaction.
438 BOOST_CHECK_EQUAL(50 * COIN, WITH_LOCK(wallet->cs_wallet, return AvailableCoins(*wallet).GetTotalAmount()));
439
440 // Add a transaction creating a change address, and confirm ListCoins still
441 // returns the coin associated with the change address underneath the
442 // coinbaseKey pubkey, even though the change address has a different
443 // pubkey.
444 AddTx(CRecipient{PubKeyDestination{{}}, 1 * COIN, /*subtract_fee=*/false});
445 {
446 LOCK(wallet->cs_wallet);
447 list = ListCoins(*wallet);
448 }
449 BOOST_CHECK_EQUAL(list.size(), 1U);
450 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
451 BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
452
453 // Lock both coins. Confirm number of available coins drops to 0.
454 {
455 LOCK(wallet->cs_wallet);
457 }
458 for (const auto& group : list) {
459 for (const auto& coin : group.second) {
460 LOCK(wallet->cs_wallet);
461 wallet->LockCoin(coin.outpoint);
462 }
463 }
464 {
465 LOCK(wallet->cs_wallet);
467 }
468 // Confirm ListCoins still returns same result as before, despite coins
469 // being locked.
470 {
471 LOCK(wallet->cs_wallet);
472 list = ListCoins(*wallet);
473 }
474 BOOST_CHECK_EQUAL(list.size(), 1U);
475 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
476 BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
477}
478
479void TestCoinsResult(ListCoinsTest& context, OutputType out_type, CAmount amount,
480 std::map<OutputType, size_t>& expected_coins_sizes)
481{
482 LOCK(context.wallet->cs_wallet);
483 util::Result<CTxDestination> dest = Assert(context.wallet->GetNewDestination(out_type, ""));
484 CWalletTx& wtx = context.AddTx(CRecipient{*dest, amount, /*fSubtractFeeFromAmount=*/true});
485 CoinFilterParams filter;
486 filter.skip_locked = false;
487 CoinsResult available_coins = AvailableCoins(*context.wallet, nullptr, std::nullopt, filter);
488 // Lock outputs so they are not spent in follow-up transactions
489 for (uint32_t i = 0; i < wtx.tx->vout.size(); i++) context.wallet->LockCoin({wtx.GetHash(), i});
490 for (const auto& [type, size] : expected_coins_sizes) BOOST_CHECK_EQUAL(size, available_coins.coins[type].size());
491}
492
493BOOST_FIXTURE_TEST_CASE(BasicOutputTypesTest, ListCoinsTest)
494{
495 std::map<OutputType, size_t> expected_coins_sizes;
496 for (const auto& out_type : OUTPUT_TYPES) { expected_coins_sizes[out_type] = 0U; }
497
498 // Verify our wallet has one usable coinbase UTXO before starting
499 // This UTXO is a P2PK, so it should show up in the Other bucket
500 expected_coins_sizes[OutputType::UNKNOWN] = 1U;
501 CoinsResult available_coins = WITH_LOCK(wallet->cs_wallet, return AvailableCoins(*wallet));
502 BOOST_CHECK_EQUAL(available_coins.Size(), expected_coins_sizes[OutputType::UNKNOWN]);
503 BOOST_CHECK_EQUAL(available_coins.coins[OutputType::UNKNOWN].size(), expected_coins_sizes[OutputType::UNKNOWN]);
504
505 // We will create a self transfer for each of the OutputTypes and
506 // verify it is put in the correct bucket after running GetAvailablecoins
507 //
508 // For each OutputType, We expect 2 UTXOs in our wallet following the self transfer:
509 // 1. One UTXO as the recipient
510 // 2. One UTXO from the change, due to payment address matching logic
511
512 for (const auto& out_type : OUTPUT_TYPES) {
513 if (out_type == OutputType::UNKNOWN) continue;
514 expected_coins_sizes[out_type] = 2U;
515 TestCoinsResult(*this, out_type, 1 * COIN, expected_coins_sizes);
516 }
517}
518
520{
521 const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateMockableWalletDatabase());
522 LOCK(wallet->cs_wallet);
523 wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
524 wallet->SetMinVersion(FEATURE_LATEST);
526 BOOST_CHECK(!wallet->GetNewDestination(OutputType::BECH32, ""));
527}
528
529// Explicit calculation which is used to test the wallet constant
530// We get the same virtual size due to rounding(weight/4) for both use_max_sig values
531static size_t CalculateNestedKeyhashInputSize(bool use_max_sig)
532{
533 // Generate ephemeral valid pubkey
534 CKey key = GenerateRandomKey();
535 CPubKey pubkey = key.GetPubKey();
536
537 // Generate pubkey hash
538 uint160 key_hash(Hash160(pubkey));
539
540 // Create inner-script to enter into keystore. Key hash can't be 0...
541 CScript inner_script = CScript() << OP_0 << std::vector<unsigned char>(key_hash.begin(), key_hash.end());
542
543 // Create outer P2SH script for the output
544 uint160 script_id(Hash160(inner_script));
545 CScript script_pubkey = CScript() << OP_HASH160 << std::vector<unsigned char>(script_id.begin(), script_id.end()) << OP_EQUAL;
546
547 // Add inner-script to key store and key to watchonly
549 keystore.AddCScript(inner_script);
550 keystore.AddKeyPubKey(key, pubkey);
551
552 // Fill in dummy signatures for fee calculation.
553 SignatureData sig_data;
554
555 if (!ProduceSignature(keystore, use_max_sig ? DUMMY_MAXIMUM_SIGNATURE_CREATOR : DUMMY_SIGNATURE_CREATOR, script_pubkey, sig_data)) {
556 // We're hand-feeding it correct arguments; shouldn't happen
557 assert(false);
558 }
559
560 CTxIn tx_in;
561 UpdateInput(tx_in, sig_data);
562 return (size_t)GetVirtualTransactionInputSize(tx_in);
563}
564
566{
569}
570
571bool malformed_descriptor(std::ios_base::failure e)
572{
573 std::string s(e.what());
574 return s.find("Missing checksum") != std::string::npos;
575}
576
578{
579 std::vector<unsigned char> malformed_record;
580 VectorWriter vw{malformed_record, 0};
581 vw << std::string("notadescriptor");
582 vw << uint64_t{0};
583 vw << int32_t{0};
584 vw << int32_t{0};
585 vw << int32_t{1};
586
587 SpanReader vr{malformed_record};
588 WalletDescriptor w_desc;
589 BOOST_CHECK_EXCEPTION(vr >> w_desc, std::ios_base::failure, malformed_descriptor);
590}
591
611{
612 m_args.ForceSetArg("-unsafesqlitesync", "1");
613 // Create new wallet with known key and unload it.
614 WalletContext context;
615 context.args = &m_args;
616 context.chain = m_node.chain.get();
617 auto wallet = TestLoadWallet(context);
618 CKey key = GenerateRandomKey();
619 AddKey(*wallet, key);
620 TestUnloadWallet(std::move(wallet));
621
622
623 // Add log hook to detect AddToWallet events from rescans, blockConnected,
624 // and transactionAddedToMempool notifications
625 int addtx_count = 0;
626 DebugLogHelper addtx_counter("[default wallet] AddToWallet", [&](const std::string* s) {
627 if (s) ++addtx_count;
628 return false;
629 });
630
631
632 bool rescan_completed = false;
633 DebugLogHelper rescan_check("[default wallet] Rescan completed", [&](const std::string* s) {
634 if (s) rescan_completed = true;
635 return false;
636 });
637
638
639 // Block the queue to prevent the wallet receiving blockConnected and
640 // transactionAddedToMempool notifications, and create block and mempool
641 // transactions paying to the wallet
642 std::promise<void> promise;
643 m_node.validation_signals->CallFunctionInValidationInterfaceQueue([&promise] {
644 promise.get_future().wait();
645 });
646 std::string error;
647 m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
648 auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
649 m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
650 auto mempool_tx = TestSimpleSpend(*m_coinbase_txns[1], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
651 BOOST_CHECK(m_node.chain->broadcastTransaction(MakeTransactionRef(mempool_tx), DEFAULT_TRANSACTION_MAXFEE, false, error));
652
653
654 // Reload wallet and make sure new transactions are detected despite events
655 // being blocked
656 // Loading will also ask for current mempool transactions
657 wallet = TestLoadWallet(context);
658 BOOST_CHECK(rescan_completed);
659 // AddToWallet events for block_tx and mempool_tx (x2)
660 BOOST_CHECK_EQUAL(addtx_count, 3);
661 {
662 LOCK(wallet->cs_wallet);
663 BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_tx.GetHash()), 1U);
664 BOOST_CHECK_EQUAL(wallet->mapWallet.count(mempool_tx.GetHash()), 1U);
665 }
666
667
668 // Unblock notification queue and make sure stale blockConnected and
669 // transactionAddedToMempool events are processed
670 promise.set_value();
671 m_node.validation_signals->SyncWithValidationInterfaceQueue();
672 // AddToWallet events for block_tx and mempool_tx events are counted a
673 // second time as the notification queue is processed
674 BOOST_CHECK_EQUAL(addtx_count, 5);
675
676
677 TestUnloadWallet(std::move(wallet));
678
679
680 // Load wallet again, this time creating new block and mempool transactions
681 // paying to the wallet as the wallet finishes loading and syncing the
682 // queue so the events have to be handled immediately. Releasing the wallet
683 // lock during the sync is a little artificial but is needed to avoid a
684 // deadlock during the sync and simulates a new block notification happening
685 // as soon as possible.
686 addtx_count = 0;
687 auto handler = HandleLoadWallet(context, [&](std::unique_ptr<interfaces::Wallet> wallet) {
688 BOOST_CHECK(rescan_completed);
689 m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
690 block_tx = TestSimpleSpend(*m_coinbase_txns[2], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
691 m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
692 mempool_tx = TestSimpleSpend(*m_coinbase_txns[3], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
693 BOOST_CHECK(m_node.chain->broadcastTransaction(MakeTransactionRef(mempool_tx), DEFAULT_TRANSACTION_MAXFEE, false, error));
694 m_node.validation_signals->SyncWithValidationInterfaceQueue();
695 });
696 wallet = TestLoadWallet(context);
697 // Since mempool transactions are requested at the end of loading, there will
698 // be 2 additional AddToWallet calls, one from the previous test, and a duplicate for mempool_tx
699 BOOST_CHECK_EQUAL(addtx_count, 2 + 2);
700 {
701 LOCK(wallet->cs_wallet);
702 BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_tx.GetHash()), 1U);
703 BOOST_CHECK_EQUAL(wallet->mapWallet.count(mempool_tx.GetHash()), 1U);
704 }
705
706
707 TestUnloadWallet(std::move(wallet));
708}
709
711{
712 WalletContext context;
713 context.args = &m_args;
714 auto wallet = TestLoadWallet(context);
716 WaitForDeleteWallet(std::move(wallet));
717}
718
720{
721 m_args.ForceSetArg("-unsafesqlitesync", "1");
722 WalletContext context;
723 context.args = &m_args;
724 context.chain = m_node.chain.get();
725 auto wallet = TestLoadWallet(context);
726 CKey key = GenerateRandomKey();
727 AddKey(*wallet, key);
728
729 std::string error;
730 m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
731 auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
732 CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
733
734 m_node.validation_signals->SyncWithValidationInterfaceQueue();
735
736 {
737 auto block_hash = block_tx.GetHash();
738 auto prev_tx = m_coinbase_txns[0];
739
740 LOCK(wallet->cs_wallet);
741 BOOST_CHECK(wallet->HasWalletSpend(prev_tx));
742 BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_hash), 1u);
743
744 std::vector<Txid> vHashIn{ block_hash };
745 BOOST_CHECK(wallet->RemoveTxs(vHashIn));
746
747 BOOST_CHECK(!wallet->HasWalletSpend(prev_tx));
748 BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_hash), 0u);
749 }
750
751 TestUnloadWallet(std::move(wallet));
752}
753
758BOOST_FIXTURE_TEST_CASE(wallet_sync_tx_invalid_state_test, TestingSetup)
759{
761 {
762 LOCK(wallet.cs_wallet);
763 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
764 wallet.SetupDescriptorScriptPubKeyMans();
765 }
766
767 // Add tx to wallet
768 const auto op_dest{*Assert(wallet.GetNewDestination(OutputType::BECH32M, ""))};
769
771 mtx.vout.emplace_back(COIN, GetScriptForDestination(op_dest));
772 mtx.vin.emplace_back(Txid::FromUint256(m_rng.rand256()), 0);
773 const auto& tx_id_to_spend = wallet.AddToWallet(MakeTransactionRef(mtx), TxStateInMempool{})->GetHash();
774
775 {
776 // Cache and verify available balance for the wtx
777 LOCK(wallet.cs_wallet);
778 const CWalletTx* wtx_to_spend = wallet.GetWalletTx(tx_id_to_spend);
780 }
781
782 // Now the good case:
783 // 1) Add a transaction that spends the previously created transaction
784 // 2) Verify that the available balance of this new tx and the old one is updated (prev tx is marked dirty)
785
786 mtx.vin.clear();
787 mtx.vin.emplace_back(tx_id_to_spend, 0);
788 wallet.transactionAddedToMempool(MakeTransactionRef(mtx));
789 const auto good_tx_id{mtx.GetHash()};
790
791 {
792 // Verify balance update for the new tx and the old one
793 LOCK(wallet.cs_wallet);
794 const CWalletTx* new_wtx = wallet.GetWalletTx(good_tx_id);
796
797 // Now the old wtx
798 const CWalletTx* wtx_to_spend = wallet.GetWalletTx(tx_id_to_spend);
800 }
801
802 // Now the bad case:
803 // 1) Make db always fail
804 // 2) Try to add a transaction that spends the previously created transaction and
805 // verify that we are not moving forward if the wallet cannot store it
807 mtx.vin.clear();
808 mtx.vin.emplace_back(good_tx_id, 0);
809 BOOST_CHECK_EXCEPTION(wallet.transactionAddedToMempool(MakeTransactionRef(mtx)),
810 std::runtime_error,
811 HasReason("DB error adding transaction to wallet, write failed"));
812}
813
815} // namespace wallet
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
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:42
#define Assert(val)
Identity function.
Definition: check.h:106
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:141
uint32_t nTime
Definition: chain.h:189
uint256 GetBlockHash() const
Definition: chain.h:243
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:153
FlatFilePos GetBlockPos() const EXCLUSIVE_LOCKS_REQUIRED(
Definition: chain.h:208
const uint256 * phashBlock
pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
Definition: chain.h:144
An encapsulated private key.
Definition: key.h:35
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:182
An encapsulated public key.
Definition: pubkey.h:34
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:415
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:867
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:1124
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: setup_common.h:302
Minimal stream for reading from an existing byte array by std::span.
Definition: streams.h:101
constexpr bool IsNull() const
Definition: uint256.h:48
constexpr unsigned char * end()
Definition: uint256.h:102
constexpr unsigned char * begin()
Definition: uint256.h:101
static transaction_identifier FromUint256(const uint256 &id)
160-bit opaque blob.
Definition: uint256.h:184
256-bit opaque blob.
Definition: uint256.h:196
Coin Control Features.
Definition: coincontrol.h:81
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:301
A transaction with a bunch of additional info that only the owner cares about.
Definition: transaction.h:177
CTransactionRef tx
Definition: transaction.h:251
CWalletTx & AddTx(CRecipient recipient)
std::unique_ptr< CWallet > wallet
Access to the wallet database.
Definition: walletdb.h:190
Descriptor with some wallet metadata.
Definition: walletutil.h:85
RAII object to check and reserve a wallet rescan.
Definition: wallet.h:1059
void setNow(NowFn now)
Definition: wallet.h:1089
bool reserve(bool with_passphrase=false)
Definition: wallet.h:1069
static UniValue Parse(std::string_view raw)
Parse string to UniValue or throw runtime_error if string contains invalid JSON.
Definition: client.cpp:317
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:30
CKey GenerateRandomKey(bool compressed) noexcept
Definition: key.cpp:352
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:997
Definition: messages.h:20
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
Definition: blockstorage.h:75
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:144
static CMutableTransaction TestSimpleSpend(const CTransaction &from, uint32_t index, const CKey &key, const CScript &pubkey)
CAmount CachedTxGetAvailableCredit(const CWallet &wallet, const CWalletTx &wtx, const isminefilter &filter)
Definition: receive.cpp:159
Balance GetBalance(const CWallet &wallet, const int min_depth, bool avoid_reuse)
Definition: receive.cpp:293
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:1369
constexpr CAmount DEFAULT_TRANSACTION_MAXFEE
-maxtxfee default
Definition: wallet.h:138
static bool RunWithinTxn(WalletBatch &batch, std::string_view process_desc, const std::function< bool(WalletBatch &)> &func)
Definition: walletdb.cpp:1248
std::variant< TxStateConfirmed, TxStateInMempool, TxStateBlockConflicted, TxStateInactive, TxStateUnrecognized > TxState
All possible CWalletTx states.
Definition: transaction.h:78
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:164
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:94
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:107
std::unique_ptr< interfaces::Handler > HandleLoadWallet(WalletContext &context, LoadWalletFn load_wallet)
Definition: wallet.cpp:214
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:111
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:2810
MockableDatabase & GetMockableDatabase(CWallet &wallet)
Definition: util.cpp:191
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:505
std::unique_ptr< WalletDatabase > CreateMockableWalletDatabase(MockableData records)
Definition: util.cpp:186
BOOST_AUTO_TEST_CASE(bnb_test)
@ ISMINE_SPENDABLE
Definition: types.h:44
CoinsResult AvailableCoinsListUnspent(const CWallet &wallet, const CCoinControl *coinControl, CoinFilterParams params)
Wrapper function for AvailableCoins which skips the feerate and CoinFilterParams::only_spendable para...
Definition: spend.cpp:479
static void AddKey(CWallet &wallet, const CKey &key)
static const CAmount WALLET_INCREMENTAL_RELAY_FEE
minimum recommended increment for replacement txs
Definition: wallet.h:125
@ FEATURE_LATEST
Definition: walletutil.h:30
BOOST_FIXTURE_TEST_CASE(wallet_sync_tx_invalid_state_test, TestingSetup)
Checks a wallet invalid state where the inputs (prev-txs) of a new arriving transaction are not marke...
CAmount CachedTxGetImmatureCredit(const CWallet &wallet, const CWalletTx &wtx, const isminefilter &filter)
Definition: receive.cpp:148
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:380
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:74
@ WALLET_FLAG_DISABLE_PRIVATE_KEYS
Definition: walletutil.h:51
void WaitForDeleteWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly delete the wallet.
Definition: wallet.cpp:252
static size_t CalculateNestedKeyhashInputSize(bool use_max_sig)
DatabaseStatus
Definition: db.h:183
#define BOOST_CHECK_EQUAL(v1, v2)
Definition: object.cpp:18
#define BOOST_CHECK(expr)
Definition: object.cpp:17
OutputType
Definition: outputtype.h:17
static constexpr auto OUTPUT_TYPES
Definition: outputtype.h:25
int64_t GetVirtualTransactionInputSize(const CTxIn &txin, int64_t nSigOpCost, unsigned int bytes_per_sigop)
Definition: policy.cpp:320
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:42
static constexpr unsigned int DEFAULT_MIN_RELAY_TX_FEE
Default for -minrelaytxfee, minimum relay fee for transactions.
Definition: policy.h:64
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:454
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:1010
const char * name
Definition: rest.cpp:49
@ 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:502
void UpdateInput(CTxIn &input, const SignatureData &data)
Definition: sign.cpp:675
const BaseSignatureCreator & DUMMY_MAXIMUM_SIGNATURE_CREATOR
A signature creator that just produces 72-byte empty signatures.
Definition: sign.cpp:745
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
Definition: sign.cpp:744
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
Txid GetHash() const
Compute the hash of this CMutableTransaction.
Definition: transaction.cpp:69
std::vector< CTxIn > vin
Definition: transaction.h:379
int 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:624
enum wallet::CWallet::ScanResult::@19 status
uint256 last_scanned_block
Hash and height of most recent block that was successfully scanned.
Definition: wallet.h:623
uint256 last_failed_block
Height of the most recent block that could not be scanned due to read errors or pruning.
Definition: wallet.h:630
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:193
std::map< OutputType, std::vector< COutput > > coins
Definition: spend.h:46
std::optional< DatabaseFormat > require_format
Definition: db.h:172
State of transaction confirmed in a block.
Definition: transaction.h:31
State of transaction added to mempool.
Definition: transaction.h:41
State of transaction not confirmed or conflicting with a known block and not in the mempool.
Definition: transaction.h:58
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:257
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:302
#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
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:544
static void AvailableCoins(benchmark::Bench &bench, const std::vector< OutputType > &output_type)