Bitcoin ABC  0.24.7
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/context.h>
10 #include <policy/policy.h>
11 #include <rpc/server.h>
12 #include <util/ref.h>
13 #include <util/translation.h>
14 #include <validation.h>
15 #include <wallet/coincontrol.h>
16 #include <wallet/rpcdump.h>
17 #include <wallet/wallet.h>
18 
19 #include <test/util/logging.h>
20 #include <test/util/setup_common.h>
22 
23 #include <boost/test/unit_test.hpp>
24 
25 #include <univalue.h>
26 
27 #include <cstdint>
28 #include <future>
29 #include <memory>
30 #include <vector>
31 
33 
34 static std::shared_ptr<CWallet> TestLoadWallet(interfaces::Chain &chain) {
35  DatabaseOptions options;
36  DatabaseStatus status;
38  std::vector<bilingual_str> warnings;
39  auto database = MakeWalletDatabase("", options, status, error);
40  auto wallet = CWallet::Create(chain, "", std::move(database),
41  options.create_flags, error, warnings);
42  wallet->postInitProcess();
43  return wallet;
44 }
45 
46 static void TestUnloadWallet(std::shared_ptr<CWallet> &&wallet) {
48  wallet->m_chain_notifications_handler.reset();
49  UnloadWallet(std::move(wallet));
50 }
51 
53  uint32_t index, const CKey &key,
54  const CScript &pubkey) {
56  mtx.vout.push_back(
57  {from.vout[index].nValue - DEFAULT_TRANSACTION_MAXFEE, pubkey});
58  mtx.vin.push_back({CTxIn{from.GetId(), index}});
59  FillableSigningProvider keystore;
60  keystore.AddKey(key);
61  std::map<COutPoint, Coin> coins;
62  coins[mtx.vin[0].prevout].GetTxOut() = from.vout[index];
63  std::map<int, std::string> input_errors;
64  BOOST_CHECK(SignTransaction(mtx, &keystore, coins,
65  SigHashType().withForkId(), input_errors));
66  return mtx;
67 }
68 
69 static void AddKey(CWallet &wallet, const CKey &key) {
70  auto spk_man = wallet.GetOrCreateLegacyScriptPubKeyMan();
71  LOCK2(wallet.cs_wallet, spk_man->cs_KeyStore);
72  spk_man->AddKeyPubKey(key, key.GetPubKey());
73 }
74 
75 BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions, TestChain100Setup) {
76  // Cap last block file size, and mine new block in a new block file.
77  CBlockIndex *oldTip = ::ChainActive().Tip();
79  CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
80  CBlockIndex *newTip = ::ChainActive().Tip();
81 
82  NodeContext node;
83  auto chain = interfaces::MakeChain(node, Params());
84 
85  // Verify ScanForWalletTransactions fails to read an unknown start block.
86  {
87  CWallet wallet(chain.get(), "", CreateDummyWalletDatabase());
88  {
89  LOCK(wallet.cs_wallet);
90  wallet.SetLastBlockProcessed(::ChainActive().Height(),
91  ::ChainActive().Tip()->GetBlockHash());
92  }
93  AddKey(wallet, coinbaseKey);
94  WalletRescanReserver reserver(wallet);
95  reserver.reserve();
97  BlockHash() /* start_block */, 0 /* start_height */,
98  {} /* max_height */, reserver, false /* update */);
104  }
105 
106  // Verify ScanForWalletTransactions picks up transactions in both the old
107  // and new block files.
108  {
109  CWallet wallet(chain.get(), "", CreateDummyWalletDatabase());
110  {
111  LOCK(wallet.cs_wallet);
112  wallet.SetLastBlockProcessed(::ChainActive().Height(),
113  ::ChainActive().Tip()->GetBlockHash());
114  }
115  AddKey(wallet, coinbaseKey);
116  WalletRescanReserver reserver(wallet);
117  reserver.reserve();
119  oldTip->GetBlockHash(), oldTip->nHeight, {} /* max_height */,
120  reserver, false /* update */);
123  BOOST_CHECK_EQUAL(result.last_scanned_block, newTip->GetBlockHash());
124  BOOST_CHECK_EQUAL(*result.last_scanned_height, newTip->nHeight);
126  }
127 
128  // Prune the older block file.
129  {
130  LOCK(cs_main);
132  ->m_blockman.PruneOneBlockFile(oldTip->GetBlockPos().nFile);
133  }
134  UnlinkPrunedFiles({oldTip->GetBlockPos().nFile});
135 
136  // Verify ScanForWalletTransactions only picks transactions in the new block
137  // file.
138  {
139  CWallet wallet(chain.get(), "", CreateDummyWalletDatabase());
140  {
141  LOCK(wallet.cs_wallet);
142  wallet.SetLastBlockProcessed(::ChainActive().Height(),
143  ::ChainActive().Tip()->GetBlockHash());
144  }
145  AddKey(wallet, coinbaseKey);
146  WalletRescanReserver reserver(wallet);
147  reserver.reserve();
149  oldTip->GetBlockHash(), oldTip->nHeight, {} /* max_height */,
150  reserver, false /* update */);
153  BOOST_CHECK_EQUAL(result.last_scanned_block, newTip->GetBlockHash());
154  BOOST_CHECK_EQUAL(*result.last_scanned_height, newTip->nHeight);
156  }
157 
158  // Prune the remaining block file.
159  {
160  LOCK(cs_main);
162  ->m_blockman.PruneOneBlockFile(newTip->GetBlockPos().nFile);
163  }
164  UnlinkPrunedFiles({newTip->GetBlockPos().nFile});
165 
166  // Verify ScanForWalletTransactions scans no blocks.
167  {
168  CWallet wallet(chain.get(), "", CreateDummyWalletDatabase());
169  {
170  LOCK(wallet.cs_wallet);
171  wallet.SetLastBlockProcessed(::ChainActive().Height(),
172  ::ChainActive().Tip()->GetBlockHash());
173  }
174  AddKey(wallet, coinbaseKey);
175  WalletRescanReserver reserver(wallet);
176  reserver.reserve();
178  oldTip->GetBlockHash(), oldTip->nHeight, {} /* max_height */,
179  reserver, false /* update */);
181  BOOST_CHECK_EQUAL(result.last_failed_block, newTip->GetBlockHash());
185  }
186 }
187 
188 BOOST_FIXTURE_TEST_CASE(importmulti_rescan, TestChain100Setup) {
189  // Cap last block file size, and mine new block in a new block file.
190  CBlockIndex *oldTip = ::ChainActive().Tip();
192  CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
193  CBlockIndex *newTip = ::ChainActive().Tip();
194 
195  NodeContext node;
196  auto chain = interfaces::MakeChain(node, Params());
197 
198  // Prune the older block file.
199  {
200  LOCK(cs_main);
202  ->m_blockman.PruneOneBlockFile(oldTip->GetBlockPos().nFile);
203  }
204  UnlinkPrunedFiles({oldTip->GetBlockPos().nFile});
205 
206  // Verify importmulti RPC returns failure for a key whose creation time is
207  // before the missing block, and success for a key whose creation time is
208  // after.
209  {
210  std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(
211  chain.get(), "", CreateDummyWalletDatabase());
212  wallet->SetupLegacyScriptPubKeyMan();
213  WITH_LOCK(wallet->cs_wallet,
214  wallet->SetLastBlockProcessed(newTip->nHeight,
215  newTip->GetBlockHash()));
216  AddWallet(wallet);
217  UniValue keys;
218  keys.setArray();
219  UniValue key;
220  key.setObject();
221  key.pushKV("scriptPubKey",
222  HexStr(GetScriptForRawPubKey(coinbaseKey.GetPubKey())));
223  key.pushKV("timestamp", 0);
224  key.pushKV("internal", UniValue(true));
225  keys.push_back(key);
226  key.clear();
227  key.setObject();
228  CKey futureKey;
229  futureKey.MakeNewKey(true);
230  key.pushKV("scriptPubKey",
231  HexStr(GetScriptForRawPubKey(futureKey.GetPubKey())));
232  key.pushKV("timestamp",
233  newTip->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1);
234  key.pushKV("internal", UniValue(true));
235  keys.push_back(key);
236  util::Ref context;
237  JSONRPCRequest request(context);
238  request.params.setArray();
239  request.params.push_back(keys);
240 
243  response.write(),
244  strprintf("[{\"success\":false,\"error\":{\"code\":-1,\"message\":"
245  "\"Rescan failed for key with creation timestamp %d. "
246  "There was an error reading a block from time %d, which "
247  "is after or within %d seconds of key creation, and "
248  "could contain transactions pertaining to the key. As a "
249  "result, transactions and coins using this key may not "
250  "appear in the wallet. This error could be caused by "
251  "pruning or data corruption (see bitcoind log for "
252  "details) and could be dealt with by downloading and "
253  "rescanning the relevant blocks (see -reindex and "
254  "-rescan options).\"}},{\"success\":true}]",
255  0, oldTip->GetBlockTimeMax(), TIMESTAMP_WINDOW));
256  RemoveWallet(wallet, std::nullopt);
257  }
258 }
259 
260 // Verify importwallet RPC starts rescan at earliest block with timestamp
261 // greater or equal than key birthday. Previously there was a bug where
262 // importwallet RPC would start the scan at the latest block with timestamp less
263 // than or equal to key birthday.
264 BOOST_FIXTURE_TEST_CASE(importwallet_rescan, TestChain100Setup) {
265  // Create two blocks with same timestamp to verify that importwallet rescan
266  // will pick up both blocks, not just the first.
267  const int64_t BLOCK_TIME = ::ChainActive().Tip()->GetBlockTimeMax() + 5;
268  SetMockTime(BLOCK_TIME);
269  m_coinbase_txns.emplace_back(
270  CreateAndProcessBlock({},
271  GetScriptForRawPubKey(coinbaseKey.GetPubKey()))
272  .vtx[0]);
273  m_coinbase_txns.emplace_back(
274  CreateAndProcessBlock({},
275  GetScriptForRawPubKey(coinbaseKey.GetPubKey()))
276  .vtx[0]);
277 
278  // Set key birthday to block time increased by the timestamp window, so
279  // rescan will start at the block time.
280  const int64_t KEY_TIME = BLOCK_TIME + TIMESTAMP_WINDOW;
281  SetMockTime(KEY_TIME);
282  m_coinbase_txns.emplace_back(
283  CreateAndProcessBlock({},
284  GetScriptForRawPubKey(coinbaseKey.GetPubKey()))
285  .vtx[0]);
286 
287  NodeContext node;
288  auto chain = interfaces::MakeChain(node, Params());
289 
290  std::string backup_file = (GetDataDir() / "wallet.backup").string();
291 
292  // Import key into wallet and call dumpwallet to create backup file.
293  {
294  std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(
295  chain.get(), "", CreateDummyWalletDatabase());
296  {
297  auto spk_man = wallet->GetOrCreateLegacyScriptPubKeyMan();
298  LOCK2(wallet->cs_wallet, spk_man->cs_KeyStore);
299  spk_man->mapKeyMetadata[coinbaseKey.GetPubKey().GetID()]
300  .nCreateTime = KEY_TIME;
301  spk_man->AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey());
302 
303  AddWallet(wallet);
304  wallet->SetLastBlockProcessed(
305  ::ChainActive().Height(),
306  ::ChainActive().Tip()->GetBlockHash());
307  }
308  util::Ref context;
309  JSONRPCRequest request(context);
310  request.params.setArray();
311  request.params.push_back(backup_file);
312  ::dumpwallet().HandleRequest(GetConfig(), request);
313  RemoveWallet(wallet, std::nullopt);
314  }
315 
316  // Call importwallet RPC and verify all blocks with timestamps >= BLOCK_TIME
317  // were scanned, and no prior blocks were scanned.
318  {
319  std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(
320  chain.get(), "", CreateDummyWalletDatabase());
321  LOCK(wallet->cs_wallet);
322  wallet->SetupLegacyScriptPubKeyMan();
323 
324  util::Ref context;
325  JSONRPCRequest request(context);
326  request.params.setArray();
327  request.params.push_back(backup_file);
328  AddWallet(wallet);
329  wallet->SetLastBlockProcessed(::ChainActive().Height(),
330  ::ChainActive().Tip()->GetBlockHash());
331  ::importwallet().HandleRequest(GetConfig(), request);
332  RemoveWallet(wallet, std::nullopt);
333 
334  BOOST_CHECK_EQUAL(wallet->mapWallet.size(), 3U);
335  BOOST_CHECK_EQUAL(m_coinbase_txns.size(), 103U);
336  for (size_t i = 0; i < m_coinbase_txns.size(); ++i) {
337  bool found = wallet->GetWalletTx(m_coinbase_txns[i]->GetId());
338  bool expected = i >= 100;
339  BOOST_CHECK_EQUAL(found, expected);
340  }
341  }
342 }
343 
344 // Check that GetImmatureCredit() returns a newly calculated value instead of
345 // the cached value after a MarkDirty() call.
346 //
347 // This is a regression test written to verify a bugfix for the immature credit
348 // function. Similar tests probably should be written for the other credit and
349 // debit functions.
350 BOOST_FIXTURE_TEST_CASE(coin_mark_dirty_immature_credit, TestChain100Setup) {
351  NodeContext node;
352  auto chain = interfaces::MakeChain(node, Params());
353  CWallet wallet(chain.get(), "", CreateDummyWalletDatabase());
354  auto spk_man = wallet.GetOrCreateLegacyScriptPubKeyMan();
355  CWalletTx wtx(&wallet, m_coinbase_txns.back());
356 
357  LOCK2(wallet.cs_wallet, spk_man->cs_KeyStore);
358  wallet.SetLastBlockProcessed(::ChainActive().Height(),
359  ::ChainActive().Tip()->GetBlockHash());
360 
361  CWalletTx::Confirmation confirm(CWalletTx::Status::CONFIRMED,
362  ::ChainActive().Height(),
363  ::ChainActive().Tip()->GetBlockHash(), 0);
364  wtx.m_confirm = confirm;
365 
366  // Call GetImmatureCredit() once before adding the key to the wallet to
367  // cache the current immature credit amount, which is 0.
369 
370  // Invalidate the cached value, add the key, and make sure a new immature
371  // credit amount is calculated.
372  wtx.MarkDirty();
373  BOOST_CHECK(spk_man->AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey()));
375 }
376 
377 static int64_t AddTx(ChainstateManager &chainman, CWallet &wallet,
378  uint32_t lockTime, int64_t mockTime, int64_t blockTime) {
380  CWalletTx::Confirmation confirm;
381  tx.nLockTime = lockTime;
382  SetMockTime(mockTime);
383  CBlockIndex *block = nullptr;
384  if (blockTime > 0) {
385  LOCK(cs_main);
386  auto inserted = chainman.BlockIndex().emplace(BlockHash(GetRandHash()),
387  new CBlockIndex);
388  assert(inserted.second);
389  const BlockHash &hash = inserted.first->first;
390  block = inserted.first->second;
391  block->nTime = blockTime;
392  block->phashBlock = &hash;
393  confirm = {CWalletTx::Status::CONFIRMED, block->nHeight, hash, 0};
394  }
395 
396  // If transaction is already in map, to avoid inconsistencies,
397  // unconfirmation is needed before confirm again with different block.
398  return wallet
399  .AddToWallet(MakeTransactionRef(tx), confirm,
400  [&](CWalletTx &wtx, bool /* new_tx */) {
401  wtx.setUnconfirmed();
402  return true;
403  })
404  ->nTimeSmart;
405 }
406 
407 // Simple test to verify assignment of CWalletTx::nSmartTime value. Could be
408 // expanded to cover more corner cases of smart time logic.
409 BOOST_AUTO_TEST_CASE(ComputeTimeSmart) {
410  // New transaction should use clock time if lower than block time.
411  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 100, 120), 100);
412 
413  // Test that updating existing transaction does not change smart time.
414  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 200, 220), 100);
415 
416  // New transaction should use clock time if there's no block time.
417  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 2, 300, 0), 300);
418 
419  // New transaction should use block time if lower than clock time.
420  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 3, 420, 400), 400);
421 
422  // New transaction should use latest entry time if higher than
423  // min(block time, clock time).
424  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 4, 500, 390), 400);
425 
426  // If there are future entries, new transaction should use time of the
427  // newest entry that is no more than 300 seconds ahead of the clock time.
428  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 5, 50, 600), 300);
429 
430  // Reset mock time for other tests.
431  SetMockTime(0);
432 }
433 
434 BOOST_AUTO_TEST_CASE(LoadReceiveRequests) {
435  CTxDestination dest = PKHash();
436  LOCK(m_wallet.cs_wallet);
437  WalletBatch batch{m_wallet.GetDatabase()};
438  m_wallet.AddDestData(batch, dest, "misc", "val_misc");
439  m_wallet.AddDestData(batch, dest, "rr0", "val_rr0");
440  m_wallet.AddDestData(batch, dest, "rr1", "val_rr1");
441 
442  auto values = m_wallet.GetDestValues("rr");
443  BOOST_CHECK_EQUAL(values.size(), 2U);
444  BOOST_CHECK_EQUAL(values[0], "val_rr0");
445  BOOST_CHECK_EQUAL(values[1], "val_rr1");
446 }
447 
448 // Test some watch-only LegacyScriptPubKeyMan methods by the procedure of
449 // loading (LoadWatchOnly), checking (HaveWatchOnly), getting (GetWatchPubKey)
450 // and removing (RemoveWatchOnly) a given PubKey, resp. its corresponding P2PK
451 // Script. Results of the the impact on the address -> PubKey map is dependent
452 // on whether the PubKey is a point on the curve
454  const CPubKey &add_pubkey) {
455  CScript p2pk = GetScriptForRawPubKey(add_pubkey);
456  CKeyID add_address = add_pubkey.GetID();
457  CPubKey found_pubkey;
458  LOCK(spk_man->cs_KeyStore);
459 
460  // all Scripts (i.e. also all PubKeys) are added to the general watch-only
461  // set
462  BOOST_CHECK(!spk_man->HaveWatchOnly(p2pk));
463  spk_man->LoadWatchOnly(p2pk);
464  BOOST_CHECK(spk_man->HaveWatchOnly(p2pk));
465 
466  // only PubKeys on the curve shall be added to the watch-only address ->
467  // PubKey map
468  bool is_pubkey_fully_valid = add_pubkey.IsFullyValid();
469  if (is_pubkey_fully_valid) {
470  BOOST_CHECK(spk_man->GetWatchPubKey(add_address, found_pubkey));
471  BOOST_CHECK(found_pubkey == add_pubkey);
472  } else {
473  BOOST_CHECK(!spk_man->GetWatchPubKey(add_address, found_pubkey));
474  // passed key is unchanged
475  BOOST_CHECK(found_pubkey == CPubKey());
476  }
477 
478  spk_man->RemoveWatchOnly(p2pk);
479  BOOST_CHECK(!spk_man->HaveWatchOnly(p2pk));
480 
481  if (is_pubkey_fully_valid) {
482  BOOST_CHECK(!spk_man->GetWatchPubKey(add_address, found_pubkey));
483  // passed key is unchanged
484  BOOST_CHECK(found_pubkey == add_pubkey);
485  }
486 }
487 
488 // Cryptographically invalidate a PubKey whilst keeping length and first byte
489 static void PollutePubKey(CPubKey &pubkey) {
490  std::vector<uint8_t> pubkey_raw(pubkey.begin(), pubkey.end());
491  std::fill(pubkey_raw.begin() + 1, pubkey_raw.end(), 0);
492  pubkey = CPubKey(pubkey_raw);
493  assert(!pubkey.IsFullyValid());
494  assert(pubkey.IsValid());
495 }
496 
497 // Test watch-only logic for PubKeys
498 BOOST_AUTO_TEST_CASE(WatchOnlyPubKeys) {
499  CKey key;
500  CPubKey pubkey;
501  LegacyScriptPubKeyMan *spk_man =
502  m_wallet.GetOrCreateLegacyScriptPubKeyMan();
503 
504  BOOST_CHECK(!spk_man->HaveWatchOnly());
505 
506  // uncompressed valid PubKey
507  key.MakeNewKey(false);
508  pubkey = key.GetPubKey();
509  assert(!pubkey.IsCompressed());
510  TestWatchOnlyPubKey(spk_man, pubkey);
511 
512  // uncompressed cryptographically invalid PubKey
513  PollutePubKey(pubkey);
514  TestWatchOnlyPubKey(spk_man, pubkey);
515 
516  // compressed valid PubKey
517  key.MakeNewKey(true);
518  pubkey = key.GetPubKey();
519  assert(pubkey.IsCompressed());
520  TestWatchOnlyPubKey(spk_man, pubkey);
521 
522  // compressed cryptographically invalid PubKey
523  PollutePubKey(pubkey);
524  TestWatchOnlyPubKey(spk_man, pubkey);
525 
526  // invalid empty PubKey
527  pubkey = CPubKey();
528  TestWatchOnlyPubKey(spk_man, pubkey);
529 }
530 
531 class ListCoinsTestingSetup : public TestChain100Setup {
532 public:
534  CreateAndProcessBlock({},
535  GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
536  wallet = std::make_unique<CWallet>(m_chain.get(), "",
538  {
539  LOCK2(wallet->cs_wallet, ::cs_main);
540  wallet->SetLastBlockProcessed(
541  ::ChainActive().Height(),
542  ::ChainActive().Tip()->GetBlockHash());
543  }
544  bool firstRun;
545  wallet->LoadWallet(firstRun);
546  AddKey(*wallet, coinbaseKey);
547  WalletRescanReserver reserver(*wallet);
548  reserver.reserve();
549  CWallet::ScanResult result = wallet->ScanForWalletTransactions(
550  ::ChainActive().Genesis()->GetBlockHash(), 0 /* start_height */,
551  {} /* max_height */, reserver, false /* update */);
554  ::ChainActive().Tip()->GetBlockHash());
556  ::ChainActive().Height());
558  }
559 
561 
562  CWalletTx &AddTx(CRecipient recipient) {
563  CTransactionRef tx;
564  Amount fee;
565  int changePos = -1;
567  CCoinControl dummy;
568  {
569  BOOST_CHECK(wallet->CreateTransaction({recipient}, tx, fee,
570  changePos, error, dummy));
571  }
572  wallet->CommitTransaction(tx, {}, {});
573  CMutableTransaction blocktx;
574  {
575  LOCK(wallet->cs_wallet);
576  blocktx =
577  CMutableTransaction(*wallet->mapWallet.at(tx->GetId()).tx);
578  }
579  CreateAndProcessBlock({CMutableTransaction(blocktx)},
580  GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
581 
582  LOCK(wallet->cs_wallet);
583  wallet->SetLastBlockProcessed(wallet->GetLastBlockHeight() + 1,
584  ::ChainActive().Tip()->GetBlockHash());
585  auto it = wallet->mapWallet.find(tx->GetId());
586  BOOST_CHECK(it != wallet->mapWallet.end());
587  CWalletTx::Confirmation confirm(
588  CWalletTx::Status::CONFIRMED, ::ChainActive().Height(),
589  ::ChainActive().Tip()->GetBlockHash(), 1);
590  it->second.m_confirm = confirm;
591  return it->second;
592  }
593 
594  std::unique_ptr<interfaces::Chain> m_chain =
596  std::unique_ptr<CWallet> wallet;
597 };
598 
600  std::string coinbaseAddress = coinbaseKey.GetPubKey().GetID().ToString();
601 
602  // Confirm ListCoins initially returns 1 coin grouped under coinbaseKey
603  // address.
604  std::map<CTxDestination, std::vector<COutput>> list;
605  {
606  LOCK(wallet->cs_wallet);
607  list = wallet->ListCoins();
608  }
609  BOOST_CHECK_EQUAL(list.size(), 1U);
610  BOOST_CHECK_EQUAL(boost::get<PKHash>(list.begin()->first).ToString(),
611  coinbaseAddress);
612  BOOST_CHECK_EQUAL(list.begin()->second.size(), 1U);
613 
614  // Check initial balance from one mature coinbase transaction.
615  BOOST_CHECK_EQUAL(50 * COIN, wallet->GetAvailableBalance());
616 
617  // Add a transaction creating a change address, and confirm ListCoins still
618  // returns the coin associated with the change address underneath the
619  // coinbaseKey pubkey, even though the change address has a different
620  // pubkey.
622  false /* subtract fee */});
623  {
624  LOCK(wallet->cs_wallet);
625  list = wallet->ListCoins();
626  }
627  BOOST_CHECK_EQUAL(list.size(), 1U);
628  BOOST_CHECK_EQUAL(boost::get<PKHash>(list.begin()->first).ToString(),
629  coinbaseAddress);
630  BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
631 
632  // Lock both coins. Confirm number of available coins drops to 0.
633  {
634  LOCK(wallet->cs_wallet);
635  std::vector<COutput> available;
636  wallet->AvailableCoins(available);
637  BOOST_CHECK_EQUAL(available.size(), 2U);
638  }
639  for (const auto &group : list) {
640  for (const auto &coin : group.second) {
641  LOCK(wallet->cs_wallet);
642  wallet->LockCoin(COutPoint(coin.tx->GetId(), coin.i));
643  }
644  }
645  {
646  LOCK(wallet->cs_wallet);
647  std::vector<COutput> available;
648  wallet->AvailableCoins(available);
649  BOOST_CHECK_EQUAL(available.size(), 0U);
650  }
651  // Confirm ListCoins still returns same result as before, despite coins
652  // being locked.
653  {
654  LOCK(wallet->cs_wallet);
655  list = wallet->ListCoins();
656  }
657  BOOST_CHECK_EQUAL(list.size(), 1U);
658  BOOST_CHECK_EQUAL(boost::get<PKHash>(list.begin()->first).ToString(),
659  coinbaseAddress);
660  BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
661 }
662 
663 BOOST_FIXTURE_TEST_CASE(wallet_disableprivkeys, TestChain100Setup) {
664  NodeContext node;
665  auto chain = interfaces::MakeChain(node, Params());
666  std::shared_ptr<CWallet> wallet =
667  std::make_shared<CWallet>(chain.get(), "", CreateDummyWalletDatabase());
668  wallet->SetupLegacyScriptPubKeyMan();
669  wallet->SetMinVersion(FEATURE_LATEST);
670  wallet->SetWalletFlag(WALLET_FLAG_DISABLE_PRIVATE_KEYS);
671  BOOST_CHECK(!wallet->TopUpKeyPool(1000));
672  CTxDestination dest;
673  std::string error;
674  BOOST_CHECK(
675  !wallet->GetNewDestination(OutputType::LEGACY, "", dest, error));
676 }
677 
678 // Explicit calculation which is used to test the wallet constant
679 static size_t CalculateP2PKHInputSize(bool use_max_sig) {
680  // Generate ephemeral valid pubkey
681  CKey key;
682  key.MakeNewKey(true);
683  CPubKey pubkey = key.GetPubKey();
684 
685  // Generate pubkey hash
686  PKHash key_hash(pubkey);
687 
688  // Create script to enter into keystore. Key hash can't be 0...
689  CScript script = GetScriptForDestination(key_hash);
690 
691  // Add script to key store and key to watchonly
692  FillableSigningProvider keystore;
693  keystore.AddKeyPubKey(key, pubkey);
694 
695  // Fill in dummy signatures for fee calculation.
696  SignatureData sig_data;
697  if (!ProduceSignature(keystore,
698  use_max_sig ? DUMMY_MAXIMUM_SIGNATURE_CREATOR
700  script, sig_data)) {
701  // We're hand-feeding it correct arguments; shouldn't happen
702  assert(false);
703  }
704 
705  CTxIn tx_in;
706  UpdateInput(tx_in, sig_data);
707  return (size_t)GetVirtualTransactionInputSize(tx_in);
708 }
709 
710 BOOST_FIXTURE_TEST_CASE(dummy_input_size_test, TestChain100Setup) {
713 }
714 
715 bool malformed_descriptor(std::ios_base::failure e) {
716  std::string s(e.what());
717  return s.find("Missing checksum") != std::string::npos;
718 }
719 
720 BOOST_FIXTURE_TEST_CASE(wallet_descriptor_test, BasicTestingSetup) {
721  std::vector<uint8_t> malformed_record;
722  CVectorWriter vw(0, 0, malformed_record, 0);
723  vw << std::string("notadescriptor");
724  vw << (uint64_t)0;
725  vw << (int32_t)0;
726  vw << (int32_t)0;
727  vw << (int32_t)1;
728 
729  VectorReader vr(0, 0, malformed_record, 0);
730  WalletDescriptor w_desc;
731  BOOST_CHECK_EXCEPTION(vr >> w_desc, std::ios_base::failure,
733 }
734 
753 BOOST_FIXTURE_TEST_CASE(CreateWalletFromFile, TestChain100Setup) {
754  // Create new wallet with known key and unload it.
755  auto chain = interfaces::MakeChain(m_node, Params());
756  auto wallet = TestLoadWallet(*chain);
757  CKey key;
758  key.MakeNewKey(true);
759  AddKey(*wallet, key);
760  TestUnloadWallet(std::move(wallet));
761 
762  // Add log hook to detect AddToWallet events from rescans, blockConnected,
763  // and transactionAddedToMempool notifications
764  int addtx_count = 0;
765  DebugLogHelper addtx_counter("[default wallet] AddToWallet",
766  [&](const std::string *s) {
767  if (s) {
768  ++addtx_count;
769  }
770  return false;
771  });
772 
773  bool rescan_completed = false;
774  DebugLogHelper rescan_check("[default wallet] Rescan completed",
775  [&](const std::string *s) {
776  if (s) {
777  rescan_completed = true;
778  }
779  return false;
780  });
781 
782  // Block the queue to prevent the wallet receiving blockConnected and
783  // transactionAddedToMempool notifications, and create block and mempool
784  // transactions paying to the wallet
785  std::promise<void> promise;
787  [&promise] { promise.get_future().wait(); });
788  std::string error;
789  m_coinbase_txns.push_back(
790  CreateAndProcessBlock({},
791  GetScriptForRawPubKey(coinbaseKey.GetPubKey()))
792  .vtx[0]);
793  auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey,
795  m_coinbase_txns.push_back(
796  CreateAndProcessBlock({block_tx},
797  GetScriptForRawPubKey(coinbaseKey.GetPubKey()))
798  .vtx[0]);
799  auto mempool_tx = TestSimpleSpend(*m_coinbase_txns[1], 0, coinbaseKey,
801  BOOST_CHECK(
802  chain->broadcastTransaction(GetConfig(), MakeTransactionRef(mempool_tx),
804 
805  // Reload wallet and make sure new transactions are detected despite events
806  // being blocked
807  wallet = TestLoadWallet(*chain);
808  BOOST_CHECK(rescan_completed);
809  BOOST_CHECK_EQUAL(addtx_count, 2);
810  {
811  LOCK(wallet->cs_wallet);
812  BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_tx.GetId()), 1U);
813  BOOST_CHECK_EQUAL(wallet->mapWallet.count(mempool_tx.GetId()), 1U);
814  }
815 
816  // Unblock notification queue and make sure stale blockConnected and
817  // transactionAddedToMempool events are processed
818  promise.set_value();
820  BOOST_CHECK_EQUAL(addtx_count, 4);
821 
822  TestUnloadWallet(std::move(wallet));
823 
824  // Load wallet again, this time creating new block and mempool transactions
825  // paying to the wallet as the wallet finishes loading and syncing the
826  // queue so the events have to be handled immediately. Releasing the wallet
827  // lock during the sync is a little artificial but is needed to avoid a
828  // deadlock during the sync and simulates a new block notification happening
829  // as soon as possible.
830  addtx_count = 0;
831  auto handler = HandleLoadWallet(
832  [&](std::unique_ptr<interfaces::Wallet> wallet_param)
833  EXCLUSIVE_LOCKS_REQUIRED(wallet_param->wallet()->cs_wallet) {
834  BOOST_CHECK(rescan_completed);
835  m_coinbase_txns.push_back(
836  CreateAndProcessBlock(
837  {}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()))
838  .vtx[0]);
839  block_tx =
840  TestSimpleSpend(*m_coinbase_txns[2], 0, coinbaseKey,
842  m_coinbase_txns.push_back(
843  CreateAndProcessBlock(
844  {block_tx},
845  GetScriptForRawPubKey(coinbaseKey.GetPubKey()))
846  .vtx[0]);
847  mempool_tx =
848  TestSimpleSpend(*m_coinbase_txns[3], 0, coinbaseKey,
850  BOOST_CHECK(chain->broadcastTransaction(
851  GetConfig(), MakeTransactionRef(mempool_tx),
853  LEAVE_CRITICAL_SECTION(wallet_param->wallet()->cs_wallet);
855  ENTER_CRITICAL_SECTION(wallet_param->wallet()->cs_wallet);
856  });
857  wallet = TestLoadWallet(*chain);
858  BOOST_CHECK_EQUAL(addtx_count, 4);
859  {
860  LOCK(wallet->cs_wallet);
861  BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_tx.GetId()), 1U);
862  BOOST_CHECK_EQUAL(wallet->mapWallet.count(mempool_tx.GetId()), 1U);
863  }
864 
865  TestUnloadWallet(std::move(wallet));
866 }
867 
868 BOOST_FIXTURE_TEST_CASE(ZapSelectTx, TestChain100Setup) {
869  auto chain = interfaces::MakeChain(m_node, Params());
870  auto wallet = TestLoadWallet(*chain);
871  CKey key;
872  key.MakeNewKey(true);
873  AddKey(*wallet, key);
874 
875  std::string error;
876  m_coinbase_txns.push_back(
877  CreateAndProcessBlock({},
878  GetScriptForRawPubKey(coinbaseKey.GetPubKey()))
879  .vtx[0]);
880  auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey,
882  CreateAndProcessBlock({block_tx},
883  GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
884 
886 
887  {
888  auto block_id = block_tx.GetId();
889  auto prev_id = m_coinbase_txns[0]->GetId();
890 
891  LOCK(wallet->cs_wallet);
892  BOOST_CHECK(wallet->HasWalletSpend(prev_id));
893  BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_id), 1u);
894 
895  std::vector<TxId> vIdIn{block_id}, vIdOut;
896  BOOST_CHECK_EQUAL(wallet->ZapSelectTx(vIdIn, vIdOut),
898 
899  BOOST_CHECK(!wallet->HasWalletSpend(prev_id));
900  BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_id), 0u);
901  }
902 
903  TestUnloadWallet(std::move(wallet));
904 }
905 
HandleLoadWallet
std::unique_ptr< interfaces::Handler > HandleLoadWallet(LoadWalletFn load_wallet)
Definition: wallet.cpp:163
DatabaseOptions
Definition: db.h:221
CTxIn
An input of a transaction.
Definition: transaction.h:61
FlatFilePos::nFile
int nFile
Definition: flatfile.h:15
interfaces
Definition: dummywallet.cpp:12
LOCK2
#define LOCK2(cs1, cs2)
Definition: sync.h:244
policy.h
ref.h
m_wallet
std::shared_ptr< CWallet > m_wallet
Definition: wallet.cpp:462
ChainstateManager::BlockIndex
BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:1188
GetDataDir
const fs::path & GetDataDir(bool fNetSpecific)
Definition: system.cpp:779
TestLoadWallet
static std::shared_ptr< CWallet > TestLoadWallet(interfaces::Chain &chain)
Definition: wallet_tests.cpp:34
ListCoinsTestingSetup::AddTx
CWalletTx & AddTx(CRecipient recipient)
Definition: wallet_tests.cpp:562
DUMMY_P2PKH_INPUT_SIZE
static constexpr size_t DUMMY_P2PKH_INPUT_SIZE
Pre-calculated constants for input size estimation.
Definition: wallet.h:115
LegacyScriptPubKeyMan::GetWatchPubKey
bool GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
Fetches a pubkey from mapWatchKeys if it exists there.
Definition: scriptpubkeyman.cpp:952
MakeTransactionRef
static CTransactionRef MakeTransactionRef()
Definition: transaction.h:320
CreateDummyWalletDatabase
std::unique_ptr< WalletDatabase > CreateDummyWalletDatabase()
Return object for accessing dummy database with no read/write capabilities.
Definition: walletdb.cpp:1164
CBlockIndex::nTime
uint32_t nTime
Definition: blockindex.h:81
wallet.h
CKey::MakeNewKey
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
Definition: key.cpp:183
AddKey
static void AddKey(CWallet &wallet, const CKey &key)
Definition: wallet_tests.cpp:69
ChainActive
CChain & ChainActive()
Please prefer the identical ChainstateManager::ActiveChain.
Definition: validation.cpp:86
UniValue::clear
void clear()
Definition: univalue.cpp:15
CVectorWriter
Minimal stream for overwriting and/or appending to an existing byte vector.
Definition: streams.h:63
DUMMY_SIGNATURE_CREATOR
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
Definition: sign.cpp:418
CPubKey::end
const uint8_t * end() const
Definition: pubkey.h:101
OutputType::LEGACY
@ LEGACY
CWallet::GetBalance
Balance GetBalance(int min_depth=0, bool avoid_reuse=true) const
Definition: wallet.cpp:2406
FillableSigningProvider
Fillable signing provider that keeps keys in an address->secret map.
Definition: signingprovider.h:76
GetScriptForDestination
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:243
GetVirtualTransactionInputSize
int64_t GetVirtualTransactionInputSize(const CTxIn &txin, int64_t nSigOpCount, unsigned int bytes_per_sigop)
Definition: policy.cpp:173
AddTx
static int64_t AddTx(ChainstateManager &chainman, CWallet &wallet, uint32_t lockTime, int64_t mockTime, int64_t blockTime)
Definition: wallet_tests.cpp:377
bilingual_str
Bilingual messages:
Definition: translation.h:17
RemoveWallet
bool RemoveWallet(const std::shared_ptr< CWallet > &wallet, std::optional< bool > load_on_start, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:117
CWallet::ScanResult::last_scanned_height
std::optional< int > last_scanned_height
Definition: wallet.h:1077
CCoinControl
Coin Control Features.
Definition: coincontrol.h:21
CBlockIndex::nHeight
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: blockindex.h:36
CWalletTx::setUnconfirmed
void setUnconfirmed()
Definition: wallet.h:581
DEFAULT_TRANSACTION_MAXFEE
constexpr Amount DEFAULT_TRANSACTION_MAXFEE
-maxtxfee default
Definition: wallet.h:108
MakeWalletDatabase
std::unique_ptr< WalletDatabase > MakeWalletDatabase(const std::string &name, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error_string)
Definition: wallet.cpp:4221
WITH_LOCK
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:272
TestUnloadWallet
static void TestUnloadWallet(std::shared_ptr< CWallet > &&wallet)
Definition: wallet_tests.cpp:46
ListCoinsTestingSetup::ListCoinsTestingSetup
ListCoinsTestingSetup()
Definition: wallet_tests.cpp:533
CWalletTx::m_confirm
Confirmation m_confirm
Definition: wallet.h:413
WalletRescanReserver::reserve
bool reserve()
Definition: wallet.h:1596
CWallet::AddToWallet
CWalletTx * AddToWallet(CTransactionRef tx, const CWalletTx::Confirmation &confirm, const UpdateWalletTxFn &update_wtx=nullptr, bool fFlushOnClose=true)
Definition: wallet.cpp:953
CKeyID
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:22
LegacyScriptPubKeyMan
Definition: scriptpubkeyman.h:320
chainparams.h
chain.h
BOOST_FIXTURE_TEST_SUITE
#define BOOST_FIXTURE_TEST_SUITE(a, b)
Definition: object.cpp:14
CChain::Tip
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:168
VectorReader
Minimal stream for reading from an existing vector by reference.
Definition: streams.h:129
CWallet::ScanForWalletTransactions
ScanResult ScanForWalletTransactions(const BlockHash &start_block, int start_height, std::optional< int > max_height, const WalletRescanReserver &reserver, bool fUpdate)
Scan the block chain (starting in start_block) for transactions from or to us.
Definition: wallet.cpp:1919
context.h
Assert
#define Assert(val)
Identity function.
Definition: check.h:56
UniValue::pushKV
bool pushKV(const std::string &key, const UniValue &val)
Definition: univalue.cpp:133
CBlockIndex::GetBlockHash
BlockHash GetBlockHash() const
Definition: blockindex.h:133
COIN
static constexpr Amount COIN
Definition: amount.h:154
UniValue
Definition: univalue.h:23
FillableSigningProvider::AddKey
virtual bool AddKey(const CKey &key)
Definition: signingprovider.h:110
CTransaction
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:194
CBlockIndex::GetBlockPos
FlatFilePos GetBlockPos() const
Definition: blockindex.h:102
Amount::zero
static constexpr Amount zero()
Definition: amount.h:42
GetBlockFileInfo
CBlockFileInfo * GetBlockFileInfo(size_t n)
Get block file info entry for one block file.
Definition: validation.cpp:5772
CBlockIndex::GetBlockTimeMax
int64_t GetBlockTimeMax() const
Definition: blockindex.h:162
CPubKey::begin
const uint8_t * begin() const
Definition: pubkey.h:100
SyncWithValidationInterfaceQueue
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
Definition: validationinterface.cpp:162
util::Ref
Type-safe dynamic reference.
Definition: ref.h:21
ENTER_CRITICAL_SECTION
#define ENTER_CRITICAL_SECTION(cs)
Definition: sync.h:252
MAX_BLOCKFILE_SIZE
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
Definition: validation.h:79
ListCoinsTestingSetup
Definition: wallet_tests.cpp:531
CalculateP2PKHInputSize
static size_t CalculateP2PKHInputSize(bool use_max_sig)
Definition: wallet_tests.cpp:679
DUMMY_MAXIMUM_SIGNATURE_CREATOR
const BaseSignatureCreator & DUMMY_MAXIMUM_SIGNATURE_CREATOR
A signature creator that just produces 72-byte empty signatures.
Definition: sign.cpp:420
BOOST_AUTO_TEST_CASE
BOOST_AUTO_TEST_CASE(ComputeTimeSmart)
Definition: wallet_tests.cpp:409
malformed_descriptor
bool malformed_descriptor(std::ios_base::failure e)
Definition: wallet_tests.cpp:715
SignatureData
Definition: sign.h:66
CTransaction::GetId
const TxId GetId() const
Definition: transaction.h:244
GetScriptForRawPubKey
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
Definition: standard.cpp:247
cs_main
RecursiveMutex cs_main
Global state.
Definition: validation.cpp:103
response
Response response
Definition: processor.cpp:321
CTransaction::vout
const std::vector< CTxOut > vout
Definition: transaction.h:211
SetMockTime
void SetMockTime(int64_t nMockTimeIn)
For testing.
Definition: time.cpp:50
PollutePubKey
static void PollutePubKey(CPubKey &pubkey)
Definition: wallet_tests.cpp:489
univalue.h
LegacyScriptPubKeyMan::HaveWatchOnly
bool HaveWatchOnly(const CScript &dest) const
Returns whether the watch-only script is in the wallet.
Definition: scriptpubkeyman.cpp:799
GetRandHash
uint256 GetRandHash() noexcept
Definition: random.cpp:658
CWallet::Create
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:4250
ListCoinsTestingSetup::~ListCoinsTestingSetup
~ListCoinsTestingSetup()
Definition: wallet_tests.cpp:560
RPCHelpMan::HandleRequest
UniValue HandleRequest(const Config &config, const JSONRPCRequest &request)
Definition: util.h:346
importwallet
RPCHelpMan importwallet()
Definition: rpcdump.cpp:631
WalletRescanReserver
RAII object to check and reserve a wallet rescan.
Definition: wallet.h:1587
SigHashType
Signature hash type wrapper class.
Definition: sighashtype.h:37
importmulti
RPCHelpMan importmulti()
Definition: rpcdump.cpp:1657
CWallet::ScanResult::status
enum CWallet::ScanResult::@20 status
CWallet::ScanResult
Definition: wallet.h:1070
CKey::GetPubKey
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:210
WalletTestingSetup
Testing setup and teardown for wallet.
Definition: wallet_test_fixture.h:21
CWalletTx::Confirmation
Confirmation includes tx status and a triplet of {block height/block hash/tx index in block} at which...
Definition: wallet.h:403
Amount
Definition: amount.h:19
CScript
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:430
handler
bool(* handler)(Config &config, const util::Ref &context, HTTPRequest *req, const std::string &strReq)
Definition: rest.cpp:773
CWallet::SetLastBlockProcessed
void SetLastBlockProcessed(int block_height, BlockHash block_hash) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Set last block processed height, currently only use in unit test.
Definition: wallet.h:1531
DBErrors::LOAD_OK
@ LOAD_OK
wallet_test_fixture.h
dumpwallet
RPCHelpMan dumpwallet()
Definition: rpcdump.cpp:898
CWallet::ScanResult::SUCCESS
@ SUCCESS
Definition: wallet.h:1071
BlockHash
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
JSONRPCRequest::params
UniValue params
Definition: request.h:37
ChainstateManager
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1099
WALLET_FLAG_DISABLE_PRIVATE_KEYS
@ WALLET_FLAG_DISABLE_PRIVATE_KEYS
Definition: walletutil.h:55
CPubKey::IsCompressed
bool IsCompressed() const
Check whether this is a compressed public key.
Definition: pubkey.h:159
UnloadWallet
void UnloadWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly unload and delete the wallet.
Definition: wallet.cpp:198
ListCoinsTestingSetup::m_chain
std::unique_ptr< interfaces::Chain > m_chain
Definition: wallet_tests.cpp:594
ProduceSignature
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:197
PKHash
Definition: standard.h:106
m_node
NodeContext & m_node
Definition: chain.cpp:485
strprintf
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1201
CWallet::ScanResult::last_scanned_block
BlockHash last_scanned_block
Hash and height of most recent block that was successfully scanned.
Definition: wallet.h:1076
CPubKey
An encapsulated public key.
Definition: pubkey.h:31
FEATURE_LATEST
@ FEATURE_LATEST
Definition: walletutil.h:36
base_blob::IsNull
bool IsNull() const
Definition: uint256.h:30
UnlinkPrunedFiles
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune)
Actually unlink the specified files.
Definition: validation.cpp:4537
CKey
An encapsulated secp256k1 private key.
Definition: key.h:28
CMutableTransaction::vout
std::vector< CTxOut > vout
Definition: transaction.h:281
translation.h
EXCLUSIVE_LOCKS_REQUIRED
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:56
LOCK
#define LOCK(cs)
Definition: sync.h:241
CreateMockWalletDatabase
std::unique_ptr< WalletDatabase > CreateMockWalletDatabase()
Return object for accessing temporary in-memory database.
Definition: walletdb.cpp:1169
CWallet
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:678
AddWallet
bool AddWallet(const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:104
CWalletTx
A transaction with a bunch of additional info that only the owner cares about.
Definition: wallet.h:280
TestWatchOnlyPubKey
static void TestWatchOnlyPubKey(LegacyScriptPubKeyMan *spk_man, const CPubKey &add_pubkey)
Definition: wallet_tests.cpp:453
LegacyScriptPubKeyMan::LoadWatchOnly
bool LoadWatchOnly(const CScript &dest)
Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
Definition: scriptpubkeyman.cpp:832
ListCoinsTestingSetup::wallet
std::unique_ptr< CWallet > wallet
Definition: wallet_tests.cpp:596
FillableSigningProvider::AddKeyPubKey
virtual bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey)
Definition: signingprovider.cpp:93
TestSimpleSpend
static CMutableTransaction TestSimpleSpend(const CTransaction &from, uint32_t index, const CKey &key, const CScript &pubkey)
Definition: wallet_tests.cpp:52
UniValue::push_back
bool push_back(const UniValue &val)
Definition: univalue.cpp:108
LegacyScriptPubKeyMan::RemoveWatchOnly
bool RemoveWatchOnly(const CScript &dest)
Remove a watch only script from the keystore.
Definition: scriptpubkeyman.cpp:815
CMutableTransaction::nLockTime
uint32_t nLockTime
Definition: transaction.h:283
Params
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:508
CTransactionRef
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:319
DatabaseStatus
DatabaseStatus
Definition: db.h:229
CPubKey::IsFullyValid
bool IsFullyValid() const
fully validate whether this is a valid public key (more expensive than IsValid())
Definition: pubkey.cpp:257
CWallet::ScanResult::last_failed_block
BlockHash last_failed_block
Hash of the most recent block that could not be scanned due to read errors or pruning.
Definition: wallet.h:1083
CWallet::cs_wallet
RecursiveMutex cs_wallet
Definition: wallet.h:819
rpcdump.h
interfaces::MakeChain
std::unique_ptr< Chain > MakeChain(NodeContext &node, const CChainParams &params)
Return implementation of Chain interface.
Definition: chain.cpp:491
config.h
BOOST_FIXTURE_TEST_CASE
BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions, TestChain100Setup)
Definition: wallet_tests.cpp:75
CWalletTx::MarkDirty
void MarkDirty()
make sure balances are recalculated
Definition: wallet.h:485
JSONRPCRequest
Definition: request.h:33
WalletDescriptor
Descriptor with some wallet metadata.
Definition: walletutil.h:80
LEAVE_CRITICAL_SECTION
#define LEAVE_CRITICAL_SECTION(cs)
Definition: sync.h:258
UpdateInput
void UpdateInput(CTxIn &input, const SignatureData &data)
Definition: sign.cpp:330
COutPoint
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:22
CPubKey::IsValid
bool IsValid() const
Definition: pubkey.h:152
SignTransaction
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.
Definition: rawtransaction_util.cpp:262
FillableSigningProvider::cs_KeyStore
RecursiveMutex cs_KeyStore
Definition: signingprovider.h:107
error
bool error(const char *fmt, const Args &... args)
Definition: system.h:48
NodeContext
NodeContext struct containing references to chain state and connection state.
Definition: context.h:36
coincontrol.h
server.h
CBlockIndex
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: blockindex.h:23
CBlockIndex::phashBlock
const BlockHash * phashBlock
pointer to the hash of the block, if any.
Definition: blockindex.h:27
CallFunctionInValidationInterfaceQueue
void CallFunctionInValidationInterfaceQueue(std::function< void()> func)
Pushes a function to callback onto the notification queue, guaranteeing any callbacks generated prior...
Definition: validationinterface.cpp:158
HexStr
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: strencodings.cpp:656
CRecipient
Definition: wallet.h:220
WalletBatch
Access to the wallet database.
Definition: walletdb.h:176
CBlockFileInfo::nSize
unsigned int nSize
number of used bytes of block file
Definition: blockfileinfo.h:18
UniValue::setObject
bool setObject()
Definition: univalue.cpp:101
GetConfig
const Config & GetConfig()
Definition: config.cpp:34
CMutableTransaction::vin
std::vector< CTxIn > vin
Definition: transaction.h:280
CWallet::ScanResult::FAILURE
@ FAILURE
Definition: wallet.h:1071
CTxDestination
boost::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:132
CWallet::GetOrCreateLegacyScriptPubKeyMan
LegacyScriptPubKeyMan * GetOrCreateLegacyScriptPubKeyMan()
Definition: wallet.cpp:4886
BOOST_CHECK
#define BOOST_CHECK(expr)
Definition: object.cpp:17
DatabaseOptions::create_flags
uint64_t create_flags
Definition: db.h:224
CWalletTx::GetImmatureCredit
Amount GetImmatureCredit(bool fUseCache=true) const
Definition: wallet.cpp:2183
BOOST_AUTO_TEST_SUITE_END
#define BOOST_AUTO_TEST_SUITE_END()
Definition: object.cpp:16
BOOST_CHECK_EQUAL
#define BOOST_CHECK_EQUAL(v1, v2)
Definition: object.cpp:18
CPubKey::GetID
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:140
UniValue::setArray
bool setArray()
Definition: univalue.cpp:94
CMutableTransaction
A mutable version of CTransaction.
Definition: transaction.h:278
TIMESTAMP_WINDOW
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
CWallet::Balance::m_mine_immature
Amount m_mine_immature
Immature coinbases in the main chain.
Definition: wallet.h:1101
NodeContext::chainman
ChainstateManager * chainman
Definition: context.h:41