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
21namespace {
22const TestingSetup* g_setup;
23
24void initialize_setup()
25{
26 static const auto testing_setup = MakeNoLogFileContext<const TestingSetup>();
27 g_setup = testing_setup.get();
28}
29
34struct 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);
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 if (type == OutputType::BECH32M) {
72 type = OutputType::BECH32; // TODO: Setup taproot descriptor and remove this line
73 }
74 CTxDestination dest;
76 if (fuzzed_data_provider.ConsumeBool()) {
77 assert(wallet->GetNewDestination(type, "", dest, error));
78 } else {
79 assert(wallet->GetNewChangeDestination(type, dest, error));
80 }
81 assert(error.empty());
82 return GetScriptForDestination(dest);
83 }
84};
85
86FUZZ_TARGET_INIT(wallet_notifications, initialize_setup)
87{
88 FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
89 // The total amount, to be distributed to the wallets a and b in txs
90 // without fee. Thus, the balance of the wallets should always equal the
91 // total amount.
92 const auto total_amount{ConsumeMoney(fuzzed_data_provider)};
93 FuzzedWallet a{"fuzzed_wallet_a"};
94 FuzzedWallet b{"fuzzed_wallet_b"};
95
96 // Keep track of all coins in this test.
97 // Each tuple in the chain represents the coins and the block created with
98 // those coins. Once the block is mined, the next tuple will have an empty
99 // block and the freshly mined coins.
100 using Coins = std::set<std::tuple<CAmount, COutPoint>>;
101 std::vector<std::tuple<Coins, CBlock>> chain;
102 {
103 // Add the inital entry
104 chain.emplace_back();
105 auto& [coins, block]{chain.back()};
106 coins.emplace(total_amount, COutPoint{uint256::ONE, 1});
107 }
108 LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 200)
109 {
110 CallOneOf(
111 fuzzed_data_provider,
112 [&] {
113 auto& [coins_orig, block]{chain.back()};
114 // Copy the coins for this block and consume all of them
115 Coins coins = coins_orig;
116 while (!coins.empty()) {
117 // Create a new tx
118 CMutableTransaction tx{};
119 // Add some coins as inputs to it
120 auto num_inputs{fuzzed_data_provider.ConsumeIntegralInRange<int>(1, coins.size())};
121 CAmount in{0};
122 while (num_inputs-- > 0) {
123 const auto& [coin_amt, coin_outpoint]{*coins.begin()};
124 in += coin_amt;
125 tx.vin.emplace_back(coin_outpoint);
126 coins.erase(coins.begin());
127 }
128 // Create some outputs spending all inputs, without fee
129 LIMITED_WHILE(in > 0 && fuzzed_data_provider.ConsumeBool(), 100)
130 {
131 const auto out_value{ConsumeMoney(fuzzed_data_provider, in)};
132 in -= out_value;
133 auto& wallet{fuzzed_data_provider.ConsumeBool() ? a : b};
134 tx.vout.emplace_back(out_value, wallet.GetScriptPubKey(fuzzed_data_provider));
135 }
136 // Spend the remaining input value, if any
137 auto& wallet{fuzzed_data_provider.ConsumeBool() ? a : b};
138 tx.vout.emplace_back(in, wallet.GetScriptPubKey(fuzzed_data_provider));
139 // Add tx to block
140 block.vtx.emplace_back(MakeTransactionRef(tx));
141 }
142 // Mine block
143 a.wallet->blockConnected(block, chain.size());
144 b.wallet->blockConnected(block, chain.size());
145 // Store the coins for the next block
146 Coins coins_new;
147 for (const auto& tx : block.vtx) {
148 uint32_t i{0};
149 for (const auto& out : tx->vout) {
150 coins_new.emplace(out.nValue, COutPoint{tx->GetHash(), i++});
151 }
152 }
153 chain.emplace_back(coins_new, CBlock{});
154 },
155 [&] {
156 if (chain.size() <= 1) return; // The first entry can't be removed
157 auto& [coins, block]{chain.back()};
158 if (block.vtx.empty()) return; // Can only disconnect if the block was submitted first
159 // Disconnect block
160 a.wallet->blockDisconnected(block, chain.size() - 1);
161 b.wallet->blockDisconnected(block, chain.size() - 1);
162 chain.pop_back();
163 });
164 auto& [coins, first_block]{chain.front()};
165 if (!first_block.vtx.empty()) {
166 // Only check balance when at least one block was submitted
167 const auto bal_a{GetBalance(*a.wallet).m_mine_trusted};
168 const auto bal_b{GetBalance(*b.wallet).m_mine_trusted};
169 assert(total_amount == bal_a + bal_b);
170 }
171 }
172}
173} // namespace
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
void ForceSetArg(const std::string &strArg, const std::string &strValue)
Definition: system.cpp:624
Definition: block.h:63
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:27
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:406
T PickValueInArray(const T(&array)[size])
static const uint256 ONE
Definition: uint256.h:130
DatabaseStatus
Definition: db.h:212
#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 constexpr auto OUTPUT_TYPES
Definition: outputtype.h:25
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:387
Balance GetBalance(const CWallet &wallet, const int min_depth, bool avoid_reuse)
Definition: receive.cpp:317
const char * name
Definition: rest.cpp:43
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:310
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:157
CAmount m_mine_trusted
Trusted, at depth=GetBalance.min_depth or more.
Definition: receive.h:52
NodeContext m_node
Definition: setup_common.h:78
bool require_create
Definition: db.h:205
uint64_t create_flags
Definition: db.h:207
std::unique_ptr< interfaces::Chain > chain
Definition: context.h:50
Testing setup that configures a complete environment.
Definition: setup_common.h:99
WalletContext struct containing references to state shared between CWallet instances,...
Definition: context.h:34
ArgsManager * args
Definition: context.h:36
interfaces::Chain * chain
Definition: context.h:35
Bilingual messages:
Definition: translation.h:16
bool error(const char *fmt, const Args &... args)
Definition: system.h:49
CAmount ConsumeMoney(FuzzedDataProvider &fuzzed_data_provider, const std::optional< CAmount > &max) noexcept
Definition: util.cpp:222
size_t CallOneOf(FuzzedDataProvider &fuzzed_data_provider, Callables... callables)
Definition: util.h:40
ArgsManager gArgs
Definition: system.cpp:85
assert(!tx.IsCoinBase())
bool RemoveWallet(WalletContext &context, const std::shared_ptr< CWallet > &wallet, std::optional< bool > load_on_start, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:117
void UnloadWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly unload and delete the wallet.
Definition: wallet.cpp:189
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:258
fs::path GetWalletDir()
Get the path of the wallet directory.
Definition: walletutil.cpp:10
@ WALLET_FLAG_DESCRIPTORS
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:65