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