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 : 0 : void ImportDescriptors(CWallet& wallet, const std::string& seed_insecure)
57 : : {
58 : 0 : const std::vector<std::string> DESCS{
59 : : "pkh(%s/%s/*)",
60 : : "sh(wpkh(%s/%s/*))",
61 : : "tr(%s/%s/*)",
62 : : "wpkh(%s/%s/*)",
63 [ # # # # : 0 : };
# # # # #
# # # ]
64 : :
65 [ # # ]: 0 : for (const std::string& desc_fmt : DESCS) {
66 [ # # ]: 0 : for (bool internal : {true, false}) {
67 [ # # # # ]: 0 : const auto descriptor{(strprintf)(desc_fmt, "[5aa9973a/66h/4h/2h]" + seed_insecure, int{internal})};
68 : :
69 : 0 : FlatSigningProvider keys;
70 [ # # ]: 0 : std::string error;
71 [ # # ]: 0 : auto parsed_desc = Parse(descriptor, keys, error, /*require_checksum=*/false);
72 [ # # ]: 0 : assert(parsed_desc);
73 [ # # ]: 0 : assert(error.empty());
74 [ # # # # ]: 0 : assert(parsed_desc->IsRange());
75 [ # # # # ]: 0 : assert(parsed_desc->IsSingleType());
76 [ # # ]: 0 : assert(!keys.keys.empty());
77 [ # # # # ]: 0 : WalletDescriptor w_desc{std::move(parsed_desc), /*creation_time=*/0, /*range_start=*/0, /*range_end=*/1, /*next_index=*/0};
78 [ # # # # ]: 0 : assert(!wallet.GetDescriptorScriptPubKeyMan(w_desc));
79 [ # # ]: 0 : LOCK(wallet.cs_wallet);
80 [ # # # # ]: 0 : auto spk_manager{wallet.AddWalletDescriptor(w_desc, keys, /*label=*/"", internal)};
81 [ # # ]: 0 : assert(spk_manager);
82 [ # # # # : 0 : wallet.AddActiveScriptPubKeyMan(spk_manager->GetID(), *Assert(w_desc.descriptor->GetOutputType()), internal);
# # # # ]
83 : 0 : }
84 : : }
85 : 0 : }
86 : :
87 : : /**
88 : : * Wraps a descriptor wallet for fuzzing.
89 : : */
90 [ # # # # ]: 0 : struct FuzzedWallet {
91 : : std::shared_ptr<CWallet> wallet;
92 : 0 : FuzzedWallet(const std::string& name, const std::string& seed_insecure)
93 [ # # ]: 0 : {
94 [ # # # # ]: 0 : auto& chain{*Assert(g_setup->m_node.chain)};
95 [ # # # # : 0 : wallet = std::make_shared<CWallet>(&chain, name, CreateMockableWalletDatabase());
# # ]
96 : 0 : {
97 [ # # ]: 0 : LOCK(wallet->cs_wallet);
98 [ # # ]: 0 : wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
99 [ # # # # : 0 : auto height{*Assert(chain.getHeight())};
# # ]
100 [ # # # # ]: 0 : wallet->SetLastBlockProcessed(height, chain.getBlockHash(height));
101 : 0 : }
102 [ # # ]: 0 : wallet->m_keypool_size = 1; // Avoid timeout in TopUp()
103 [ # # # # ]: 0 : assert(wallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
104 [ # # ]: 0 : ImportDescriptors(*wallet, seed_insecure);
105 [ # # ]: 0 : }
106 : 0 : CTxDestination GetDestination(FuzzedDataProvider& fuzzed_data_provider)
107 : : {
108 : 0 : auto type{fuzzed_data_provider.PickValueInArray(OUTPUT_TYPES)};
109 [ # # ]: 0 : if (fuzzed_data_provider.ConsumeBool()) {
110 [ # # # # : 0 : return *Assert(wallet->GetNewDestination(type, ""));
# # ]
111 : : } else {
112 [ # # # # ]: 0 : return *Assert(wallet->GetNewChangeDestination(type));
113 : : }
114 : : }
115 [ # # ]: 0 : CScript GetScriptPubKey(FuzzedDataProvider& fuzzed_data_provider) { return GetScriptForDestination(GetDestination(fuzzed_data_provider)); }
116 : 0 : 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 : 0 : const CAmount total_amt{
120 : 0 : std::accumulate(tx.vout.begin(), tx.vout.end(), CAmount{}, [](CAmount t, const CTxOut& out) { return t + out.nValue; })};
121 [ # # ]: 0 : const uint32_t tx_size(GetVirtualTransactionSize(CTransaction{tx}));
122 : 0 : std::set<int> subtract_fee_from_outputs;
123 [ # # ]: 0 : if (fuzzed_data_provider.ConsumeBool()) {
124 [ # # ]: 0 : for (size_t i{}; i < tx.vout.size(); ++i) {
125 [ # # ]: 0 : if (fuzzed_data_provider.ConsumeBool()) {
126 [ # # ]: 0 : subtract_fee_from_outputs.insert(i);
127 : : }
128 : : }
129 : : }
130 : 0 : std::vector<CRecipient> recipients;
131 [ # # ]: 0 : for (size_t idx = 0; idx < tx.vout.size(); idx++) {
132 [ # # ]: 0 : const CTxOut& tx_out = tx.vout[idx];
133 : 0 : CTxDestination dest;
134 [ # # ]: 0 : ExtractDestination(tx_out.scriptPubKey, dest);
135 [ # # ]: 0 : CRecipient recipient = {dest, tx_out.nValue, subtract_fee_from_outputs.count(idx) == 1};
136 [ # # ]: 0 : recipients.push_back(recipient);
137 : 0 : }
138 [ # # ]: 0 : CCoinControl coin_control;
139 : 0 : coin_control.m_allow_other_inputs = fuzzed_data_provider.ConsumeBool();
140 [ # # ]: 0 : CallOneOf(
141 : 0 : fuzzed_data_provider, [&] { coin_control.destChange = GetDestination(fuzzed_data_provider); },
142 [ # # ]: 0 : [&] { coin_control.m_change_type.emplace(fuzzed_data_provider.PickValueInArray(OUTPUT_TYPES)); },
143 : : [&] { /* no op (leave uninitialized) */ });
144 : 0 : coin_control.fAllowWatchOnly = fuzzed_data_provider.ConsumeBool();
145 : 0 : coin_control.m_include_unsafe_inputs = fuzzed_data_provider.ConsumeBool();
146 : 0 : {
147 : 0 : auto& r{coin_control.m_signal_bip125_rbf};
148 : 0 : CallOneOf(
149 [ # # ]: 0 : fuzzed_data_provider, [&] { r = true; }, [&] { r = false; }, [&] { r = std::nullopt; });
150 : : }
151 : 0 : coin_control.m_feerate = CFeeRate{
152 : : // A fee of this range should cover all cases
153 : 0 : fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(0, 2 * total_amt),
154 : : tx_size,
155 [ # # ]: 0 : };
156 [ # # ]: 0 : if (fuzzed_data_provider.ConsumeBool()) {
157 [ # # ]: 0 : *coin_control.m_feerate += GetMinimumFeeRate(*wallet, coin_control, nullptr);
158 : : }
159 : 0 : coin_control.fOverrideFeeRate = fuzzed_data_provider.ConsumeBool();
160 : : // Add solving data (m_external_provider and SelectExternal)?
161 : :
162 : 0 : int change_position{fuzzed_data_provider.ConsumeIntegralInRange<int>(-1, tx.vout.size() - 1)};
163 : 0 : 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 : 0 : tx.vout.clear();
167 [ # # # # ]: 0 : (void)FundTransaction(*wallet, tx, recipients, change_position, /*lockUnspents=*/false, coin_control);
168 : 0 : }
169 : : };
170 : :
171 [ # # ]: 0 : FUZZ_TARGET(wallet_notifications, .init = initialize_setup)
172 : : {
173 : 0 : 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 : 0 : const auto total_amount{ConsumeMoney(fuzzed_data_provider, /*max=*/MAX_MONEY / 100000)};
178 : 0 : FuzzedWallet a{
179 : : "fuzzed_wallet_a",
180 : : "tprv8ZgxMBicQKsPd1QwsGgzfu2pcPYbBosZhJknqreRHgsWx32nNEhMjGQX2cgFL8n6wz9xdDYwLcs78N4nsCo32cxEX8RBtwGsEGgybLiQJfk",
181 [ # # # # ]: 0 : };
182 [ # # ]: 0 : FuzzedWallet b{
183 : : "fuzzed_wallet_b",
184 : : "tprv8ZgxMBicQKsPfCunYTF18sEmEyjz8TfhGnZ3BoVAhkqLv7PLkQgmoG2Ecsp4JuqciWnkopuEwShit7st743fdmB9cMD4tznUkcs33vK51K9",
185 [ # # # # : 0 : };
# # ]
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 : 0 : using Coins = std::set<std::tuple<CAmount, COutPoint>>;
192 : 0 : std::vector<std::tuple<Coins, CBlock>> chain;
193 : 0 : {
194 : : // Add the initial entry
195 [ # # ]: 0 : chain.emplace_back();
196 [ # # ]: 0 : auto& [coins, block]{chain.back()};
197 [ # # ]: 0 : coins.emplace(total_amount, COutPoint{Txid::FromUint256(uint256::ONE), 1});
198 : : }
199 [ # # # # ]: 0 : LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 200)
200 : : {
201 [ # # ]: 0 : CallOneOf(
202 : : fuzzed_data_provider,
203 : 0 : [&] {
204 : 0 : auto& [coins_orig, block]{chain.back()};
205 : : // Copy the coins for this block and consume all of them
206 : 0 : Coins coins = coins_orig;
207 [ # # ]: 0 : while (!coins.empty()) {
208 : : // Create a new tx
209 [ # # ]: 0 : CMutableTransaction tx{};
210 : : // Add some coins as inputs to it
211 : 0 : auto num_inputs{fuzzed_data_provider.ConsumeIntegralInRange<int>(1, coins.size())};
212 : 0 : CAmount in{0};
213 [ # # ]: 0 : while (num_inputs-- > 0) {
214 [ # # ]: 0 : const auto& [coin_amt, coin_outpoint]{*coins.begin()};
215 : 0 : in += coin_amt;
216 [ # # ]: 0 : tx.vin.emplace_back(coin_outpoint);
217 : 0 : coins.erase(coins.begin());
218 : : }
219 : : // Create some outputs spending all inputs, without fee
220 [ # # # # : 0 : LIMITED_WHILE(in > 0 && fuzzed_data_provider.ConsumeBool(), 10)
# # ]
221 : : {
222 : 0 : const auto out_value{ConsumeMoney(fuzzed_data_provider, in)};
223 : 0 : in -= out_value;
224 [ # # ]: 0 : auto& wallet{fuzzed_data_provider.ConsumeBool() ? a : b};
225 [ # # # # ]: 0 : tx.vout.emplace_back(out_value, wallet.GetScriptPubKey(fuzzed_data_provider));
226 : : }
227 : : // Spend the remaining input value, if any
228 [ # # ]: 0 : auto& wallet{fuzzed_data_provider.ConsumeBool() ? a : b};
229 [ # # # # ]: 0 : tx.vout.emplace_back(in, wallet.GetScriptPubKey(fuzzed_data_provider));
230 : : // Add tx to block
231 [ # # # # ]: 0 : block.vtx.emplace_back(MakeTransactionRef(tx));
232 : : // Check that funding the tx doesn't crash the wallet
233 [ # # # # ]: 0 : a.FundTx(fuzzed_data_provider, tx);
234 [ # # # # ]: 0 : b.FundTx(fuzzed_data_provider, tx);
235 : 0 : }
236 : : // Mine block
237 [ # # ]: 0 : const uint256& hash = block.GetHash();
238 [ # # ]: 0 : interfaces::BlockInfo info{hash};
239 : 0 : info.prev_hash = &block.hashPrevBlock;
240 [ # # ]: 0 : info.height = chain.size();
241 : 0 : 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 : 0 : info.chain_time_max = std::numeric_limits<unsigned int>::max();
246 [ # # ]: 0 : a.wallet->blockConnected(ChainstateRole::NORMAL, info);
247 [ # # ]: 0 : b.wallet->blockConnected(ChainstateRole::NORMAL, info);
248 : : // Store the coins for the next block
249 : 0 : Coins coins_new;
250 [ # # ]: 0 : for (const auto& tx : block.vtx) {
251 : 0 : uint32_t i{0};
252 [ # # ]: 0 : for (const auto& out : tx->vout) {
253 [ # # ]: 0 : coins_new.emplace(out.nValue, COutPoint{tx->GetHash(), i++});
254 : : }
255 : : }
256 [ # # ]: 0 : chain.emplace_back(coins_new, CBlock{});
257 : 0 : },
258 : 0 : [&] {
259 [ # # ]: 0 : if (chain.size() <= 1) return; // The first entry can't be removed
260 [ # # ]: 0 : auto& [coins, block]{chain.back()};
261 [ # # ]: 0 : 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 : : });
272 [ # # ]: 0 : auto& [coins, first_block]{chain.front()};
273 [ # # ]: 0 : if (!first_block.vtx.empty()) {
274 : : // Only check balance when at least one block was submitted
275 [ # # ]: 0 : const auto bal_a{GetBalance(*a.wallet).m_mine_trusted};
276 [ # # ]: 0 : const auto bal_b{GetBalance(*b.wallet).m_mine_trusted};
277 [ # # ]: 0 : assert(total_amount == bal_a + bal_b);
278 : : }
279 : : }
280 [ # # # # ]: 0 : }
281 : : } // namespace
282 : : } // namespace wallet
|