Bitcoin Core  22.99.0
P2P Digital Currency
notifications.cpp
Go to the documentation of this file.
1 // Copyright (c) 2021 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
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 {
22 const TestingSetup* g_setup;
23 
24 void initialize_setup()
25 {
26  static const auto testing_setup = MakeNoLogFileContext<const TestingSetup>();
27  g_setup = testing_setup.get();
28 }
29 
34 struct FuzzedWallet {
35  ArgsManager args;
36  WalletContext context;
37  std::shared_ptr<CWallet> wallet;
38  FuzzedWallet(const std::string& name)
39  {
40  context.args = &args;
41  context.chain = g_setup->m_node.chain.get();
42 
43  DatabaseOptions options;
44  options.require_create = true;
46  const std::optional<bool> load_on_start;
47  gArgs.ForceSetArg("-keypool", "0"); // Avoid timeout in TopUp()
48 
49  DatabaseStatus status;
51  std::vector<bilingual_str> warnings;
52  wallet = CreateWallet(context, name, load_on_start, options, status, error, warnings);
53  assert(wallet);
54  assert(error.empty());
55  assert(warnings.empty());
56  assert(wallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
57  }
58  ~FuzzedWallet()
59  {
60  const auto name{wallet->GetName()};
61  std::vector<bilingual_str> warnings;
62  std::optional<bool> load_on_start;
63  assert(RemoveWallet(context, wallet, load_on_start, warnings));
64  assert(warnings.empty());
65  UnloadWallet(std::move(wallet));
66  fs::remove_all(GetWalletDir() / name);
67  }
68  CScript GetScriptPubKey(FuzzedDataProvider& fuzzed_data_provider)
69  {
70  auto type{fuzzed_data_provider.PickValueInArray(OUTPUT_TYPES)};
71  CTxDestination dest;
73  if (fuzzed_data_provider.ConsumeBool()) {
74  assert(wallet->GetNewDestination(type, "", dest, error));
75  } else {
76  assert(wallet->GetNewChangeDestination(type, dest, error));
77  }
78  assert(error.empty());
79  return GetScriptForDestination(dest);
80  }
81 };
82 
83 FUZZ_TARGET_INIT(wallet_notifications, 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  a.wallet->blockConnected(block, chain.size());
141  b.wallet->blockConnected(block, chain.size());
142  // Store the coins for the next block
143  Coins coins_new;
144  for (const auto& tx : block.vtx) {
145  uint32_t i{0};
146  for (const auto& out : tx->vout) {
147  coins_new.emplace(out.nValue, COutPoint{tx->GetHash(), i++});
148  }
149  }
150  chain.emplace_back(coins_new, CBlock{});
151  },
152  [&] {
153  if (chain.size() <= 1) return; // The first entry can't be removed
154  auto& [coins, block]{chain.back()};
155  if (block.vtx.empty()) return; // Can only disconnect if the block was submitted first
156  // Disconnect block
157  a.wallet->blockDisconnected(block, chain.size() - 1);
158  b.wallet->blockDisconnected(block, chain.size() - 1);
159  chain.pop_back();
160  });
161  auto& [coins, first_block]{chain.front()};
162  if (!first_block.vtx.empty()) {
163  // Only check balance when at least one block was submitted
164  const auto bal_a{GetBalance(*a.wallet).m_mine_trusted};
165  const auto bal_b{GetBalance(*b.wallet).m_mine_trusted};
166  assert(total_amount == bal_a + bal_b);
167  }
168  }
169 }
170 } // namespace
RemoveWallet
bool RemoveWallet(WalletContext &context, const std::shared_ptr< CWallet > &wallet, std::optional< bool > load_on_start, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:121
DatabaseOptions
Definition: db.h:203
assert
assert(!tx.IsCoinBase())
OUTPUT_TYPES
static constexpr auto OUTPUT_TYPES
Definition: outputtype.h:25
DatabaseStatus
DatabaseStatus
Definition: db.h:212
wallet.h
setup_common.h
GetScriptForDestination
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:310
bilingual_str
Bilingual messages:
Definition: translation.h:16
util.h
DatabaseOptions::require_create
bool require_create
Definition: db.h:205
FuzzedDataProvider::PickValueInArray
T PickValueInArray(const T(&array)[size])
Definition: FuzzedDataProvider.h:303
MakeTransactionRef
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:387
wallet
Definition: interfaces.cpp:50
GetBalance
Balance GetBalance(const CWallet &wallet, const int min_depth, bool avoid_reuse)
Definition: receive.cpp:317
CreateWallet
std::shared_ptr< CWallet > CreateWallet(WalletContext &context, const std::string &name, std::optional< bool > load_on_start, DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:262
NodeContext::chain
std::unique_ptr< interfaces::Chain > chain
Definition: context.h:50
walletutil.h
CTxDestination
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:157
CallOneOf
size_t CallOneOf(FuzzedDataProvider &fuzzed_data_provider, Callables... callables)
Definition: util.h:40
FuzzedDataProvider.h
ArgsManager::ForceSetArg
void ForceSetArg(const std::string &strArg, const std::string &strValue)
Definition: system.cpp:624
CAmount
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
LIMITED_WHILE
#define LIMITED_WHILE(condition, limit)
Can be used to limit a theoretically unbounded loop.
Definition: fuzz.h:18
CScript
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:405
gArgs
ArgsManager gArgs
Definition: system.cpp:85
name
const char * name
Definition: rest.cpp:43
UnloadWallet
void UnloadWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly unload and delete the wallet.
Definition: wallet.cpp:193
CBlock
Definition: block.h:62
BasicTestingSetup::m_node
NodeContext m_node
Definition: setup_common.h:78
ArgsManager
Definition: system.h:158
translation.h
fuzz.h
FuzzedDataProvider
Definition: FuzzedDataProvider.h:31
WalletContext::chain
interfaces::Chain * chain
Definition: context.h:35
TestingSetup
Testing setup that configures a complete environment.
Definition: setup_common.h:99
context.h
receive.h
Balance::m_mine_trusted
CAmount m_mine_trusted
Trusted, at depth=GetBalance.min_depth or more.
Definition: receive.h:52
walletdb.h
COutPoint
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:26
error
bool error(const char *fmt, const Args &... args)
Definition: system.h:49
FuzzedDataProvider::ConsumeBool
bool ConsumeBool()
Definition: FuzzedDataProvider.h:288
WalletContext::args
ArgsManager * args
Definition: context.h:36
FUZZ_TARGET_INIT
#define FUZZ_TARGET_INIT(name, init_fun)
Definition: fuzz.h:34
GetWalletDir
fs::path GetWalletDir()
Get the path of the wallet directory.
Definition: walletutil.cpp:10
ConsumeMoney
CAmount ConsumeMoney(FuzzedDataProvider &fuzzed_data_provider, const std::optional< CAmount > &max) noexcept
Definition: util.cpp:222
WalletContext
WalletContext struct containing references to state shared between CWallet instances,...
Definition: context.h:34
DatabaseOptions::create_flags
uint64_t create_flags
Definition: db.h:207
WALLET_FLAG_DESCRIPTORS
@ WALLET_FLAG_DESCRIPTORS
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:65
uint256::ONE
static const uint256 ONE
Definition: uint256.h:130