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 <core_io.h>
6 : : #include <hash.h>
7 : : #include <key.h>
8 : : #include <script/miniscript.h>
9 : : #include <script/script.h>
10 : : #include <script/signingprovider.h>
11 : : #include <test/fuzz/FuzzedDataProvider.h>
12 : : #include <test/fuzz/fuzz.h>
13 : : #include <test/fuzz/util.h>
14 : : #include <test/fuzz/util/descriptor.h>
15 : : #include <util/strencodings.h>
16 : :
17 : : #include <algorithm>
18 : : #include <map>
19 : : #include <optional>
20 : : #include <vector>
21 : :
22 : : namespace {
23 : :
24 : : using Fragment = miniscript::Fragment;
25 : : using Node = miniscript::Node<CPubKey>;
26 : : using Type = miniscript::Type;
27 : : using MsCtx = miniscript::MiniscriptContext;
28 : : using miniscript::operator""_mst;
29 : :
30 : : //! Some pre-computed data for more efficient string roundtrips and to simulate challenges.
31 : : struct TestData {
32 : : typedef CPubKey Key;
33 : :
34 : : // Precomputed public keys, and a dummy signature for each of them.
35 : : std::vector<Key> dummy_keys;
36 : : std::map<Key, int> dummy_key_idx_map;
37 : : std::map<CKeyID, Key> dummy_keys_map;
38 : : std::map<Key, std::pair<std::vector<unsigned char>, bool>> dummy_sigs;
39 : : std::map<XOnlyPubKey, std::pair<std::vector<unsigned char>, bool>> schnorr_sigs;
40 : :
41 : : // Precomputed hashes of each kind.
42 : : std::vector<std::vector<unsigned char>> sha256;
43 : : std::vector<std::vector<unsigned char>> ripemd160;
44 : : std::vector<std::vector<unsigned char>> hash256;
45 : : std::vector<std::vector<unsigned char>> hash160;
46 : : std::map<std::vector<unsigned char>, std::vector<unsigned char>> sha256_preimages;
47 : : std::map<std::vector<unsigned char>, std::vector<unsigned char>> ripemd160_preimages;
48 : : std::map<std::vector<unsigned char>, std::vector<unsigned char>> hash256_preimages;
49 : : std::map<std::vector<unsigned char>, std::vector<unsigned char>> hash160_preimages;
50 : :
51 : : //! Set the precomputed data.
52 : 3 : void Init() {
53 : 3 : unsigned char keydata[32] = {1};
54 : : // All our signatures sign (and are required to sign) this constant message.
55 : 3 : constexpr uint256 MESSAGE_HASH{"0000000000000000f5cd94e18b6fe77dd7aca9e35c2b0c9cbd86356c80a71065"};
56 : : // We don't pass additional randomness when creating a schnorr signature.
57 : 3 : const auto EMPTY_AUX{uint256::ZERO};
58 : :
59 [ + + ]: 771 : for (size_t i = 0; i < 256; i++) {
60 : 768 : keydata[31] = i;
61 : 768 : CKey privkey;
62 [ + - ]: 768 : privkey.Set(keydata, keydata + 32, true);
63 [ + - ]: 768 : const Key pubkey = privkey.GetPubKey();
64 : :
65 [ + - ]: 768 : dummy_keys.push_back(pubkey);
66 [ + - ]: 768 : dummy_key_idx_map.emplace(pubkey, i);
67 [ + - + - ]: 768 : dummy_keys_map.insert({pubkey.GetID(), pubkey});
68 : 768 : XOnlyPubKey xonly_pubkey{pubkey};
69 [ + - ]: 768 : dummy_key_idx_map.emplace(xonly_pubkey, i);
70 [ + - ]: 768 : uint160 xonly_hash{Hash160(xonly_pubkey)};
71 [ + - ]: 768 : dummy_keys_map.emplace(xonly_hash, pubkey);
72 : :
73 [ + - ]: 768 : std::vector<unsigned char> sig, schnorr_sig(64);
74 [ + - ]: 768 : privkey.Sign(MESSAGE_HASH, sig);
75 [ + - ]: 768 : sig.push_back(1); // SIGHASH_ALL
76 [ + - + - ]: 1536 : dummy_sigs.insert({pubkey, {sig, i & 1}});
77 [ - + + - : 768 : assert(privkey.SignSchnorr(MESSAGE_HASH, schnorr_sig, nullptr, EMPTY_AUX));
- + ]
78 [ + - ]: 768 : schnorr_sig.push_back(1); // Maximally-sized signature has sighash byte
79 [ + - ]: 768 : schnorr_sigs.emplace(XOnlyPubKey{pubkey}, std::make_pair(std::move(schnorr_sig), i & 1));
80 : :
81 : 768 : std::vector<unsigned char> hash;
82 [ + - ]: 768 : hash.resize(32);
83 [ + - + - : 768 : CSHA256().Write(keydata, 32).Finalize(hash.data());
+ - ]
84 [ + - ]: 768 : sha256.push_back(hash);
85 [ + + + - : 768 : if (i & 1) sha256_preimages[hash] = std::vector<unsigned char>(keydata, keydata + 32);
+ - ]
86 [ + - + - : 768 : CHash256().Write(keydata).Finalize(hash);
- + + - ]
87 [ + - ]: 768 : hash256.push_back(hash);
88 [ + + + - : 768 : if (i & 1) hash256_preimages[hash] = std::vector<unsigned char>(keydata, keydata + 32);
+ - ]
89 [ + - ]: 768 : hash.resize(20);
90 [ + - + - : 768 : CRIPEMD160().Write(keydata, 32).Finalize(hash.data());
+ - ]
91 [ - + - + ]: 768 : assert(hash.size() == 20);
92 [ + - ]: 768 : ripemd160.push_back(hash);
93 [ + + + - : 768 : if (i & 1) ripemd160_preimages[hash] = std::vector<unsigned char>(keydata, keydata + 32);
+ - ]
94 [ + - + - : 768 : CHash160().Write(keydata).Finalize(hash);
- + + - ]
95 [ + - ]: 768 : hash160.push_back(hash);
96 [ + + + - : 768 : if (i & 1) hash160_preimages[hash] = std::vector<unsigned char>(keydata, keydata + 32);
+ - ]
97 : 768 : }
98 : 3 : }
99 : :
100 : : //! Get the (Schnorr or ECDSA, depending on context) signature for this pubkey.
101 : 239892 : const std::pair<std::vector<unsigned char>, bool>* GetSig(const MsCtx script_ctx, const Key& key) const {
102 [ + + ]: 239892 : if (!miniscript::IsTapscript(script_ctx)) {
103 : 137835 : const auto it = dummy_sigs.find(key);
104 [ + - ]: 137835 : if (it == dummy_sigs.end()) return nullptr;
105 : 137835 : return &it->second;
106 : : } else {
107 : 102057 : const auto it = schnorr_sigs.find(XOnlyPubKey{key});
108 [ + - ]: 102057 : if (it == schnorr_sigs.end()) return nullptr;
109 : 102057 : return &it->second;
110 : : }
111 : : }
112 : : } TEST_DATA;
113 : :
114 : : /**
115 : : * Context to parse a Miniscript node to and from Script or text representation.
116 : : * Uses an integer (an index in the dummy keys array from the test data) as keys in order
117 : : * to focus on fuzzing the Miniscript nodes' test representation, not the key representation.
118 : : */
119 : : struct ParserContext {
120 : : typedef CPubKey Key;
121 : :
122 : : const MsCtx script_ctx;
123 : :
124 : 9146 : constexpr ParserContext(MsCtx ctx) noexcept : script_ctx(ctx) {}
125 : :
126 : 1046386 : bool KeyCompare(const Key& a, const Key& b) const {
127 : 1046386 : return a < b;
[ + + + +
- - - - -
- - - + +
+ + + + ]
128 : : }
129 : :
130 : 162056 : std::optional<std::string> ToString(const Key& key, bool& has_priv_key) const
131 : : {
132 : 162056 : has_priv_key = false;
133 : 162056 : auto it = TEST_DATA.dummy_key_idx_map.find(key);
134 [ - + ]: 162056 : if (it == TEST_DATA.dummy_key_idx_map.end()) {
135 : 0 : return HexStr(key);
136 : : }
137 : 162056 : has_priv_key = true;
138 : 162056 : uint8_t idx = it->second;
139 : 162056 : return HexStr(std::span{&idx, 1});
140 : : }
141 : :
142 : 162414 : std::vector<unsigned char> ToPKBytes(const Key& key) const {
143 [ + + ]: 162414 : if (!miniscript::IsTapscript(script_ctx)) {
144 : 93773 : return {key.begin(), key.end()};
145 : : }
146 : 68641 : const XOnlyPubKey xonly_pubkey{key};
147 : 68641 : return {xonly_pubkey.begin(), xonly_pubkey.end()};
148 : : }
149 : :
150 : 16781 : std::vector<unsigned char> ToPKHBytes(const Key& key) const {
151 [ + + ]: 16781 : if (!miniscript::IsTapscript(script_ctx)) {
152 : 8908 : const auto h = Hash160(key);
153 : 8908 : return {h.begin(), h.end()};
154 : : }
155 : 7873 : const auto h = Hash160(XOnlyPubKey{key});
156 : 7873 : return {h.begin(), h.end()};
157 : : }
158 : :
159 : 178745 : std::optional<Key> FromString(std::span<const char>& in) const {
160 [ + + ]: 178745 : if (in.size() != 2) return {};
161 [ - + + - ]: 178742 : auto idx = ParseHex(std::string(in.begin(), in.end()));
162 [ - + + + ]: 178742 : if (idx.size() != 1) return {};
163 : 178722 : return TEST_DATA.dummy_keys[idx[0]];
164 : 178742 : }
165 : :
166 : : template<typename I>
167 : 71746 : std::optional<Key> FromPKBytes(I first, I last) const {
168 [ + + ]: 71746 : if (!miniscript::IsTapscript(script_ctx)) {
169 [ + - ]: 41603 : Key key{first, last};
170 [ + - ]: 41603 : if (key.IsValid()) return key;
171 : 0 : return {};
172 : : }
173 [ - + ]: 30143 : if (last - first != 32) return {};
174 : 30143 : XOnlyPubKey xonly_pubkey;
175 : 30143 : std::copy(first, last, xonly_pubkey.begin());
176 : 30143 : return xonly_pubkey.GetEvenCorrespondingCPubKey();
177 : : }
178 : :
179 : : template<typename I>
180 [ - + ]: 8218 : std::optional<Key> FromPKHBytes(I first, I last) const {
181 [ - + ]: 8218 : assert(last - first == 20);
182 : 8218 : CKeyID keyid;
183 : 8218 : std::copy(first, last, keyid.begin());
184 [ - + ]: 8218 : const auto it = TEST_DATA.dummy_keys_map.find(keyid);
185 [ - + ]: 8218 : if (it == TEST_DATA.dummy_keys_map.end()) return {};
186 : 8218 : return it->second;
187 : : }
188 : :
189 : 2215544 : MsCtx MsContext() const {
190 : 2215544 : return script_ctx;
[ + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + + + -
+ - ]
191 : : }
192 : : };
193 : :
194 : : //! Context that implements naive conversion from/to script only, for roundtrip testing.
195 : : struct ScriptParserContext {
196 : : const MsCtx script_ctx;
197 : :
198 : 867 : constexpr ScriptParserContext(MsCtx ctx) noexcept : script_ctx(ctx) {}
199 : :
200 : : //! For Script roundtrip we never need the key from a key hash.
201 [ + - ]: 48244 : struct Key {
202 : : bool is_hash;
203 : : std::vector<unsigned char> data;
204 : : };
205 : :
206 : 18368 : bool KeyCompare(const Key& a, const Key& b) const {
207 : 18368 : return a.data < b.data;
[ + + + +
- - - - -
- - - + +
+ + + + ]
208 : : }
209 : :
210 : 1267 : const std::vector<unsigned char>& ToPKBytes(const Key& key) const
211 : : {
212 [ - + ]: 1267 : assert(!key.is_hash);
213 : 1267 : return key.data;
214 : : }
215 : :
216 : 550 : std::vector<unsigned char> ToPKHBytes(const Key& key) const
217 : : {
218 [ + - ]: 550 : if (key.is_hash) return key.data;
219 : 0 : const auto h = Hash160(key.data);
220 : 0 : return {h.begin(), h.end()};
221 : : }
222 : :
223 : : template<typename I>
224 [ + - ]: 5137 : std::optional<Key> FromPKBytes(I first, I last) const
225 : : {
226 [ + - ]: 5137 : Key key;
227 : 5137 : key.data.assign(first, last);
228 : 5137 : key.is_hash = false;
229 : 5137 : return key;
230 : 5137 : }
231 : :
232 : : template<typename I>
233 [ + - ]: 4729 : std::optional<Key> FromPKHBytes(I first, I last) const
234 : : {
235 [ + - ]: 4729 : Key key;
236 : 4729 : key.data.assign(first, last);
237 : 4729 : key.is_hash = true;
238 : 4729 : return key;
239 : 4729 : }
240 : :
241 : 4415392 : MsCtx MsContext() const {
242 : 4415392 : return script_ctx;
[ + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - +
- ]
243 : : }
244 : : };
245 : :
246 : : //! Context to produce a satisfaction for a Miniscript node using the pre-computed data.
247 : : struct SatisfierContext : ParserContext {
248 : :
249 : 3918 : constexpr SatisfierContext(MsCtx ctx) noexcept : ParserContext(ctx) {}
250 : :
251 : : // Timelock challenges satisfaction. Make the value (deterministically) vary to explore different
252 : : // paths.
253 [ + + ]: 7750 : bool CheckAfter(uint32_t value) const { return value % 2; }
254 [ + + ]: 10448 : bool CheckOlder(uint32_t value) const { return value % 2; }
255 : :
256 : : // Signature challenges fulfilled with a dummy signature, if it was one of our dummy keys.
257 : 159928 : miniscript::Availability Sign(const CPubKey& key, std::vector<unsigned char>& sig) const {
258 : 159928 : bool sig_available{false};
259 [ + - ]: 159928 : if (auto res = TEST_DATA.GetSig(script_ctx, key)) {
260 : 159928 : std::tie(sig, sig_available) = *res;
261 : : }
262 [ + + ]: 159928 : return sig_available ? miniscript::Availability::YES : miniscript::Availability::NO;
263 : : }
264 : :
265 : : //! Lookup generalization for all the hash satisfactions below
266 : 25804 : miniscript::Availability LookupHash(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage,
267 : : const std::map<std::vector<unsigned char>, std::vector<unsigned char>>& map) const
268 : : {
269 : 25804 : const auto it = map.find(hash);
270 [ + + ]: 25804 : if (it == map.end()) return miniscript::Availability::NO;
271 : 16818 : preimage = it->second;
272 : 16818 : return miniscript::Availability::YES;
273 : : }
274 : 5762 : miniscript::Availability SatSHA256(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
275 [ + - ]: 5762 : return LookupHash(hash, preimage, TEST_DATA.sha256_preimages);
276 : : }
277 : 6208 : miniscript::Availability SatRIPEMD160(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
278 [ + - ]: 6208 : return LookupHash(hash, preimage, TEST_DATA.ripemd160_preimages);
279 : : }
280 : 6888 : miniscript::Availability SatHASH256(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
281 [ + - ]: 6888 : return LookupHash(hash, preimage, TEST_DATA.hash256_preimages);
282 : : }
283 : 6946 : miniscript::Availability SatHASH160(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
284 [ + - ]: 6946 : return LookupHash(hash, preimage, TEST_DATA.hash160_preimages);
285 : : }
286 : : };
287 : :
288 : : //! Context to check a satisfaction against the pre-computed data.
289 : : const struct CheckerContext: BaseSignatureChecker {
290 : : // Signature checker methods. Checks the right dummy signature is used.
291 : 25803 : bool CheckECDSASignature(const std::vector<unsigned char>& sig, const std::vector<unsigned char>& vchPubKey,
292 : : const CScript& scriptCode, SigVersion sigversion) const override
293 : : {
294 [ - + ]: 25803 : const CPubKey key{vchPubKey};
295 : 25803 : const auto it = TEST_DATA.dummy_sigs.find(key);
296 [ + - ]: 25803 : if (it == TEST_DATA.dummy_sigs.end()) return false;
297 : 25803 : return it->second.first == sig;
298 : : }
299 : 9346 : bool CheckSchnorrSignature(std::span<const unsigned char> sig, std::span<const unsigned char> pubkey, SigVersion,
300 : : ScriptExecutionData&, ScriptError*) const override {
301 : 9346 : XOnlyPubKey pk{pubkey};
302 : 9346 : auto it = TEST_DATA.schnorr_sigs.find(pk);
303 [ + - ]: 9346 : if (it == TEST_DATA.schnorr_sigs.end()) return false;
304 : 9346 : return std::ranges::equal(it->second.first, sig);
305 : : }
306 : 1317 : bool CheckLockTime(const CScriptNum& nLockTime) const override { return nLockTime.GetInt64() & 1; }
307 : 2285 : bool CheckSequence(const CScriptNum& nSequence) const override { return nSequence.GetInt64() & 1; }
308 : : } CHECKER_CTX;
309 : :
310 : : //! Context to check for duplicates when instancing a Node.
311 : : const struct KeyComparator {
312 : 262297 : bool KeyCompare(const CPubKey& a, const CPubKey& b) const {
313 : 262297 : return a < b;
[ + + + +
- - - - -
- - - + +
+ + + + ]
314 : : }
315 : : } KEY_COMP;
316 : :
317 : : // A dummy scriptsig to pass to VerifyScript (we always use Segwit v0).
318 : : const CScript DUMMY_SCRIPTSIG;
319 : :
320 : : /** Information about a yet to be constructed Miniscript node. */
321 : : struct NodeInfo {
322 : : //! The type of this node
323 : : Fragment fragment;
324 : : //! The timelock value for older() and after(), the threshold value for multi() and thresh()
325 : : uint32_t k;
326 : : //! Keys for this node, if it has some
327 : : std::vector<CPubKey> keys;
328 : : //! The hash value for this node, if it has one
329 : : std::vector<unsigned char> hash;
330 : : //! The type requirements for the children of this node.
331 : : std::vector<Type> subtypes;
332 : :
333 : 34832 : NodeInfo(Fragment frag): fragment(frag), k(0) {}
334 : 24485 : NodeInfo(Fragment frag, CPubKey key): fragment(frag), k(0), keys({key}) {}
335 : 6755 : NodeInfo(Fragment frag, uint32_t _k): fragment(frag), k(_k) {}
336 : 14380 : NodeInfo(Fragment frag, std::vector<unsigned char> h): fragment(frag), k(0), hash(std::move(h)) {}
337 : 110290 : NodeInfo(std::vector<Type> subt, Fragment frag): fragment(frag), k(0), subtypes(std::move(subt)) {}
338 : 11090 : NodeInfo(std::vector<Type> subt, Fragment frag, uint32_t _k): fragment(frag), k(_k), subtypes(std::move(subt)) {}
339 : 9741 : NodeInfo(Fragment frag, uint32_t _k, std::vector<CPubKey> _keys): fragment(frag), k(_k), keys(std::move(_keys)) {}
340 : : };
341 : :
342 : : /** Pick an index in a collection from a single byte in the fuzzer's output. */
343 : : template<typename T, typename A>
344 : 106767 : T ConsumeIndex(FuzzedDataProvider& provider, A& col) {
345 : 106767 : const uint8_t i = provider.ConsumeIntegral<uint8_t>();
346 : 106767 : return col[i];
347 : : }
348 : :
349 : 98444 : CPubKey ConsumePubKey(FuzzedDataProvider& provider) {
350 : 98444 : return ConsumeIndex<CPubKey>(provider, TEST_DATA.dummy_keys);
351 : : }
352 : :
353 : 1821 : std::vector<unsigned char> ConsumeSha256(FuzzedDataProvider& provider) {
354 : 1821 : return ConsumeIndex<std::vector<unsigned char>>(provider, TEST_DATA.sha256);
355 : : }
356 : :
357 : 2330 : std::vector<unsigned char> ConsumeHash256(FuzzedDataProvider& provider) {
358 : 2330 : return ConsumeIndex<std::vector<unsigned char>>(provider, TEST_DATA.hash256);
359 : : }
360 : :
361 : 1965 : std::vector<unsigned char> ConsumeRipemd160(FuzzedDataProvider& provider) {
362 : 1965 : return ConsumeIndex<std::vector<unsigned char>>(provider, TEST_DATA.ripemd160);
363 : : }
364 : :
365 : 2207 : std::vector<unsigned char> ConsumeHash160(FuzzedDataProvider& provider) {
366 : 2207 : return ConsumeIndex<std::vector<unsigned char>>(provider, TEST_DATA.hash160);
367 : : }
368 : :
369 : 6780 : std::optional<uint32_t> ConsumeTimeLock(FuzzedDataProvider& provider) {
370 : 6780 : const uint32_t k = provider.ConsumeIntegral<uint32_t>();
371 [ + + ]: 6780 : if (k == 0 || k >= 0x80000000) return {};
372 : 6755 : return k;
373 : : }
374 : :
375 : : /**
376 : : * Consume a Miniscript node from the fuzzer's output.
377 : : *
378 : : * This version is intended to have a fixed, stable, encoding for Miniscript nodes:
379 : : * - The first byte sets the type of the fragment. 0, 1 and all non-leaf fragments but thresh() are a
380 : : * single byte.
381 : : * - For the other leaf fragments, the following bytes depend on their type.
382 : : * - For older() and after(), the next 4 bytes define the timelock value.
383 : : * - For pk_k(), pk_h(), and all hashes, the next byte defines the index of the value in the test data.
384 : : * - For multi(), the next 2 bytes define respectively the threshold and the number of keys. Then as many
385 : : * bytes as the number of keys define the index of each key in the test data.
386 : : * - For multi_a(), same as for multi() but the threshold and the keys count are encoded on two bytes.
387 : : * - For thresh(), the next byte defines the threshold value and the following one the number of subs.
388 : : */
389 : 183181 : std::optional<NodeInfo> ConsumeNodeStable(MsCtx script_ctx, FuzzedDataProvider& provider, Type type_needed) {
390 [ + + + + ]: 183181 : bool allow_B = (type_needed == ""_mst) || (type_needed << "B"_mst);
391 [ + + + + ]: 183181 : bool allow_K = (type_needed == ""_mst) || (type_needed << "K"_mst);
392 [ + + + + ]: 183181 : bool allow_V = (type_needed == ""_mst) || (type_needed << "V"_mst);
393 [ + + + + ]: 183181 : bool allow_W = (type_needed == ""_mst) || (type_needed << "W"_mst);
394 : :
395 : 183181 : switch (provider.ConsumeIntegral<uint8_t>()) {
[ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + ]
396 : 25622 : case 0:
397 [ + + ]: 25622 : if (!allow_B) return {};
398 : 25560 : return {{Fragment::JUST_0}};
399 : 9279 : case 1:
400 [ + + ]: 9279 : if (!allow_B) return {};
401 : 9272 : return {{Fragment::JUST_1}};
402 : 6721 : case 2:
403 [ + + ]: 6721 : if (!allow_K) return {};
404 : 6713 : return {{Fragment::PK_K, ConsumePubKey(provider)}};
405 : 4939 : case 3:
406 [ + + ]: 4939 : if (!allow_K) return {};
407 : 4935 : return {{Fragment::PK_H, ConsumePubKey(provider)}};
408 : 3797 : case 4: {
409 [ + + ]: 3797 : if (!allow_B) return {};
410 : 3791 : const auto k = ConsumeTimeLock(provider);
411 [ + + ]: 3791 : if (!k) return {};
412 : 3779 : return {{Fragment::OLDER, *k}};
413 : : }
414 : 2992 : case 5: {
415 [ + + ]: 2992 : if (!allow_B) return {};
416 : 2989 : const auto k = ConsumeTimeLock(provider);
417 [ + + ]: 2989 : if (!k) return {};
418 : 2976 : return {{Fragment::AFTER, *k}};
419 : : }
420 : 1826 : case 6:
421 [ + + ]: 1826 : if (!allow_B) return {};
422 : 1821 : return {{Fragment::SHA256, ConsumeSha256(provider)}};
423 : 2335 : case 7:
424 [ + + ]: 2335 : if (!allow_B) return {};
425 : 2330 : return {{Fragment::HASH256, ConsumeHash256(provider)}};
426 : 1970 : case 8:
427 [ + + ]: 1970 : if (!allow_B) return {};
428 : 1965 : return {{Fragment::RIPEMD160, ConsumeRipemd160(provider)}};
429 : 2210 : case 9:
430 [ + + ]: 2210 : if (!allow_B) return {};
431 : 2207 : return {{Fragment::HASH160, ConsumeHash160(provider)}};
432 : 4579 : case 10: {
433 [ + + + + ]: 4579 : if (!allow_B || IsTapscript(script_ctx)) return {};
434 : 3911 : const auto k = provider.ConsumeIntegral<uint8_t>();
435 : 3911 : const auto n_keys = provider.ConsumeIntegral<uint8_t>();
436 [ + + + + ]: 3911 : if (n_keys > 20 || k == 0 || k > n_keys) return {};
437 : 3903 : std::vector<CPubKey> keys{n_keys};
438 [ + + ]: 21290 : for (auto& key: keys) key = ConsumePubKey(provider);
439 : 3903 : return {{Fragment::MULTI, k, std::move(keys)}};
440 : 3903 : }
441 : 7990 : case 11:
442 [ + + + + ]: 7990 : if (!(allow_B || allow_K || allow_V)) return {};
443 : 7987 : return {{{"B"_mst, type_needed, type_needed}, Fragment::ANDOR}};
444 : 21587 : case 12:
445 [ + + + + ]: 21587 : if (!(allow_B || allow_K || allow_V)) return {};
446 : 21584 : return {{{"V"_mst, type_needed}, Fragment::AND_V}};
447 : 4824 : case 13:
448 [ + + ]: 4824 : if (!allow_B) return {};
449 : 4819 : return {{{"B"_mst, "W"_mst}, Fragment::AND_B}};
450 : 3049 : case 15:
451 [ + + ]: 3049 : if (!allow_B) return {};
452 : 3046 : return {{{"B"_mst, "W"_mst}, Fragment::OR_B}};
453 : 2432 : case 16:
454 [ + + ]: 2432 : if (!allow_V) return {};
455 : 2426 : return {{{"B"_mst, "V"_mst}, Fragment::OR_C}};
456 : 5937 : case 17:
457 [ + + ]: 5937 : if (!allow_B) return {};
458 : 5932 : return {{{"B"_mst, "B"_mst}, Fragment::OR_D}};
459 : 12376 : case 18:
460 [ + + + + ]: 12376 : if (!(allow_B || allow_K || allow_V)) return {};
461 : 12371 : return {{{type_needed, type_needed}, Fragment::OR_I}};
462 : 5406 : case 19: {
463 [ + + ]: 5406 : if (!allow_B) return {};
464 : 5400 : auto k = provider.ConsumeIntegral<uint8_t>();
465 : 5400 : auto n_subs = provider.ConsumeIntegral<uint8_t>();
466 [ + + ]: 5400 : if (k == 0 || k > n_subs) return {};
467 : 5376 : std::vector<Type> subtypes;
468 [ + - ]: 5376 : subtypes.reserve(n_subs);
469 [ + - ]: 5376 : subtypes.emplace_back("B"_mst);
470 [ + - + + ]: 20301 : for (size_t i = 1; i < n_subs; ++i) subtypes.emplace_back("W"_mst);
471 : 5376 : return {{std::move(subtypes), Fragment::THRESH, k}};
472 : 5376 : }
473 : 11156 : case 20:
474 [ + + ]: 11156 : if (!allow_W) return {};
475 : 11148 : return {{{"B"_mst}, Fragment::WRAP_A}};
476 : 1366 : case 21:
477 [ + + ]: 1366 : if (!allow_W) return {};
478 : 1361 : return {{{"B"_mst}, Fragment::WRAP_S}};
479 : 9782 : case 22:
480 [ + + ]: 9782 : if (!allow_B) return {};
481 : 9777 : return {{{"K"_mst}, Fragment::WRAP_C}};
482 : 976 : case 23:
483 [ + + ]: 976 : if (!allow_B) return {};
484 : 973 : return {{{"V"_mst}, Fragment::WRAP_D}};
485 : 22215 : case 24:
486 [ + + ]: 22215 : if (!allow_V) return {};
487 : 22208 : return {{{"B"_mst}, Fragment::WRAP_V}};
488 : 1860 : case 25:
489 [ + + ]: 1860 : if (!allow_B) return {};
490 : 1855 : return {{{"B"_mst}, Fragment::WRAP_J}};
491 : 4809 : case 26:
492 [ + + ]: 4809 : if (!allow_B) return {};
493 : 4803 : return {{{"B"_mst}, Fragment::WRAP_N}};
494 : 1136 : case 27: {
495 [ + + + + ]: 1136 : if (!allow_B || !IsTapscript(script_ctx)) return {};
496 : 899 : const auto k = provider.ConsumeIntegral<uint16_t>();
497 : 899 : const auto n_keys = provider.ConsumeIntegral<uint16_t>();
498 [ + + + + ]: 899 : if (n_keys > 999 || k == 0 || k > n_keys) return {};
499 : 890 : std::vector<CPubKey> keys{n_keys};
500 [ + + ]: 17310 : for (auto& key: keys) key = ConsumePubKey(provider);
501 : 890 : return {{Fragment::MULTI_A, k, std::move(keys)}};
502 : 890 : }
503 : 10 : default:
504 : 10 : break;
505 : : }
506 : 10 : return {};
507 : : }
508 : :
509 : : /* This structure contains a table which for each "target" Type a list of recipes
510 : : * to construct it, automatically inferred from the behavior of ComputeType.
511 : : * Note that the Types here are not the final types of the constructed Nodes, but
512 : : * just the subset that are required. For example, a recipe for the "Bo" type
513 : : * might construct a "Bondu" sha256() NodeInfo, but cannot construct a "Bz" older().
514 : : * Each recipe is a Fragment together with a list of required types for its subnodes.
515 : : */
516 : : struct SmartInfo
517 : : {
518 : : using recipe = std::pair<Fragment, std::vector<Type>>;
519 : : std::map<Type, std::vector<recipe>> wsh_table, tap_table;
520 : :
521 : 1 : void Init()
522 : : {
523 : 1 : Init(wsh_table, MsCtx::P2WSH);
524 : 1 : Init(tap_table, MsCtx::TAPSCRIPT);
525 : 1 : }
526 : :
527 : 2 : void Init(std::map<Type, std::vector<recipe>>& table, MsCtx script_ctx)
528 : : {
529 : : /* Construct a set of interesting type requirements to reason with (sections of BKVWzondu). */
530 : 2 : std::vector<Type> types;
531 [ + + ]: 10 : for (int base = 0; base < 4; ++base) { /* select from B,K,V,W */
532 [ + + + + : 8 : Type type_base = base == 0 ? "B"_mst : base == 1 ? "K"_mst : base == 2 ? "V"_mst : "W"_mst;
+ + ]
533 [ + + ]: 32 : for (int zo = 0; zo < 3; ++zo) { /* select from z,o,(none) */
534 [ + + + + ]: 24 : Type type_zo = zo == 0 ? "z"_mst : zo == 1 ? "o"_mst : ""_mst;
535 [ + + ]: 72 : for (int n = 0; n < 2; ++n) { /* select from (none),n */
536 [ + + ]: 48 : if (zo == 0 && n == 1) continue; /* z conflicts with n */
537 [ + + ]: 40 : if (base == 3 && n == 1) continue; /* W conflicts with n */
538 [ + + ]: 36 : Type type_n = n == 0 ? ""_mst : "n"_mst;
539 [ + + ]: 108 : for (int d = 0; d < 2; ++d) { /* select from (none),d */
540 [ + + ]: 72 : if (base == 2 && d == 1) continue; /* V conflicts with d */
541 [ + + ]: 62 : Type type_d = d == 0 ? ""_mst : "d"_mst;
542 [ + + ]: 186 : for (int u = 0; u < 2; ++u) { /* select from (none),u */
543 [ + + ]: 124 : if (base == 2 && u == 1) continue; /* V conflicts with u */
544 [ + + ]: 114 : Type type_u = u == 0 ? ""_mst : "u"_mst;
545 [ + - ]: 114 : Type type = type_base | type_zo | type_n | type_d | type_u;
546 [ + - ]: 114 : types.push_back(type);
547 : : }
548 : : }
549 : : }
550 : : }
551 : : }
552 : :
553 : : /* We define a recipe a to be a super-recipe of recipe b if they use the same
554 : : * fragment, the same number of subexpressions, and each of a's subexpression
555 : : * types is a supertype of the corresponding subexpression type of b.
556 : : * Within the set of recipes for the construction of a given type requirement,
557 : : * no recipe should be a super-recipe of another (as the super-recipe is
558 : : * applicable in every place the sub-recipe is, the sub-recipe is redundant). */
559 : 260828 : auto is_super_of = [](const recipe& a, const recipe& b) {
560 [ + + ]: 260826 : if (a.first != b.first) return false;
561 [ - + - + : 26260 : if (a.second.size() != b.second.size()) return false;
+ + ]
562 [ + + ]: 91420 : for (size_t i = 0; i < a.second.size(); ++i) {
563 [ + + ]: 66654 : if (!(b.second[i] << a.second[i])) return false;
564 : : }
565 : : return true;
566 : : };
567 : :
568 : : /* Sort the type requirements. Subtypes will always sort later (e.g. Bondu will
569 : : * sort after Bo or Bu). As we'll be constructing recipes using these types, in
570 : : * order, in what follows, we'll construct super-recipes before sub-recipes.
571 : : * That means we never need to go back and delete a sub-recipe because a
572 : : * super-recipe got added. */
573 : 2 : std::sort(types.begin(), types.end());
574 : :
575 : : // Iterate over all possible fragments.
576 [ + + ]: 56 : for (int fragidx = 0; fragidx <= int(Fragment::MULTI_A); ++fragidx) {
577 : 54 : int sub_count = 0; //!< The minimum number of child nodes this recipe has.
578 : 54 : int sub_range = 1; //!< The maximum number of child nodes for this recipe is sub_count+sub_range-1.
579 : 54 : size_t data_size = 0;
580 : 54 : size_t n_keys = 0;
581 : 54 : uint32_t k = 0;
582 : 54 : Fragment frag{fragidx};
583 : :
584 : : // Only produce recipes valid in the given context.
585 [ + + ]: 81 : if ((!miniscript::IsTapscript(script_ctx) && frag == Fragment::MULTI_A)
586 [ + + + + : 80 : || (miniscript::IsTapscript(script_ctx) && frag == Fragment::MULTI)) {
+ + ]
587 : 2 : continue;
588 : : }
589 : :
590 : : // Based on the fragment, determine #subs/data/k/keys to pass to ComputeType. */
591 [ + + + + : 52 : switch (frag) {
+ + + + +
+ ]
592 : 4 : case Fragment::PK_K:
593 : 4 : case Fragment::PK_H:
594 : 4 : n_keys = 1;
595 : 4 : break;
596 : 2 : case Fragment::MULTI:
597 : 2 : case Fragment::MULTI_A:
598 : 2 : n_keys = 1;
599 : 2 : k = 1;
600 : 2 : break;
601 : 4 : case Fragment::OLDER:
602 : 4 : case Fragment::AFTER:
603 : 4 : k = 1;
604 : 4 : break;
605 : 4 : case Fragment::SHA256:
606 : 4 : case Fragment::HASH256:
607 : 4 : data_size = 32;
608 : 4 : break;
609 : 4 : case Fragment::RIPEMD160:
610 : 4 : case Fragment::HASH160:
611 : 4 : data_size = 20;
612 : 4 : break;
613 : : case Fragment::JUST_0:
614 : : case Fragment::JUST_1:
615 : : break;
616 : 14 : case Fragment::WRAP_A:
617 : 14 : case Fragment::WRAP_S:
618 : 14 : case Fragment::WRAP_C:
619 : 14 : case Fragment::WRAP_D:
620 : 14 : case Fragment::WRAP_V:
621 : 14 : case Fragment::WRAP_J:
622 : 14 : case Fragment::WRAP_N:
623 : 14 : sub_count = 1;
624 : 14 : break;
625 : 12 : case Fragment::AND_V:
626 : 12 : case Fragment::AND_B:
627 : 12 : case Fragment::OR_B:
628 : 12 : case Fragment::OR_C:
629 : 12 : case Fragment::OR_D:
630 : 12 : case Fragment::OR_I:
631 : 12 : sub_count = 2;
632 : 12 : break;
633 : 2 : case Fragment::ANDOR:
634 : 2 : sub_count = 3;
635 : 2 : break;
636 : 2 : case Fragment::THRESH:
637 : : // Thresh logic is executed for 1 and 2 arguments. Larger numbers use ad-hoc code to extend.
638 : 2 : sub_count = 1;
639 : 2 : sub_range = 2;
640 : 2 : k = 1;
641 : 2 : break;
642 : : }
643 : :
644 : : // Iterate over the number of subnodes (sub_count...sub_count+sub_range-1).
645 : 52 : std::vector<Type> subt;
646 [ + + ]: 106 : for (int subs = sub_count; subs < sub_count + sub_range; ++subs) {
647 : : // Iterate over the possible subnode types (at most 3).
648 [ + + ]: 1878 : for (Type x : types) {
649 [ + + ]: 53830 : for (Type y : types) {
650 [ + + ]: 2886502 : for (Type z : types) {
651 : : // Compute the resulting type of a node with the selected fragment / subnode types.
652 [ + + ]: 2836790 : subt.clear();
653 [ + + + - ]: 2836790 : if (subs > 0) subt.push_back(x);
654 [ + + + - ]: 2836768 : if (subs > 1) subt.push_back(y);
655 [ + + + - ]: 2796208 : if (subs > 2) subt.push_back(z);
656 [ + - ]: 2836790 : Type res = miniscript::internal::ComputeType(frag, x, y, z, subt, k, data_size, subs, n_keys, script_ctx);
657 : : // Continue if the result is not a valid node.
658 [ + + ]: 2836790 : if ((res << "K"_mst) + (res << "V"_mst) + (res << "B"_mst) + (res << "W"_mst) != 1) continue;
659 : :
660 [ + - ]: 11456 : recipe entry{frag, subt};
661 [ + + ]: 260826 : auto super_of_entry = [&](const recipe& rec) { return is_super_of(rec, entry); };
662 : : // Iterate over all supertypes of res (because if e.g. our selected fragment/subnodes result
663 : : // in a Bondu, they can form a recipe that is also applicable for constructing a B, Bou, Bdu, ...).
664 [ + + ]: 664448 : for (Type s : types) {
665 [ + + ]: 652992 : if ((res & "BKVWzondu"_mst) << s) {
666 [ + - ]: 25510 : auto& recipes = table[s];
667 : : // If we don't already have a super-recipe to the new one, add it.
668 [ + + ]: 25510 : if (!std::any_of(recipes.begin(), recipes.end(), super_of_entry)) {
669 [ + - ]: 744 : recipes.push_back(entry);
670 : : }
671 : : }
672 : : }
673 : :
674 [ + + ]: 11456 : if (subs <= 2) break;
675 : 11456 : }
676 [ + + ]: 52918 : if (subs <= 1) break;
677 : : }
678 [ + + ]: 1846 : if (subs <= 0) break;
679 : : }
680 : : }
681 : : }
682 : :
683 : : /* Find which types are useful. The fuzzer logic only cares about constructing
684 : : * B,V,K,W nodes, so any type that isn't needed in any recipe (directly or
685 : : * indirectly) for the construction of those is uninteresting. */
686 [ + - ]: 4 : std::set<Type> useful_types{"B"_mst, "V"_mst, "K"_mst, "W"_mst};
687 : : // Find the transitive closure by adding types until the set of types does not change.
688 : 4 : while (true) {
689 : 4 : size_t set_size = useful_types.size();
690 [ + + ]: 200 : for (const auto& [type, recipes] : table) {
691 [ + + ]: 196 : if (useful_types.contains(type)) {
692 [ + + ]: 1129 : for (const auto& [_, subtypes] : recipes) {
693 [ + - + + ]: 2379 : for (auto subtype : subtypes) useful_types.insert(subtype);
694 : : }
695 : : }
696 : : }
697 [ + + ]: 4 : if (useful_types.size() == set_size) break;
698 : : }
699 : : // Remove all rules that construct uninteresting types.
700 : 100 : std::erase_if(table, [&](const auto& entry) { return !useful_types.contains(entry.first); });
701 : :
702 : : /* Find which types are constructible. A type is constructible if there is a leaf
703 : : * node recipe for constructing it, or a recipe whose subnodes are all constructible.
704 : : * Types can be non-constructible because they have no recipes to begin with,
705 : : * because they can only be constructed using recipes that involve otherwise
706 : : * non-constructible types, or because they require infinite recursion. */
707 : 4 : std::set<Type> constructible_types{};
708 : 812 : auto known_constructible = [&](Type type) { return constructible_types.contains(type); };
709 : : // Find the transitive closure by adding types until the set of types does not change.
710 : 4 : while (true) {
711 : 4 : size_t set_size = constructible_types.size();
712 : : // Iterate over all types we have recipes for.
713 [ + + ]: 132 : for (const auto& [type, recipes] : table) {
714 [ + + ]: 128 : if (!known_constructible(type)) {
715 : : // For not (yet known to be) constructible types, iterate over their recipes.
716 [ + + ]: 80 : for (const auto& [_, subt] : recipes) {
717 : : // If any recipe involves only (already known to be) constructible types,
718 : : // add the recipe's type to the set.
719 [ + + ]: 72 : if (std::all_of(subt.begin(), subt.end(), known_constructible)) {
720 [ + - ]: 60 : constructible_types.insert(type);
721 : : break;
722 : : }
723 : : }
724 : : }
725 : : }
726 [ + + ]: 4 : if (constructible_types.size() == set_size) break;
727 : : }
728 [ + + ]: 66 : for (auto type_it = table.begin(); type_it != table.end();) {
729 : : // Remove all recipes which involve non-constructible types.
730 : 64 : std::erase_if(type_it->second, [&](const recipe& rec) {
731 : 594 : return !std::all_of(rec.second.begin(), rec.second.end(), known_constructible);
732 : : });
733 : : // Delete types entirely which have no recipes left.
734 [ + + ]: 64 : if (type_it->second.empty()) {
735 : 4 : type_it = table.erase(type_it);
736 : : } else {
737 : 60 : ++type_it;
738 : : }
739 : : }
740 : :
741 [ + + ]: 62 : for (auto& [type, recipes] : table) {
742 : : // Sort recipes for determinism, and place those using fewer subnodes first.
743 : : // This avoids runaway expansion (when reaching the end of the fuzz input,
744 : : // all zeroes are read, resulting in the first available recipe being picked).
745 : 60 : std::sort(recipes.begin(), recipes.end(),
746 : 1271 : [](const recipe& a, const recipe& b) {
747 [ - + - + : 1271 : if (a.second.size() < b.second.size()) return true;
+ + ]
748 [ + + ]: 988 : if (a.second.size() > b.second.size()) return false;
749 : 536 : return a < b;
750 : : }
751 : : );
752 : : }
753 : 2 : }
754 : : } SMARTINFO;
755 : :
756 : : /**
757 : : * Consume a Miniscript node from the fuzzer's output.
758 : : *
759 : : * This is similar to ConsumeNodeStable, but uses a precomputed table with permitted
760 : : * fragments/subnode type for each required type. It is intended to more quickly explore
761 : : * interesting miniscripts, at the cost of higher implementation complexity (which could
762 : : * cause it miss things if incorrect), and with less regard for stability of the seeds
763 : : * (as improvements to the tables or changes to the typing rules could invalidate
764 : : * everything).
765 : : */
766 : 156584 : std::optional<NodeInfo> ConsumeNodeSmart(MsCtx script_ctx, FuzzedDataProvider& provider, Type type_needed) {
767 : : /** Table entry for the requested type. */
768 [ + + ]: 156584 : const auto& table{IsTapscript(script_ctx) ? SMARTINFO.tap_table : SMARTINFO.wsh_table};
769 : 156584 : auto recipes_it = table.find(type_needed);
770 [ - + ]: 156584 : assert(recipes_it != table.end());
771 : : /** Pick one recipe from the available ones for that type. */
772 : 156584 : const auto& [frag, subt] = PickValue(provider, recipes_it->second);
[ + + + +
+ + + + +
+ - ]
773 : :
774 : : // Based on the fragment the recipe uses, fill in other data (k, keys, data).
775 : 156584 : switch (frag) {
[ + + + +
+ + + + +
+ - ]
776 : 12837 : case Fragment::PK_K:
777 : 12837 : case Fragment::PK_H:
778 : 12837 : return {{frag, ConsumePubKey(provider)}};
779 : 3927 : case Fragment::MULTI: {
780 : 3927 : const auto n_keys = provider.ConsumeIntegralInRange<uint8_t>(1, 20);
781 : 3927 : const auto k = provider.ConsumeIntegralInRange<uint8_t>(1, n_keys);
782 : 3927 : std::vector<CPubKey> keys{n_keys};
783 [ + + ]: 22837 : for (auto& key: keys) key = ConsumePubKey(provider);
784 : 3927 : return {{frag, k, std::move(keys)}};
785 : 3927 : }
786 : 1021 : case Fragment::MULTI_A: {
787 : 1021 : const auto n_keys = provider.ConsumeIntegralInRange<uint16_t>(1, 999);
788 : 1021 : const auto k = provider.ConsumeIntegralInRange<uint16_t>(1, n_keys);
789 : 1021 : std::vector<CPubKey> keys{n_keys};
790 [ + + ]: 22263 : for (auto& key: keys) key = ConsumePubKey(provider);
791 : 1021 : return {{frag, k, std::move(keys)}};
792 : 1021 : }
793 : 3328 : case Fragment::OLDER:
794 : 3328 : case Fragment::AFTER:
795 : 3328 : return {{frag, provider.ConsumeIntegralInRange<uint32_t>(1, 0x7FFFFFF)}};
796 : 1425 : case Fragment::SHA256:
797 : 1425 : return {{frag, PickValue(provider, TEST_DATA.sha256)}};
798 : 1527 : case Fragment::HASH256:
799 : 1527 : return {{frag, PickValue(provider, TEST_DATA.hash256)}};
800 : 1499 : case Fragment::RIPEMD160:
801 : 1499 : return {{frag, PickValue(provider, TEST_DATA.ripemd160)}};
802 : 1606 : case Fragment::HASH160:
803 : 1606 : return {{frag, PickValue(provider, TEST_DATA.hash160)}};
804 : 123700 : case Fragment::JUST_0:
805 : 123700 : case Fragment::JUST_1:
806 : 123700 : case Fragment::WRAP_A:
807 : 123700 : case Fragment::WRAP_S:
808 : 123700 : case Fragment::WRAP_C:
809 : 123700 : case Fragment::WRAP_D:
810 : 123700 : case Fragment::WRAP_V:
811 : 123700 : case Fragment::WRAP_J:
812 : 123700 : case Fragment::WRAP_N:
813 : 123700 : case Fragment::AND_V:
814 : 123700 : case Fragment::AND_B:
815 : 123700 : case Fragment::OR_B:
816 : 123700 : case Fragment::OR_C:
817 : 123700 : case Fragment::OR_D:
818 : 123700 : case Fragment::OR_I:
819 : 123700 : case Fragment::ANDOR:
820 : 123700 : return {{subt, frag}};
821 : 5714 : case Fragment::THRESH: {
822 : 5714 : uint32_t children;
823 [ - + + + ]: 5714 : if (subt.size() < 2) {
824 : 4793 : children = subt.size();
825 : : } else {
826 : : // If we hit a thresh with 2 subnodes, artificially extend it to any number
827 : : // (2 or larger) by replicating the type of the last subnode.
828 : 921 : children = provider.ConsumeIntegralInRange<uint32_t>(2, MAX_OPS_PER_SCRIPT / 2);
829 : : }
830 : 5714 : auto k = provider.ConsumeIntegralInRange<uint32_t>(1, children);
831 : 5714 : std::vector<Type> subs = subt;
832 [ + - - + : 26492 : while (subs.size() < children) subs.push_back(subs.back());
+ + ]
833 : 5714 : return {{std::move(subs), frag, k}};
834 : 5714 : }
835 : : }
836 : :
837 : 0 : assert(false);
838 : : }
839 : :
840 : : /**
841 : : * Generate a Miniscript node based on the fuzzer's input.
842 : : *
843 : : * - ConsumeNode is a function object taking a Type, and returning an std::optional<NodeInfo>.
844 : : * - root_type is the required type properties of the constructed Node.
845 : : * - strict_valid sets whether ConsumeNode is expected to guarantee a NodeInfo that results in
846 : : * a Node whose Type() matches the type fed to ConsumeNode.
847 : : */
848 : : template <typename F>
849 : 5761 : std::optional<Node> GenNode(MsCtx script_ctx, F ConsumeNode, Type root_type, bool strict_valid = false)
850 : : {
851 : : /** A stack of miniscript Nodes being built up. */
852 : 5761 : std::vector<Node> stack;
853 : : /** The queue of instructions. */
854 [ + - + + : 17283 : std::vector<std::pair<Type, std::optional<NodeInfo>>> todo{{root_type, {}}};
- - ]
855 : : /** Predict the number of (static) script ops. */
856 : 5761 : uint32_t ops{0};
857 : : /** Predict the total script size (every unexplored subnode is counted as one, as every leaf is
858 : : * at least one script byte). */
859 : 5761 : uint32_t scriptsize{1};
860 : :
861 [ + + ]: 664546 : while (!todo.empty()) {
862 : : // The expected type we have to construct.
863 : 660283 : auto type_needed = todo.back().first;
864 [ + + ]: 660283 : if (!todo.back().second) {
865 : : // Fragment/children have not been decided yet. Decide them.
866 [ + + ]: 339765 : auto node_info = ConsumeNode(type_needed);
867 [ + + ]: 339765 : if (!node_info) return {};
868 : : // Update predicted resource limits. Since every leaf Miniscript node is at least one
869 : : // byte long, we move one byte from each child to their parent. A similar technique is
870 : : // used in the miniscript::internal::Parse function to prevent runaway string parsing.
871 [ - + - + : 338601 : scriptsize += miniscript::internal::ComputeScriptLen(node_info->fragment, ""_mst, node_info->subtypes.size(), node_info->k, node_info->subtypes.size(),
+ - ]
872 [ - + ]: 338601 : node_info->keys.size(), script_ctx) - 1;
873 [ + + ]: 338601 : if (scriptsize > MAX_STANDARD_P2WSH_SCRIPT_SIZE) return {};
874 : 338568 : switch (node_info->fragment) {
[ + + + +
+ + + + +
+ + + + +
+ + + + ]
875 : : case Fragment::JUST_0:
876 : : case Fragment::JUST_1:
877 : : break;
878 : : case Fragment::PK_K:
879 : : break;
880 : 8854 : case Fragment::PK_H:
881 : 8854 : ops += 3;
882 : 8854 : break;
883 : 10083 : case Fragment::OLDER:
884 : : case Fragment::AFTER:
885 : 10083 : ops += 1;
886 : 10083 : break;
887 : 14380 : case Fragment::RIPEMD160:
888 : : case Fragment::SHA256:
889 : : case Fragment::HASH160:
890 : : case Fragment::HASH256:
891 : 14380 : ops += 4;
892 : 14380 : break;
893 : 14499 : case Fragment::ANDOR:
894 : 14499 : ops += 3;
895 : 14499 : break;
896 : : case Fragment::AND_V:
897 : : break;
898 : 15184 : case Fragment::AND_B:
899 : : case Fragment::OR_B:
900 : 15184 : ops += 1;
901 : 15184 : break;
902 : 4595 : case Fragment::OR_C:
903 : 4595 : ops += 2;
904 : 4595 : break;
905 : 9257 : case Fragment::OR_D:
906 : 9257 : ops += 3;
907 : 9257 : break;
908 : 20242 : case Fragment::OR_I:
909 : 20242 : ops += 3;
910 : 20242 : break;
911 [ - + ]: 11090 : case Fragment::THRESH:
912 [ - + ]: 11090 : ops += node_info->subtypes.size();
913 : 11090 : break;
914 : 7830 : case Fragment::MULTI:
915 : 7830 : ops += 1;
916 : 7830 : break;
917 [ - + ]: 1887 : case Fragment::MULTI_A:
918 [ - + ]: 1887 : ops += node_info->keys.size() + 1;
919 : 1887 : break;
920 : 26297 : case Fragment::WRAP_A:
921 : 26297 : ops += 2;
922 : 26297 : break;
923 : 3712 : case Fragment::WRAP_S:
924 : 3712 : ops += 1;
925 : 3712 : break;
926 : 16895 : case Fragment::WRAP_C:
927 : 16895 : ops += 1;
928 : 16895 : break;
929 : 1623 : case Fragment::WRAP_D:
930 : 1623 : ops += 3;
931 : 1623 : break;
932 : : case Fragment::WRAP_V:
933 : : // We don't account for OP_VERIFY here; that will be corrected for when the actual
934 : : // node is constructed below.
935 : : break;
936 : 3016 : case Fragment::WRAP_J:
937 : 3016 : ops += 4;
938 : 3016 : break;
939 : 8038 : case Fragment::WRAP_N:
940 : 8038 : ops += 1;
941 : 8038 : break;
942 : : }
943 [ + + ]: 338568 : if (ops > MAX_OPS_PER_SCRIPT) return {};
944 [ + - ]: 338468 : auto subtypes = node_info->subtypes;
945 [ - + ]: 338468 : todo.back().second = std::move(node_info);
946 [ - + + - ]: 338468 : todo.reserve(todo.size() + subtypes.size());
947 : : // As elements on the todo stack are processed back to front, construct
948 : : // them in reverse order (so that the first subnode is generated first).
949 [ - + + + ]: 695708 : for (size_t i = 0; i < subtypes.size(); ++i) {
950 [ + - ]: 357240 : todo.emplace_back(*(subtypes.rbegin() + i), std::nullopt);
951 : : }
952 : 339765 : } else {
953 : : // The back of todo has fragment and number of children decided, and
954 : : // those children have been constructed at the back of stack. Pop
955 : : // that entry off todo, and use it to construct a new Node on
956 : : // stack.
957 [ - + ]: 320518 : NodeInfo& info = *todo.back().second;
958 : : // Gather children from the back of stack.
959 : 320518 : std::vector<Node> sub;
960 [ - + + - ]: 320518 : sub.reserve(info.subtypes.size());
961 [ - + + + ]: 631425 : for (size_t i = 0; i < info.subtypes.size(); ++i) {
962 [ + - ]: 310907 : sub.push_back(std::move(*(stack.end() - info.subtypes.size() + i)));
963 : : }
964 : 320518 : stack.erase(stack.end() - info.subtypes.size(), stack.end());
965 : : // Construct new Node.
966 [ + - ]: 641036 : Node node{[&] {
967 [ + + + + ]: 320518 : if (info.keys.empty()) {
968 [ + - + - ]: 572658 : return Node{miniscript::internal::NoDupCheck{}, script_ctx, info.fragment, std::move(sub), std::move(info.hash), info.k};
969 : : }
970 [ - + - + ]: 34189 : assert(sub.empty());
971 [ - + - + ]: 34189 : assert(info.hash.empty());
972 [ + - + - ]: 68378 : return Node{miniscript::internal::NoDupCheck{}, script_ctx, info.fragment, std::move(info.keys), info.k};
973 : : }()};
974 : : // Verify acceptability.
975 [ + + ]: 320518 : if ((node.GetType() & "KVWB"_mst) == ""_mst) {
976 [ - + ]: 178 : assert(!strict_valid);
977 : 178 : return {};
978 : : }
979 [ + + ]: 320340 : if (!(type_needed == ""_mst)) {
980 [ - + ]: 301327 : assert(node.GetType() << type_needed);
981 : : }
982 [ + + ]: 320340 : if (!node.IsValid()) return {};
983 : : // Update resource predictions.
984 [ + + + + ]: 320337 : if (node.Fragment() == Fragment::WRAP_V && node.Subs()[0].GetType() << "x"_mst) {
985 : 18381 : ops += 1;
986 : 18381 : scriptsize += 1;
987 : : }
988 [ + + + + ]: 320337 : if (!miniscript::IsTapscript(script_ctx) && ops > MAX_OPS_PER_SCRIPT) return {};
989 [ + + + + ]: 517692 : if (scriptsize > miniscript::internal::MaxScriptSize(script_ctx)) {
990 : 2 : return {};
991 : : }
992 : : // Move it to the stack.
993 : 320317 : stack.push_back(std::move(node));
994 : 320317 : todo.pop_back();
995 : 320518 : }
996 : : }
997 [ - + ]: 4263 : assert(stack.size() == 1);
998 [ - + ]: 4263 : assert(stack[0].GetStaticOps() == ops);
999 [ - + ]: 4263 : assert(stack[0].ScriptSize() == scriptsize);
1000 [ + - ]: 4263 : stack[0].DuplicateKeyCheck(KEY_COMP);
1001 : 4263 : return std::move(stack[0]);
1002 [ - + ]: 11522 : }
1003 : :
1004 : : //! The spk for this script under the given context. If it's a Taproot output also record the spend data.
1005 : 3918 : CScript ScriptPubKey(MsCtx ctx, const CScript& script, TaprootBuilder& builder)
1006 : : {
1007 [ + + + - : 3918 : if (!miniscript::IsTapscript(ctx)) return CScript() << OP_0 << WitnessV0ScriptHash(script);
+ - ]
1008 : :
1009 : : // For Taproot outputs we always use a tree with a single script and a dummy internal key.
1010 [ + + ]: 3342 : builder.Add(0, script, TAPROOT_LEAF_TAPSCRIPT);
1011 : 1671 : builder.Finalize(XOnlyPubKey::NUMS_H);
1012 [ + - ]: 3342 : return GetScriptForDestination(builder.GetOutput());
1013 : : }
1014 : :
1015 : : //! Fill the witness with the data additional to the script satisfaction.
1016 : 3669 : void SatisfactionToWitness(MsCtx ctx, CScriptWitness& witness, const CScript& script, TaprootBuilder& builder) {
1017 : : // For P2WSH, it's only the witness script.
1018 [ + + ]: 7338 : witness.stack.emplace_back(script.begin(), script.end());
1019 [ + + ]: 3669 : if (!miniscript::IsTapscript(ctx)) return;
1020 : : // For Tapscript we also need the control block.
1021 [ + - ]: 3028 : witness.stack.push_back(*builder.GetSpendData().scripts.begin()->second.begin());
1022 : : }
1023 : :
1024 : : /** Perform various applicable tests on a miniscript Node. */
1025 : 5761 : void TestNode(const MsCtx script_ctx, const std::optional<Node>& node, FuzzedDataProvider& provider)
1026 : : {
1027 [ + + ]: 5761 : if (!node) return;
1028 : :
1029 : : // Check that it roundtrips to text representation
1030 : 4263 : const ParserContext parser_ctx{script_ctx};
1031 : 4263 : std::optional<std::string> str{node->ToString(parser_ctx)};
1032 [ - + ]: 4263 : assert(str);
1033 [ - + ]: 4263 : auto parsed = miniscript::FromString(*str, parser_ctx);
1034 [ - + ]: 4263 : assert(parsed);
1035 [ + - - + ]: 4263 : assert(*parsed == *node);
1036 : :
1037 : : // Check consistency between script size estimation and real size.
1038 [ + - ]: 4263 : auto script = node->ToScript(parser_ctx);
1039 [ + + - + ]: 8148 : assert(node->ScriptSize() == script.size());
1040 : :
1041 : : // Check consistency of "x" property with the script (type K is excluded, because it can end
1042 : : // with a push of a key, which could match these opcodes).
1043 [ + + ]: 4263 : if (!(node->GetType() << "K"_mst)) {
1044 [ + + ]: 4158 : bool ends_in_verify = !(node->GetType() << "x"_mst);
1045 : 19302 : assert(ends_in_verify == (script.back() == OP_CHECKSIG || script.back() == OP_CHECKMULTISIG || script.back() == OP_EQUAL || script.back() == OP_NUMEQUAL));
[ + + + +
+ + + + +
+ - + ]
1046 : : }
1047 : :
1048 : : // The rest of the checks only apply when testing a valid top-level script.
1049 [ + + ]: 4263 : if (!node->IsValidTopLevel()) return;
1050 : :
1051 : : // Check roundtrip to script
1052 [ + - ]: 3918 : auto decoded = miniscript::FromScript(script, parser_ctx);
1053 [ - + ]: 3918 : assert(decoded);
1054 : : // Note we can't use *decoded == *node because the miniscript representation may differ, so we check that:
1055 : : // - The script corresponding to that decoded form matches exactly
1056 : : // - The type matches exactly
1057 [ + - - + ]: 3918 : assert(decoded->ToScript(parser_ctx) == script);
1058 [ - + ]: 3918 : assert(decoded->GetType() == node->GetType());
1059 : :
1060 : : // Optionally pad the script or the witness in order to increase the sensitivity of the tests of
1061 : : // the resources limits logic.
1062 : 3918 : CScriptWitness witness_mal, witness_nonmal;
1063 [ + + ]: 3918 : if (provider.ConsumeBool()) {
1064 : : // Under P2WSH, optionally pad the script with OP_NOPs to max op the ops limit of the constructed script.
1065 : : // This makes the script obviously not actually miniscript-compatible anymore, but the
1066 : : // signatures constructed in this test don't commit to the script anyway, so the same
1067 : : // miniscript satisfier will work. This increases the sensitivity of the test to the ops
1068 : : // counting logic being too low, especially for simple scripts.
1069 : : // Do this optionally because we're not solely interested in cases where the number of ops is
1070 : : // maximal.
1071 : : // Do not pad more than what would cause MAX_STANDARD_P2WSH_SCRIPT_SIZE to be reached, however,
1072 : : // as that also invalidates scripts.
1073 : 647 : const auto node_ops{node->GetOps()};
1074 [ + + + + ]: 991 : if (!IsTapscript(script_ctx) && node_ops && *node_ops < MAX_OPS_PER_SCRIPT
1075 [ + + + + ]: 935 : && node->ScriptSize() < MAX_STANDARD_P2WSH_SCRIPT_SIZE) {
1076 [ + + ]: 286 : int add = std::min<int>(
1077 [ + + ]: 286 : MAX_OPS_PER_SCRIPT - *node_ops,
1078 [ + + ]: 286 : MAX_STANDARD_P2WSH_SCRIPT_SIZE - node->ScriptSize());
1079 [ + + ]: 28306 : for (int i = 0; i < add; ++i) script.push_back(OP_NOP);
1080 : : }
1081 : :
1082 : : // Under Tapscript, optionally pad the stack up to the limit minus the calculated maximum execution stack
1083 : : // size to assert a Miniscript would never add more elements to the stack during execution than anticipated.
1084 : 647 : const auto node_exec_ss{node->GetExecStackSize()};
1085 [ + + + + : 647 : if (miniscript::IsTapscript(script_ctx) && node_exec_ss && *node_exec_ss < MAX_STACK_SIZE) {
+ - ]
1086 [ + - ]: 281 : unsigned add{(unsigned)MAX_STACK_SIZE - *node_exec_ss};
1087 [ + - ]: 281 : witness_mal.stack.resize(add);
1088 [ + - ]: 281 : witness_nonmal.stack.resize(add);
1089 : 281 : script.reserve(add);
1090 [ + + ]: 270174 : for (unsigned i = 0; i < add; ++i) script.push_back(OP_NIP);
1091 : : }
1092 : : }
1093 : :
1094 : 3918 : const SatisfierContext satisfier_ctx{script_ctx};
1095 : :
1096 : : // Get the ScriptPubKey for this script, filling spend data if it's Taproot.
1097 [ + - ]: 3918 : TaprootBuilder builder;
1098 [ + - ]: 3918 : const CScript script_pubkey{ScriptPubKey(script_ctx, script, builder)};
1099 : :
1100 : : // Run malleable satisfaction algorithm.
1101 : 3918 : std::vector<std::vector<unsigned char>> stack_mal;
1102 [ + - ]: 3918 : const bool mal_success = node->Satisfy(satisfier_ctx, stack_mal, false) == miniscript::Availability::YES;
1103 : :
1104 : : // Run non-malleable satisfaction algorithm.
1105 : 3918 : std::vector<std::vector<unsigned char>> stack_nonmal;
1106 [ + - ]: 3918 : const bool nonmal_success = node->Satisfy(satisfier_ctx, stack_nonmal, true) == miniscript::Availability::YES;
1107 : :
1108 [ + + ]: 3918 : if (nonmal_success) {
1109 : : // Non-malleable satisfactions are bounded by the satisfaction size plus:
1110 : : // - For P2WSH spends, the witness script
1111 : : // - For Tapscript spends, both the witness script and the control block
1112 : 1114 : const size_t max_stack_size{*node->GetStackSize() + 1 + miniscript::IsTapscript(script_ctx)};
1113 [ - + - + ]: 1114 : assert(stack_nonmal.size() <= max_stack_size);
1114 : : // If a non-malleable satisfaction exists, the malleable one must also exist, and be identical to it.
1115 [ - + ]: 1114 : assert(mal_success);
1116 [ - + ]: 1114 : assert(stack_nonmal == stack_mal);
1117 : : // Compute witness size (excluding script push, control block, and witness count encoding).
1118 [ - + - + ]: 1114 : const uint64_t wit_size{GetSerializeSize(stack_nonmal) - GetSizeOfCompactSize(stack_nonmal.size())};
1119 [ - + - + ]: 2228 : assert(wit_size <= *node->GetWitnessSize());
1120 : :
1121 : : // Test non-malleable satisfaction.
1122 [ + - ]: 1114 : witness_nonmal.stack.insert(witness_nonmal.stack.end(), std::make_move_iterator(stack_nonmal.begin()), std::make_move_iterator(stack_nonmal.end()));
1123 [ + - ]: 1114 : SatisfactionToWitness(script_ctx, witness_nonmal, script, builder);
1124 : 1114 : ScriptError serror;
1125 [ + - ]: 1114 : bool res = VerifyScript(DUMMY_SCRIPTSIG, script_pubkey, &witness_nonmal, STANDARD_SCRIPT_VERIFY_FLAGS, CHECKER_CTX, &serror);
1126 : : // Non-malleable satisfactions are guaranteed to be valid if ValidSatisfactions().
1127 [ + + - + ]: 1114 : if (node->ValidSatisfactions()) assert(res);
1128 : : // More detailed: non-malleable satisfactions must be valid, or could fail with ops count error (if CheckOpsLimit failed),
1129 : : // or with a stack size error (if CheckStackSize check failed).
1130 [ + + + - : 93 : assert(res ||
- + - - -
- ]
1131 : : (!node->CheckOpsLimit() && serror == ScriptError::SCRIPT_ERR_OP_COUNT) ||
1132 : : (!node->CheckStackSize() && serror == ScriptError::SCRIPT_ERR_STACK_SIZE));
1133 : : }
1134 : :
1135 [ + + + + : 3918 : if (mal_success && (!nonmal_success || witness_mal.stack != witness_nonmal.stack)) {
+ - ]
1136 : : // Test malleable satisfaction only if it's different from the non-malleable one.
1137 [ + - ]: 2555 : witness_mal.stack.insert(witness_mal.stack.end(), std::make_move_iterator(stack_mal.begin()), std::make_move_iterator(stack_mal.end()));
1138 [ + - ]: 2555 : SatisfactionToWitness(script_ctx, witness_mal, script, builder);
1139 : 2555 : ScriptError serror;
1140 [ + - ]: 2555 : bool res = VerifyScript(DUMMY_SCRIPTSIG, script_pubkey, &witness_mal, STANDARD_SCRIPT_VERIFY_FLAGS, CHECKER_CTX, &serror);
1141 : : // Malleable satisfactions are not guaranteed to be valid under any conditions, but they can only
1142 : : // fail due to stack or ops limits.
1143 [ + + + + : 2555 : assert(res || serror == ScriptError::SCRIPT_ERR_OP_COUNT || serror == ScriptError::SCRIPT_ERR_STACK_SIZE);
- + ]
1144 : : }
1145 : :
1146 [ + + ]: 3918 : if (node->IsSane()) {
1147 : : // For sane nodes, the two algorithms behave identically.
1148 [ - + ]: 483 : assert(mal_success == nonmal_success);
1149 : : }
1150 : :
1151 : : // Verify that if a node is policy-satisfiable, the malleable satisfaction
1152 : : // algorithm succeeds. Given that under IsSane() both satisfactions
1153 : : // are identical, this implies that for such nodes, the non-malleable
1154 : : // satisfaction will also match the expected policy.
1155 : 83882 : const auto is_key_satisfiable = [script_ctx](const CPubKey& pubkey) -> bool {
1156 : 79964 : auto sig_ptr{TEST_DATA.GetSig(script_ctx, pubkey)};
1157 [ + - + + ]: 79964 : return sig_ptr != nullptr && sig_ptr->second;
1158 : 3918 : };
1159 [ + - ]: 3918 : bool satisfiable = node->IsSatisfiable([&](const Node& node) -> bool {
1160 [ + + + + : 53176 : switch (node.Fragment()) {
+ + + - ]
1161 : 21991 : case Fragment::PK_K:
1162 : 21991 : case Fragment::PK_H:
1163 : 21991 : return is_key_satisfiable(node.Keys()[0]);
1164 : 9184 : case Fragment::MULTI:
1165 : 9184 : case Fragment::MULTI_A: {
1166 : 9184 : size_t sats = std::ranges::count_if(node.Keys(), [&](const auto& key) {
1167 : 57973 : return size_t(is_key_satisfiable(key));
1168 : 9184 : });
1169 : 9184 : return sats >= node.K();
1170 : : }
1171 : 9099 : case Fragment::OLDER:
1172 : 9099 : case Fragment::AFTER:
1173 : 9099 : return node.K() & 1;
1174 : 2881 : case Fragment::SHA256:
1175 : 2881 : return TEST_DATA.sha256_preimages.contains(node.Data());
1176 : 3444 : case Fragment::HASH256:
1177 : 3444 : return TEST_DATA.hash256_preimages.contains(node.Data());
1178 : 3104 : case Fragment::RIPEMD160:
1179 : 3104 : return TEST_DATA.ripemd160_preimages.contains(node.Data());
1180 : 3473 : case Fragment::HASH160:
1181 : 3473 : return TEST_DATA.hash160_preimages.contains(node.Data());
1182 : 0 : default:
1183 : 0 : assert(false);
1184 : : }
1185 : : return false;
1186 : : });
1187 [ - + ]: 3918 : assert(mal_success == satisfiable);
1188 : 4263 : }
1189 : :
1190 : : } // namespace
1191 : :
1192 : 3 : void FuzzInit()
1193 : : {
1194 [ + - + - : 3 : static ECC_Context ecc_context{};
+ - ]
1195 : 3 : TEST_DATA.Init();
1196 : 3 : }
1197 : :
1198 : 1 : void FuzzInitSmart()
1199 : : {
1200 : 1 : FuzzInit();
1201 : 1 : SMARTINFO.Init();
1202 : 1 : }
1203 : :
1204 : : /** Fuzz target that runs TestNode on nodes generated using ConsumeNodeStable. */
1205 [ + - ]: 2402 : FUZZ_TARGET(miniscript_stable, .init = FuzzInit)
1206 : : {
1207 : : // Run it under both P2WSH and Tapscript contexts.
1208 [ + + ]: 5778 : for (const auto script_ctx: {MsCtx::P2WSH, MsCtx::TAPSCRIPT}) {
1209 : 3852 : FuzzedDataProvider provider(buffer.data(), buffer.size());
1210 [ + - ]: 190885 : TestNode(script_ctx, GenNode(script_ctx, [&](Type needed_type) {
1211 [ + - ]: 183181 : return ConsumeNodeStable(script_ctx, provider, needed_type);
1212 : : }, ""_mst), provider);
1213 : : }
1214 : 1926 : }
1215 : :
1216 : : /** Fuzz target that runs TestNode on nodes generated using ConsumeNodeSmart. */
1217 [ + - ]: 2385 : FUZZ_TARGET(miniscript_smart, .init = FuzzInitSmart)
1218 : : {
1219 : : /** The set of types we aim to construct nodes for. Together they cover all. */
1220 : 1909 : static constexpr std::array<Type, 4> BASE_TYPES{"B"_mst, "V"_mst, "K"_mst, "W"_mst};
1221 : :
1222 : 1909 : FuzzedDataProvider provider(buffer.data(), buffer.size());
1223 : 1909 : const auto script_ctx{(MsCtx)provider.ConsumeBool()};
1224 [ + - ]: 158493 : TestNode(script_ctx, GenNode(script_ctx, [&](Type needed_type) {
1225 [ + - ]: 156584 : return ConsumeNodeSmart(script_ctx, provider, needed_type);
1226 : 1909 : }, PickValue(provider, BASE_TYPES), true), provider);
1227 : 1909 : }
1228 : :
1229 : : /* Fuzz tests that test parsing from a string, and roundtripping via string. */
1230 [ + - ]: 1450 : FUZZ_TARGET(miniscript_string, .init = FuzzInit)
1231 : : {
1232 [ + + + + ]: 1948 : constexpr auto is_too_expensive{[](std::span<const uint8_t> buf) { return HasTooManySubFrag(buf) || HasTooManyWrappers(buf); }};
1233 : :
1234 [ + - ]: 974 : if (buffer.empty()) return;
1235 : 974 : FuzzedDataProvider provider(buffer.data(), buffer.size());
1236 : 974 : auto str = provider.ConsumeBytesAsString(provider.remaining_bytes() - 1);
1237 [ + - + + ]: 974 : if (is_too_expensive(MakeUCharSpan(str))) return;
1238 : 965 : const ParserContext parser_ctx{(MsCtx)provider.ConsumeBool()};
1239 [ - + ]: 965 : auto parsed = miniscript::FromString(str, parser_ctx);
1240 [ + + ]: 965 : if (!parsed) return;
1241 : :
1242 [ + - ]: 535 : const auto str2 = parsed->ToString(parser_ctx);
1243 [ - + ]: 535 : assert(str2);
1244 [ - + ]: 535 : auto parsed2 = miniscript::FromString(*str2, parser_ctx);
1245 [ - + ]: 535 : assert(parsed2);
1246 [ + - - + ]: 535 : assert(*parsed == *parsed2);
1247 : 1404 : }
1248 : :
1249 : : /* Fuzz tests that test parsing from a script, and roundtripping via script. */
1250 [ + - ]: 1356 : FUZZ_TARGET(miniscript_script)
1251 : : {
1252 : 880 : FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
1253 : 880 : const std::optional<CScript> script = ConsumeDeserializable<CScript>(fuzzed_data_provider);
1254 [ + + ]: 880 : if (!script) return;
1255 : :
1256 : 867 : const ScriptParserContext script_parser_ctx{(MsCtx)fuzzed_data_provider.ConsumeBool()};
1257 [ + - ]: 867 : const auto ms = miniscript::FromScript(*script, script_parser_ctx);
1258 [ + + ]: 867 : if (!ms) return;
1259 : :
1260 [ + - - + ]: 606 : assert(ms->ToScript(script_parser_ctx) == *script);
1261 : 1444 : }
|