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