Bitcoin Core  22.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/blockstorage.h>
15 #include <node/context.h>
16 #include <policy/policy.h>
17 #include <rpc/server.h>
18 #include <test/util/logging.h>
19 #include <test/util/setup_common.h>
20 #include <util/translation.h>
21 #include <validation.h>
22 #include <wallet/coincontrol.h>
23 #include <wallet/context.h>
24 #include <wallet/receive.h>
25 #include <wallet/spend.h>
26 #include <wallet/test/util.h>
28 
29 #include <boost/test/unit_test.hpp>
30 #include <univalue.h>
31 
35 
36 // Ensure that fee levels defined in the wallet are at least as high
37 // as the default levels for node policy.
38 static_assert(DEFAULT_TRANSACTION_MINFEE >= DEFAULT_MIN_RELAY_TX_FEE, "wallet minimum fee is smaller than default relay fee");
39 static_assert(WALLET_INCREMENTAL_RELAY_FEE >= DEFAULT_INCREMENTAL_RELAY_FEE, "wallet incremental fee is smaller than default incremental relay fee");
40 
42 
43 static std::shared_ptr<CWallet> TestLoadWallet(WalletContext& context)
44 {
45  DatabaseOptions options;
46  DatabaseStatus status;
48  std::vector<bilingual_str> warnings;
49  auto database = MakeWalletDatabase("", options, status, error);
50  auto wallet = CWallet::Create(context, "", std::move(database), options.create_flags, error, warnings);
51  if (context.chain) {
52  wallet->postInitProcess();
53  }
54  return wallet;
55 }
56 
57 static void TestUnloadWallet(std::shared_ptr<CWallet>&& wallet)
58 {
60  wallet->m_chain_notifications_handler.reset();
61  UnloadWallet(std::move(wallet));
62 }
63 
64 static CMutableTransaction TestSimpleSpend(const CTransaction& from, uint32_t index, const CKey& key, const CScript& pubkey)
65 {
67  mtx.vout.push_back({from.vout[index].nValue - DEFAULT_TRANSACTION_MAXFEE, pubkey});
68  mtx.vin.push_back({CTxIn{from.GetHash(), index}});
69  FillableSigningProvider keystore;
70  keystore.AddKey(key);
71  std::map<COutPoint, Coin> coins;
72  coins[mtx.vin[0].prevout].out = from.vout[index];
73  std::map<int, bilingual_str> input_errors;
74  BOOST_CHECK(SignTransaction(mtx, &keystore, coins, SIGHASH_ALL, input_errors));
75  return mtx;
76 }
77 
78 static void AddKey(CWallet& wallet, const CKey& key)
79 {
80  auto spk_man = wallet.GetOrCreateLegacyScriptPubKeyMan();
81  LOCK2(wallet.cs_wallet, spk_man->cs_KeyStore);
82  spk_man->AddKeyPubKey(key, key.GetPubKey());
83 }
84 
85 BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions, TestChain100Setup)
86 {
87  // Cap last block file size, and mine new block in a new block file.
88  CBlockIndex* oldTip = m_node.chainman->ActiveChain().Tip();
90  CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
91  CBlockIndex* newTip = m_node.chainman->ActiveChain().Tip();
92 
93  // Verify ScanForWalletTransactions fails to read an unknown start block.
94  {
96  {
97  LOCK(wallet.cs_wallet);
98  wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
99  }
100  AddKey(wallet, coinbaseKey);
101  WalletRescanReserver reserver(wallet);
102  reserver.reserve();
103  CWallet::ScanResult result = wallet.ScanForWalletTransactions({} /* start_block */, 0 /* start_height */, {} /* max_height */, reserver, false /* update */);
108  BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 0);
109  }
110 
111  // Verify ScanForWalletTransactions picks up transactions in both the old
112  // and new block files.
113  {
115  {
116  LOCK(wallet.cs_wallet);
117  wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
118  }
119  AddKey(wallet, coinbaseKey);
120  WalletRescanReserver reserver(wallet);
121  reserver.reserve();
122  CWallet::ScanResult result = wallet.ScanForWalletTransactions(oldTip->GetBlockHash(), oldTip->nHeight, {} /* max_height */, reserver, false /* update */);
125  BOOST_CHECK_EQUAL(result.last_scanned_block, newTip->GetBlockHash());
126  BOOST_CHECK_EQUAL(*result.last_scanned_height, newTip->nHeight);
127  BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 100 * COIN);
128  }
129 
130  // Prune the older block file.
131  {
132  LOCK(cs_main);
133  Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(oldTip->GetBlockPos().nFile);
134  }
135  UnlinkPrunedFiles({oldTip->GetBlockPos().nFile});
136 
137  // Verify ScanForWalletTransactions only picks transactions in the new block
138  // file.
139  {
141  {
142  LOCK(wallet.cs_wallet);
143  wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
144  }
145  AddKey(wallet, coinbaseKey);
146  WalletRescanReserver reserver(wallet);
147  reserver.reserve();
148  CWallet::ScanResult result = wallet.ScanForWalletTransactions(oldTip->GetBlockHash(), oldTip->nHeight, {} /* max_height */, reserver, false /* update */);
151  BOOST_CHECK_EQUAL(result.last_scanned_block, newTip->GetBlockHash());
152  BOOST_CHECK_EQUAL(*result.last_scanned_height, newTip->nHeight);
153  BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 50 * COIN);
154  }
155 
156  // Prune the remaining block file.
157  {
158  LOCK(cs_main);
159  Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(newTip->GetBlockPos().nFile);
160  }
161  UnlinkPrunedFiles({newTip->GetBlockPos().nFile});
162 
163  // Verify ScanForWalletTransactions scans no blocks.
164  {
166  {
167  LOCK(wallet.cs_wallet);
168  wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
169  }
170  AddKey(wallet, coinbaseKey);
171  WalletRescanReserver reserver(wallet);
172  reserver.reserve();
173  CWallet::ScanResult result = wallet.ScanForWalletTransactions(oldTip->GetBlockHash(), oldTip->nHeight, {} /* max_height */, reserver, false /* update */);
175  BOOST_CHECK_EQUAL(result.last_failed_block, newTip->GetBlockHash());
178  BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 0);
179  }
180 }
181 
183 {
184  // Cap last block file size, and mine new block in a new block file.
185  CBlockIndex* oldTip = m_node.chainman->ActiveChain().Tip();
187  CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
188  CBlockIndex* newTip = m_node.chainman->ActiveChain().Tip();
189 
190  // Prune the older block file.
191  {
192  LOCK(cs_main);
193  Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(oldTip->GetBlockPos().nFile);
194  }
195  UnlinkPrunedFiles({oldTip->GetBlockPos().nFile});
196 
197  // Verify importmulti RPC returns failure for a key whose creation time is
198  // before the missing block, and success for a key whose creation time is
199  // after.
200  {
201  std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateDummyWalletDatabase());
202  wallet->SetupLegacyScriptPubKeyMan();
203  WITH_LOCK(wallet->cs_wallet, wallet->SetLastBlockProcessed(newTip->nHeight, newTip->GetBlockHash()));
204  WalletContext context;
205  context.args = &gArgs;
206  AddWallet(context, wallet);
207  UniValue keys;
208  keys.setArray();
209  UniValue key;
210  key.setObject();
211  key.pushKV("scriptPubKey", HexStr(GetScriptForRawPubKey(coinbaseKey.GetPubKey())));
212  key.pushKV("timestamp", 0);
213  key.pushKV("internal", UniValue(true));
214  keys.push_back(key);
215  key.clear();
216  key.setObject();
217  CKey futureKey;
218  futureKey.MakeNewKey(true);
219  key.pushKV("scriptPubKey", HexStr(GetScriptForRawPubKey(futureKey.GetPubKey())));
220  key.pushKV("timestamp", newTip->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1);
221  key.pushKV("internal", UniValue(true));
222  keys.push_back(key);
223  JSONRPCRequest request;
224  request.context = &context;
225  request.params.setArray();
226  request.params.push_back(keys);
227 
228  UniValue response = importmulti().HandleRequest(request);
229  BOOST_CHECK_EQUAL(response.write(),
230  strprintf("[{\"success\":false,\"error\":{\"code\":-1,\"message\":\"Rescan failed for key with creation "
231  "timestamp %d. There was an error reading a block from time %d, which is after or within %d "
232  "seconds of key creation, and could contain transactions pertaining to the key. As a result, "
233  "transactions and coins using this key may not appear in the wallet. This error could be caused "
234  "by pruning or data corruption (see bitcoind log for details) and could be dealt with by "
235  "downloading and rescanning the relevant blocks (see -reindex and -rescan "
236  "options).\"}},{\"success\":true}]",
237  0, oldTip->GetBlockTimeMax(), TIMESTAMP_WINDOW));
238  RemoveWallet(context, wallet, /* load_on_start= */ std::nullopt);
239  }
240 }
241 
242 // Verify importwallet RPC starts rescan at earliest block with timestamp
243 // greater or equal than key birthday. Previously there was a bug where
244 // importwallet RPC would start the scan at the latest block with timestamp less
245 // than or equal to key birthday.
247 {
248  // Create two blocks with same timestamp to verify that importwallet rescan
249  // will pick up both blocks, not just the first.
250  const int64_t BLOCK_TIME = m_node.chainman->ActiveChain().Tip()->GetBlockTimeMax() + 5;
251  SetMockTime(BLOCK_TIME);
252  m_coinbase_txns.emplace_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
253  m_coinbase_txns.emplace_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
254 
255  // Set key birthday to block time increased by the timestamp window, so
256  // rescan will start at the block time.
257  const int64_t KEY_TIME = BLOCK_TIME + TIMESTAMP_WINDOW;
258  SetMockTime(KEY_TIME);
259  m_coinbase_txns.emplace_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
260 
261  std::string backup_file = (gArgs.GetDataDirNet() / "wallet.backup").string();
262 
263  // Import key into wallet and call dumpwallet to create backup file.
264  {
265  WalletContext context;
266  context.args = &gArgs;
267  std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateDummyWalletDatabase());
268  {
269  auto spk_man = wallet->GetOrCreateLegacyScriptPubKeyMan();
270  LOCK2(wallet->cs_wallet, spk_man->cs_KeyStore);
271  spk_man->mapKeyMetadata[coinbaseKey.GetPubKey().GetID()].nCreateTime = KEY_TIME;
272  spk_man->AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey());
273 
274  AddWallet(context, wallet);
275  wallet->SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
276  }
277  JSONRPCRequest request;
278  request.context = &context;
279  request.params.setArray();
280  request.params.push_back(backup_file);
281 
282  ::dumpwallet().HandleRequest(request);
283  RemoveWallet(context, wallet, /* load_on_start= */ std::nullopt);
284  }
285 
286  // Call importwallet RPC and verify all blocks with timestamps >= BLOCK_TIME
287  // were scanned, and no prior blocks were scanned.
288  {
289  std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateDummyWalletDatabase());
290  LOCK(wallet->cs_wallet);
291  wallet->SetupLegacyScriptPubKeyMan();
292 
293  WalletContext context;
294  context.args = &gArgs;
295  JSONRPCRequest request;
296  request.context = &context;
297  request.params.setArray();
298  request.params.push_back(backup_file);
299  AddWallet(context, wallet);
300  wallet->SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
301  ::importwallet().HandleRequest(request);
302  RemoveWallet(context, wallet, /* load_on_start= */ std::nullopt);
303 
304  BOOST_CHECK_EQUAL(wallet->mapWallet.size(), 3U);
305  BOOST_CHECK_EQUAL(m_coinbase_txns.size(), 103U);
306  for (size_t i = 0; i < m_coinbase_txns.size(); ++i) {
307  bool found = wallet->GetWalletTx(m_coinbase_txns[i]->GetHash());
308  bool expected = i >= 100;
309  BOOST_CHECK_EQUAL(found, expected);
310  }
311  }
312 }
313 
314 // Check that GetImmatureCredit() returns a newly calculated value instead of
315 // the cached value after a MarkDirty() call.
316 //
317 // This is a regression test written to verify a bugfix for the immature credit
318 // function. Similar tests probably should be written for the other credit and
319 // debit functions.
320 BOOST_FIXTURE_TEST_CASE(coin_mark_dirty_immature_credit, TestChain100Setup)
321 {
323  auto spk_man = wallet.GetOrCreateLegacyScriptPubKeyMan();
324  CWalletTx wtx(m_coinbase_txns.back());
325 
326  LOCK2(wallet.cs_wallet, spk_man->cs_KeyStore);
327  wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
328 
329  CWalletTx::Confirmation confirm(CWalletTx::Status::CONFIRMED, m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash(), 0);
330  wtx.m_confirm = confirm;
331 
332  // Call GetImmatureCredit() once before adding the key to the wallet to
333  // cache the current immature credit amount, which is 0.
335 
336  // Invalidate the cached value, add the key, and make sure a new immature
337  // credit amount is calculated.
338  wtx.MarkDirty();
339  BOOST_CHECK(spk_man->AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey()));
341 }
342 
343 static int64_t AddTx(ChainstateManager& chainman, CWallet& wallet, uint32_t lockTime, int64_t mockTime, int64_t blockTime)
344 {
346  CWalletTx::Confirmation confirm;
347  tx.nLockTime = lockTime;
348  SetMockTime(mockTime);
349  CBlockIndex* block = nullptr;
350  if (blockTime > 0) {
351  LOCK(cs_main);
352  auto inserted = chainman.BlockIndex().emplace(GetRandHash(), new CBlockIndex);
353  assert(inserted.second);
354  const uint256& hash = inserted.first->first;
355  block = inserted.first->second;
356  block->nTime = blockTime;
357  block->phashBlock = &hash;
358  confirm = {CWalletTx::Status::CONFIRMED, block->nHeight, hash, 0};
359  }
360 
361  // If transaction is already in map, to avoid inconsistencies, unconfirmation
362  // is needed before confirm again with different block.
363  return wallet.AddToWallet(MakeTransactionRef(tx), confirm, [&](CWalletTx& wtx, bool /* new_tx */) {
364  wtx.setUnconfirmed();
365  return true;
366  })->nTimeSmart;
367 }
368 
369 // Simple test to verify assignment of CWalletTx::nSmartTime value. Could be
370 // expanded to cover more corner cases of smart time logic.
371 BOOST_AUTO_TEST_CASE(ComputeTimeSmart)
372 {
373  // New transaction should use clock time if lower than block time.
374  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 100, 120), 100);
375 
376  // Test that updating existing transaction does not change smart time.
377  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 200, 220), 100);
378 
379  // New transaction should use clock time if there's no block time.
380  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 2, 300, 0), 300);
381 
382  // New transaction should use block time if lower than clock time.
383  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 3, 420, 400), 400);
384 
385  // New transaction should use latest entry time if higher than
386  // min(block time, clock time).
387  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 4, 500, 390), 400);
388 
389  // If there are future entries, new transaction should use time of the
390  // newest entry that is no more than 300 seconds ahead of the clock time.
391  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 5, 50, 600), 300);
392 }
393 
394 BOOST_AUTO_TEST_CASE(LoadReceiveRequests)
395 {
396  CTxDestination dest = PKHash();
397  LOCK(m_wallet.cs_wallet);
398  WalletBatch batch{m_wallet.GetDatabase()};
399  m_wallet.SetAddressUsed(batch, dest, true);
400  m_wallet.SetAddressReceiveRequest(batch, dest, "0", "val_rr0");
401  m_wallet.SetAddressReceiveRequest(batch, dest, "1", "val_rr1");
402 
403  auto values = m_wallet.GetAddressReceiveRequests();
404  BOOST_CHECK_EQUAL(values.size(), 2U);
405  BOOST_CHECK_EQUAL(values[0], "val_rr0");
406  BOOST_CHECK_EQUAL(values[1], "val_rr1");
407 }
408 
409 // Test some watch-only LegacyScriptPubKeyMan methods by the procedure of loading (LoadWatchOnly),
410 // checking (HaveWatchOnly), getting (GetWatchPubKey) and removing (RemoveWatchOnly) a
411 // given PubKey, resp. its corresponding P2PK Script. Results of the the impact on
412 // the address -> PubKey map is dependent on whether the PubKey is a point on the curve
413 static void TestWatchOnlyPubKey(LegacyScriptPubKeyMan* spk_man, const CPubKey& add_pubkey)
414 {
415  CScript p2pk = GetScriptForRawPubKey(add_pubkey);
416  CKeyID add_address = add_pubkey.GetID();
417  CPubKey found_pubkey;
418  LOCK(spk_man->cs_KeyStore);
419 
420  // all Scripts (i.e. also all PubKeys) are added to the general watch-only set
421  BOOST_CHECK(!spk_man->HaveWatchOnly(p2pk));
422  spk_man->LoadWatchOnly(p2pk);
423  BOOST_CHECK(spk_man->HaveWatchOnly(p2pk));
424 
425  // only PubKeys on the curve shall be added to the watch-only address -> PubKey map
426  bool is_pubkey_fully_valid = add_pubkey.IsFullyValid();
427  if (is_pubkey_fully_valid) {
428  BOOST_CHECK(spk_man->GetWatchPubKey(add_address, found_pubkey));
429  BOOST_CHECK(found_pubkey == add_pubkey);
430  } else {
431  BOOST_CHECK(!spk_man->GetWatchPubKey(add_address, found_pubkey));
432  BOOST_CHECK(found_pubkey == CPubKey()); // passed key is unchanged
433  }
434 
435  spk_man->RemoveWatchOnly(p2pk);
436  BOOST_CHECK(!spk_man->HaveWatchOnly(p2pk));
437 
438  if (is_pubkey_fully_valid) {
439  BOOST_CHECK(!spk_man->GetWatchPubKey(add_address, found_pubkey));
440  BOOST_CHECK(found_pubkey == add_pubkey); // passed key is unchanged
441  }
442 }
443 
444 // Cryptographically invalidate a PubKey whilst keeping length and first byte
445 static void PollutePubKey(CPubKey& pubkey)
446 {
447  std::vector<unsigned char> pubkey_raw(pubkey.begin(), pubkey.end());
448  std::fill(pubkey_raw.begin()+1, pubkey_raw.end(), 0);
449  pubkey = CPubKey(pubkey_raw);
450  assert(!pubkey.IsFullyValid());
451  assert(pubkey.IsValid());
452 }
453 
454 // Test watch-only logic for PubKeys
455 BOOST_AUTO_TEST_CASE(WatchOnlyPubKeys)
456 {
457  CKey key;
458  CPubKey pubkey;
459  LegacyScriptPubKeyMan* spk_man = m_wallet.GetOrCreateLegacyScriptPubKeyMan();
460 
461  BOOST_CHECK(!spk_man->HaveWatchOnly());
462 
463  // uncompressed valid PubKey
464  key.MakeNewKey(false);
465  pubkey = key.GetPubKey();
466  assert(!pubkey.IsCompressed());
467  TestWatchOnlyPubKey(spk_man, pubkey);
468 
469  // uncompressed cryptographically invalid PubKey
470  PollutePubKey(pubkey);
471  TestWatchOnlyPubKey(spk_man, pubkey);
472 
473  // compressed valid PubKey
474  key.MakeNewKey(true);
475  pubkey = key.GetPubKey();
476  assert(pubkey.IsCompressed());
477  TestWatchOnlyPubKey(spk_man, pubkey);
478 
479  // compressed cryptographically invalid PubKey
480  PollutePubKey(pubkey);
481  TestWatchOnlyPubKey(spk_man, pubkey);
482 
483  // invalid empty PubKey
484  pubkey = CPubKey();
485  TestWatchOnlyPubKey(spk_man, pubkey);
486 }
487 
489 {
490 public:
492  {
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(CreateTransaction(*wallet, {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  }
520 
521  LOCK(wallet->cs_wallet);
522  wallet->SetLastBlockProcessed(wallet->GetLastBlockHeight() + 1, m_node.chainman->ActiveChain().Tip()->GetBlockHash());
523  auto it = wallet->mapWallet.find(tx->GetHash());
524  BOOST_CHECK(it != wallet->mapWallet.end());
525  CWalletTx::Confirmation confirm(CWalletTx::Status::CONFIRMED, m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().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 = ListCoins(*wallet);
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.
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 = ListCoins(*wallet);
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  AvailableCoins(*wallet, 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  AvailableCoins(*wallet, 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 = ListCoins(*wallet);
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 
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;
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 
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 
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.
692  WalletContext context;
693  context.args = &gArgs;
694  context.chain = m_node.chain.get();
695  auto wallet = TestLoadWallet(context);
696  CKey key;
697  key.MakeNewKey(true);
698  AddKey(*wallet, key);
699  TestUnloadWallet(std::move(wallet));
700 
701 
702  // Add log hook to detect AddToWallet events from rescans, blockConnected,
703  // and transactionAddedToMempool notifications
704  int addtx_count = 0;
705  DebugLogHelper addtx_counter("[default wallet] AddToWallet", [&](const std::string* s) {
706  if (s) ++addtx_count;
707  return false;
708  });
709 
710 
711  bool rescan_completed = false;
712  DebugLogHelper rescan_check("[default wallet] Rescan completed", [&](const std::string* s) {
713  if (s) rescan_completed = true;
714  return false;
715  });
716 
717 
718  // Block the queue to prevent the wallet receiving blockConnected and
719  // transactionAddedToMempool notifications, and create block and mempool
720  // transactions paying to the wallet
721  std::promise<void> promise;
723  promise.get_future().wait();
724  });
725  std::string error;
726  m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
727  auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
728  m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
729  auto mempool_tx = TestSimpleSpend(*m_coinbase_txns[1], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
730  BOOST_CHECK(m_node.chain->broadcastTransaction(MakeTransactionRef(mempool_tx), DEFAULT_TRANSACTION_MAXFEE, false, error));
731 
732 
733  // Reload wallet and make sure new transactions are detected despite events
734  // being blocked
735  wallet = TestLoadWallet(context);
736  BOOST_CHECK(rescan_completed);
737  BOOST_CHECK_EQUAL(addtx_count, 2);
738  {
739  LOCK(wallet->cs_wallet);
740  BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_tx.GetHash()), 1U);
741  BOOST_CHECK_EQUAL(wallet->mapWallet.count(mempool_tx.GetHash()), 1U);
742  }
743 
744 
745  // Unblock notification queue and make sure stale blockConnected and
746  // transactionAddedToMempool events are processed
747  promise.set_value();
749  BOOST_CHECK_EQUAL(addtx_count, 4);
750 
751 
752  TestUnloadWallet(std::move(wallet));
753 
754 
755  // Load wallet again, this time creating new block and mempool transactions
756  // paying to the wallet as the wallet finishes loading and syncing the
757  // queue so the events have to be handled immediately. Releasing the wallet
758  // lock during the sync is a little artificial but is needed to avoid a
759  // deadlock during the sync and simulates a new block notification happening
760  // as soon as possible.
761  addtx_count = 0;
762  auto handler = HandleLoadWallet(context, [&](std::unique_ptr<interfaces::Wallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->wallet()->cs_wallet, context.wallets_mutex) {
763  BOOST_CHECK(rescan_completed);
764  m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
765  block_tx = TestSimpleSpend(*m_coinbase_txns[2], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
766  m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
767  mempool_tx = TestSimpleSpend(*m_coinbase_txns[3], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
768  BOOST_CHECK(m_node.chain->broadcastTransaction(MakeTransactionRef(mempool_tx), DEFAULT_TRANSACTION_MAXFEE, false, error));
770  LEAVE_CRITICAL_SECTION(wallet->wallet()->cs_wallet);
772  ENTER_CRITICAL_SECTION(wallet->wallet()->cs_wallet);
774  });
775  wallet = TestLoadWallet(context);
776  BOOST_CHECK_EQUAL(addtx_count, 4);
777  {
778  LOCK(wallet->cs_wallet);
779  BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_tx.GetHash()), 1U);
780  BOOST_CHECK_EQUAL(wallet->mapWallet.count(mempool_tx.GetHash()), 1U);
781  }
782 
783 
784  TestUnloadWallet(std::move(wallet));
785 }
786 
787 BOOST_FIXTURE_TEST_CASE(CreateWalletWithoutChain, BasicTestingSetup)
788 {
789  WalletContext context;
790  context.args = &gArgs;
791  auto wallet = TestLoadWallet(context);
793  UnloadWallet(std::move(wallet));
794 }
795 
797 {
798  gArgs.ForceSetArg("-unsafesqlitesync", "1");
799  WalletContext context;
800  context.args = &gArgs;
801  context.chain = m_node.chain.get();
802  auto wallet = TestLoadWallet(context);
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 
RemoveWallet
bool RemoveWallet(WalletContext &context, const std::shared_ptr< CWallet > &wallet, std::optional< bool > load_on_start, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:116
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:527
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
LOCK2
#define LOCK2(cs1, cs2)
Definition: sync.h:227
policy.h
CMutableTransaction::vin
std::vector< CTxIn > vin
Definition: transaction.h:346
ChainstateManager::BlockIndex
BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:961
ListCoinsTestingSetup::AddTx
CWalletTx & AddTx(CRecipient recipient)
Definition: wallet_tests.cpp:502
LegacyScriptPubKeyMan::GetWatchPubKey
bool GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
Fetches a pubkey from mapWatchKeys if it exists there.
Definition: scriptpubkeyman.cpp:1007
assert
assert(!tx.IsCoinBase())
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
CreateDummyWalletDatabase
std::unique_ptr< WalletDatabase > CreateDummyWalletDatabase()
Return object for accessing dummy database with no read/write capabilities.
Definition: walletdb.cpp:1150
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:160
AddKey
static void AddKey(CWallet &wallet, const CKey &key)
Definition: wallet_tests.cpp:78
UniValue::clear
void clear()
Definition: univalue.cpp:15
CVectorWriter
Definition: streams.h:72
JSONRPCRequest::context
std::any context
Definition: request.h:38
ArgsManager::GetDataDirNet
const fs::path & GetDataDirNet() const
Get data directory path with appended network identifier.
Definition: system.h:282
setup_common.h
importmulti
RPCHelpMan importmulti()
Definition: rpcdump.cpp:1269
DUMMY_SIGNATURE_CREATOR
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
Definition: sign.cpp:577
RPCHelpMan
Definition: util.h:345
handler
bool(* handler)(const std::any &context, HTTPRequest *req, const std::string &strReq)
Definition: rest.cpp:713
FillableSigningProvider
Fillable signing provider that keeps keys in an address->secret map.
Definition: signingprovider.h:91
MAX_BLOCKFILE_SIZE
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
Definition: blockstorage.h:36
AddTx
static int64_t AddTx(ChainstateManager &chainman, CWallet &wallet, uint32_t lockTime, int64_t mockTime, int64_t blockTime)
Definition: wallet_tests.cpp:343
bilingual_str
Bilingual messages:
Definition: translation.h:16
AvailableCoins
void AvailableCoins(const CWallet &wallet, std::vector< COutput > &vCoins, const CCoinControl *coinControl, const CAmount &nMinimumAmount, const CAmount &nMaximumAmount, const CAmount &nMinimumSumAmount, const uint64_t nMaximumCount)
populate vCoins with vector of available COutputs.
Definition: spend.cpp:72
CWallet::ScanResult::last_scanned_height
std::optional< int > last_scanned_height
Definition: wallet.h:521
CWallet::ScanResult::last_scanned_block
uint256 last_scanned_block
Hash and height of most recent block that was successfully scanned.
Definition: wallet.h:520
m_node
NodeContext & m_node
Definition: bitcoin-node.cpp:38
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: transaction.h:278
MakeWalletDatabase
std::unique_ptr< WalletDatabase > MakeWalletDatabase(const std::string &name, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error_string)
Definition: wallet.cpp:2485
WITH_LOCK
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:270
TestUnloadWallet
static void TestUnloadWallet(std::shared_ptr< CWallet > &&wallet)
Definition: wallet_tests.cpp:57
MakeTransactionRef
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:387
ListCoinsTestingSetup::ListCoinsTestingSetup
ListCoinsTestingSetup()
Definition: wallet_tests.cpp:491
CWalletTx::m_confirm
Confirmation m_confirm
Definition: transaction.h:187
wallet
Definition: interfaces.cpp:50
WalletRescanReserver::reserve
bool reserve()
Definition: wallet.h:897
GetBalance
Balance GetBalance(const CWallet &wallet, const int min_depth, bool avoid_reuse)
Definition: receive.cpp:316
CKeyID
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:22
CreateWallet
std::shared_ptr< CWallet > CreateWallet(WalletContext &context, 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:257
DebugLogHelper
Definition: logging.h:14
LegacyScriptPubKeyMan
Definition: scriptpubkeyman.h:250
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
VectorReader
Minimal stream for reading from an existing vector by reference.
Definition: streams.h:133
context.h
BOOST_AUTO_TEST_SUITE_END
BOOST_AUTO_TEST_SUITE_END()
NodeContext::chain
std::unique_ptr< interfaces::Chain > chain
Definition: context.h:50
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
CWallet::ScanResult::FAILURE
@ FAILURE
Definition: wallet.h:515
UniValue
Definition: univalue.h:19
FillableSigningProvider::AddKey
virtual bool AddKey(const CKey &key)
Definition: signingprovider.h:152
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
CBlockIndex::GetBlockTimeMax
int64_t GetBlockTimeMax() const
Definition: chain.h:265
CPubKey::begin
const unsigned char * begin() const
Definition: pubkey.h:113
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
AddWallet
bool AddWallet(WalletContext &context, const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:104
ENTER_CRITICAL_SECTION
#define ENTER_CRITICAL_SECTION(cs)
Definition: sync.h:233
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:488
CTxDestination
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:157
CreateTransaction
bool CreateTransaction(CWallet &wallet, const std::vector< CRecipient > &vecSend, CTransactionRef &tx, CAmount &nFeeRet, int &nChangePosInOut, bilingual_str &error, const CCoinControl &coin_control, FeeCalculation &fee_calc_out, bool sign)
Create a new transaction paying the recipients with a set of coins selected by SelectCoins(); Also cr...
Definition: spend.cpp:908
DUMMY_MAXIMUM_SIGNATURE_CREATOR
const BaseSignatureCreator & DUMMY_MAXIMUM_SIGNATURE_CREATOR
A signature creator that just produces 72-byte empty signatures.
Definition: sign.cpp:578
BOOST_AUTO_TEST_CASE
BOOST_AUTO_TEST_CASE(ComputeTimeSmart)
Definition: wallet_tests.cpp:371
malformed_descriptor
bool malformed_descriptor(std::ios_base::failure e)
Definition: wallet_tests.cpp:649
SignatureData
Definition: sign.h:65
GetScriptForRawPubKey
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
Definition: standard.cpp:356
values
static const int64_t values[]
A selection of numbers that do not trigger int64_t overflow when added/subtracted.
Definition: scriptnum_tests.cpp:17
RPCHelpMan::HandleRequest
UniValue HandleRequest(const JSONRPCRequest &request) const
Definition: util.cpp:563
GetAvailableBalance
CAmount GetAvailableBalance(const CWallet &wallet, const CCoinControl *coinControl)
Definition: spend.cpp:200
CTransaction::vout
const std::vector< CTxOut > vout
Definition: transaction.h:271
OP_EQUAL
@ OP_EQUAL
Definition: script.h:139
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:445
WALLET_INCREMENTAL_RELAY_FEE
static const CAmount WALLET_INCREMENTAL_RELAY_FEE
minimum recommended increment for BIP 125 replacement txs
Definition: wallet.h:87
CPubKey::end
const unsigned char * end() const
Definition: pubkey.h:114
DEFAULT_TRANSACTION_MAXFEE
constexpr CAmount DEFAULT_TRANSACTION_MAXFEE
-maxtxfee default
Definition: wallet.h:99
TestChain100Setup::CreateAndProcessBlock
CBlock CreateAndProcessBlock(const std::vector< CMutableTransaction > &txns, const CScript &scriptPubKey)
Create a new block with just given transactions, coinbase paying to scriptPubKey, and try to add it t...
Definition: setup_common.cpp:237
univalue.h
LegacyScriptPubKeyMan::HaveWatchOnly
bool HaveWatchOnly(const CScript &dest) const
Returns whether the watch-only script is in the wallet.
Definition: scriptpubkeyman.cpp:845
GetRandHash
uint256 GetRandHash() noexcept
Definition: random.cpp:601
CWallet::ScanResult::status
enum CWallet::ScanResult::@17 status
ArgsManager::ForceSetArg
void ForceSetArg(const std::string &strArg, const std::string &strValue)
Definition: system.cpp:622
ListCoinsTestingSetup::~ListCoinsTestingSetup
~ListCoinsTestingSetup()
Definition: wallet_tests.cpp:497
CAmount
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
WalletRescanReserver
RAII object to check and reserve a wallet rescan.
Definition: wallet.h:889
BasicTestingSetup
Basic testing setup.
Definition: setup_common.h:76
TestLoadWallet
static std::shared_ptr< CWallet > TestLoadWallet(WalletContext &context)
Definition: wallet_tests.cpp:43
TestChain100Setup
Testing fixture that pre-creates a 100-block REGTEST-mode block chain.
Definition: setup_common.h:116
uint256
256-bit opaque blob.
Definition: uint256.h:124
WalletContext::wallets_mutex
Mutex wallets_mutex
Definition: context.h:37
CWallet::ScanResult::SUCCESS
@ SUCCESS
Definition: wallet.h:515
CWallet::Create
static std::shared_ptr< CWallet > Create(WalletContext &context, 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:2509
CWallet::ScanResult
Definition: wallet.h:514
HandleLoadWallet
std::unique_ptr< interfaces::Handler > HandleLoadWallet(WalletContext &context, LoadWalletFn load_wallet)
Definition: wallet.cpp:157
GetBlockFileInfo
CBlockFileInfo * GetBlockFileInfo(size_t n)
Get block file info entry for one block file.
Definition: blockstorage.cpp:101
CKey::GetPubKey
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:187
WalletTestingSetup
Testing setup and teardown for wallet.
Definition: wallet_test_fixture.h:20
CWalletTx::Confirmation
Confirmation includes tx status and a triplet of {block height/block hash/tx index in block} at which...
Definition: transaction.h:179
CScript
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:405
DBErrors::LOAD_OK
@ LOAD_OK
CBlockIndex::GetBlockHash
uint256 GetBlockHash() const
Definition: chain.h:246
gArgs
ArgsManager gArgs
Definition: system.cpp:84
logging.h
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:65
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:858
util.h
WALLET_FLAG_DISABLE_PRIVATE_KEYS
@ WALLET_FLAG_DISABLE_PRIVATE_KEYS
Definition: walletutil.h:50
ListCoins
std::map< CTxDestination, std::vector< COutput > > ListCoins(const CWallet &wallet)
Return list of available coins and locked coins grouped by non-change output address.
Definition: spend.cpp:233
CPubKey::IsCompressed
bool IsCompressed() const
Check whether this is a compressed public key.
Definition: pubkey.h:194
UnloadWallet
void UnloadWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly unload and delete the wallet.
Definition: wallet.cpp:188
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:330
OutputType::BECH32
@ BECH32
CMutableTransaction::vout
std::vector< CTxOut > vout
Definition: transaction.h:347
PKHash
Definition: standard.h:79
CachedTxGetImmatureCredit
CAmount CachedTxGetImmatureCredit(const CWallet &wallet, const CWalletTx &wtx, bool fUseCache)
Definition: receive.cpp:163
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:27
uint160
160-bit opaque blob.
Definition: uint256.h:113
CPubKey
An encapsulated public key.
Definition: pubkey.h:32
BasicTestingSetup::m_node
NodeContext m_node
Definition: setup_common.h:78
FEATURE_LATEST
@ FEATURE_LATEST
Definition: walletutil.h:29
base_blob::IsNull
bool IsNull() const
Definition: uint256.h:31
dumpwallet
RPCHelpMan dumpwallet()
Definition: rpcdump.cpp:712
CKey
An encapsulated private key.
Definition: key.h:26
cs_main
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: validation.cpp:116
translation.h
NodeContext::chainman
std::unique_ptr< ChainstateManager > chainman
Definition: context.h:47
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:226
WalletContext::chain
interfaces::Chain * chain
Definition: context.h:35
CWallet
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:228
blockstorage.h
CWalletTx
A transaction with a bunch of additional info that only the owner cares about.
Definition: transaction.h:65
m_wallet
std::shared_ptr< CWallet > m_wallet
Definition: interfaces.cpp:500
TestWatchOnlyPubKey
static void TestWatchOnlyPubKey(LegacyScriptPubKeyMan *spk_man, const CPubKey &add_pubkey)
Definition: wallet_tests.cpp:413
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:885
ListCoinsTestingSetup::wallet
std::unique_ptr< CWallet > wallet
Definition: wallet_tests.cpp:530
FillableSigningProvider::AddKeyPubKey
virtual bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey)
Definition: signingprovider.cpp:118
TestSimpleSpend
static CMutableTransaction TestSimpleSpend(const CTransaction &from, uint32_t index, const CKey &key, const CScript &pubkey)
Definition: wallet_tests.cpp:64
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:864
CPubKey::IsFullyValid
bool IsFullyValid() const
fully validate whether this is a valid public key (more expensive than IsValid())
Definition: pubkey.cpp:292
TestChain100Setup::coinbaseKey
CKey coinbaseKey
Definition: setup_common.h:151
COIN
static const CAmount COIN
Definition: amount.h:14
context.h
BOOST_FIXTURE_TEST_CASE
BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions, TestChain100Setup)
Definition: wallet_tests.cpp:85
CWalletTx::MarkDirty
void MarkDirty()
make sure balances are recalculated
Definition: transaction.h:250
FillableSigningProvider::AddCScript
virtual bool AddCScript(const CScript &redeemScript)
Definition: signingprovider.cpp:153
receive.h
JSONRPCRequest
Definition: request.h:28
WalletDescriptor
Descriptor with some wallet metadata.
Definition: walletutil.h:75
CTransaction::GetHash
const uint256 & GetHash() const
Definition: transaction.h:302
importwallet
RPCHelpMan importwallet()
Definition: rpcdump.cpp:509
LEAVE_CRITICAL_SECTION
#define LEAVE_CRITICAL_SECTION(cs)
Definition: sync.h:239
UpdateInput
void UpdateInput(CTxIn &input, const SignatureData &data)
Definition: sign.cpp:491
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:185
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:279
FillableSigningProvider::cs_KeyStore
RecursiveMutex cs_KeyStore
Definition: signingprovider.h:149
error
bool error(const char *fmt, const Args &... args)
Definition: system.h:49
WalletContext::args
ArgsManager * args
Definition: context.h:36
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:105
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:217
WalletBatch
Access to the wallet database.
Definition: walletdb.h:177
CBlockFileInfo::nSize
unsigned int nSize
number of used bytes of block file
Definition: chain.h:44
UniValue::setObject
bool setObject()
Definition: univalue.cpp:101
WalletContext
WalletContext struct containing references to state shared between CWallet instances,...
Definition: context.h:34
CreateSyncedWallet
std::unique_ptr< CWallet > CreateSyncedWallet(interfaces::Chain &chain, CChain &cchain, const CKey &key)
Definition: util.cpp:17
spend.h
base_blob::begin
unsigned char * begin()
Definition: uint256.h:58
DEFAULT_TRANSACTION_MINFEE
static const CAmount DEFAULT_TRANSACTION_MINFEE
-mintxfee default
Definition: wallet.h:73
BOOST_CHECK
#define BOOST_CHECK(expr)
Definition: object.cpp:17
DatabaseOptions::create_flags
uint64_t create_flags
Definition: db.h:207
BOOST_CHECK_EQUAL
#define BOOST_CHECK_EQUAL(v1, v2)
Definition: object.cpp:18
UnlinkPrunedFiles
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune)
Actually unlink the specified files.
Definition: blockstorage.cpp:200
CPubKey::GetID
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:160
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