Bitcoin Core  29.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  auto descs = Parse("combo(" + EncodeSecret(key) + ")", provider, error, /* require_checksum=*/ false);
69  assert(descs.size() == 1);
70  auto& desc = descs.at(0);
71  WalletDescriptor w_desc(std::move(desc), 0, 0, 1, 1);
72  if (!wallet.AddWalletDescriptor(w_desc, provider, "", false)) assert(false);
73 }
74 
75 BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions, TestChain100Setup)
76 {
77  // Cap last block file size, and mine new block in a new block file.
78  CBlockIndex* oldTip = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip());
79  WITH_LOCK(::cs_main, m_node.chainman->m_blockman.GetBlockFileInfo(oldTip->GetBlockPos().nFile)->nSize = MAX_BLOCKFILE_SIZE);
80  CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
81  CBlockIndex* newTip = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip());
82 
83  // Verify ScanForWalletTransactions fails to read an unknown start block.
84  {
86  {
87  LOCK(wallet.cs_wallet);
88  LOCK(Assert(m_node.chainman)->GetMutex());
89  wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
90  wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
91  }
92  AddKey(wallet, coinbaseKey);
93  WalletRescanReserver reserver(wallet);
94  reserver.reserve();
95  CWallet::ScanResult result = wallet.ScanForWalletTransactions(/*start_block=*/{}, /*start_height=*/0, /*max_height=*/{}, reserver, /*fUpdate=*/false, /*save_progress=*/false);
97  BOOST_CHECK(result.last_failed_block.IsNull());
98  BOOST_CHECK(result.last_scanned_block.IsNull());
99  BOOST_CHECK(!result.last_scanned_height);
100  BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 0);
101  }
102 
103  // Verify ScanForWalletTransactions picks up transactions in both the old
104  // and new block files.
105  {
107  {
108  LOCK(wallet.cs_wallet);
109  LOCK(Assert(m_node.chainman)->GetMutex());
110  wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
111  wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
112  }
113  AddKey(wallet, coinbaseKey);
114  WalletRescanReserver reserver(wallet);
115  std::chrono::steady_clock::time_point fake_time;
116  reserver.setNow([&] { fake_time += 60s; return fake_time; });
117  reserver.reserve();
118 
119  {
120  CBlockLocator locator;
121  BOOST_CHECK(!WalletBatch{wallet.GetDatabase()}.ReadBestBlock(locator));
122  BOOST_CHECK(locator.IsNull());
123  }
124 
125  CWallet::ScanResult result = wallet.ScanForWalletTransactions(/*start_block=*/oldTip->GetBlockHash(), /*start_height=*/oldTip->nHeight, /*max_height=*/{}, reserver, /*fUpdate=*/false, /*save_progress=*/true);
127  BOOST_CHECK(result.last_failed_block.IsNull());
128  BOOST_CHECK_EQUAL(result.last_scanned_block, newTip->GetBlockHash());
129  BOOST_CHECK_EQUAL(*result.last_scanned_height, newTip->nHeight);
130  BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 100 * COIN);
131 
132  {
133  CBlockLocator locator;
134  BOOST_CHECK(WalletBatch{wallet.GetDatabase()}.ReadBestBlock(locator));
135  BOOST_CHECK(!locator.IsNull());
136  }
137  }
138 
139  // Prune the older block file.
140  int file_number;
141  {
142  LOCK(cs_main);
143  file_number = oldTip->GetBlockPos().nFile;
144  Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
145  }
146  m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
147 
148  // Verify ScanForWalletTransactions only picks transactions in the new block
149  // file.
150  {
152  {
153  LOCK(wallet.cs_wallet);
154  LOCK(Assert(m_node.chainman)->GetMutex());
155  wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
156  wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
157  }
158  AddKey(wallet, coinbaseKey);
159  WalletRescanReserver reserver(wallet);
160  reserver.reserve();
161  CWallet::ScanResult result = wallet.ScanForWalletTransactions(/*start_block=*/oldTip->GetBlockHash(), /*start_height=*/oldTip->nHeight, /*max_height=*/{}, reserver, /*fUpdate=*/false, /*save_progress=*/false);
163  BOOST_CHECK_EQUAL(result.last_failed_block, oldTip->GetBlockHash());
164  BOOST_CHECK_EQUAL(result.last_scanned_block, newTip->GetBlockHash());
165  BOOST_CHECK_EQUAL(*result.last_scanned_height, newTip->nHeight);
166  BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 50 * COIN);
167  }
168 
169  // Prune the remaining block file.
170  {
171  LOCK(cs_main);
172  file_number = newTip->GetBlockPos().nFile;
173  Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
174  }
175  m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
176 
177  // Verify ScanForWalletTransactions scans no blocks.
178  {
180  {
181  LOCK(wallet.cs_wallet);
182  LOCK(Assert(m_node.chainman)->GetMutex());
183  wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
184  wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
185  }
186  AddKey(wallet, coinbaseKey);
187  WalletRescanReserver reserver(wallet);
188  reserver.reserve();
189  CWallet::ScanResult result = wallet.ScanForWalletTransactions(/*start_block=*/oldTip->GetBlockHash(), /*start_height=*/oldTip->nHeight, /*max_height=*/{}, reserver, /*fUpdate=*/false, /*save_progress=*/false);
191  BOOST_CHECK_EQUAL(result.last_failed_block, newTip->GetBlockHash());
192  BOOST_CHECK(result.last_scanned_block.IsNull());
193  BOOST_CHECK(!result.last_scanned_height);
194  BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 0);
195  }
196 }
197 
199 {
200  // Cap last block file size, and mine new block in a new block file.
201  CBlockIndex* oldTip = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip());
202  WITH_LOCK(::cs_main, m_node.chainman->m_blockman.GetBlockFileInfo(oldTip->GetBlockPos().nFile)->nSize = MAX_BLOCKFILE_SIZE);
203  CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
204  CBlockIndex* newTip = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip());
205 
206  // Prune the older block file.
207  int file_number;
208  {
209  LOCK(cs_main);
210  file_number = oldTip->GetBlockPos().nFile;
211  Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
212  }
213  m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
214 
215  // Verify importmulti RPC returns failure for a key whose creation time is
216  // before the missing block, and success for a key whose creation time is
217  // after.
218  {
219  const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateMockableWalletDatabase());
220  wallet->SetupLegacyScriptPubKeyMan();
221  WITH_LOCK(wallet->cs_wallet, wallet->SetLastBlockProcessed(newTip->nHeight, newTip->GetBlockHash()));
222  WalletContext context;
223  context.args = &m_args;
224  AddWallet(context, wallet);
225  UniValue keys;
226  keys.setArray();
227  UniValue key;
228  key.setObject();
229  key.pushKV("scriptPubKey", HexStr(GetScriptForRawPubKey(coinbaseKey.GetPubKey())));
230  key.pushKV("timestamp", 0);
231  key.pushKV("internal", UniValue(true));
232  keys.push_back(key);
233  key.clear();
234  key.setObject();
235  CKey futureKey = GenerateRandomKey();
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(std::move(key));
240  JSONRPCRequest request;
241  request.context = &context;
242  request.params.setArray();
243  request.params.push_back(std::move(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  {
282  WalletContext context;
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 
291  AddWallet(context, wallet);
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 
311  WalletContext context;
312  context.args = &m_args;
313  JSONRPCRequest request;
314  request.context = &context;
315  request.params.setArray();
316  request.params.push_back(backup_file);
317  AddWallet(context, wallet);
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 // This test verifies that wallet settings can be added and removed
334 // concurrently, ensuring no race conditions occur during either process.
335 BOOST_FIXTURE_TEST_CASE(write_wallet_settings_concurrently, TestingSetup)
336 {
337  auto chain = m_node.chain.get();
338  const auto NUM_WALLETS{5};
339 
340  // Since we're counting the number of wallets, ensure we start without any.
341  BOOST_REQUIRE(chain->getRwSetting("wallet").isNull());
342 
343  const auto& check_concurrent_wallet = [&](const auto& settings_function, int num_expected_wallets) {
344  std::vector<std::thread> threads;
345  threads.reserve(NUM_WALLETS);
346  for (auto i{0}; i < NUM_WALLETS; ++i) threads.emplace_back(settings_function, i);
347  for (auto& t : threads) t.join();
348 
349  auto wallets = chain->getRwSetting("wallet");
350  BOOST_CHECK_EQUAL(wallets.getValues().size(), num_expected_wallets);
351  };
352 
353  // Add NUM_WALLETS wallets concurrently, ensure we end up with NUM_WALLETS stored.
354  check_concurrent_wallet([&chain](int i) {
355  Assert(AddWalletSetting(*chain, strprintf("wallet_%d", i)));
356  },
357  /*num_expected_wallets=*/NUM_WALLETS);
358 
359  // Remove NUM_WALLETS wallets concurrently, ensure we end up with 0 wallets.
360  check_concurrent_wallet([&chain](int i) {
361  Assert(RemoveWalletSetting(*chain, strprintf("wallet_%d", i)));
362  },
363  /*num_expected_wallets=*/0);
364 }
365 
366 // Check that GetImmatureCredit() returns a newly calculated value instead of
367 // the cached value after a MarkDirty() call.
368 //
369 // This is a regression test written to verify a bugfix for the immature credit
370 // function. Similar tests probably should be written for the other credit and
371 // debit functions.
372 BOOST_FIXTURE_TEST_CASE(coin_mark_dirty_immature_credit, TestChain100Setup)
373 {
375 
376  LOCK(wallet.cs_wallet);
377  LOCK(Assert(m_node.chainman)->GetMutex());
378  CWalletTx wtx{m_coinbase_txns.back(), TxStateConfirmed{m_node.chainman->ActiveChain().Tip()->GetBlockHash(), m_node.chainman->ActiveChain().Height(), /*index=*/0}};
379  wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
380  wallet.SetupDescriptorScriptPubKeyMans();
381 
382  wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
383 
384  // Call GetImmatureCredit() once before adding the key to the wallet to
385  // cache the current immature credit amount, which is 0.
387 
388  // Invalidate the cached value, add the key, and make sure a new immature
389  // credit amount is calculated.
390  wtx.MarkDirty();
391  AddKey(wallet, coinbaseKey);
393 }
394 
395 static int64_t AddTx(ChainstateManager& chainman, CWallet& wallet, uint32_t lockTime, int64_t mockTime, int64_t blockTime)
396 {
398  TxState state = TxStateInactive{};
399  tx.nLockTime = lockTime;
400  SetMockTime(mockTime);
401  CBlockIndex* block = nullptr;
402  if (blockTime > 0) {
403  LOCK(cs_main);
404  auto inserted = chainman.BlockIndex().emplace(std::piecewise_construct, std::make_tuple(GetRandHash()), std::make_tuple());
405  assert(inserted.second);
406  const uint256& hash = inserted.first->first;
407  block = &inserted.first->second;
408  block->nTime = blockTime;
409  block->phashBlock = &hash;
410  state = TxStateConfirmed{hash, block->nHeight, /*index=*/0};
411  }
412  return wallet.AddToWallet(MakeTransactionRef(tx), state, [&](CWalletTx& wtx, bool /* new_tx */) {
413  // Assign wtx.m_state to simplify test and avoid the need to simulate
414  // reorg events. Without this, AddToWallet asserts false when the same
415  // transaction is confirmed in different blocks.
416  wtx.m_state = state;
417  return true;
418  })->nTimeSmart;
419 }
420 
421 // Simple test to verify assignment of CWalletTx::nSmartTime value. Could be
422 // expanded to cover more corner cases of smart time logic.
423 BOOST_AUTO_TEST_CASE(ComputeTimeSmart)
424 {
425  // New transaction should use clock time if lower than block time.
426  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 100, 120), 100);
427 
428  // Test that updating existing transaction does not change smart time.
429  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 200, 220), 100);
430 
431  // New transaction should use clock time if there's no block time.
432  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 2, 300, 0), 300);
433 
434  // New transaction should use block time if lower than clock time.
435  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 3, 420, 400), 400);
436 
437  // New transaction should use latest entry time if higher than
438  // min(block time, clock time).
439  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 4, 500, 390), 400);
440 
441  // If there are future entries, new transaction should use time of the
442  // newest entry that is no more than 300 seconds ahead of the clock time.
443  BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 5, 50, 600), 300);
444 }
445 
446 void TestLoadWallet(const std::string& name, DatabaseFormat format, std::function<void(std::shared_ptr<CWallet>)> f)
447 {
449  auto chain{interfaces::MakeChain(node)};
450  DatabaseOptions options;
451  options.require_format = format;
452  DatabaseStatus status;
453  bilingual_str error;
454  std::vector<bilingual_str> warnings;
455  auto database{MakeWalletDatabase(name, options, status, error)};
456  auto wallet{std::make_shared<CWallet>(chain.get(), "", std::move(database))};
458  WITH_LOCK(wallet->cs_wallet, f(wallet));
459 }
460 
462 {
464  const std::string name{strprintf("receive-requests-%i", format)};
465  TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
466  BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash()));
467  WalletBatch batch{wallet->GetDatabase()};
468  BOOST_CHECK(batch.WriteAddressPreviouslySpent(PKHash(), true));
469  BOOST_CHECK(batch.WriteAddressPreviouslySpent(ScriptHash(), true));
470  BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "0", "val_rr00"));
471  BOOST_CHECK(wallet->EraseAddressReceiveRequest(batch, PKHash(), "0"));
472  BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "1", "val_rr10"));
473  BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "1", "val_rr11"));
474  BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, ScriptHash(), "2", "val_rr20"));
475  });
476  TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
477  BOOST_CHECK(wallet->IsAddressPreviouslySpent(PKHash()));
478  BOOST_CHECK(wallet->IsAddressPreviouslySpent(ScriptHash()));
479  auto requests = wallet->GetAddressReceiveRequests();
480  auto erequests = {"val_rr11", "val_rr20"};
481  BOOST_CHECK_EQUAL_COLLECTIONS(requests.begin(), requests.end(), std::begin(erequests), std::end(erequests));
482  RunWithinTxn(wallet->GetDatabase(), /*process_desc*/"test", [](WalletBatch& batch){
483  BOOST_CHECK(batch.WriteAddressPreviouslySpent(PKHash(), false));
484  BOOST_CHECK(batch.EraseAddressData(ScriptHash()));
485  return true;
486  });
487  });
488  TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
489  BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash()));
490  BOOST_CHECK(!wallet->IsAddressPreviouslySpent(ScriptHash()));
491  auto requests = wallet->GetAddressReceiveRequests();
492  auto erequests = {"val_rr11"};
493  BOOST_CHECK_EQUAL_COLLECTIONS(requests.begin(), requests.end(), std::begin(erequests), std::end(erequests));
494  });
495  }
496 }
497 
498 // Test some watch-only LegacyScriptPubKeyMan methods by the procedure of loading (LoadWatchOnly),
499 // checking (HaveWatchOnly), getting (GetWatchPubKey) and removing (RemoveWatchOnly) a
500 // given PubKey, resp. its corresponding P2PK Script. Results of the impact on
501 // the address -> PubKey map is dependent on whether the PubKey is a point on the curve
502 static void TestWatchOnlyPubKey(LegacyScriptPubKeyMan* spk_man, const CPubKey& add_pubkey)
503 {
504  CScript p2pk = GetScriptForRawPubKey(add_pubkey);
505  CKeyID add_address = add_pubkey.GetID();
506  CPubKey found_pubkey;
507  LOCK(spk_man->cs_KeyStore);
508 
509  // all Scripts (i.e. also all PubKeys) are added to the general watch-only set
510  BOOST_CHECK(!spk_man->HaveWatchOnly(p2pk));
511  spk_man->LoadWatchOnly(p2pk);
512  BOOST_CHECK(spk_man->HaveWatchOnly(p2pk));
513 
514  // only PubKeys on the curve shall be added to the watch-only address -> PubKey map
515  bool is_pubkey_fully_valid = add_pubkey.IsFullyValid();
516  if (is_pubkey_fully_valid) {
517  BOOST_CHECK(spk_man->GetWatchPubKey(add_address, found_pubkey));
518  BOOST_CHECK(found_pubkey == add_pubkey);
519  } else {
520  BOOST_CHECK(!spk_man->GetWatchPubKey(add_address, found_pubkey));
521  BOOST_CHECK(found_pubkey == CPubKey()); // passed key is unchanged
522  }
523 
524  spk_man->RemoveWatchOnly(p2pk);
525  BOOST_CHECK(!spk_man->HaveWatchOnly(p2pk));
526 
527  if (is_pubkey_fully_valid) {
528  BOOST_CHECK(!spk_man->GetWatchPubKey(add_address, found_pubkey));
529  BOOST_CHECK(found_pubkey == add_pubkey); // passed key is unchanged
530  }
531 }
532 
533 // Cryptographically invalidate a PubKey whilst keeping length and first byte
534 static void PollutePubKey(CPubKey& pubkey)
535 {
536  assert(pubkey.size() >= 1);
537  std::vector<unsigned char> pubkey_raw;
538  pubkey_raw.push_back(pubkey[0]);
539  pubkey_raw.insert(pubkey_raw.end(), pubkey.size() - 1, 0);
540  pubkey = CPubKey(pubkey_raw);
541  assert(!pubkey.IsFullyValid());
542  assert(pubkey.IsValid());
543 }
544 
545 // Test watch-only logic for PubKeys
546 BOOST_AUTO_TEST_CASE(WatchOnlyPubKeys)
547 {
548  CKey key;
549  CPubKey pubkey;
550  LegacyScriptPubKeyMan* spk_man = m_wallet.GetOrCreateLegacyScriptPubKeyMan();
551 
552  BOOST_CHECK(!spk_man->HaveWatchOnly());
553 
554  // uncompressed valid PubKey
555  key.MakeNewKey(false);
556  pubkey = key.GetPubKey();
557  assert(!pubkey.IsCompressed());
558  TestWatchOnlyPubKey(spk_man, pubkey);
559 
560  // uncompressed cryptographically invalid PubKey
561  PollutePubKey(pubkey);
562  TestWatchOnlyPubKey(spk_man, pubkey);
563 
564  // compressed valid PubKey
565  key.MakeNewKey(true);
566  pubkey = key.GetPubKey();
567  assert(pubkey.IsCompressed());
568  TestWatchOnlyPubKey(spk_man, pubkey);
569 
570  // compressed cryptographically invalid PubKey
571  PollutePubKey(pubkey);
572  TestWatchOnlyPubKey(spk_man, pubkey);
573 
574  // invalid empty PubKey
575  pubkey = CPubKey();
576  TestWatchOnlyPubKey(spk_man, pubkey);
577 }
578 
580 {
581 public:
583  {
584  CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
585  wallet = CreateSyncedWallet(*m_node.chain, WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain()), coinbaseKey);
586  }
587 
589  {
590  wallet.reset();
591  }
592 
594  {
595  CTransactionRef tx;
596  CCoinControl dummy;
597  {
598  auto res = CreateTransaction(*wallet, {recipient}, /*change_pos=*/std::nullopt, dummy);
599  BOOST_CHECK(res);
600  tx = res->tx;
601  }
602  wallet->CommitTransaction(tx, {}, {});
603  CMutableTransaction blocktx;
604  {
605  LOCK(wallet->cs_wallet);
606  blocktx = CMutableTransaction(*wallet->mapWallet.at(tx->GetHash()).tx);
607  }
608  CreateAndProcessBlock({CMutableTransaction(blocktx)}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
609 
610  LOCK(wallet->cs_wallet);
611  LOCK(Assert(m_node.chainman)->GetMutex());
612  wallet->SetLastBlockProcessed(wallet->GetLastBlockHeight() + 1, m_node.chainman->ActiveChain().Tip()->GetBlockHash());
613  auto it = wallet->mapWallet.find(tx->GetHash());
614  BOOST_CHECK(it != wallet->mapWallet.end());
615  it->second.m_state = TxStateConfirmed{m_node.chainman->ActiveChain().Tip()->GetBlockHash(), m_node.chainman->ActiveChain().Height(), /*index=*/1};
616  return it->second;
617  }
618 
619  std::unique_ptr<CWallet> wallet;
620 };
621 
623 {
624  std::string coinbaseAddress = coinbaseKey.GetPubKey().GetID().ToString();
625 
626  // Confirm ListCoins initially returns 1 coin grouped under coinbaseKey
627  // address.
628  std::map<CTxDestination, std::vector<COutput>> list;
629  {
630  LOCK(wallet->cs_wallet);
631  list = ListCoins(*wallet);
632  }
633  BOOST_CHECK_EQUAL(list.size(), 1U);
634  BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
635  BOOST_CHECK_EQUAL(list.begin()->second.size(), 1U);
636 
637  // Check initial balance from one mature coinbase transaction.
638  BOOST_CHECK_EQUAL(50 * COIN, WITH_LOCK(wallet->cs_wallet, return AvailableCoins(*wallet).GetTotalAmount()));
639 
640  // Add a transaction creating a change address, and confirm ListCoins still
641  // returns the coin associated with the change address underneath the
642  // coinbaseKey pubkey, even though the change address has a different
643  // pubkey.
644  AddTx(CRecipient{PubKeyDestination{{}}, 1 * COIN, /*subtract_fee=*/false});
645  {
646  LOCK(wallet->cs_wallet);
647  list = ListCoins(*wallet);
648  }
649  BOOST_CHECK_EQUAL(list.size(), 1U);
650  BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
651  BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
652 
653  // Lock both coins. Confirm number of available coins drops to 0.
654  {
655  LOCK(wallet->cs_wallet);
657  }
658  for (const auto& group : list) {
659  for (const auto& coin : group.second) {
660  LOCK(wallet->cs_wallet);
661  wallet->LockCoin(coin.outpoint);
662  }
663  }
664  {
665  LOCK(wallet->cs_wallet);
667  }
668  // Confirm ListCoins still returns same result as before, despite coins
669  // being locked.
670  {
671  LOCK(wallet->cs_wallet);
672  list = ListCoins(*wallet);
673  }
674  BOOST_CHECK_EQUAL(list.size(), 1U);
675  BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
676  BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
677 }
678 
679 void TestCoinsResult(ListCoinsTest& context, OutputType out_type, CAmount amount,
680  std::map<OutputType, size_t>& expected_coins_sizes)
681 {
682  LOCK(context.wallet->cs_wallet);
683  util::Result<CTxDestination> dest = Assert(context.wallet->GetNewDestination(out_type, ""));
684  CWalletTx& wtx = context.AddTx(CRecipient{*dest, amount, /*fSubtractFeeFromAmount=*/true});
685  CoinFilterParams filter;
686  filter.skip_locked = false;
687  CoinsResult available_coins = AvailableCoins(*context.wallet, nullptr, std::nullopt, filter);
688  // Lock outputs so they are not spent in follow-up transactions
689  for (uint32_t i = 0; i < wtx.tx->vout.size(); i++) context.wallet->LockCoin({wtx.GetHash(), i});
690  for (const auto& [type, size] : expected_coins_sizes) BOOST_CHECK_EQUAL(size, available_coins.coins[type].size());
691 }
692 
693 BOOST_FIXTURE_TEST_CASE(BasicOutputTypesTest, ListCoinsTest)
694 {
695  std::map<OutputType, size_t> expected_coins_sizes;
696  for (const auto& out_type : OUTPUT_TYPES) { expected_coins_sizes[out_type] = 0U; }
697 
698  // Verify our wallet has one usable coinbase UTXO before starting
699  // This UTXO is a P2PK, so it should show up in the Other bucket
700  expected_coins_sizes[OutputType::UNKNOWN] = 1U;
701  CoinsResult available_coins = WITH_LOCK(wallet->cs_wallet, return AvailableCoins(*wallet));
702  BOOST_CHECK_EQUAL(available_coins.Size(), expected_coins_sizes[OutputType::UNKNOWN]);
703  BOOST_CHECK_EQUAL(available_coins.coins[OutputType::UNKNOWN].size(), expected_coins_sizes[OutputType::UNKNOWN]);
704 
705  // We will create a self transfer for each of the OutputTypes and
706  // verify it is put in the correct bucket after running GetAvailablecoins
707  //
708  // For each OutputType, We expect 2 UTXOs in our wallet following the self transfer:
709  // 1. One UTXO as the recipient
710  // 2. One UTXO from the change, due to payment address matching logic
711 
712  for (const auto& out_type : OUTPUT_TYPES) {
713  if (out_type == OutputType::UNKNOWN) continue;
714  expected_coins_sizes[out_type] = 2U;
715  TestCoinsResult(*this, out_type, 1 * COIN, expected_coins_sizes);
716  }
717 }
718 
720 {
721  {
722  const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateMockableWalletDatabase());
723  wallet->SetupLegacyScriptPubKeyMan();
724  wallet->SetMinVersion(FEATURE_LATEST);
726  BOOST_CHECK(!wallet->TopUpKeyPool(1000));
727  BOOST_CHECK(!wallet->GetNewDestination(OutputType::BECH32, ""));
728  }
729  {
730  const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateMockableWalletDatabase());
731  LOCK(wallet->cs_wallet);
732  wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
733  wallet->SetMinVersion(FEATURE_LATEST);
735  BOOST_CHECK(!wallet->GetNewDestination(OutputType::BECH32, ""));
736  }
737 }
738 
739 // Explicit calculation which is used to test the wallet constant
740 // We get the same virtual size due to rounding(weight/4) for both use_max_sig values
741 static size_t CalculateNestedKeyhashInputSize(bool use_max_sig)
742 {
743  // Generate ephemeral valid pubkey
744  CKey key = GenerateRandomKey();
745  CPubKey pubkey = key.GetPubKey();
746 
747  // Generate pubkey hash
748  uint160 key_hash(Hash160(pubkey));
749 
750  // Create inner-script to enter into keystore. Key hash can't be 0...
751  CScript inner_script = CScript() << OP_0 << std::vector<unsigned char>(key_hash.begin(), key_hash.end());
752 
753  // Create outer P2SH script for the output
754  uint160 script_id(Hash160(inner_script));
755  CScript script_pubkey = CScript() << OP_HASH160 << std::vector<unsigned char>(script_id.begin(), script_id.end()) << OP_EQUAL;
756 
757  // Add inner-script to key store and key to watchonly
758  FillableSigningProvider keystore;
759  keystore.AddCScript(inner_script);
760  keystore.AddKeyPubKey(key, pubkey);
761 
762  // Fill in dummy signatures for fee calculation.
763  SignatureData sig_data;
764 
765  if (!ProduceSignature(keystore, use_max_sig ? DUMMY_MAXIMUM_SIGNATURE_CREATOR : DUMMY_SIGNATURE_CREATOR, script_pubkey, sig_data)) {
766  // We're hand-feeding it correct arguments; shouldn't happen
767  assert(false);
768  }
769 
770  CTxIn tx_in;
771  UpdateInput(tx_in, sig_data);
772  return (size_t)GetVirtualTransactionInputSize(tx_in);
773 }
774 
776 {
779 }
780 
781 bool malformed_descriptor(std::ios_base::failure e)
782 {
783  std::string s(e.what());
784  return s.find("Missing checksum") != std::string::npos;
785 }
786 
788 {
789  std::vector<unsigned char> malformed_record;
790  VectorWriter vw{malformed_record, 0};
791  vw << std::string("notadescriptor");
792  vw << uint64_t{0};
793  vw << int32_t{0};
794  vw << int32_t{0};
795  vw << int32_t{1};
796 
797  SpanReader vr{malformed_record};
798  WalletDescriptor w_desc;
799  BOOST_CHECK_EXCEPTION(vr >> w_desc, std::ios_base::failure, malformed_descriptor);
800 }
801 
821 {
822  m_args.ForceSetArg("-unsafesqlitesync", "1");
823  // Create new wallet with known key and unload it.
824  WalletContext context;
825  context.args = &m_args;
826  context.chain = m_node.chain.get();
827  auto wallet = TestLoadWallet(context);
828  CKey key = GenerateRandomKey();
829  AddKey(*wallet, key);
830  TestUnloadWallet(std::move(wallet));
831 
832 
833  // Add log hook to detect AddToWallet events from rescans, blockConnected,
834  // and transactionAddedToMempool notifications
835  int addtx_count = 0;
836  DebugLogHelper addtx_counter("[default wallet] AddToWallet", [&](const std::string* s) {
837  if (s) ++addtx_count;
838  return false;
839  });
840 
841 
842  bool rescan_completed = false;
843  DebugLogHelper rescan_check("[default wallet] Rescan completed", [&](const std::string* s) {
844  if (s) rescan_completed = true;
845  return false;
846  });
847 
848 
849  // Block the queue to prevent the wallet receiving blockConnected and
850  // transactionAddedToMempool notifications, and create block and mempool
851  // transactions paying to the wallet
852  std::promise<void> promise;
853  m_node.validation_signals->CallFunctionInValidationInterfaceQueue([&promise] {
854  promise.get_future().wait();
855  });
856  std::string error;
857  m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
858  auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
859  m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
860  auto mempool_tx = TestSimpleSpend(*m_coinbase_txns[1], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
861  BOOST_CHECK(m_node.chain->broadcastTransaction(MakeTransactionRef(mempool_tx), DEFAULT_TRANSACTION_MAXFEE, false, error));
862 
863 
864  // Reload wallet and make sure new transactions are detected despite events
865  // being blocked
866  // Loading will also ask for current mempool transactions
867  wallet = TestLoadWallet(context);
868  BOOST_CHECK(rescan_completed);
869  // AddToWallet events for block_tx and mempool_tx (x2)
870  BOOST_CHECK_EQUAL(addtx_count, 3);
871  {
872  LOCK(wallet->cs_wallet);
873  BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_tx.GetHash()), 1U);
874  BOOST_CHECK_EQUAL(wallet->mapWallet.count(mempool_tx.GetHash()), 1U);
875  }
876 
877 
878  // Unblock notification queue and make sure stale blockConnected and
879  // transactionAddedToMempool events are processed
880  promise.set_value();
881  m_node.validation_signals->SyncWithValidationInterfaceQueue();
882  // AddToWallet events for block_tx and mempool_tx events are counted a
883  // second time as the notification queue is processed
884  BOOST_CHECK_EQUAL(addtx_count, 5);
885 
886 
887  TestUnloadWallet(std::move(wallet));
888 
889 
890  // Load wallet again, this time creating new block and mempool transactions
891  // paying to the wallet as the wallet finishes loading and syncing the
892  // queue so the events have to be handled immediately. Releasing the wallet
893  // lock during the sync is a little artificial but is needed to avoid a
894  // deadlock during the sync and simulates a new block notification happening
895  // as soon as possible.
896  addtx_count = 0;
897  auto handler = HandleLoadWallet(context, [&](std::unique_ptr<interfaces::Wallet> wallet) {
898  BOOST_CHECK(rescan_completed);
899  m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
900  block_tx = TestSimpleSpend(*m_coinbase_txns[2], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
901  m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
902  mempool_tx = TestSimpleSpend(*m_coinbase_txns[3], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
903  BOOST_CHECK(m_node.chain->broadcastTransaction(MakeTransactionRef(mempool_tx), DEFAULT_TRANSACTION_MAXFEE, false, error));
904  m_node.validation_signals->SyncWithValidationInterfaceQueue();
905  });
906  wallet = TestLoadWallet(context);
907  // Since mempool transactions are requested at the end of loading, there will
908  // be 2 additional AddToWallet calls, one from the previous test, and a duplicate for mempool_tx
909  BOOST_CHECK_EQUAL(addtx_count, 2 + 2);
910  {
911  LOCK(wallet->cs_wallet);
912  BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_tx.GetHash()), 1U);
913  BOOST_CHECK_EQUAL(wallet->mapWallet.count(mempool_tx.GetHash()), 1U);
914  }
915 
916 
917  TestUnloadWallet(std::move(wallet));
918 }
919 
920 BOOST_FIXTURE_TEST_CASE(CreateWalletWithoutChain, BasicTestingSetup)
921 {
922  WalletContext context;
923  context.args = &m_args;
924  auto wallet = TestLoadWallet(context);
926  WaitForDeleteWallet(std::move(wallet));
927 }
928 
930 {
931  m_args.ForceSetArg("-unsafesqlitesync", "1");
932  WalletContext context;
933  context.args = &m_args;
934  context.chain = m_node.chain.get();
935  auto wallet = TestLoadWallet(context);
936  CKey key = GenerateRandomKey();
937  AddKey(*wallet, key);
938 
939  std::string error;
940  m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
941  auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
942  CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
943 
944  m_node.validation_signals->SyncWithValidationInterfaceQueue();
945 
946  {
947  auto block_hash = block_tx.GetHash();
948  auto prev_tx = m_coinbase_txns[0];
949 
950  LOCK(wallet->cs_wallet);
951  BOOST_CHECK(wallet->HasWalletSpend(prev_tx));
952  BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_hash), 1u);
953 
954  std::vector<uint256> vHashIn{ block_hash };
955  BOOST_CHECK(wallet->RemoveTxs(vHashIn));
956 
957  BOOST_CHECK(!wallet->HasWalletSpend(prev_tx));
958  BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_hash), 0u);
959  }
960 
961  TestUnloadWallet(std::move(wallet));
962 }
963 
968 BOOST_FIXTURE_TEST_CASE(wallet_sync_tx_invalid_state_test, TestingSetup)
969 {
971  {
972  LOCK(wallet.cs_wallet);
973  wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
974  wallet.SetupDescriptorScriptPubKeyMans();
975  }
976 
977  // Add tx to wallet
978  const auto op_dest{*Assert(wallet.GetNewDestination(OutputType::BECH32M, ""))};
979 
981  mtx.vout.emplace_back(COIN, GetScriptForDestination(op_dest));
982  mtx.vin.emplace_back(Txid::FromUint256(m_rng.rand256()), 0);
983  const auto& tx_id_to_spend = wallet.AddToWallet(MakeTransactionRef(mtx), TxStateInMempool{})->GetHash();
984 
985  {
986  // Cache and verify available balance for the wtx
987  LOCK(wallet.cs_wallet);
988  const CWalletTx* wtx_to_spend = wallet.GetWalletTx(tx_id_to_spend);
990  }
991 
992  // Now the good case:
993  // 1) Add a transaction that spends the previously created transaction
994  // 2) Verify that the available balance of this new tx and the old one is updated (prev tx is marked dirty)
995 
996  mtx.vin.clear();
997  mtx.vin.emplace_back(tx_id_to_spend, 0);
998  wallet.transactionAddedToMempool(MakeTransactionRef(mtx));
999  const auto good_tx_id{mtx.GetHash()};
1000 
1001  {
1002  // Verify balance update for the new tx and the old one
1003  LOCK(wallet.cs_wallet);
1004  const CWalletTx* new_wtx = wallet.GetWalletTx(good_tx_id.ToUint256());
1006 
1007  // Now the old wtx
1008  const CWalletTx* wtx_to_spend = wallet.GetWalletTx(tx_id_to_spend);
1010  }
1011 
1012  // Now the bad case:
1013  // 1) Make db always fail
1014  // 2) Try to add a transaction that spends the previously created transaction and
1015  // verify that we are not moving forward if the wallet cannot store it
1017  mtx.vin.clear();
1018  mtx.vin.emplace_back(good_tx_id, 0);
1019  BOOST_CHECK_EXCEPTION(wallet.transactionAddedToMempool(MakeTransactionRef(mtx)),
1020  std::runtime_error,
1021  HasReason("DB error adding transaction to wallet, write failed"));
1022 }
1023 
1025 } // namespace wallet
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:423
RPCHelpMan importwallet()
Definition: backup.cpp:488
std::unique_ptr< interfaces::Chain > chain
Definition: context.h:76
std::optional< DatabaseFormat > require_format
Definition: db.h:194
static UniValue Parse(std::string_view raw)
Parse string to UniValue or throw runtime_error if string contains invalid JSON.
Definition: client.cpp:327
bool HaveWatchOnly(const CScript &dest) const
Returns whether the watch-only script is in the wallet.
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:41
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:110
std::any context
Definition: request.h:45
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:44
static constexpr size_t DUMMY_NESTED_P2WPKH_INPUT_SIZE
Pre-calculated constants for input size estimation in virtual size
Definition: wallet.h:143
static void AddKey(CWallet &wallet, const CKey &key)
assert(!tx.IsCoinBase())
RPCHelpMan importmulti()
Definition: backup.cpp:1254
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
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:192
Bilingual messages:
Definition: translation.h:24
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:865
node::NodeContext m_node
Definition: bitcoin-gui.cpp:42
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172
RecursiveMutex cs_KeyStore
static const DatabaseFormat DATABASE_FORMATS[]
Definition: util.h:29
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:182
std::vector< CTxIn > vin
Definition: transaction.h:379
virtual bool AddCScript(const CScript &redeemScript)
std::shared_ptr< CWallet > m_wallet
Definition: interfaces.cpp:564
void setNow(NowFn now)
Definition: wallet.h:1112
std::unique_ptr< ValidationSignals > validation_signals
Issues calls about blocks and transactions.
Definition: context.h:88
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:478
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
Definition: sign.cpp:744
static constexpr unsigned int DEFAULT_MIN_RELAY_TX_FEE
Default for -minrelaytxfee, minimum relay fee for transactions.
Definition: policy.h:66
const BaseSignatureCreator & DUMMY_MAXIMUM_SIGNATURE_CREATOR
A signature creator that just produces 72-byte empty signatures.
Definition: sign.cpp:745
State of transaction not confirmed or conflicting with a known block and not in the mempool...
Definition: transaction.h:58
bool RemoveWalletSetting(interfaces::Chain &chain, const std::string &wallet_name)
Remove wallet name from persistent configuration so it will not be loaded on startup.
Definition: wallet.cpp:107
RAII object to check and reserve a wallet rescan.
Definition: wallet.h:1081
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:189
bool reserve(bool with_passphrase=false)
Definition: wallet.h:1092
Access to the wallet database.
Definition: walletdb.h:195
State of transaction confirmed in a block.
Definition: transaction.h:31
int nFile
Definition: flatfile.h:16
void format(std::ostream &out, FormatStringCheck< sizeof...(Args)> fmt, const Args &... args)
Format list of arguments to the stream according to given format string.
Definition: tinyformat.h:1079
bool(* handler)(const std::any &context, HTTPRequest *req, const std::string &strReq)
Definition: rest.cpp:1010
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:37
BOOST_AUTO_TEST_CASE(WatchOnlyPubKeys)
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:164
OutputType
Definition: outputtype.h:17
bool GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
Fetches a pubkey from mapWatchKeys if it exists there.
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:64
constexpr unsigned char * begin()
Definition: uint256.h:115
bool LoadWatchOnly(const CScript &dest)
Adds a watch-only address to the store, without saving it to disk (used by LoadWallet) ...
Minimal stream for reading from an existing byte array by Span.
Definition: streams.h:100
CKey GenerateRandomKey(bool compressed) noexcept
Definition: key.cpp:352
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:243
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
Definition: time.cpp:40
A transaction with a bunch of additional info that only the owner cares about.
Definition: transaction.h:176
NodeContext struct containing references to chain state and connection state.
Definition: context.h:56
#define LOCK2(cs1, cs2)
Definition: sync.h:258
void WaitForDeleteWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly delete the wallet.
Definition: wallet.cpp:252
int64_t GetVirtualTransactionInputSize(const CTxIn &txin, int64_t nSigOpCost, unsigned int bytes_per_sigop)
Definition: policy.cpp:357
static std::string PathToString(const path &path)
Convert path object to a byte string.
Definition: fs.h:151
bool IsFullyValid() const
fully validate whether this is a valid public key (more expensive than IsValid()) ...
Definition: pubkey.cpp:314
static const CAmount WALLET_INCREMENTAL_RELAY_FEE
minimum recommended increment for replacement txs
Definition: wallet.h:124
UniValue params
Definition: request.h:40
BOOST_FIXTURE_TEST_SUITE(cuckoocache_tests, BasicTestingSetup)
Test Suite for CuckooCache.
An input of a transaction.
Definition: transaction.h:66
util::Result< CreatedTransactionResult > CreateTransaction(CWallet &wallet, const std::vector< CRecipient > &vecSend, std::optional< unsigned 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:1370
#define LOCK(cs)
Definition: sync.h:257
const char * name
Definition: rest.cpp:49
static void PollutePubKey(CPubKey &pubkey)
bool IsValid() const
Definition: pubkey.h:189
BOOST_AUTO_TEST_SUITE_END()
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.
std::variant< TxStateConfirmed, TxStateInMempool, TxStateBlockConflicted, TxStateInactive, TxStateUnrecognized > TxState
All possible CWalletTx states.
Definition: transaction.h:78
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:271
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:74
BOOST_CHECK_EXCEPTION predicates to check the specific validation error.
Definition: setup_common.h:295
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:299
bool malformed_descriptor(std::ios_base::failure e)
unsigned int size() const
Simple read-only vector-like interface to the pubkey data.
Definition: pubkey.h:112
Txid GetHash() const
Compute the hash of this CMutableTransaction.
Definition: transaction.cpp:69
Testing fixture that pre-creates a 100-block REGTEST-mode block chain.
Definition: setup_common.h:140
MockableDatabase & GetMockableDatabase(CWallet &wallet)
Definition: util.cpp:191
std::vector< CTxOut > vout
Definition: transaction.h:380
void setObject()
Definition: univalue.cpp:98
bool AddWalletSetting(interfaces::Chain &chain, const std::string &wallet_name)
Add wallet name to persistent configuration so it will be loaded on startup.
Definition: wallet.cpp:94
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:301
Descriptor with some wallet metadata.
Definition: walletutil.h:84
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:1125
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:424
Definition: messages.h:20
bool RemoveWallet(WalletContext &context, const std::shared_ptr< CWallet > &wallet, std::optional< bool > load_on_start, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:161
CWalletTx & AddTx(CRecipient recipient)
uint160 Hash160(const T1 &in1)
Compute the 160-bit hash an object.
Definition: hash.h:92
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:205
256-bit opaque blob.
Definition: uint256.h:201
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:186
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
std::unique_ptr< Chain > MakeChain(node::NodeContext &node)
Return implementation of Chain interface.
auto result
Definition: common-types.h:74
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:184
#define BOOST_CHECK_EQUAL(v1, v2)
Definition: object.cpp:18
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:140
void pushKV(std::string key, UniValue val)
Definition: univalue.cpp:126
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:414
static transaction_identifier FromUint256(const uint256 &id)
void TestUnloadWallet(std::shared_ptr< CWallet > &&wallet)
Definition: util.cpp:73
RPCHelpMan dumpwallet()
Definition: backup.cpp:683
constexpr unsigned char * end()
Definition: uint256.h:116
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
Definition: blockstorage.h:75
uint256 GetRandHash() noexcept
Generate a random uint256.
Definition: random.h:454
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:23
void UpdateInput(CTxIn &input, const SignatureData &data)
Definition: sign.cpp:675
void TestCoinsResult(ListCoinsTest &context, OutputType out_type, CAmount amount, std::map< OutputType, size_t > &expected_coins_sizes)
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: hex_base.cpp:29
std::unique_ptr< interfaces::Handler > HandleLoadWallet(WalletContext &context, LoadWalletFn load_wallet)
Definition: wallet.cpp:213
constexpr CAmount DEFAULT_TRANSACTION_MAXFEE
-maxtxfee default
Definition: wallet.h:137
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:36
160-bit opaque blob.
Definition: uint256.h:189
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:502
interfaces::Chain * chain
Definition: context.h:37
A mutable version of CTransaction.
Definition: transaction.h:377
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
Definition: solver.cpp:213
void clear()
Definition: univalue.cpp:18
An encapsulated private key.
Definition: key.h:34
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:295
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:153
FlatFilePos GetBlockPos() const EXCLUSIVE_LOCKS_REQUIRED(
Definition: chain.h:208
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:383
BOOST_AUTO_TEST_CASE(bnb_search_test)
UniValue HandleRequest(const JSONRPCRequest &request) const
Definition: util.cpp:659
std::string EncodeSecret(const CKey &key)
Definition: key_io.cpp:231
static bool RunWithinTxn(WalletBatch &batch, std::string_view process_desc, const std::function< bool(WalletBatch &)> &func)
Definition: walletdb.cpp:1276
ArgsManager * args
Definition: context.h:39
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:149
Coin Control Features.
Definition: coincontrol.h:80
Testing setup that configures a complete environment.
Definition: setup_common.h:121
std::unique_ptr< ChainstateManager > chainman
Definition: context.h:72
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:233
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:2992
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:504
#define Assert(val)
Identity function.
Definition: check.h:85
#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:144