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