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