Bitcoin Core  21.99.0
P2P Digital Currency
wallet_tests.cpp
Go to the documentation of this file.
1 // Copyright (c) 2012-2020 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 <future>
8 #include <memory>
9 #include <stdint.h>
10 #include <vector>
11 
12 #include <interfaces/chain.h>
13 #include <node/context.h>
14 #include <policy/policy.h>
15 #include <rpc/server.h>
16 #include <test/util/logging.h>
17 #include <test/util/setup_common.h>
18 #include <util/ref.h>
19 #include <util/translation.h>
20 #include <validation.h>
21 #include <wallet/coincontrol.h>
23 
24 #include <boost/test/unit_test.hpp>
25 #include <univalue.h>
26 
30 
32 
33 // Ensure that fee levels defined in the wallet are at least as high
34 // as the default levels for node policy.
35 static_assert(DEFAULT_TRANSACTION_MINFEE >= DEFAULT_MIN_RELAY_TX_FEE, "wallet minimum fee is smaller than default relay fee");
36 static_assert(WALLET_INCREMENTAL_RELAY_FEE >= DEFAULT_INCREMENTAL_RELAY_FEE, "wallet incremental fee is smaller than default incremental relay fee");
37 
39 
40 static std::shared_ptr<CWallet> TestLoadWallet(interfaces::Chain& chain)
41 {
42  DatabaseOptions options;
43  DatabaseStatus status;
45  std::vector<bilingual_str> warnings;
46  auto database = MakeWalletDatabase("", options, status, error);
47  auto wallet = CWallet::Create(chain, "", std::move(database), options.create_flags, error, warnings);
48  wallet->postInitProcess();
49  return wallet;
50 }
51 
52 static void TestUnloadWallet(std::shared_ptr<CWallet>&& wallet)
53 {
55  wallet->m_chain_notifications_handler.reset();
56  UnloadWallet(std::move(wallet));
57 }
58 
59 static CMutableTransaction TestSimpleSpend(const CTransaction& from, uint32_t index, const CKey& key, const CScript& pubkey)
60 {
62  mtx.vout.push_back({from.vout[index].nValue - DEFAULT_TRANSACTION_MAXFEE, pubkey});
63  mtx.vin.push_back({CTxIn{from.GetHash(), index}});
64  FillableSigningProvider keystore;
65  keystore.AddKey(key);
66  std::map<COutPoint, Coin> coins;
67  coins[mtx.vin[0].prevout].out = from.vout[index];
68  std::map<int, std::string> input_errors;
69  BOOST_CHECK(SignTransaction(mtx, &keystore, coins, SIGHASH_ALL, input_errors));
70  return mtx;
71 }
72 
73 static void AddKey(CWallet& wallet, const CKey& key)
74 {
75  auto spk_man = wallet.GetOrCreateLegacyScriptPubKeyMan();
76  LOCK2(wallet.cs_wallet, spk_man->cs_KeyStore);
77  spk_man->AddKeyPubKey(key, key.GetPubKey());
78 }
79 
80 BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions, TestChain100Setup)
81 {
82  // Cap last block file size, and mine new block in a new block file.
83  CBlockIndex* oldTip = ::ChainActive().Tip();
85  CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
86  CBlockIndex* newTip = ::ChainActive().Tip();
87 
88  // Verify ScanForWalletTransactions fails to read an unknown start block.
89  {
91  {
92  LOCK(wallet.cs_wallet);
93  wallet.SetLastBlockProcessed(::ChainActive().Height(), ::ChainActive().Tip()->GetBlockHash());
94  }
95  AddKey(wallet, coinbaseKey);
96  WalletRescanReserver reserver(wallet);
97  reserver.reserve();
98  CWallet::ScanResult result = wallet.ScanForWalletTransactions({} /* start_block */, 0 /* start_height */, {} /* max_height */, reserver, false /* update */);
103  BOOST_CHECK_EQUAL(wallet.GetBalance().m_mine_immature, 0);
104  }
105 
106  // Verify ScanForWalletTransactions picks up transactions in both the old
107  // and new block files.
108  {
110  {
111  LOCK(wallet.cs_wallet);
112  wallet.SetLastBlockProcessed(::ChainActive().Height(), ::ChainActive().Tip()->GetBlockHash());
113  }
114  AddKey(wallet, coinbaseKey);
115  WalletRescanReserver reserver(wallet);
116  reserver.reserve();
117  CWallet::ScanResult result = wallet.ScanForWalletTransactions(oldTip->GetBlockHash(), oldTip->nHeight, {} /* max_height */, reserver, false /* update */);
122  BOOST_CHECK_EQUAL(wallet.GetBalance().m_mine_immature, 100 * COIN);
123  }
124 
125  // Prune the older block file.
126  {
127  LOCK(cs_main);
128  Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(oldTip->GetBlockPos().nFile);
129  }
130  UnlinkPrunedFiles({oldTip->GetBlockPos().nFile});
131 
132  // Verify ScanForWalletTransactions only picks transactions in the new block
133  // file.
134  {
136  {
137  LOCK(wallet.cs_wallet);
138  wallet.SetLastBlockProcessed(::ChainActive().Height(), ::ChainActive().Tip()->GetBlockHash());
139  }
140  AddKey(wallet, coinbaseKey);
141  WalletRescanReserver reserver(wallet);
142  reserver.reserve();
143  CWallet::ScanResult result = wallet.ScanForWalletTransactions(oldTip->GetBlockHash(), oldTip->nHeight, {} /* max_height */, reserver, false /* update */);
148  BOOST_CHECK_EQUAL(wallet.GetBalance().m_mine_immature, 50 * COIN);
149  }
150 
151  // Prune the remaining block file.
152  {
153  LOCK(cs_main);
154  Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(newTip->GetBlockPos().nFile);
155  }
156  UnlinkPrunedFiles({newTip->GetBlockPos().nFile});
157 
158  // Verify ScanForWalletTransactions scans no blocks.
159  {
161  {
162  LOCK(wallet.cs_wallet);
163  wallet.SetLastBlockProcessed(::ChainActive().Height(), ::ChainActive().Tip()->GetBlockHash());
164  }
165  AddKey(wallet, coinbaseKey);
166  WalletRescanReserver reserver(wallet);
167  reserver.reserve();
168  CWallet::ScanResult result = wallet.ScanForWalletTransactions(oldTip->GetBlockHash(), oldTip->nHeight, {} /* max_height */, reserver, false /* update */);
173  BOOST_CHECK_EQUAL(wallet.GetBalance().m_mine_immature, 0);
174  }
175 }
176 
177 BOOST_FIXTURE_TEST_CASE(importmulti_rescan, TestChain100Setup)
178 {
179  // Cap last block file size, and mine new block in a new block file.
180  CBlockIndex* oldTip = ::ChainActive().Tip();
182  CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
183  CBlockIndex* newTip = ::ChainActive().Tip();
184 
185  // Prune the older block file.
186  {
187  LOCK(cs_main);
188  Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(oldTip->GetBlockPos().nFile);
189  }
190  UnlinkPrunedFiles({oldTip->GetBlockPos().nFile});
191 
192  // Verify importmulti RPC returns failure for a key whose creation time is
193  // before the missing block, and success for a key whose creation time is
194  // after.
195  {
196  std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateDummyWalletDatabase());
197  wallet->SetupLegacyScriptPubKeyMan();
198  WITH_LOCK(wallet->cs_wallet, wallet->SetLastBlockProcessed(newTip->nHeight, newTip->GetBlockHash()));
199  AddWallet(wallet);
200  UniValue keys;
201  keys.setArray();
202  UniValue key;
203  key.setObject();
204  key.pushKV("scriptPubKey", HexStr(GetScriptForRawPubKey(coinbaseKey.GetPubKey())));
205  key.pushKV("timestamp", 0);
206  key.pushKV("internal", UniValue(true));
207  keys.push_back(key);
208  key.clear();
209  key.setObject();
210  CKey futureKey;
211  futureKey.MakeNewKey(true);
212  key.pushKV("scriptPubKey", HexStr(GetScriptForRawPubKey(futureKey.GetPubKey())));
213  key.pushKV("timestamp", newTip->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1);
214  key.pushKV("internal", UniValue(true));
215  keys.push_back(key);
216  util::Ref context;
217  JSONRPCRequest request(context);
218  request.params.setArray();
219  request.params.push_back(keys);
220 
221  UniValue response = importmulti().HandleRequest(request);
222  BOOST_CHECK_EQUAL(response.write(),
223  strprintf("[{\"success\":false,\"error\":{\"code\":-1,\"message\":\"Rescan failed for key with creation "
224  "timestamp %d. There was an error reading a block from time %d, which is after or within %d "
225  "seconds of key creation, and could contain transactions pertaining to the key. As a result, "
226  "transactions and coins using this key may not appear in the wallet. This error could be caused "
227  "by pruning or data corruption (see bitcoind log for details) and could be dealt with by "
228  "downloading and rescanning the relevant blocks (see -reindex and -rescan "
229  "options).\"}},{\"success\":true}]",
230  0, oldTip->GetBlockTimeMax(), TIMESTAMP_WINDOW));
231  RemoveWallet(wallet, nullopt);
232  }
233 }
234 
235 // Verify importwallet RPC starts rescan at earliest block with timestamp
236 // greater or equal than key birthday. Previously there was a bug where
237 // importwallet RPC would start the scan at the latest block with timestamp less
238 // than or equal to key birthday.
239 BOOST_FIXTURE_TEST_CASE(importwallet_rescan, TestChain100Setup)
240 {
241  // Create two blocks with same timestamp to verify that importwallet rescan
242  // will pick up both blocks, not just the first.
243  const int64_t BLOCK_TIME = ::ChainActive().Tip()->GetBlockTimeMax() + 5;
244  SetMockTime(BLOCK_TIME);
245  m_coinbase_txns.emplace_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
246  m_coinbase_txns.emplace_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
247 
248  // Set key birthday to block time increased by the timestamp window, so
249  // rescan will start at the block time.
250  const int64_t KEY_TIME = BLOCK_TIME + TIMESTAMP_WINDOW;
251  SetMockTime(KEY_TIME);
252  m_coinbase_txns.emplace_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
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>(m_node.chain.get(), "", CreateDummyWalletDatabase());
259  {
260  auto spk_man = wallet->GetOrCreateLegacyScriptPubKeyMan();
261  LOCK2(wallet->cs_wallet, spk_man->cs_KeyStore);
262  spk_man->mapKeyMetadata[coinbaseKey.GetPubKey().GetID()].nCreateTime = KEY_TIME;
263  spk_man->AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey());
264 
265  AddWallet(wallet);
266  wallet->SetLastBlockProcessed(::ChainActive().Height(), ::ChainActive().Tip()->GetBlockHash());
267  }
268  util::Ref context;
269  JSONRPCRequest request(context);
270  request.params.setArray();
271  request.params.push_back(backup_file);
272 
273  ::dumpwallet().HandleRequest(request);
274  RemoveWallet(wallet, nullopt);
275  }
276 
277  // Call importwallet RPC and verify all blocks with timestamps >= BLOCK_TIME
278  // were scanned, and no prior blocks were scanned.
279  {
280  std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateDummyWalletDatabase());
281  LOCK(wallet->cs_wallet);
282  wallet->SetupLegacyScriptPubKeyMan();
283 
284  util::Ref context;
285  JSONRPCRequest request(context);
286  request.params.setArray();
287  request.params.push_back(backup_file);
288  AddWallet(wallet);
289  wallet->SetLastBlockProcessed(::ChainActive().Height(), ::ChainActive().Tip()->GetBlockHash());
290  ::importwallet().HandleRequest(request);
291  RemoveWallet(wallet, nullopt);
292 
293  BOOST_CHECK_EQUAL(wallet->mapWallet.size(), 3U);
294  BOOST_CHECK_EQUAL(m_coinbase_txns.size(), 103U);
295  for (size_t i = 0; i < m_coinbase_txns.size(); ++i) {
296  bool found = wallet->GetWalletTx(m_coinbase_txns[i]->GetHash());
297  bool expected = i >= 100;
298  BOOST_CHECK_EQUAL(found, expected);
299  }
300  }
301 
302  SetMockTime(0);
303 }
304 
305 // Check that GetImmatureCredit() returns a newly calculated value instead of
306 // the cached value after a MarkDirty() call.
307 //
308 // This is a regression test written to verify a bugfix for the immature credit
309 // function. Similar tests probably should be written for the other credit and
310 // debit functions.
311 BOOST_FIXTURE_TEST_CASE(coin_mark_dirty_immature_credit, TestChain100Setup)
312 {
314  auto spk_man = wallet.GetOrCreateLegacyScriptPubKeyMan();
315  CWalletTx wtx(&wallet, m_coinbase_txns.back());
316 
317  LOCK2(wallet.cs_wallet, spk_man->cs_KeyStore);
318  wallet.SetLastBlockProcessed(::ChainActive().Height(), ::ChainActive().Tip()->GetBlockHash());
319 
320  CWalletTx::Confirmation confirm(CWalletTx::Status::CONFIRMED, ::ChainActive().Height(), ::ChainActive().Tip()->GetBlockHash(), 0);
321  wtx.m_confirm = confirm;
322 
323  // Call GetImmatureCredit() once before adding the key to the wallet to
324  // cache the current immature credit amount, which is 0.
325  BOOST_CHECK_EQUAL(wtx.GetImmatureCredit(), 0);
326 
327  // Invalidate the cached value, add the key, and make sure a new immature
328  // credit amount is calculated.
329  wtx.MarkDirty();
330  BOOST_CHECK(spk_man->AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey()));
331  BOOST_CHECK_EQUAL(wtx.GetImmatureCredit(), 50*COIN);
332 }
333 
334 static int64_t AddTx(ChainstateManager& chainman, CWallet& wallet, uint32_t lockTime, int64_t mockTime, int64_t blockTime)
335 {
337  CWalletTx::Confirmation confirm;
338  tx.nLockTime = lockTime;
339  SetMockTime(mockTime);
340  CBlockIndex* block = nullptr;
341  if (blockTime > 0) {
342  LOCK(cs_main);
343  auto inserted = chainman.BlockIndex().emplace(GetRandHash(), new CBlockIndex);
344  assert(inserted.second);
345  const uint256& hash = inserted.first->first;
346  block = inserted.first->second;
347  block->nTime = blockTime;
348  block->phashBlock = &hash;
349  confirm = {CWalletTx::Status::CONFIRMED, block->nHeight, hash, 0};
350  }
351 
352  // If transaction is already in map, to avoid inconsistencies, unconfirmation
353  // is needed before confirm again with different block.
354  return wallet.AddToWallet(MakeTransactionRef(tx), confirm, [&](CWalletTx& wtx, bool /* new_tx */) {
355  wtx.setUnconfirmed();
356  return true;
357  })->nTimeSmart;
358 }
359 
360 // Simple test to verify assignment of CWalletTx::nSmartTime value. Could be
361 // expanded to cover more corner cases of smart time logic.
362 BOOST_AUTO_TEST_CASE(ComputeTimeSmart)
363 {
364  // New transaction should use clock time if lower than block time.
365  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 100, 120), 100);
366 
367  // Test that updating existing transaction does not change smart time.
368  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 200, 220), 100);
369 
370  // New transaction should use clock time if there's no block time.
371  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 2, 300, 0), 300);
372 
373  // New transaction should use block time if lower than clock time.
374  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 3, 420, 400), 400);
375 
376  // New transaction should use latest entry time if higher than
377  // min(block time, clock time).
378  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 4, 500, 390), 400);
379 
380  // If there are future entries, new transaction should use time of the
381  // newest entry that is no more than 300 seconds ahead of the clock time.
382  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 5, 50, 600), 300);
383 
384  // Reset mock time for other tests.
385  SetMockTime(0);
386 }
387 
388 BOOST_AUTO_TEST_CASE(LoadReceiveRequests)
389 {
390  CTxDestination dest = PKHash();
391  LOCK(m_wallet.cs_wallet);
392  WalletBatch batch{m_wallet.GetDatabase()};
393  m_wallet.AddDestData(batch, dest, "misc", "val_misc");
394  m_wallet.AddDestData(batch, dest, "rr0", "val_rr0");
395  m_wallet.AddDestData(batch, dest, "rr1", "val_rr1");
396 
397  auto values = m_wallet.GetDestValues("rr");
398  BOOST_CHECK_EQUAL(values.size(), 2U);
399  BOOST_CHECK_EQUAL(values[0], "val_rr0");
400  BOOST_CHECK_EQUAL(values[1], "val_rr1");
401 }
402 
403 // Test some watch-only LegacyScriptPubKeyMan methods by the procedure of loading (LoadWatchOnly),
404 // checking (HaveWatchOnly), getting (GetWatchPubKey) and removing (RemoveWatchOnly) a
405 // given PubKey, resp. its corresponding P2PK Script. Results of the the impact on
406 // the address -> PubKey map is dependent on whether the PubKey is a point on the curve
407 static void TestWatchOnlyPubKey(LegacyScriptPubKeyMan* spk_man, const CPubKey& add_pubkey)
408 {
409  CScript p2pk = GetScriptForRawPubKey(add_pubkey);
410  CKeyID add_address = add_pubkey.GetID();
411  CPubKey found_pubkey;
412  LOCK(spk_man->cs_KeyStore);
413 
414  // all Scripts (i.e. also all PubKeys) are added to the general watch-only set
415  BOOST_CHECK(!spk_man->HaveWatchOnly(p2pk));
416  spk_man->LoadWatchOnly(p2pk);
417  BOOST_CHECK(spk_man->HaveWatchOnly(p2pk));
418 
419  // only PubKeys on the curve shall be added to the watch-only address -> PubKey map
420  bool is_pubkey_fully_valid = add_pubkey.IsFullyValid();
421  if (is_pubkey_fully_valid) {
422  BOOST_CHECK(spk_man->GetWatchPubKey(add_address, found_pubkey));
423  BOOST_CHECK(found_pubkey == add_pubkey);
424  } else {
425  BOOST_CHECK(!spk_man->GetWatchPubKey(add_address, found_pubkey));
426  BOOST_CHECK(found_pubkey == CPubKey()); // passed key is unchanged
427  }
428 
429  spk_man->RemoveWatchOnly(p2pk);
430  BOOST_CHECK(!spk_man->HaveWatchOnly(p2pk));
431 
432  if (is_pubkey_fully_valid) {
433  BOOST_CHECK(!spk_man->GetWatchPubKey(add_address, found_pubkey));
434  BOOST_CHECK(found_pubkey == add_pubkey); // passed key is unchanged
435  }
436 }
437 
438 // Cryptographically invalidate a PubKey whilst keeping length and first byte
439 static void PollutePubKey(CPubKey& pubkey)
440 {
441  std::vector<unsigned char> pubkey_raw(pubkey.begin(), pubkey.end());
442  std::fill(pubkey_raw.begin()+1, pubkey_raw.end(), 0);
443  pubkey = CPubKey(pubkey_raw);
444  assert(!pubkey.IsFullyValid());
445  assert(pubkey.IsValid());
446 }
447 
448 // Test watch-only logic for PubKeys
449 BOOST_AUTO_TEST_CASE(WatchOnlyPubKeys)
450 {
451  CKey key;
452  CPubKey pubkey;
453  LegacyScriptPubKeyMan* spk_man = m_wallet.GetOrCreateLegacyScriptPubKeyMan();
454 
455  BOOST_CHECK(!spk_man->HaveWatchOnly());
456 
457  // uncompressed valid PubKey
458  key.MakeNewKey(false);
459  pubkey = key.GetPubKey();
460  assert(!pubkey.IsCompressed());
461  TestWatchOnlyPubKey(spk_man, pubkey);
462 
463  // uncompressed cryptographically invalid PubKey
464  PollutePubKey(pubkey);
465  TestWatchOnlyPubKey(spk_man, pubkey);
466 
467  // compressed valid PubKey
468  key.MakeNewKey(true);
469  pubkey = key.GetPubKey();
470  assert(pubkey.IsCompressed());
471  TestWatchOnlyPubKey(spk_man, pubkey);
472 
473  // compressed cryptographically invalid PubKey
474  PollutePubKey(pubkey);
475  TestWatchOnlyPubKey(spk_man, pubkey);
476 
477  // invalid empty PubKey
478  pubkey = CPubKey();
479  TestWatchOnlyPubKey(spk_man, pubkey);
480 }
481 
482 class ListCoinsTestingSetup : public TestChain100Setup
483 {
484 public:
486  {
487  CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
488  wallet = MakeUnique<CWallet>(m_node.chain.get(), "", CreateMockWalletDatabase());
489  {
490  LOCK2(wallet->cs_wallet, ::cs_main);
491  wallet->SetLastBlockProcessed(::ChainActive().Height(), ::ChainActive().Tip()->GetBlockHash());
492  }
493  bool firstRun;
494  wallet->LoadWallet(firstRun);
495  AddKey(*wallet, coinbaseKey);
496  WalletRescanReserver reserver(*wallet);
497  reserver.reserve();
498  CWallet::ScanResult result = wallet->ScanForWalletTransactions(::ChainActive().Genesis()->GetBlockHash(), 0 /* start_height */, {} /* max_height */, reserver, false /* update */);
500  BOOST_CHECK_EQUAL(result.last_scanned_block, ::ChainActive().Tip()->GetBlockHash());
501  BOOST_CHECK_EQUAL(*result.last_scanned_height, ::ChainActive().Height());
503  }
504 
506  {
507  wallet.reset();
508  }
509 
511  {
512  CTransactionRef tx;
513  CAmount fee;
514  int changePos = -1;
516  CCoinControl dummy;
517  FeeCalculation fee_calc_out;
518  {
519  BOOST_CHECK(wallet->CreateTransaction({recipient}, tx, fee, changePos, error, dummy, fee_calc_out));
520  }
521  wallet->CommitTransaction(tx, {}, {});
522  CMutableTransaction blocktx;
523  {
524  LOCK(wallet->cs_wallet);
525  blocktx = CMutableTransaction(*wallet->mapWallet.at(tx->GetHash()).tx);
526  }
527  CreateAndProcessBlock({CMutableTransaction(blocktx)}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
528 
529  LOCK(wallet->cs_wallet);
530  wallet->SetLastBlockProcessed(wallet->GetLastBlockHeight() + 1, ::ChainActive().Tip()->GetBlockHash());
531  auto it = wallet->mapWallet.find(tx->GetHash());
532  BOOST_CHECK(it != wallet->mapWallet.end());
533  CWalletTx::Confirmation confirm(CWalletTx::Status::CONFIRMED, ::ChainActive().Height(), ::ChainActive().Tip()->GetBlockHash(), 1);
534  it->second.m_confirm = confirm;
535  return it->second;
536  }
537 
538  std::unique_ptr<CWallet> wallet;
539 };
540 
542 {
543  std::string coinbaseAddress = coinbaseKey.GetPubKey().GetID().ToString();
544 
545  // Confirm ListCoins initially returns 1 coin grouped under coinbaseKey
546  // address.
547  std::map<CTxDestination, std::vector<COutput>> list;
548  {
549  LOCK(wallet->cs_wallet);
550  list = wallet->ListCoins();
551  }
552  BOOST_CHECK_EQUAL(list.size(), 1U);
553  BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
554  BOOST_CHECK_EQUAL(list.begin()->second.size(), 1U);
555 
556  // Check initial balance from one mature coinbase transaction.
557  BOOST_CHECK_EQUAL(50 * COIN, wallet->GetAvailableBalance());
558 
559  // Add a transaction creating a change address, and confirm ListCoins still
560  // returns the coin associated with the change address underneath the
561  // coinbaseKey pubkey, even though the change address has a different
562  // pubkey.
563  AddTx(CRecipient{GetScriptForRawPubKey({}), 1 * COIN, false /* subtract fee */});
564  {
565  LOCK(wallet->cs_wallet);
566  list = wallet->ListCoins();
567  }
568  BOOST_CHECK_EQUAL(list.size(), 1U);
569  BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
570  BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
571 
572  // Lock both coins. Confirm number of available coins drops to 0.
573  {
574  LOCK(wallet->cs_wallet);
575  std::vector<COutput> available;
576  wallet->AvailableCoins(available);
577  BOOST_CHECK_EQUAL(available.size(), 2U);
578  }
579  for (const auto& group : list) {
580  for (const auto& coin : group.second) {
581  LOCK(wallet->cs_wallet);
582  wallet->LockCoin(COutPoint(coin.tx->GetHash(), coin.i));
583  }
584  }
585  {
586  LOCK(wallet->cs_wallet);
587  std::vector<COutput> available;
588  wallet->AvailableCoins(available);
589  BOOST_CHECK_EQUAL(available.size(), 0U);
590  }
591  // Confirm ListCoins still returns same result as before, despite coins
592  // being locked.
593  {
594  LOCK(wallet->cs_wallet);
595  list = wallet->ListCoins();
596  }
597  BOOST_CHECK_EQUAL(list.size(), 1U);
598  BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
599  BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
600 }
601 
602 BOOST_FIXTURE_TEST_CASE(wallet_disableprivkeys, TestChain100Setup)
603 {
604  std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateDummyWalletDatabase());
605  wallet->SetupLegacyScriptPubKeyMan();
606  wallet->SetMinVersion(FEATURE_LATEST);
607  wallet->SetWalletFlag(WALLET_FLAG_DISABLE_PRIVATE_KEYS);
608  BOOST_CHECK(!wallet->TopUpKeyPool(1000));
609  CTxDestination dest;
610  std::string error;
611  BOOST_CHECK(!wallet->GetNewDestination(OutputType::BECH32, "", dest, error));
612 }
613 
614 // Explicit calculation which is used to test the wallet constant
615 // We get the same virtual size due to rounding(weight/4) for both use_max_sig values
616 static size_t CalculateNestedKeyhashInputSize(bool use_max_sig)
617 {
618  // Generate ephemeral valid pubkey
619  CKey key;
620  key.MakeNewKey(true);
621  CPubKey pubkey = key.GetPubKey();
622 
623  // Generate pubkey hash
624  uint160 key_hash(Hash160(pubkey));
625 
626  // Create inner-script to enter into keystore. Key hash can't be 0...
627  CScript inner_script = CScript() << OP_0 << std::vector<unsigned char>(key_hash.begin(), key_hash.end());
628 
629  // Create outer P2SH script for the output
630  uint160 script_id(Hash160(inner_script));
631  CScript script_pubkey = CScript() << OP_HASH160 << std::vector<unsigned char>(script_id.begin(), script_id.end()) << OP_EQUAL;
632 
633  // Add inner-script to key store and key to watchonly
634  FillableSigningProvider keystore;
635  keystore.AddCScript(inner_script);
636  keystore.AddKeyPubKey(key, pubkey);
637 
638  // Fill in dummy signatures for fee calculation.
639  SignatureData sig_data;
640 
641  if (!ProduceSignature(keystore, use_max_sig ? DUMMY_MAXIMUM_SIGNATURE_CREATOR : DUMMY_SIGNATURE_CREATOR, script_pubkey, sig_data)) {
642  // We're hand-feeding it correct arguments; shouldn't happen
643  assert(false);
644  }
645 
646  CTxIn tx_in;
647  UpdateInput(tx_in, sig_data);
648  return (size_t)GetVirtualTransactionInputSize(tx_in);
649 }
650 
651 BOOST_FIXTURE_TEST_CASE(dummy_input_size_test, TestChain100Setup)
652 {
655 }
656 
657 bool malformed_descriptor(std::ios_base::failure e)
658 {
659  std::string s(e.what());
660  return s.find("Missing checksum") != std::string::npos;
661 }
662 
663 BOOST_FIXTURE_TEST_CASE(wallet_descriptor_test, BasicTestingSetup)
664 {
665  std::vector<unsigned char> malformed_record;
666  CVectorWriter vw(0, 0, malformed_record, 0);
667  vw << std::string("notadescriptor");
668  vw << (uint64_t)0;
669  vw << (int32_t)0;
670  vw << (int32_t)0;
671  vw << (int32_t)1;
672 
673  VectorReader vr(0, 0, malformed_record, 0);
674  WalletDescriptor w_desc;
675  BOOST_CHECK_EXCEPTION(vr >> w_desc, std::ios_base::failure, malformed_descriptor);
676 }
677 
697 {
698  // Create new wallet with known key and unload it.
700  CKey key;
701  key.MakeNewKey(true);
702  AddKey(*wallet, key);
703  TestUnloadWallet(std::move(wallet));
704 
705 
706  // Add log hook to detect AddToWallet events from rescans, blockConnected,
707  // and transactionAddedToMempool notifications
708  int addtx_count = 0;
709  DebugLogHelper addtx_counter("[default wallet] AddToWallet", [&](const std::string* s) {
710  if (s) ++addtx_count;
711  return false;
712  });
713 
714 
715  bool rescan_completed = false;
716  DebugLogHelper rescan_check("[default wallet] Rescan completed", [&](const std::string* s) {
717  if (s) rescan_completed = true;
718  return false;
719  });
720 
721 
722  // Block the queue to prevent the wallet receiving blockConnected and
723  // transactionAddedToMempool notifications, and create block and mempool
724  // transactions paying to the wallet
725  std::promise<void> promise;
727  promise.get_future().wait();
728  });
729  std::string error;
730  m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
731  auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
732  m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
733  auto mempool_tx = TestSimpleSpend(*m_coinbase_txns[1], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
734  BOOST_CHECK(m_node.chain->broadcastTransaction(MakeTransactionRef(mempool_tx), DEFAULT_TRANSACTION_MAXFEE, false, error));
735 
736 
737  // Reload wallet and make sure new transactions are detected despite events
738  // being blocked
740  BOOST_CHECK(rescan_completed);
741  BOOST_CHECK_EQUAL(addtx_count, 2);
742  {
743  LOCK(wallet->cs_wallet);
744  BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_tx.GetHash()), 1U);
745  BOOST_CHECK_EQUAL(wallet->mapWallet.count(mempool_tx.GetHash()), 1U);
746  }
747 
748 
749  // Unblock notification queue and make sure stale blockConnected and
750  // transactionAddedToMempool events are processed
751  promise.set_value();
753  BOOST_CHECK_EQUAL(addtx_count, 4);
754 
755 
756  TestUnloadWallet(std::move(wallet));
757 
758 
759  // Load wallet again, this time creating new block and mempool transactions
760  // paying to the wallet as the wallet finishes loading and syncing the
761  // queue so the events have to be handled immediately. Releasing the wallet
762  // lock during the sync is a little artificial but is needed to avoid a
763  // deadlock during the sync and simulates a new block notification happening
764  // as soon as possible.
765  addtx_count = 0;
766  auto handler = HandleLoadWallet([&](std::unique_ptr<interfaces::Wallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->wallet()->cs_wallet, cs_wallets) {
767  BOOST_CHECK(rescan_completed);
768  m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
769  block_tx = TestSimpleSpend(*m_coinbase_txns[2], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
770  m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
771  mempool_tx = TestSimpleSpend(*m_coinbase_txns[3], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
772  BOOST_CHECK(m_node.chain->broadcastTransaction(MakeTransactionRef(mempool_tx), DEFAULT_TRANSACTION_MAXFEE, false, error));
773  LEAVE_CRITICAL_SECTION(cs_wallets);
774  LEAVE_CRITICAL_SECTION(wallet->wallet()->cs_wallet);
776  ENTER_CRITICAL_SECTION(wallet->wallet()->cs_wallet);
777  ENTER_CRITICAL_SECTION(cs_wallets);
778  });
779  wallet = TestLoadWallet(*m_node.chain);
780  BOOST_CHECK_EQUAL(addtx_count, 4);
781  {
782  LOCK(wallet->cs_wallet);
783  BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_tx.GetHash()), 1U);
784  BOOST_CHECK_EQUAL(wallet->mapWallet.count(mempool_tx.GetHash()), 1U);
785  }
786 
787 
788  TestUnloadWallet(std::move(wallet));
789 }
790 
791 BOOST_FIXTURE_TEST_CASE(ZapSelectTx, TestChain100Setup)
792 {
794  CKey key;
795  key.MakeNewKey(true);
796  AddKey(*wallet, key);
797 
798  std::string error;
799  m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
800  auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
801  CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
802 
804 
805  {
806  auto block_hash = block_tx.GetHash();
807  auto prev_hash = m_coinbase_txns[0]->GetHash();
808 
809  LOCK(wallet->cs_wallet);
810  BOOST_CHECK(wallet->HasWalletSpend(prev_hash));
811  BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_hash), 1u);
812 
813  std::vector<uint256> vHashIn{ block_hash }, vHashOut;
814  BOOST_CHECK_EQUAL(wallet->ZapSelectTx(vHashIn, vHashOut), DBErrors::LOAD_OK);
815 
816  BOOST_CHECK(!wallet->HasWalletSpend(prev_hash));
817  BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_hash), 0u);
818  }
819 
820  TestUnloadWallet(std::move(wallet));
821 }
822 
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:386
std::unique_ptr< WalletDatabase > CreateMockWalletDatabase()
Return object for accessing temporary in-memory database.
Definition: walletdb.cpp:1089
bool malformed_descriptor(std::ios_base::failure e)
bool(* handler)(const util::Ref &context, HTTPRequest *req, const std::string &strReq)
Definition: rest.cpp:671
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
Definition: validation.h:68
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.
std::deque< CInv >::iterator it
assert(!tx.IsCoinBase())
constexpr CAmount DEFAULT_TRANSACTION_MAXFEE
-maxtxfee default
Definition: wallet.h:93
NodeContext & m_node
Definition: interfaces.cpp:660
Bilingual messages:
Definition: translation.h:16
CChain & ChainActive()
Please prefer the identical ChainstateManager::ActiveChain.
Definition: validation.cpp:112
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:772
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
RecursiveMutex cs_KeyStore
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:184
uint256 GetRandHash() noexcept
Definition: random.cpp:602
std::vector< CTxIn > vin
Definition: transaction.h:346
uint256 last_scanned_block
Hash and height of most recent block that was successfully scanned.
Definition: wallet.h:909
static const CAmount COIN
Definition: amount.h:14
UniValue HandleRequest(const JSONRPCRequest &request)
Definition: util.h:339
virtual bool AddCScript(const CScript &redeemScript)
std::shared_ptr< CWallet > m_wallet
Definition: interfaces.cpp:499
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
Definition: sign.cpp:434
std::unique_ptr< interfaces::Chain > chain
Definition: context.h:45
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
Definition: standard.cpp:305
static const unsigned int DEFAULT_INCREMENTAL_RELAY_FEE
Default for -incrementalrelayfee, which sets the minimum feerate increase for mempool limiting or BIP...
Definition: policy.h:34
const BaseSignatureCreator & DUMMY_MAXIMUM_SIGNATURE_CREATOR
A signature creator that just produces 72-byte empty signatures.
Definition: sign.cpp:435
static auto & nullopt
Substitute for C++17 std::nullopt DEPRECATED use std::nullopt in new code.
Definition: optional.h:18
FlatFilePos GetBlockPos() const
Definition: chain.h:202
uint32_t nTime
Definition: chain.h:179
RecursiveMutex cs_wallets
Definition: wallet.cpp:55
static size_t CalculateNestedKeyhashInputSize(bool use_max_sig)
static std::shared_ptr< CWallet > TestLoadWallet(interfaces::Chain &chain)
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:212
int nFile
Definition: flatfile.h:16
RPCHelpMan dumpwallet()
Definition: rpcdump.cpp:716
unsigned char * begin()
Definition: uint256.h:58
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:159
bool IsNull() const
Definition: uint256.h:31
const unsigned char * begin() const
Definition: pubkey.h:112
bool RemoveWallet(const std::shared_ptr< CWallet > &wallet, Optional< bool > load_on_start, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:107
Coin Control Features.
Definition: coincontrol.h:22
unsigned char * end()
Definition: uint256.h:63
Access to the wallet database.
Definition: walletdb.h:176
CWalletTx & AddTx(CRecipient recipient)
static void TestWatchOnlyPubKey(LegacyScriptPubKeyMan *spk_man, const CPubKey &add_pubkey)
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
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:71
#define LOCK2(cs1, cs2)
Definition: sync.h:233
ChainstateManager * chainman
Definition: context.h:42
bool push_back(const UniValue &val)
Definition: univalue.cpp:108
static void AddKey(CWallet &wallet, const CKey &key)
int64_t GetVirtualTransactionInputSize(const CTxIn &txin, int64_t nSigOpCost, unsigned int bytes_per_sigop)
Definition: policy.cpp:290
const unsigned char * end() const
Definition: pubkey.h:113
bool IsFullyValid() const
fully validate whether this is a valid public key (more expensive than IsValid()) ...
Definition: pubkey.cpp:230
bool GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
Fetches a pubkey from mapWatchKeys if it exists there.
#define LEAVE_CRITICAL_SECTION(cs)
Definition: sync.h:245
std::unique_ptr< CWallet > wallet
Minimal stream for reading from an existing vector by reference.
Definition: streams.h:131
UniValue params
Definition: request.h:36
An input of a transaction.
Definition: transaction.h:65
std::unique_ptr< interfaces::Handler > HandleLoadWallet(LoadWalletFn load_wallet)
Definition: wallet.cpp:148
#define LOCK(cs)
Definition: sync.h:232
const uint256 & GetHash() const
Definition: transaction.h:302
An encapsulated public key.
Definition: pubkey.h:31
Fillable signing provider that keeps keys in an address->secret map.
bool AddWallet(const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:95
const fs::path & GetDataDir(bool fNetSpecific)
Definition: system.cpp:720
static const unsigned int DEFAULT_MIN_RELAY_TX_FEE
Default for -minrelaytxfee, minimum relay fee for transactions.
Definition: validation.h:56
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
Definition: validation.cpp:128
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
Definition: key.cpp:157
const std::vector< CTxOut > vout
Definition: transaction.h:271
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
RPCHelpMan importmulti()
Definition: rpcdump.cpp:1262
LegacyScriptPubKeyMan * GetOrCreateLegacyScriptPubKeyMan()
Definition: wallet.cpp:4377
bool pushKV(const std::string &key, const UniValue &val)
Definition: univalue.cpp:133
std::unique_ptr< WalletDatabase > CreateDummyWalletDatabase()
Return object for accessing dummy database with no read/write capabilities.
Definition: walletdb.cpp:1083
void CallFunctionInValidationInterfaceQueue(std::function< void()> func)
Pushes a function to callback onto the notification queue, guaranteeing any callbacks generated prior...
CWalletTx * AddToWallet(CTransactionRef tx, const CWalletTx::Confirmation &confirm, const UpdateWalletTxFn &update_wtx=nullptr, bool fFlushOnClose=true)
Definition: wallet.cpp:845
Descriptor with some wallet metadata.
Definition: walletutil.h:69
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:26
void UnloadWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly unload and delete the wallet.
Definition: wallet.cpp:179
CBlockFileInfo * GetBlockFileInfo(size_t n)
Get block file info entry for one block file.
std::vector< CTxOut > vout
Definition: transaction.h:347
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:276
RPCHelpMan importwallet()
Definition: rpcdump.cpp:511
Type-safe dynamic reference.
Definition: ref.h:21
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
RAII object to check and reserve a wallet rescan.
Definition: wallet.h:1284
BOOST_AUTO_TEST_CASE(ComputeTimeSmart)
A transaction with a bunch of additional info that only the owner cares about.
Definition: wallet.h:270
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:387
static void TestUnloadWallet(std::shared_ptr< CWallet > &&wallet)
uint160 Hash160(const T1 &in1)
Compute the 160-bit hash an object.
Definition: hash.h:92
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)
Definition: wallet.cpp:3799
#define ENTER_CRITICAL_SECTION(cs)
Definition: sync.h:239
256-bit opaque blob.
Definition: uint256.h:124
void setUnconfirmed()
Definition: wallet.h:546
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
static const CAmount DEFAULT_TRANSACTION_MINFEE
-mintxfee default
Definition: wallet.h:69
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:404
std::shared_ptr< CWallet > CreateWallet(interfaces::Chain &chain, const std::string &name, Optional< bool > load_on_start, DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:247
static int64_t AddTx(ChainstateManager &chainman, CWallet &wallet, uint32_t lockTime, int64_t mockTime, int64_t blockTime)
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:21
void UpdateInput(CTxIn &input, const SignatureData &data)
Definition: sign.cpp:354
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
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:622
bool setObject()
Definition: univalue.cpp:101
static CMutableTransaction TestSimpleSpend(const CTransaction &from, uint32_t index, const CKey &key, const CScript &pubkey)
160-bit opaque blob.
Definition: uint256.h:113
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:199
RecursiveMutex cs_wallet
Definition: wallet.h:730
Optional< int > last_scanned_height
Definition: wallet.h:910
A mutable version of CTransaction.
Definition: transaction.h:344
uint256 last_failed_block
Height of the most recent block that could not be scanned due to read errors or pruning.
Definition: wallet.h:916
static const CAmount WALLET_INCREMENTAL_RELAY_FEE
minimum recommended increment for BIP 125 replacement txs
Definition: wallet.h:81
void clear()
Definition: univalue.cpp:15
uint64_t create_flags
Definition: db.h:208
An encapsulated private key.
Definition: key.h:27
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:259
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:150
std::unique_ptr< WalletDatabase > MakeWalletDatabase(const std::string &name, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error_string)
Definition: wallet.cpp:3775
DatabaseStatus
Definition: db.h:213
bool error(const char *fmt, const Args &... args)
Definition: system.h:52
enum CWallet::ScanResult::@16 status
virtual bool AddKey(const CKey &key)
#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:193
const uint256 * phashBlock
pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
Definition: chain.h:141
BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:860
static constexpr size_t DUMMY_NESTED_P2WPKH_INPUT_SIZE
Pre-calculated constants for input size estimation in virtual size
Definition: wallet.h:100