Branch data Line data Source code
1 : : // Copyright (c) 2021-present 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 <addresstype.h>
6 : : #include <common/args.h>
7 : : #include <consensus/amount.h>
8 : : #include <interfaces/chain.h>
9 : : #include <kernel/chain.h>
10 : : #include <outputtype.h>
11 : : #include <policy/feerate.h>
12 : : #include <policy/policy.h>
13 : : #include <primitives/block.h>
14 : : #include <primitives/transaction.h>
15 : : #include <script/descriptor.h>
16 : : #include <script/script.h>
17 : : #include <script/signingprovider.h>
18 : : #include <sync.h>
19 : : #include <test/fuzz/FuzzedDataProvider.h>
20 : : #include <test/fuzz/fuzz.h>
21 : : #include <test/fuzz/util.h>
22 : : #include <test/util/setup_common.h>
23 : : #include <tinyformat.h>
24 : : #include <uint256.h>
25 : : #include <util/check.h>
26 : : #include <util/result.h>
27 : 2 : #include <util/translation.h>
28 : : #include <wallet/coincontrol.h>
29 : : #include <wallet/context.h>
30 : : #include <wallet/fees.h>
31 : : #include <wallet/receive.h>
32 : : #include <wallet/spend.h>
33 : : #include <wallet/test/util.h>
34 : : #include <wallet/wallet.h>
35 [ + - ]: 2 : #include <wallet/walletutil.h>
36 : :
37 : : #include <cstddef>
38 : : #include <cstdint>
39 : : #include <limits>
40 : : #include <numeric>
41 : : #include <set>
42 : : #include <string>
43 : : #include <tuple>
44 : : #include <utility>
45 : : #include <vector>
46 : :
47 : : namespace wallet {
48 : : namespace {
49 : : const TestingSetup* g_setup;
50 : :
51 : 0 : void initialize_setup()
52 : : {
53 [ # # ][ # # ]: 0 : static const auto testing_setup = MakeNoLogFileContext<const TestingSetup>();
[ # # ]
54 : 0 : g_setup = testing_setup.get();
55 : 0 : }
56 : :
57 : 0 : void ImportDescriptors(CWallet& wallet, const std::string& seed_insecure)
58 : : {
59 [ # # ][ # # ]: 0 : const std::vector<std::string> DESCS{
60 [ # # ]: 0 : "pkh(%s/%s/*)",
61 [ # # ]: 0 : "sh(wpkh(%s/%s/*))",
62 [ # # ]: 0 : "tr(%s/%s/*)",
63 [ # # ]: 0 : "wpkh(%s/%s/*)",
64 : : };
65 : :
66 [ # # ]: 0 : for (const std::string& desc_fmt : DESCS) {
67 [ # # ]: 0 : for (bool internal : {true, false}) {
68 [ # # ][ # # ]: 0 : const auto descriptor{(strprintf)(desc_fmt, "[5aa9973a/66h/4h/2h]" + seed_insecure, int{internal})};
69 : :
70 : 0 : FlatSigningProvider keys;
71 : 0 : std::string error;
72 [ # # ]: 0 : auto parsed_desc = Parse(descriptor, keys, error, /*require_checksum=*/false);
73 [ # # ]: 0 : assert(parsed_desc);
74 [ # # ]: 0 : assert(error.empty());
75 [ # # ][ # # ]: 0 : assert(parsed_desc->IsRange());
76 [ # # ][ # # ]: 0 : assert(parsed_desc->IsSingleType());
77 [ # # ]: 0 : assert(!keys.keys.empty());
78 [ # # ][ # # ]: 0 : WalletDescriptor w_desc{std::move(parsed_desc), /*creation_time=*/0, /*range_start=*/0, /*range_end=*/1, /*next_index=*/0};
79 [ # # ][ # # ]: 0 : assert(!wallet.GetDescriptorScriptPubKeyMan(w_desc));
80 [ # # ]: 0 : LOCK(wallet.cs_wallet);
81 [ # # ][ # # ]: 0 : auto spk_manager{wallet.AddWalletDescriptor(w_desc, keys, /*label=*/"", internal)};
82 [ # # ]: 0 : assert(spk_manager);
83 [ # # ][ # # ]: 0 : wallet.AddActiveScriptPubKeyMan(spk_manager->GetID(), *Assert(w_desc.descriptor->GetOutputType()), internal);
[ # # ][ # # ]
84 : 0 : }
85 : : }
86 : 0 : }
87 : :
88 : : /**
89 : : * Wraps a descriptor wallet for fuzzing.
90 : : */
91 : 0 : struct FuzzedWallet {
92 : : ArgsManager args;
93 : : WalletContext context;
94 : : std::shared_ptr<CWallet> wallet;
95 [ # # ]: 0 : FuzzedWallet(const std::string& name, const std::string& seed_insecure)
96 : : {
97 [ # # ]: 0 : auto& chain{*Assert(g_setup->m_node.chain)};
98 [ # # ][ # # ]: 2 : wallet = std::make_shared<CWallet>(&chain, name, CreateMockableWalletDatabase());
99 : : {
100 [ # # ][ # # ]: 0 : LOCK(wallet->cs_wallet);
101 [ # # ]: 0 : wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
102 [ # # ][ # # ]: 0 : auto height{*Assert(chain.getHeight())};
103 [ # # ][ # # ]: 0 : wallet->SetLastBlockProcessed(height, chain.getBlockHash(height));
104 : 0 : }
105 : 0 : wallet->m_keypool_size = 1; // Avoid timeout in TopUp()
106 [ # # ][ # # ]: 2 : assert(wallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
107 [ # # ]: 0 : ImportDescriptors(*wallet, seed_insecure);
108 : 0 : }
109 : 0 : CTxDestination GetDestination(FuzzedDataProvider& fuzzed_data_provider)
110 : : {
111 : 0 : auto type{fuzzed_data_provider.PickValueInArray(OUTPUT_TYPES)};
112 [ # # ]: 0 : util::Result<CTxDestination> op_dest{util::Error{}};
113 [ # # ][ # # ]: 0 : if (fuzzed_data_provider.ConsumeBool()) {
114 [ # # ][ # # ]: 0 : op_dest = wallet->GetNewDestination(type, "");
115 : 0 : } else {
116 [ # # ]: 0 : op_dest = wallet->GetNewChangeDestination(type);
117 : : }
118 [ # # ][ # # ]: 0 : return *Assert(op_dest);
[ # # ]
119 : 0 : }
120 [ # # ]: 0 : CScript GetScriptPubKey(FuzzedDataProvider& fuzzed_data_provider) { return GetScriptForDestination(GetDestination(fuzzed_data_provider)); }
121 : 0 : void FundTx(FuzzedDataProvider& fuzzed_data_provider, CMutableTransaction tx)
122 : : {
123 : : // The fee of "tx" is 0, so this is the total input and output amount
124 : 0 : const CAmount total_amt{
125 : 0 : std::accumulate(tx.vout.begin(), tx.vout.end(), CAmount{}, [](CAmount t, const CTxOut& out) { return t + out.nValue; })};
126 [ # # ]: 0 : const uint32_t tx_size(GetVirtualTransactionSize(CTransaction{tx}));
127 : 0 : std::set<int> subtract_fee_from_outputs;
128 [ # # ][ # # ]: 0 : if (fuzzed_data_provider.ConsumeBool()) {
129 [ # # ]: 0 : for (size_t i{}; i < tx.vout.size(); ++i) {
130 [ # # ][ # # ]: 0 : if (fuzzed_data_provider.ConsumeBool()) {
131 [ # # ]: 0 : subtract_fee_from_outputs.insert(i);
132 : 0 : }
133 : 0 : }
134 : 0 : }
135 [ # # ]: 0 : CCoinControl coin_control;
136 [ # # ]: 0 : coin_control.m_allow_other_inputs = fuzzed_data_provider.ConsumeBool();
137 [ # # ]: 0 : CallOneOf(
138 : 0 : fuzzed_data_provider, [&] { coin_control.destChange = GetDestination(fuzzed_data_provider); },
139 : 0 : [&] { coin_control.m_change_type.emplace(fuzzed_data_provider.PickValueInArray(OUTPUT_TYPES)); },
140 : 0 : [&] { /* no op (leave uninitialized) */ });
141 [ # # ]: 0 : coin_control.fAllowWatchOnly = fuzzed_data_provider.ConsumeBool();
142 [ # # ]: 0 : coin_control.m_include_unsafe_inputs = fuzzed_data_provider.ConsumeBool();
143 : : {
144 : 0 : auto& r{coin_control.m_signal_bip125_rbf};
145 [ # # ]: 0 : CallOneOf(
146 : 0 : fuzzed_data_provider, [&] { r = true; }, [&] { r = false; }, [&] { r = std::nullopt; });
147 : : }
148 [ # # ]: 0 : coin_control.m_feerate = CFeeRate{
149 : : // A fee of this range should cover all cases
150 [ # # ]: 0 : fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(0, 2 * total_amt),
151 : 0 : tx_size,
152 : : };
153 [ # # ][ # # ]: 0 : if (fuzzed_data_provider.ConsumeBool()) {
154 [ # # ][ # # ]: 0 : *coin_control.m_feerate += GetMinimumFeeRate(*wallet, coin_control, nullptr);
155 : 0 : }
156 [ # # ]: 0 : coin_control.fOverrideFeeRate = fuzzed_data_provider.ConsumeBool();
157 : : // Add solving data (m_external_provider and SelectExternal)?
158 : :
159 : 0 : int change_position{fuzzed_data_provider.ConsumeIntegralInRange<int>(-1, tx.vout.size() - 1)};
160 : 0 : bilingual_str error;
161 [ # # ][ # # ]: 0 : (void)FundTransaction(*wallet, tx, change_position, /*lockUnspents=*/false, subtract_fee_from_outputs, coin_control);
162 : 0 : }
163 [ + - ]: 2 : };
164 [ + - ]: 2 :
165 [ + - ][ + - ]: 6 : FUZZ_TARGET(wallet_notifications, .init = initialize_setup)
166 [ + - ]: 2 : {
167 [ + - ]: 2 : FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
168 [ + - ]: 2 : // The total amount, to be distributed to the wallets a and b in txs
169 [ + - ]: 2 : // without fee. Thus, the balance of the wallets should always equal the
170 [ + - ]: 2 : // total amount.
171 : 0 : const auto total_amount{ConsumeMoney(fuzzed_data_provider, /*max=*/MAX_MONEY / 100000)};
172 [ # # ]: 0 : FuzzedWallet a{
173 [ # # ]: 0 : "fuzzed_wallet_a",
174 [ # # ]: 0 : "tprv8ZgxMBicQKsPd1QwsGgzfu2pcPYbBosZhJknqreRHgsWx32nNEhMjGQX2cgFL8n6wz9xdDYwLcs78N4nsCo32cxEX8RBtwGsEGgybLiQJfk",
175 : : };
176 [ # # ]: 0 : FuzzedWallet b{
177 [ # # ]: 0 : "fuzzed_wallet_b",
178 [ # # ]: 0 : "tprv8ZgxMBicQKsPfCunYTF18sEmEyjz8TfhGnZ3BoVAhkqLv7PLkQgmoG2Ecsp4JuqciWnkopuEwShit7st743fdmB9cMD4tznUkcs33vK51K9",
179 : : };
180 : :
181 : : // Keep track of all coins in this test.
182 : : // Each tuple in the chain represents the coins and the block created with
183 : : // those coins. Once the block is mined, the next tuple will have an empty
184 : : // block and the freshly mined coins.
185 : : using Coins = std::set<std::tuple<CAmount, COutPoint>>;
186 : 0 : std::vector<std::tuple<Coins, CBlock>> chain;
187 : : {
188 : : // Add the initial entry
189 [ # # ]: 0 : chain.emplace_back();
190 : 0 : auto& [coins, block]{chain.back()};
191 [ # # ][ # # ]: 0 : coins.emplace(total_amount, COutPoint{Txid::FromUint256(uint256::ONE), 1});
[ # # ]
192 : : }
193 [ # # ][ # # ]: 0 : LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 200)
[ # # ]
194 : : {
195 [ # # ]: 0 : CallOneOf(
196 : : fuzzed_data_provider,
197 : 0 : [&] {
198 : 0 : auto& [coins_orig, block]{chain.back()};
199 : : // Copy the coins for this block and consume all of them
200 : 0 : Coins coins = coins_orig;
201 [ # # ]: 0 : while (!coins.empty()) {
202 : : // Create a new tx
203 [ # # ]: 0 : CMutableTransaction tx{};
204 : : // Add some coins as inputs to it
205 [ # # ]: 0 : auto num_inputs{fuzzed_data_provider.ConsumeIntegralInRange<int>(1, coins.size())};
206 : 0 : CAmount in{0};
207 [ # # ]: 0 : while (num_inputs-- > 0) {
208 : 0 : const auto& [coin_amt, coin_outpoint]{*coins.begin()};
209 : 0 : in += coin_amt;
210 [ # # ][ # # ]: 0 : tx.vin.emplace_back(coin_outpoint);
211 [ # # ]: 0 : coins.erase(coins.begin());
212 : : }
213 : : // Create some outputs spending all inputs, without fee
214 [ # # ][ # # ]: 0 : LIMITED_WHILE(in > 0 && fuzzed_data_provider.ConsumeBool(), 10)
[ # # ][ # # ]
215 : : {
216 : 0 : const auto out_value{ConsumeMoney(fuzzed_data_provider, in)};
217 : 0 : in -= out_value;
218 [ # # ][ # # ]: 0 : auto& wallet{fuzzed_data_provider.ConsumeBool() ? a : b};
219 [ # # ][ # # ]: 0 : tx.vout.emplace_back(out_value, wallet.GetScriptPubKey(fuzzed_data_provider));
220 : 0 : }
221 : : // Spend the remaining input value, if any
222 [ # # ][ # # ]: 0 : auto& wallet{fuzzed_data_provider.ConsumeBool() ? a : b};
223 [ # # ][ # # ]: 0 : tx.vout.emplace_back(in, wallet.GetScriptPubKey(fuzzed_data_provider));
224 : : // Add tx to block
225 [ # # ][ # # ]: 0 : block.vtx.emplace_back(MakeTransactionRef(tx));
226 : : // Check that funding the tx doesn't crash the wallet
227 [ # # ][ # # ]: 0 : a.FundTx(fuzzed_data_provider, tx);
228 [ # # ][ # # ]: 0 : b.FundTx(fuzzed_data_provider, tx);
229 : 0 : }
230 : : // Mine block
231 [ # # ]: 0 : const uint256& hash = block.GetHash();
232 [ # # ]: 0 : interfaces::BlockInfo info{hash};
233 : 0 : info.prev_hash = &block.hashPrevBlock;
234 : 0 : info.height = chain.size();
235 : 0 : info.data = █
236 : : // Ensure that no blocks are skipped by the wallet by setting the chain's accumulated
237 : : // time to the maximum value. This ensures that the wallet's birth time is always
238 : : // earlier than this maximum time.
239 : 0 : info.chain_time_max = std::numeric_limits<unsigned int>::max();
240 [ # # ]: 0 : a.wallet->blockConnected(ChainstateRole::NORMAL, info);
241 [ # # ]: 0 : b.wallet->blockConnected(ChainstateRole::NORMAL, info);
242 : : // Store the coins for the next block
243 : 0 : Coins coins_new;
244 [ # # ]: 0 : for (const auto& tx : block.vtx) {
245 : 0 : uint32_t i{0};
246 [ # # ]: 0 : for (const auto& out : tx->vout) {
247 [ # # ][ # # ]: 0 : coins_new.emplace(out.nValue, COutPoint{tx->GetHash(), i++});
[ # # ]
248 : : }
249 : : }
250 [ # # ][ # # ]: 0 : chain.emplace_back(coins_new, CBlock{});
251 : 0 : },
252 : 0 : [&] {
253 [ # # ]: 0 : if (chain.size() <= 1) return; // The first entry can't be removed
254 : 0 : auto& [coins, block]{chain.back()};
255 [ # # ]: 0 : if (block.vtx.empty()) return; // Can only disconnect if the block was submitted first
256 : : // Disconnect block
257 : 0 : const uint256& hash = block.GetHash();
258 : 0 : interfaces::BlockInfo info{hash};
259 : 0 : info.prev_hash = &block.hashPrevBlock;
260 : 0 : info.height = chain.size() - 1;
261 : 0 : info.data = █
262 : 0 : a.wallet->blockDisconnected(info);
263 : 0 : b.wallet->blockDisconnected(info);
264 : 0 : chain.pop_back();
265 : 0 : });
266 : 0 : auto& [coins, first_block]{chain.front()};
267 [ + - ][ # # ]: 2 : if (!first_block.vtx.empty()) {
268 : : // Only check balance when at least one block was submitted
269 [ # # ]: 0 : const auto bal_a{GetBalance(*a.wallet).m_mine_trusted};
270 [ # # ]: 0 : const auto bal_b{GetBalance(*b.wallet).m_mine_trusted};
271 [ # # ]: 0 : assert(total_amount == bal_a + bal_b);
272 : 0 : }
273 : 0 : }
274 : 0 : }
275 : : } // namespace
276 : : } // namespace wallet
|