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