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  int file_number;
144  {
145  LOCK(cs_main);
146  file_number = oldTip->GetBlockPos().nFile;
147  Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
148  }
149  UnlinkPrunedFiles({file_number});
150 
151  // Verify ScanForWalletTransactions only picks transactions in the new block
152  // file.
153  {
154  CWallet wallet(m_node.chain.get(), "", m_args, CreateDummyWalletDatabase());
155  {
156  LOCK(wallet.cs_wallet);
157  wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
158  wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
159  }
160  AddKey(wallet, coinbaseKey);
161  WalletRescanReserver reserver(wallet);
162  reserver.reserve();
163  CWallet::ScanResult result = wallet.ScanForWalletTransactions(oldTip->GetBlockHash(), oldTip->nHeight, {} /* max_height */, reserver, false /* update */);
166  BOOST_CHECK_EQUAL(result.last_scanned_block, newTip->GetBlockHash());
167  BOOST_CHECK_EQUAL(*result.last_scanned_height, newTip->nHeight);
168  BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 50 * COIN);
169  }
170 
171  // Prune the remaining block file.
172  {
173  LOCK(cs_main);
174  file_number = newTip->GetBlockPos().nFile;
175  Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
176  }
177  UnlinkPrunedFiles({file_number});
178 
179  // Verify ScanForWalletTransactions scans no blocks.
180  {
181  CWallet wallet(m_node.chain.get(), "", m_args, CreateDummyWalletDatabase());
182  {
183  LOCK(wallet.cs_wallet);
184  wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
185  wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
186  }
187  AddKey(wallet, coinbaseKey);
188  WalletRescanReserver reserver(wallet);
189  reserver.reserve();
190  CWallet::ScanResult result = wallet.ScanForWalletTransactions(oldTip->GetBlockHash(), oldTip->nHeight, {} /* max_height */, reserver, false /* update */);
192  BOOST_CHECK_EQUAL(result.last_failed_block, newTip->GetBlockHash());
195  BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 0);
196  }
197 }
198 
200 {
201  // Cap last block file size, and mine new block in a new block file.
202  CBlockIndex* oldTip = m_node.chainman->ActiveChain().Tip();
203  WITH_LOCK(::cs_main, m_node.chainman->m_blockman.GetBlockFileInfo(oldTip->GetBlockPos().nFile)->nSize = MAX_BLOCKFILE_SIZE);
204  CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
205  CBlockIndex* newTip = m_node.chainman->ActiveChain().Tip();
206 
207  // Prune the older block file.
208  int file_number;
209  {
210  LOCK(cs_main);
211  file_number = oldTip->GetBlockPos().nFile;
212  Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
213  }
214  UnlinkPrunedFiles({file_number});
215 
216  // Verify importmulti RPC returns failure for a key whose creation time is
217  // before the missing block, and success for a key whose creation time is
218  // after.
219  {
220  const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", m_args, CreateDummyWalletDatabase());
221  wallet->SetupLegacyScriptPubKeyMan();
222  WITH_LOCK(wallet->cs_wallet, wallet->SetLastBlockProcessed(newTip->nHeight, newTip->GetBlockHash()));
224  context.args = &gArgs;
226  UniValue keys;
227  keys.setArray();
228  UniValue key;
229  key.setObject();
230  key.pushKV("scriptPubKey", HexStr(GetScriptForRawPubKey(coinbaseKey.GetPubKey())));
231  key.pushKV("timestamp", 0);
232  key.pushKV("internal", UniValue(true));
233  keys.push_back(key);
234  key.clear();
235  key.setObject();
236  CKey futureKey;
237  futureKey.MakeNewKey(true);
238  key.pushKV("scriptPubKey", HexStr(GetScriptForRawPubKey(futureKey.GetPubKey())));
239  key.pushKV("timestamp", newTip->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1);
240  key.pushKV("internal", UniValue(true));
241  keys.push_back(key);
242  JSONRPCRequest request;
243  request.context = &context;
244  request.params.setArray();
245  request.params.push_back(keys);
246 
247  UniValue response = importmulti().HandleRequest(request);
248  BOOST_CHECK_EQUAL(response.write(),
249  strprintf("[{\"success\":false,\"error\":{\"code\":-1,\"message\":\"Rescan failed for key with creation "
250  "timestamp %d. There was an error reading a block from time %d, which is after or within %d "
251  "seconds of key creation, and could contain transactions pertaining to the key. As a result, "
252  "transactions and coins using this key may not appear in the wallet. This error could be caused "
253  "by pruning or data corruption (see bitcoind log for details) and could be dealt with by "
254  "downloading and rescanning the relevant blocks (see -reindex option and rescanblockchain "
255  "RPC).\"}},{\"success\":true}]",
256  0, oldTip->GetBlockTimeMax(), TIMESTAMP_WINDOW));
257  RemoveWallet(context, wallet, /* load_on_start= */ std::nullopt);
258  }
259 }
260 
261 // Verify importwallet RPC starts rescan at earliest block with timestamp
262 // greater or equal than key birthday. Previously there was a bug where
263 // importwallet RPC would start the scan at the latest block with timestamp less
264 // than or equal to key birthday.
266 {
267  // Create two blocks with same timestamp to verify that importwallet rescan
268  // will pick up both blocks, not just the first.
269  const int64_t BLOCK_TIME = m_node.chainman->ActiveChain().Tip()->GetBlockTimeMax() + 5;
270  SetMockTime(BLOCK_TIME);
271  m_coinbase_txns.emplace_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
272  m_coinbase_txns.emplace_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
273 
274  // Set key birthday to block time increased by the timestamp window, so
275  // rescan will start at the block time.
276  const int64_t KEY_TIME = BLOCK_TIME + TIMESTAMP_WINDOW;
277  SetMockTime(KEY_TIME);
278  m_coinbase_txns.emplace_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
279 
280  std::string backup_file = fs::PathToString(gArgs.GetDataDirNet() / "wallet.backup");
281 
282  // Import key into wallet and call dumpwallet to create backup file.
283  {
285  context.args = &gArgs;
286  const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", m_args, CreateDummyWalletDatabase());
287  {
288  auto spk_man = wallet->GetOrCreateLegacyScriptPubKeyMan();
289  LOCK2(wallet->cs_wallet, spk_man->cs_KeyStore);
290  spk_man->mapKeyMetadata[coinbaseKey.GetPubKey().GetID()].nCreateTime = KEY_TIME;
291  spk_man->AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey());
292 
294  wallet->SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
295  }
296  JSONRPCRequest request;
297  request.context = &context;
298  request.params.setArray();
299  request.params.push_back(backup_file);
300 
302  RemoveWallet(context, wallet, /* load_on_start= */ std::nullopt);
303  }
304 
305  // Call importwallet RPC and verify all blocks with timestamps >= BLOCK_TIME
306  // were scanned, and no prior blocks were scanned.
307  {
308  const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", m_args, CreateDummyWalletDatabase());
309  LOCK(wallet->cs_wallet);
310  wallet->SetupLegacyScriptPubKeyMan();
311 
313  context.args = &gArgs;
314  JSONRPCRequest request;
315  request.context = &context;
316  request.params.setArray();
317  request.params.push_back(backup_file);
319  wallet->SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
321  RemoveWallet(context, wallet, /* load_on_start= */ std::nullopt);
322 
323  BOOST_CHECK_EQUAL(wallet->mapWallet.size(), 3U);
324  BOOST_CHECK_EQUAL(m_coinbase_txns.size(), 103U);
325  for (size_t i = 0; i < m_coinbase_txns.size(); ++i) {
326  bool found = wallet->GetWalletTx(m_coinbase_txns[i]->GetHash());
327  bool expected = i >= 100;
328  BOOST_CHECK_EQUAL(found, expected);
329  }
330  }
331 }
332 
333 // Check that GetImmatureCredit() returns a newly calculated value instead of
334 // the cached value after a MarkDirty() call.
335 //
336 // This is a regression test written to verify a bugfix for the immature credit
337 // function. Similar tests probably should be written for the other credit and
338 // debit functions.
339 BOOST_FIXTURE_TEST_CASE(coin_mark_dirty_immature_credit, TestChain100Setup)
340 {
341  CWallet wallet(m_node.chain.get(), "", m_args, CreateDummyWalletDatabase());
342  CWalletTx wtx{m_coinbase_txns.back(), TxStateConfirmed{m_node.chainman->ActiveChain().Tip()->GetBlockHash(), m_node.chainman->ActiveChain().Height(), /*position_in_block=*/0}};
343 
344  LOCK(wallet.cs_wallet);
345  wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
346  wallet.SetupDescriptorScriptPubKeyMans();
347 
348  wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
349 
350  // Call GetImmatureCredit() once before adding the key to the wallet to
351  // cache the current immature credit amount, which is 0.
353 
354  // Invalidate the cached value, add the key, and make sure a new immature
355  // credit amount is calculated.
356  wtx.MarkDirty();
357  AddKey(wallet, coinbaseKey);
359 }
360 
361 static int64_t AddTx(ChainstateManager& chainman, CWallet& wallet, uint32_t lockTime, int64_t mockTime, int64_t blockTime)
362 {
364  TxState state = TxStateInactive{};
365  tx.nLockTime = lockTime;
366  SetMockTime(mockTime);
367  CBlockIndex* block = nullptr;
368  if (blockTime > 0) {
369  LOCK(cs_main);
370  auto inserted = chainman.BlockIndex().emplace(GetRandHash(), new CBlockIndex);
371  assert(inserted.second);
372  const uint256& hash = inserted.first->first;
373  block = inserted.first->second;
374  block->nTime = blockTime;
375  block->phashBlock = &hash;
376  state = TxStateConfirmed{hash, block->nHeight, /*position_in_block=*/0};
377  }
378  return wallet.AddToWallet(MakeTransactionRef(tx), state, [&](CWalletTx& wtx, bool /* new_tx */) {
379  // Assign wtx.m_state to simplify test and avoid the need to simulate
380  // reorg events. Without this, AddToWallet asserts false when the same
381  // transaction is confirmed in different blocks.
382  wtx.m_state = state;
383  return true;
384  })->nTimeSmart;
385 }
386 
387 // Simple test to verify assignment of CWalletTx::nSmartTime value. Could be
388 // expanded to cover more corner cases of smart time logic.
389 BOOST_AUTO_TEST_CASE(ComputeTimeSmart)
390 {
391  // New transaction should use clock time if lower than block time.
392  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 100, 120), 100);
393 
394  // Test that updating existing transaction does not change smart time.
395  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 200, 220), 100);
396 
397  // New transaction should use clock time if there's no block time.
398  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 2, 300, 0), 300);
399 
400  // New transaction should use block time if lower than clock time.
401  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 3, 420, 400), 400);
402 
403  // New transaction should use latest entry time if higher than
404  // min(block time, clock time).
405  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 4, 500, 390), 400);
406 
407  // If there are future entries, new transaction should use time of the
408  // newest entry that is no more than 300 seconds ahead of the clock time.
409  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 5, 50, 600), 300);
410 }
411 
412 BOOST_AUTO_TEST_CASE(LoadReceiveRequests)
413 {
414  CTxDestination dest = PKHash();
415  LOCK(m_wallet.cs_wallet);
416  WalletBatch batch{m_wallet.GetDatabase()};
417  m_wallet.SetAddressUsed(batch, dest, true);
418  m_wallet.SetAddressReceiveRequest(batch, dest, "0", "val_rr0");
419  m_wallet.SetAddressReceiveRequest(batch, dest, "1", "val_rr1");
420 
421  auto values = m_wallet.GetAddressReceiveRequests();
422  BOOST_CHECK_EQUAL(values.size(), 2U);
423  BOOST_CHECK_EQUAL(values[0], "val_rr0");
424  BOOST_CHECK_EQUAL(values[1], "val_rr1");
425 }
426 
427 // Test some watch-only LegacyScriptPubKeyMan methods by the procedure of loading (LoadWatchOnly),
428 // checking (HaveWatchOnly), getting (GetWatchPubKey) and removing (RemoveWatchOnly) a
429 // given PubKey, resp. its corresponding P2PK Script. Results of the the impact on
430 // the address -> PubKey map is dependent on whether the PubKey is a point on the curve
431 static void TestWatchOnlyPubKey(LegacyScriptPubKeyMan* spk_man, const CPubKey& add_pubkey)
432 {
433  CScript p2pk = GetScriptForRawPubKey(add_pubkey);
434  CKeyID add_address = add_pubkey.GetID();
435  CPubKey found_pubkey;
436  LOCK(spk_man->cs_KeyStore);
437 
438  // all Scripts (i.e. also all PubKeys) are added to the general watch-only set
439  BOOST_CHECK(!spk_man->HaveWatchOnly(p2pk));
440  spk_man->LoadWatchOnly(p2pk);
441  BOOST_CHECK(spk_man->HaveWatchOnly(p2pk));
442 
443  // only PubKeys on the curve shall be added to the watch-only address -> PubKey map
444  bool is_pubkey_fully_valid = add_pubkey.IsFullyValid();
445  if (is_pubkey_fully_valid) {
446  BOOST_CHECK(spk_man->GetWatchPubKey(add_address, found_pubkey));
447  BOOST_CHECK(found_pubkey == add_pubkey);
448  } else {
449  BOOST_CHECK(!spk_man->GetWatchPubKey(add_address, found_pubkey));
450  BOOST_CHECK(found_pubkey == CPubKey()); // passed key is unchanged
451  }
452 
453  spk_man->RemoveWatchOnly(p2pk);
454  BOOST_CHECK(!spk_man->HaveWatchOnly(p2pk));
455 
456  if (is_pubkey_fully_valid) {
457  BOOST_CHECK(!spk_man->GetWatchPubKey(add_address, found_pubkey));
458  BOOST_CHECK(found_pubkey == add_pubkey); // passed key is unchanged
459  }
460 }
461 
462 // Cryptographically invalidate a PubKey whilst keeping length and first byte
463 static void PollutePubKey(CPubKey& pubkey)
464 {
465  std::vector<unsigned char> pubkey_raw(pubkey.begin(), pubkey.end());
466  std::fill(pubkey_raw.begin()+1, pubkey_raw.end(), 0);
467  pubkey = CPubKey(pubkey_raw);
468  assert(!pubkey.IsFullyValid());
469  assert(pubkey.IsValid());
470 }
471 
472 // Test watch-only logic for PubKeys
473 BOOST_AUTO_TEST_CASE(WatchOnlyPubKeys)
474 {
475  CKey key;
476  CPubKey pubkey;
477  LegacyScriptPubKeyMan* spk_man = m_wallet.GetOrCreateLegacyScriptPubKeyMan();
478 
479  BOOST_CHECK(!spk_man->HaveWatchOnly());
480 
481  // uncompressed valid PubKey
482  key.MakeNewKey(false);
483  pubkey = key.GetPubKey();
484  assert(!pubkey.IsCompressed());
485  TestWatchOnlyPubKey(spk_man, pubkey);
486 
487  // uncompressed cryptographically invalid PubKey
488  PollutePubKey(pubkey);
489  TestWatchOnlyPubKey(spk_man, pubkey);
490 
491  // compressed valid PubKey
492  key.MakeNewKey(true);
493  pubkey = key.GetPubKey();
494  assert(pubkey.IsCompressed());
495  TestWatchOnlyPubKey(spk_man, pubkey);
496 
497  // compressed cryptographically invalid PubKey
498  PollutePubKey(pubkey);
499  TestWatchOnlyPubKey(spk_man, pubkey);
500 
501  // invalid empty PubKey
502  pubkey = CPubKey();
503  TestWatchOnlyPubKey(spk_man, pubkey);
504 }
505 
507 {
508 public:
510  {
513  }
514 
516  {
517  wallet.reset();
518  }
519 
521  {
522  CTransactionRef tx;
523  CAmount fee;
524  int changePos = -1;
526  CCoinControl dummy;
527  FeeCalculation fee_calc_out;
528  {
529  BOOST_CHECK(CreateTransaction(*wallet, {recipient}, tx, fee, changePos, error, dummy, fee_calc_out));
530  }
531  wallet->CommitTransaction(tx, {}, {});
532  CMutableTransaction blocktx;
533  {
534  LOCK(wallet->cs_wallet);
535  blocktx = CMutableTransaction(*wallet->mapWallet.at(tx->GetHash()).tx);
536  }
538 
539  LOCK(wallet->cs_wallet);
540  wallet->SetLastBlockProcessed(wallet->GetLastBlockHeight() + 1, m_node.chainman->ActiveChain().Tip()->GetBlockHash());
541  auto it = wallet->mapWallet.find(tx->GetHash());
542  BOOST_CHECK(it != wallet->mapWallet.end());
543  it->second.m_state = TxStateConfirmed{m_node.chainman->ActiveChain().Tip()->GetBlockHash(), m_node.chainman->ActiveChain().Height(), /*position_in_block=*/1};
544  return it->second;
545  }
546 
547  std::unique_ptr<CWallet> wallet;
548 };
549 
551 {
552  std::string coinbaseAddress = coinbaseKey.GetPubKey().GetID().ToString();
553 
554  // Confirm ListCoins initially returns 1 coin grouped under coinbaseKey
555  // address.
556  std::map<CTxDestination, std::vector<COutput>> list;
557  {
558  LOCK(wallet->cs_wallet);
559  list = ListCoins(*wallet);
560  }
561  BOOST_CHECK_EQUAL(list.size(), 1U);
562  BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
563  BOOST_CHECK_EQUAL(list.begin()->second.size(), 1U);
564 
565  // Check initial balance from one mature coinbase transaction.
567 
568  // Add a transaction creating a change address, and confirm ListCoins still
569  // returns the coin associated with the change address underneath the
570  // coinbaseKey pubkey, even though the change address has a different
571  // pubkey.
572  AddTx(CRecipient{GetScriptForRawPubKey({}), 1 * COIN, false /* subtract fee */});
573  {
574  LOCK(wallet->cs_wallet);
575  list = ListCoins(*wallet);
576  }
577  BOOST_CHECK_EQUAL(list.size(), 1U);
578  BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
579  BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
580 
581  // Lock both coins. Confirm number of available coins drops to 0.
582  {
583  LOCK(wallet->cs_wallet);
584  std::vector<COutput> available;
585  AvailableCoins(*wallet, available);
586  BOOST_CHECK_EQUAL(available.size(), 2U);
587  }
588  for (const auto& group : list) {
589  for (const auto& coin : group.second) {
590  LOCK(wallet->cs_wallet);
591  wallet->LockCoin(COutPoint(coin.tx->GetHash(), coin.i));
592  }
593  }
594  {
595  LOCK(wallet->cs_wallet);
596  std::vector<COutput> available;
597  AvailableCoins(*wallet, available);
598  BOOST_CHECK_EQUAL(available.size(), 0U);
599  }
600  // Confirm ListCoins still returns same result as before, despite coins
601  // being locked.
602  {
603  LOCK(wallet->cs_wallet);
604  list = ListCoins(*wallet);
605  }
606  BOOST_CHECK_EQUAL(list.size(), 1U);
607  BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
608  BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
609 }
610 
612 {
613  {
614  const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", m_args, CreateDummyWalletDatabase());
615  wallet->SetupLegacyScriptPubKeyMan();
616  wallet->SetMinVersion(FEATURE_LATEST);
618  BOOST_CHECK(!wallet->TopUpKeyPool(1000));
619  CTxDestination dest;
621  BOOST_CHECK(!wallet->GetNewDestination(OutputType::BECH32, "", dest, error));
622  }
623  {
624  const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", m_args, CreateDummyWalletDatabase());
625  LOCK(wallet->cs_wallet);
626  wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
627  wallet->SetMinVersion(FEATURE_LATEST);
629  CTxDestination dest;
631  BOOST_CHECK(!wallet->GetNewDestination(OutputType::BECH32, "", dest, error));
632  }
633 }
634 
635 // Explicit calculation which is used to test the wallet constant
636 // We get the same virtual size due to rounding(weight/4) for both use_max_sig values
637 static size_t CalculateNestedKeyhashInputSize(bool use_max_sig)
638 {
639  // Generate ephemeral valid pubkey
640  CKey key;
641  key.MakeNewKey(true);
642  CPubKey pubkey = key.GetPubKey();
643 
644  // Generate pubkey hash
645  uint160 key_hash(Hash160(pubkey));
646 
647  // Create inner-script to enter into keystore. Key hash can't be 0...
648  CScript inner_script = CScript() << OP_0 << std::vector<unsigned char>(key_hash.begin(), key_hash.end());
649 
650  // Create outer P2SH script for the output
651  uint160 script_id(Hash160(inner_script));
652  CScript script_pubkey = CScript() << OP_HASH160 << std::vector<unsigned char>(script_id.begin(), script_id.end()) << OP_EQUAL;
653 
654  // Add inner-script to key store and key to watchonly
655  FillableSigningProvider keystore;
656  keystore.AddCScript(inner_script);
657  keystore.AddKeyPubKey(key, pubkey);
658 
659  // Fill in dummy signatures for fee calculation.
660  SignatureData sig_data;
661 
662  if (!ProduceSignature(keystore, use_max_sig ? DUMMY_MAXIMUM_SIGNATURE_CREATOR : DUMMY_SIGNATURE_CREATOR, script_pubkey, sig_data)) {
663  // We're hand-feeding it correct arguments; shouldn't happen
664  assert(false);
665  }
666 
667  CTxIn tx_in;
668  UpdateInput(tx_in, sig_data);
669  return (size_t)GetVirtualTransactionInputSize(tx_in);
670 }
671 
673 {
676 }
677 
678 bool malformed_descriptor(std::ios_base::failure e)
679 {
680  std::string s(e.what());
681  return s.find("Missing checksum") != std::string::npos;
682 }
683 
685 {
686  std::vector<unsigned char> malformed_record;
687  CVectorWriter vw(0, 0, malformed_record, 0);
688  vw << std::string("notadescriptor");
689  vw << (uint64_t)0;
690  vw << (int32_t)0;
691  vw << (int32_t)0;
692  vw << (int32_t)1;
693 
694  SpanReader vr{0, 0, malformed_record};
695  WalletDescriptor w_desc;
696  BOOST_CHECK_EXCEPTION(vr >> w_desc, std::ios_base::failure, malformed_descriptor);
697 }
698 
718 {
719  gArgs.ForceSetArg("-unsafesqlitesync", "1");
720  // Create new wallet with known key and unload it.
722  context.args = &gArgs;
723  context.chain = m_node.chain.get();
724  auto wallet = TestLoadWallet(context);
725  CKey key;
726  key.MakeNewKey(true);
727  AddKey(*wallet, key);
728  TestUnloadWallet(std::move(wallet));
729 
730 
731  // Add log hook to detect AddToWallet events from rescans, blockConnected,
732  // and transactionAddedToMempool notifications
733  int addtx_count = 0;
734  DebugLogHelper addtx_counter("[default wallet] AddToWallet", [&](const std::string* s) {
735  if (s) ++addtx_count;
736  return false;
737  });
738 
739 
740  bool rescan_completed = false;
741  DebugLogHelper rescan_check("[default wallet] Rescan completed", [&](const std::string* s) {
742  if (s) rescan_completed = true;
743  return false;
744  });
745 
746 
747  // Block the queue to prevent the wallet receiving blockConnected and
748  // transactionAddedToMempool notifications, and create block and mempool
749  // transactions paying to the wallet
750  std::promise<void> promise;
752  promise.get_future().wait();
753  });
754  std::string error;
755  m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
756  auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
757  m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
758  auto mempool_tx = TestSimpleSpend(*m_coinbase_txns[1], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
759  BOOST_CHECK(m_node.chain->broadcastTransaction(MakeTransactionRef(mempool_tx), DEFAULT_TRANSACTION_MAXFEE, false, error));
760 
761 
762  // Reload wallet and make sure new transactions are detected despite events
763  // being blocked
765  BOOST_CHECK(rescan_completed);
766  BOOST_CHECK_EQUAL(addtx_count, 2);
767  {
768  LOCK(wallet->cs_wallet);
769  BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_tx.GetHash()), 1U);
770  BOOST_CHECK_EQUAL(wallet->mapWallet.count(mempool_tx.GetHash()), 1U);
771  }
772 
773 
774  // Unblock notification queue and make sure stale blockConnected and
775  // transactionAddedToMempool events are processed
776  promise.set_value();
778  BOOST_CHECK_EQUAL(addtx_count, 4);
779 
780 
781  TestUnloadWallet(std::move(wallet));
782 
783 
784  // Load wallet again, this time creating new block and mempool transactions
785  // paying to the wallet as the wallet finishes loading and syncing the
786  // queue so the events have to be handled immediately. Releasing the wallet
787  // lock during the sync is a little artificial but is needed to avoid a
788  // deadlock during the sync and simulates a new block notification happening
789  // as soon as possible.
790  addtx_count = 0;
791  auto handler = HandleLoadWallet(context, [&](std::unique_ptr<interfaces::Wallet> wallet) {
792  BOOST_CHECK(rescan_completed);
793  m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
794  block_tx = TestSimpleSpend(*m_coinbase_txns[2], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
795  m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
796  mempool_tx = TestSimpleSpend(*m_coinbase_txns[3], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
797  BOOST_CHECK(m_node.chain->broadcastTransaction(MakeTransactionRef(mempool_tx), DEFAULT_TRANSACTION_MAXFEE, false, error));
799  });
801  BOOST_CHECK_EQUAL(addtx_count, 4);
802  {
803  LOCK(wallet->cs_wallet);
804  BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_tx.GetHash()), 1U);
805  BOOST_CHECK_EQUAL(wallet->mapWallet.count(mempool_tx.GetHash()), 1U);
806  }
807 
808 
809  TestUnloadWallet(std::move(wallet));
810 }
811 
812 BOOST_FIXTURE_TEST_CASE(CreateWalletWithoutChain, BasicTestingSetup)
813 {
815  context.args = &gArgs;
816  auto wallet = TestLoadWallet(context);
818  UnloadWallet(std::move(wallet));
819 }
820 
822 {
823  gArgs.ForceSetArg("-unsafesqlitesync", "1");
825  context.args = &gArgs;
826  context.chain = m_node.chain.get();
827  auto wallet = TestLoadWallet(context);
828  AddKey(*wallet, coinbaseKey);
829 
830  // rescan to ensure coinbase transactions from test fixture are picked up by the wallet
831  {
832  WalletRescanReserver reserver(*wallet);
833  reserver.reserve();
834  wallet->ScanForWalletTransactions(m_node.chain->getBlockHash(0), 0, /* max height= */ {}, reserver, /* update= */ true);
835  }
836  // create one more block to get the first block coinbase to maturity
837  m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
838  // spend first coinbase tx
839  auto spend_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
840  CreateAndProcessBlock({spend_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
841 
843 
844  {
845  auto spend_tx_hash = spend_tx.GetHash();
846  auto prev_hash = m_coinbase_txns[0]->GetHash();
847 
848  LOCK(wallet->cs_wallet);
849  BOOST_CHECK(wallet->HasWalletSpend(prev_hash));
850  BOOST_CHECK_EQUAL(wallet->mapWallet.count(spend_tx_hash), 1u);
851 
852  std::vector<uint256> vHashIn{spend_tx_hash}, vHashOut;
853  BOOST_CHECK_EQUAL(wallet->ZapSelectTx(vHashIn, vHashOut), DBErrors::LOAD_OK);
854 
855  BOOST_CHECK(!wallet->HasWalletSpend(prev_hash));
856  BOOST_CHECK_EQUAL(wallet->mapWallet.count(spend_tx_hash), 0u);
857  }
858 
859  TestUnloadWallet(std::move(wallet));
860 }
861 
863 } // 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:678
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:515
CBlockIndex::phashBlock
const uint256 * phashBlock
pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
Definition: chain.h:155
CBlockIndex::nTime
uint32_t nTime
Definition: chain.h:206
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:346
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:509
CBlockIndex::nHeight
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:164
CBlockIndex::GetBlockPos
FlatFilePos GetBlockPos() const EXCLUSIVE_LOCKS_REQUIRED(
Definition: chain.h:229
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:915
wallet::GetAvailableBalance
CAmount GetAvailableBalance(const CWallet &wallet, const CCoinControl *coinControl)
Definition: spend.cpp:213
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
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:283
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:547
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:2646
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:637
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:602
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:126
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:43
CBlockIndex::GetBlockHash
uint256 GetBlockHash() const
Definition: chain.h:264
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:777
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:931
CPubKey::IsCompressed
bool IsCompressed() const
Check whether this is a compressed public key.
Definition: pubkey.h:198
wallet::ListCoinsTestingSetup
Definition: wallet_tests.cpp:506
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:431
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:28
uint160
160-bit opaque blob.
Definition: uint256.h:115
CPubKey
An encapsulated public key.
Definition: pubkey.h:33
base_blob::IsNull
bool IsNull() const
Definition: uint256.h:33
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
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:520
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:246
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:2670
m_wallet
std::shared_ptr< CWallet > m_wallet
Definition: interfaces.cpp:509
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:316
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:463
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
cs_main
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: validation.cpp:138
CBlockIndex
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:151
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:361
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:60
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:65
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:31
node::UnlinkPrunedFiles
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune)
Actually unlink the specified files.
Definition: blockstorage.cpp:579