Bitcoin ABC 0.31.2
P2P Digital Currency
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
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
40BOOST_FIXTURE_TEST_SUITE(wallet_tests, WalletTestingSetup)
41
42static std::shared_ptr<CWallet> TestLoadWallet(interfaces::Chain *chain) {
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 if (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()));
245 UniValue keys;
246 keys.setArray();
247 UniValue key;
248 key.setObject();
249 key.pushKV("scriptPubKey",
250 HexStr(GetScriptForRawPubKey(coinbaseKey.GetPubKey())));
251 key.pushKV("timestamp", 0);
252 key.pushKV("internal", UniValue(true));
253 keys.push_back(key);
254 key.clear();
255 key.setObject();
256 CKey futureKey;
257 futureKey.MakeNewKey(true);
258 key.pushKV("scriptPubKey",
260 key.pushKV("timestamp",
261 newTip->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1);
262 key.pushKV("internal", UniValue(true));
263 keys.push_back(key);
264 JSONRPCRequest request;
265 request.params.setArray();
266 request.params.push_back(keys);
267
270 response.write(),
271 strprintf("[{\"success\":false,\"error\":{\"code\":-1,\"message\":"
272 "\"Rescan failed for key with creation timestamp %d. "
273 "There was an error reading a block from time %d, which "
274 "is after or within %d seconds of key creation, and "
275 "could contain transactions pertaining to the key. As a "
276 "result, transactions and coins using this key may not "
277 "appear in the wallet. This error could be caused by "
278 "pruning or data corruption (see bitcoind log for "
279 "details) and could be dealt with by downloading and "
280 "rescanning the relevant blocks (see -reindex option "
281 "and rescanblockchain RPC).\"}},{\"success\":true}]",
282 0, oldTip->GetBlockTimeMax(), TIMESTAMP_WINDOW));
283 RemoveWallet(wallet, std::nullopt);
284 }
285}
286
287// Verify importwallet RPC starts rescan at earliest block with timestamp
288// greater or equal than key birthday. Previously there was a bug where
289// importwallet RPC would start the scan at the latest block with timestamp less
290// than or equal to key birthday.
291BOOST_FIXTURE_TEST_CASE(importwallet_rescan, TestChain100Setup) {
292 ChainstateManager &chainman = *Assert(m_node.chainman);
293 // Create two blocks with same timestamp to verify that importwallet rescan
294 // will pick up both blocks, not just the first.
295 const int64_t BLOCK_TIME =
296 WITH_LOCK(chainman.GetMutex(),
297 return chainman.ActiveTip()->GetBlockTimeMax() + 5);
298 SetMockTime(BLOCK_TIME);
299 m_coinbase_txns.emplace_back(
300 CreateAndProcessBlock({},
301 GetScriptForRawPubKey(coinbaseKey.GetPubKey()))
302 .vtx[0]);
303 m_coinbase_txns.emplace_back(
304 CreateAndProcessBlock({},
305 GetScriptForRawPubKey(coinbaseKey.GetPubKey()))
306 .vtx[0]);
307
308 // Set key birthday to block time increased by the timestamp window, so
309 // rescan will start at the block time.
310 const int64_t KEY_TIME = BLOCK_TIME + TIMESTAMP_WINDOW;
311 SetMockTime(KEY_TIME);
312 m_coinbase_txns.emplace_back(
313 CreateAndProcessBlock({},
314 GetScriptForRawPubKey(coinbaseKey.GetPubKey()))
315 .vtx[0]);
316
317 std::string backup_file =
318 fs::PathToString(gArgs.GetDataDirNet() / "wallet.backup");
319
320 // Import key into wallet and call dumpwallet to create backup file.
321 {
322 std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(
323 m_node.chain.get(), "", CreateDummyWalletDatabase());
324 {
325 auto spk_man = wallet->GetOrCreateLegacyScriptPubKeyMan();
326 LOCK2(wallet->cs_wallet, spk_man->cs_KeyStore);
327 spk_man->mapKeyMetadata[coinbaseKey.GetPubKey().GetID()]
328 .nCreateTime = KEY_TIME;
329 spk_man->AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey());
330
332 LOCK(chainman.GetMutex());
333 wallet->SetLastBlockProcessed(chainman.ActiveHeight(),
334 chainman.ActiveTip()->GetBlockHash());
335 }
336 JSONRPCRequest request;
337 request.params.setArray();
338 request.params.push_back(backup_file);
340 RemoveWallet(wallet, std::nullopt);
341 }
342
343 // Call importwallet RPC and verify all blocks with timestamps >= BLOCK_TIME
344 // were scanned, and no prior blocks were scanned.
345 {
346 std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(
347 m_node.chain.get(), "", CreateDummyWalletDatabase());
348 LOCK(wallet->cs_wallet);
349 wallet->SetupLegacyScriptPubKeyMan();
350
351 JSONRPCRequest request;
352 request.params.setArray();
353 request.params.push_back(backup_file);
355 {
356 LOCK(chainman.GetMutex());
357 wallet->SetLastBlockProcessed(chainman.ActiveHeight(),
358 chainman.ActiveTip()->GetBlockHash());
359 }
361 RemoveWallet(wallet, std::nullopt);
362
363 BOOST_CHECK_EQUAL(wallet->mapWallet.size(), 3U);
364 BOOST_CHECK_EQUAL(m_coinbase_txns.size(), 103U);
365 for (size_t i = 0; i < m_coinbase_txns.size(); ++i) {
366 bool found = wallet->GetWalletTx(m_coinbase_txns[i]->GetId());
367 bool expected = i >= 100;
368 BOOST_CHECK_EQUAL(found, expected);
369 }
370 }
371}
372
373// Check that GetImmatureCredit() returns a newly calculated value instead of
374// the cached value after a MarkDirty() call.
375//
376// This is a regression test written to verify a bugfix for the immature credit
377// function. Similar tests probably should be written for the other credit and
378// debit functions.
379BOOST_FIXTURE_TEST_CASE(coin_mark_dirty_immature_credit, TestChain100Setup) {
380 ChainstateManager &chainman = *Assert(m_node.chainman);
382 auto spk_man = wallet.GetOrCreateLegacyScriptPubKeyMan();
383 CWalletTx wtx(m_coinbase_txns.back());
384
385 LOCK2(wallet.cs_wallet, spk_man->cs_KeyStore);
386 LOCK(chainman.GetMutex());
387 wallet.SetLastBlockProcessed(chainman.ActiveHeight(),
388 chainman.ActiveTip()->GetBlockHash());
389
390 CWalletTx::Confirmation confirm(CWalletTx::Status::CONFIRMED,
391 chainman.ActiveHeight(),
392 chainman.ActiveTip()->GetBlockHash(), 0);
393 wtx.m_confirm = confirm;
394
395 // Call GetImmatureCredit() once before adding the key to the wallet to
396 // cache the current immature credit amount, which is 0.
398
399 // Invalidate the cached value, add the key, and make sure a new immature
400 // credit amount is calculated.
401 wtx.MarkDirty();
402 BOOST_CHECK(spk_man->AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey()));
404}
405
406static int64_t AddTx(ChainstateManager &chainman, CWallet &wallet,
407 uint32_t lockTime, int64_t mockTime, int64_t blockTime) {
410 tx.nLockTime = lockTime;
411 SetMockTime(mockTime);
412 CBlockIndex *block = nullptr;
413 if (blockTime > 0) {
414 LOCK(cs_main);
415 auto inserted = chainman.BlockIndex().emplace(
416 std::piecewise_construct, std::make_tuple(GetRandHash()),
417 std::make_tuple());
418 assert(inserted.second);
419 const BlockHash &hash = inserted.first->first;
420 block = &inserted.first->second;
421 block->nTime = blockTime;
422 block->phashBlock = &hash;
423 confirm = {CWalletTx::Status::CONFIRMED, block->nHeight, hash, 0};
424 }
425
426 // If transaction is already in map, to avoid inconsistencies,
427 // unconfirmation is needed before confirm again with different block.
428 return wallet
429 .AddToWallet(MakeTransactionRef(tx), confirm,
430 [&](CWalletTx &wtx, bool /* new_tx */) {
431 wtx.setUnconfirmed();
432 return true;
433 })
434 ->nTimeSmart;
435}
436
437// Simple test to verify assignment of CWalletTx::nSmartTime value. Could be
438// expanded to cover more corner cases of smart time logic.
439BOOST_AUTO_TEST_CASE(ComputeTimeSmart) {
440 // New transaction should use clock time if lower than block time.
441 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 100, 120), 100);
442
443 // Test that updating existing transaction does not change smart time.
444 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 200, 220), 100);
445
446 // New transaction should use clock time if there's no block time.
447 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 2, 300, 0), 300);
448
449 // New transaction should use block time if lower than clock time.
450 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 3, 420, 400), 400);
451
452 // New transaction should use latest entry time if higher than
453 // min(block time, clock time).
454 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 4, 500, 390), 400);
455
456 // If there are future entries, new transaction should use time of the
457 // newest entry that is no more than 300 seconds ahead of the clock time.
458 BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 5, 50, 600), 300);
459
460 // Reset mock time for other tests.
461 SetMockTime(0);
462}
463
464BOOST_AUTO_TEST_CASE(LoadReceiveRequests) {
465 CTxDestination dest = PKHash();
466 LOCK(m_wallet.cs_wallet);
467 WalletBatch batch{m_wallet.GetDatabase()};
468 m_wallet.AddDestData(batch, dest, "misc", "val_misc");
469 m_wallet.AddDestData(batch, dest, "rr0", "val_rr0");
470 m_wallet.AddDestData(batch, dest, "rr1", "val_rr1");
471
472 auto values = m_wallet.GetDestValues("rr");
473 BOOST_CHECK_EQUAL(values.size(), 2U);
474 BOOST_CHECK_EQUAL(values[0], "val_rr0");
475 BOOST_CHECK_EQUAL(values[1], "val_rr1");
476}
477
478// Test some watch-only LegacyScriptPubKeyMan methods by the procedure of
479// loading (LoadWatchOnly), checking (HaveWatchOnly), getting (GetWatchPubKey)
480// and removing (RemoveWatchOnly) a given PubKey, resp. its corresponding P2PK
481// Script. Results of the the impact on the address -> PubKey map is dependent
482// on whether the PubKey is a point on the curve
484 const CPubKey &add_pubkey) {
485 CScript p2pk = GetScriptForRawPubKey(add_pubkey);
486 CKeyID add_address = add_pubkey.GetID();
487 CPubKey found_pubkey;
488 LOCK(spk_man->cs_KeyStore);
489
490 // all Scripts (i.e. also all PubKeys) are added to the general watch-only
491 // set
492 BOOST_CHECK(!spk_man->HaveWatchOnly(p2pk));
493 spk_man->LoadWatchOnly(p2pk);
494 BOOST_CHECK(spk_man->HaveWatchOnly(p2pk));
495
496 // only PubKeys on the curve shall be added to the watch-only address ->
497 // PubKey map
498 bool is_pubkey_fully_valid = add_pubkey.IsFullyValid();
499 if (is_pubkey_fully_valid) {
500 BOOST_CHECK(spk_man->GetWatchPubKey(add_address, found_pubkey));
501 BOOST_CHECK(found_pubkey == add_pubkey);
502 } else {
503 BOOST_CHECK(!spk_man->GetWatchPubKey(add_address, found_pubkey));
504 // passed key is unchanged
505 BOOST_CHECK(found_pubkey == CPubKey());
506 }
507
508 spk_man->RemoveWatchOnly(p2pk);
509 BOOST_CHECK(!spk_man->HaveWatchOnly(p2pk));
510
511 if (is_pubkey_fully_valid) {
512 BOOST_CHECK(!spk_man->GetWatchPubKey(add_address, found_pubkey));
513 // passed key is unchanged
514 BOOST_CHECK(found_pubkey == add_pubkey);
515 }
516}
517
518// Cryptographically invalidate a PubKey whilst keeping length and first byte
519static void PollutePubKey(CPubKey &pubkey) {
520 assert(pubkey.size() > 0);
521 std::vector<uint8_t> pubkey_raw(pubkey.begin(), pubkey.end());
522 std::fill(pubkey_raw.begin() + 1, pubkey_raw.end(), 0);
523 pubkey = CPubKey(pubkey_raw);
524 assert(!pubkey.IsFullyValid());
525 assert(pubkey.IsValid());
526}
527
528// Test watch-only logic for PubKeys
529BOOST_AUTO_TEST_CASE(WatchOnlyPubKeys) {
530 CKey key;
531 CPubKey pubkey;
532 LegacyScriptPubKeyMan *spk_man =
533 m_wallet.GetOrCreateLegacyScriptPubKeyMan();
534
535 BOOST_CHECK(!spk_man->HaveWatchOnly());
536
537 // uncompressed valid PubKey
538 key.MakeNewKey(false);
539 pubkey = key.GetPubKey();
540 assert(!pubkey.IsCompressed());
541 TestWatchOnlyPubKey(spk_man, pubkey);
542
543 // uncompressed cryptographically invalid PubKey
544 PollutePubKey(pubkey);
545 TestWatchOnlyPubKey(spk_man, pubkey);
546
547 // compressed valid PubKey
548 key.MakeNewKey(true);
549 pubkey = key.GetPubKey();
550 assert(pubkey.IsCompressed());
551 TestWatchOnlyPubKey(spk_man, pubkey);
552
553 // compressed cryptographically invalid PubKey
554 PollutePubKey(pubkey);
555 TestWatchOnlyPubKey(spk_man, pubkey);
556
557 // invalid empty PubKey
558 pubkey = CPubKey();
559 TestWatchOnlyPubKey(spk_man, pubkey);
560}
561
562class ListCoinsTestingSetup : public TestChain100Setup {
563public:
565 ChainstateManager &chainman = *Assert(m_node.chainman);
566 CreateAndProcessBlock({},
567 GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
568 wallet = std::make_unique<CWallet>(m_node.chain.get(), "",
570 {
571 LOCK2(wallet->cs_wallet, ::cs_main);
572 wallet->SetLastBlockProcessed(chainman.ActiveHeight(),
573 chainman.ActiveTip()->GetBlockHash());
574 }
575 wallet->LoadWallet();
576 AddKey(*wallet, coinbaseKey);
577 WalletRescanReserver reserver(*wallet);
578 reserver.reserve();
579 CWallet::ScanResult result = wallet->ScanForWalletTransactions(
580 m_node.chainman->ActiveChain().Genesis()->GetBlockHash(),
581 0 /* start_height */, {} /* max_height */, reserver,
582 false /* update */);
584 LOCK(chainman.GetMutex());
586 chainman.ActiveTip()->GetBlockHash());
589 }
590
592
594 ChainstateManager &chainman = *Assert(m_node.chainman);
596 Amount fee;
597 int changePos = -1;
599 CCoinControl dummy;
600 {
601 BOOST_CHECK(CreateTransaction(*wallet, {recipient}, tx, fee,
602 changePos, error, dummy));
603 }
604 BOOST_CHECK_EQUAL(tx->nLockTime, 0);
605
606 wallet->CommitTransaction(tx, {}, {});
607 CMutableTransaction blocktx;
608 {
609 LOCK(wallet->cs_wallet);
610 blocktx =
611 CMutableTransaction(*wallet->mapWallet.at(tx->GetId()).tx);
612 }
613 CreateAndProcessBlock({CMutableTransaction(blocktx)},
614 GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
615
616 LOCK(wallet->cs_wallet);
617 LOCK(chainman.GetMutex());
618 wallet->SetLastBlockProcessed(wallet->GetLastBlockHeight() + 1,
619 chainman.ActiveTip()->GetBlockHash());
620 auto it = wallet->mapWallet.find(tx->GetId());
621 BOOST_CHECK(it != wallet->mapWallet.end());
623 CWalletTx::Status::CONFIRMED, chainman.ActiveHeight(),
624 chainman.ActiveTip()->GetBlockHash(), 1);
625 it->second.m_confirm = confirm;
626 return it->second;
627 }
628
629 std::unique_ptr<CWallet> wallet;
630};
631
633 std::string coinbaseAddress = coinbaseKey.GetPubKey().GetID().ToString();
634
635 // Confirm ListCoins initially returns 1 coin grouped under coinbaseKey
636 // address.
637 std::map<CTxDestination, std::vector<COutput>> list;
638 {
639 LOCK(wallet->cs_wallet);
640 list = ListCoins(*wallet);
641 }
642 BOOST_CHECK_EQUAL(list.size(), 1U);
643 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(),
644 coinbaseAddress);
645 BOOST_CHECK_EQUAL(list.begin()->second.size(), 1U);
646
647 // Check initial balance from one mature coinbase transaction.
649
650 // Add a transaction creating a change address, and confirm ListCoins still
651 // returns the coin associated with the change address underneath the
652 // coinbaseKey pubkey, even though the change address has a different
653 // pubkey.
655 false /* subtract fee */});
656 {
657 LOCK(wallet->cs_wallet);
658 list = ListCoins(*wallet);
659 }
660 BOOST_CHECK_EQUAL(list.size(), 1U);
661 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(),
662 coinbaseAddress);
663 BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
664
665 // Lock both coins. Confirm number of available coins drops to 0.
666 {
667 LOCK(wallet->cs_wallet);
668 std::vector<COutput> available;
669 AvailableCoins(*wallet, available);
670 BOOST_CHECK_EQUAL(available.size(), 2U);
671 }
672 for (const auto &group : list) {
673 for (const auto &coin : group.second) {
674 LOCK(wallet->cs_wallet);
675 wallet->LockCoin(COutPoint(coin.tx->GetId(), coin.i));
676 }
677 }
678 {
679 LOCK(wallet->cs_wallet);
680 std::vector<COutput> available;
681 AvailableCoins(*wallet, available);
682 BOOST_CHECK_EQUAL(available.size(), 0U);
683 }
684 // Confirm ListCoins still returns same result as before, despite coins
685 // being locked.
686 {
687 LOCK(wallet->cs_wallet);
688 list = ListCoins(*wallet);
689 }
690 BOOST_CHECK_EQUAL(list.size(), 1U);
691 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(),
692 coinbaseAddress);
693 BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
694}
695
696BOOST_FIXTURE_TEST_CASE(wallet_disableprivkeys, TestChain100Setup) {
697 std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(
698 m_node.chain.get(), "", CreateDummyWalletDatabase());
699 wallet->SetupLegacyScriptPubKeyMan();
700 wallet->SetMinVersion(FEATURE_LATEST);
702 BOOST_CHECK(!wallet->TopUpKeyPool(1000));
703 CTxDestination dest;
704 std::string error;
706 !wallet->GetNewDestination(OutputType::LEGACY, "", dest, error));
707}
708
709// Explicit calculation which is used to test the wallet constant
710static size_t CalculateP2PKHInputSize(bool use_max_sig) {
711 // Generate ephemeral valid pubkey
712 CKey key;
713 key.MakeNewKey(true);
714 CPubKey pubkey = key.GetPubKey();
715
716 // Generate pubkey hash
717 PKHash key_hash(pubkey);
718
719 // Create script to enter into keystore. Key hash can't be 0...
720 CScript script = GetScriptForDestination(key_hash);
721
722 // Add script to key store and key to watchonly
724 keystore.AddKeyPubKey(key, pubkey);
725
726 // Fill in dummy signatures for fee calculation.
727 SignatureData sig_data;
728 if (!ProduceSignature(keystore,
731 script, sig_data)) {
732 // We're hand-feeding it correct arguments; shouldn't happen
733 assert(false);
734 }
735
736 CTxIn tx_in;
737 UpdateInput(tx_in, sig_data);
738 return (size_t)GetVirtualTransactionInputSize(tx_in);
739}
740
741BOOST_FIXTURE_TEST_CASE(dummy_input_size_test, TestChain100Setup) {
744}
745
746bool malformed_descriptor(std::ios_base::failure e) {
747 std::string s(e.what());
748 return s.find("Missing checksum") != std::string::npos;
749}
750
751BOOST_FIXTURE_TEST_CASE(wallet_descriptor_test, BasicTestingSetup) {
752 std::vector<uint8_t> malformed_record;
753 CVectorWriter vw(0, 0, malformed_record, 0);
754 vw << std::string("notadescriptor");
755 vw << (uint64_t)0;
756 vw << (int32_t)0;
757 vw << (int32_t)0;
758 vw << (int32_t)1;
759
760 SpanReader vr{0, 0, malformed_record};
761 WalletDescriptor w_desc;
762 BOOST_CHECK_EXCEPTION(vr >> w_desc, std::ios_base::failure,
764}
765
785 // Create new wallet with known key and unload it.
786 auto wallet = TestLoadWallet(m_node.chain.get());
787 CKey key;
788 key.MakeNewKey(true);
789 AddKey(*wallet, key);
790 TestUnloadWallet(std::move(wallet));
791
792 // Add log hook to detect AddToWallet events from rescans, blockConnected,
793 // and transactionAddedToMempool notifications
794 int addtx_count = 0;
795 DebugLogHelper addtx_counter("[default wallet] AddToWallet",
796 [&](const std::string *s) {
797 if (s) {
798 ++addtx_count;
799 }
800 return false;
801 });
802
803 bool rescan_completed = false;
804 DebugLogHelper rescan_check("[default wallet] Rescan completed",
805 [&](const std::string *s) {
806 if (s) {
807 rescan_completed = true;
808 }
809 return false;
810 });
811
812 // Block the queue to prevent the wallet receiving blockConnected and
813 // transactionAddedToMempool notifications, and create block and mempool
814 // transactions paying to the wallet
815 std::promise<void> promise;
817 [&promise] { promise.get_future().wait(); });
818 std::string error;
819 m_coinbase_txns.push_back(
820 CreateAndProcessBlock({},
821 GetScriptForRawPubKey(coinbaseKey.GetPubKey()))
822 .vtx[0]);
823 auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey,
825 m_coinbase_txns.push_back(
826 CreateAndProcessBlock({block_tx},
827 GetScriptForRawPubKey(coinbaseKey.GetPubKey()))
828 .vtx[0]);
829 auto mempool_tx = TestSimpleSpend(*m_coinbase_txns[1], 0, coinbaseKey,
831 BOOST_CHECK(m_node.chain->broadcastTransaction(
833 false, error));
834
835 // Reload wallet and make sure new transactions are detected despite events
836 // being blocked
837 wallet = TestLoadWallet(m_node.chain.get());
838 BOOST_CHECK(rescan_completed);
839 BOOST_CHECK_EQUAL(addtx_count, 2);
840 {
841 LOCK(wallet->cs_wallet);
842 BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_tx.GetId()), 1U);
843 BOOST_CHECK_EQUAL(wallet->mapWallet.count(mempool_tx.GetId()), 1U);
844 }
845
846 // Unblock notification queue and make sure stale blockConnected and
847 // transactionAddedToMempool events are processed
848 promise.set_value();
850 BOOST_CHECK_EQUAL(addtx_count, 4);
851
852 TestUnloadWallet(std::move(wallet));
853
854 // Load wallet again, this time creating new block and mempool transactions
855 // paying to the wallet as the wallet finishes loading and syncing the
856 // queue so the events have to be handled immediately. Releasing the wallet
857 // lock during the sync is a little artificial but is needed to avoid a
858 // deadlock during the sync and simulates a new block notification happening
859 // as soon as possible.
860 addtx_count = 0;
862 [&](std::unique_ptr<interfaces::Wallet> wallet_param)
863 EXCLUSIVE_LOCKS_REQUIRED(wallet_param->wallet()->cs_wallet,
864 cs_wallets) {
865 BOOST_CHECK(rescan_completed);
866 m_coinbase_txns.push_back(
867 CreateAndProcessBlock(
868 {}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()))
869 .vtx[0]);
870 block_tx =
871 TestSimpleSpend(*m_coinbase_txns[2], 0, coinbaseKey,
873 m_coinbase_txns.push_back(
874 CreateAndProcessBlock(
875 {block_tx},
876 GetScriptForRawPubKey(coinbaseKey.GetPubKey()))
877 .vtx[0]);
878 mempool_tx =
879 TestSimpleSpend(*m_coinbase_txns[3], 0, coinbaseKey,
881 BOOST_CHECK(m_node.chain->broadcastTransaction(
882 GetConfig(), MakeTransactionRef(mempool_tx),
885 LEAVE_CRITICAL_SECTION(wallet_param->wallet()->cs_wallet);
887 ENTER_CRITICAL_SECTION(wallet_param->wallet()->cs_wallet);
889 });
890 wallet = TestLoadWallet(m_node.chain.get());
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 auto wallet = TestLoadWallet(nullptr);
904 UnloadWallet(std::move(wallet));
905}
906
907BOOST_FIXTURE_TEST_CASE(ZapSelectTx, TestChain100Setup) {
908 auto wallet = TestLoadWallet(m_node.chain.get());
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:38
RPCHelpMan importmulti()
Definition: backup.cpp:1713
RPCHelpMan importwallet()
Definition: backup.cpp:669
RPCHelpMan dumpwallet()
Definition: backup.cpp:928
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: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: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:2713
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:295
void MarkDirty()
make sure balances are recalculated
Definition: transaction.h:263
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1149
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:1415
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
Definition: validation.h:1273
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1398
int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1395
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1281
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
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: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:1113
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:263
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)
Definition: blockstorage.h:50
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:815
#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:510
uint256 GetRandHash() noexcept
Definition: random.cpp:659
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
Definition: amount.h:19
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:629
BlockHash last_scanned_block
Hash and height of most recent block that was successfully scanned.
Definition: wallet.h:628
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:635
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:224
int nFile
Definition: flatfile.h:15
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(...)
Definition: threadsafety.h:56
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:229
std::shared_ptr< CWallet > m_wallet
Definition: interfaces.cpp:475
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:168
bool RemoveWallet(const std::shared_ptr< CWallet > &wallet, std::optional< bool > load_on_start, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:122
std::unique_ptr< WalletDatabase > MakeWalletDatabase(const std::string &name, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error_string)
Definition: wallet.cpp:2681
void UnloadWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly unload and delete the wallet.
Definition: wallet.cpp:203
bool AddWallet(const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:108
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:285
static void PollutePubKey(CPubKey &pubkey)
static std::shared_ptr< CWallet > TestLoadWallet(interfaces::Chain *chain)
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:52
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:1170
std::unique_ptr< WalletDatabase > CreateMockWalletDatabase()
Return object for accessing temporary in-memory database.
Definition: walletdb.cpp:1175
@ WALLET_FLAG_DISABLE_PRIVATE_KEYS
Definition: walletutil.h:55
@ FEATURE_LATEST
Definition: walletutil.h:36