Bitcoin Core  26.1.0
P2P Digital Currency
wallet_tests.cpp
Go to the documentation of this file.
1 // Copyright (c) 2012-2022 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #include <wallet/wallet.h>
6 
7 #include <future>
8 #include <memory>
9 #include <stdint.h>
10 #include <vector>
11 
12 #include <addresstype.h>
13 #include <interfaces/chain.h>
14 #include <key_io.h>
15 #include <node/blockstorage.h>
16 #include <policy/policy.h>
17 #include <rpc/server.h>
18 #include <script/solver.h>
19 #include <test/util/logging.h>
20 #include <test/util/random.h>
21 #include <test/util/setup_common.h>
22 #include <util/translation.h>
23 #include <validation.h>
24 #include <validationinterface.h>
25 #include <wallet/coincontrol.h>
26 #include <wallet/context.h>
27 #include <wallet/receive.h>
28 #include <wallet/spend.h>
29 #include <wallet/test/util.h>
31 
32 #include <boost/test/unit_test.hpp>
33 #include <univalue.h>
34 
36 
37 namespace wallet {
41 
42 // Ensure that fee levels defined in the wallet are at least as high
43 // as the default levels for node policy.
44 static_assert(DEFAULT_TRANSACTION_MINFEE >= DEFAULT_MIN_RELAY_TX_FEE, "wallet minimum fee is smaller than default relay fee");
45 static_assert(WALLET_INCREMENTAL_RELAY_FEE >= DEFAULT_INCREMENTAL_RELAY_FEE, "wallet incremental fee is smaller than default incremental relay fee");
46 
47 BOOST_FIXTURE_TEST_SUITE(wallet_tests, WalletTestingSetup)
48 
49 static CMutableTransaction TestSimpleSpend(const CTransaction& from, uint32_t index, const CKey& key, const CScript& pubkey)
50 {
52  mtx.vout.emplace_back(from.vout[index].nValue - DEFAULT_TRANSACTION_MAXFEE, pubkey);
53  mtx.vin.push_back({CTxIn{from.GetHash(), index}});
54  FillableSigningProvider keystore;
55  keystore.AddKey(key);
56  std::map<COutPoint, Coin> coins;
57  coins[mtx.vin[0].prevout].out = from.vout[index];
58  std::map<int, bilingual_str> input_errors;
59  BOOST_CHECK(SignTransaction(mtx, &keystore, coins, SIGHASH_ALL, input_errors));
60  return mtx;
61 }
62 
63 static void AddKey(CWallet& wallet, const CKey& key)
64 {
65  LOCK(wallet.cs_wallet);
66  FlatSigningProvider provider;
67  std::string error;
68  std::unique_ptr<Descriptor> desc = Parse("combo(" + EncodeSecret(key) + ")", provider, error, /* require_checksum=*/ false);
69  assert(desc);
70  WalletDescriptor w_desc(std::move(desc), 0, 0, 1, 1);
71  if (!wallet.AddWalletDescriptor(w_desc, provider, "", false)) assert(false);
72 }
73 
74 BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions, TestChain100Setup)
75 {
76  // Cap last block file size, and mine new block in a new block file.
77  CBlockIndex* oldTip = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip());
78  WITH_LOCK(::cs_main, m_node.chainman->m_blockman.GetBlockFileInfo(oldTip->GetBlockPos().nFile)->nSize = MAX_BLOCKFILE_SIZE);
79  CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
80  CBlockIndex* newTip = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip());
81 
82  // Verify ScanForWalletTransactions fails to read an unknown start block.
83  {
85  {
86  LOCK(wallet.cs_wallet);
87  LOCK(Assert(m_node.chainman)->GetMutex());
88  wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
89  wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
90  }
91  AddKey(wallet, coinbaseKey);
92  WalletRescanReserver reserver(wallet);
93  reserver.reserve();
94  CWallet::ScanResult result = wallet.ScanForWalletTransactions(/*start_block=*/{}, /*start_height=*/0, /*max_height=*/{}, reserver, /*fUpdate=*/false, /*save_progress=*/false);
99  BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 0);
100  }
101 
102  // Verify ScanForWalletTransactions picks up transactions in both the old
103  // and new block files.
104  {
106  {
107  LOCK(wallet.cs_wallet);
108  LOCK(Assert(m_node.chainman)->GetMutex());
109  wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
110  wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
111  }
112  AddKey(wallet, coinbaseKey);
113  WalletRescanReserver reserver(wallet);
114  std::chrono::steady_clock::time_point fake_time;
115  reserver.setNow([&] { fake_time += 60s; return fake_time; });
116  reserver.reserve();
117 
118  {
119  CBlockLocator locator;
120  BOOST_CHECK(!WalletBatch{wallet.GetDatabase()}.ReadBestBlock(locator));
121  BOOST_CHECK(locator.IsNull());
122  }
123 
124  CWallet::ScanResult result = wallet.ScanForWalletTransactions(/*start_block=*/oldTip->GetBlockHash(), /*start_height=*/oldTip->nHeight, /*max_height=*/{}, reserver, /*fUpdate=*/false, /*save_progress=*/true);
129  BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 100 * COIN);
130 
131  {
132  CBlockLocator locator;
133  BOOST_CHECK(WalletBatch{wallet.GetDatabase()}.ReadBestBlock(locator));
134  BOOST_CHECK(!locator.IsNull());
135  }
136  }
137 
138  // Prune the older block file.
139  int file_number;
140  {
141  LOCK(cs_main);
142  file_number = oldTip->GetBlockPos().nFile;
143  Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
144  }
145  m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
146 
147  // Verify ScanForWalletTransactions only picks transactions in the new block
148  // file.
149  {
151  {
152  LOCK(wallet.cs_wallet);
153  LOCK(Assert(m_node.chainman)->GetMutex());
154  wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
155  wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
156  }
157  AddKey(wallet, coinbaseKey);
158  WalletRescanReserver reserver(wallet);
159  reserver.reserve();
160  CWallet::ScanResult result = wallet.ScanForWalletTransactions(/*start_block=*/oldTip->GetBlockHash(), /*start_height=*/oldTip->nHeight, /*max_height=*/{}, reserver, /*fUpdate=*/false, /*save_progress=*/false);
165  BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 50 * COIN);
166  }
167 
168  // Prune the remaining block file.
169  {
170  LOCK(cs_main);
171  file_number = newTip->GetBlockPos().nFile;
172  Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
173  }
174  m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
175 
176  // Verify ScanForWalletTransactions scans no blocks.
177  {
179  {
180  LOCK(wallet.cs_wallet);
181  LOCK(Assert(m_node.chainman)->GetMutex());
182  wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
183  wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
184  }
185  AddKey(wallet, coinbaseKey);
186  WalletRescanReserver reserver(wallet);
187  reserver.reserve();
188  CWallet::ScanResult result = wallet.ScanForWalletTransactions(/*start_block=*/oldTip->GetBlockHash(), /*start_height=*/oldTip->nHeight, /*max_height=*/{}, reserver, /*fUpdate=*/false, /*save_progress=*/false);
193  BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 0);
194  }
195 }
196 
198 {
199  // Cap last block file size, and mine new block in a new block file.
200  CBlockIndex* oldTip = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip());
201  WITH_LOCK(::cs_main, m_node.chainman->m_blockman.GetBlockFileInfo(oldTip->GetBlockPos().nFile)->nSize = MAX_BLOCKFILE_SIZE);
202  CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
203  CBlockIndex* newTip = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip());
204 
205  // Prune the older block file.
206  int file_number;
207  {
208  LOCK(cs_main);
209  file_number = oldTip->GetBlockPos().nFile;
210  Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
211  }
212  m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
213 
214  // Verify importmulti RPC returns failure for a key whose creation time is
215  // before the missing block, and success for a key whose creation time is
216  // after.
217  {
218  const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateMockableWalletDatabase());
219  wallet->SetupLegacyScriptPubKeyMan();
220  WITH_LOCK(wallet->cs_wallet, wallet->SetLastBlockProcessed(newTip->nHeight, newTip->GetBlockHash()));
222  context.args = &m_args;
224  UniValue keys;
225  keys.setArray();
226  UniValue key;
227  key.setObject();
228  key.pushKV("scriptPubKey", HexStr(GetScriptForRawPubKey(coinbaseKey.GetPubKey())));
229  key.pushKV("timestamp", 0);
230  key.pushKV("internal", UniValue(true));
231  keys.push_back(key);
232  key.clear();
233  key.setObject();
234  CKey futureKey;
235  futureKey.MakeNewKey(true);
236  key.pushKV("scriptPubKey", HexStr(GetScriptForRawPubKey(futureKey.GetPubKey())));
237  key.pushKV("timestamp", newTip->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1);
238  key.pushKV("internal", UniValue(true));
239  keys.push_back(key);
240  JSONRPCRequest request;
241  request.context = &context;
242  request.params.setArray();
243  request.params.push_back(keys);
244 
245  UniValue response = importmulti().HandleRequest(request);
246  BOOST_CHECK_EQUAL(response.write(),
247  strprintf("[{\"success\":false,\"error\":{\"code\":-1,\"message\":\"Rescan failed for key with creation "
248  "timestamp %d. There was an error reading a block from time %d, which is after or within %d "
249  "seconds of key creation, and could contain transactions pertaining to the key. As a result, "
250  "transactions and coins using this key may not appear in the wallet. This error could be caused "
251  "by pruning or data corruption (see bitcoind log for details) and could be dealt with by "
252  "downloading and rescanning the relevant blocks (see -reindex option and rescanblockchain "
253  "RPC).\"}},{\"success\":true}]",
254  0, oldTip->GetBlockTimeMax(), TIMESTAMP_WINDOW));
255  RemoveWallet(context, wallet, /* load_on_start= */ std::nullopt);
256  }
257 }
258 
259 // Verify importwallet RPC starts rescan at earliest block with timestamp
260 // greater or equal than key birthday. Previously there was a bug where
261 // importwallet RPC would start the scan at the latest block with timestamp less
262 // than or equal to key birthday.
264 {
265  // Create two blocks with same timestamp to verify that importwallet rescan
266  // will pick up both blocks, not just the first.
267  const int64_t BLOCK_TIME = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip()->GetBlockTimeMax() + 5);
268  SetMockTime(BLOCK_TIME);
269  m_coinbase_txns.emplace_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
270  m_coinbase_txns.emplace_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
271 
272  // Set key birthday to block time increased by the timestamp window, so
273  // rescan will start at the block time.
274  const int64_t KEY_TIME = BLOCK_TIME + TIMESTAMP_WINDOW;
275  SetMockTime(KEY_TIME);
276  m_coinbase_txns.emplace_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
277 
278  std::string backup_file = fs::PathToString(m_args.GetDataDirNet() / "wallet.backup");
279 
280  // Import key into wallet and call dumpwallet to create backup file.
281  {
283  context.args = &m_args;
284  const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateMockableWalletDatabase());
285  {
286  auto spk_man = wallet->GetOrCreateLegacyScriptPubKeyMan();
287  LOCK2(wallet->cs_wallet, spk_man->cs_KeyStore);
288  spk_man->mapKeyMetadata[coinbaseKey.GetPubKey().GetID()].nCreateTime = KEY_TIME;
289  spk_man->AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey());
290 
292  LOCK(Assert(m_node.chainman)->GetMutex());
293  wallet->SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
294  }
295  JSONRPCRequest request;
296  request.context = &context;
297  request.params.setArray();
298  request.params.push_back(backup_file);
299 
301  RemoveWallet(context, wallet, /* load_on_start= */ std::nullopt);
302  }
303 
304  // Call importwallet RPC and verify all blocks with timestamps >= BLOCK_TIME
305  // were scanned, and no prior blocks were scanned.
306  {
307  const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateMockableWalletDatabase());
308  LOCK(wallet->cs_wallet);
309  wallet->SetupLegacyScriptPubKeyMan();
310 
312  context.args = &m_args;
313  JSONRPCRequest request;
314  request.context = &context;
315  request.params.setArray();
316  request.params.push_back(backup_file);
318  LOCK(Assert(m_node.chainman)->GetMutex());
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 {
342 
343  LOCK(wallet.cs_wallet);
344  LOCK(Assert(m_node.chainman)->GetMutex());
345  CWalletTx wtx{m_coinbase_txns.back(), TxStateConfirmed{m_node.chainman->ActiveChain().Tip()->GetBlockHash(), m_node.chainman->ActiveChain().Height(), /*index=*/0}};
346  wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
347  wallet.SetupDescriptorScriptPubKeyMans();
348 
349  wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
350 
351  // Call GetImmatureCredit() once before adding the key to the wallet to
352  // cache the current immature credit amount, which is 0.
354 
355  // Invalidate the cached value, add the key, and make sure a new immature
356  // credit amount is calculated.
357  wtx.MarkDirty();
358  AddKey(wallet, coinbaseKey);
360 }
361 
362 static int64_t AddTx(ChainstateManager& chainman, CWallet& wallet, uint32_t lockTime, int64_t mockTime, int64_t blockTime)
363 {
365  TxState state = TxStateInactive{};
366  tx.nLockTime = lockTime;
367  SetMockTime(mockTime);
368  CBlockIndex* block = nullptr;
369  if (blockTime > 0) {
370  LOCK(cs_main);
371  auto inserted = chainman.BlockIndex().emplace(std::piecewise_construct, std::make_tuple(GetRandHash()), std::make_tuple());
372  assert(inserted.second);
373  const uint256& hash = inserted.first->first;
374  block = &inserted.first->second;
375  block->nTime = blockTime;
376  block->phashBlock = &hash;
377  state = TxStateConfirmed{hash, block->nHeight, /*index=*/0};
378  }
379  return wallet.AddToWallet(MakeTransactionRef(tx), state, [&](CWalletTx& wtx, bool /* new_tx */) {
380  // Assign wtx.m_state to simplify test and avoid the need to simulate
381  // reorg events. Without this, AddToWallet asserts false when the same
382  // transaction is confirmed in different blocks.
383  wtx.m_state = state;
384  return true;
385  })->nTimeSmart;
386 }
387 
388 // Simple test to verify assignment of CWalletTx::nSmartTime value. Could be
389 // expanded to cover more corner cases of smart time logic.
390 BOOST_AUTO_TEST_CASE(ComputeTimeSmart)
391 {
392  // New transaction should use clock time if lower than block time.
393  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 100, 120), 100);
394 
395  // Test that updating existing transaction does not change smart time.
396  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 200, 220), 100);
397 
398  // New transaction should use clock time if there's no block time.
399  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 2, 300, 0), 300);
400 
401  // New transaction should use block time if lower than clock time.
402  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 3, 420, 400), 400);
403 
404  // New transaction should use latest entry time if higher than
405  // min(block time, clock time).
406  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 4, 500, 390), 400);
407 
408  // If there are future entries, new transaction should use time of the
409  // newest entry that is no more than 300 seconds ahead of the clock time.
410  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 5, 50, 600), 300);
411 }
412 
413 void TestLoadWallet(const std::string& name, DatabaseFormat format, std::function<void(std::shared_ptr<CWallet>)> f)
414 {
416  auto chain{interfaces::MakeChain(node)};
417  DatabaseOptions options;
418  options.require_format = format;
419  DatabaseStatus status;
421  std::vector<bilingual_str> warnings;
422  auto database{MakeWalletDatabase(name, options, status, error)};
423  auto wallet{std::make_shared<CWallet>(chain.get(), "", std::move(database))};
425  WITH_LOCK(wallet->cs_wallet, f(wallet));
426 }
427 
429 {
431  const std::string name{strprintf("receive-requests-%i", format)};
432  TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
433  BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash()));
434  WalletBatch batch{wallet->GetDatabase()};
435  BOOST_CHECK(batch.WriteAddressPreviouslySpent(PKHash(), true));
436  BOOST_CHECK(batch.WriteAddressPreviouslySpent(ScriptHash(), true));
437  BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "0", "val_rr00"));
438  BOOST_CHECK(wallet->EraseAddressReceiveRequest(batch, PKHash(), "0"));
439  BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "1", "val_rr10"));
440  BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "1", "val_rr11"));
441  BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, ScriptHash(), "2", "val_rr20"));
442  });
443  TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
444  BOOST_CHECK(wallet->IsAddressPreviouslySpent(PKHash()));
445  BOOST_CHECK(wallet->IsAddressPreviouslySpent(ScriptHash()));
446  auto requests = wallet->GetAddressReceiveRequests();
447  auto erequests = {"val_rr11", "val_rr20"};
448  BOOST_CHECK_EQUAL_COLLECTIONS(requests.begin(), requests.end(), std::begin(erequests), std::end(erequests));
449  WalletBatch batch{wallet->GetDatabase()};
450  BOOST_CHECK(batch.WriteAddressPreviouslySpent(PKHash(), false));
451  BOOST_CHECK(batch.EraseAddressData(ScriptHash()));
452  });
453  TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
454  BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash()));
455  BOOST_CHECK(!wallet->IsAddressPreviouslySpent(ScriptHash()));
456  auto requests = wallet->GetAddressReceiveRequests();
457  auto erequests = {"val_rr11"};
458  BOOST_CHECK_EQUAL_COLLECTIONS(requests.begin(), requests.end(), std::begin(erequests), std::end(erequests));
459  });
460  }
461 }
462 
463 // Test some watch-only LegacyScriptPubKeyMan methods by the procedure of loading (LoadWatchOnly),
464 // checking (HaveWatchOnly), getting (GetWatchPubKey) and removing (RemoveWatchOnly) a
465 // given PubKey, resp. its corresponding P2PK Script. Results of the impact on
466 // the address -> PubKey map is dependent on whether the PubKey is a point on the curve
467 static void TestWatchOnlyPubKey(LegacyScriptPubKeyMan* spk_man, const CPubKey& add_pubkey)
468 {
469  CScript p2pk = GetScriptForRawPubKey(add_pubkey);
470  CKeyID add_address = add_pubkey.GetID();
471  CPubKey found_pubkey;
472  LOCK(spk_man->cs_KeyStore);
473 
474  // all Scripts (i.e. also all PubKeys) are added to the general watch-only set
475  BOOST_CHECK(!spk_man->HaveWatchOnly(p2pk));
476  spk_man->LoadWatchOnly(p2pk);
477  BOOST_CHECK(spk_man->HaveWatchOnly(p2pk));
478 
479  // only PubKeys on the curve shall be added to the watch-only address -> PubKey map
480  bool is_pubkey_fully_valid = add_pubkey.IsFullyValid();
481  if (is_pubkey_fully_valid) {
482  BOOST_CHECK(spk_man->GetWatchPubKey(add_address, found_pubkey));
483  BOOST_CHECK(found_pubkey == add_pubkey);
484  } else {
485  BOOST_CHECK(!spk_man->GetWatchPubKey(add_address, found_pubkey));
486  BOOST_CHECK(found_pubkey == CPubKey()); // passed key is unchanged
487  }
488 
489  spk_man->RemoveWatchOnly(p2pk);
490  BOOST_CHECK(!spk_man->HaveWatchOnly(p2pk));
491 
492  if (is_pubkey_fully_valid) {
493  BOOST_CHECK(!spk_man->GetWatchPubKey(add_address, found_pubkey));
494  BOOST_CHECK(found_pubkey == add_pubkey); // passed key is unchanged
495  }
496 }
497 
498 // Cryptographically invalidate a PubKey whilst keeping length and first byte
499 static void PollutePubKey(CPubKey& pubkey)
500 {
501  std::vector<unsigned char> pubkey_raw(pubkey.begin(), pubkey.end());
502  std::fill(pubkey_raw.begin()+1, pubkey_raw.end(), 0);
503  pubkey = CPubKey(pubkey_raw);
504  assert(!pubkey.IsFullyValid());
505  assert(pubkey.IsValid());
506 }
507 
508 // Test watch-only logic for PubKeys
509 BOOST_AUTO_TEST_CASE(WatchOnlyPubKeys)
510 {
511  CKey key;
512  CPubKey pubkey;
513  LegacyScriptPubKeyMan* spk_man = m_wallet.GetOrCreateLegacyScriptPubKeyMan();
514 
515  BOOST_CHECK(!spk_man->HaveWatchOnly());
516 
517  // uncompressed valid PubKey
518  key.MakeNewKey(false);
519  pubkey = key.GetPubKey();
520  assert(!pubkey.IsCompressed());
521  TestWatchOnlyPubKey(spk_man, pubkey);
522 
523  // uncompressed cryptographically invalid PubKey
524  PollutePubKey(pubkey);
525  TestWatchOnlyPubKey(spk_man, pubkey);
526 
527  // compressed valid PubKey
528  key.MakeNewKey(true);
529  pubkey = key.GetPubKey();
530  assert(pubkey.IsCompressed());
531  TestWatchOnlyPubKey(spk_man, pubkey);
532 
533  // compressed cryptographically invalid PubKey
534  PollutePubKey(pubkey);
535  TestWatchOnlyPubKey(spk_man, pubkey);
536 
537  // invalid empty PubKey
538  pubkey = CPubKey();
539  TestWatchOnlyPubKey(spk_man, pubkey);
540 }
541 
543 {
544 public:
546  {
547  CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
548  wallet = CreateSyncedWallet(*m_node.chain, WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain()), coinbaseKey);
549  }
550 
552  {
553  wallet.reset();
554  }
555 
557  {
558  CTransactionRef tx;
559  CCoinControl dummy;
560  {
561  constexpr int RANDOM_CHANGE_POSITION = -1;
562  auto res = CreateTransaction(*wallet, {recipient}, RANDOM_CHANGE_POSITION, dummy);
563  BOOST_CHECK(res);
564  tx = res->tx;
565  }
566  wallet->CommitTransaction(tx, {}, {});
567  CMutableTransaction blocktx;
568  {
569  LOCK(wallet->cs_wallet);
570  blocktx = CMutableTransaction(*wallet->mapWallet.at(tx->GetHash()).tx);
571  }
572  CreateAndProcessBlock({CMutableTransaction(blocktx)}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
573 
574  LOCK(wallet->cs_wallet);
575  LOCK(Assert(m_node.chainman)->GetMutex());
576  wallet->SetLastBlockProcessed(wallet->GetLastBlockHeight() + 1, m_node.chainman->ActiveChain().Tip()->GetBlockHash());
577  auto it = wallet->mapWallet.find(tx->GetHash());
578  BOOST_CHECK(it != wallet->mapWallet.end());
579  it->second.m_state = TxStateConfirmed{m_node.chainman->ActiveChain().Tip()->GetBlockHash(), m_node.chainman->ActiveChain().Height(), /*index=*/1};
580  return it->second;
581  }
582 
583  std::unique_ptr<CWallet> wallet;
584 };
585 
587 {
588  std::string coinbaseAddress = coinbaseKey.GetPubKey().GetID().ToString();
589 
590  // Confirm ListCoins initially returns 1 coin grouped under coinbaseKey
591  // address.
592  std::map<CTxDestination, std::vector<COutput>> list;
593  {
594  LOCK(wallet->cs_wallet);
595  list = ListCoins(*wallet);
596  }
597  BOOST_CHECK_EQUAL(list.size(), 1U);
598  BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
599  BOOST_CHECK_EQUAL(list.begin()->second.size(), 1U);
600 
601  // Check initial balance from one mature coinbase transaction.
602  BOOST_CHECK_EQUAL(50 * COIN, WITH_LOCK(wallet->cs_wallet, return AvailableCoins(*wallet).GetTotalAmount()));
603 
604  // Add a transaction creating a change address, and confirm ListCoins still
605  // returns the coin associated with the change address underneath the
606  // coinbaseKey pubkey, even though the change address has a different
607  // pubkey.
608  AddTx(CRecipient{PubKeyDestination{{}}, 1 * COIN, /*subtract_fee=*/false});
609  {
610  LOCK(wallet->cs_wallet);
611  list = ListCoins(*wallet);
612  }
613  BOOST_CHECK_EQUAL(list.size(), 1U);
614  BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
615  BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
616 
617  // Lock both coins. Confirm number of available coins drops to 0.
618  {
619  LOCK(wallet->cs_wallet);
621  }
622  for (const auto& group : list) {
623  for (const auto& coin : group.second) {
624  LOCK(wallet->cs_wallet);
625  wallet->LockCoin(coin.outpoint);
626  }
627  }
628  {
629  LOCK(wallet->cs_wallet);
631  }
632  // Confirm ListCoins still returns same result as before, despite coins
633  // being locked.
634  {
635  LOCK(wallet->cs_wallet);
636  list = ListCoins(*wallet);
637  }
638  BOOST_CHECK_EQUAL(list.size(), 1U);
639  BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
640  BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
641 }
642 
643 void TestCoinsResult(ListCoinsTest& context, OutputType out_type, CAmount amount,
644  std::map<OutputType, size_t>& expected_coins_sizes)
645 {
646  LOCK(context.wallet->cs_wallet);
647  util::Result<CTxDestination> dest = Assert(context.wallet->GetNewDestination(out_type, ""));
648  CWalletTx& wtx = context.AddTx(CRecipient{*dest, amount, /*fSubtractFeeFromAmount=*/true});
649  CoinFilterParams filter;
650  filter.skip_locked = false;
651  CoinsResult available_coins = AvailableCoins(*context.wallet, nullptr, std::nullopt, filter);
652  // Lock outputs so they are not spent in follow-up transactions
653  for (uint32_t i = 0; i < wtx.tx->vout.size(); i++) context.wallet->LockCoin({wtx.GetHash(), i});
654  for (const auto& [type, size] : expected_coins_sizes) BOOST_CHECK_EQUAL(size, available_coins.coins[type].size());
655 }
656 
657 BOOST_FIXTURE_TEST_CASE(BasicOutputTypesTest, ListCoinsTest)
658 {
659  std::map<OutputType, size_t> expected_coins_sizes;
660  for (const auto& out_type : OUTPUT_TYPES) { expected_coins_sizes[out_type] = 0U; }
661 
662  // Verify our wallet has one usable coinbase UTXO before starting
663  // This UTXO is a P2PK, so it should show up in the Other bucket
664  expected_coins_sizes[OutputType::UNKNOWN] = 1U;
665  CoinsResult available_coins = WITH_LOCK(wallet->cs_wallet, return AvailableCoins(*wallet));
666  BOOST_CHECK_EQUAL(available_coins.Size(), expected_coins_sizes[OutputType::UNKNOWN]);
667  BOOST_CHECK_EQUAL(available_coins.coins[OutputType::UNKNOWN].size(), expected_coins_sizes[OutputType::UNKNOWN]);
668 
669  // We will create a self transfer for each of the OutputTypes and
670  // verify it is put in the correct bucket after running GetAvailablecoins
671  //
672  // For each OutputType, We expect 2 UTXOs in our wallet following the self transfer:
673  // 1. One UTXO as the recipient
674  // 2. One UTXO from the change, due to payment address matching logic
675 
676  for (const auto& out_type : OUTPUT_TYPES) {
677  if (out_type == OutputType::UNKNOWN) continue;
678  expected_coins_sizes[out_type] = 2U;
679  TestCoinsResult(*this, out_type, 1 * COIN, expected_coins_sizes);
680  }
681 }
682 
684 {
685  {
686  const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateMockableWalletDatabase());
687  wallet->SetupLegacyScriptPubKeyMan();
688  wallet->SetMinVersion(FEATURE_LATEST);
690  BOOST_CHECK(!wallet->TopUpKeyPool(1000));
691  BOOST_CHECK(!wallet->GetNewDestination(OutputType::BECH32, ""));
692  }
693  {
694  const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateMockableWalletDatabase());
695  LOCK(wallet->cs_wallet);
696  wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
697  wallet->SetMinVersion(FEATURE_LATEST);
699  BOOST_CHECK(!wallet->GetNewDestination(OutputType::BECH32, ""));
700  }
701 }
702 
703 // Explicit calculation which is used to test the wallet constant
704 // We get the same virtual size due to rounding(weight/4) for both use_max_sig values
705 static size_t CalculateNestedKeyhashInputSize(bool use_max_sig)
706 {
707  // Generate ephemeral valid pubkey
708  CKey key;
709  key.MakeNewKey(true);
710  CPubKey pubkey = key.GetPubKey();
711 
712  // Generate pubkey hash
713  uint160 key_hash(Hash160(pubkey));
714 
715  // Create inner-script to enter into keystore. Key hash can't be 0...
716  CScript inner_script = CScript() << OP_0 << std::vector<unsigned char>(key_hash.begin(), key_hash.end());
717 
718  // Create outer P2SH script for the output
719  uint160 script_id(Hash160(inner_script));
720  CScript script_pubkey = CScript() << OP_HASH160 << std::vector<unsigned char>(script_id.begin(), script_id.end()) << OP_EQUAL;
721 
722  // Add inner-script to key store and key to watchonly
723  FillableSigningProvider keystore;
724  keystore.AddCScript(inner_script);
725  keystore.AddKeyPubKey(key, pubkey);
726 
727  // Fill in dummy signatures for fee calculation.
728  SignatureData sig_data;
729 
730  if (!ProduceSignature(keystore, use_max_sig ? DUMMY_MAXIMUM_SIGNATURE_CREATOR : DUMMY_SIGNATURE_CREATOR, script_pubkey, sig_data)) {
731  // We're hand-feeding it correct arguments; shouldn't happen
732  assert(false);
733  }
734 
735  CTxIn tx_in;
736  UpdateInput(tx_in, sig_data);
737  return (size_t)GetVirtualTransactionInputSize(tx_in);
738 }
739 
741 {
744 }
745 
746 bool malformed_descriptor(std::ios_base::failure e)
747 {
748  std::string s(e.what());
749  return s.find("Missing checksum") != std::string::npos;
750 }
751 
753 {
754  std::vector<unsigned char> malformed_record;
755  CVectorWriter vw{0, malformed_record, 0};
756  vw << std::string("notadescriptor");
757  vw << uint64_t{0};
758  vw << int32_t{0};
759  vw << int32_t{0};
760  vw << int32_t{1};
761 
762  SpanReader vr{0, malformed_record};
763  WalletDescriptor w_desc;
764  BOOST_CHECK_EXCEPTION(vr >> w_desc, std::ios_base::failure, malformed_descriptor);
765 }
766 
786 {
787  m_args.ForceSetArg("-unsafesqlitesync", "1");
788  // Create new wallet with known key and unload it.
790  context.args = &m_args;
791  context.chain = m_node.chain.get();
792  auto wallet = TestLoadWallet(context);
793  CKey key;
794  key.MakeNewKey(true);
795  AddKey(*wallet, key);
796  TestUnloadWallet(std::move(wallet));
797 
798 
799  // Add log hook to detect AddToWallet events from rescans, blockConnected,
800  // and transactionAddedToMempool notifications
801  int addtx_count = 0;
802  DebugLogHelper addtx_counter("[default wallet] AddToWallet", [&](const std::string* s) {
803  if (s) ++addtx_count;
804  return false;
805  });
806 
807 
808  bool rescan_completed = false;
809  DebugLogHelper rescan_check("[default wallet] Rescan completed", [&](const std::string* s) {
810  if (s) rescan_completed = true;
811  return false;
812  });
813 
814 
815  // Block the queue to prevent the wallet receiving blockConnected and
816  // transactionAddedToMempool notifications, and create block and mempool
817  // transactions paying to the wallet
818  std::promise<void> promise;
820  promise.get_future().wait();
821  });
822  std::string error;
823  m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
824  auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
825  m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
826  auto mempool_tx = TestSimpleSpend(*m_coinbase_txns[1], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
827  BOOST_CHECK(m_node.chain->broadcastTransaction(MakeTransactionRef(mempool_tx), DEFAULT_TRANSACTION_MAXFEE, false, error));
828 
829 
830  // Reload wallet and make sure new transactions are detected despite events
831  // being blocked
832  // Loading will also ask for current mempool transactions
834  BOOST_CHECK(rescan_completed);
835  // AddToWallet events for block_tx and mempool_tx (x2)
836  BOOST_CHECK_EQUAL(addtx_count, 3);
837  {
838  LOCK(wallet->cs_wallet);
839  BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_tx.GetHash()), 1U);
840  BOOST_CHECK_EQUAL(wallet->mapWallet.count(mempool_tx.GetHash()), 1U);
841  }
842 
843 
844  // Unblock notification queue and make sure stale blockConnected and
845  // transactionAddedToMempool events are processed
846  promise.set_value();
848  // AddToWallet events for block_tx and mempool_tx events are counted a
849  // second time as the notification queue is processed
850  BOOST_CHECK_EQUAL(addtx_count, 5);
851 
852 
853  TestUnloadWallet(std::move(wallet));
854 
855 
856  // Load wallet again, this time creating new block and mempool transactions
857  // paying to the wallet as the wallet finishes loading and syncing the
858  // queue so the events have to be handled immediately. Releasing the wallet
859  // lock during the sync is a little artificial but is needed to avoid a
860  // deadlock during the sync and simulates a new block notification happening
861  // as soon as possible.
862  addtx_count = 0;
863  auto handler = HandleLoadWallet(context, [&](std::unique_ptr<interfaces::Wallet> wallet) {
864  BOOST_CHECK(rescan_completed);
865  m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
866  block_tx = TestSimpleSpend(*m_coinbase_txns[2], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
867  m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
868  mempool_tx = TestSimpleSpend(*m_coinbase_txns[3], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
869  BOOST_CHECK(m_node.chain->broadcastTransaction(MakeTransactionRef(mempool_tx), DEFAULT_TRANSACTION_MAXFEE, false, error));
871  });
873  // Since mempool transactions are requested at the end of loading, there will
874  // be 2 additional AddToWallet calls, one from the previous test, and a duplicate for mempool_tx
875  BOOST_CHECK_EQUAL(addtx_count, 2 + 2);
876  {
877  LOCK(wallet->cs_wallet);
878  BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_tx.GetHash()), 1U);
879  BOOST_CHECK_EQUAL(wallet->mapWallet.count(mempool_tx.GetHash()), 1U);
880  }
881 
882 
883  TestUnloadWallet(std::move(wallet));
884 }
885 
886 BOOST_FIXTURE_TEST_CASE(CreateWalletWithoutChain, BasicTestingSetup)
887 {
889  context.args = &m_args;
890  auto wallet = TestLoadWallet(context);
892  UnloadWallet(std::move(wallet));
893 }
894 
896 {
897  m_args.ForceSetArg("-unsafesqlitesync", "1");
899  context.args = &m_args;
900  context.chain = m_node.chain.get();
901  auto wallet = TestLoadWallet(context);
902  CKey key;
903  key.MakeNewKey(true);
904  AddKey(*wallet, key);
905 
906  std::string error;
907  m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
908  auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
909  CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
910 
912 
913  {
914  auto block_hash = block_tx.GetHash();
915  auto prev_tx = m_coinbase_txns[0];
916 
917  LOCK(wallet->cs_wallet);
918  BOOST_CHECK(wallet->HasWalletSpend(prev_tx));
919  BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_hash), 1u);
920 
921  std::vector<uint256> vHashIn{ block_hash }, vHashOut;
922  BOOST_CHECK_EQUAL(wallet->ZapSelectTx(vHashIn, vHashOut), DBErrors::LOAD_OK);
923 
924  BOOST_CHECK(!wallet->HasWalletSpend(prev_tx));
925  BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_hash), 0u);
926  }
927 
928  TestUnloadWallet(std::move(wallet));
929 }
930 
935 BOOST_FIXTURE_TEST_CASE(wallet_sync_tx_invalid_state_test, TestingSetup)
936 {
938  {
939  LOCK(wallet.cs_wallet);
940  wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
941  wallet.SetupDescriptorScriptPubKeyMans();
942  }
943 
944  // Add tx to wallet
945  const auto op_dest{*Assert(wallet.GetNewDestination(OutputType::BECH32M, ""))};
946 
948  mtx.vout.emplace_back(COIN, GetScriptForDestination(op_dest));
949  mtx.vin.emplace_back(g_insecure_rand_ctx.rand256(), 0);
950  const auto& tx_id_to_spend = wallet.AddToWallet(MakeTransactionRef(mtx), TxStateInMempool{})->GetHash();
951 
952  {
953  // Cache and verify available balance for the wtx
954  LOCK(wallet.cs_wallet);
955  const CWalletTx* wtx_to_spend = wallet.GetWalletTx(tx_id_to_spend);
957  }
958 
959  // Now the good case:
960  // 1) Add a transaction that spends the previously created transaction
961  // 2) Verify that the available balance of this new tx and the old one is updated (prev tx is marked dirty)
962 
963  mtx.vin.clear();
964  mtx.vin.emplace_back(tx_id_to_spend, 0);
965  wallet.transactionAddedToMempool(MakeTransactionRef(mtx));
966  const uint256& good_tx_id = mtx.GetHash();
967 
968  {
969  // Verify balance update for the new tx and the old one
970  LOCK(wallet.cs_wallet);
971  const CWalletTx* new_wtx = wallet.GetWalletTx(good_tx_id);
973 
974  // Now the old wtx
975  const CWalletTx* wtx_to_spend = wallet.GetWalletTx(tx_id_to_spend);
977  }
978 
979  // Now the bad case:
980  // 1) Make db always fail
981  // 2) Try to add a transaction that spends the previously created transaction and
982  // verify that we are not moving forward if the wallet cannot store it
984  mtx.vin.clear();
985  mtx.vin.emplace_back(good_tx_id, 0);
986  BOOST_CHECK_EXCEPTION(wallet.transactionAddedToMempool(MakeTransactionRef(mtx)),
987  std::runtime_error,
988  HasReason("DB error adding transaction to wallet, write failed"));
989 }
990 
992 } // namespace wallet
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:421
uint256 last_failed_block
Height of the most recent block that could not be scanned due to read errors or pruning.
Definition: wallet.h:620
enum wallet::CWallet::ScanResult::@17 status
RPCHelpMan importwallet()
Definition: backup.cpp:496
std::unique_ptr< interfaces::Chain > chain
Definition: context.h:63
std::optional< DatabaseFormat > require_format
Definition: db.h:186
static UniValue Parse(std::string_view raw)
Parse string to UniValue or throw runtime_error if string contains invalid JSON.
Definition: client.cpp:309
void push_back(UniValue val)
Definition: univalue.cpp:104
bool RemoveWatchOnly(const CScript &dest)
Remove a watch only script from the keystore.
State of transaction added to mempool.
Definition: transaction.h:36
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
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.
static const CAmount DEFAULT_TRANSACTION_MINFEE
-mintxfee default
Definition: wallet.h:111
std::any context
Definition: request.h:38
static constexpr unsigned int DEFAULT_INCREMENTAL_RELAY_FEE
Default for -incrementalrelayfee, which sets the minimum feerate increase for mempool limiting or rep...
Definition: policy.h:35
static constexpr size_t DUMMY_NESTED_P2WPKH_INPUT_SIZE
Pre-calculated constants for input size estimation in virtual size
Definition: wallet.h:144
static void AddKey(CWallet &wallet, const CKey &key)
assert(!tx.IsCoinBase())
RPCHelpMan importmulti()
Definition: backup.cpp:1251
static size_t CalculateNestedKeyhashInputSize(bool use_max_sig)
Describes a place in the block chain to another node such that if the other node doesn&#39;t have the sam...
Definition: block.h:123
std::optional< int > last_scanned_height
Definition: wallet.h:614
bool LoadWatchOnly(const CScript &dest)
Adds a watch-only address to the store, without saving it to disk (used by LoadWallet) ...
size_t Size() const
The following methods are provided so that CoinsResult can mimic a vector, i.e., methods can work wit...
Definition: spend.cpp:182
Bilingual messages:
Definition: translation.h:18
void TestLoadWallet(const std::string &name, DatabaseFormat format, std::function< void(std::shared_ptr< CWallet >)> f)
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:827
node::NodeContext m_node
Definition: bitcoin-gui.cpp:37
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1162
uint256 last_scanned_block
Hash and height of most recent block that was successfully scanned.
Definition: wallet.h:613
RecursiveMutex cs_KeyStore
static const DatabaseFormat DATABASE_FORMATS[]
Definition: util.h:26
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:188
uint256 GetRandHash() noexcept
Definition: random.cpp:573
std::vector< CTxIn > vin
Definition: transaction.h:381
virtual bool AddCScript(const CScript &redeemScript)
std::shared_ptr< CWallet > m_wallet
Definition: interfaces.cpp:561
void setNow(NowFn now)
Definition: wallet.h:1074
CoinsResult AvailableCoinsListUnspent(const CWallet &wallet, const CCoinControl *coinControl, CoinFilterParams params)
Wrapper function for AvailableCoins which skips the feerate and CoinFilterParams::only_spendable para...
Definition: spend.cpp:468
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
Definition: sign.cpp:762
static constexpr unsigned int DEFAULT_MIN_RELAY_TX_FEE
Default for -minrelaytxfee, minimum relay fee for transactions.
Definition: policy.h:57
uint256 rand256() noexcept
generate a random uint256.
Definition: random.cpp:587
const BaseSignatureCreator & DUMMY_MAXIMUM_SIGNATURE_CREATOR
A signature creator that just produces 72-byte empty signatures.
Definition: sign.cpp:763
State of transaction not confirmed or conflicting with a known block and not in the mempool...
Definition: transaction.h:53
RAII object to check and reserve a wallet rescan.
Definition: wallet.h:1043
Balance GetBalance(const CWallet &wallet, const int min_depth, bool avoid_reuse)
Definition: receive.cpp:293
bool IsNull() const
Definition: block.h:152
uint32_t nTime
Definition: chain.h:199
bool reserve(bool with_passphrase=false)
Definition: wallet.h:1054
Access to the wallet database.
Definition: walletdb.h:190
State of transaction confirmed in a block.
Definition: transaction.h:26
int nFile
Definition: flatfile.h:16
bool(* handler)(const std::any &context, HTTPRequest *req, const std::string &strReq)
Definition: rest.cpp:1005
std::shared_ptr< CWallet > TestLoadWallet(std::unique_ptr< WalletDatabase > database, WalletContext &context, uint64_t create_flags)
Definition: util.cpp:50
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:32
BOOST_AUTO_TEST_CASE(WatchOnlyPubKeys)
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:164
const unsigned char * begin() const
Definition: pubkey.h:114
OutputType
Definition: outputtype.h:17
static constexpr auto OUTPUT_TYPES
Definition: outputtype.h:25
std::unique_ptr< CWallet > wallet
static void AvailableCoins(benchmark::Bench &bench, const std::vector< OutputType > &output_type)
Basic testing setup.
Definition: setup_common.h:49
constexpr unsigned char * begin()
Definition: uint256.h:68
Minimal stream for reading from an existing byte array by Span.
Definition: streams.h:146
std::map< OutputType, std::vector< COutput > > coins
Definition: spend.h:41
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
static int64_t AddTx(ChainstateManager &chainman, CWallet &wallet, uint32_t lockTime, int64_t mockTime, int64_t blockTime)
COutputs available for spending, stored by OutputType.
Definition: spend.h:40
uint256 GetBlockHash() const
Definition: chain.h:253
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
Definition: time.cpp:81
A transaction with a bunch of additional info that only the owner cares about.
Definition: transaction.h:171
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:109
NodeContext struct containing references to chain state and connection state.
Definition: context.h:48
#define LOCK2(cs1, cs2)
Definition: sync.h:259
int64_t GetVirtualTransactionInputSize(const CTxIn &txin, int64_t nSigOpCost, unsigned int bytes_per_sigop)
Definition: policy.cpp:305
static std::string PathToString(const path &path)
Convert path object to a byte string.
Definition: fs.h:150
const unsigned char * end() const
Definition: pubkey.h:115
bool IsFullyValid() const
fully validate whether this is a valid public key (more expensive than IsValid()) ...
Definition: pubkey.cpp:304
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
static const CAmount WALLET_INCREMENTAL_RELAY_FEE
minimum recommended increment for replacement txs
Definition: wallet.h:125
UniValue params
Definition: request.h:33
An input of a transaction.
Definition: transaction.h:74
#define LOCK(cs)
Definition: sync.h:258
const char * name
Definition: rest.cpp:45
static void PollutePubKey(CPubKey &pubkey)
BOOST_AUTO_TEST_SUITE_END()
void format(std::ostream &out, const char *fmt, const Args &... args)
Format list of arguments to the stream according to given format string.
Definition: tinyformat.h:1060
static void TestWatchOnlyPubKey(LegacyScriptPubKeyMan *spk_man, const CPubKey &add_pubkey)
An encapsulated public key.
Definition: pubkey.h:33
Fillable signing provider that keeps keys in an address->secret map.
static CMutableTransaction TestSimpleSpend(const CTransaction &from, uint32_t index, const CKey &key, const CScript &pubkey)
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
Definition: key.cpp:161
static void AddTx(CWallet &wallet)
CAmount CachedTxGetImmatureCredit(const CWallet &wallet, const CWalletTx &wtx, const isminefilter &filter)
Definition: receive.cpp:148
int64_t GetBlockTimeMax() const
Definition: chain.h:282
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:74
BOOST_CHECK_EXCEPTION predicates to check the specific validation error.
Definition: setup_common.h:200
WalletContext context
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:300
bool malformed_descriptor(std::ios_base::failure e)
void CallFunctionInValidationInterfaceQueue(std::function< void()> func)
Pushes a function to callback onto the notification queue, guaranteeing any callbacks generated prior...
Testing fixture that pre-creates a 100-block REGTEST-mode block chain.
Definition: setup_common.h:98
MockableDatabase & GetMockableDatabase(CWallet &wallet)
Definition: util.cpp:195
std::vector< CTxOut > vout
Definition: transaction.h:382
constexpr bool IsNull() const
Definition: uint256.h:42
void setObject()
Definition: univalue.cpp:98
void UnloadWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly unload and delete the wallet.
Definition: wallet.cpp:239
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:302
Descriptor with some wallet metadata.
Definition: walletutil.h:84
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:1058
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:422
Definition: init.h:25
bool RemoveWallet(WalletContext &context, const std::shared_ptr< CWallet > &wallet, std::optional< bool > load_on_start, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:152
CWalletTx & AddTx(CRecipient recipient)
uint160 Hash160(const T1 &in1)
Compute the 160-bit hash an object.
Definition: hash.h:93
CAmount CachedTxGetAvailableCredit(const CWallet &wallet, const CWalletTx &wtx, const isminefilter &filter)
Definition: receive.cpp:159
BOOST_FIXTURE_TEST_CASE(wallet_coinsresult_test, BasicTestingSetup)
DatabaseStatus
Definition: db.h:197
256-bit opaque blob.
Definition: uint256.h:106
std::unique_ptr< CWallet > CreateSyncedWallet(interfaces::Chain &chain, CChain &cchain, const CKey &key)
Definition: util.cpp:20
std::unique_ptr< WalletDatabase > CreateMockableWalletDatabase(MockableData records)
Definition: util.cpp:190
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
std::unique_ptr< Chain > MakeChain(node::NodeContext &node)
Return implementation of Chain interface.
Definition: interfaces.cpp:828
uint256 GetHash() const
Compute the hash of this CMutableTransaction.
Definition: transaction.cpp:68
BOOST_FIXTURE_TEST_CASE(wallet_sync_tx_invalid_state_test, TestingSetup)
Checks a wallet invalid state where the inputs (prev-txs) of a new arriving transaction are not marke...
DatabaseFormat
Definition: db.h:178
#define BOOST_CHECK_EQUAL(v1, v2)
Definition: object.cpp:18
bool error(const char *fmt, const Args &... args)
Definition: logging.h:262
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:144
void pushKV(std::string key, UniValue val)
Definition: univalue.cpp:126
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:412
void TestUnloadWallet(std::shared_ptr< CWallet > &&wallet)
Definition: util.cpp:73
RPCHelpMan dumpwallet()
Definition: backup.cpp:691
constexpr unsigned char * end()
Definition: uint256.h:69
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
Definition: blockstorage.h:74
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:23
FastRandomContext g_insecure_rand_ctx
This global and the helpers that use it are not thread-safe.
Definition: random.cpp:14
void UpdateInput(CTxIn &input, const SignatureData &data)
Definition: sign.cpp:672
void TestCoinsResult(ListCoinsTest &context, OutputType out_type, CAmount amount, std::map< OutputType, size_t > &expected_coins_sizes)
std::unique_ptr< interfaces::Handler > HandleLoadWallet(WalletContext &context, LoadWalletFn load_wallet)
Definition: wallet.cpp:200
constexpr CAmount DEFAULT_TRANSACTION_MAXFEE
-maxtxfee default
Definition: wallet.h:138
WalletContext struct containing references to state shared between CWallet instances, like the reference to the chain interface, and the list of opened wallets.
Definition: context.h:35
160-bit opaque blob.
Definition: uint256.h:95
bool GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
Fetches a pubkey from mapWatchKeys if it exists there.
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:499
util::Result< CreatedTransactionResult > CreateTransaction(CWallet &wallet, const std::vector< CRecipient > &vecSend, int change_pos, const CCoinControl &coin_control, bool sign)
Create a new transaction paying the recipients with a set of coins selected by SelectCoins(); Also cr...
Definition: spend.cpp:1278
A mutable version of CTransaction.
Definition: transaction.h:379
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
Definition: solver.cpp:209
void clear()
Definition: univalue.cpp:18
An encapsulated private key.
Definition: key.h:32
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:294
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:157
FlatFilePos GetBlockPos() const EXCLUSIVE_LOCKS_REQUIRED(
Definition: chain.h:218
std::shared_ptr< CWallet > wallet
void setArray()
Definition: univalue.cpp:92
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:373
BOOST_AUTO_TEST_CASE(bnb_search_test)
UniValue HandleRequest(const JSONRPCRequest &request) const
Definition: util.cpp:594
std::string EncodeSecret(const CKey &key)
Definition: key_io.cpp:227
ArgsManager * args
Definition: context.h:37
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
Definition: cs_main.cpp:8
bool AddWallet(WalletContext &context, const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:140
Coin Control Features.
Definition: coincontrol.h:28
std::variant< TxStateConfirmed, TxStateInMempool, TxStateConflicted, TxStateInactive, TxStateUnrecognized > TxState
All possible CWalletTx states.
Definition: transaction.h:73
Testing setup that configures a complete environment.
Definition: setup_common.h:77
std::unique_ptr< ChainstateManager > chainman
Definition: context.h:59
virtual bool AddKey(const CKey &key)
std::unique_ptr< WalletDatabase > MakeWalletDatabase(const std::string &name, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error_string)
Definition: wallet.cpp:2845
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:494
#define Assert(val)
Identity function.
Definition: check.h:73
bool HaveWatchOnly(const CScript &dest) const
Returns whether the watch-only script is in the wallet.
#define BOOST_CHECK(expr)
Definition: object.cpp:17
static constexpr CAmount COIN
The amount of satoshis in one BTC.
Definition: amount.h:15
bool IsCompressed() const
Check whether this is a compressed public key.
Definition: pubkey.h:204
const uint256 * phashBlock
pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
Definition: chain.h:148