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