Bitcoin ABC 0.26.3
P2P Digital Currency
Loading...
Searching...
No Matches
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 <chain.h>
6#include <chainparams.h>
7#include <config.h>
8#include <interfaces/chain.h>
9#include <node/blockstorage.h>
10#include <node/context.h>
11#include <policy/policy.h>
12#include <rpc/server.h>
13#include <util/translation.h>
14#include <validation.h>
15#include <wallet/coincontrol.h>
16#include <wallet/receive.h>
17#include <wallet/rpc/backup.h>
18#include <wallet/spend.h>
19#include <wallet/wallet.h>
20
21#include <test/util/logging.h>
22#include <test/util/setup_common.h>
24
25#include <boost/test/unit_test.hpp>
26
27#include <univalue.h>
28
29#include <any>
30#include <cstdint>
31#include <future>
32#include <memory>
33#include <variant>
34#include <vector>
35
37
39
41
43 DatabaseOptions options;
44 DatabaseStatus status;
46 std::vector<bilingual_str> warnings;
47 auto database = MakeWalletDatabase("", options, status, error);
48 auto wallet = CWallet::Create(chain, "", std::move(database),
49 options.create_flags, error, warnings);
50 wallet->postInitProcess();
51 return wallet;
52}
53
54static void TestUnloadWallet(std::shared_ptr<CWallet> &&wallet) {
56 wallet->m_chain_notifications_handler.reset();
57 UnloadWallet(std::move(wallet));
58}
59
61 uint32_t index, const CKey &key,
62 const CScript &pubkey) {
64 mtx.vout.push_back(
65 {from.vout[index].nValue - DEFAULT_TRANSACTION_MAXFEE, pubkey});
66 mtx.vin.push_back({CTxIn{from.GetId(), index}});
68 keystore.AddKey(key);
69 std::map<COutPoint, Coin> coins;
70 coins[mtx.vin[0].prevout].GetTxOut() = from.vout[index];
71 std::map<int, std::string> input_errors;
73 SigHashType().withForkId(), input_errors));
74 return mtx;
75}
76
77static void AddKey(CWallet &wallet, const CKey &key) {
78 auto spk_man = wallet.GetOrCreateLegacyScriptPubKeyMan();
79 LOCK2(wallet.cs_wallet, spk_man->cs_KeyStore);
80 spk_man->AddKeyPubKey(key, key.GetPubKey());
81}
82
84 ChainstateManager &chainman = *Assert(m_node.chainman);
85 // Cap last block file size, and mine new block in a new block file.
87 chainman.GetMutex(), return m_node.chainman->ActiveChain().Tip());
88 WITH_LOCK(::cs_main, m_node.chainman->m_blockman
89 .GetBlockFileInfo(oldTip->GetBlockPos().nFile)
90 ->nSize = MAX_BLOCKFILE_SIZE);
93 chainman.GetMutex(), return m_node.chainman->ActiveChain().Tip());
94
95 // Verify ScanForWalletTransactions fails to read an unknown start block.
96 {
98 {
99 LOCK(wallet.cs_wallet);
100 LOCK(chainman.GetMutex());
101 wallet.SetLastBlockProcessed(
102 m_node.chainman->ActiveHeight(),
103 m_node.chainman->ActiveTip()->GetBlockHash());
104 }
107 reserver.reserve();
108 CWallet::ScanResult result = wallet.ScanForWalletTransactions(
109 BlockHash() /* start_block */, 0 /* start_height */,
110 {} /* max_height */, reserver, false /* update */);
115 BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, Amount::zero());
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 LOCK(chainman.GetMutex());
125 wallet.SetLastBlockProcessed(
126 m_node.chainman->ActiveHeight(),
127 m_node.chainman->ActiveTip()->GetBlockHash());
128 }
131 reserver.reserve();
132 CWallet::ScanResult result = wallet.ScanForWalletTransactions(
133 oldTip->GetBlockHash(), oldTip->nHeight, {} /* max_height */,
134 reserver, false /* update */);
137 BOOST_CHECK_EQUAL(result.last_scanned_block, newTip->GetBlockHash());
139 BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 100 * COIN);
140 }
141
142 // Prune the older block file.
143 int file_number;
144 {
145 LOCK(cs_main);
146 file_number = oldTip->GetBlockPos().nFile;
147 Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
148 }
149 m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
150
151 // Verify ScanForWalletTransactions only picks transactions in the new block
152 // file.
153 {
155 {
156 LOCK(wallet.cs_wallet);
157 LOCK(chainman.GetMutex());
158 wallet.SetLastBlockProcessed(
159 m_node.chainman->ActiveHeight(),
160 m_node.chainman->ActiveTip()->GetBlockHash());
161 }
164 reserver.reserve();
165 CWallet::ScanResult result = wallet.ScanForWalletTransactions(
166 oldTip->GetBlockHash(), oldTip->nHeight, {} /* max_height */,
167 reserver, false /* update */);
169 BOOST_CHECK_EQUAL(result.last_failed_block, oldTip->GetBlockHash());
170 BOOST_CHECK_EQUAL(result.last_scanned_block, newTip->GetBlockHash());
172 BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 50 * COIN);
173 }
174
175 // Prune the remaining block file.
176 {
177 LOCK(cs_main);
178 file_number = newTip->GetBlockPos().nFile;
179 Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
180 }
181 m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
182
183 // Verify ScanForWalletTransactions scans no blocks.
184 {
186 {
187 LOCK(wallet.cs_wallet);
188 LOCK(chainman.GetMutex());
189 wallet.SetLastBlockProcessed(
190 m_node.chainman->ActiveHeight(),
191 m_node.chainman->ActiveTip()->GetBlockHash());
192 }
195 reserver.reserve();
196 CWallet::ScanResult result = wallet.ScanForWalletTransactions(
197 oldTip->GetBlockHash(), oldTip->nHeight, {} /* max_height */,
198 reserver, false /* update */);
200 BOOST_CHECK_EQUAL(result.last_failed_block, newTip->GetBlockHash());
203 BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, Amount::zero());
204 }
205}
206
208 ChainstateManager &chainman = *Assert(m_node.chainman);
209 // Cap last block file size, and mine new block in a new block file.
211 chainman.GetMutex(), return m_node.chainman->ActiveChain().Tip());
212 WITH_LOCK(::cs_main, m_node.chainman->m_blockman
213 .GetBlockFileInfo(oldTip->GetBlockPos().nFile)
214 ->nSize = MAX_BLOCKFILE_SIZE);
217 chainman.GetMutex(), return m_node.chainman->ActiveChain().Tip());
218
219 // Prune the older block file.
220 int file_number;
221 {
222 LOCK(cs_main);
223 file_number = oldTip->GetBlockPos().nFile;
225 }
226 m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
227
228 // Verify importmulti RPC returns failure for a key whose creation time is
229 // before the missing block, and success for a key whose creation time is
230 // after.
231 {
232 std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(
233 m_node.chain.get(), "", CreateDummyWalletDatabase());
234 wallet->SetupLegacyScriptPubKeyMan();
235 WITH_LOCK(wallet->cs_wallet,
236 wallet->SetLastBlockProcessed(newTip->nHeight,
237 newTip->GetBlockHash()));
239 UniValue keys;
240 keys.setArray();
241 UniValue key;
242 key.setObject();
243 key.pushKV("scriptPubKey",
245 key.pushKV("timestamp", 0);
246 key.pushKV("internal", UniValue(true));
247 keys.push_back(key);
248 key.clear();
249 key.setObject();
251 futureKey.MakeNewKey(true);
252 key.pushKV("scriptPubKey",
254 key.pushKV("timestamp",
255 newTip->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1);
256 key.pushKV("internal", UniValue(true));
257 keys.push_back(key);
258 JSONRPCRequest request;
259 request.params.setArray();
260 request.params.push_back(keys);
261
264 response.write(),
265 strprintf("[{\"success\":false,\"error\":{\"code\":-1,\"message\":"
266 "\"Rescan failed for key with creation timestamp %d. "
267 "There was an error reading a block from time %d, which "
268 "is after or within %d seconds of key creation, and "
269 "could contain transactions pertaining to the key. As a "
270 "result, transactions and coins using this key may not "
271 "appear in the wallet. This error could be caused by "
272 "pruning or data corruption (see bitcoind log for "
273 "details) and could be dealt with by downloading and "
274 "rescanning the relevant blocks (see -reindex and "
275 "-rescan options).\"}},{\"success\":true}]",
276 0, oldTip->GetBlockTimeMax(), TIMESTAMP_WINDOW));
277 RemoveWallet(wallet, std::nullopt);
278 }
279}
280
281// Verify importwallet RPC starts rescan at earliest block with timestamp
282// greater or equal than key birthday. Previously there was a bug where
283// importwallet RPC would start the scan at the latest block with timestamp less
284// than or equal to key birthday.
286 ChainstateManager &chainman = *Assert(m_node.chainman);
287 // Create two blocks with same timestamp to verify that importwallet rescan
288 // will pick up both blocks, not just the first.
289 const int64_t BLOCK_TIME =
290 WITH_LOCK(chainman.GetMutex(),
291 return chainman.ActiveTip()->GetBlockTimeMax() + 5);
293 m_coinbase_txns.emplace_back(
296 .vtx[0]);
297 m_coinbase_txns.emplace_back(
300 .vtx[0]);
301
302 // Set key birthday to block time increased by the timestamp window, so
303 // rescan will start at the block time.
306 m_coinbase_txns.emplace_back(
309 .vtx[0]);
310
311 std::string backup_file =
312 fs::PathToString(gArgs.GetDataDirNet() / "wallet.backup");
313
314 // Import key into wallet and call dumpwallet to create backup file.
315 {
316 std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(
317 m_node.chain.get(), "", CreateDummyWalletDatabase());
318 {
319 auto spk_man = wallet->GetOrCreateLegacyScriptPubKeyMan();
320 LOCK2(wallet->cs_wallet, spk_man->cs_KeyStore);
321 spk_man->mapKeyMetadata[coinbaseKey.GetPubKey().GetID()]
322 .nCreateTime = KEY_TIME;
323 spk_man->AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey());
324
326 LOCK(chainman.GetMutex());
327 wallet->SetLastBlockProcessed(chainman.ActiveHeight(),
328 chainman.ActiveTip()->GetBlockHash());
329 }
330 JSONRPCRequest request;
331 request.params.setArray();
334 RemoveWallet(wallet, std::nullopt);
335 }
336
337 // Call importwallet RPC and verify all blocks with timestamps >= BLOCK_TIME
338 // were scanned, and no prior blocks were scanned.
339 {
340 std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(
341 m_node.chain.get(), "", CreateDummyWalletDatabase());
342 LOCK(wallet->cs_wallet);
343 wallet->SetupLegacyScriptPubKeyMan();
344
345 JSONRPCRequest request;
346 request.params.setArray();
349 {
350 LOCK(chainman.GetMutex());
351 wallet->SetLastBlockProcessed(chainman.ActiveHeight(),
352 chainman.ActiveTip()->GetBlockHash());
353 }
355 RemoveWallet(wallet, std::nullopt);
356
357 BOOST_CHECK_EQUAL(wallet->mapWallet.size(), 3U);
359 for (size_t i = 0; i < m_coinbase_txns.size(); ++i) {
360 bool found = wallet->GetWalletTx(m_coinbase_txns[i]->GetId());
361 bool expected = i >= 100;
362 BOOST_CHECK_EQUAL(found, expected);
363 }
364 }
365}
366
367// Check that GetImmatureCredit() returns a newly calculated value instead of
368// the cached value after a MarkDirty() call.
369//
370// This is a regression test written to verify a bugfix for the immature credit
371// function. Similar tests probably should be written for the other credit and
372// debit functions.
374 ChainstateManager &chainman = *Assert(m_node.chainman);
376 auto spk_man = wallet.GetOrCreateLegacyScriptPubKeyMan();
377 CWalletTx wtx(m_coinbase_txns.back());
378
379 LOCK2(wallet.cs_wallet, spk_man->cs_KeyStore);
380 LOCK(chainman.GetMutex());
381 wallet.SetLastBlockProcessed(chainman.ActiveHeight(),
382 chainman.ActiveTip()->GetBlockHash());
383
385 chainman.ActiveHeight(),
386 chainman.ActiveTip()->GetBlockHash(), 0);
387 wtx.m_confirm = confirm;
388
389 // Call GetImmatureCredit() once before adding the key to the wallet to
390 // cache the current immature credit amount, which is 0.
392
393 // Invalidate the cached value, add the key, and make sure a new immature
394 // credit amount is calculated.
395 wtx.MarkDirty();
396 BOOST_CHECK(spk_man->AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey()));
398}
399
404 tx.nLockTime = lockTime;
406 CBlockIndex *block = nullptr;
407 if (blockTime > 0) {
408 LOCK(cs_main);
409 auto inserted = chainman.BlockIndex().emplace(
410 std::piecewise_construct, std::make_tuple(GetRandHash()),
411 std::make_tuple());
412 assert(inserted.second);
413 const BlockHash &hash = inserted.first->first;
414 block = &inserted.first->second;
415 block->nTime = blockTime;
416 block->phashBlock = &hash;
417 confirm = {CWalletTx::Status::CONFIRMED, block->nHeight, hash, 0};
418 }
419
420 // If transaction is already in map, to avoid inconsistencies,
421 // unconfirmation is needed before confirm again with different block.
422 return wallet
423 .AddToWallet(MakeTransactionRef(tx), confirm,
424 [&](CWalletTx &wtx, bool /* new_tx */) {
425 wtx.setUnconfirmed();
426 return true;
427 })
428 ->nTimeSmart;
429}
430
431// Simple test to verify assignment of CWalletTx::nSmartTime value. Could be
432// expanded to cover more corner cases of smart time logic.
433BOOST_AUTO_TEST_CASE(ComputeTimeSmart) {
434 // New transaction should use clock time if lower than block time.
435 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 100, 120), 100);
436
437 // Test that updating existing transaction does not change smart time.
438 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 200, 220), 100);
439
440 // New transaction should use clock time if there's no block time.
441 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 2, 300, 0), 300);
442
443 // New transaction should use block time if lower than clock time.
444 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 3, 420, 400), 400);
445
446 // New transaction should use latest entry time if higher than
447 // min(block time, clock time).
448 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 4, 500, 390), 400);
449
450 // If there are future entries, new transaction should use time of the
451 // newest entry that is no more than 300 seconds ahead of the clock time.
452 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 5, 50, 600), 300);
453
454 // Reset mock time for other tests.
455 SetMockTime(0);
456}
457
459 CTxDestination dest = PKHash();
460 LOCK(m_wallet.cs_wallet);
461 WalletBatch batch{m_wallet.GetDatabase()};
462 m_wallet.AddDestData(batch, dest, "misc", "val_misc");
463 m_wallet.AddDestData(batch, dest, "rr0", "val_rr0");
464 m_wallet.AddDestData(batch, dest, "rr1", "val_rr1");
465
466 auto values = m_wallet.GetDestValues("rr");
467 BOOST_CHECK_EQUAL(values.size(), 2U);
468 BOOST_CHECK_EQUAL(values[0], "val_rr0");
469 BOOST_CHECK_EQUAL(values[1], "val_rr1");
470}
471
472// Test some watch-only LegacyScriptPubKeyMan methods by the procedure of
473// loading (LoadWatchOnly), checking (HaveWatchOnly), getting (GetWatchPubKey)
474// and removing (RemoveWatchOnly) a given PubKey, resp. its corresponding P2PK
475// Script. Results of the the impact on the address -> PubKey map is dependent
476// on whether the PubKey is a point on the curve
478 const CPubKey &add_pubkey) {
480 CKeyID add_address = add_pubkey.GetID();
482 LOCK(spk_man->cs_KeyStore);
483
484 // all Scripts (i.e. also all PubKeys) are added to the general watch-only
485 // set
486 BOOST_CHECK(!spk_man->HaveWatchOnly(p2pk));
487 spk_man->LoadWatchOnly(p2pk);
488 BOOST_CHECK(spk_man->HaveWatchOnly(p2pk));
489
490 // only PubKeys on the curve shall be added to the watch-only address ->
491 // PubKey map
492 bool is_pubkey_fully_valid = add_pubkey.IsFullyValid();
494 BOOST_CHECK(spk_man->GetWatchPubKey(add_address, found_pubkey));
496 } else {
497 BOOST_CHECK(!spk_man->GetWatchPubKey(add_address, found_pubkey));
498 // passed key is unchanged
500 }
501
502 spk_man->RemoveWatchOnly(p2pk);
503 BOOST_CHECK(!spk_man->HaveWatchOnly(p2pk));
504
506 BOOST_CHECK(!spk_man->GetWatchPubKey(add_address, found_pubkey));
507 // passed key is unchanged
509 }
510}
511
512// Cryptographically invalidate a PubKey whilst keeping length and first byte
513static void PollutePubKey(CPubKey &pubkey) {
514 assert(pubkey.size() > 0);
515 std::vector<uint8_t> pubkey_raw(pubkey.begin(), pubkey.end());
516 std::fill(pubkey_raw.begin() + 1, pubkey_raw.end(), 0);
517 pubkey = CPubKey(pubkey_raw);
518 assert(!pubkey.IsFullyValid());
519 assert(pubkey.IsValid());
520}
521
522// Test watch-only logic for PubKeys
524 CKey key;
525 CPubKey pubkey;
527 m_wallet.GetOrCreateLegacyScriptPubKeyMan();
528
529 BOOST_CHECK(!spk_man->HaveWatchOnly());
530
531 // uncompressed valid PubKey
532 key.MakeNewKey(false);
533 pubkey = key.GetPubKey();
534 assert(!pubkey.IsCompressed());
536
537 // uncompressed cryptographically invalid PubKey
538 PollutePubKey(pubkey);
540
541 // compressed valid PubKey
542 key.MakeNewKey(true);
543 pubkey = key.GetPubKey();
544 assert(pubkey.IsCompressed());
546
547 // compressed cryptographically invalid PubKey
548 PollutePubKey(pubkey);
550
551 // invalid empty PubKey
552 pubkey = CPubKey();
554}
555
556class ListCoinsTestingSetup : public TestChain100Setup {
557public:
559 ChainstateManager &chainman = *Assert(m_node.chainman);
562 wallet = std::make_unique<CWallet>(m_node.chain.get(), "",
564 {
565 LOCK2(wallet->cs_wallet, ::cs_main);
566 wallet->SetLastBlockProcessed(chainman.ActiveHeight(),
567 chainman.ActiveTip()->GetBlockHash());
568 }
569 bool firstRun;
570 wallet->LoadWallet(firstRun);
573 reserver.reserve();
574 CWallet::ScanResult result = wallet->ScanForWalletTransactions(
575 m_node.chainman->ActiveChain().Genesis()->GetBlockHash(),
576 0 /* start_height */, {} /* max_height */, reserver,
577 false /* update */);
579 LOCK(chainman.GetMutex());
581 chainman.ActiveTip()->GetBlockHash());
584 }
585
587
589 ChainstateManager &chainman = *Assert(m_node.chainman);
591 Amount fee;
592 int changePos = -1;
594 CCoinControl dummy;
595 {
596 BOOST_CHECK(CreateTransaction(*wallet, {recipient}, tx, fee,
597 changePos, error, dummy));
598 }
599 BOOST_CHECK_EQUAL(tx->nLockTime, 0);
600
601 wallet->CommitTransaction(tx, {}, {});
603 {
604 LOCK(wallet->cs_wallet);
605 blocktx =
606 CMutableTransaction(*wallet->mapWallet.at(tx->GetId()).tx);
607 }
610
611 LOCK(wallet->cs_wallet);
612 LOCK(chainman.GetMutex());
613 wallet->SetLastBlockProcessed(wallet->GetLastBlockHeight() + 1,
614 chainman.ActiveTip()->GetBlockHash());
615 auto it = wallet->mapWallet.find(tx->GetId());
616 BOOST_CHECK(it != wallet->mapWallet.end());
619 chainman.ActiveTip()->GetBlockHash(), 1);
620 it->second.m_confirm = confirm;
621 return it->second;
622 }
623
624 std::unique_ptr<CWallet> wallet;
625};
626
628 std::string coinbaseAddress = coinbaseKey.GetPubKey().GetID().ToString();
629
630 // Confirm ListCoins initially returns 1 coin grouped under coinbaseKey
631 // address.
632 std::map<CTxDestination, std::vector<COutput>> list;
633 {
634 LOCK(wallet->cs_wallet);
635 list = ListCoins(*wallet);
636 }
637 BOOST_CHECK_EQUAL(list.size(), 1U);
638 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(),
640 BOOST_CHECK_EQUAL(list.begin()->second.size(), 1U);
641
642 // Check initial balance from one mature coinbase transaction.
644
645 // Add a transaction creating a change address, and confirm ListCoins still
646 // returns the coin associated with the change address underneath the
647 // coinbaseKey pubkey, even though the change address has a different
648 // pubkey.
650 false /* subtract fee */});
651 {
652 LOCK(wallet->cs_wallet);
653 list = ListCoins(*wallet);
654 }
655 BOOST_CHECK_EQUAL(list.size(), 1U);
656 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(),
658 BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
659
660 // Lock both coins. Confirm number of available coins drops to 0.
661 {
662 LOCK(wallet->cs_wallet);
663 std::vector<COutput> available;
665 BOOST_CHECK_EQUAL(available.size(), 2U);
666 }
667 for (const auto &group : list) {
668 for (const auto &coin : group.second) {
669 LOCK(wallet->cs_wallet);
670 wallet->LockCoin(COutPoint(coin.tx->GetId(), coin.i));
671 }
672 }
673 {
674 LOCK(wallet->cs_wallet);
675 std::vector<COutput> available;
677 BOOST_CHECK_EQUAL(available.size(), 0U);
678 }
679 // Confirm ListCoins still returns same result as before, despite coins
680 // being locked.
681 {
682 LOCK(wallet->cs_wallet);
683 list = ListCoins(*wallet);
684 }
685 BOOST_CHECK_EQUAL(list.size(), 1U);
686 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(),
688 BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
689}
690
692 std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(
693 m_node.chain.get(), "", CreateDummyWalletDatabase());
694 wallet->SetupLegacyScriptPubKeyMan();
695 wallet->SetMinVersion(FEATURE_LATEST);
697 BOOST_CHECK(!wallet->TopUpKeyPool(1000));
698 CTxDestination dest;
699 std::string error;
701 !wallet->GetNewDestination(OutputType::LEGACY, "", dest, error));
702}
703
704// Explicit calculation which is used to test the wallet constant
705static size_t CalculateP2PKHInputSize(bool use_max_sig) {
706 // Generate ephemeral valid pubkey
707 CKey key;
708 key.MakeNewKey(true);
709 CPubKey pubkey = key.GetPubKey();
710
711 // Generate pubkey hash
712 PKHash key_hash(pubkey);
713
714 // Create script to enter into keystore. Key hash can't be 0...
716
717 // Add script to key store and key to watchonly
719 keystore.AddKeyPubKey(key, pubkey);
720
721 // Fill in dummy signatures for fee calculation.
726 script, sig_data)) {
727 // We're hand-feeding it correct arguments; shouldn't happen
728 assert(false);
729 }
730
731 CTxIn tx_in;
734}
735
740
741bool malformed_descriptor(std::ios_base::failure e) {
742 std::string s(e.what());
743 return s.find("Missing checksum") != std::string::npos;
744}
745
747 std::vector<uint8_t> malformed_record;
749 vw << std::string("notadescriptor");
750 vw << (uint64_t)0;
751 vw << (int32_t)0;
752 vw << (int32_t)0;
753 vw << (int32_t)1;
754
757 BOOST_CHECK_EXCEPTION(vr >> w_desc, std::ios_base::failure,
759}
760
780 // Create new wallet with known key and unload it.
781 auto wallet = TestLoadWallet(*m_node.chain);
782 CKey key;
783 key.MakeNewKey(true);
784 AddKey(*wallet, key);
785 TestUnloadWallet(std::move(wallet));
786
787 // Add log hook to detect AddToWallet events from rescans, blockConnected,
788 // and transactionAddedToMempool notifications
789 int addtx_count = 0;
790 DebugLogHelper addtx_counter("[default wallet] AddToWallet",
791 [&](const std::string *s) {
792 if (s) {
793 ++addtx_count;
794 }
795 return false;
796 });
797
798 bool rescan_completed = false;
799 DebugLogHelper rescan_check("[default wallet] Rescan completed",
800 [&](const std::string *s) {
801 if (s) {
802 rescan_completed = true;
803 }
804 return false;
805 });
806
807 // Block the queue to prevent the wallet receiving blockConnected and
808 // transactionAddedToMempool notifications, and create block and mempool
809 // transactions paying to the wallet
810 std::promise<void> promise;
812 [&promise] { promise.get_future().wait(); });
813 std::string error;
814 m_coinbase_txns.push_back(
817 .vtx[0]);
820 m_coinbase_txns.push_back(
823 .vtx[0]);
826 BOOST_CHECK(m_node.chain->broadcastTransaction(
828 false, error));
829
830 // Reload wallet and make sure new transactions are detected despite events
831 // being blocked
832 wallet = TestLoadWallet(*m_node.chain);
835 {
836 LOCK(wallet->cs_wallet);
837 BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_tx.GetId()), 1U);
838 BOOST_CHECK_EQUAL(wallet->mapWallet.count(mempool_tx.GetId()), 1U);
839 }
840
841 // Unblock notification queue and make sure stale blockConnected and
842 // transactionAddedToMempool events are processed
843 promise.set_value();
846
847 TestUnloadWallet(std::move(wallet));
848
849 // Load wallet again, this time creating new block and mempool transactions
850 // paying to the wallet as the wallet finishes loading and syncing the
851 // queue so the events have to be handled immediately. Releasing the wallet
852 // lock during the sync is a little artificial but is needed to avoid a
853 // deadlock during the sync and simulates a new block notification happening
854 // as soon as possible.
855 addtx_count = 0;
857 [&](std::unique_ptr<interfaces::Wallet> wallet_param)
858 EXCLUSIVE_LOCKS_REQUIRED(wallet_param->wallet()->cs_wallet,
859 cs_wallets) {
860 BOOST_CHECK(rescan_completed);
861 m_coinbase_txns.push_back(
862 CreateAndProcessBlock(
863 {}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()))
864 .vtx[0]);
865 block_tx =
868 m_coinbase_txns.push_back(
870 {block_tx},
872 .vtx[0]);
873 mempool_tx =
876 BOOST_CHECK(m_node.chain->broadcastTransaction(
880 LEAVE_CRITICAL_SECTION(wallet_param->wallet()->cs_wallet);
882 ENTER_CRITICAL_SECTION(wallet_param->wallet()->cs_wallet);
884 });
885 wallet = TestLoadWallet(*m_node.chain);
887 {
888 LOCK(wallet->cs_wallet);
889 BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_tx.GetId()), 1U);
890 BOOST_CHECK_EQUAL(wallet->mapWallet.count(mempool_tx.GetId()), 1U);
891 }
892
893 TestUnloadWallet(std::move(wallet));
894}
895
896BOOST_FIXTURE_TEST_CASE(ZapSelectTx, TestChain100Setup) {
897 auto wallet = TestLoadWallet(*m_node.chain);
898 CKey key;
899 key.MakeNewKey(true);
900 AddKey(*wallet, key);
901
902 std::string error;
903 m_coinbase_txns.push_back(
906 .vtx[0]);
911
913
914 {
915 auto block_id = block_tx.GetId();
916 auto prev_id = m_coinbase_txns[0]->GetId();
917
918 LOCK(wallet->cs_wallet);
919 BOOST_CHECK(wallet->HasWalletSpend(prev_id));
920 BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_id), 1u);
921
922 std::vector<TxId> vIdIn{block_id}, vIdOut;
923 BOOST_CHECK_EQUAL(wallet->ZapSelectTx(vIdIn, vIdOut),
925
926 BOOST_CHECK(!wallet->HasWalletSpend(prev_id));
927 BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_id), 0u);
928 }
929
930 TestUnloadWallet(std::move(wallet));
931}
932
static constexpr Amount COIN
Definition amount.h:144
ArgsManager gArgs
Definition args.cpp:38
RPCHelpMan importmulti()
Definition backup.cpp:1682
RPCHelpMan importwallet()
Definition backup.cpp:647
RPCHelpMan dumpwallet()
Definition backup.cpp:915
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:84
fs::path GetDataDirNet() const
Get data directory path with appended network identifier.
Definition args.h:215
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:92
int64_t GetBlockTimeMax() const
Definition blockindex.h:182
BlockHash GetBlockHash() const
Definition blockindex.h:146
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition blockindex.h:38
Coin Control Features.
Definition coincontrol.h:21
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:183
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition key.cpp:210
A reference to a CKey: the Hash160 of its serialized public key.
Definition pubkey.h:22
A mutable version of CTransaction.
std::vector< CTxOut > vout
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition transaction.h:20
An encapsulated public key.
Definition pubkey.h:31
bool IsCompressed() const
Check whether this is a compressed public key.
Definition pubkey.h:154
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:256
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
Serialized script, used inside transaction inputs and outputs.
Definition script.h:431
The basic transaction that is broadcasted on the network and contained in blocks.
An input of a transaction.
Definition transaction.h:59
Minimal stream for overwriting and/or appending to an existing byte vector.
Definition streams.h:65
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition wallet.h:254
static std::shared_ptr< CWallet > Create(interfaces::Chain &chain, 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:2707
A transaction with a bunch of additional info that only the owner cares about.
Definition transaction.h:65
Confirmation m_confirm
void setUnconfirmed()
void MarkDirty()
make sure balances are recalculated
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
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)
UniValue params
Definition request.h:34
std::unique_ptr< CWallet > wallet
CWalletTx & AddTx(CRecipient recipient)
UniValue HandleRequest(const Config &config, const JSONRPCRequest &request) const
Definition util.cpp:587
Signature hash type wrapper class.
Definition sighashtype.h:37
Minimal stream for reading from an existing byte array by Span.
Definition streams.h:129
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
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:1101
bool IsNull() const
Definition uint256.h:32
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
bool error(const char *fmt, const Args &...args)
Definition logging.h:226
static std::string PathToString(const path &path)
Convert path object to byte string.
Definition fs.h:142
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
Implement std::hash so RCUPtr can be used as a key for maps or sets.
Definition rcu.h:259
NodeContext & m_node
#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:176
static CTransactionRef MakeTransactionRef()
std::shared_ptr< const CTransaction > CTransactionRef
Response response
uint256 GetRandHash() noexcept
Definition random.cpp:659
T GetRand(T nMax=std::numeric_limits< T >::max()) noexcept
Generate a uniform random integer of type T in the range [0..nMax) nMax defaults to std::numeric_limi...
Definition random.h:85
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:818
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:198
void UpdateInput(CTxIn &input, const SignatureData &data)
Definition sign.cpp:331
const BaseSignatureCreator & DUMMY_MAXIMUM_SIGNATURE_CREATOR
A signature creator that just produces 72-byte empty signatures.
Definition sign.cpp:421
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
Definition sign.cpp:419
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:252
bool CreateTransaction(CWallet &wallet, const std::vector< CRecipient > &vecSend, CTransactionRef &tx, Amount &nFeeRet, int &nChangePosInOut, bilingual_str &error, 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:993
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:73
Amount GetAvailableBalance(const CWallet &wallet, const CCoinControl *coinControl)
Definition spend.cpp:217
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
Definition standard.cpp:244
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition standard.cpp:240
std::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
Definition standard.h:85
static constexpr Amount zero() noexcept
Definition amount.h:32
A BlockHash is a unqiue identifier for a block.
Definition blockhash.h:13
std::optional< int > last_scanned_height
Definition wallet.h:618
BlockHash last_scanned_block
Hash and height of most recent block that was successfully scanned.
Definition wallet.h:617
enum CWallet::ScanResult::@20 status
BlockHash last_failed_block
Hash of the most recent block that could not be scanned due to read errors or pruning.
Definition wallet.h:624
Confirmation includes tx status and a triplet of {block height/block hash/tx index in block} at which...
uint64_t create_flags
Definition db.h:224
Testing setup and teardown for wallet.
Bilingual messages:
Definition translation.h:17
#define ENTER_CRITICAL_SECTION(cs)
Definition sync.h:320
#define LEAVE_CRITICAL_SECTION(cs)
Definition sync.h:326
#define LOCK2(cs1, cs2)
Definition sync.h:309
#define LOCK(cs)
Definition sync.h:306
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition sync.h:357
#define EXCLUSIVE_LOCKS_REQUIRED(...)
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
Definition time.cpp:89
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
assert(!tx.IsCoinBase())
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...
DatabaseStatus
Definition db.h:229
std::shared_ptr< CWallet > m_wallet
static constexpr size_t DUMMY_P2PKH_INPUT_SIZE
Pre-calculated constants for input size estimation.
Definition wallet.h:115
constexpr Amount DEFAULT_TRANSACTION_MAXFEE
-maxtxfee default
Definition wallet.h:108
std::unique_ptr< interfaces::Handler > HandleLoadWallet(LoadWalletFn load_wallet)
Definition wallet.cpp:167
bool RemoveWallet(const std::shared_ptr< CWallet > &wallet, std::optional< bool > load_on_start, std::vector< bilingual_str > &warnings)
Definition wallet.cpp:121
std::unique_ptr< WalletDatabase > MakeWalletDatabase(const std::string &name, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error_string)
Definition wallet.cpp:2675
void UnloadWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly unload and delete the wallet.
Definition wallet.cpp:202
bool AddWallet(const std::shared_ptr< CWallet > &wallet)
Definition wallet.cpp:107
std::shared_ptr< CWallet > CreateWallet(interfaces::Chain &chain, const std::string &name, std::optional< bool > load_on_start, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error, std::vector< bilingual_str > &warnings)
Definition wallet.cpp:283
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)
RecursiveMutex cs_wallets
Definition wallet.cpp:51
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)
static std::shared_ptr< CWallet > TestLoadWallet(interfaces::Chain &chain)
std::unique_ptr< WalletDatabase > CreateDummyWalletDatabase()
Return object for accessing dummy database with no read/write capabilities.
std::unique_ptr< WalletDatabase > CreateMockWalletDatabase()
Return object for accessing temporary in-memory database.
@ WALLET_FLAG_DISABLE_PRIVATE_KEYS
Definition walletutil.h:55
@ FEATURE_LATEST
Definition walletutil.h:36