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