Bitcoin ABC 0.34.2
P2P Digital Currency
wallet_tests.cpp
Go to the documentation of this file.
1// Copyright (c) 2012-2019 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 <addresstype.h>
6#include <chain.h>
7#include <chainparams.h>
8#include <config.h>
9#include <interfaces/chain.h>
10#include <node/blockstorage.h>
11#include <node/context.h>
12#include <policy/policy.h>
13#include <rpc/server.h>
14#include <script/solver.h>
15#include <util/translation.h>
16#include <validation.h>
17#include <wallet/coincontrol.h>
18#include <wallet/context.h>
19#include <wallet/receive.h>
20#include <wallet/rpc/backup.h>
21#include <wallet/spend.h>
22#include <wallet/wallet.h>
23
24#include <test/util/logging.h>
25#include <test/util/setup_common.h>
27
28#include <boost/test/unit_test.hpp>
29
30#include <univalue.h>
31
32#include <any>
33#include <cstdint>
34#include <future>
35#include <memory>
36#include <variant>
37#include <vector>
38
40
41BOOST_FIXTURE_TEST_SUITE(wallet_tests, WalletTestingSetup)
42
43static std::shared_ptr<CWallet> TestLoadWallet(WalletContext &context) {
44 DatabaseOptions options;
45 DatabaseStatus status;
46 bilingual_str error;
47 std::vector<bilingual_str> warnings;
48 auto database = MakeWalletDatabase("", options, status, error);
49 auto wallet = CWallet::Create(context, "", std::move(database),
50 options.create_flags, error, warnings);
51 NotifyWalletLoaded(context, wallet);
52 if (context.chain) {
53 wallet->postInitProcess();
54 }
55 return wallet;
56}
57
58static void TestUnloadWallet(std::shared_ptr<CWallet> &&wallet) {
59 // Calls SyncWithValidationInterfaceQueue
60 wallet->chain().waitForNotificationsIfTipChanged(BlockHash{});
61 wallet->m_chain_notifications_handler.reset();
62 WaitForDeleteWallet(std::move(wallet));
63}
64
65static CMutableTransaction TestSimpleSpend(const CTransaction &from,
66 uint32_t index, const CKey &key,
67 const CScript &pubkey) {
69 mtx.vout.push_back(
70 {from.vout[index].nValue - DEFAULT_TRANSACTION_MAXFEE, pubkey});
71 mtx.vin.push_back({CTxIn{from.GetId(), index}});
73 keystore.AddKey(key);
74 std::map<COutPoint, Coin> coins;
75 coins[mtx.vin[0].prevout].GetTxOut() = from.vout[index];
76 std::map<int, std::string> input_errors;
77 BOOST_CHECK(SignTransaction(mtx, &keystore, coins,
78 SigHashType().withForkId(), input_errors));
79 return mtx;
80}
81
82static void AddKey(CWallet &wallet, const CKey &key) {
83 auto spk_man = wallet.GetOrCreateLegacyScriptPubKeyMan();
84 LOCK2(wallet.cs_wallet, spk_man->cs_KeyStore);
85 spk_man->AddKeyPubKey(key, key.GetPubKey());
86}
87
88BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions, TestChain100Setup) {
89 ChainstateManager &chainman = *Assert(m_node.chainman);
90 // Cap last block file size, and mine new block in a new block file.
91 CBlockIndex *oldTip = WITH_LOCK(
92 chainman.GetMutex(), return m_node.chainman->ActiveChain().Tip());
93 WITH_LOCK(::cs_main, m_node.chainman->m_blockman
94 .GetBlockFileInfo(oldTip->GetBlockPos().nFile)
95 ->nSize = MAX_BLOCKFILE_SIZE);
96 CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
97 CBlockIndex *newTip = WITH_LOCK(
98 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(chainman.GetMutex());
106 wallet.SetLastBlockProcessed(
107 m_node.chainman->ActiveHeight(),
108 m_node.chainman->ActiveTip()->GetBlockHash());
109 }
110 AddKey(wallet, coinbaseKey);
112 reserver.reserve();
113 CWallet::ScanResult result = wallet.ScanForWalletTransactions(
114 BlockHash() /* start_block */, 0 /* start_height */,
115 {} /* max_height */, reserver, false /* update */);
120 BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, Amount::zero());
121 }
122
123 // Verify ScanForWalletTransactions picks up transactions in both the old
124 // and new block files.
125 {
127 {
128 LOCK(wallet.cs_wallet);
129 LOCK(chainman.GetMutex());
130 wallet.SetLastBlockProcessed(
131 m_node.chainman->ActiveHeight(),
132 m_node.chainman->ActiveTip()->GetBlockHash());
133 }
134 AddKey(wallet, coinbaseKey);
136 reserver.reserve();
137 CWallet::ScanResult result = wallet.ScanForWalletTransactions(
138 oldTip->GetBlockHash(), oldTip->nHeight, {} /* max_height */,
139 reserver, false /* update */);
142 BOOST_CHECK_EQUAL(result.last_scanned_block, newTip->GetBlockHash());
143 BOOST_CHECK_EQUAL(*result.last_scanned_height, newTip->nHeight);
144 BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 100 * COIN);
145 }
146
147 // Prune the older block file.
148 int file_number;
149 {
150 LOCK(cs_main);
151 file_number = oldTip->GetBlockPos().nFile;
152 Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
153 }
154 m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
155
156 // Verify ScanForWalletTransactions only picks transactions in the new block
157 // file.
158 {
160 {
161 LOCK(wallet.cs_wallet);
162 LOCK(chainman.GetMutex());
163 wallet.SetLastBlockProcessed(
164 m_node.chainman->ActiveHeight(),
165 m_node.chainman->ActiveTip()->GetBlockHash());
166 }
167 AddKey(wallet, coinbaseKey);
169 reserver.reserve();
170 CWallet::ScanResult result = wallet.ScanForWalletTransactions(
171 oldTip->GetBlockHash(), oldTip->nHeight, {} /* max_height */,
172 reserver, false /* update */);
175 BOOST_CHECK_EQUAL(result.last_scanned_block, newTip->GetBlockHash());
176 BOOST_CHECK_EQUAL(*result.last_scanned_height, newTip->nHeight);
177 BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 50 * COIN);
178 }
179
180 // Prune the remaining block file.
181 {
182 LOCK(cs_main);
183 file_number = newTip->GetBlockPos().nFile;
184 Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
185 }
186 m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
187
188 // Verify ScanForWalletTransactions scans no blocks.
189 {
191 {
192 LOCK(wallet.cs_wallet);
193 LOCK(chainman.GetMutex());
194 wallet.SetLastBlockProcessed(
195 m_node.chainman->ActiveHeight(),
196 m_node.chainman->ActiveTip()->GetBlockHash());
197 }
198 AddKey(wallet, coinbaseKey);
200 reserver.reserve();
201 CWallet::ScanResult result = wallet.ScanForWalletTransactions(
202 oldTip->GetBlockHash(), oldTip->nHeight, {} /* max_height */,
203 reserver, false /* update */);
205 BOOST_CHECK_EQUAL(result.last_failed_block, newTip->GetBlockHash());
208 BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, Amount::zero());
209 }
210}
211
212BOOST_FIXTURE_TEST_CASE(importmulti_rescan, TestChain100Setup) {
213 ChainstateManager &chainman = *Assert(m_node.chainman);
214 // Cap last block file size, and mine new block in a new block file.
215 CBlockIndex *oldTip = WITH_LOCK(
216 chainman.GetMutex(), return m_node.chainman->ActiveChain().Tip());
217 WITH_LOCK(::cs_main, m_node.chainman->m_blockman
218 .GetBlockFileInfo(oldTip->GetBlockPos().nFile)
219 ->nSize = MAX_BLOCKFILE_SIZE);
220 CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
221 CBlockIndex *newTip = WITH_LOCK(
222 chainman.GetMutex(), return m_node.chainman->ActiveChain().Tip());
223
224 // Prune the older block file.
225 int file_number;
226 {
227 LOCK(cs_main);
228 file_number = oldTip->GetBlockPos().nFile;
229 chainman.m_blockman.PruneOneBlockFile(file_number);
230 }
231 m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
232
233 // Set this flag so that pwallet->chain().havePruned() returns true, which
234 // affects the RPC error message below.
235 m_node.chainman->m_blockman.m_have_pruned = true;
236
237 // Verify importmulti RPC returns failure for a key whose creation time is
238 // before the missing block, and success for a key whose creation time is
239 // after.
240 {
241 std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(
242 m_node.chain.get(), "", CreateDummyWalletDatabase());
243 wallet->SetupLegacyScriptPubKeyMan();
244 WITH_LOCK(wallet->cs_wallet,
245 wallet->SetLastBlockProcessed(newTip->nHeight,
246 newTip->GetBlockHash()));
247 WalletContext context;
248 AddWallet(context, wallet);
249 UniValue keys;
250 keys.setArray();
251 UniValue key;
252 key.setObject();
253 key.pushKV("scriptPubKey",
254 HexStr(GetScriptForRawPubKey(coinbaseKey.GetPubKey())));
255 key.pushKV("timestamp", 0);
256 key.pushKV("internal", UniValue(true));
257 keys.push_back(key);
258 key.clear();
259 key.setObject();
260 CKey futureKey;
261 futureKey.MakeNewKey(true);
262 key.pushKV("scriptPubKey",
264 key.pushKV("timestamp",
265 newTip->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1);
266 key.pushKV("internal", UniValue(true));
267 keys.push_back(std::move(key));
268 JSONRPCRequest request;
269 request.context = &context;
270 request.params.setArray();
271 request.params.push_back(std::move(keys));
272
275 response.write(),
276 strprintf("[{\"success\":false,\"error\":{\"code\":-1,\"message\":"
277 "\"Rescan failed for key with creation timestamp %d. "
278 "There was an error reading a block from time %d, which "
279 "is after or within %d seconds of key creation, and "
280 "could contain transactions pertaining to the key. As a "
281 "result, transactions and coins using this key may not "
282 "appear in the wallet. This error could be caused by "
283 "pruning or data corruption (see bitcoind log for "
284 "details) and could be dealt with by downloading and "
285 "rescanning the relevant blocks (see -reindex option "
286 "and rescanblockchain RPC).\"}},{\"success\":true}]",
287 0, oldTip->GetBlockTimeMax(), TIMESTAMP_WINDOW));
288 RemoveWallet(context, wallet, /*load_on_start=*/std::nullopt);
289 }
290}
291
292// Verify importwallet RPC starts rescan at earliest block with timestamp
293// greater or equal than key birthday. Previously there was a bug where
294// importwallet RPC would start the scan at the latest block with timestamp less
295// than or equal to key birthday.
296BOOST_FIXTURE_TEST_CASE(importwallet_rescan, TestChain100Setup) {
297 ChainstateManager &chainman = *Assert(m_node.chainman);
298 // Create two blocks with same timestamp to verify that importwallet rescan
299 // will pick up both blocks, not just the first.
300 const int64_t BLOCK_TIME =
301 WITH_LOCK(chainman.GetMutex(),
302 return chainman.ActiveTip()->GetBlockTimeMax() + 5);
303 SetMockTime(BLOCK_TIME);
304 m_coinbase_txns.emplace_back(
305 CreateAndProcessBlock({},
306 GetScriptForRawPubKey(coinbaseKey.GetPubKey()))
307 .vtx[0]);
308 m_coinbase_txns.emplace_back(
309 CreateAndProcessBlock({},
310 GetScriptForRawPubKey(coinbaseKey.GetPubKey()))
311 .vtx[0]);
312
313 // Set key birthday to block time increased by the timestamp window, so
314 // rescan will start at the block time.
315 const int64_t KEY_TIME = BLOCK_TIME + TIMESTAMP_WINDOW;
316 SetMockTime(KEY_TIME);
317 m_coinbase_txns.emplace_back(
318 CreateAndProcessBlock({},
319 GetScriptForRawPubKey(coinbaseKey.GetPubKey()))
320 .vtx[0]);
321
322 std::string backup_file =
323 fs::PathToString(gArgs.GetDataDirNet() / "wallet.backup");
324
325 // Import key into wallet and call dumpwallet to create backup file.
326 {
327 WalletContext context;
328 std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(
329 m_node.chain.get(), "", CreateDummyWalletDatabase());
330 {
331 auto spk_man = wallet->GetOrCreateLegacyScriptPubKeyMan();
332 LOCK2(wallet->cs_wallet, spk_man->cs_KeyStore);
333 spk_man->mapKeyMetadata[coinbaseKey.GetPubKey().GetID()]
334 .nCreateTime = KEY_TIME;
335 spk_man->AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey());
336
337 AddWallet(context, wallet);
338 LOCK(chainman.GetMutex());
339 wallet->SetLastBlockProcessed(chainman.ActiveHeight(),
340 chainman.ActiveTip()->GetBlockHash());
341 }
342 JSONRPCRequest request;
343 request.context = &context;
344 request.params.setArray();
345 request.params.push_back(backup_file);
347 RemoveWallet(context, wallet, /*load_on_start=*/std::nullopt);
348 }
349
350 // Call importwallet RPC and verify all blocks with timestamps >= BLOCK_TIME
351 // were scanned, and no prior blocks were scanned.
352 {
353 std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(
354 m_node.chain.get(), "", CreateDummyWalletDatabase());
355 LOCK(wallet->cs_wallet);
356 wallet->SetupLegacyScriptPubKeyMan();
357
358 WalletContext context;
359 JSONRPCRequest request;
360 request.context = &context;
361 request.params.setArray();
362 request.params.push_back(backup_file);
363 AddWallet(context, wallet);
364 {
365 LOCK(chainman.GetMutex());
366 wallet->SetLastBlockProcessed(chainman.ActiveHeight(),
367 chainman.ActiveTip()->GetBlockHash());
368 }
370 RemoveWallet(context, wallet, /*load_on_start=*/std::nullopt);
371
372 BOOST_CHECK_EQUAL(wallet->mapWallet.size(), 3U);
373 BOOST_CHECK_EQUAL(m_coinbase_txns.size(), 103U);
374 for (size_t i = 0; i < m_coinbase_txns.size(); ++i) {
375 bool found = wallet->GetWalletTx(m_coinbase_txns[i]->GetId());
376 bool expected = i >= 100;
377 BOOST_CHECK_EQUAL(found, expected);
378 }
379 }
380}
381
382// Check that GetImmatureCredit() returns a newly calculated value instead of
383// the cached value after a MarkDirty() call.
384//
385// This is a regression test written to verify a bugfix for the immature credit
386// function. Similar tests probably should be written for the other credit and
387// debit functions.
388BOOST_FIXTURE_TEST_CASE(coin_mark_dirty_immature_credit, TestChain100Setup) {
389 ChainstateManager &chainman = *Assert(m_node.chainman);
391 auto spk_man = wallet.GetOrCreateLegacyScriptPubKeyMan();
392 CWalletTx wtx(m_coinbase_txns.back());
393
394 LOCK2(wallet.cs_wallet, spk_man->cs_KeyStore);
395 LOCK(chainman.GetMutex());
396 wallet.SetLastBlockProcessed(chainman.ActiveHeight(),
397 chainman.ActiveTip()->GetBlockHash());
398
399 CWalletTx::Confirmation confirm(CWalletTx::Status::CONFIRMED,
400 chainman.ActiveHeight(),
401 chainman.ActiveTip()->GetBlockHash(), 0);
402 wtx.m_confirm = confirm;
403
404 // Call GetImmatureCredit() once before adding the key to the wallet to
405 // cache the current immature credit amount, which is 0.
407
408 // Invalidate the cached value, add the key, and make sure a new immature
409 // credit amount is calculated.
410 wtx.MarkDirty();
411 BOOST_CHECK(spk_man->AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey()));
413}
414
415static int64_t AddTx(ChainstateManager &chainman, CWallet &wallet,
416 uint32_t lockTime, int64_t mockTime, int64_t blockTime) {
419 tx.nLockTime = lockTime;
420 SetMockTime(mockTime);
421 CBlockIndex *block = nullptr;
422 if (blockTime > 0) {
423 LOCK(cs_main);
424 auto inserted = chainman.BlockIndex().emplace(
425 std::piecewise_construct, std::make_tuple(GetRandHash()),
426 std::make_tuple());
427 assert(inserted.second);
428 const BlockHash &hash = inserted.first->first;
429 block = &inserted.first->second;
430 block->nTime = blockTime;
431 block->phashBlock = &hash;
432 confirm = {CWalletTx::Status::CONFIRMED, block->nHeight, hash, 0};
433 }
434
435 // If transaction is already in map, to avoid inconsistencies,
436 // unconfirmation is needed before confirm again with different block.
437 return wallet
438 .AddToWallet(MakeTransactionRef(tx), confirm,
439 [&](CWalletTx &wtx, bool /* new_tx */) {
440 wtx.setUnconfirmed();
441 return true;
442 })
443 ->nTimeSmart;
444}
445
446// Simple test to verify assignment of CWalletTx::nSmartTime value. Could be
447// expanded to cover more corner cases of smart time logic.
448BOOST_AUTO_TEST_CASE(ComputeTimeSmart) {
449 // New transaction should use clock time if lower than block time.
450 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 100, 120), 100);
451
452 // Test that updating existing transaction does not change smart time.
453 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 200, 220), 100);
454
455 // New transaction should use clock time if there's no block time.
456 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 2, 300, 0), 300);
457
458 // New transaction should use block time if lower than clock time.
459 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 3, 420, 400), 400);
460
461 // New transaction should use latest entry time if higher than
462 // min(block time, clock time).
463 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 4, 500, 390), 400);
464
465 // If there are future entries, new transaction should use time of the
466 // newest entry that is no more than 300 seconds ahead of the clock time.
467 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 5, 50, 600), 300);
468
469 // Reset mock time for other tests.
470 SetMockTime(0);
471}
472
473BOOST_AUTO_TEST_CASE(LoadReceiveRequests) {
474 CTxDestination dest = PKHash();
475 LOCK(m_wallet.cs_wallet);
476 WalletBatch batch{m_wallet.GetDatabase()};
477 m_wallet.AddDestData(batch, dest, "misc", "val_misc");
478 m_wallet.AddDestData(batch, dest, "rr0", "val_rr0");
479 m_wallet.AddDestData(batch, dest, "rr1", "val_rr1");
480
481 auto values = m_wallet.GetDestValues("rr");
482 BOOST_CHECK_EQUAL(values.size(), 2U);
483 BOOST_CHECK_EQUAL(values[0], "val_rr0");
484 BOOST_CHECK_EQUAL(values[1], "val_rr1");
485}
486
487// Test some watch-only LegacyScriptPubKeyMan methods by the procedure of
488// loading (LoadWatchOnly), checking (HaveWatchOnly), getting (GetWatchPubKey)
489// and removing (RemoveWatchOnly) a given PubKey, resp. its corresponding P2PK
490// Script. Results of the the impact on the address -> PubKey map is dependent
491// on whether the PubKey is a point on the curve
493 const CPubKey &add_pubkey) {
494 CScript p2pk = GetScriptForRawPubKey(add_pubkey);
495 CKeyID add_address = add_pubkey.GetID();
496 CPubKey found_pubkey;
497 LOCK(spk_man->cs_KeyStore);
498
499 // all Scripts (i.e. also all PubKeys) are added to the general watch-only
500 // set
501 BOOST_CHECK(!spk_man->HaveWatchOnly(p2pk));
502 spk_man->LoadWatchOnly(p2pk);
503 BOOST_CHECK(spk_man->HaveWatchOnly(p2pk));
504
505 // only PubKeys on the curve shall be added to the watch-only address ->
506 // PubKey map
507 bool is_pubkey_fully_valid = add_pubkey.IsFullyValid();
508 if (is_pubkey_fully_valid) {
509 BOOST_CHECK(spk_man->GetWatchPubKey(add_address, found_pubkey));
510 BOOST_CHECK(found_pubkey == add_pubkey);
511 } else {
512 BOOST_CHECK(!spk_man->GetWatchPubKey(add_address, found_pubkey));
513 // passed key is unchanged
514 BOOST_CHECK(found_pubkey == CPubKey());
515 }
516
517 spk_man->RemoveWatchOnly(p2pk);
518 BOOST_CHECK(!spk_man->HaveWatchOnly(p2pk));
519
520 if (is_pubkey_fully_valid) {
521 BOOST_CHECK(!spk_man->GetWatchPubKey(add_address, found_pubkey));
522 // passed key is unchanged
523 BOOST_CHECK(found_pubkey == add_pubkey);
524 }
525}
526
527// Cryptographically invalidate a PubKey whilst keeping length and first byte
528static void PollutePubKey(CPubKey &pubkey) {
529 assert(pubkey.size() > 0);
530 std::vector<uint8_t> pubkey_raw(pubkey.begin(), pubkey.end());
531 std::fill(pubkey_raw.begin() + 1, pubkey_raw.end(), 0);
532 pubkey = CPubKey(pubkey_raw);
533 assert(!pubkey.IsFullyValid());
534 assert(pubkey.IsValid());
535}
536
537// Test watch-only logic for PubKeys
538BOOST_AUTO_TEST_CASE(WatchOnlyPubKeys) {
539 CKey key;
540 CPubKey pubkey;
541 LegacyScriptPubKeyMan *spk_man =
542 m_wallet.GetOrCreateLegacyScriptPubKeyMan();
543
544 BOOST_CHECK(!spk_man->HaveWatchOnly());
545
546 // uncompressed valid PubKey
547 key.MakeNewKey(false);
548 pubkey = key.GetPubKey();
549 assert(!pubkey.IsCompressed());
550 TestWatchOnlyPubKey(spk_man, pubkey);
551
552 // uncompressed cryptographically invalid PubKey
553 PollutePubKey(pubkey);
554 TestWatchOnlyPubKey(spk_man, pubkey);
555
556 // compressed valid PubKey
557 key.MakeNewKey(true);
558 pubkey = key.GetPubKey();
559 assert(pubkey.IsCompressed());
560 TestWatchOnlyPubKey(spk_man, pubkey);
561
562 // compressed cryptographically invalid PubKey
563 PollutePubKey(pubkey);
564 TestWatchOnlyPubKey(spk_man, pubkey);
565
566 // invalid empty PubKey
567 pubkey = CPubKey();
568 TestWatchOnlyPubKey(spk_man, pubkey);
569}
570
571class ListCoinsTestingSetup : public TestChain100Setup {
572public:
574 ChainstateManager &chainman = *Assert(m_node.chainman);
575 CreateAndProcessBlock({},
576 GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
577 wallet = std::make_unique<CWallet>(m_node.chain.get(), "",
579 {
580 LOCK2(wallet->cs_wallet, ::cs_main);
581 wallet->SetLastBlockProcessed(chainman.ActiveHeight(),
582 chainman.ActiveTip()->GetBlockHash());
583 }
584 wallet->LoadWallet();
585 AddKey(*wallet, coinbaseKey);
586 WalletRescanReserver reserver(*wallet);
587 reserver.reserve();
588 CWallet::ScanResult result = wallet->ScanForWalletTransactions(
589 m_node.chainman->ActiveChain().Genesis()->GetBlockHash(),
590 0 /* start_height */, {} /* max_height */, reserver,
591 false /* update */);
593 LOCK(chainman.GetMutex());
595 chainman.ActiveTip()->GetBlockHash());
598 }
599
601
603 ChainstateManager &chainman = *Assert(m_node.chainman);
605 CCoinControl dummy;
606 {
607 constexpr int RANDOM_CHANGE_POSITION = -1;
608 auto res = CreateTransaction(*wallet, {recipient},
609 RANDOM_CHANGE_POSITION, dummy);
610 BOOST_CHECK(res);
611 tx = res->tx;
612 }
613 BOOST_CHECK_EQUAL(tx->nLockTime, 0);
614
615 wallet->CommitTransaction(tx, {}, {});
616 CMutableTransaction blocktx;
617 {
618 LOCK(wallet->cs_wallet);
619 blocktx =
620 CMutableTransaction(*wallet->mapWallet.at(tx->GetId()).tx);
621 }
622 CreateAndProcessBlock({CMutableTransaction(blocktx)},
623 GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
624
625 LOCK(wallet->cs_wallet);
626 LOCK(chainman.GetMutex());
627 wallet->SetLastBlockProcessed(wallet->GetLastBlockHeight() + 1,
628 chainman.ActiveTip()->GetBlockHash());
629 auto it = wallet->mapWallet.find(tx->GetId());
630 BOOST_CHECK(it != wallet->mapWallet.end());
632 CWalletTx::Status::CONFIRMED, chainman.ActiveHeight(),
633 chainman.ActiveTip()->GetBlockHash(), 1);
634 it->second.m_confirm = confirm;
635 return it->second;
636 }
637
638 std::unique_ptr<CWallet> wallet;
639};
640
642 std::string coinbaseAddress = coinbaseKey.GetPubKey().GetID().ToString();
643
644 // Confirm ListCoins initially returns 1 coin grouped under coinbaseKey
645 // address.
646 std::map<CTxDestination, std::vector<COutput>> list;
647 {
648 LOCK(wallet->cs_wallet);
649 list = ListCoins(*wallet);
650 }
651 BOOST_CHECK_EQUAL(list.size(), 1U);
652 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(),
653 coinbaseAddress);
654 BOOST_CHECK_EQUAL(list.begin()->second.size(), 1U);
655
656 // Check initial balance from one mature coinbase transaction.
658
659 // Add a transaction creating a change address, and confirm ListCoins still
660 // returns the coin associated with the change address underneath the
661 // coinbaseKey pubkey, even though the change address has a different
662 // pubkey.
664 false /* subtract fee */});
665 {
666 LOCK(wallet->cs_wallet);
667 list = ListCoins(*wallet);
668 }
669 BOOST_CHECK_EQUAL(list.size(), 1U);
670 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(),
671 coinbaseAddress);
672 BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
673
674 // Lock both coins. Confirm number of available coins drops to 0.
675 {
676 LOCK(wallet->cs_wallet);
677 std::vector<COutput> available;
678 AvailableCoins(*wallet, available);
679 BOOST_CHECK_EQUAL(available.size(), 2U);
680 }
681 for (const auto &group : list) {
682 for (const auto &coin : group.second) {
683 LOCK(wallet->cs_wallet);
684 wallet->LockCoin(COutPoint(coin.tx->GetId(), coin.i));
685 }
686 }
687 {
688 LOCK(wallet->cs_wallet);
689 std::vector<COutput> available;
690 AvailableCoins(*wallet, available);
691 BOOST_CHECK_EQUAL(available.size(), 0U);
692 }
693 // Confirm ListCoins still returns same result as before, despite coins
694 // being locked.
695 {
696 LOCK(wallet->cs_wallet);
697 list = ListCoins(*wallet);
698 }
699 BOOST_CHECK_EQUAL(list.size(), 1U);
700 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(),
701 coinbaseAddress);
702 BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
703}
704
705BOOST_FIXTURE_TEST_CASE(wallet_disableprivkeys, TestChain100Setup) {
706 std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(
707 m_node.chain.get(), "", CreateDummyWalletDatabase());
708 wallet->SetupLegacyScriptPubKeyMan();
709 wallet->SetMinVersion(FEATURE_LATEST);
711 BOOST_CHECK(!wallet->TopUpKeyPool(1000));
712 BOOST_CHECK(!wallet->GetNewDestination(OutputType::LEGACY, ""));
713}
714
715// Explicit calculation which is used to test the wallet constant
716static size_t CalculateP2PKHInputSize(bool use_max_sig) {
717 // Generate ephemeral valid pubkey
718 CKey key;
719 key.MakeNewKey(true);
720 CPubKey pubkey = key.GetPubKey();
721
722 // Generate pubkey hash
723 PKHash key_hash(pubkey);
724
725 // Create script to enter into keystore. Key hash can't be 0...
726 CScript script = GetScriptForDestination(key_hash);
727
728 // Add script to key store and key to watchonly
730 keystore.AddKeyPubKey(key, pubkey);
731
732 // Fill in dummy signatures for fee calculation.
733 SignatureData sig_data;
734 if (!ProduceSignature(keystore,
737 script, sig_data)) {
738 // We're hand-feeding it correct arguments; shouldn't happen
739 assert(false);
740 }
741
742 CTxIn tx_in;
743 UpdateInput(tx_in, sig_data);
744 return (size_t)GetVirtualTransactionInputSize(tx_in);
745}
746
747BOOST_FIXTURE_TEST_CASE(dummy_input_size_test, TestChain100Setup) {
750}
751
752bool malformed_descriptor(std::ios_base::failure e) {
753 std::string s(e.what());
754 return s.find("Missing checksum") != std::string::npos;
755}
756
757BOOST_FIXTURE_TEST_CASE(wallet_descriptor_test, BasicTestingSetup) {
758 std::vector<uint8_t> malformed_record;
759 VectorWriter vw{malformed_record, 0};
760 vw << std::string("notadescriptor");
761 vw << (uint64_t)0;
762 vw << (int32_t)0;
763 vw << (int32_t)0;
764 vw << (int32_t)1;
765
766 SpanReader vr{malformed_record};
767 WalletDescriptor w_desc;
768 BOOST_CHECK_EXCEPTION(vr >> w_desc, std::ios_base::failure,
770}
771
791 // Create new wallet with known key and unload it.
792 WalletContext context;
793 context.chain = m_node.chain.get();
794 auto wallet = TestLoadWallet(context);
795 CKey key;
796 key.MakeNewKey(true);
797 AddKey(*wallet, key);
798 TestUnloadWallet(std::move(wallet));
799
800 // Add log hook to detect AddToWallet events from rescans, blockConnected,
801 // and transactionAddedToMempool notifications
802 int addtx_count = 0;
803 DebugLogHelper addtx_counter("[default wallet] AddToWallet",
804 [&](const std::string *s) {
805 if (s) {
806 ++addtx_count;
807 }
808 return false;
809 });
810
811 bool rescan_completed = false;
812 DebugLogHelper rescan_check("[default wallet] Rescan completed",
813 [&](const std::string *s) {
814 if (s) {
815 rescan_completed = true;
816 }
817 return false;
818 });
819
820 // Block the queue to prevent the wallet receiving blockConnected and
821 // transactionAddedToMempool notifications, and create block and mempool
822 // transactions paying to the wallet
823 std::promise<void> promise;
824 m_node.validation_signals->CallFunctionInValidationInterfaceQueue(
825 [&promise] { promise.get_future().wait(); });
826 std::string error;
827 m_coinbase_txns.push_back(
828 CreateAndProcessBlock({},
829 GetScriptForRawPubKey(coinbaseKey.GetPubKey()))
830 .vtx[0]);
831 auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey,
833 m_coinbase_txns.push_back(
834 CreateAndProcessBlock({block_tx},
835 GetScriptForRawPubKey(coinbaseKey.GetPubKey()))
836 .vtx[0]);
837 auto mempool_tx = TestSimpleSpend(*m_coinbase_txns[1], 0, coinbaseKey,
839 BOOST_CHECK(m_node.chain->broadcastTransaction(
841 false, error));
842
843 // Reload wallet and make sure new transactions are detected despite events
844 // being blocked
845 wallet = TestLoadWallet(context);
846 BOOST_CHECK(rescan_completed);
847 BOOST_CHECK_EQUAL(addtx_count, 2);
848 {
849 LOCK(wallet->cs_wallet);
850 BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_tx.GetId()), 1U);
851 BOOST_CHECK_EQUAL(wallet->mapWallet.count(mempool_tx.GetId()), 1U);
852 }
853
854 // Unblock notification queue and make sure stale blockConnected and
855 // transactionAddedToMempool events are processed
856 promise.set_value();
857 m_node.validation_signals->SyncWithValidationInterfaceQueue();
858 BOOST_CHECK_EQUAL(addtx_count, 4);
859
860 TestUnloadWallet(std::move(wallet));
861
862 // Load wallet again, this time creating new block and mempool transactions
863 // paying to the wallet as the wallet finishes loading and syncing the
864 // queue so the events have to be handled immediately. Releasing the wallet
865 // lock during the sync is a little artificial but is needed to avoid a
866 // deadlock during the sync and simulates a new block notification happening
867 // as soon as possible.
868 addtx_count = 0;
870 context, [&](std::unique_ptr<interfaces::Wallet> wallet_param) {
871 BOOST_CHECK(rescan_completed);
872 m_coinbase_txns.push_back(
873 CreateAndProcessBlock(
874 {}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()))
875 .vtx[0]);
876 block_tx = TestSimpleSpend(*m_coinbase_txns[2], 0, coinbaseKey,
878 m_coinbase_txns.push_back(
879 CreateAndProcessBlock(
880 {block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()))
881 .vtx[0]);
882 mempool_tx =
883 TestSimpleSpend(*m_coinbase_txns[3], 0, coinbaseKey,
885 BOOST_CHECK(m_node.chain->broadcastTransaction(
886 GetConfig(), MakeTransactionRef(mempool_tx),
887 DEFAULT_TRANSACTION_MAXFEE, false, error));
888 m_node.validation_signals->SyncWithValidationInterfaceQueue();
889 });
890 wallet = TestLoadWallet(context);
891 BOOST_CHECK_EQUAL(addtx_count, 4);
892 {
893 LOCK(wallet->cs_wallet);
894 BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_tx.GetId()), 1U);
895 BOOST_CHECK_EQUAL(wallet->mapWallet.count(mempool_tx.GetId()), 1U);
896 }
897
898 TestUnloadWallet(std::move(wallet));
899}
900
901BOOST_FIXTURE_TEST_CASE(CreateWalletWithoutChain, BasicTestingSetup) {
902 WalletContext context;
903 auto wallet = TestLoadWallet(context);
905 WaitForDeleteWallet(std::move(wallet));
906}
907
908BOOST_FIXTURE_TEST_CASE(ZapSelectTx, TestChain100Setup) {
909 WalletContext context;
910 context.chain = m_node.chain.get();
911 auto wallet = TestLoadWallet(context);
912 CKey key;
913 key.MakeNewKey(true);
914 AddKey(*wallet, key);
915
916 std::string error;
917 m_coinbase_txns.push_back(
918 CreateAndProcessBlock({},
919 GetScriptForRawPubKey(coinbaseKey.GetPubKey()))
920 .vtx[0]);
921 auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey,
923 CreateAndProcessBlock({block_tx},
924 GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
925
926 m_node.validation_signals->SyncWithValidationInterfaceQueue();
927
928 {
929 auto block_id = block_tx.GetId();
930 auto prev_id = m_coinbase_txns[0]->GetId();
931
932 LOCK(wallet->cs_wallet);
933 BOOST_CHECK(wallet->HasWalletSpend(prev_id));
934 BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_id), 1u);
935
936 std::vector<TxId> vIdIn{block_id}, vIdOut;
937 BOOST_CHECK_EQUAL(wallet->ZapSelectTx(vIdIn, vIdOut),
939
940 BOOST_CHECK(!wallet->HasWalletSpend(prev_id));
941 BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_id), 0u);
942 }
943
944 TestUnloadWallet(std::move(wallet));
945}
946
947BOOST_AUTO_TEST_SUITE_END()
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
std::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
Definition: addresstype.h:54
static constexpr Amount COIN
Definition: amount.h:154
ArgsManager gArgs
Definition: args.cpp:39
RPCHelpMan importmulti()
Definition: backup.cpp:1717
RPCHelpMan importwallet()
Definition: backup.cpp:670
RPCHelpMan dumpwallet()
Definition: backup.cpp:931
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:36
#define Assert(val)
Identity function.
Definition: check.h:87
fs::path GetDataDirNet() const
Get data directory path with appended network identifier.
Definition: args.h:239
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: blockindex.h:25
const BlockHash * phashBlock
pointer to the hash of the block, if any.
Definition: blockindex.h:29
uint32_t nTime
Definition: blockindex.h:75
int64_t GetBlockTimeMax() const
Definition: blockindex.h:161
BlockHash GetBlockHash() const
Definition: blockindex.h:129
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: blockindex.h:38
FlatFilePos GetBlockPos() const EXCLUSIVE_LOCKS_REQUIRED(
Definition: blockindex.h:96
Coin Control Features.
Definition: coincontrol.h:20
An encapsulated secp256k1 private key.
Definition: key.h:28
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
Definition: key.cpp:182
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:209
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:22
A mutable version of CTransaction.
Definition: transaction.h:274
std::vector< CTxOut > vout
Definition: transaction.h:277
std::vector< CTxIn > vin
Definition: transaction.h:276
An encapsulated public key.
Definition: pubkey.h:31
bool IsCompressed() const
Check whether this is a compressed public key.
Definition: pubkey.h:154
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:137
const uint8_t * end() const
Definition: pubkey.h:101
bool IsValid() const
Definition: pubkey.h:147
bool IsFullyValid() const
fully validate whether this is a valid public key (more expensive than IsValid())
Definition: pubkey.cpp:261
unsigned int size() const
Simple read-only vector-like interface to the pubkey data.
Definition: pubkey.h:98
const uint8_t * begin() const
Definition: pubkey.h:100
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:270
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)
Initializes the wallet, returns a new CWallet instance or a null pointer in case of an error.
Definition: wallet.cpp:2790
A transaction with a bunch of additional info that only the owner cares about.
Definition: transaction.h:65
Confirmation m_confirm
Definition: transaction.h:191
void setUnconfirmed()
Definition: transaction.h:296
void MarkDirty()
make sure balances are recalculated
Definition: transaction.h:264
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1176
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:1472
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
Definition: validation.h:1328
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1453
int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1450
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1336
Fillable signing provider that keeps keys in an address->secret map.
virtual bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey)
virtual bool AddKey(const CKey &key)
RecursiveMutex cs_KeyStore
UniValue params
Definition: request.h:34
std::any context
Definition: request.h:39
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 Config &config, const JSONRPCRequest &request) const
Definition: util.cpp:611
Signature hash type wrapper class.
Definition: sighashtype.h:37
Minimal stream for reading from an existing byte array by Span.
Definition: streams.h:79
void push_back(UniValue val)
Definition: univalue.cpp:96
void setArray()
Definition: univalue.cpp:86
void clear()
Definition: univalue.cpp:18
void setObject()
Definition: univalue.cpp:91
void pushKV(std::string key, UniValue val)
Definition: univalue.cpp:115
Minimal stream for overwriting and/or appending to an existing byte vector.
Definition: streams.h:31
Access to the wallet database.
Definition: walletdb.h:175
Descriptor with some wallet metadata.
Definition: walletutil.h:80
RAII object to check and reserve a wallet rescan.
Definition: wallet.h:1132
constexpr bool IsNull() const
Definition: uint256.h:44
void PruneOneBlockFile(const int fileNumber) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Mark one block file as pruned (modify associated database entries)
const Config & GetConfig()
Definition: config.cpp:40
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:7
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: hex_base.cpp:30
static std::string PathToString(const path &path)
Convert path object to byte string.
Definition: fs.h:147
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
Definition: blockstorage.h:55
Implement std::hash so RCUPtr can be used as a key for maps or sets.
Definition: rcu.h:259
NodeContext & m_node
Definition: interfaces.cpp:827
#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 nSigChecks, unsigned int bytes_per_sigCheck)
Definition: policy.cpp:178
static CTransactionRef MakeTransactionRef()
Definition: transaction.h:316
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:315
Response response
Definition: processor.cpp:537
uint256 GetRandHash() noexcept
========== CONVENIENCE FUNCTIONS FOR COMMONLY USED RANDOMNESS ==========
Definition: random.h:494
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.
Amount CachedTxGetImmatureCredit(const CWallet &wallet, const CWalletTx &wtx, bool fUseCache)
Definition: receive.cpp:192
Balance GetBalance(const CWallet &wallet, const int min_depth, bool avoid_reuse)
Definition: receive.cpp:384
bool(* handler)(Config &config, const std::any &context, HTTPRequest *req, const std::string &strReq)
Definition: rest.cpp:1079
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:210
void UpdateInput(CTxIn &input, const SignatureData &data)
Definition: sign.cpp:343
const BaseSignatureCreator & DUMMY_MAXIMUM_SIGNATURE_CREATOR
A signature creator that just produces 72-byte empty signatures.
Definition: sign.cpp:433
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
Definition: sign.cpp:431
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
Definition: solver.cpp:143
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:256
util::Result< CreatedTransactionResult > CreateTransaction(CWallet &wallet, const std::vector< CRecipient > &vecSend, 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:996
void AvailableCoins(const CWallet &wallet, std::vector< COutput > &vCoins, const CCoinControl *coinControl, const Amount nMinimumAmount, const Amount nMaximumAmount, const Amount nMinimumSumAmount, const uint64_t nMaximumCount)
populate vCoins with vector of available COutputs.
Definition: spend.cpp:77
Amount GetAvailableBalance(const CWallet &wallet, const CCoinControl *coinControl)
Definition: spend.cpp:221
static constexpr Amount zero() noexcept
Definition: amount.h:36
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
std::optional< int > last_scanned_height
Definition: wallet.h:647
BlockHash last_scanned_block
Hash and height of most recent block that was successfully scanned.
Definition: wallet.h:646
BlockHash last_failed_block
Hash of the most recent block that could not be scanned due to read errors or pruning.
Definition: wallet.h:653
enum CWallet::ScanResult::@19 status
Confirmation includes tx status and a triplet of {block height/block hash/tx index in block} at which...
Definition: transaction.h:181
uint64_t create_flags
Definition: db.h:220
int nFile
Definition: flatfile.h:15
WalletContext struct containing references to state shared between CWallet instances,...
Definition: context.h:35
interfaces::Chain * chain
Definition: context.h:36
Testing setup and teardown for wallet.
Bilingual messages:
Definition: translation.h:17
#define LOCK2(cs1, cs2)
Definition: sync.h:298
#define LOCK(cs)
Definition: sync.h:295
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:343
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
Definition: time.cpp:64
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1203
assert(!tx.IsCoinBase())
DatabaseStatus
Definition: db.h:225
std::shared_ptr< CWallet > m_wallet
Definition: interfaces.cpp:480
static constexpr size_t DUMMY_P2PKH_INPUT_SIZE
Pre-calculated constants for input size estimation.
Definition: wallet.h:131
constexpr Amount DEFAULT_TRANSACTION_MAXFEE
-maxtxfee default
Definition: wallet.h:124
std::unique_ptr< interfaces::Handler > HandleLoadWallet(WalletContext &context, LoadWalletFn load_wallet)
Definition: wallet.cpp:179
std::unique_ptr< WalletDatabase > MakeWalletDatabase(const std::string &name, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error_string)
Definition: wallet.cpp:2758
bool RemoveWallet(WalletContext &context, const std::shared_ptr< CWallet > &wallet, std::optional< bool > load_on_start, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:126
bool AddWallet(WalletContext &context, const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:112
void WaitForDeleteWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly delete the wallet.
Definition: wallet.cpp:222
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:303
void NotifyWalletLoaded(WalletContext &context, const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:189
static void PollutePubKey(CPubKey &pubkey)
static size_t CalculateP2PKHInputSize(bool use_max_sig)
static void TestUnloadWallet(std::shared_ptr< CWallet > &&wallet)
static CMutableTransaction TestSimpleSpend(const CTransaction &from, uint32_t index, const CKey &key, const CScript &pubkey)
BOOST_AUTO_TEST_CASE(ComputeTimeSmart)
static int64_t AddTx(ChainstateManager &chainman, CWallet &wallet, uint32_t lockTime, int64_t mockTime, int64_t blockTime)
static std::shared_ptr< CWallet > TestLoadWallet(WalletContext &context)
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:1169
std::unique_ptr< WalletDatabase > CreateMockWalletDatabase()
Return object for accessing temporary in-memory database.
Definition: walletdb.cpp:1174
@ WALLET_FLAG_DISABLE_PRIVATE_KEYS
Definition: walletutil.h:55
@ FEATURE_LATEST
Definition: walletutil.h:36