Bitcoin Core  24.99.0
P2P Digital Currency
notifications.cpp
Go to the documentation of this file.
1 // Copyright (c) 2021-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 
6 #include <test/fuzz/fuzz.h>
7 #include <test/fuzz/util.h>
9 #include <util/translation.h>
10 #include <wallet/context.h>
11 #include <wallet/receive.h>
12 #include <wallet/wallet.h>
13 #include <wallet/walletdb.h>
14 #include <wallet/walletutil.h>
15 
16 #include <cassert>
17 #include <cstdint>
18 #include <string>
19 #include <vector>
20 
21 namespace wallet {
22 namespace {
23 const TestingSetup* g_setup;
24 
25 void initialize_setup()
26 {
27  static const auto testing_setup = MakeNoLogFileContext<const TestingSetup>();
28  g_setup = testing_setup.get();
29 }
30 
35 struct FuzzedWallet {
37  WalletContext context;
38  std::shared_ptr<CWallet> wallet;
39  FuzzedWallet(const std::string& name)
40  {
41  context.args = &args;
42  context.chain = g_setup->m_node.chain.get();
43 
44  DatabaseOptions options;
45  options.require_create = true;
46  options.create_flags = WALLET_FLAG_DESCRIPTORS;
47  const std::optional<bool> load_on_start;
48  gArgs.ForceSetArg("-keypool", "0"); // Avoid timeout in TopUp()
49 
50  DatabaseStatus status;
52  std::vector<bilingual_str> warnings;
53  wallet = CreateWallet(context, name, load_on_start, options, status, error, warnings);
54  assert(wallet);
55  assert(error.empty());
56  assert(warnings.empty());
57  assert(wallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
58  }
59  ~FuzzedWallet()
60  {
61  const auto name{wallet->GetName()};
62  std::vector<bilingual_str> warnings;
63  std::optional<bool> load_on_start;
64  assert(RemoveWallet(context, wallet, load_on_start, warnings));
65  assert(warnings.empty());
66  UnloadWallet(std::move(wallet));
67  fs::remove_all(GetWalletDir() / fs::PathFromString(name));
68  }
69  CScript GetScriptPubKey(FuzzedDataProvider& fuzzed_data_provider)
70  {
71  auto type{fuzzed_data_provider.PickValueInArray(OUTPUT_TYPES)};
73  if (fuzzed_data_provider.ConsumeBool()) {
74  op_dest = wallet->GetNewDestination(type, "");
75  } else {
76  op_dest = wallet->GetNewChangeDestination(type);
77  }
78  return GetScriptForDestination(*Assert(op_dest));
79  }
80 };
81 
82 FUZZ_TARGET_INIT(wallet_notifications, initialize_setup)
83 {
84  FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
85  // The total amount, to be distributed to the wallets a and b in txs
86  // without fee. Thus, the balance of the wallets should always equal the
87  // total amount.
88  const auto total_amount{ConsumeMoney(fuzzed_data_provider)};
89  FuzzedWallet a{"fuzzed_wallet_a"};
90  FuzzedWallet b{"fuzzed_wallet_b"};
91 
92  // Keep track of all coins in this test.
93  // Each tuple in the chain represents the coins and the block created with
94  // those coins. Once the block is mined, the next tuple will have an empty
95  // block and the freshly mined coins.
96  using Coins = std::set<std::tuple<CAmount, COutPoint>>;
97  std::vector<std::tuple<Coins, CBlock>> chain;
98  {
99  // Add the initial entry
100  chain.emplace_back();
101  auto& [coins, block]{chain.back()};
102  coins.emplace(total_amount, COutPoint{uint256::ONE, 1});
103  }
104  LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 200)
105  {
106  CallOneOf(
107  fuzzed_data_provider,
108  [&] {
109  auto& [coins_orig, block]{chain.back()};
110  // Copy the coins for this block and consume all of them
111  Coins coins = coins_orig;
112  while (!coins.empty()) {
113  // Create a new tx
114  CMutableTransaction tx{};
115  // Add some coins as inputs to it
116  auto num_inputs{fuzzed_data_provider.ConsumeIntegralInRange<int>(1, coins.size())};
117  CAmount in{0};
118  while (num_inputs-- > 0) {
119  const auto& [coin_amt, coin_outpoint]{*coins.begin()};
120  in += coin_amt;
121  tx.vin.emplace_back(coin_outpoint);
122  coins.erase(coins.begin());
123  }
124  // Create some outputs spending all inputs, without fee
125  LIMITED_WHILE(in > 0 && fuzzed_data_provider.ConsumeBool(), 100)
126  {
127  const auto out_value{ConsumeMoney(fuzzed_data_provider, in)};
128  in -= out_value;
129  auto& wallet{fuzzed_data_provider.ConsumeBool() ? a : b};
130  tx.vout.emplace_back(out_value, wallet.GetScriptPubKey(fuzzed_data_provider));
131  }
132  // Spend the remaining input value, if any
133  auto& wallet{fuzzed_data_provider.ConsumeBool() ? a : b};
134  tx.vout.emplace_back(in, wallet.GetScriptPubKey(fuzzed_data_provider));
135  // Add tx to block
136  block.vtx.emplace_back(MakeTransactionRef(tx));
137  }
138  // Mine block
139  const uint256& hash = block.GetHash();
140  interfaces::BlockInfo info{hash};
141  info.prev_hash = &block.hashPrevBlock;
142  info.height = chain.size();
143  info.data = &block;
144  a.wallet->blockConnected(info);
145  b.wallet->blockConnected(info);
146  // Store the coins for the next block
147  Coins coins_new;
148  for (const auto& tx : block.vtx) {
149  uint32_t i{0};
150  for (const auto& out : tx->vout) {
151  coins_new.emplace(out.nValue, COutPoint{tx->GetHash(), i++});
152  }
153  }
154  chain.emplace_back(coins_new, CBlock{});
155  },
156  [&] {
157  if (chain.size() <= 1) return; // The first entry can't be removed
158  auto& [coins, block]{chain.back()};
159  if (block.vtx.empty()) return; // Can only disconnect if the block was submitted first
160  // Disconnect block
161  const uint256& hash = block.GetHash();
162  interfaces::BlockInfo info{hash};
163  info.prev_hash = &block.hashPrevBlock;
164  info.height = chain.size() - 1;
165  info.data = &block;
166  a.wallet->blockDisconnected(info);
167  b.wallet->blockDisconnected(info);
168  chain.pop_back();
169  });
170  auto& [coins, first_block]{chain.front()};
171  if (!first_block.vtx.empty()) {
172  // Only check balance when at least one block was submitted
173  const auto bal_a{GetBalance(*a.wallet).m_mine_trusted};
174  const auto bal_b{GetBalance(*b.wallet).m_mine_trusted};
175  assert(total_amount == bal_a + bal_b);
176  }
177  }
178 }
179 } // namespace
180 } // namespace wallet
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
#define Assert(val)
Identity function.
Definition: check.h:73
void ForceSetArg(const std::string &strArg, const std::string &strValue)
Definition: system.cpp:680
Definition: block.h:69
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:36
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:411
T PickValueInArray(const T(&array)[size])
static constexpr unsigned int size()
Definition: uint256.h:81
256-bit opaque blob.
Definition: uint256.h:119
static const uint256 ONE
Definition: uint256.h:125
#define FUZZ_TARGET_INIT(name, init_fun)
Definition: fuzz.h:34
#define LIMITED_WHILE(condition, limit)
Can be used to limit a theoretically unbounded loop.
Definition: fuzz.h:18
static path PathFromString(const std::string &string)
Convert byte string to path object.
Definition: fs.h:173
Definition: node.h:39
void UnloadWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly unload and delete the wallet.
Definition: wallet.cpp:209
Balance GetBalance(const CWallet &wallet, const int min_depth, bool avoid_reuse)
Definition: receive.cpp:293
fs::path GetWalletDir()
Get the path of the wallet directory.
Definition: walletutil.cpp:11
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:338
@ WALLET_FLAG_DESCRIPTORS
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:66
DatabaseStatus
Definition: db.h:239
bool RemoveWallet(WalletContext &context, const std::shared_ptr< CWallet > &wallet, std::optional< bool > load_on_start, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:122
std::shared_ptr< CWallet > wallet
WalletContext context
ArgsManager args
static constexpr auto OUTPUT_TYPES
Definition: outputtype.h:25
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:422
const char * name
Definition: rest.cpp:46
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:334
node::NodeContext m_node
Definition: setup_common.h:86
Testing setup that configures a complete environment.
Definition: setup_common.h:108
Bilingual messages:
Definition: translation.h:18
Block data sent with blockConnected, blockDisconnected notifications.
Definition: chain.h:82
std::unique_ptr< interfaces::Chain > chain
Definition: context.h:57
CAmount m_mine_trusted
Trusted, at depth=GetBalance.min_depth or more.
Definition: receive.h:52
bool error(const char *fmt, const Args &... args)
Definition: system.h:48
CAmount ConsumeMoney(FuzzedDataProvider &fuzzed_data_provider, const std::optional< CAmount > &max) noexcept
Definition: util.cpp:17
size_t CallOneOf(FuzzedDataProvider &fuzzed_data_provider, Callables... callables)
Definition: util.h:36
ArgsManager gArgs
Definition: system.cpp:73
assert(!tx.IsCoinBase())