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