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