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 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() / name);
68  }
69  CScript GetScriptPubKey(FuzzedDataProvider& fuzzed_data_provider)
70  {
71  auto type{fuzzed_data_provider.PickValueInArray(OUTPUT_TYPES)};
72  CTxDestination dest;
74  if (fuzzed_data_provider.ConsumeBool()) {
75  assert(wallet->GetNewDestination(type, "", dest, error));
76  } else {
77  assert(wallet->GetNewChangeDestination(type, dest, error));
78  }
79  assert(error.empty());
80  return GetScriptForDestination(dest);
81  }
82 };
83 
84 FUZZ_TARGET_INIT(wallet_notifications, initialize_setup)
85 {
86  FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
87  // The total amount, to be distributed to the wallets a and b in txs
88  // without fee. Thus, the balance of the wallets should always equal the
89  // total amount.
90  const auto total_amount{ConsumeMoney(fuzzed_data_provider)};
91  FuzzedWallet a{"fuzzed_wallet_a"};
92  FuzzedWallet b{"fuzzed_wallet_b"};
93 
94  // Keep track of all coins in this test.
95  // Each tuple in the chain represents the coins and the block created with
96  // those coins. Once the block is mined, the next tuple will have an empty
97  // block and the freshly mined coins.
98  using Coins = std::set<std::tuple<CAmount, COutPoint>>;
99  std::vector<std::tuple<Coins, CBlock>> chain;
100  {
101  // Add the initial entry
102  chain.emplace_back();
103  auto& [coins, block]{chain.back()};
104  coins.emplace(total_amount, COutPoint{uint256::ONE, 1});
105  }
106  LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 200)
107  {
108  CallOneOf(
109  fuzzed_data_provider,
110  [&] {
111  auto& [coins_orig, block]{chain.back()};
112  // Copy the coins for this block and consume all of them
113  Coins coins = coins_orig;
114  while (!coins.empty()) {
115  // Create a new tx
116  CMutableTransaction tx{};
117  // Add some coins as inputs to it
118  auto num_inputs{fuzzed_data_provider.ConsumeIntegralInRange<int>(1, coins.size())};
119  CAmount in{0};
120  while (num_inputs-- > 0) {
121  const auto& [coin_amt, coin_outpoint]{*coins.begin()};
122  in += coin_amt;
123  tx.vin.emplace_back(coin_outpoint);
124  coins.erase(coins.begin());
125  }
126  // Create some outputs spending all inputs, without fee
127  LIMITED_WHILE(in > 0 && fuzzed_data_provider.ConsumeBool(), 100)
128  {
129  const auto out_value{ConsumeMoney(fuzzed_data_provider, in)};
130  in -= out_value;
131  auto& wallet{fuzzed_data_provider.ConsumeBool() ? a : b};
132  tx.vout.emplace_back(out_value, wallet.GetScriptPubKey(fuzzed_data_provider));
133  }
134  // Spend the remaining input value, if any
135  auto& wallet{fuzzed_data_provider.ConsumeBool() ? a : b};
136  tx.vout.emplace_back(in, wallet.GetScriptPubKey(fuzzed_data_provider));
137  // Add tx to block
138  block.vtx.emplace_back(MakeTransactionRef(tx));
139  }
140  // Mine block
141  a.wallet->blockConnected(block, chain.size());
142  b.wallet->blockConnected(block, chain.size());
143  // Store the coins for the next block
144  Coins coins_new;
145  for (const auto& tx : block.vtx) {
146  uint32_t i{0};
147  for (const auto& out : tx->vout) {
148  coins_new.emplace(out.nValue, COutPoint{tx->GetHash(), i++});
149  }
150  }
151  chain.emplace_back(coins_new, CBlock{});
152  },
153  [&] {
154  if (chain.size() <= 1) return; // The first entry can't be removed
155  auto& [coins, block]{chain.back()};
156  if (block.vtx.empty()) return; // Can only disconnect if the block was submitted first
157  // Disconnect block
158  a.wallet->blockDisconnected(block, chain.size() - 1);
159  b.wallet->blockDisconnected(block, chain.size() - 1);
160  chain.pop_back();
161  });
162  auto& [coins, first_block]{chain.front()};
163  if (!first_block.vtx.empty()) {
164  // Only check balance when at least one block was submitted
165  const auto bal_a{GetBalance(*a.wallet).m_mine_trusted};
166  const auto bal_b{GetBalance(*b.wallet).m_mine_trusted};
167  assert(total_amount == bal_a + bal_b);
168  }
169  }
170 }
171 } // namespace
172 } // namespace wallet
BasicTestingSetup::m_node
node::NodeContext m_node
Definition: setup_common.h:85
assert
assert(!tx.IsCoinBase())
OUTPUT_TYPES
static constexpr auto OUTPUT_TYPES
Definition: outputtype.h:25
wallet.h
wallet::DatabaseStatus
DatabaseStatus
Definition: db.h:213
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
wallet::WALLET_FLAG_DESCRIPTORS
@ WALLET_FLAG_DESCRIPTORS
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:66
FuzzedDataProvider::PickValueInArray
T PickValueInArray(const T(&array)[size])
Definition: FuzzedDataProvider.h:303
MakeTransactionRef
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:407
wallet
Definition: node.h:38
wallet
std::shared_ptr< CWallet > wallet
Definition: notifications.cpp:38
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:82
FuzzedDataProvider.h
ArgsManager::ForceSetArg
void ForceSetArg(const std::string &strArg, const std::string &strValue)
Definition: system.cpp:622
CAmount
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
context
WalletContext context
Definition: notifications.cpp:37
wallet::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:263
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:87
name
const char * name
Definition: rest.cpp:52
CBlock
Definition: block.h:62
ArgsManager
Definition: system.h:164
translation.h
fuzz.h
FuzzedDataProvider
Definition: FuzzedDataProvider.h:31
wallet::GetWalletDir
fs::path GetWalletDir()
Get the path of the wallet directory.
Definition: walletutil.cpp:11
TestingSetup
Testing setup that configures a complete environment.
Definition: setup_common.h:107
wallet::GetBalance
Balance GetBalance(const CWallet &wallet, const int min_depth, bool avoid_reuse)
Definition: receive.cpp:316
context.h
receive.h
walletdb.h
COutPoint
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:26
wallet::UnloadWallet
void UnloadWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly unload and delete the wallet.
Definition: wallet.cpp:194
error
bool error(const char *fmt, const Args &... args)
Definition: system.h:49
FuzzedDataProvider::ConsumeBool
bool ConsumeBool()
Definition: FuzzedDataProvider.h:288
FUZZ_TARGET_INIT
#define FUZZ_TARGET_INIT(name, init_fun)
Definition: fuzz.h:34
ConsumeMoney
CAmount ConsumeMoney(FuzzedDataProvider &fuzzed_data_provider, const std::optional< CAmount > &max) noexcept
Definition: util.cpp:276
wallet::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:122
wallet::Balance::m_mine_trusted
CAmount m_mine_trusted
Trusted, at depth=GetBalance.min_depth or more.
Definition: receive.h:53
node::NodeContext::chain
std::unique_ptr< interfaces::Chain > chain
Definition: context.h:51
args
ArgsManager args
Definition: notifications.cpp:36
uint256::ONE
static const uint256 ONE
Definition: uint256.h:132