Bitcoin Core 22.99.0
P2P Digital Currency
wallet_tests.cpp
Go to the documentation of this file.
1// Copyright (c) 2012-2020 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 <any>
8#include <future>
9#include <memory>
10#include <stdint.h>
11#include <vector>
12
13#include <interfaces/chain.h>
14#include <key_io.h>
15#include <node/blockstorage.h>
16#include <node/context.h>
17#include <policy/policy.h>
18#include <rpc/server.h>
19#include <test/util/logging.h>
21#include <util/translation.h>
22#include <validation.h>
23#include <wallet/coincontrol.h>
24#include <wallet/context.h>
25#include <wallet/receive.h>
26#include <wallet/spend.h>
27#include <wallet/test/util.h>
29
30#include <boost/test/unit_test.hpp>
31#include <univalue.h>
32
36
37// Ensure that fee levels defined in the wallet are at least as high
38// as the default levels for node policy.
39static_assert(DEFAULT_TRANSACTION_MINFEE >= DEFAULT_MIN_RELAY_TX_FEE, "wallet minimum fee is smaller than default relay fee");
40static_assert(WALLET_INCREMENTAL_RELAY_FEE >= DEFAULT_INCREMENTAL_RELAY_FEE, "wallet incremental fee is smaller than default incremental relay fee");
41
43
44static const std::shared_ptr<CWallet> TestLoadWallet(WalletContext& context)
45{
46 DatabaseOptions options;
48 DatabaseStatus status;
50 std::vector<bilingual_str> warnings;
51 auto database = MakeWalletDatabase("", options, status, error);
52 auto wallet = CWallet::Create(context, "", std::move(database), options.create_flags, error, warnings);
53 if (context.chain) {
54 wallet->postInitProcess();
55 }
56 return wallet;
57}
58
59static void TestUnloadWallet(std::shared_ptr<CWallet>&& wallet)
60{
62 wallet->m_chain_notifications_handler.reset();
63 UnloadWallet(std::move(wallet));
64}
65
66static CMutableTransaction TestSimpleSpend(const CTransaction& from, uint32_t index, const CKey& key, const CScript& pubkey)
67{
69 mtx.vout.push_back({from.vout[index].nValue - DEFAULT_TRANSACTION_MAXFEE, pubkey});
70 mtx.vin.push_back({CTxIn{from.GetHash(), index}});
72 keystore.AddKey(key);
73 std::map<COutPoint, Coin> coins;
74 coins[mtx.vin[0].prevout].out = from.vout[index];
75 std::map<int, bilingual_str> input_errors;
76 BOOST_CHECK(SignTransaction(mtx, &keystore, coins, SIGHASH_ALL, input_errors));
77 return mtx;
78}
79
80static void AddKey(CWallet& wallet, const CKey& key)
81{
82 LOCK(wallet.cs_wallet);
83 FlatSigningProvider provider;
84 std::string error;
85 std::unique_ptr<Descriptor> desc = Parse("combo(" + EncodeSecret(key) + ")", provider, error, /* require_checksum=*/ false);
86 assert(desc);
87 WalletDescriptor w_desc(std::move(desc), 0, 0, 1, 1);
88 if (!wallet.AddWalletDescriptor(w_desc, provider, "", false)) assert(false);
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 = m_node.chainman->ActiveChain().Tip();
96 CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
97 CBlockIndex* newTip = m_node.chainman->ActiveChain().Tip();
98
99 // Verify ScanForWalletTransactions fails to read an unknown start block.
100 {
102 {
103 LOCK(wallet.cs_wallet);
104 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
105 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
106 }
107 AddKey(wallet, coinbaseKey);
109 reserver.reserve();
110 CWallet::ScanResult result = wallet.ScanForWalletTransactions({} /* start_block */, 0 /* start_height */, {} /* max_height */, reserver, false /* update */);
115 BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 0);
116 }
117
118 // Verify ScanForWalletTransactions picks up transactions in both the old
119 // and new block files.
120 {
122 {
123 LOCK(wallet.cs_wallet);
124 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
125 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
126 }
127 AddKey(wallet, coinbaseKey);
129 reserver.reserve();
130 CWallet::ScanResult result = wallet.ScanForWalletTransactions(oldTip->GetBlockHash(), oldTip->nHeight, {} /* max_height */, reserver, false /* update */);
133 BOOST_CHECK_EQUAL(result.last_scanned_block, newTip->GetBlockHash());
134 BOOST_CHECK_EQUAL(*result.last_scanned_height, newTip->nHeight);
135 BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 100 * COIN);
136 }
137
138 // Prune the older block file.
139 {
140 LOCK(cs_main);
141 Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(oldTip->GetBlockPos().nFile);
142 }
143 UnlinkPrunedFiles({oldTip->GetBlockPos().nFile});
144
145 // Verify ScanForWalletTransactions only picks transactions in the new block
146 // file.
147 {
149 {
150 LOCK(wallet.cs_wallet);
151 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
152 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
153 }
154 AddKey(wallet, coinbaseKey);
156 reserver.reserve();
157 CWallet::ScanResult result = wallet.ScanForWalletTransactions(oldTip->GetBlockHash(), oldTip->nHeight, {} /* max_height */, reserver, false /* update */);
160 BOOST_CHECK_EQUAL(result.last_scanned_block, newTip->GetBlockHash());
161 BOOST_CHECK_EQUAL(*result.last_scanned_height, newTip->nHeight);
162 BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 50 * COIN);
163 }
164
165 // Prune the remaining block file.
166 {
167 LOCK(cs_main);
168 Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(newTip->GetBlockPos().nFile);
169 }
170 UnlinkPrunedFiles({newTip->GetBlockPos().nFile});
171
172 // Verify ScanForWalletTransactions scans no blocks.
173 {
175 {
176 LOCK(wallet.cs_wallet);
177 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
178 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
179 }
180 AddKey(wallet, coinbaseKey);
182 reserver.reserve();
183 CWallet::ScanResult result = wallet.ScanForWalletTransactions(oldTip->GetBlockHash(), oldTip->nHeight, {} /* max_height */, reserver, false /* update */);
185 BOOST_CHECK_EQUAL(result.last_failed_block, newTip->GetBlockHash());
188 BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 0);
189 }
190}
191
193{
194 // Cap last block file size, and mine new block in a new block file.
195 CBlockIndex* oldTip = m_node.chainman->ActiveChain().Tip();
197 CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
198 CBlockIndex* newTip = m_node.chainman->ActiveChain().Tip();
199
200 // Prune the older block file.
201 {
202 LOCK(cs_main);
203 Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(oldTip->GetBlockPos().nFile);
204 }
205 UnlinkPrunedFiles({oldTip->GetBlockPos().nFile});
206
207 // Verify importmulti RPC returns failure for a key whose creation time is
208 // before the missing block, and success for a key whose creation time is
209 // after.
210 {
211 const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateDummyWalletDatabase());
212 wallet->SetupLegacyScriptPubKeyMan();
213 WITH_LOCK(wallet->cs_wallet, wallet->SetLastBlockProcessed(newTip->nHeight, newTip->GetBlockHash()));
214 WalletContext context;
215 context.args = &gArgs;
216 AddWallet(context, wallet);
217 UniValue keys;
218 keys.setArray();
219 UniValue key;
220 key.setObject();
221 key.pushKV("scriptPubKey", HexStr(GetScriptForRawPubKey(coinbaseKey.GetPubKey())));
222 key.pushKV("timestamp", 0);
223 key.pushKV("internal", UniValue(true));
224 keys.push_back(key);
225 key.clear();
226 key.setObject();
227 CKey futureKey;
228 futureKey.MakeNewKey(true);
229 key.pushKV("scriptPubKey", HexStr(GetScriptForRawPubKey(futureKey.GetPubKey())));
230 key.pushKV("timestamp", newTip->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1);
231 key.pushKV("internal", UniValue(true));
232 keys.push_back(key);
233 JSONRPCRequest request;
234 request.context = &context;
235 request.params.setArray();
236 request.params.push_back(keys);
237
238 UniValue response = importmulti().HandleRequest(request);
239 BOOST_CHECK_EQUAL(response.write(),
240 strprintf("[{\"success\":false,\"error\":{\"code\":-1,\"message\":\"Rescan failed for key with creation "
241 "timestamp %d. There was an error reading a block from time %d, which is after or within %d "
242 "seconds of key creation, and could contain transactions pertaining to the key. As a result, "
243 "transactions and coins using this key may not appear in the wallet. This error could be caused "
244 "by pruning or data corruption (see bitcoind log for details) and could be dealt with by "
245 "downloading and rescanning the relevant blocks (see -reindex option and rescanblockchain "
246 "RPC).\"}},{\"success\":true}]",
247 0, oldTip->GetBlockTimeMax(), TIMESTAMP_WINDOW));
248 RemoveWallet(context, wallet, /* load_on_start= */ std::nullopt);
249 }
250}
251
252// Verify importwallet RPC starts rescan at earliest block with timestamp
253// greater or equal than key birthday. Previously there was a bug where
254// importwallet RPC would start the scan at the latest block with timestamp less
255// than or equal to key birthday.
257{
258 // Create two blocks with same timestamp to verify that importwallet rescan
259 // will pick up both blocks, not just the first.
260 const int64_t BLOCK_TIME = m_node.chainman->ActiveChain().Tip()->GetBlockTimeMax() + 5;
261 SetMockTime(BLOCK_TIME);
262 m_coinbase_txns.emplace_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
263 m_coinbase_txns.emplace_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
264
265 // Set key birthday to block time increased by the timestamp window, so
266 // rescan will start at the block time.
267 const int64_t KEY_TIME = BLOCK_TIME + TIMESTAMP_WINDOW;
268 SetMockTime(KEY_TIME);
269 m_coinbase_txns.emplace_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
270
271 std::string backup_file = fs::PathToString(gArgs.GetDataDirNet() / "wallet.backup");
272
273 // Import key into wallet and call dumpwallet to create backup file.
274 {
275 WalletContext context;
276 context.args = &gArgs;
277 const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateDummyWalletDatabase());
278 {
279 auto spk_man = wallet->GetOrCreateLegacyScriptPubKeyMan();
280 LOCK2(wallet->cs_wallet, spk_man->cs_KeyStore);
281 spk_man->mapKeyMetadata[coinbaseKey.GetPubKey().GetID()].nCreateTime = KEY_TIME;
282 spk_man->AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey());
283
284 AddWallet(context, wallet);
285 wallet->SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
286 }
287 JSONRPCRequest request;
288 request.context = &context;
289 request.params.setArray();
290 request.params.push_back(backup_file);
291
292 ::dumpwallet().HandleRequest(request);
293 RemoveWallet(context, wallet, /* load_on_start= */ std::nullopt);
294 }
295
296 // Call importwallet RPC and verify all blocks with timestamps >= BLOCK_TIME
297 // were scanned, and no prior blocks were scanned.
298 {
299 const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateDummyWalletDatabase());
300 LOCK(wallet->cs_wallet);
301 wallet->SetupLegacyScriptPubKeyMan();
302
303 WalletContext context;
304 context.args = &gArgs;
305 JSONRPCRequest request;
306 request.context = &context;
307 request.params.setArray();
308 request.params.push_back(backup_file);
309 AddWallet(context, wallet);
310 wallet->SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
311 ::importwallet().HandleRequest(request);
312 RemoveWallet(context, wallet, /* load_on_start= */ std::nullopt);
313
314 BOOST_CHECK_EQUAL(wallet->mapWallet.size(), 3U);
315 BOOST_CHECK_EQUAL(m_coinbase_txns.size(), 103U);
316 for (size_t i = 0; i < m_coinbase_txns.size(); ++i) {
317 bool found = wallet->GetWalletTx(m_coinbase_txns[i]->GetHash());
318 bool expected = i >= 100;
319 BOOST_CHECK_EQUAL(found, expected);
320 }
321 }
322}
323
324// Check that GetImmatureCredit() returns a newly calculated value instead of
325// the cached value after a MarkDirty() call.
326//
327// This is a regression test written to verify a bugfix for the immature credit
328// function. Similar tests probably should be written for the other credit and
329// debit functions.
330BOOST_FIXTURE_TEST_CASE(coin_mark_dirty_immature_credit, TestChain100Setup)
331{
333 CWalletTx wtx(m_coinbase_txns.back());
334
335 LOCK(wallet.cs_wallet);
336 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
337 wallet.SetupDescriptorScriptPubKeyMans();
338
339 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
340
341 CWalletTx::Confirmation confirm(CWalletTx::Status::CONFIRMED, m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash(), 0);
342 wtx.m_confirm = confirm;
343
344 // Call GetImmatureCredit() once before adding the key to the wallet to
345 // cache the current immature credit amount, which is 0.
347
348 // Invalidate the cached value, add the key, and make sure a new immature
349 // credit amount is calculated.
350 wtx.MarkDirty();
351 AddKey(wallet, coinbaseKey);
353}
354
355static int64_t AddTx(ChainstateManager& chainman, CWallet& wallet, uint32_t lockTime, int64_t mockTime, int64_t blockTime)
356{
359 tx.nLockTime = lockTime;
360 SetMockTime(mockTime);
361 CBlockIndex* block = nullptr;
362 if (blockTime > 0) {
363 LOCK(cs_main);
364 auto inserted = chainman.BlockIndex().emplace(GetRandHash(), new CBlockIndex);
365 assert(inserted.second);
366 const uint256& hash = inserted.first->first;
367 block = inserted.first->second;
368 block->nTime = blockTime;
369 block->phashBlock = &hash;
370 confirm = {CWalletTx::Status::CONFIRMED, block->nHeight, hash, 0};
371 }
372
373 // If transaction is already in map, to avoid inconsistencies, unconfirmation
374 // is needed before confirm again with different block.
375 return wallet.AddToWallet(MakeTransactionRef(tx), confirm, [&](CWalletTx& wtx, bool /* new_tx */) {
376 wtx.setUnconfirmed();
377 return true;
378 })->nTimeSmart;
379}
380
381// Simple test to verify assignment of CWalletTx::nSmartTime value. Could be
382// expanded to cover more corner cases of smart time logic.
383BOOST_AUTO_TEST_CASE(ComputeTimeSmart)
384{
385 // New transaction should use clock time if lower than block time.
386 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 100, 120), 100);
387
388 // Test that updating existing transaction does not change smart time.
389 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 200, 220), 100);
390
391 // New transaction should use clock time if there's no block time.
392 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 2, 300, 0), 300);
393
394 // New transaction should use block time if lower than clock time.
395 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 3, 420, 400), 400);
396
397 // New transaction should use latest entry time if higher than
398 // min(block time, clock time).
399 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 4, 500, 390), 400);
400
401 // If there are future entries, new transaction should use time of the
402 // newest entry that is no more than 300 seconds ahead of the clock time.
403 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 5, 50, 600), 300);
404}
405
406BOOST_AUTO_TEST_CASE(LoadReceiveRequests)
407{
408 CTxDestination dest = PKHash();
409 LOCK(m_wallet.cs_wallet);
410 WalletBatch batch{m_wallet.GetDatabase()};
411 m_wallet.SetAddressUsed(batch, dest, true);
412 m_wallet.SetAddressReceiveRequest(batch, dest, "0", "val_rr0");
413 m_wallet.SetAddressReceiveRequest(batch, dest, "1", "val_rr1");
414
415 auto values = m_wallet.GetAddressReceiveRequests();
416 BOOST_CHECK_EQUAL(values.size(), 2U);
417 BOOST_CHECK_EQUAL(values[0], "val_rr0");
418 BOOST_CHECK_EQUAL(values[1], "val_rr1");
419}
420
421// Test some watch-only LegacyScriptPubKeyMan methods by the procedure of loading (LoadWatchOnly),
422// checking (HaveWatchOnly), getting (GetWatchPubKey) and removing (RemoveWatchOnly) a
423// given PubKey, resp. its corresponding P2PK Script. Results of the the impact on
424// the address -> PubKey map is dependent on whether the PubKey is a point on the curve
425static void TestWatchOnlyPubKey(LegacyScriptPubKeyMan* spk_man, const CPubKey& add_pubkey)
426{
427 CScript p2pk = GetScriptForRawPubKey(add_pubkey);
428 CKeyID add_address = add_pubkey.GetID();
429 CPubKey found_pubkey;
430 LOCK(spk_man->cs_KeyStore);
431
432 // all Scripts (i.e. also all PubKeys) are added to the general watch-only set
433 BOOST_CHECK(!spk_man->HaveWatchOnly(p2pk));
434 spk_man->LoadWatchOnly(p2pk);
435 BOOST_CHECK(spk_man->HaveWatchOnly(p2pk));
436
437 // only PubKeys on the curve shall be added to the watch-only address -> PubKey map
438 bool is_pubkey_fully_valid = add_pubkey.IsFullyValid();
439 if (is_pubkey_fully_valid) {
440 BOOST_CHECK(spk_man->GetWatchPubKey(add_address, found_pubkey));
441 BOOST_CHECK(found_pubkey == add_pubkey);
442 } else {
443 BOOST_CHECK(!spk_man->GetWatchPubKey(add_address, found_pubkey));
444 BOOST_CHECK(found_pubkey == CPubKey()); // passed key is unchanged
445 }
446
447 spk_man->RemoveWatchOnly(p2pk);
448 BOOST_CHECK(!spk_man->HaveWatchOnly(p2pk));
449
450 if (is_pubkey_fully_valid) {
451 BOOST_CHECK(!spk_man->GetWatchPubKey(add_address, found_pubkey));
452 BOOST_CHECK(found_pubkey == add_pubkey); // passed key is unchanged
453 }
454}
455
456// Cryptographically invalidate a PubKey whilst keeping length and first byte
457static void PollutePubKey(CPubKey& pubkey)
458{
459 std::vector<unsigned char> pubkey_raw(pubkey.begin(), pubkey.end());
460 std::fill(pubkey_raw.begin()+1, pubkey_raw.end(), 0);
461 pubkey = CPubKey(pubkey_raw);
462 assert(!pubkey.IsFullyValid());
463 assert(pubkey.IsValid());
464}
465
466// Test watch-only logic for PubKeys
467BOOST_AUTO_TEST_CASE(WatchOnlyPubKeys)
468{
469 CKey key;
470 CPubKey pubkey;
471 LegacyScriptPubKeyMan* spk_man = m_wallet.GetOrCreateLegacyScriptPubKeyMan();
472
473 BOOST_CHECK(!spk_man->HaveWatchOnly());
474
475 // uncompressed valid PubKey
476 key.MakeNewKey(false);
477 pubkey = key.GetPubKey();
478 assert(!pubkey.IsCompressed());
479 TestWatchOnlyPubKey(spk_man, pubkey);
480
481 // uncompressed cryptographically invalid PubKey
482 PollutePubKey(pubkey);
483 TestWatchOnlyPubKey(spk_man, pubkey);
484
485 // compressed valid PubKey
486 key.MakeNewKey(true);
487 pubkey = key.GetPubKey();
488 assert(pubkey.IsCompressed());
489 TestWatchOnlyPubKey(spk_man, pubkey);
490
491 // compressed cryptographically invalid PubKey
492 PollutePubKey(pubkey);
493 TestWatchOnlyPubKey(spk_man, pubkey);
494
495 // invalid empty PubKey
496 pubkey = CPubKey();
497 TestWatchOnlyPubKey(spk_man, pubkey);
498}
499
501{
502public:
504 {
507 }
508
510 {
511 wallet.reset();
512 }
513
515 {
517 CAmount fee;
518 int changePos = -1;
520 CCoinControl dummy;
521 FeeCalculation fee_calc_out;
522 {
523 BOOST_CHECK(CreateTransaction(*wallet, {recipient}, tx, fee, changePos, error, dummy, fee_calc_out));
524 }
525 wallet->CommitTransaction(tx, {}, {});
526 CMutableTransaction blocktx;
527 {
528 LOCK(wallet->cs_wallet);
529 blocktx = CMutableTransaction(*wallet->mapWallet.at(tx->GetHash()).tx);
530 }
532
533 LOCK(wallet->cs_wallet);
534 wallet->SetLastBlockProcessed(wallet->GetLastBlockHeight() + 1, m_node.chainman->ActiveChain().Tip()->GetBlockHash());
535 auto it = wallet->mapWallet.find(tx->GetHash());
536 BOOST_CHECK(it != wallet->mapWallet.end());
537 CWalletTx::Confirmation confirm(CWalletTx::Status::CONFIRMED, m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash(), 1);
538 it->second.m_confirm = confirm;
539 return it->second;
540 }
541
542 std::unique_ptr<CWallet> wallet;
543};
544
546{
547 std::string coinbaseAddress = coinbaseKey.GetPubKey().GetID().ToString();
548
549 // Confirm ListCoins initially returns 1 coin grouped under coinbaseKey
550 // address.
551 std::map<CTxDestination, std::vector<COutput>> list;
552 {
553 LOCK(wallet->cs_wallet);
554 list = ListCoins(*wallet);
555 }
556 BOOST_CHECK_EQUAL(list.size(), 1U);
557 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
558 BOOST_CHECK_EQUAL(list.begin()->second.size(), 1U);
559
560 // Check initial balance from one mature coinbase transaction.
562
563 // Add a transaction creating a change address, and confirm ListCoins still
564 // returns the coin associated with the change address underneath the
565 // coinbaseKey pubkey, even though the change address has a different
566 // pubkey.
567 AddTx(CRecipient{GetScriptForRawPubKey({}), 1 * COIN, false /* subtract fee */});
568 {
569 LOCK(wallet->cs_wallet);
570 list = ListCoins(*wallet);
571 }
572 BOOST_CHECK_EQUAL(list.size(), 1U);
573 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
574 BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
575
576 // Lock both coins. Confirm number of available coins drops to 0.
577 {
578 LOCK(wallet->cs_wallet);
579 std::vector<COutput> available;
580 AvailableCoins(*wallet, available);
581 BOOST_CHECK_EQUAL(available.size(), 2U);
582 }
583 for (const auto& group : list) {
584 for (const auto& coin : group.second) {
585 LOCK(wallet->cs_wallet);
586 wallet->LockCoin(COutPoint(coin.tx->GetHash(), coin.i));
587 }
588 }
589 {
590 LOCK(wallet->cs_wallet);
591 std::vector<COutput> available;
592 AvailableCoins(*wallet, available);
593 BOOST_CHECK_EQUAL(available.size(), 0U);
594 }
595 // Confirm ListCoins still returns same result as before, despite coins
596 // being locked.
597 {
598 LOCK(wallet->cs_wallet);
599 list = ListCoins(*wallet);
600 }
601 BOOST_CHECK_EQUAL(list.size(), 1U);
602 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
603 BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
604}
605
607{
608 {
609 const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateDummyWalletDatabase());
610 wallet->SetupLegacyScriptPubKeyMan();
611 wallet->SetMinVersion(FEATURE_LATEST);
613 BOOST_CHECK(!wallet->TopUpKeyPool(1000));
614 CTxDestination dest;
616 BOOST_CHECK(!wallet->GetNewDestination(OutputType::BECH32, "", dest, error));
617 }
618 {
619 const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateDummyWalletDatabase());
620 LOCK(wallet->cs_wallet);
621 wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
622 wallet->SetMinVersion(FEATURE_LATEST);
624 CTxDestination dest;
626 BOOST_CHECK(!wallet->GetNewDestination(OutputType::BECH32, "", dest, error));
627 }
628}
629
630// Explicit calculation which is used to test the wallet constant
631// We get the same virtual size due to rounding(weight/4) for both use_max_sig values
632static size_t CalculateNestedKeyhashInputSize(bool use_max_sig)
633{
634 // Generate ephemeral valid pubkey
635 CKey key;
636 key.MakeNewKey(true);
637 CPubKey pubkey = key.GetPubKey();
638
639 // Generate pubkey hash
640 uint160 key_hash(Hash160(pubkey));
641
642 // Create inner-script to enter into keystore. Key hash can't be 0...
643 CScript inner_script = CScript() << OP_0 << std::vector<unsigned char>(key_hash.begin(), key_hash.end());
644
645 // Create outer P2SH script for the output
646 uint160 script_id(Hash160(inner_script));
647 CScript script_pubkey = CScript() << OP_HASH160 << std::vector<unsigned char>(script_id.begin(), script_id.end()) << OP_EQUAL;
648
649 // Add inner-script to key store and key to watchonly
651 keystore.AddCScript(inner_script);
652 keystore.AddKeyPubKey(key, pubkey);
653
654 // Fill in dummy signatures for fee calculation.
655 SignatureData sig_data;
656
657 if (!ProduceSignature(keystore, use_max_sig ? DUMMY_MAXIMUM_SIGNATURE_CREATOR : DUMMY_SIGNATURE_CREATOR, script_pubkey, sig_data)) {
658 // We're hand-feeding it correct arguments; shouldn't happen
659 assert(false);
660 }
661
662 CTxIn tx_in;
663 UpdateInput(tx_in, sig_data);
664 return (size_t)GetVirtualTransactionInputSize(tx_in);
665}
666
668{
671}
672
673bool malformed_descriptor(std::ios_base::failure e)
674{
675 std::string s(e.what());
676 return s.find("Missing checksum") != std::string::npos;
677}
678
680{
681 std::vector<unsigned char> malformed_record;
682 CVectorWriter vw(0, 0, malformed_record, 0);
683 vw << std::string("notadescriptor");
684 vw << (uint64_t)0;
685 vw << (int32_t)0;
686 vw << (int32_t)0;
687 vw << (int32_t)1;
688
689 VectorReader vr(0, 0, malformed_record, 0);
690 WalletDescriptor w_desc;
691 BOOST_CHECK_EXCEPTION(vr >> w_desc, std::ios_base::failure, malformed_descriptor);
692}
693
713{
714 gArgs.ForceSetArg("-unsafesqlitesync", "1");
715 // Create new wallet with known key and unload it.
716 WalletContext context;
717 context.args = &gArgs;
718 context.chain = m_node.chain.get();
719 auto wallet = TestLoadWallet(context);
720 CKey key;
721 key.MakeNewKey(true);
722 AddKey(*wallet, key);
723 TestUnloadWallet(std::move(wallet));
724
725
726 // Add log hook to detect AddToWallet events from rescans, blockConnected,
727 // and transactionAddedToMempool notifications
728 int addtx_count = 0;
729 DebugLogHelper addtx_counter("[default wallet] AddToWallet", [&](const std::string* s) {
730 if (s) ++addtx_count;
731 return false;
732 });
733
734
735 bool rescan_completed = false;
736 DebugLogHelper rescan_check("[default wallet] Rescan completed", [&](const std::string* s) {
737 if (s) rescan_completed = true;
738 return false;
739 });
740
741
742 // Block the queue to prevent the wallet receiving blockConnected and
743 // transactionAddedToMempool notifications, and create block and mempool
744 // transactions paying to the wallet
745 std::promise<void> promise;
747 promise.get_future().wait();
748 });
749 std::string error;
750 m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
751 auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
752 m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
753 auto mempool_tx = TestSimpleSpend(*m_coinbase_txns[1], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
754 BOOST_CHECK(m_node.chain->broadcastTransaction(MakeTransactionRef(mempool_tx), DEFAULT_TRANSACTION_MAXFEE, false, error));
755
756
757 // Reload wallet and make sure new transactions are detected despite events
758 // being blocked
759 wallet = TestLoadWallet(context);
760 BOOST_CHECK(rescan_completed);
761 BOOST_CHECK_EQUAL(addtx_count, 2);
762 {
763 LOCK(wallet->cs_wallet);
764 BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_tx.GetHash()), 1U);
765 BOOST_CHECK_EQUAL(wallet->mapWallet.count(mempool_tx.GetHash()), 1U);
766 }
767
768
769 // Unblock notification queue and make sure stale blockConnected and
770 // transactionAddedToMempool events are processed
771 promise.set_value();
773 BOOST_CHECK_EQUAL(addtx_count, 4);
774
775
776 TestUnloadWallet(std::move(wallet));
777
778
779 // Load wallet again, this time creating new block and mempool transactions
780 // paying to the wallet as the wallet finishes loading and syncing the
781 // queue so the events have to be handled immediately. Releasing the wallet
782 // lock during the sync is a little artificial but is needed to avoid a
783 // deadlock during the sync and simulates a new block notification happening
784 // as soon as possible.
785 addtx_count = 0;
786 auto handler = HandleLoadWallet(context, [&](std::unique_ptr<interfaces::Wallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->wallet()->cs_wallet, context.wallets_mutex) {
787 BOOST_CHECK(rescan_completed);
788 m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
789 block_tx = TestSimpleSpend(*m_coinbase_txns[2], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
790 m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
791 mempool_tx = TestSimpleSpend(*m_coinbase_txns[3], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
792 BOOST_CHECK(m_node.chain->broadcastTransaction(MakeTransactionRef(mempool_tx), DEFAULT_TRANSACTION_MAXFEE, false, error));
794 LEAVE_CRITICAL_SECTION(wallet->wallet()->cs_wallet);
796 ENTER_CRITICAL_SECTION(wallet->wallet()->cs_wallet);
798 });
799 wallet = TestLoadWallet(context);
800 BOOST_CHECK_EQUAL(addtx_count, 4);
801 {
802 LOCK(wallet->cs_wallet);
803 BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_tx.GetHash()), 1U);
804 BOOST_CHECK_EQUAL(wallet->mapWallet.count(mempool_tx.GetHash()), 1U);
805 }
806
807
808 TestUnloadWallet(std::move(wallet));
809}
810
812{
813 WalletContext context;
814 context.args = &gArgs;
815 auto wallet = TestLoadWallet(context);
817 UnloadWallet(std::move(wallet));
818}
819
821{
822 gArgs.ForceSetArg("-unsafesqlitesync", "1");
823 WalletContext context;
824 context.args = &gArgs;
825 context.chain = m_node.chain.get();
826 auto wallet = TestLoadWallet(context);
827 CKey key;
828 key.MakeNewKey(true);
829 AddKey(*wallet, key);
830
831 std::string error;
832 m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
833 auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
834 CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
835
837
838 {
839 auto block_hash = block_tx.GetHash();
840 auto prev_hash = m_coinbase_txns[0]->GetHash();
841
842 LOCK(wallet->cs_wallet);
843 BOOST_CHECK(wallet->HasWalletSpend(prev_hash));
844 BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_hash), 1u);
845
846 std::vector<uint256> vHashIn{ block_hash }, vHashOut;
847 BOOST_CHECK_EQUAL(wallet->ZapSelectTx(vHashIn, vHashOut), DBErrors::LOAD_OK);
848
849 BOOST_CHECK(!wallet->HasWalletSpend(prev_hash));
850 BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_hash), 0u);
851 }
852
853 TestUnloadWallet(std::move(wallet));
854}
855
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
NodeContext m_node
Definition: bitcoin-gui.cpp:36
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: validation.cpp:118
CBlockFileInfo * GetBlockFileInfo(size_t n)
Get block file info entry for one block file.
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune)
Actually unlink the specified files.
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
Definition: blockstorage.h:36
static constexpr int64_t TIMESTAMP_WINDOW
Timestamp window used as a grace period by code that compares external timestamps (such as timestamps...
Definition: chain.h:30
#define Assert(val)
Identity function.
Definition: check.h:57
void ForceSetArg(const std::string &strArg, const std::string &strValue)
Definition: system.cpp:624
const fs::path & GetDataDirNet() const
Get data directory path with appended network identifier.
Definition: system.h:288
unsigned int nSize
number of used bytes of block file
Definition: chain.h:44
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:146
FlatFilePos GetBlockPos() const
Definition: chain.h:223
uint32_t nTime
Definition: chain.h:200
uint256 GetBlockHash() const
Definition: chain.h:254
int64_t GetBlockTimeMax() const
Definition: chain.h:273
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:158
const uint256 * phashBlock
pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
Definition: chain.h:149
Coin Control Features.
Definition: coincontrol.h:29
An encapsulated private key.
Definition: key.h:27
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
Definition: key.cpp:160
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:187
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:23
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:27
An encapsulated public key.
Definition: pubkey.h:33
bool IsCompressed() const
Check whether this is a compressed public key.
Definition: pubkey.h:194
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:160
bool IsValid() const
Definition: pubkey.h:185
const unsigned char * end() const
Definition: pubkey.h:114
bool IsFullyValid() const
fully validate whether this is a valid public key (more expensive than IsValid())
Definition: pubkey.cpp:292
const unsigned char * begin() const
Definition: pubkey.h:113
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:406
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:260
const uint256 & GetHash() const
Definition: transaction.h:302
const std::vector< CTxOut > vout
Definition: transaction.h:271
An input of a transaction.
Definition: transaction.h:66
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:229
static std::shared_ptr< CWallet > Create(WalletContext &context, const std::string &name, std::unique_ptr< WalletDatabase > database, uint64_t wallet_creation_flags, bilingual_str &error, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:2534
A transaction with a bunch of additional info that only the owner cares about.
Definition: transaction.h:47
Confirmation m_confirm
Definition: transaction.h:169
void setUnconfirmed()
Definition: transaction.h:264
void MarkDirty()
make sure balances are recalculated
Definition: transaction.h:236
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:847
BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:949
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)
RecursiveMutex cs_KeyStore
UniValue params
Definition: request.h:33
std::any context
Definition: request.h:38
bool LoadWatchOnly(const CScript &dest)
Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
bool RemoveWatchOnly(const CScript &dest)
Remove a watch only script from the keystore.
bool GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
Fetches a pubkey from mapWatchKeys if it exists there.
bool HaveWatchOnly(const CScript &dest) const
Returns whether the watch-only script is in the wallet.
std::unique_ptr< CWallet > wallet
CWalletTx & AddTx(CRecipient recipient)
UniValue HandleRequest(const JSONRPCRequest &request) const
Definition: util.cpp:564
bool setArray()
Definition: univalue.cpp:94
bool setObject()
Definition: univalue.cpp:101
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
void clear()
Definition: univalue.cpp:15
bool push_back(const UniValue &val)
Definition: univalue.cpp:108
bool pushKV(const std::string &key, const UniValue &val)
Definition: univalue.cpp:133
Minimal stream for reading from an existing vector by reference.
Definition: streams.h:134
Access to the wallet database.
Definition: walletdb.h:179
Descriptor with some wallet metadata.
Definition: walletutil.h:76
RAII object to check and reserve a wallet rescan.
Definition: wallet.h:890
unsigned char * end()
Definition: uint256.h:63
unsigned char * begin()
Definition: uint256.h:58
bool IsNull() const
Definition: uint256.h:31
160-bit opaque blob.
Definition: uint256.h:113
256-bit opaque blob.
Definition: uint256.h:124
BOOST_AUTO_TEST_SUITE_END()
DatabaseStatus
Definition: db.h:212
std::unique_ptr< Descriptor > Parse(const std::string &descriptor, FlatSigningProvider &out, std::string &error, bool require_checksum)
Parse a descriptor string.
uint160 Hash160(const T1 &in1)
Compute the 160-bit hash an object.
Definition: hash.h:92
@ SIGHASH_ALL
Definition: interpreter.h:27
std::string EncodeSecret(const CKey &key)
Definition: key_io.cpp:196
static std::string PathToString(const path &path)
Convert path object to byte string.
Definition: fs.h:120
#define BOOST_FIXTURE_TEST_SUITE(a, b)
Definition: object.cpp:14
#define BOOST_CHECK_EQUAL(v1, v2)
Definition: object.cpp:18
#define BOOST_CHECK(expr)
Definition: object.cpp:17
int64_t GetVirtualTransactionInputSize(const CTxIn &txin, int64_t nSigOpCost, unsigned int bytes_per_sigop)
Definition: policy.cpp:295
static const unsigned int DEFAULT_INCREMENTAL_RELAY_FEE
Default for -incrementalrelayfee, which sets the minimum feerate increase for mempool limiting or BIP...
Definition: policy.h:34
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:387
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:386
uint256 GetRandHash() noexcept
Definition: random.cpp:601
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.
CAmount CachedTxGetImmatureCredit(const CWallet &wallet, const CWalletTx &wtx, bool fUseCache)
Definition: receive.cpp:164
Balance GetBalance(const CWallet &wallet, const int min_depth, bool avoid_reuse)
Definition: receive.cpp:317
bool(* handler)(const std::any &context, HTTPRequest *req, const std::string &strReq)
Definition: rest.cpp:715
@ OP_EQUAL
Definition: script.h:139
static const int64_t values[]
A selection of numbers that do not trigger int64_t overflow when added/subtracted.
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:331
void UpdateInput(CTxIn &input, const SignatureData &data)
Definition: sign.cpp:492
const BaseSignatureCreator & DUMMY_MAXIMUM_SIGNATURE_CREATOR
A signature creator that just produces 72-byte empty signatures.
Definition: sign.cpp:579
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
Definition: sign.cpp:578
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:249
void AvailableCoins(const CWallet &wallet, std::vector< COutput > &vCoins, const CCoinControl *coinControl, const CAmount &nMinimumAmount, const CAmount &nMaximumAmount, const CAmount &nMinimumSumAmount, const uint64_t nMaximumCount)
populate vCoins with vector of available COutputs.
Definition: spend.cpp:88
CAmount GetAvailableBalance(const CWallet &wallet, const CCoinControl *coinControl)
Definition: spend.cpp:216
bool CreateTransaction(CWallet &wallet, const std::vector< CRecipient > &vecSend, CTransactionRef &tx, CAmount &nFeeRet, int &nChangePosInOut, bilingual_str &error, const CCoinControl &coin_control, FeeCalculation &fee_calc_out, bool sign)
Create a new transaction paying the recipients with a set of coins selected by SelectCoins(); Also cr...
Definition: spend.cpp:941
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
Definition: standard.cpp:315
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:157
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Basic testing setup.
Definition: setup_common.h:76
NodeContext m_node
Definition: setup_common.h:78
A mutable version of CTransaction.
Definition: transaction.h:345
std::vector< CTxOut > vout
Definition: transaction.h:347
std::vector< CTxIn > vin
Definition: transaction.h:346
std::optional< int > last_scanned_height
Definition: wallet.h:522
uint256 last_failed_block
Height of the most recent block that could not be scanned due to read errors or pruning.
Definition: wallet.h:528
enum CWallet::ScanResult::@17 status
uint256 last_scanned_block
Hash and height of most recent block that was successfully scanned.
Definition: wallet.h:521
Confirmation includes tx status and a triplet of {block height/block hash/tx index in block} at which...
Definition: transaction.h:160
uint64_t create_flags
Definition: db.h:207
int nFile
Definition: flatfile.h:16
std::unique_ptr< ChainstateManager > chainman
Definition: context.h:47
std::unique_ptr< interfaces::Chain > chain
Definition: context.h:50
Testing fixture that pre-creates a 100-block REGTEST-mode block chain.
Definition: setup_common.h:116
CBlock CreateAndProcessBlock(const std::vector< CMutableTransaction > &txns, const CScript &scriptPubKey, CChainState *chainstate=nullptr)
Create a new block with just given transactions, coinbase paying to scriptPubKey, and try to add it t...
WalletContext struct containing references to state shared between CWallet instances,...
Definition: context.h:34
ArgsManager * args
Definition: context.h:36
Mutex wallets_mutex
Definition: context.h:37
interfaces::Chain * chain
Definition: context.h:35
Testing setup and teardown for wallet.
Bilingual messages:
Definition: translation.h:16
#define ENTER_CRITICAL_SECTION(cs)
Definition: sync.h:233
#define LEAVE_CRITICAL_SECTION(cs)
Definition: sync.h:239
#define LOCK2(cs1, cs2)
Definition: sync.h:227
#define LOCK(cs)
Definition: sync.h:226
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:270
bool error(const char *fmt, const Args &... args)
Definition: system.h:49
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
Definition: time.cpp:101
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
ArgsManager gArgs
Definition: system.cpp:85
assert(!tx.IsCoinBase())
static const unsigned int DEFAULT_MIN_RELAY_TX_FEE
Default for -minrelaytxfee, minimum relay fee for transactions.
Definition: validation.h:54
void CallFunctionInValidationInterfaceQueue(std::function< void()> func)
Pushes a function to callback onto the notification queue, guaranteeing any callbacks generated prior...
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
std::shared_ptr< CWallet > m_wallet
Definition: interfaces.cpp:502
std::unique_ptr< CWallet > CreateSyncedWallet(interfaces::Chain &chain, CChain &cchain, const CKey &key)
Definition: util.cpp:18
std::unique_ptr< interfaces::Handler > HandleLoadWallet(WalletContext &context, LoadWalletFn load_wallet)
Definition: wallet.cpp:158
std::unique_ptr< WalletDatabase > MakeWalletDatabase(const std::string &name, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error_string)
Definition: wallet.cpp:2510
bool RemoveWallet(WalletContext &context, const std::shared_ptr< CWallet > &wallet, std::optional< bool > load_on_start, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:117
void UnloadWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly unload and delete the wallet.
Definition: wallet.cpp:189
bool AddWallet(WalletContext &context, const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:105
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:258
static const CAmount WALLET_INCREMENTAL_RELAY_FEE
minimum recommended increment for BIP 125 replacement txs
Definition: wallet.h:87
constexpr CAmount DEFAULT_TRANSACTION_MAXFEE
-maxtxfee default
Definition: wallet.h:99
static constexpr size_t DUMMY_NESTED_P2WPKH_INPUT_SIZE
Pre-calculated constants for input size estimation in virtual size
Definition: wallet.h:105
static const CAmount DEFAULT_TRANSACTION_MINFEE
-mintxfee default
Definition: wallet.h:73
static const std::shared_ptr< CWallet > TestLoadWallet(WalletContext &context)
static void PollutePubKey(CPubKey &pubkey)
static void TestUnloadWallet(std::shared_ptr< CWallet > &&wallet)
RPCHelpMan importmulti()
Definition: rpcdump.cpp:1269
static size_t CalculateNestedKeyhashInputSize(bool use_max_sig)
RPCHelpMan importwallet()
Definition: rpcdump.cpp:509
static CMutableTransaction TestSimpleSpend(const CTransaction &from, uint32_t index, const CKey &key, const CScript &pubkey)
RPCHelpMan dumpwallet()
Definition: rpcdump.cpp:712
BOOST_AUTO_TEST_CASE(ComputeTimeSmart)
static int64_t AddTx(ChainstateManager &chainman, CWallet &wallet, uint32_t lockTime, int64_t mockTime, int64_t blockTime)
BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions, TestChain100Setup)
static void AddKey(CWallet &wallet, const CKey &key)
static void TestWatchOnlyPubKey(LegacyScriptPubKeyMan *spk_man, const CPubKey &add_pubkey)
bool malformed_descriptor(std::ios_base::failure e)
std::unique_ptr< WalletDatabase > CreateDummyWalletDatabase()
Return object for accessing dummy database with no read/write capabilities.
Definition: walletdb.cpp:1183
@ WALLET_FLAG_DISABLE_PRIVATE_KEYS
Definition: walletutil.h:50
@ WALLET_FLAG_DESCRIPTORS
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:65
@ FEATURE_LATEST
Definition: walletutil.h:29