Bitcoin ABC  0.22.12
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/setup_common.h>
21 
22 #include <boost/test/unit_test.hpp>
23 
24 #include <univalue.h>
25 
26 #include <cstdint>
27 #include <memory>
28 #include <vector>
29 
31 
32 static void AddKey(CWallet &wallet, const CKey &key) {
33  auto spk_man = wallet.GetOrCreateLegacyScriptPubKeyMan();
34  LOCK2(wallet.cs_wallet, spk_man->cs_KeyStore);
35  spk_man->AddKeyPubKey(key, key.GetPubKey());
36 }
37 
38 BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions, TestChain100Setup) {
39  // Cap last block file size, and mine new block in a new block file.
40  CBlockIndex *oldTip = ::ChainActive().Tip();
42  CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
43  CBlockIndex *newTip = ::ChainActive().Tip();
44 
45  NodeContext node;
46  auto chain = interfaces::MakeChain(node, Params());
47 
48  // Verify ScanForWalletTransactions fails to read an unknown start block.
49  {
50  CWallet wallet(chain.get(), WalletLocation(),
52  {
53  LOCK(wallet.cs_wallet);
54  wallet.SetLastBlockProcessed(::ChainActive().Height(),
55  ::ChainActive().Tip()->GetBlockHash());
56  }
57  AddKey(wallet, coinbaseKey);
58  WalletRescanReserver reserver(wallet);
59  reserver.reserve();
60  CWallet::ScanResult result = wallet.ScanForWalletTransactions(
61  BlockHash() /* start_block */, 0 /* start_height */,
62  {} /* max_height */, reserver, false /* update */);
67  BOOST_CHECK_EQUAL(wallet.GetBalance().m_mine_immature, Amount::zero());
68  }
69 
70  // Verify ScanForWalletTransactions picks up transactions in both the old
71  // and new block files.
72  {
73  CWallet wallet(chain.get(), WalletLocation(),
75  {
76  LOCK(wallet.cs_wallet);
77  wallet.SetLastBlockProcessed(::ChainActive().Height(),
78  ::ChainActive().Tip()->GetBlockHash());
79  }
80  AddKey(wallet, coinbaseKey);
81  WalletRescanReserver reserver(wallet);
82  reserver.reserve();
83  CWallet::ScanResult result = wallet.ScanForWalletTransactions(
84  oldTip->GetBlockHash(), oldTip->nHeight, {} /* max_height */,
85  reserver, false /* update */);
90  BOOST_CHECK_EQUAL(wallet.GetBalance().m_mine_immature, 100 * COIN);
91  }
92 
93  // Prune the older block file.
94  {
95  LOCK(cs_main);
96  Assert(m_node.chainman)->PruneOneBlockFile(oldTip->GetBlockPos().nFile);
97  }
98  UnlinkPrunedFiles({oldTip->GetBlockPos().nFile});
99 
100  // Verify ScanForWalletTransactions only picks transactions in the new block
101  // file.
102  {
103  CWallet wallet(chain.get(), WalletLocation(),
105  {
106  LOCK(wallet.cs_wallet);
107  wallet.SetLastBlockProcessed(::ChainActive().Height(),
108  ::ChainActive().Tip()->GetBlockHash());
109  }
110  AddKey(wallet, coinbaseKey);
111  WalletRescanReserver reserver(wallet);
112  reserver.reserve();
113  CWallet::ScanResult result = wallet.ScanForWalletTransactions(
114  oldTip->GetBlockHash(), oldTip->nHeight, {} /* max_height */,
115  reserver, false /* update */);
120  BOOST_CHECK_EQUAL(wallet.GetBalance().m_mine_immature, 50 * COIN);
121  }
122 
123  // Prune the remaining block file.
124  {
125  LOCK(cs_main);
126  Assert(m_node.chainman)->PruneOneBlockFile(newTip->GetBlockPos().nFile);
127  }
128  UnlinkPrunedFiles({newTip->GetBlockPos().nFile});
129 
130  // Verify ScanForWalletTransactions scans no blocks.
131  {
132  CWallet wallet(chain.get(), WalletLocation(),
134  {
135  LOCK(wallet.cs_wallet);
136  wallet.SetLastBlockProcessed(::ChainActive().Height(),
137  ::ChainActive().Tip()->GetBlockHash());
138  }
139  AddKey(wallet, coinbaseKey);
140  WalletRescanReserver reserver(wallet);
141  reserver.reserve();
142  CWallet::ScanResult result = wallet.ScanForWalletTransactions(
143  oldTip->GetBlockHash(), oldTip->nHeight, {} /* max_height */,
144  reserver, false /* update */);
149  BOOST_CHECK_EQUAL(wallet.GetBalance().m_mine_immature, Amount::zero());
150  }
151 }
152 
153 BOOST_FIXTURE_TEST_CASE(importmulti_rescan, TestChain100Setup) {
154  // Cap last block file size, and mine new block in a new block file.
155  CBlockIndex *oldTip = ::ChainActive().Tip();
157  CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
158  CBlockIndex *newTip = ::ChainActive().Tip();
159 
160  NodeContext node;
161  auto chain = interfaces::MakeChain(node, Params());
162 
163  // Prune the older block file.
164  {
165  LOCK(cs_main);
166  Assert(m_node.chainman)->PruneOneBlockFile(oldTip->GetBlockPos().nFile);
167  }
168  UnlinkPrunedFiles({oldTip->GetBlockPos().nFile});
169 
170  // Verify importmulti RPC returns failure for a key whose creation time is
171  // before the missing block, and success for a key whose creation time is
172  // after.
173  {
174  std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(
175  chain.get(), WalletLocation(), WalletDatabase::CreateDummy());
176  wallet->SetupLegacyScriptPubKeyMan();
177  WITH_LOCK(wallet->cs_wallet,
178  wallet->SetLastBlockProcessed(newTip->nHeight,
179  newTip->GetBlockHash()));
180  AddWallet(wallet);
181  UniValue keys;
182  keys.setArray();
183  UniValue key;
184  key.setObject();
185  key.pushKV("scriptPubKey",
186  HexStr(GetScriptForRawPubKey(coinbaseKey.GetPubKey())));
187  key.pushKV("timestamp", 0);
188  key.pushKV("internal", UniValue(true));
189  keys.push_back(key);
190  key.clear();
191  key.setObject();
192  CKey futureKey;
193  futureKey.MakeNewKey(true);
194  key.pushKV("scriptPubKey",
195  HexStr(GetScriptForRawPubKey(futureKey.GetPubKey())));
196  key.pushKV("timestamp",
197  newTip->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1);
198  key.pushKV("internal", UniValue(true));
199  keys.push_back(key);
200  util::Ref context;
201  JSONRPCRequest request(context);
202  request.params.setArray();
203  request.params.push_back(keys);
204 
205  UniValue response = importmulti(GetConfig(), request);
207  response.write(),
208  strprintf("[{\"success\":false,\"error\":{\"code\":-1,\"message\":"
209  "\"Rescan failed for key with creation timestamp %d. "
210  "There was an error reading a block from time %d, which "
211  "is after or within %d seconds of key creation, and "
212  "could contain transactions pertaining to the key. As a "
213  "result, transactions and coins using this key may not "
214  "appear in the wallet. This error could be caused by "
215  "pruning or data corruption (see bitcoind log for "
216  "details) and could be dealt with by downloading and "
217  "rescanning the relevant blocks (see -reindex and "
218  "-rescan options).\"}},{\"success\":true}]",
219  0, oldTip->GetBlockTimeMax(), TIMESTAMP_WINDOW));
220  RemoveWallet(wallet);
221  }
222 }
223 
224 // Verify importwallet RPC starts rescan at earliest block with timestamp
225 // greater or equal than key birthday. Previously there was a bug where
226 // importwallet RPC would start the scan at the latest block with timestamp less
227 // than or equal to key birthday.
228 BOOST_FIXTURE_TEST_CASE(importwallet_rescan, TestChain100Setup) {
229  // Create two blocks with same timestamp to verify that importwallet rescan
230  // will pick up both blocks, not just the first.
231  const int64_t BLOCK_TIME = ::ChainActive().Tip()->GetBlockTimeMax() + 5;
232  SetMockTime(BLOCK_TIME);
233  m_coinbase_txns.emplace_back(
234  CreateAndProcessBlock({},
235  GetScriptForRawPubKey(coinbaseKey.GetPubKey()))
236  .vtx[0]);
237  m_coinbase_txns.emplace_back(
238  CreateAndProcessBlock({},
239  GetScriptForRawPubKey(coinbaseKey.GetPubKey()))
240  .vtx[0]);
241 
242  // Set key birthday to block time increased by the timestamp window, so
243  // rescan will start at the block time.
244  const int64_t KEY_TIME = BLOCK_TIME + TIMESTAMP_WINDOW;
245  SetMockTime(KEY_TIME);
246  m_coinbase_txns.emplace_back(
247  CreateAndProcessBlock({},
248  GetScriptForRawPubKey(coinbaseKey.GetPubKey()))
249  .vtx[0]);
250 
251  NodeContext node;
252  auto chain = interfaces::MakeChain(node, Params());
253 
254  std::string backup_file = (GetDataDir() / "wallet.backup").string();
255 
256  // Import key into wallet and call dumpwallet to create backup file.
257  {
258  std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(
259  chain.get(), WalletLocation(), WalletDatabase::CreateDummy());
260  {
261  auto spk_man = wallet->GetOrCreateLegacyScriptPubKeyMan();
262  LOCK2(wallet->cs_wallet, spk_man->cs_KeyStore);
263  spk_man->mapKeyMetadata[coinbaseKey.GetPubKey().GetID()]
264  .nCreateTime = KEY_TIME;
265  spk_man->AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey());
266 
267  AddWallet(wallet);
268  wallet->SetLastBlockProcessed(
269  ::ChainActive().Height(),
270  ::ChainActive().Tip()->GetBlockHash());
271  }
272  util::Ref context;
273  JSONRPCRequest request(context);
274  request.params.setArray();
275  request.params.push_back(backup_file);
276  ::dumpwallet(GetConfig(), request);
277  RemoveWallet(wallet);
278  }
279 
280  // Call importwallet RPC and verify all blocks with timestamps >= BLOCK_TIME
281  // were scanned, and no prior blocks were scanned.
282  {
283  std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(
284  chain.get(), WalletLocation(), WalletDatabase::CreateDummy());
285  LOCK(wallet->cs_wallet);
286  wallet->SetupLegacyScriptPubKeyMan();
287 
288  util::Ref context;
289  JSONRPCRequest request(context);
290  request.params.setArray();
291  request.params.push_back(backup_file);
292  AddWallet(wallet);
293  wallet->SetLastBlockProcessed(::ChainActive().Height(),
294  ::ChainActive().Tip()->GetBlockHash());
295  ::importwallet(GetConfig(), request);
296  RemoveWallet(wallet);
297 
298  BOOST_CHECK_EQUAL(wallet->mapWallet.size(), 3U);
299  BOOST_CHECK_EQUAL(m_coinbase_txns.size(), 103U);
300  for (size_t i = 0; i < m_coinbase_txns.size(); ++i) {
301  bool found = wallet->GetWalletTx(m_coinbase_txns[i]->GetId());
302  bool expected = i >= 100;
303  BOOST_CHECK_EQUAL(found, expected);
304  }
305  }
306 }
307 
308 // Check that GetImmatureCredit() returns a newly calculated value instead of
309 // the cached value after a MarkDirty() call.
310 //
311 // This is a regression test written to verify a bugfix for the immature credit
312 // function. Similar tests probably should be written for the other credit and
313 // debit functions.
314 BOOST_FIXTURE_TEST_CASE(coin_mark_dirty_immature_credit, TestChain100Setup) {
315  NodeContext node;
316  auto chain = interfaces::MakeChain(node, Params());
317  CWallet wallet(chain.get(), WalletLocation(),
319  auto spk_man = wallet.GetOrCreateLegacyScriptPubKeyMan();
320  CWalletTx wtx(&wallet, m_coinbase_txns.back());
321 
322  LOCK2(wallet.cs_wallet, spk_man->cs_KeyStore);
323  wallet.SetLastBlockProcessed(::ChainActive().Height(),
324  ::ChainActive().Tip()->GetBlockHash());
325 
326  CWalletTx::Confirmation confirm(CWalletTx::Status::CONFIRMED,
327  ::ChainActive().Height(),
328  ::ChainActive().Tip()->GetBlockHash(), 0);
329  wtx.m_confirm = confirm;
330 
331  // Call GetImmatureCredit() once before adding the key to the wallet to
332  // cache the current immature credit amount, which is 0.
333  BOOST_CHECK_EQUAL(wtx.GetImmatureCredit(), Amount::zero());
334 
335  // Invalidate the cached value, add the key, and make sure a new immature
336  // credit amount is calculated.
337  wtx.MarkDirty();
338  BOOST_CHECK(spk_man->AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey()));
339  BOOST_CHECK_EQUAL(wtx.GetImmatureCredit(), 50 * COIN);
340 }
341 
342 static int64_t AddTx(CWallet &wallet, uint32_t lockTime, int64_t mockTime,
343  int64_t blockTime) {
345  tx.nLockTime = lockTime;
346  SetMockTime(mockTime);
347  CBlockIndex *block = nullptr;
348  if (blockTime > 0) {
349  auto inserted =
350  ::BlockIndex().emplace(BlockHash(GetRandHash()), new CBlockIndex);
351  assert(inserted.second);
352  const BlockHash &hash = inserted.first->first;
353  block = inserted.first->second;
354  block->nTime = blockTime;
355  block->phashBlock = &hash;
356  }
357 
358  CWalletTx wtx(&wallet, MakeTransactionRef(tx));
359  LOCK(wallet.cs_wallet);
360  // If transaction is already in map, to avoid inconsistencies,
361  // unconfirmation is needed before confirm again with different block.
362  std::map<TxId, CWalletTx>::iterator it = wallet.mapWallet.find(wtx.GetId());
363  if (it != wallet.mapWallet.end()) {
364  wtx.setUnconfirmed();
365  wallet.AddToWallet(wtx);
366  }
367  if (block) {
368  CWalletTx::Confirmation confirm(CWalletTx::Status::CONFIRMED,
369  block->nHeight, block->GetBlockHash(),
370  0);
371  wtx.m_confirm = confirm;
372  }
373  wallet.AddToWallet(wtx);
374  return wallet.mapWallet.at(wtx.GetId()).nTimeSmart;
375 }
376 
377 // Simple test to verify assignment of CWalletTx::nSmartTime value. Could be
378 // expanded to cover more corner cases of smart time logic.
379 BOOST_AUTO_TEST_CASE(ComputeTimeSmart) {
380  // New transaction should use clock time if lower than block time.
381  BOOST_CHECK_EQUAL(AddTx(m_wallet, 1, 100, 120), 100);
382 
383  // Test that updating existing transaction does not change smart time.
384  BOOST_CHECK_EQUAL(AddTx(m_wallet, 1, 200, 220), 100);
385 
386  // New transaction should use clock time if there's no block time.
387  BOOST_CHECK_EQUAL(AddTx(m_wallet, 2, 300, 0), 300);
388 
389  // New transaction should use block time if lower than clock time.
390  BOOST_CHECK_EQUAL(AddTx(m_wallet, 3, 420, 400), 400);
391 
392  // New transaction should use latest entry time if higher than
393  // min(block time, clock time).
394  BOOST_CHECK_EQUAL(AddTx(m_wallet, 4, 500, 390), 400);
395 
396  // If there are future entries, new transaction should use time of the
397  // newest entry that is no more than 300 seconds ahead of the clock time.
398  BOOST_CHECK_EQUAL(AddTx(m_wallet, 5, 50, 600), 300);
399 
400  // Reset mock time for other tests.
401  SetMockTime(0);
402 }
403 
404 BOOST_AUTO_TEST_CASE(LoadReceiveRequests) {
405  CTxDestination dest = PKHash();
406  LOCK(m_wallet.cs_wallet);
407  WalletBatch batch{m_wallet.GetDatabase()};
408  m_wallet.AddDestData(batch, dest, "misc", "val_misc");
409  m_wallet.AddDestData(batch, dest, "rr0", "val_rr0");
410  m_wallet.AddDestData(batch, dest, "rr1", "val_rr1");
411 
412  auto values = m_wallet.GetDestValues("rr");
413  BOOST_CHECK_EQUAL(values.size(), 2U);
414  BOOST_CHECK_EQUAL(values[0], "val_rr0");
415  BOOST_CHECK_EQUAL(values[1], "val_rr1");
416 }
417 
418 // Test some watch-only LegacyScriptPubKeyMan methods by the procedure of
419 // loading (LoadWatchOnly), checking (HaveWatchOnly), getting (GetWatchPubKey)
420 // and removing (RemoveWatchOnly) a given PubKey, resp. its corresponding P2PK
421 // Script. Results of the the impact on the address -> PubKey map is dependent
422 // on whether the PubKey is a point on the curve
424  const CPubKey &add_pubkey) {
425  CScript p2pk = GetScriptForRawPubKey(add_pubkey);
426  CKeyID add_address = add_pubkey.GetID();
427  CPubKey found_pubkey;
428  LOCK(spk_man->cs_KeyStore);
429 
430  // all Scripts (i.e. also all PubKeys) are added to the general watch-only
431  // set
432  BOOST_CHECK(!spk_man->HaveWatchOnly(p2pk));
433  spk_man->LoadWatchOnly(p2pk);
434  BOOST_CHECK(spk_man->HaveWatchOnly(p2pk));
435 
436  // only PubKeys on the curve shall be added to the watch-only address ->
437  // PubKey map
438  bool is_pubkey_fully_valid = add_pubkey.IsFullyValid();
439  if (is_pubkey_fully_valid) {
440  BOOST_CHECK(spk_man->GetWatchPubKey(add_address, found_pubkey));
441  BOOST_CHECK(found_pubkey == add_pubkey);
442  } else {
443  BOOST_CHECK(!spk_man->GetWatchPubKey(add_address, found_pubkey));
444  // passed key is unchanged
445  BOOST_CHECK(found_pubkey == CPubKey());
446  }
447 
448  spk_man->RemoveWatchOnly(p2pk);
449  BOOST_CHECK(!spk_man->HaveWatchOnly(p2pk));
450 
451  if (is_pubkey_fully_valid) {
452  BOOST_CHECK(!spk_man->GetWatchPubKey(add_address, found_pubkey));
453  // passed key is unchanged
454  BOOST_CHECK(found_pubkey == add_pubkey);
455  }
456 }
457 
458 // Cryptographically invalidate a PubKey whilst keeping length and first byte
459 static void PollutePubKey(CPubKey &pubkey) {
460  std::vector<uint8_t> pubkey_raw(pubkey.begin(), pubkey.end());
461  std::fill(pubkey_raw.begin() + 1, pubkey_raw.end(), 0);
462  pubkey = CPubKey(pubkey_raw);
463  assert(!pubkey.IsFullyValid());
464  assert(pubkey.IsValid());
465 }
466 
467 // Test watch-only logic for PubKeys
468 BOOST_AUTO_TEST_CASE(WatchOnlyPubKeys) {
469  CKey key;
470  CPubKey pubkey;
471  LegacyScriptPubKeyMan *spk_man =
472  m_wallet.GetOrCreateLegacyScriptPubKeyMan();
473 
474  BOOST_CHECK(!spk_man->HaveWatchOnly());
475 
476  // uncompressed valid PubKey
477  key.MakeNewKey(false);
478  pubkey = key.GetPubKey();
479  assert(!pubkey.IsCompressed());
480  TestWatchOnlyPubKey(spk_man, pubkey);
481 
482  // uncompressed cryptographically invalid PubKey
483  PollutePubKey(pubkey);
484  TestWatchOnlyPubKey(spk_man, pubkey);
485 
486  // compressed valid PubKey
487  key.MakeNewKey(true);
488  pubkey = key.GetPubKey();
489  assert(pubkey.IsCompressed());
490  TestWatchOnlyPubKey(spk_man, pubkey);
491 
492  // compressed cryptographically invalid PubKey
493  PollutePubKey(pubkey);
494  TestWatchOnlyPubKey(spk_man, pubkey);
495 
496  // invalid empty PubKey
497  pubkey = CPubKey();
498  TestWatchOnlyPubKey(spk_man, pubkey);
499 }
500 
501 class ListCoinsTestingSetup : public TestChain100Setup {
502 public:
504  CreateAndProcessBlock({},
505  GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
506  wallet = std::make_unique<CWallet>(m_chain.get(), WalletLocation(),
508  {
509  LOCK2(wallet->cs_wallet, ::cs_main);
510  wallet->SetLastBlockProcessed(
511  ::ChainActive().Height(),
512  ::ChainActive().Tip()->GetBlockHash());
513  }
514  bool firstRun;
515  wallet->LoadWallet(firstRun);
516  AddKey(*wallet, coinbaseKey);
517  WalletRescanReserver reserver(*wallet);
518  reserver.reserve();
519  CWallet::ScanResult result = wallet->ScanForWalletTransactions(
520  ::ChainActive().Genesis()->GetBlockHash(), 0 /* start_height */,
521  {} /* max_height */, reserver, false /* update */);
524  ::ChainActive().Tip()->GetBlockHash());
526  ::ChainActive().Height());
528  }
529 
531 
532  CWalletTx &AddTx(CRecipient recipient) {
533  CTransactionRef tx;
534  Amount fee;
535  int changePos = -1;
537  CCoinControl dummy;
538  {
539  BOOST_CHECK(wallet->CreateTransaction({recipient}, tx, fee,
540  changePos, error, dummy));
541  }
542  wallet->CommitTransaction(tx, {}, {});
543  CMutableTransaction blocktx;
544  {
545  LOCK(wallet->cs_wallet);
546  blocktx =
547  CMutableTransaction(*wallet->mapWallet.at(tx->GetId()).tx);
548  }
549  CreateAndProcessBlock({CMutableTransaction(blocktx)},
550  GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
551 
552  LOCK(wallet->cs_wallet);
553  wallet->SetLastBlockProcessed(wallet->GetLastBlockHeight() + 1,
555  auto it = wallet->mapWallet.find(tx->GetId());
556  BOOST_CHECK(it != wallet->mapWallet.end());
557  CWalletTx::Confirmation confirm(
558  CWalletTx::Status::CONFIRMED, ::ChainActive().Height(),
559  ::ChainActive().Tip()->GetBlockHash(), 1);
560  it->second.m_confirm = confirm;
561  return it->second;
562  }
563 
564  std::unique_ptr<interfaces::Chain> m_chain =
566  std::unique_ptr<CWallet> wallet;
567 };
568 
570  std::string coinbaseAddress = coinbaseKey.GetPubKey().GetID().ToString();
571 
572  // Confirm ListCoins initially returns 1 coin grouped under coinbaseKey
573  // address.
574  std::map<CTxDestination, std::vector<COutput>> list;
575  {
576  LOCK(wallet->cs_wallet);
577  list = wallet->ListCoins();
578  }
579  BOOST_CHECK_EQUAL(list.size(), 1U);
580  BOOST_CHECK_EQUAL(boost::get<PKHash>(list.begin()->first).ToString(),
581  coinbaseAddress);
582  BOOST_CHECK_EQUAL(list.begin()->second.size(), 1U);
583 
584  // Check initial balance from one mature coinbase transaction.
585  BOOST_CHECK_EQUAL(50 * COIN, wallet->GetAvailableBalance());
586 
587  // Add a transaction creating a change address, and confirm ListCoins still
588  // returns the coin associated with the change address underneath the
589  // coinbaseKey pubkey, even though the change address has a different
590  // pubkey.
592  false /* subtract fee */});
593  {
594  LOCK(wallet->cs_wallet);
595  list = wallet->ListCoins();
596  }
597  BOOST_CHECK_EQUAL(list.size(), 1U);
598  BOOST_CHECK_EQUAL(boost::get<PKHash>(list.begin()->first).ToString(),
599  coinbaseAddress);
600  BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
601 
602  // Lock both coins. Confirm number of available coins drops to 0.
603  {
604  LOCK(wallet->cs_wallet);
605  std::vector<COutput> available;
606  wallet->AvailableCoins(available);
607  BOOST_CHECK_EQUAL(available.size(), 2U);
608  }
609  for (const auto &group : list) {
610  for (const auto &coin : group.second) {
611  LOCK(wallet->cs_wallet);
612  wallet->LockCoin(COutPoint(coin.tx->GetId(), coin.i));
613  }
614  }
615  {
616  LOCK(wallet->cs_wallet);
617  std::vector<COutput> available;
618  wallet->AvailableCoins(available);
619  BOOST_CHECK_EQUAL(available.size(), 0U);
620  }
621  // Confirm ListCoins still returns same result as before, despite coins
622  // being locked.
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 
633 BOOST_FIXTURE_TEST_CASE(wallet_disableprivkeys, TestChain100Setup) {
634  NodeContext node;
635  auto chain = interfaces::MakeChain(node, Params());
636  std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(
637  chain.get(), WalletLocation(), WalletDatabase::CreateDummy());
638  wallet->SetupLegacyScriptPubKeyMan();
639  wallet->SetMinVersion(FEATURE_LATEST);
640  wallet->SetWalletFlag(WALLET_FLAG_DISABLE_PRIVATE_KEYS);
641  BOOST_CHECK(!wallet->TopUpKeyPool(1000));
642  CTxDestination dest;
643  std::string error;
644  BOOST_CHECK(
645  !wallet->GetNewDestination(OutputType::LEGACY, "", dest, error));
646 }
647 
648 // Explicit calculation which is used to test the wallet constant
649 static size_t CalculateP2PKHInputSize(bool use_max_sig) {
650  // Generate ephemeral valid pubkey
651  CKey key;
652  key.MakeNewKey(true);
653  CPubKey pubkey = key.GetPubKey();
654 
655  // Generate pubkey hash
656  PKHash key_hash(pubkey);
657 
658  // Create script to enter into keystore. Key hash can't be 0...
659  CScript script = GetScriptForDestination(key_hash);
660 
661  // Add script to key store and key to watchonly
662  FillableSigningProvider keystore;
663  keystore.AddKeyPubKey(key, pubkey);
664 
665  // Fill in dummy signatures for fee calculation.
666  SignatureData sig_data;
667  if (!ProduceSignature(keystore,
668  use_max_sig ? DUMMY_MAXIMUM_SIGNATURE_CREATOR
670  script, sig_data)) {
671  // We're hand-feeding it correct arguments; shouldn't happen
672  assert(false);
673  }
674 
675  CTxIn tx_in;
676  UpdateInput(tx_in, sig_data);
677  return (size_t)GetVirtualTransactionInputSize(tx_in);
678 }
679 
680 BOOST_FIXTURE_TEST_CASE(dummy_input_size_test, TestChain100Setup) {
683 }
684 
685 bool malformed_descriptor(std::ios_base::failure e) {
686  std::string s(e.what());
687  return s.find("Missing checksum") != std::string::npos;
688 }
689 
690 BOOST_FIXTURE_TEST_CASE(wallet_descriptor_test, BasicTestingSetup) {
691  std::vector<uint8_t> malformed_record;
692  CVectorWriter vw(0, 0, malformed_record, 0);
693  vw << std::string("notadescriptor");
694  vw << (uint64_t)0;
695  vw << (int32_t)0;
696  vw << (int32_t)0;
697  vw << (int32_t)1;
698 
699  VectorReader vr(0, 0, malformed_record, 0);
700  WalletDescriptor w_desc;
701  BOOST_CHECK_EXCEPTION(vr >> w_desc, std::ios_base::failure,
703 }
704 
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:338
static std::unique_ptr< BerkeleyDatabase > CreateDummy()
Return object for accessing dummy database with no read/write capabilities.
Definition: bdb.h:135
static std::unique_ptr< BerkeleyDatabase > CreateMock()
Return object for accessing temporary in-memory database.
Definition: bdb.h:142
bool malformed_descriptor(std::ios_base::failure e)
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
Definition: validation.h:77
std::shared_ptr< CWallet > m_wallet
Definition: wallet.cpp:464
static constexpr Amount zero()
Definition: amount.h:35
int64_t GetVirtualTransactionInputSize(const CTxIn &txin, int64_t nSigOpCount, unsigned int bytes_per_sigop)
Definition: policy.cpp:172
const BlockHash * phashBlock
pointer to the hash of the block, if any.
Definition: blockindex.h:27
Bilingual messages:
Definition: translation.h:17
CChain & ChainActive()
Definition: validation.cpp:73
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1201
bool AddWallet(const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:50
RecursiveMutex cs_KeyStore
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:210
std::unique_ptr< interfaces::Chain > m_chain
std::optional< int > last_scanned_height
Definition: wallet.h:1065
UniValue dumpwallet(const Config &config, const JSONRPCRequest &request)
Definition: rpcdump.cpp:862
uint256 GetRandHash() noexcept
Definition: random.cpp:654
NodeContext & m_node
Definition: chain.cpp:442
static CTransactionRef MakeTransactionRef()
Definition: transaction.h:339
static size_t CalculateP2PKHInputSize(bool use_max_sig)
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
Definition: sign.cpp:418
Definition: amount.h:17
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
Definition: standard.cpp:253
const BaseSignatureCreator & DUMMY_MAXIMUM_SIGNATURE_CREATOR
A signature creator that just produces 72-byte empty signatures.
Definition: sign.cpp:420
FlatFilePos GetBlockPos() const
Definition: blockindex.h:102
uint32_t nTime
Definition: blockindex.h:81
BlockHash last_scanned_block
Hash and height of most recent block that was successfully scanned.
Definition: wallet.h:1064
int nFile
Definition: flatfile.h:15
bool RemoveWatchOnly(const CScript &dest)
Remove a watch only script from the keystore.
BlockHash last_failed_block
Hash of the most recent block that could not be scanned due to read errors or pruning.
Definition: wallet.h:1071
enum CWallet::ScanResult::@23 status
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
const uint8_t * begin() const
Definition: pubkey.h:100
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:137
bool IsNull() const
Definition: uint256.h:26
Coin Control Features.
Definition: coincontrol.h:19
Access to the wallet database.
Definition: walletdb.h:183
CWalletTx & AddTx(CRecipient recipient)
static void TestWatchOnlyPubKey(LegacyScriptPubKeyMan *spk_man, const CPubKey &add_pubkey)
void SetMockTime(int64_t nMockTimeIn)
For testing.
Definition: time.cpp:50
BlockHash GetBlockHash() const
Definition: blockindex.h:133
Response response
Definition: processor.cpp:247
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:67
#define LOCK2(cs1, cs2)
Definition: sync.h:233
ChainstateManager * chainman
Definition: context.h:41
bool push_back(const UniValue &val)
Definition: univalue.cpp:108
static void AddKey(CWallet &wallet, const CKey &key)
NodeContext struct containing references to chain state and connection state.
Definition: context.h:35
bool IsFullyValid() const
fully validate whether this is a valid public key (more expensive than IsValid()) ...
Definition: pubkey.cpp:257
static constexpr Amount COIN
Definition: amount.h:153
Confirmation m_confirm
Definition: wallet.h:414
bool GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
Fetches a pubkey from mapWatchKeys if it exists there.
std::unique_ptr< CWallet > wallet
Minimal stream for reading from an existing vector by reference.
Definition: streams.h:128
UniValue params
Definition: request.h:37
An input of a transaction.
Definition: transaction.h:67
#define LOCK(cs)
Definition: sync.h:230
An encapsulated public key.
Definition: pubkey.h:31
Fillable signing provider that keeps keys in an address->secret map.
const fs::path & GetDataDir(bool fNetSpecific)
Definition: system.cpp:760
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
Definition: key.cpp:183
int64_t GetBlockTimeMax() const
Definition: blockindex.h:162
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune)
Actually unlink the specified files.
RecursiveMutex cs_main
Global state.
Definition: validation.cpp:90
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
const Config & GetConfig()
Definition: config.cpp:34
LegacyScriptPubKeyMan * GetOrCreateLegacyScriptPubKeyMan()
Definition: wallet.cpp:4848
bool pushKV(const std::string &key, const UniValue &val)
Definition: univalue.cpp:133
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:246
Descriptor with some wallet metadata.
Definition: walletutil.h:99
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:22
CBlockFileInfo * GetBlockFileInfo(size_t n)
Get block file info entry for one block file.
bool LoadWatchOnly(const CScript &dest)
Adds a watch-only address to the store, without saving it to disk (used by LoadWallet) ...
static void PollutePubKey(CPubKey &pubkey)
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:261
bool AddToWallet(const CWalletTx &wtxIn, bool fFlushOnClose=true)
Definition: wallet.cpp:857
Type-safe dynamic reference.
Definition: ref.h:21
RAII object to check and reserve a wallet rescan.
Definition: wallet.h:1554
BOOST_AUTO_TEST_CASE(ComputeTimeSmart)
A transaction with a bunch of additional info that only the owner cares about.
Definition: wallet.h:280
void setUnconfirmed()
Definition: wallet.h:588
bool setArray()
Definition: univalue.cpp:94
#define BOOST_FIXTURE_TEST_SUITE(a, b)
Definition: object.cpp:14
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
Testing setup and teardown for wallet.
#define BOOST_CHECK_EQUAL(v1, v2)
Definition: object.cpp:18
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: blockindex.h:23
const CChainParams & Params()
Return the currently selected parameters.
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:429
BlockMap & BlockIndex()
Definition: validation.cpp:926
A mutable version of CTransaction.
Definition: transaction.h:297
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:22
void UpdateInput(CTxIn &input, const SignatureData &data)
Definition: sign.cpp:330
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:168
#define BOOST_AUTO_TEST_SUITE_END()
Definition: object.cpp:16
bool RemoveWallet(const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:63
std::string HexStr(const T itbegin, const T itend)
Definition: strencodings.h:132
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:679
bool setObject()
Definition: univalue.cpp:101
BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions, TestChain100Setup)
UniValue importwallet(const Config &config, const JSONRPCRequest &request)
Definition: rpcdump.cpp:612
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
static int64_t AddTx(CWallet &wallet, uint32_t lockTime, int64_t mockTime, int64_t blockTime)
RecursiveMutex cs_wallet
Definition: wallet.h:823
virtual bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey)
The WalletLocation class provides wallet information.
Definition: walletutil.h:80
void clear()
Definition: univalue.cpp:15
Minimal stream for overwriting and/or appending to an existing byte vector.
Definition: streams.h:62
An encapsulated secp256k1 private key.
Definition: key.h:25
const uint8_t * end() const
Definition: pubkey.h:101
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: blockindex.h:36
Confirmation includes tx status and a triplet of {block height/block hash/tx index in block} at which...
Definition: wallet.h:404
static constexpr size_t DUMMY_P2PKH_INPUT_SIZE
Pre-calculated constants for input size estimation.
Definition: wallet.h:112
TxId GetId() const
Definition: wallet.h:593
UniValue importmulti(const Config &config, const JSONRPCRequest &mainRequest)
Definition: rpcdump.cpp:1597
bool error(const char *fmt, const Args &... args)
Definition: system.h:47
boost::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:87
#define Assert(val)
Identity function.
Definition: check.h:57
#define BOOST_CHECK(expr)
Definition: object.cpp:17
bool HaveWatchOnly(const CScript &dest) const
Returns whether the watch-only script is in the wallet.
bool IsCompressed() const
Check whether this is a compressed public key.
Definition: pubkey.h:154
std::unique_ptr< Chain > MakeChain(NodeContext &node, const CChainParams &params)
Return implementation of Chain interface.
Definition: chain.cpp:448