Bitcoin Core  22.99.0
P2P Digital Currency
wallet_tests.cpp
Go to the documentation of this file.
1 // Copyright (c) 2012-2021 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 <key_io.h>
15 #include <node/blockstorage.h>
16 #include <node/context.h>
17 #include <policy/policy.h>
18 #include <rpc/server.h>
19 #include <test/util/logging.h>
20 #include <test/util/setup_common.h>
21 #include <util/translation.h>
22 #include <validation.h>
23 #include <wallet/coincontrol.h>
24 #include <wallet/context.h>
25 #include <wallet/receive.h>
26 #include <wallet/spend.h>
27 #include <wallet/test/util.h>
29 
30 #include <boost/test/unit_test.hpp>
31 #include <univalue.h>
32 
35 
36 namespace wallet {
40 
41 // Ensure that fee levels defined in the wallet are at least as high
42 // as the default levels for node policy.
43 static_assert(DEFAULT_TRANSACTION_MINFEE >= DEFAULT_MIN_RELAY_TX_FEE, "wallet minimum fee is smaller than default relay fee");
44 static_assert(WALLET_INCREMENTAL_RELAY_FEE >= DEFAULT_INCREMENTAL_RELAY_FEE, "wallet incremental fee is smaller than default incremental relay fee");
45 
46 BOOST_FIXTURE_TEST_SUITE(wallet_tests, WalletTestingSetup)
47 
48 static const std::shared_ptr<CWallet> TestLoadWallet(WalletContext& context)
49 {
50  DatabaseOptions options;
52  DatabaseStatus status;
54  std::vector<bilingual_str> warnings;
55  auto database = MakeWalletDatabase("", options, status, error);
56  auto wallet = CWallet::Create(context, "", std::move(database), options.create_flags, error, warnings);
57  if (context.chain) {
58  wallet->postInitProcess();
59  }
60  return wallet;
61 }
62 
63 static void TestUnloadWallet(std::shared_ptr<CWallet>&& wallet)
64 {
66  wallet->m_chain_notifications_handler.reset();
67  UnloadWallet(std::move(wallet));
68 }
69 
70 static CMutableTransaction TestSimpleSpend(const CTransaction& from, uint32_t index, const CKey& key, const CScript& pubkey)
71 {
73  mtx.vout.push_back({from.vout[index].nValue - DEFAULT_TRANSACTION_MAXFEE, pubkey});
74  mtx.vin.push_back({CTxIn{from.GetHash(), index}});
75  FillableSigningProvider keystore;
76  keystore.AddKey(key);
77  std::map<COutPoint, Coin> coins;
78  coins[mtx.vin[0].prevout].out = from.vout[index];
79  std::map<int, bilingual_str> input_errors;
80  BOOST_CHECK(SignTransaction(mtx, &keystore, coins, SIGHASH_ALL, input_errors));
81  return mtx;
82 }
83 
84 static void AddKey(CWallet& wallet, const CKey& key)
85 {
86  LOCK(wallet.cs_wallet);
87  FlatSigningProvider provider;
88  std::string error;
89  std::unique_ptr<Descriptor> desc = Parse("combo(" + EncodeSecret(key) + ")", provider, error, /* require_checksum=*/ false);
90  assert(desc);
91  WalletDescriptor w_desc(std::move(desc), 0, 0, 1, 1);
92  if (!wallet.AddWalletDescriptor(w_desc, provider, "", false)) assert(false);
93 }
94 
95 BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions, TestChain100Setup)
96 {
97  // Cap last block file size, and mine new block in a new block file.
98  CBlockIndex* oldTip = m_node.chainman->ActiveChain().Tip();
99  WITH_LOCK(::cs_main, m_node.chainman->m_blockman.GetBlockFileInfo(oldTip->GetBlockPos().nFile)->nSize = MAX_BLOCKFILE_SIZE);
100  CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
101  CBlockIndex* newTip = m_node.chainman->ActiveChain().Tip();
102 
103  // Verify ScanForWalletTransactions fails to read an unknown start block.
104  {
105  CWallet wallet(m_node.chain.get(), "", m_args, CreateDummyWalletDatabase());
106  {
107  LOCK(wallet.cs_wallet);
108  wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
109  wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
110  }
111  AddKey(wallet, coinbaseKey);
112  WalletRescanReserver reserver(wallet);
113  reserver.reserve();
114  CWallet::ScanResult result = wallet.ScanForWalletTransactions({} /* start_block */, 0 /* start_height */, {} /* max_height */, reserver, false /* update */);
119  BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 0);
120  }
121 
122  // Verify ScanForWalletTransactions picks up transactions in both the old
123  // and new block files.
124  {
125  CWallet wallet(m_node.chain.get(), "", m_args, CreateDummyWalletDatabase());
126  {
127  LOCK(wallet.cs_wallet);
128  wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
129  wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
130  }
131  AddKey(wallet, coinbaseKey);
132  WalletRescanReserver reserver(wallet);
133  reserver.reserve();
134  CWallet::ScanResult result = wallet.ScanForWalletTransactions(oldTip->GetBlockHash(), oldTip->nHeight, {} /* max_height */, reserver, false /* update */);
137  BOOST_CHECK_EQUAL(result.last_scanned_block, newTip->GetBlockHash());
138  BOOST_CHECK_EQUAL(*result.last_scanned_height, newTip->nHeight);
139  BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 100 * COIN);
140  }
141 
142  // Prune the older block file.
143  {
144  LOCK(cs_main);
145  Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(oldTip->GetBlockPos().nFile);
146  }
147  UnlinkPrunedFiles({oldTip->GetBlockPos().nFile});
148 
149  // Verify ScanForWalletTransactions only picks transactions in the new block
150  // file.
151  {
152  CWallet wallet(m_node.chain.get(), "", m_args, CreateDummyWalletDatabase());
153  {
154  LOCK(wallet.cs_wallet);
155  wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
156  wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
157  }
158  AddKey(wallet, coinbaseKey);
159  WalletRescanReserver reserver(wallet);
160  reserver.reserve();
161  CWallet::ScanResult result = wallet.ScanForWalletTransactions(oldTip->GetBlockHash(), oldTip->nHeight, {} /* max_height */, reserver, false /* update */);
164  BOOST_CHECK_EQUAL(result.last_scanned_block, newTip->GetBlockHash());
165  BOOST_CHECK_EQUAL(*result.last_scanned_height, newTip->nHeight);
166  BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 50 * COIN);
167  }
168 
169  // Prune the remaining block file.
170  {
171  LOCK(cs_main);
172  Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(newTip->GetBlockPos().nFile);
173  }
174  UnlinkPrunedFiles({newTip->GetBlockPos().nFile});
175 
176  // Verify ScanForWalletTransactions scans no blocks.
177  {
178  CWallet wallet(m_node.chain.get(), "", m_args, CreateDummyWalletDatabase());
179  {
180  LOCK(wallet.cs_wallet);
181  wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
182  wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
183  }
184  AddKey(wallet, coinbaseKey);
185  WalletRescanReserver reserver(wallet);
186  reserver.reserve();
187  CWallet::ScanResult result = wallet.ScanForWalletTransactions(oldTip->GetBlockHash(), oldTip->nHeight, {} /* max_height */, reserver, false /* update */);
189  BOOST_CHECK_EQUAL(result.last_failed_block, newTip->GetBlockHash());
192  BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 0);
193  }
194 }
195 
197 {
198  // Cap last block file size, and mine new block in a new block file.
199  CBlockIndex* oldTip = m_node.chainman->ActiveChain().Tip();
200  WITH_LOCK(::cs_main, m_node.chainman->m_blockman.GetBlockFileInfo(oldTip->GetBlockPos().nFile)->nSize = MAX_BLOCKFILE_SIZE);
201  CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
202  CBlockIndex* newTip = m_node.chainman->ActiveChain().Tip();
203 
204  // Prune the older block file.
205  {
206  LOCK(cs_main);
207  Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(oldTip->GetBlockPos().nFile);
208  }
209  UnlinkPrunedFiles({oldTip->GetBlockPos().nFile});
210 
211  // Verify importmulti RPC returns failure for a key whose creation time is
212  // before the missing block, and success for a key whose creation time is
213  // after.
214  {
215  const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", m_args, CreateDummyWalletDatabase());
216  wallet->SetupLegacyScriptPubKeyMan();
217  WITH_LOCK(wallet->cs_wallet, wallet->SetLastBlockProcessed(newTip->nHeight, newTip->GetBlockHash()));
219  context.args = &gArgs;
221  UniValue keys;
222  keys.setArray();
223  UniValue key;
224  key.setObject();
225  key.pushKV("scriptPubKey", HexStr(GetScriptForRawPubKey(coinbaseKey.GetPubKey())));
226  key.pushKV("timestamp", 0);
227  key.pushKV("internal", UniValue(true));
228  keys.push_back(key);
229  key.clear();
230  key.setObject();
231  CKey futureKey;
232  futureKey.MakeNewKey(true);
233  key.pushKV("scriptPubKey", HexStr(GetScriptForRawPubKey(futureKey.GetPubKey())));
234  key.pushKV("timestamp", newTip->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1);
235  key.pushKV("internal", UniValue(true));
236  keys.push_back(key);
237  JSONRPCRequest request;
238  request.context = &context;
239  request.params.setArray();
240  request.params.push_back(keys);
241 
242  UniValue response = importmulti().HandleRequest(request);
243  BOOST_CHECK_EQUAL(response.write(),
244  strprintf("[{\"success\":false,\"error\":{\"code\":-1,\"message\":\"Rescan failed for key with creation "
245  "timestamp %d. There was an error reading a block from time %d, which is after or within %d "
246  "seconds of key creation, and could contain transactions pertaining to the key. As a result, "
247  "transactions and coins using this key may not appear in the wallet. This error could be caused "
248  "by pruning or data corruption (see bitcoind log for details) and could be dealt with by "
249  "downloading and rescanning the relevant blocks (see -reindex option and rescanblockchain "
250  "RPC).\"}},{\"success\":true}]",
251  0, oldTip->GetBlockTimeMax(), TIMESTAMP_WINDOW));
252  RemoveWallet(context, wallet, /* load_on_start= */ std::nullopt);
253  }
254 }
255 
256 // Verify importwallet RPC starts rescan at earliest block with timestamp
257 // greater or equal than key birthday. Previously there was a bug where
258 // importwallet RPC would start the scan at the latest block with timestamp less
259 // than or equal to key birthday.
261 {
262  // Create two blocks with same timestamp to verify that importwallet rescan
263  // will pick up both blocks, not just the first.
264  const int64_t BLOCK_TIME = m_node.chainman->ActiveChain().Tip()->GetBlockTimeMax() + 5;
265  SetMockTime(BLOCK_TIME);
266  m_coinbase_txns.emplace_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
267  m_coinbase_txns.emplace_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
268 
269  // Set key birthday to block time increased by the timestamp window, so
270  // rescan will start at the block time.
271  const int64_t KEY_TIME = BLOCK_TIME + TIMESTAMP_WINDOW;
272  SetMockTime(KEY_TIME);
273  m_coinbase_txns.emplace_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
274 
275  std::string backup_file = fs::PathToString(gArgs.GetDataDirNet() / "wallet.backup");
276 
277  // Import key into wallet and call dumpwallet to create backup file.
278  {
280  context.args = &gArgs;
281  const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", m_args, CreateDummyWalletDatabase());
282  {
283  auto spk_man = wallet->GetOrCreateLegacyScriptPubKeyMan();
284  LOCK2(wallet->cs_wallet, spk_man->cs_KeyStore);
285  spk_man->mapKeyMetadata[coinbaseKey.GetPubKey().GetID()].nCreateTime = KEY_TIME;
286  spk_man->AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey());
287 
289  wallet->SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
290  }
291  JSONRPCRequest request;
292  request.context = &context;
293  request.params.setArray();
294  request.params.push_back(backup_file);
295 
297  RemoveWallet(context, wallet, /* load_on_start= */ std::nullopt);
298  }
299 
300  // Call importwallet RPC and verify all blocks with timestamps >= BLOCK_TIME
301  // were scanned, and no prior blocks were scanned.
302  {
303  const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", m_args, CreateDummyWalletDatabase());
304  LOCK(wallet->cs_wallet);
305  wallet->SetupLegacyScriptPubKeyMan();
306 
308  context.args = &gArgs;
309  JSONRPCRequest request;
310  request.context = &context;
311  request.params.setArray();
312  request.params.push_back(backup_file);
314  wallet->SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
316  RemoveWallet(context, wallet, /* load_on_start= */ std::nullopt);
317 
318  BOOST_CHECK_EQUAL(wallet->mapWallet.size(), 3U);
319  BOOST_CHECK_EQUAL(m_coinbase_txns.size(), 103U);
320  for (size_t i = 0; i < m_coinbase_txns.size(); ++i) {
321  bool found = wallet->GetWalletTx(m_coinbase_txns[i]->GetHash());
322  bool expected = i >= 100;
323  BOOST_CHECK_EQUAL(found, expected);
324  }
325  }
326 }
327 
328 // Check that GetImmatureCredit() returns a newly calculated value instead of
329 // the cached value after a MarkDirty() call.
330 //
331 // This is a regression test written to verify a bugfix for the immature credit
332 // function. Similar tests probably should be written for the other credit and
333 // debit functions.
334 BOOST_FIXTURE_TEST_CASE(coin_mark_dirty_immature_credit, TestChain100Setup)
335 {
336  CWallet wallet(m_node.chain.get(), "", m_args, CreateDummyWalletDatabase());
337  CWalletTx wtx{m_coinbase_txns.back(), TxStateConfirmed{m_node.chainman->ActiveChain().Tip()->GetBlockHash(), m_node.chainman->ActiveChain().Height(), /*position_in_block=*/0}};
338 
339  LOCK(wallet.cs_wallet);
340  wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
341  wallet.SetupDescriptorScriptPubKeyMans();
342 
343  wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
344 
345  // Call GetImmatureCredit() once before adding the key to the wallet to
346  // cache the current immature credit amount, which is 0.
348 
349  // Invalidate the cached value, add the key, and make sure a new immature
350  // credit amount is calculated.
351  wtx.MarkDirty();
352  AddKey(wallet, coinbaseKey);
354 }
355 
356 static int64_t AddTx(ChainstateManager& chainman, CWallet& wallet, uint32_t lockTime, int64_t mockTime, int64_t blockTime)
357 {
359  TxState state = TxStateInactive{};
360  tx.nLockTime = lockTime;
361  SetMockTime(mockTime);
362  CBlockIndex* block = nullptr;
363  if (blockTime > 0) {
364  LOCK(cs_main);
365  auto inserted = chainman.BlockIndex().emplace(GetRandHash(), new CBlockIndex);
366  assert(inserted.second);
367  const uint256& hash = inserted.first->first;
368  block = inserted.first->second;
369  block->nTime = blockTime;
370  block->phashBlock = &hash;
371  state = TxStateConfirmed{hash, block->nHeight, /*position_in_block=*/0};
372  }
373  return wallet.AddToWallet(MakeTransactionRef(tx), state, [&](CWalletTx& wtx, bool /* new_tx */) {
374  // Assign wtx.m_state to simplify test and avoid the need to simulate
375  // reorg events. Without this, AddToWallet asserts false when the same
376  // transaction is confirmed in different blocks.
377  wtx.m_state = state;
378  return true;
379  })->nTimeSmart;
380 }
381 
382 // Simple test to verify assignment of CWalletTx::nSmartTime value. Could be
383 // expanded to cover more corner cases of smart time logic.
384 BOOST_AUTO_TEST_CASE(ComputeTimeSmart)
385 {
386  // New transaction should use clock time if lower than block time.
387  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 100, 120), 100);
388 
389  // Test that updating existing transaction does not change smart time.
390  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 200, 220), 100);
391 
392  // New transaction should use clock time if there's no block time.
393  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 2, 300, 0), 300);
394 
395  // New transaction should use block time if lower than clock time.
396  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 3, 420, 400), 400);
397 
398  // New transaction should use latest entry time if higher than
399  // min(block time, clock time).
400  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 4, 500, 390), 400);
401 
402  // If there are future entries, new transaction should use time of the
403  // newest entry that is no more than 300 seconds ahead of the clock time.
404  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 5, 50, 600), 300);
405 }
406 
407 BOOST_AUTO_TEST_CASE(LoadReceiveRequests)
408 {
409  CTxDestination dest = PKHash();
410  LOCK(m_wallet.cs_wallet);
411  WalletBatch batch{m_wallet.GetDatabase()};
412  m_wallet.SetAddressUsed(batch, dest, true);
413  m_wallet.SetAddressReceiveRequest(batch, dest, "0", "val_rr0");
414  m_wallet.SetAddressReceiveRequest(batch, dest, "1", "val_rr1");
415 
416  auto values = m_wallet.GetAddressReceiveRequests();
417  BOOST_CHECK_EQUAL(values.size(), 2U);
418  BOOST_CHECK_EQUAL(values[0], "val_rr0");
419  BOOST_CHECK_EQUAL(values[1], "val_rr1");
420 }
421 
422 // Test some watch-only LegacyScriptPubKeyMan methods by the procedure of loading (LoadWatchOnly),
423 // checking (HaveWatchOnly), getting (GetWatchPubKey) and removing (RemoveWatchOnly) a
424 // given PubKey, resp. its corresponding P2PK Script. Results of the the impact on
425 // the address -> PubKey map is dependent on whether the PubKey is a point on the curve
426 static void TestWatchOnlyPubKey(LegacyScriptPubKeyMan* spk_man, const CPubKey& add_pubkey)
427 {
428  CScript p2pk = GetScriptForRawPubKey(add_pubkey);
429  CKeyID add_address = add_pubkey.GetID();
430  CPubKey found_pubkey;
431  LOCK(spk_man->cs_KeyStore);
432 
433  // all Scripts (i.e. also all PubKeys) are added to the general watch-only set
434  BOOST_CHECK(!spk_man->HaveWatchOnly(p2pk));
435  spk_man->LoadWatchOnly(p2pk);
436  BOOST_CHECK(spk_man->HaveWatchOnly(p2pk));
437 
438  // only PubKeys on the curve shall be added to the watch-only address -> PubKey map
439  bool is_pubkey_fully_valid = add_pubkey.IsFullyValid();
440  if (is_pubkey_fully_valid) {
441  BOOST_CHECK(spk_man->GetWatchPubKey(add_address, found_pubkey));
442  BOOST_CHECK(found_pubkey == add_pubkey);
443  } else {
444  BOOST_CHECK(!spk_man->GetWatchPubKey(add_address, found_pubkey));
445  BOOST_CHECK(found_pubkey == CPubKey()); // passed key is unchanged
446  }
447 
448  spk_man->RemoveWatchOnly(p2pk);
449  BOOST_CHECK(!spk_man->HaveWatchOnly(p2pk));
450 
451  if (is_pubkey_fully_valid) {
452  BOOST_CHECK(!spk_man->GetWatchPubKey(add_address, found_pubkey));
453  BOOST_CHECK(found_pubkey == add_pubkey); // passed key is unchanged
454  }
455 }
456 
457 // Cryptographically invalidate a PubKey whilst keeping length and first byte
458 static void PollutePubKey(CPubKey& pubkey)
459 {
460  std::vector<unsigned char> pubkey_raw(pubkey.begin(), pubkey.end());
461  std::fill(pubkey_raw.begin()+1, pubkey_raw.end(), 0);
462  pubkey = CPubKey(pubkey_raw);
463  assert(!pubkey.IsFullyValid());
464  assert(pubkey.IsValid());
465 }
466 
467 // Test watch-only logic for PubKeys
468 BOOST_AUTO_TEST_CASE(WatchOnlyPubKeys)
469 {
470  CKey key;
471  CPubKey pubkey;
472  LegacyScriptPubKeyMan* spk_man = m_wallet.GetOrCreateLegacyScriptPubKeyMan();
473 
474  BOOST_CHECK(!spk_man->HaveWatchOnly());
475 
476  // uncompressed valid PubKey
477  key.MakeNewKey(false);
478  pubkey = key.GetPubKey();
479  assert(!pubkey.IsCompressed());
480  TestWatchOnlyPubKey(spk_man, pubkey);
481 
482  // uncompressed cryptographically invalid PubKey
483  PollutePubKey(pubkey);
484  TestWatchOnlyPubKey(spk_man, pubkey);
485 
486  // compressed valid PubKey
487  key.MakeNewKey(true);
488  pubkey = key.GetPubKey();
489  assert(pubkey.IsCompressed());
490  TestWatchOnlyPubKey(spk_man, pubkey);
491 
492  // compressed cryptographically invalid PubKey
493  PollutePubKey(pubkey);
494  TestWatchOnlyPubKey(spk_man, pubkey);
495 
496  // invalid empty PubKey
497  pubkey = CPubKey();
498  TestWatchOnlyPubKey(spk_man, pubkey);
499 }
500 
502 {
503 public:
505  {
508  }
509 
511  {
512  wallet.reset();
513  }
514 
516  {
517  CTransactionRef tx;
518  CAmount fee;
519  int changePos = -1;
521  CCoinControl dummy;
522  FeeCalculation fee_calc_out;
523  {
524  BOOST_CHECK(CreateTransaction(*wallet, {recipient}, tx, fee, changePos, error, dummy, fee_calc_out));
525  }
526  wallet->CommitTransaction(tx, {}, {});
527  CMutableTransaction blocktx;
528  {
529  LOCK(wallet->cs_wallet);
530  blocktx = CMutableTransaction(*wallet->mapWallet.at(tx->GetHash()).tx);
531  }
533 
534  LOCK(wallet->cs_wallet);
535  wallet->SetLastBlockProcessed(wallet->GetLastBlockHeight() + 1, m_node.chainman->ActiveChain().Tip()->GetBlockHash());
536  auto it = wallet->mapWallet.find(tx->GetHash());
537  BOOST_CHECK(it != wallet->mapWallet.end());
538  it->second.m_state = TxStateConfirmed{m_node.chainman->ActiveChain().Tip()->GetBlockHash(), m_node.chainman->ActiveChain().Height(), /*position_in_block=*/1};
539  return it->second;
540  }
541 
542  std::unique_ptr<CWallet> wallet;
543 };
544 
546 {
547  std::string coinbaseAddress = coinbaseKey.GetPubKey().GetID().ToString();
548 
549  // Confirm ListCoins initially returns 1 coin grouped under coinbaseKey
550  // address.
551  std::map<CTxDestination, std::vector<COutput>> list;
552  {
553  LOCK(wallet->cs_wallet);
554  list = ListCoins(*wallet);
555  }
556  BOOST_CHECK_EQUAL(list.size(), 1U);
557  BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
558  BOOST_CHECK_EQUAL(list.begin()->second.size(), 1U);
559 
560  // Check initial balance from one mature coinbase transaction.
562 
563  // Add a transaction creating a change address, and confirm ListCoins still
564  // returns the coin associated with the change address underneath the
565  // coinbaseKey pubkey, even though the change address has a different
566  // pubkey.
567  AddTx(CRecipient{GetScriptForRawPubKey({}), 1 * COIN, false /* subtract fee */});
568  {
569  LOCK(wallet->cs_wallet);
570  list = ListCoins(*wallet);
571  }
572  BOOST_CHECK_EQUAL(list.size(), 1U);
573  BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
574  BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
575 
576  // Lock both coins. Confirm number of available coins drops to 0.
577  {
578  LOCK(wallet->cs_wallet);
579  std::vector<COutput> available;
580  AvailableCoins(*wallet, available);
581  BOOST_CHECK_EQUAL(available.size(), 2U);
582  }
583  for (const auto& group : list) {
584  for (const auto& coin : group.second) {
585  LOCK(wallet->cs_wallet);
586  wallet->LockCoin(COutPoint(coin.tx->GetHash(), coin.i));
587  }
588  }
589  {
590  LOCK(wallet->cs_wallet);
591  std::vector<COutput> available;
592  AvailableCoins(*wallet, available);
593  BOOST_CHECK_EQUAL(available.size(), 0U);
594  }
595  // Confirm ListCoins still returns same result as before, despite coins
596  // being locked.
597  {
598  LOCK(wallet->cs_wallet);
599  list = ListCoins(*wallet);
600  }
601  BOOST_CHECK_EQUAL(list.size(), 1U);
602  BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
603  BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
604 }
605 
607 {
608  {
609  const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", m_args, CreateDummyWalletDatabase());
610  wallet->SetupLegacyScriptPubKeyMan();
611  wallet->SetMinVersion(FEATURE_LATEST);
613  BOOST_CHECK(!wallet->TopUpKeyPool(1000));
614  CTxDestination dest;
616  BOOST_CHECK(!wallet->GetNewDestination(OutputType::BECH32, "", dest, error));
617  }
618  {
619  const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", m_args, CreateDummyWalletDatabase());
620  LOCK(wallet->cs_wallet);
621  wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
622  wallet->SetMinVersion(FEATURE_LATEST);
624  CTxDestination dest;
626  BOOST_CHECK(!wallet->GetNewDestination(OutputType::BECH32, "", dest, error));
627  }
628 }
629 
630 // Explicit calculation which is used to test the wallet constant
631 // We get the same virtual size due to rounding(weight/4) for both use_max_sig values
632 static size_t CalculateNestedKeyhashInputSize(bool use_max_sig)
633 {
634  // Generate ephemeral valid pubkey
635  CKey key;
636  key.MakeNewKey(true);
637  CPubKey pubkey = key.GetPubKey();
638 
639  // Generate pubkey hash
640  uint160 key_hash(Hash160(pubkey));
641 
642  // Create inner-script to enter into keystore. Key hash can't be 0...
643  CScript inner_script = CScript() << OP_0 << std::vector<unsigned char>(key_hash.begin(), key_hash.end());
644 
645  // Create outer P2SH script for the output
646  uint160 script_id(Hash160(inner_script));
647  CScript script_pubkey = CScript() << OP_HASH160 << std::vector<unsigned char>(script_id.begin(), script_id.end()) << OP_EQUAL;
648 
649  // Add inner-script to key store and key to watchonly
650  FillableSigningProvider keystore;
651  keystore.AddCScript(inner_script);
652  keystore.AddKeyPubKey(key, pubkey);
653 
654  // Fill in dummy signatures for fee calculation.
655  SignatureData sig_data;
656 
657  if (!ProduceSignature(keystore, use_max_sig ? DUMMY_MAXIMUM_SIGNATURE_CREATOR : DUMMY_SIGNATURE_CREATOR, script_pubkey, sig_data)) {
658  // We're hand-feeding it correct arguments; shouldn't happen
659  assert(false);
660  }
661 
662  CTxIn tx_in;
663  UpdateInput(tx_in, sig_data);
664  return (size_t)GetVirtualTransactionInputSize(tx_in);
665 }
666 
668 {
671 }
672 
673 bool malformed_descriptor(std::ios_base::failure e)
674 {
675  std::string s(e.what());
676  return s.find("Missing checksum") != std::string::npos;
677 }
678 
680 {
681  std::vector<unsigned char> malformed_record;
682  CVectorWriter vw(0, 0, malformed_record, 0);
683  vw << std::string("notadescriptor");
684  vw << (uint64_t)0;
685  vw << (int32_t)0;
686  vw << (int32_t)0;
687  vw << (int32_t)1;
688 
689  SpanReader vr{0, 0, malformed_record};
690  WalletDescriptor w_desc;
691  BOOST_CHECK_EXCEPTION(vr >> w_desc, std::ios_base::failure, malformed_descriptor);
692 }
693 
713 {
714  gArgs.ForceSetArg("-unsafesqlitesync", "1");
715  // Create new wallet with known key and unload it.
717  context.args = &gArgs;
718  context.chain = m_node.chain.get();
719  auto wallet = TestLoadWallet(context);
720  CKey key;
721  key.MakeNewKey(true);
722  AddKey(*wallet, key);
723  TestUnloadWallet(std::move(wallet));
724 
725 
726  // Add log hook to detect AddToWallet events from rescans, blockConnected,
727  // and transactionAddedToMempool notifications
728  int addtx_count = 0;
729  DebugLogHelper addtx_counter("[default wallet] AddToWallet", [&](const std::string* s) {
730  if (s) ++addtx_count;
731  return false;
732  });
733 
734 
735  bool rescan_completed = false;
736  DebugLogHelper rescan_check("[default wallet] Rescan completed", [&](const std::string* s) {
737  if (s) rescan_completed = true;
738  return false;
739  });
740 
741 
742  // Block the queue to prevent the wallet receiving blockConnected and
743  // transactionAddedToMempool notifications, and create block and mempool
744  // transactions paying to the wallet
745  std::promise<void> promise;
747  promise.get_future().wait();
748  });
749  std::string error;
750  m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
751  auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
752  m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
753  auto mempool_tx = TestSimpleSpend(*m_coinbase_txns[1], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
754  BOOST_CHECK(m_node.chain->broadcastTransaction(MakeTransactionRef(mempool_tx), DEFAULT_TRANSACTION_MAXFEE, false, error));
755 
756 
757  // Reload wallet and make sure new transactions are detected despite events
758  // being blocked
760  BOOST_CHECK(rescan_completed);
761  BOOST_CHECK_EQUAL(addtx_count, 2);
762  {
763  LOCK(wallet->cs_wallet);
764  BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_tx.GetHash()), 1U);
765  BOOST_CHECK_EQUAL(wallet->mapWallet.count(mempool_tx.GetHash()), 1U);
766  }
767 
768 
769  // Unblock notification queue and make sure stale blockConnected and
770  // transactionAddedToMempool events are processed
771  promise.set_value();
773  BOOST_CHECK_EQUAL(addtx_count, 4);
774 
775 
776  TestUnloadWallet(std::move(wallet));
777 
778 
779  // Load wallet again, this time creating new block and mempool transactions
780  // paying to the wallet as the wallet finishes loading and syncing the
781  // queue so the events have to be handled immediately. Releasing the wallet
782  // lock during the sync is a little artificial but is needed to avoid a
783  // deadlock during the sync and simulates a new block notification happening
784  // as soon as possible.
785  addtx_count = 0;
786  auto handler = HandleLoadWallet(context, [&](std::unique_ptr<interfaces::Wallet> wallet) {
787  BOOST_CHECK(rescan_completed);
788  m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
789  block_tx = TestSimpleSpend(*m_coinbase_txns[2], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
790  m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
791  mempool_tx = TestSimpleSpend(*m_coinbase_txns[3], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
792  BOOST_CHECK(m_node.chain->broadcastTransaction(MakeTransactionRef(mempool_tx), DEFAULT_TRANSACTION_MAXFEE, false, error));
794  });
796  BOOST_CHECK_EQUAL(addtx_count, 4);
797  {
798  LOCK(wallet->cs_wallet);
799  BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_tx.GetHash()), 1U);
800  BOOST_CHECK_EQUAL(wallet->mapWallet.count(mempool_tx.GetHash()), 1U);
801  }
802 
803 
804  TestUnloadWallet(std::move(wallet));
805 }
806 
807 BOOST_FIXTURE_TEST_CASE(CreateWalletWithoutChain, BasicTestingSetup)
808 {
810  context.args = &gArgs;
811  auto wallet = TestLoadWallet(context);
813  UnloadWallet(std::move(wallet));
814 }
815 
817 {
818  gArgs.ForceSetArg("-unsafesqlitesync", "1");
820  context.args = &gArgs;
821  context.chain = m_node.chain.get();
822  auto wallet = TestLoadWallet(context);
823  AddKey(*wallet, coinbaseKey);
824 
825  // rescan to ensure coinbase transactions from test fixture are picked up by the wallet
826  {
827  WalletRescanReserver reserver(*wallet);
828  reserver.reserve();
829  wallet->ScanForWalletTransactions(m_node.chain->getBlockHash(0), 0, /* max height= */ {}, reserver, /* update= */ true);
830  }
831  // create one more block to get the first block coinbase to maturity
832  m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
833  // spend first coinbase tx
834  auto spend_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
835  CreateAndProcessBlock({spend_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
836 
838 
839  {
840  auto spend_tx_hash = spend_tx.GetHash();
841  auto prev_hash = m_coinbase_txns[0]->GetHash();
842 
843  LOCK(wallet->cs_wallet);
844  BOOST_CHECK(wallet->HasWalletSpend(prev_hash));
845  BOOST_CHECK_EQUAL(wallet->mapWallet.count(spend_tx_hash), 1u);
846 
847  std::vector<uint256> vHashIn{spend_tx_hash}, vHashOut;
848  BOOST_CHECK_EQUAL(wallet->ZapSelectTx(vHashIn, vHashOut), DBErrors::LOAD_OK);
849 
850  BOOST_CHECK(!wallet->HasWalletSpend(prev_hash));
851  BOOST_CHECK_EQUAL(wallet->mapWallet.count(spend_tx_hash), 0u);
852  }
853 
854  TestUnloadWallet(std::move(wallet));
855 }
856 
858 } // namespace wallet
GetVirtualTransactionInputSize
int64_t GetVirtualTransactionInputSize(const CTxIn &txin, int64_t nSigOpCost, unsigned int bytes_per_sigop)
Definition: policy.cpp:292
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
wallet::malformed_descriptor
bool malformed_descriptor(std::ios_base::failure e)
Definition: wallet_tests.cpp:673
Parse
std::unique_ptr< Descriptor > Parse(const std::string &descriptor, FlatSigningProvider &out, std::string &error, bool require_checksum)
Parse a descriptor string.
Definition: descriptor.cpp:1394
BasicTestingSetup::m_node
node::NodeContext m_node
Definition: setup_common.h:85
assert
assert(!tx.IsCoinBase())
wallet::ListCoinsTestingSetup::~ListCoinsTestingSetup
~ListCoinsTestingSetup()
Definition: wallet_tests.cpp:510
CBlockIndex::phashBlock
const uint256 * phashBlock
pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
Definition: chain.h:152
CBlockIndex::nTime
uint32_t nTime
Definition: chain.h:203
wallet.h
CKey::MakeNewKey
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
Definition: key.cpp:160
wallet::AddWallet
bool AddWallet(WalletContext &context, const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:110
wallet::WalletRescanReserver
RAII object to check and reserve a wallet rescan.
Definition: wallet.h:902
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:288
key_io.h
wallet::DatabaseStatus
DatabaseStatus
Definition: db.h:213
setup_common.h
DUMMY_SIGNATURE_CREATOR
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
Definition: sign.cpp:580
RPCHelpMan
Definition: util.h:345
wallet::CWallet::ScanResult::last_scanned_block
uint256 last_scanned_block
Hash and height of most recent block that was successfully scanned.
Definition: wallet.h:529
wallet::HandleLoadWallet
std::unique_ptr< interfaces::Handler > HandleLoadWallet(WalletContext &context, LoadWalletFn load_wallet)
Definition: wallet.cpp:163
handler
bool(* handler)(const std::any &context, HTTPRequest *req, const std::string &strReq)
Definition: rest.cpp:927
FillableSigningProvider
Fillable signing provider that keeps keys in an address->secret map.
Definition: signingprovider.h:90
bilingual_str
Bilingual messages:
Definition: translation.h:16
wallet::CWalletTx::m_state
TxState m_state
Definition: transaction.h:220
wallet::CWallet::ScanResult::FAILURE
@ FAILURE
Definition: wallet.h:524
wallet::ListCoinsTestingSetup::ListCoinsTestingSetup
ListCoinsTestingSetup()
Definition: wallet_tests.cpp:504
CBlockIndex::nHeight
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:161
m_node
node::NodeContext m_node
Definition: bitcoin-gui.cpp:36
wallet::dumpwallet
RPCHelpMan dumpwallet()
Definition: backup.cpp:684
wallet::WALLET_FLAG_DESCRIPTORS
@ WALLET_FLAG_DESCRIPTORS
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:66
wallet::CRecipient
Definition: wallet.h:221
WITH_LOCK
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:270
MakeTransactionRef
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:387
ChainstateManager::BlockIndex
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:899
wallet::GetAvailableBalance
CAmount GetAvailableBalance(const CWallet &wallet, const CCoinControl *coinControl)
Definition: spend.cpp:217
wallet
Definition: node.h:38
wallet::importmulti
RPCHelpMan importmulti()
Definition: backup.cpp:1244
CKeyID
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:23
fs::PathToString
static std::string PathToString(const path &path)
Convert path object to byte string.
Definition: fs.h:120
DebugLogHelper
Definition: logging.h:14
UniValue::write
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
Definition: univalue_write.cpp:28
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
context.h
wallet::CWalletTx
A transaction with a bunch of additional info that only the owner cares about.
Definition: transaction.h:137
BOOST_AUTO_TEST_SUITE_END
BOOST_AUTO_TEST_SUITE_END()
wallet
std::shared_ptr< CWallet > wallet
Definition: notifications.cpp:38
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
wallet::DEFAULT_TRANSACTION_MINFEE
static const CAmount DEFAULT_TRANSACTION_MINFEE
-mintxfee default
Definition: wallet.h:80
wallet::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:895
UniValue
Definition: univalue.h:17
FillableSigningProvider::AddKey
virtual bool AddKey(const CKey &key)
Definition: signingprovider.h:151
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:226
wallet::TestUnloadWallet
static void TestUnloadWallet(std::shared_ptr< CWallet > &&wallet)
Definition: wallet_tests.cpp:63
wallet::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:112
wallet::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:536
wallet::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:89
wallet::CreateDummyWalletDatabase
std::unique_ptr< WalletDatabase > CreateDummyWalletDatabase()
Return object for accessing dummy database with no read/write capabilities.
Definition: walletdb.cpp:1184
CBlockIndex::GetBlockTimeMax
int64_t GetBlockTimeMax() const
Definition: chain.h:278
CPubKey::begin
const unsigned char * begin() const
Definition: pubkey.h:114
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
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
wallet::ListCoinsTestingSetup::wallet
std::unique_ptr< CWallet > wallet
Definition: wallet_tests.cpp:542
wallet::WalletContext::args
ArgsManager * args
Definition: context.h:37
wallet::FEATURE_LATEST
@ FEATURE_LATEST
Definition: walletutil.h:30
CTxDestination
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:157
wallet::CWallet::ScanResult
Definition: wallet.h:523
DUMMY_MAXIMUM_SIGNATURE_CREATOR
const BaseSignatureCreator & DUMMY_MAXIMUM_SIGNATURE_CREATOR
A signature creator that just produces 72-byte empty signatures.
Definition: sign.cpp:581
SignatureData
Definition: sign.h:63
EncodeSecret
std::string EncodeSecret(const CKey &key)
Definition: key_io.cpp:216
GetScriptForRawPubKey
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
Definition: standard.cpp:315
wallet::MakeWalletDatabase
std::unique_ptr< WalletDatabase > MakeWalletDatabase(const std::string &name, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error_string)
Definition: wallet.cpp:2595
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
wallet::DEFAULT_TRANSACTION_MAXFEE
constexpr CAmount DEFAULT_TRANSACTION_MAXFEE
-maxtxfee default
Definition: wallet.h:106
wallet::LegacyScriptPubKeyMan
Definition: scriptpubkeyman.h:264
wallet::CWallet::ScanResult::SUCCESS
@ SUCCESS
Definition: wallet.h:524
wallet::CWallet
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:232
wallet::CalculateNestedKeyhashInputSize
static size_t CalculateNestedKeyhashInputSize(bool use_max_sig)
Definition: wallet_tests.cpp:632
RPCHelpMan::HandleRequest
UniValue HandleRequest(const JSONRPCRequest &request) const
Definition: util.cpp:564
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
wallet::DBErrors::LOAD_OK
@ LOAD_OK
wallet::LegacyScriptPubKeyMan::HaveWatchOnly
bool HaveWatchOnly(const CScript &dest) const
Returns whether the watch-only script is in the wallet.
Definition: scriptpubkeyman.cpp:855
CPubKey::end
const unsigned char * end() const
Definition: pubkey.h:115
wallet::WALLET_FLAG_DISABLE_PRIVATE_KEYS
@ WALLET_FLAG_DISABLE_PRIVATE_KEYS
Definition: walletutil.h:51
univalue.h
GetRandHash
uint256 GetRandHash() noexcept
Definition: random.cpp:601
BasicTestingSetup::m_args
ArgsManager m_args
Definition: setup_common.h:91
ArgsManager::ForceSetArg
void ForceSetArg(const std::string &strArg, const std::string &strValue)
Definition: system.cpp:619
wallet::WalletBatch
Access to the wallet database.
Definition: walletdb.h:180
CAmount
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
wallet::LegacyScriptPubKeyMan::RemoveWatchOnly
bool RemoveWatchOnly(const CScript &dest)
Remove a watch only script from the keystore.
Definition: scriptpubkeyman.cpp:874
context
WalletContext context
Definition: notifications.cpp:37
SpanReader
Minimal stream for reading from an existing byte array by Span.
Definition: streams.h:133
BasicTestingSetup
Basic testing setup.
Definition: setup_common.h:83
wallet::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:263
TestChain100Setup
Testing fixture that pre-creates a 100-block REGTEST-mode block chain.
Definition: setup_common.h:124
uint256
256-bit opaque blob.
Definition: uint256.h:124
CKey::GetPubKey
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:187
TestChain100Setup::CreateAndProcessBlock
CBlock CreateAndProcessBlock(const std::vector< CMutableTransaction > &txns, const CScript &scriptPubKey, CChainState *chainstate=nullptr)
Create a new block with just given transactions, coinbase paying to scriptPubKey, and try to add it t...
Definition: setup_common.cpp:291
CScript
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:405
wallet::TxState
std::variant< TxStateConfirmed, TxStateInMempool, TxStateConflicted, TxStateInactive, TxStateUnrecognized > TxState
All possible CWalletTx states.
Definition: transaction.h:66
node::MAX_BLOCKFILE_SIZE
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
Definition: blockstorage.h:40
CBlockIndex::GetBlockHash
uint256 GetBlockHash() const
Definition: chain.h:259
gArgs
ArgsManager gArgs
Definition: system.cpp:80
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:56
wallet::BOOST_AUTO_TEST_CASE
BOOST_AUTO_TEST_CASE(bnb_search_test)
Definition: coinselector_tests.cpp:177
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:761
util.h
wallet::AddKey
static void AddKey(CWallet &wallet, const CKey &key)
Definition: wallet_tests.cpp:84
wallet::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:933
CPubKey::IsCompressed
bool IsCompressed() const
Check whether this is a compressed public key.
Definition: pubkey.h:198
wallet::ListCoinsTestingSetup
Definition: wallet_tests.cpp:501
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:333
OutputType::BECH32
@ BECH32
wallet::TxStateInactive
State of transaction not confirmed or conflicting with a known block and not in the mempool.
Definition: transaction.h:48
CMutableTransaction::vout
std::vector< CTxOut > vout
Definition: transaction.h:347
PKHash
Definition: standard.h:79
wallet::TestWatchOnlyPubKey
static void TestWatchOnlyPubKey(LegacyScriptPubKeyMan *spk_man, const CPubKey &add_pubkey)
Definition: wallet_tests.cpp:426
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:33
base_blob::IsNull
bool IsNull() const
Definition: uint256.h:31
wallet::CachedTxGetImmatureCredit
CAmount CachedTxGetImmatureCredit(const CWallet &wallet, const CWalletTx &wtx, bool fUseCache)
Definition: receive.cpp:165
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:138
wallet::CreateSyncedWallet
std::unique_ptr< CWallet > CreateSyncedWallet(interfaces::Chain &chain, CChain &cchain, ArgsManager &args, const CKey &key)
Definition: util.cpp:19
wallet::ListCoinsTestingSetup::AddTx
CWalletTx & AddTx(CRecipient recipient)
Definition: wallet_tests.cpp:515
wallet::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:250
translation.h
Hash160
uint160 Hash160(const T1 &in1)
Compute the 160-bit hash an object.
Definition: hash.h:92
LOCK
#define LOCK(cs)
Definition: sync.h:226
wallet::CWallet::ScanResult::last_scanned_height
std::optional< int > last_scanned_height
Definition: wallet.h:530
blockstorage.h
std
Definition: setup_common.h:33
wallet::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:2619
m_wallet
std::shared_ptr< CWallet > m_wallet
Definition: interfaces.cpp:510
wallet::importwallet
RPCHelpMan importwallet()
Definition: backup.cpp:481
FillableSigningProvider::AddKeyPubKey
virtual bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey)
Definition: signingprovider.cpp:118
UniValue::push_back
bool push_back(const UniValue &val)
Definition: univalue.cpp:108
wallet::WalletRescanReserver::reserve
bool reserve()
Definition: wallet.h:910
node::NodeContext::chainman
std::unique_ptr< ChainstateManager > chainman
Definition: context.h:48
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:168
wallet::GetBalance
Balance GetBalance(const CWallet &wallet, const int min_depth, bool avoid_reuse)
Definition: receive.cpp:318
context.h
FillableSigningProvider::AddCScript
virtual bool AddCScript(const CScript &redeemScript)
Definition: signingprovider.cpp:153
receive.h
wallet::CWallet::ScanResult::status
enum wallet::CWallet::ScanResult::@17 status
wallet::WalletDescriptor
Descriptor with some wallet metadata.
Definition: walletutil.h:76
JSONRPCRequest
Definition: request.h:28
wallet::PollutePubKey
static void PollutePubKey(CPubKey &pubkey)
Definition: wallet_tests.cpp:458
CTransaction::GetHash
const uint256 & GetHash() const
Definition: transaction.h:302
UpdateInput
void UpdateInput(CTxIn &input, const SignatureData &data)
Definition: sign.cpp:494
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:189
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:280
wallet::WalletContext
WalletContext struct containing references to state shared between CWallet instances,...
Definition: context.h:35
FillableSigningProvider::cs_KeyStore
RecursiveMutex cs_KeyStore
Definition: signingprovider.h:148
wallet::TxStateConfirmed
State of transaction confirmed in a block.
Definition: transaction.h:24
wallet::UnloadWallet
void UnloadWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly unload and delete the wallet.
Definition: wallet.cpp:194
error
bool error(const char *fmt, const Args &... args)
Definition: system.h:49
wallet::TestSimpleSpend
static CMutableTransaction TestSimpleSpend(const CTransaction &from, uint32_t index, const CKey &key, const CScript &pubkey)
Definition: wallet_tests.cpp:70
COIN
static constexpr CAmount COIN
The amount of satoshis in one BTC.
Definition: amount.h:15
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:148
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:510
wallet::WalletContext::chain
interfaces::Chain * chain
Definition: context.h:36
wallet::DatabaseOptions
Definition: db.h:204
wallet::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:122
wallet::WALLET_INCREMENTAL_RELAY_FEE
static const CAmount WALLET_INCREMENTAL_RELAY_FEE
minimum recommended increment for BIP 125 replacement txs
Definition: wallet.h:94
UniValue::setObject
bool setObject()
Definition: univalue.cpp:101
wallet::CCoinControl
Coin Control Features.
Definition: coincontrol.h:29
wallet::AddTx
static int64_t AddTx(ChainstateManager &chainman, CWallet &wallet, uint32_t lockTime, int64_t mockTime, int64_t blockTime)
Definition: wallet_tests.cpp:356
wallet::DatabaseOptions::create_flags
uint64_t create_flags
Definition: db.h:208
spend.h
wallet::TestLoadWallet
static const std::shared_ptr< CWallet > TestLoadWallet(WalletContext &context)
Definition: wallet_tests.cpp:48
wallet::BOOST_FIXTURE_TEST_CASE
BOOST_FIXTURE_TEST_CASE(SubtractFee, TestChain100Setup)
Definition: spend_tests.cpp:18
base_blob::begin
unsigned char * begin()
Definition: uint256.h:58
BOOST_CHECK
#define BOOST_CHECK(expr)
Definition: object.cpp:17
wallet::LegacyScriptPubKeyMan::GetWatchPubKey
bool GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
Fetches a pubkey from mapWatchKeys if it exists there.
Definition: scriptpubkeyman.cpp:1017
BOOST_CHECK_EQUAL
#define BOOST_CHECK_EQUAL(v1, v2)
Definition: object.cpp:18
FlatSigningProvider
Definition: signingprovider.h:72
node::NodeContext::chain
std::unique_ptr< interfaces::Chain > chain
Definition: context.h:51
CPubKey::GetID
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:164
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
node::UnlinkPrunedFiles
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune)
Actually unlink the specified files.
Definition: blockstorage.cpp:577