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