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 <util/strencodings.h>
15 : :
16 : : #include <algorithm>
17 : :
18 : : namespace {
19 : :
20 : : using Fragment = miniscript::Fragment;
21 : : using NodeRef = miniscript::NodeRef<CPubKey>;
22 : : using Node = miniscript::Node<CPubKey>;
23 : : using Type = miniscript::Type;
24 : : using MsCtx = miniscript::MiniscriptContext;
25 : : using miniscript::operator""_mst;
26 : :
27 : : //! Some pre-computed data for more efficient string roundtrips and to simulate challenges.
28 : : struct TestData {
29 : : typedef CPubKey Key;
30 : :
31 : : // Precomputed public keys, and a dummy signature for each of them.
32 : : std::vector<Key> dummy_keys;
33 : : std::map<Key, int> dummy_key_idx_map;
34 : : std::map<CKeyID, Key> dummy_keys_map;
35 : : std::map<Key, std::pair<std::vector<unsigned char>, bool>> dummy_sigs;
36 : : std::map<XOnlyPubKey, std::pair<std::vector<unsigned char>, bool>> schnorr_sigs;
37 : :
38 : : // Precomputed hashes of each kind.
39 : : std::vector<std::vector<unsigned char>> sha256;
40 : : std::vector<std::vector<unsigned char>> ripemd160;
41 : : std::vector<std::vector<unsigned char>> hash256;
42 : : std::vector<std::vector<unsigned char>> hash160;
43 : : std::map<std::vector<unsigned char>, std::vector<unsigned char>> sha256_preimages;
44 : : std::map<std::vector<unsigned char>, std::vector<unsigned char>> ripemd160_preimages;
45 : : std::map<std::vector<unsigned char>, std::vector<unsigned char>> hash256_preimages;
46 : : std::map<std::vector<unsigned char>, std::vector<unsigned char>> hash160_preimages;
47 : :
48 : : //! Set the precomputed data.
49 : 3 : void Init() {
50 : 3 : unsigned char keydata[32] = {1};
51 : : // All our signatures sign (and are required to sign) this constant message.
52 : 3 : constexpr uint256 MESSAGE_HASH{"0000000000000000f5cd94e18b6fe77dd7aca9e35c2b0c9cbd86356c80a71065"};
53 : : // We don't pass additional randomness when creating a schnorr signature.
54 : 3 : const auto EMPTY_AUX{uint256::ZERO};
55 : :
56 [ + + ]: 771 : for (size_t i = 0; i < 256; i++) {
57 : 768 : keydata[31] = i;
58 : 768 : CKey privkey;
59 [ + - ]: 768 : privkey.Set(keydata, keydata + 32, true);
60 [ + - ]: 768 : const Key pubkey = privkey.GetPubKey();
61 : :
62 [ + - ]: 768 : dummy_keys.push_back(pubkey);
63 [ + - ]: 768 : dummy_key_idx_map.emplace(pubkey, i);
64 [ + - + - ]: 768 : dummy_keys_map.insert({pubkey.GetID(), pubkey});
65 : 768 : XOnlyPubKey xonly_pubkey{pubkey};
66 [ + - ]: 768 : dummy_key_idx_map.emplace(xonly_pubkey, i);
67 [ + - ]: 768 : uint160 xonly_hash{Hash160(xonly_pubkey)};
68 [ + - ]: 768 : dummy_keys_map.emplace(xonly_hash, pubkey);
69 : :
70 [ + - ]: 768 : std::vector<unsigned char> sig, schnorr_sig(64);
71 [ + - ]: 768 : privkey.Sign(MESSAGE_HASH, sig);
72 [ + - ]: 768 : sig.push_back(1); // SIGHASH_ALL
73 [ + - + - ]: 1536 : dummy_sigs.insert({pubkey, {sig, i & 1}});
74 [ + - - + ]: 768 : assert(privkey.SignSchnorr(MESSAGE_HASH, schnorr_sig, nullptr, EMPTY_AUX));
75 [ + - ]: 768 : schnorr_sig.push_back(1); // Maximally-sized signature has sighash byte
76 [ + - ]: 768 : schnorr_sigs.emplace(XOnlyPubKey{pubkey}, std::make_pair(std::move(schnorr_sig), i & 1));
77 : :
78 : 768 : std::vector<unsigned char> hash;
79 [ + - ]: 768 : hash.resize(32);
80 [ + - + - : 768 : CSHA256().Write(keydata, 32).Finalize(hash.data());
+ - ]
81 [ + - ]: 768 : sha256.push_back(hash);
82 [ + + + - : 768 : if (i & 1) sha256_preimages[hash] = std::vector<unsigned char>(keydata, keydata + 32);
+ - ]
83 [ + - + - : 768 : CHash256().Write(keydata).Finalize(hash);
+ - ]
84 [ + - ]: 768 : hash256.push_back(hash);
85 [ + + + - : 768 : if (i & 1) hash256_preimages[hash] = std::vector<unsigned char>(keydata, keydata + 32);
+ - ]
86 [ + - ]: 768 : hash.resize(20);
87 [ + - + - : 768 : CRIPEMD160().Write(keydata, 32).Finalize(hash.data());
+ - ]
88 [ - + ]: 768 : assert(hash.size() == 20);
89 [ + - ]: 768 : ripemd160.push_back(hash);
90 [ + + + - : 768 : if (i & 1) ripemd160_preimages[hash] = std::vector<unsigned char>(keydata, keydata + 32);
+ - ]
91 [ + - + - : 768 : CHash160().Write(keydata).Finalize(hash);
+ - ]
92 [ + - ]: 768 : hash160.push_back(hash);
93 [ + + + - : 768 : if (i & 1) hash160_preimages[hash] = std::vector<unsigned char>(keydata, keydata + 32);
+ - ]
94 : 768 : }
95 : 3 : }
96 : :
97 : : //! Get the (Schnorr or ECDSA, depending on context) signature for this pubkey.
98 : 239454 : const std::pair<std::vector<unsigned char>, bool>* GetSig(const MsCtx script_ctx, const Key& key) const {
99 [ + + ]: 239454 : if (!miniscript::IsTapscript(script_ctx)) {
100 : 142344 : const auto it = dummy_sigs.find(key);
101 [ + - ]: 142344 : if (it == dummy_sigs.end()) return nullptr;
102 : 142344 : return &it->second;
103 : : } else {
104 : 97110 : const auto it = schnorr_sigs.find(XOnlyPubKey{key});
105 [ + - ]: 97110 : if (it == schnorr_sigs.end()) return nullptr;
106 : 97110 : return &it->second;
107 : : }
108 : : }
109 : : } TEST_DATA;
110 : :
111 : : /**
112 : : * Context to parse a Miniscript node to and from Script or text representation.
113 : : * Uses an integer (an index in the dummy keys array from the test data) as keys in order
114 : : * to focus on fuzzing the Miniscript nodes' test representation, not the key representation.
115 : : */
116 : : struct ParserContext {
117 : : typedef CPubKey Key;
118 : :
119 : : const MsCtx script_ctx;
120 : :
121 : 9642 : constexpr ParserContext(MsCtx ctx) noexcept : script_ctx(ctx) {}
122 : :
123 : 744942 : bool KeyCompare(const Key& a, const Key& b) const {
124 [ + + + + : 744942 : return a < b;
- - - - -
- - - + +
+ + + + ]
125 : : }
126 : :
127 : 138855 : std::optional<std::string> ToString(const Key& key) const
128 : : {
129 : 138855 : auto it = TEST_DATA.dummy_key_idx_map.find(key);
130 [ - + ]: 138855 : if (it == TEST_DATA.dummy_key_idx_map.end()) return {};
131 : 138855 : uint8_t idx = it->second;
132 : 138855 : return HexStr(std::span{&idx, 1});
133 : : }
134 : :
135 : 162387 : std::vector<unsigned char> ToPKBytes(const Key& key) const {
136 [ + + ]: 162387 : if (!miniscript::IsTapscript(script_ctx)) {
137 : 97034 : return {key.begin(), key.end()};
138 : : }
139 : 65353 : const XOnlyPubKey xonly_pubkey{key};
140 : 65353 : return {xonly_pubkey.begin(), xonly_pubkey.end()};
141 : : }
142 : :
143 : 16513 : std::vector<unsigned char> ToPKHBytes(const Key& key) const {
144 [ + + ]: 16513 : if (!miniscript::IsTapscript(script_ctx)) {
145 : 8909 : const auto h = Hash160(key);
146 : 8909 : return {h.begin(), h.end()};
147 : : }
148 : 7604 : const auto h = Hash160(XOnlyPubKey{key});
149 : 7604 : return {h.begin(), h.end()};
150 : : }
151 : :
152 : : template<typename I>
153 [ + + ]: 153331 : std::optional<Key> FromString(I first, I last) const {
154 [ + + ]: 153331 : if (last - first != 2) return {};
155 [ + - + + ]: 306644 : auto idx = ParseHex(std::string(first, last));
156 [ + + ]: 153322 : if (idx.size() != 1) return {};
157 : 153306 : return TEST_DATA.dummy_keys[idx[0]];
158 : 153322 : }
159 : :
160 : : template<typename I>
161 : 71757 : std::optional<Key> FromPKBytes(I first, I last) const {
162 [ + + ]: 71757 : if (!miniscript::IsTapscript(script_ctx)) {
163 [ + - ]: 43124 : Key key{first, last};
164 [ + - ]: 43124 : if (key.IsValid()) return key;
165 : 0 : return {};
166 : : }
167 [ - + ]: 28633 : if (last - first != 32) return {};
168 : 28633 : XOnlyPubKey xonly_pubkey;
169 : 28633 : std::copy(first, last, xonly_pubkey.begin());
170 : 28633 : return xonly_pubkey.GetEvenCorrespondingCPubKey();
171 : : }
172 : :
173 : : template<typename I>
174 [ - + ]: 8061 : std::optional<Key> FromPKHBytes(I first, I last) const {
175 [ - + ]: 8061 : assert(last - first == 20);
176 : 8061 : CKeyID keyid;
177 : 8061 : std::copy(first, last, keyid.begin());
178 [ - + ]: 8061 : const auto it = TEST_DATA.dummy_keys_map.find(keyid);
179 [ - + ]: 8061 : if (it == TEST_DATA.dummy_keys_map.end()) return {};
180 : 8061 : return it->second;
181 : : }
182 : :
183 : 9392926 : MsCtx MsContext() const {
184 [ + - + - : 9392926 : return script_ctx;
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + + +
- + - ]
185 : : }
186 : : };
187 : :
188 : : //! Context that implements naive conversion from/to script only, for roundtrip testing.
189 : : struct ScriptParserContext {
190 : : const MsCtx script_ctx;
191 : :
192 : 956 : constexpr ScriptParserContext(MsCtx ctx) noexcept : script_ctx(ctx) {}
193 : :
194 : : //! For Script roundtrip we never need the key from a key hash.
195 [ + - ]: 41304 : struct Key {
196 : : bool is_hash;
197 : : std::vector<unsigned char> data;
198 : : };
199 : :
200 : 19951 : bool KeyCompare(const Key& a, const Key& b) const {
201 [ + + + + : 19951 : return a.data < b.data;
- - - - -
- - - + +
+ + + + ]
202 : : }
203 : :
204 : 911 : const std::vector<unsigned char>& ToPKBytes(const Key& key) const
205 : : {
206 [ - + ]: 911 : assert(!key.is_hash);
207 : 911 : return key.data;
208 : : }
209 : :
210 : 600 : std::vector<unsigned char> ToPKHBytes(const Key& key) const
211 : : {
212 [ + - ]: 600 : if (key.is_hash) return key.data;
213 : 0 : const auto h = Hash160(key.data);
214 : 0 : return {h.begin(), h.end()};
215 : : }
216 : :
217 : : template<typename I>
218 [ + - ]: 4649 : std::optional<Key> FromPKBytes(I first, I last) const
219 : : {
220 [ + - ]: 4649 : Key key;
221 : 4649 : key.data.assign(first, last);
222 : 4649 : key.is_hash = false;
223 : 4649 : return key;
224 : 4649 : }
225 : :
226 : : template<typename I>
227 [ + - ]: 3484 : std::optional<Key> FromPKHBytes(I first, I last) const
228 : : {
229 [ + - ]: 3484 : Key key;
230 : 3484 : key.data.assign(first, last);
231 : 3484 : key.is_hash = true;
232 : 3484 : return key;
233 : 3484 : }
234 : :
235 : 4158593 : MsCtx MsContext() const {
236 [ + - + - : 4158593 : return script_ctx;
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - +
- ]
237 : : }
238 : : };
239 : :
240 : : //! Context to produce a satisfaction for a Miniscript node using the pre-computed data.
241 : : struct SatisfierContext : ParserContext {
242 : :
243 : 4096 : constexpr SatisfierContext(MsCtx ctx) noexcept : ParserContext(ctx) {}
244 : :
245 : : // Timelock challenges satisfaction. Make the value (deterministically) vary to explore different
246 : : // paths.
247 [ + + ]: 7154 : bool CheckAfter(uint32_t value) const { return value % 2; }
248 [ + + ]: 9722 : bool CheckOlder(uint32_t value) const { return value % 2; }
249 : :
250 : : // Signature challenges fulfilled with a dummy signature, if it was one of our dummy keys.
251 : 159636 : miniscript::Availability Sign(const CPubKey& key, std::vector<unsigned char>& sig) const {
252 : 159636 : bool sig_available{false};
253 [ + - ]: 159636 : if (auto res = TEST_DATA.GetSig(script_ctx, key)) {
254 : 159636 : std::tie(sig, sig_available) = *res;
255 : : }
256 [ + + ]: 159636 : return sig_available ? miniscript::Availability::YES : miniscript::Availability::NO;
257 : : }
258 : :
259 : : //! Lookup generalization for all the hash satisfactions below
260 : 25614 : miniscript::Availability LookupHash(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage,
261 : : const std::map<std::vector<unsigned char>, std::vector<unsigned char>>& map) const
262 : : {
263 : 25614 : const auto it = map.find(hash);
264 [ + + ]: 25614 : if (it == map.end()) return miniscript::Availability::NO;
265 : 16370 : preimage = it->second;
266 : 16370 : return miniscript::Availability::YES;
267 : : }
268 : 5838 : miniscript::Availability SatSHA256(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
269 [ + - ]: 5838 : return LookupHash(hash, preimage, TEST_DATA.sha256_preimages);
270 : : }
271 : 5902 : miniscript::Availability SatRIPEMD160(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
272 [ + - ]: 5902 : return LookupHash(hash, preimage, TEST_DATA.ripemd160_preimages);
273 : : }
274 : 7372 : miniscript::Availability SatHASH256(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
275 [ + - ]: 7372 : return LookupHash(hash, preimage, TEST_DATA.hash256_preimages);
276 : : }
277 : 6502 : miniscript::Availability SatHASH160(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
278 [ + - ]: 6502 : return LookupHash(hash, preimage, TEST_DATA.hash160_preimages);
279 : : }
280 : : };
281 : :
282 : : //! Context to check a satisfaction against the pre-computed data.
283 : : const struct CheckerContext: BaseSignatureChecker {
284 : : // Signature checker methods. Checks the right dummy signature is used.
285 : 25146 : bool CheckECDSASignature(const std::vector<unsigned char>& sig, const std::vector<unsigned char>& vchPubKey,
286 : : const CScript& scriptCode, SigVersion sigversion) const override
287 : : {
288 : 25146 : const CPubKey key{vchPubKey};
289 : 25146 : const auto it = TEST_DATA.dummy_sigs.find(key);
290 [ + - ]: 25146 : if (it == TEST_DATA.dummy_sigs.end()) return false;
291 : 25146 : return it->second.first == sig;
292 : : }
293 : 8961 : bool CheckSchnorrSignature(std::span<const unsigned char> sig, std::span<const unsigned char> pubkey, SigVersion,
294 : : ScriptExecutionData&, ScriptError*) const override {
295 : 8961 : XOnlyPubKey pk{pubkey};
296 : 8961 : auto it = TEST_DATA.schnorr_sigs.find(pk);
297 [ + - ]: 8961 : if (it == TEST_DATA.schnorr_sigs.end()) return false;
298 : 8961 : return std::ranges::equal(it->second.first, sig);
299 : : }
300 : 1129 : bool CheckLockTime(const CScriptNum& nLockTime) const override { return nLockTime.GetInt64() & 1; }
301 : 1948 : bool CheckSequence(const CScriptNum& nSequence) const override { return nSequence.GetInt64() & 1; }
302 : : } CHECKER_CTX;
303 : :
304 : : //! Context to check for duplicates when instancing a Node.
305 : : const struct KeyComparator {
306 : 261183 : bool KeyCompare(const CPubKey& a, const CPubKey& b) const {
307 [ + + + + : 261183 : return a < b;
- - - - -
- - - + +
+ + + + ]
308 : : }
309 : : } KEY_COMP;
310 : :
311 : : // A dummy scriptsig to pass to VerifyScript (we always use Segwit v0).
312 : : const CScript DUMMY_SCRIPTSIG;
313 : :
314 : : //! Construct a miniscript node as a shared_ptr.
315 : 321413 : template<typename... Args> NodeRef MakeNodeRef(Args&&... args) {
316 : 321413 : return miniscript::MakeNodeRef<CPubKey>(miniscript::internal::NoDupCheck{}, std::forward<Args>(args)...);
317 : : }
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 : 35924 : NodeInfo(Fragment frag): fragment(frag), k(0) {}
333 : 22995 : NodeInfo(Fragment frag, CPubKey key): fragment(frag), k(0), keys({key}) {}
334 : 6341 : NodeInfo(Fragment frag, uint32_t _k): fragment(frag), k(_k) {}
335 : 14567 : NodeInfo(Fragment frag, std::vector<unsigned char> h): fragment(frag), k(0), hash(std::move(h)) {}
336 : 105800 : NodeInfo(std::vector<Type> subt, Fragment frag): fragment(frag), k(0), subtypes(std::move(subt)) {}
337 : 10808 : NodeInfo(std::vector<Type> subt, Fragment frag, uint32_t _k): fragment(frag), k(_k), subtypes(std::move(subt)) {}
338 : 10246 : 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 : 108602 : T ConsumeIndex(FuzzedDataProvider& provider, A& col) {
344 : 108602 : const uint8_t i = provider.ConsumeIntegral<uint8_t>();
345 : 108602 : return col[i];
346 : : }
347 : :
348 : 100640 : CPubKey ConsumePubKey(FuzzedDataProvider& provider) {
349 : 100640 : return ConsumeIndex<CPubKey>(provider, TEST_DATA.dummy_keys);
350 : : }
351 : :
352 : 1737 : std::vector<unsigned char> ConsumeSha256(FuzzedDataProvider& provider) {
353 : 1737 : return ConsumeIndex<std::vector<unsigned char>>(provider, TEST_DATA.sha256);
354 : : }
355 : :
356 : 2753 : std::vector<unsigned char> ConsumeHash256(FuzzedDataProvider& provider) {
357 : 2753 : return ConsumeIndex<std::vector<unsigned char>>(provider, TEST_DATA.hash256);
358 : : }
359 : :
360 : 1807 : std::vector<unsigned char> ConsumeRipemd160(FuzzedDataProvider& provider) {
361 : 1807 : return ConsumeIndex<std::vector<unsigned char>>(provider, TEST_DATA.ripemd160);
362 : : }
363 : :
364 : 1665 : std::vector<unsigned char> ConsumeHash160(FuzzedDataProvider& provider) {
365 : 1665 : return ConsumeIndex<std::vector<unsigned char>>(provider, TEST_DATA.hash160);
366 : : }
367 : :
368 : 6370 : std::optional<uint32_t> ConsumeTimeLock(FuzzedDataProvider& provider) {
369 : 6370 : const uint32_t k = provider.ConsumeIntegral<uint32_t>();
370 [ + + ]: 6370 : if (k == 0 || k >= 0x80000000) return {};
371 : 6341 : 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 : 177302 : std::optional<NodeInfo> ConsumeNodeStable(MsCtx script_ctx, FuzzedDataProvider& provider, Type type_needed) {
389 [ + + + + ]: 177302 : bool allow_B = (type_needed == ""_mst) || (type_needed << "B"_mst);
390 [ + + + + ]: 177302 : bool allow_K = (type_needed == ""_mst) || (type_needed << "K"_mst);
391 [ + + + + ]: 177302 : bool allow_V = (type_needed == ""_mst) || (type_needed << "V"_mst);
392 [ + + + + ]: 177302 : bool allow_W = (type_needed == ""_mst) || (type_needed << "W"_mst);
393 : :
394 [ + + + + : 177302 : switch (provider.ConsumeIntegral<uint8_t>()) {
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + ]
395 : 27337 : case 0:
396 [ + + ]: 27337 : if (!allow_B) return {};
397 : 27262 : return {{Fragment::JUST_0}};
398 : 8668 : case 1:
399 [ + + ]: 8668 : if (!allow_B) return {};
400 : 8662 : return {{Fragment::JUST_1}};
401 : 6014 : case 2:
402 [ + + ]: 6014 : if (!allow_K) return {};
403 : 6008 : return {{Fragment::PK_K, ConsumePubKey(provider)}};
404 : 4603 : case 3:
405 [ + + ]: 4603 : if (!allow_K) return {};
406 : 4598 : return {{Fragment::PK_H, ConsumePubKey(provider)}};
407 : 3759 : case 4: {
408 [ + + ]: 3759 : if (!allow_B) return {};
409 : 3750 : const auto k = ConsumeTimeLock(provider);
410 [ + + ]: 3750 : if (!k) return {};
411 : 3733 : return {{Fragment::OLDER, *k}};
412 : : }
413 : 2625 : case 5: {
414 [ + + ]: 2625 : if (!allow_B) return {};
415 : 2620 : const auto k = ConsumeTimeLock(provider);
416 [ + + ]: 2620 : if (!k) return {};
417 : 2608 : return {{Fragment::AFTER, *k}};
418 : : }
419 : 1742 : case 6:
420 [ + + ]: 1742 : if (!allow_B) return {};
421 : 1737 : return {{Fragment::SHA256, ConsumeSha256(provider)}};
422 : 2757 : case 7:
423 [ + + ]: 2757 : if (!allow_B) return {};
424 : 2753 : return {{Fragment::HASH256, ConsumeHash256(provider)}};
425 : 1812 : case 8:
426 [ + + ]: 1812 : if (!allow_B) return {};
427 : 1807 : return {{Fragment::RIPEMD160, ConsumeRipemd160(provider)}};
428 : 1668 : case 9:
429 [ + + ]: 1668 : if (!allow_B) return {};
430 : 1665 : return {{Fragment::HASH160, ConsumeHash160(provider)}};
431 : 4931 : case 10: {
432 [ + + + + ]: 4931 : if (!allow_B || IsTapscript(script_ctx)) return {};
433 : 4161 : const auto k = provider.ConsumeIntegral<uint8_t>();
434 : 4161 : const auto n_keys = provider.ConsumeIntegral<uint8_t>();
435 [ + + + + ]: 4161 : if (n_keys > 20 || k == 0 || k > n_keys) return {};
436 : 4154 : std::vector<CPubKey> keys{n_keys};
437 [ + + ]: 23872 : for (auto& key: keys) key = ConsumePubKey(provider);
438 : 4154 : return {{Fragment::MULTI, k, std::move(keys)}};
439 : 4154 : }
440 : 9028 : case 11:
441 [ + + + + ]: 9028 : if (!(allow_B || allow_K || allow_V)) return {};
442 : 9025 : return {{{"B"_mst, type_needed, type_needed}, Fragment::ANDOR}};
443 : 20160 : case 12:
444 [ + + + + ]: 20160 : if (!(allow_B || allow_K || allow_V)) return {};
445 : 20155 : return {{{"V"_mst, type_needed}, Fragment::AND_V}};
446 : 4966 : case 13:
447 [ + + ]: 4966 : if (!allow_B) return {};
448 : 4962 : return {{{"B"_mst, "W"_mst}, Fragment::AND_B}};
449 : 2921 : case 15:
450 [ + + ]: 2921 : if (!allow_B) return {};
451 : 2917 : return {{{"B"_mst, "W"_mst}, Fragment::OR_B}};
452 : 2061 : case 16:
453 [ + + ]: 2061 : if (!allow_V) return {};
454 : 2056 : return {{{"B"_mst, "V"_mst}, Fragment::OR_C}};
455 : 6373 : case 17:
456 [ + + ]: 6373 : if (!allow_B) return {};
457 : 6367 : return {{{"B"_mst, "B"_mst}, Fragment::OR_D}};
458 : 11837 : case 18:
459 [ + + + + ]: 11837 : if (!(allow_B || allow_K || allow_V)) return {};
460 : 11830 : return {{{type_needed, type_needed}, Fragment::OR_I}};
461 : 4507 : case 19: {
462 [ + + ]: 4507 : if (!allow_B) return {};
463 : 4502 : auto k = provider.ConsumeIntegral<uint8_t>();
464 : 4502 : auto n_subs = provider.ConsumeIntegral<uint8_t>();
465 [ + + ]: 4502 : if (k == 0 || k > n_subs) return {};
466 : 4486 : std::vector<Type> subtypes;
467 [ + - ]: 4486 : subtypes.reserve(n_subs);
468 [ + - ]: 4486 : subtypes.emplace_back("B"_mst);
469 [ + - + + ]: 20212 : for (size_t i = 1; i < n_subs; ++i) subtypes.emplace_back("W"_mst);
470 : 4486 : return {{std::move(subtypes), Fragment::THRESH, k}};
471 : 4486 : }
472 : 11613 : case 20:
473 [ + + ]: 11613 : if (!allow_W) return {};
474 : 11609 : return {{{"B"_mst}, Fragment::WRAP_A}};
475 : 927 : case 21:
476 [ + + ]: 927 : if (!allow_W) return {};
477 : 924 : return {{{"B"_mst}, Fragment::WRAP_S}};
478 : 8243 : case 22:
479 [ + + ]: 8243 : if (!allow_B) return {};
480 : 8238 : return {{{"K"_mst}, Fragment::WRAP_C}};
481 : 956 : case 23:
482 [ + + ]: 956 : if (!allow_B) return {};
483 : 952 : return {{{"V"_mst}, Fragment::WRAP_D}};
484 : 20160 : case 24:
485 [ + + ]: 20160 : if (!allow_V) return {};
486 : 20155 : return {{{"B"_mst}, Fragment::WRAP_V}};
487 : 2120 : case 25:
488 [ + + ]: 2120 : if (!allow_B) return {};
489 : 2115 : return {{{"B"_mst}, Fragment::WRAP_J}};
490 : 4500 : case 26:
491 [ + + ]: 4500 : if (!allow_B) return {};
492 : 4495 : return {{{"B"_mst}, Fragment::WRAP_N}};
493 : 1003 : case 27: {
494 [ + + + + ]: 1003 : if (!allow_B || !IsTapscript(script_ctx)) return {};
495 : 797 : const auto k = provider.ConsumeIntegral<uint16_t>();
496 : 797 : const auto n_keys = provider.ConsumeIntegral<uint16_t>();
497 [ + + + + ]: 797 : if (n_keys > 999 || k == 0 || k > n_keys) return {};
498 : 790 : std::vector<CPubKey> keys{n_keys};
499 [ + + ]: 14492 : for (auto& key: keys) key = ConsumePubKey(provider);
500 : 790 : return {{Fragment::MULTI_A, k, std::move(keys)}};
501 : 790 : }
502 : 11 : default:
503 : 11 : break;
504 : : }
505 : 11 : 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 [ - + - + : 93497 : 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.count(type) != 0) {
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.count(type_it->first) == 0) {
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.count(type) != 0; };
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 : 163170 : std::optional<NodeInfo> ConsumeNodeSmart(MsCtx script_ctx, FuzzedDataProvider& provider, Type type_needed) {
773 : : /** Table entry for the requested type. */
774 [ + + ]: 163170 : const auto& table{IsTapscript(script_ctx) ? SMARTINFO.tap_table : SMARTINFO.wsh_table};
775 : 163170 : auto recipes_it = table.find(type_needed);
776 [ - + ]: 163170 : assert(recipes_it != table.end());
777 : : /** Pick one recipe from the available ones for that type. */
778 [ + + + + : 163170 : 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 [ + + + + : 163170 : switch (frag) {
+ + + + +
+ - ]
782 : 12389 : case Fragment::PK_K:
783 : 12389 : case Fragment::PK_H:
784 : 12389 : return {{frag, ConsumePubKey(provider)}};
785 : 4204 : case Fragment::MULTI: {
786 : 4204 : const auto n_keys = provider.ConsumeIntegralInRange<uint8_t>(1, 20);
787 : 4204 : const auto k = provider.ConsumeIntegralInRange<uint8_t>(1, n_keys);
788 : 4204 : std::vector<CPubKey> keys{n_keys};
789 [ + + ]: 24168 : for (auto& key: keys) key = ConsumePubKey(provider);
790 : 4204 : return {{frag, k, std::move(keys)}};
791 : 4204 : }
792 : 1098 : case Fragment::MULTI_A: {
793 : 1098 : const auto n_keys = provider.ConsumeIntegralInRange<uint16_t>(1, 999);
794 : 1098 : const auto k = provider.ConsumeIntegralInRange<uint16_t>(1, n_keys);
795 : 1098 : std::vector<CPubKey> keys{n_keys};
796 [ + + ]: 25359 : for (auto& key: keys) key = ConsumePubKey(provider);
797 : 1098 : return {{frag, k, std::move(keys)}};
798 : 1098 : }
799 : 3340 : case Fragment::OLDER:
800 : 3340 : case Fragment::AFTER:
801 : 3340 : return {{frag, provider.ConsumeIntegralInRange<uint32_t>(1, 0x7FFFFFF)}};
802 : 1583 : case Fragment::SHA256:
803 : 1583 : return {{frag, PickValue(provider, TEST_DATA.sha256)}};
804 : 1577 : case Fragment::HASH256:
805 : 1577 : return {{frag, PickValue(provider, TEST_DATA.hash256)}};
806 : 1546 : case Fragment::RIPEMD160:
807 : 1546 : return {{frag, PickValue(provider, TEST_DATA.ripemd160)}};
808 : 1899 : case Fragment::HASH160:
809 : 1899 : return {{frag, PickValue(provider, TEST_DATA.hash160)}};
810 : 129212 : case Fragment::JUST_0:
811 : 129212 : case Fragment::JUST_1:
812 : 129212 : case Fragment::WRAP_A:
813 : 129212 : case Fragment::WRAP_S:
814 : 129212 : case Fragment::WRAP_C:
815 : 129212 : case Fragment::WRAP_D:
816 : 129212 : case Fragment::WRAP_V:
817 : 129212 : case Fragment::WRAP_J:
818 : 129212 : case Fragment::WRAP_N:
819 : 129212 : case Fragment::AND_V:
820 : 129212 : case Fragment::AND_B:
821 : 129212 : case Fragment::OR_B:
822 : 129212 : case Fragment::OR_C:
823 : 129212 : case Fragment::OR_D:
824 : 129212 : case Fragment::OR_I:
825 : 129212 : case Fragment::ANDOR:
826 : 129212 : return {{subt, frag}};
827 : 6322 : case Fragment::THRESH: {
828 : 6322 : uint32_t children;
829 [ + + ]: 6322 : if (subt.size() < 2) {
830 : 5378 : 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 : 944 : children = provider.ConsumeIntegralInRange<uint32_t>(2, MAX_OPS_PER_SCRIPT / 2);
835 : : }
836 : 6322 : auto k = provider.ConsumeIntegralInRange<uint32_t>(1, children);
837 : 6322 : std::vector<Type> subs = subt;
838 [ + - + + ]: 30164 : while (subs.size() < children) subs.push_back(subs.back());
839 : 6322 : return {{std::move(subs), frag, k}};
840 : 6322 : }
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 NodeRef.
851 : : * - strict_valid sets whether ConsumeNode is expected to guarantee a NodeInfo that results in
852 : : * a NodeRef whose Type() matches the type fed to ConsumeNode.
853 : : */
854 : : template<typename F>
855 : 6103 : NodeRef GenNode(MsCtx script_ctx, F ConsumeNode, Type root_type, bool strict_valid = false) {
856 : : /** A stack of miniscript Nodes being built up. */
857 : 6103 : std::vector<NodeRef> stack;
858 : : /** The queue of instructions. */
859 [ + - + + : 18309 : std::vector<std::pair<Type, std::optional<NodeInfo>>> todo{{root_type, {}}};
- - ]
860 : : /** Predict the number of (static) script ops. */
861 : 6103 : uint32_t ops{0};
862 : : /** Predict the total script size (every unexplored subnode is counted as one, as every leaf is
863 : : * at least one script byte). */
864 : 6103 : uint32_t scriptsize{1};
865 : :
866 [ + + ]: 666382 : while (!todo.empty()) {
867 : : // The expected type we have to construct.
868 : 661885 : auto type_needed = todo.back().first;
869 [ + + ]: 661885 : if (!todo.back().second) {
870 : : // Fragment/children have not been decided yet. Decide them.
871 [ + + ]: 340472 : auto node_info = ConsumeNode(type_needed);
872 [ + + ]: 340472 : if (!node_info) return {};
873 : : // Update predicted resource limits. Since every leaf Miniscript node is at least one
874 : : // byte long, we move one byte from each child to their parent. A similar technique is
875 : : // used in the miniscript::internal::Parse function to prevent runaway string parsing.
876 [ + - ]: 339233 : scriptsize += miniscript::internal::ComputeScriptLen(node_info->fragment, ""_mst, node_info->subtypes.size(), node_info->k, node_info->subtypes.size(),
877 [ + - ]: 339233 : node_info->keys.size(), script_ctx) - 1;
878 [ + + ]: 339233 : if (scriptsize > MAX_STANDARD_P2WSH_SCRIPT_SIZE) return {};
879 [ + + + + : 339195 : switch (node_info->fragment) {
+ + + + +
+ + + + +
+ + + + ]
880 : : case Fragment::JUST_0:
881 : : case Fragment::JUST_1:
882 : : break;
883 : : case Fragment::PK_K:
884 : : break;
885 : 8792 : case Fragment::PK_H:
886 : 8792 : ops += 3;
887 : 8792 : break;
888 : 9680 : case Fragment::OLDER:
889 : : case Fragment::AFTER:
890 : 9680 : ops += 1;
891 : 9680 : break;
892 : 14567 : case Fragment::RIPEMD160:
893 : : case Fragment::SHA256:
894 : : case Fragment::HASH160:
895 : : case Fragment::HASH256:
896 : 14567 : ops += 4;
897 : 14567 : break;
898 : 15858 : case Fragment::ANDOR:
899 : 15858 : ops += 3;
900 : 15858 : break;
901 : : case Fragment::AND_V:
902 : : break;
903 : 15253 : case Fragment::AND_B:
904 : : case Fragment::OR_B:
905 : 15253 : ops += 1;
906 : 15253 : break;
907 : 4492 : case Fragment::OR_C:
908 : 4492 : ops += 2;
909 : 4492 : break;
910 : 10708 : case Fragment::OR_D:
911 : 10708 : ops += 3;
912 : 10708 : break;
913 : 19868 : case Fragment::OR_I:
914 : 19868 : ops += 3;
915 : 19868 : break;
916 : 10808 : case Fragment::THRESH:
917 : 10808 : ops += node_info->subtypes.size();
918 : 10808 : break;
919 : 8357 : case Fragment::MULTI:
920 : 8357 : ops += 1;
921 : 8357 : break;
922 : 1860 : case Fragment::MULTI_A:
923 : 1860 : ops += node_info->keys.size() + 1;
924 : 1860 : break;
925 : 27587 : case Fragment::WRAP_A:
926 : 27587 : ops += 2;
927 : 27587 : break;
928 : 3329 : case Fragment::WRAP_S:
929 : 3329 : ops += 1;
930 : 3329 : break;
931 : 15094 : case Fragment::WRAP_C:
932 : 15094 : ops += 1;
933 : 15094 : break;
934 : 1620 : case Fragment::WRAP_D:
935 : 1620 : ops += 3;
936 : 1620 : break;
937 : : case Fragment::WRAP_V:
938 : : // We don't account for OP_VERIFY here; that will be corrected for when the actual
939 : : // node is constructed below.
940 : : break;
941 : 3259 : case Fragment::WRAP_J:
942 : 3259 : ops += 4;
943 : 3259 : break;
944 : 8888 : case Fragment::WRAP_N:
945 : 8888 : ops += 1;
946 : 8888 : break;
947 : : }
948 [ + + ]: 339195 : if (ops > MAX_OPS_PER_SCRIPT) return {};
949 [ + - ]: 339077 : auto subtypes = node_info->subtypes;
950 [ + - ]: 339077 : todo.back().second = std::move(node_info);
951 [ + - ]: 339077 : todo.reserve(todo.size() + subtypes.size());
952 : : // As elements on the todo stack are processed back to front, construct
953 : : // them in reverse order (so that the first subnode is generated first).
954 [ + + ]: 698716 : for (size_t i = 0; i < subtypes.size(); ++i) {
955 [ + - ]: 359639 : todo.emplace_back(*(subtypes.rbegin() + i), std::nullopt);
956 : : }
957 : 340472 : } else {
958 : : // The back of todo has fragment and number of children decided, and
959 : : // those children have been constructed at the back of stack. Pop
960 : : // that entry off todo, and use it to construct a new NodeRef on
961 : : // stack.
962 [ + - ]: 321413 : NodeInfo& info = *todo.back().second;
963 : : // Gather children from the back of stack.
964 : 321413 : std::vector<NodeRef> sub;
965 [ + - ]: 321413 : sub.reserve(info.subtypes.size());
966 [ + + ]: 632458 : for (size_t i = 0; i < info.subtypes.size(); ++i) {
967 [ + - ]: 311045 : sub.push_back(std::move(*(stack.end() - info.subtypes.size() + i)));
968 : : }
969 : 321413 : stack.erase(stack.end() - info.subtypes.size(), stack.end());
970 : : // Construct new NodeRef.
971 : 321413 : NodeRef node;
972 [ + + ]: 321413 : if (info.keys.empty()) {
973 [ + - ]: 576432 : node = MakeNodeRef(script_ctx, info.fragment, std::move(sub), std::move(info.hash), info.k);
974 : : } else {
975 [ - + ]: 33197 : assert(sub.empty());
976 [ - + ]: 33197 : assert(info.hash.empty());
977 [ + - ]: 66394 : node = MakeNodeRef(script_ctx, info.fragment, std::move(info.keys), info.k);
978 : : }
979 : : // Verify acceptability.
980 [ + - + + ]: 321413 : if (!node || (node->GetType() & "KVWB"_mst) == ""_mst) {
981 [ - + ]: 190 : assert(!strict_valid);
982 : 190 : return {};
983 : : }
984 [ + + ]: 321223 : if (!(type_needed == ""_mst)) {
985 [ - + ]: 303237 : assert(node->GetType() << type_needed);
986 : : }
987 [ + + ]: 321223 : if (!node->IsValid()) return {};
988 : : // Update resource predictions.
989 [ + + + + ]: 321221 : if (node->fragment == Fragment::WRAP_V && node->subs[0]->GetType() << "x"_mst) {
990 : 18208 : ops += 1;
991 : 18208 : scriptsize += 1;
992 : : }
993 [ + + + + ]: 321221 : if (!miniscript::IsTapscript(script_ctx) && ops > MAX_OPS_PER_SCRIPT) return {};
994 [ + + + + ]: 522996 : if (scriptsize > miniscript::internal::MaxScriptSize(script_ctx)) {
995 : 2 : return {};
996 : : }
997 : : // Move it to the stack.
998 : 321202 : stack.push_back(std::move(node));
999 : 321202 : todo.pop_back();
1000 : 321413 : }
1001 : : }
1002 [ - + ]: 4497 : assert(stack.size() == 1);
1003 [ - + ]: 4497 : assert(stack[0]->GetStaticOps() == ops);
1004 [ - + ]: 4497 : assert(stack[0]->ScriptSize() == scriptsize);
1005 [ + - ]: 4497 : stack[0]->DuplicateKeyCheck(KEY_COMP);
1006 : 4497 : return std::move(stack[0]);
1007 [ + - - + ]: 18309 : }
1008 : :
1009 : : //! The spk for this script under the given context. If it's a Taproot output also record the spend data.
1010 : 4096 : CScript ScriptPubKey(MsCtx ctx, const CScript& script, TaprootBuilder& builder)
1011 : : {
1012 [ + + + - : 4096 : if (!miniscript::IsTapscript(ctx)) return CScript() << OP_0 << WitnessV0ScriptHash(script);
+ - ]
1013 : :
1014 : : // For Taproot outputs we always use a tree with a single script and a dummy internal key.
1015 [ + + ]: 3350 : builder.Add(0, script, TAPROOT_LEAF_TAPSCRIPT);
1016 : 1675 : builder.Finalize(XOnlyPubKey::NUMS_H);
1017 [ + - ]: 3350 : return GetScriptForDestination(builder.GetOutput());
1018 : : }
1019 : :
1020 : : //! Fill the witness with the data additional to the script satisfaction.
1021 : 3674 : void SatisfactionToWitness(MsCtx ctx, CScriptWitness& witness, const CScript& script, TaprootBuilder& builder) {
1022 : : // For P2WSH, it's only the witness script.
1023 [ + + ]: 7348 : witness.stack.emplace_back(script.begin(), script.end());
1024 [ + + ]: 3674 : if (!miniscript::IsTapscript(ctx)) return;
1025 : : // For Tapscript we also need the control block.
1026 [ + - ]: 2944 : witness.stack.push_back(*builder.GetSpendData().scripts.begin()->second.begin());
1027 : : }
1028 : :
1029 : : /** Perform various applicable tests on a miniscript Node. */
1030 : 6103 : void TestNode(const MsCtx script_ctx, const NodeRef& node, FuzzedDataProvider& provider)
1031 : : {
1032 [ + + ]: 6103 : if (!node) return;
1033 : :
1034 : : // Check that it roundtrips to text representation
1035 : 4497 : const ParserContext parser_ctx{script_ctx};
1036 : 4497 : std::optional<std::string> str{node->ToString(parser_ctx)};
1037 [ - + ]: 4497 : assert(str);
1038 [ + - ]: 4497 : auto parsed = miniscript::FromString(*str, parser_ctx);
1039 [ - + ]: 4497 : assert(parsed);
1040 [ + - - + ]: 4497 : assert(*parsed == *node);
1041 : :
1042 : : // Check consistency between script size estimation and real size.
1043 [ + - ]: 4497 : auto script = node->ToScript(parser_ctx);
1044 [ + + - + ]: 8666 : assert(node->ScriptSize() == script.size());
1045 : :
1046 : : // Check consistency of "x" property with the script (type K is excluded, because it can end
1047 : : // with a push of a key, which could match these opcodes).
1048 [ + + ]: 4497 : if (!(node->GetType() << "K"_mst)) {
1049 [ + + ]: 4379 : bool ends_in_verify = !(node->GetType() << "x"_mst);
1050 [ + + + + : 20404 : assert(ends_in_verify == (script.back() == OP_CHECKSIG || script.back() == OP_CHECKMULTISIG || script.back() == OP_EQUAL || script.back() == OP_NUMEQUAL));
+ + + + +
+ - + ]
1051 : : }
1052 : :
1053 : : // The rest of the checks only apply when testing a valid top-level script.
1054 [ + + ]: 4497 : if (!node->IsValidTopLevel()) return;
1055 : :
1056 : : // Check roundtrip to script
1057 [ + - ]: 4096 : auto decoded = miniscript::FromScript(script, parser_ctx);
1058 [ - + ]: 4096 : assert(decoded);
1059 : : // Note we can't use *decoded == *node because the miniscript representation may differ, so we check that:
1060 : : // - The script corresponding to that decoded form matches exactly
1061 : : // - The type matches exactly
1062 [ + - - + ]: 4096 : assert(decoded->ToScript(parser_ctx) == script);
1063 [ - + ]: 4096 : assert(decoded->GetType() == node->GetType());
1064 : :
1065 : : // Optionally pad the script or the witness in order to increase the sensitivity of the tests of
1066 : : // the resources limits logic.
1067 : 4096 : CScriptWitness witness_mal, witness_nonmal;
1068 [ + + ]: 4096 : if (provider.ConsumeBool()) {
1069 : : // Under P2WSH, optionally pad the script with OP_NOPs to max op the ops limit of the constructed script.
1070 : : // This makes the script obviously not actually miniscript-compatible anymore, but the
1071 : : // signatures constructed in this test don't commit to the script anyway, so the same
1072 : : // miniscript satisfier will work. This increases the sensitivity of the test to the ops
1073 : : // counting logic being too low, especially for simple scripts.
1074 : : // Do this optionally because we're not solely interested in cases where the number of ops is
1075 : : // maximal.
1076 : : // Do not pad more than what would cause MAX_STANDARD_P2WSH_SCRIPT_SIZE to be reached, however,
1077 : : // as that also invalidates scripts.
1078 : 641 : const auto node_ops{node->GetOps()};
1079 [ + + + + ]: 981 : if (!IsTapscript(script_ctx) && node_ops && *node_ops < MAX_OPS_PER_SCRIPT
1080 [ + + + + ]: 918 : && node->ScriptSize() < MAX_STANDARD_P2WSH_SCRIPT_SIZE) {
1081 [ + + ]: 275 : int add = std::min<int>(
1082 [ + + ]: 275 : MAX_OPS_PER_SCRIPT - *node_ops,
1083 [ + + ]: 275 : MAX_STANDARD_P2WSH_SCRIPT_SIZE - node->ScriptSize());
1084 [ + + ]: 28135 : for (int i = 0; i < add; ++i) script.push_back(OP_NOP);
1085 : : }
1086 : :
1087 : : // Under Tapscript, optionally pad the stack up to the limit minus the calculated maximum execution stack
1088 : : // size to assert a Miniscript would never add more elements to the stack during execution than anticipated.
1089 : 641 : const auto node_exec_ss{node->GetExecStackSize()};
1090 [ + + + + : 641 : if (miniscript::IsTapscript(script_ctx) && node_exec_ss && *node_exec_ss < MAX_STACK_SIZE) {
+ - ]
1091 [ + - ]: 270 : unsigned add{(unsigned)MAX_STACK_SIZE - *node_exec_ss};
1092 [ + - ]: 270 : witness_mal.stack.resize(add);
1093 [ + - ]: 270 : witness_nonmal.stack.resize(add);
1094 : 270 : script.reserve(add);
1095 [ + + ]: 259920 : for (unsigned i = 0; i < add; ++i) script.push_back(OP_NIP);
1096 : : }
1097 : : }
1098 : :
1099 : 4096 : const SatisfierContext satisfier_ctx{script_ctx};
1100 : :
1101 : : // Get the ScriptPubKey for this script, filling spend data if it's Taproot.
1102 [ + - ]: 4096 : TaprootBuilder builder;
1103 [ + - ]: 4096 : const CScript script_pubkey{ScriptPubKey(script_ctx, script, builder)};
1104 : :
1105 : : // Run malleable satisfaction algorithm.
1106 : 4096 : std::vector<std::vector<unsigned char>> stack_mal;
1107 [ + - ]: 4096 : const bool mal_success = node->Satisfy(satisfier_ctx, stack_mal, false) == miniscript::Availability::YES;
1108 : :
1109 : : // Run non-malleable satisfaction algorithm.
1110 : 4096 : std::vector<std::vector<unsigned char>> stack_nonmal;
1111 [ + - ]: 4096 : const bool nonmal_success = node->Satisfy(satisfier_ctx, stack_nonmal, true) == miniscript::Availability::YES;
1112 : :
1113 [ + + ]: 4096 : if (nonmal_success) {
1114 : : // Non-malleable satisfactions are bounded by the satisfaction size plus:
1115 : : // - For P2WSH spends, the witness script
1116 : : // - For Tapscript spends, both the witness script and the control block
1117 : 1116 : const size_t max_stack_size{*node->GetStackSize() + 1 + miniscript::IsTapscript(script_ctx)};
1118 [ - + ]: 1116 : assert(stack_nonmal.size() <= max_stack_size);
1119 : : // If a non-malleable satisfaction exists, the malleable one must also exist, and be identical to it.
1120 [ - + ]: 1116 : assert(mal_success);
1121 [ - + ]: 1116 : assert(stack_nonmal == stack_mal);
1122 : : // Compute witness size (excluding script push, control block, and witness count encoding).
1123 [ - + ]: 1116 : const size_t wit_size = GetSerializeSize(stack_nonmal) - GetSizeOfCompactSize(stack_nonmal.size());
1124 [ - + ]: 1116 : assert(wit_size <= *node->GetWitnessSize());
1125 : :
1126 : : // Test non-malleable satisfaction.
1127 [ + - ]: 1116 : witness_nonmal.stack.insert(witness_nonmal.stack.end(), std::make_move_iterator(stack_nonmal.begin()), std::make_move_iterator(stack_nonmal.end()));
1128 [ + - ]: 1116 : SatisfactionToWitness(script_ctx, witness_nonmal, script, builder);
1129 : 1116 : ScriptError serror;
1130 [ + - ]: 1116 : bool res = VerifyScript(DUMMY_SCRIPTSIG, script_pubkey, &witness_nonmal, STANDARD_SCRIPT_VERIFY_FLAGS, CHECKER_CTX, &serror);
1131 : : // Non-malleable satisfactions are guaranteed to be valid if ValidSatisfactions().
1132 [ + + - + ]: 1116 : if (node->ValidSatisfactions()) assert(res);
1133 : : // More detailed: non-malleable satisfactions must be valid, or could fail with ops count error (if CheckOpsLimit failed),
1134 : : // or with a stack size error (if CheckStackSize check failed).
1135 [ + + + - : 87 : assert(res ||
- + - - -
- ]
1136 : : (!node->CheckOpsLimit() && serror == ScriptError::SCRIPT_ERR_OP_COUNT) ||
1137 : : (!node->CheckStackSize() && serror == ScriptError::SCRIPT_ERR_STACK_SIZE));
1138 : : }
1139 : :
1140 [ + + + + : 4096 : if (mal_success && (!nonmal_success || witness_mal.stack != witness_nonmal.stack)) {
+ - ]
1141 : : // Test malleable satisfaction only if it's different from the non-malleable one.
1142 [ + - ]: 2558 : witness_mal.stack.insert(witness_mal.stack.end(), std::make_move_iterator(stack_mal.begin()), std::make_move_iterator(stack_mal.end()));
1143 [ + - ]: 2558 : SatisfactionToWitness(script_ctx, witness_mal, script, builder);
1144 : 2558 : ScriptError serror;
1145 [ + - ]: 2558 : bool res = VerifyScript(DUMMY_SCRIPTSIG, script_pubkey, &witness_mal, STANDARD_SCRIPT_VERIFY_FLAGS, CHECKER_CTX, &serror);
1146 : : // Malleable satisfactions are not guaranteed to be valid under any conditions, but they can only
1147 : : // fail due to stack or ops limits.
1148 [ + + + + : 2558 : assert(res || serror == ScriptError::SCRIPT_ERR_OP_COUNT || serror == ScriptError::SCRIPT_ERR_STACK_SIZE);
- + ]
1149 : : }
1150 : :
1151 [ + + ]: 4096 : if (node->IsSane()) {
1152 : : // For sane nodes, the two algorithms behave identically.
1153 [ - + ]: 514 : assert(mal_success == nonmal_success);
1154 : : }
1155 : :
1156 : : // Verify that if a node is policy-satisfiable, the malleable satisfaction
1157 : : // algorithm succeeds. Given that under IsSane() both satisfactions
1158 : : // are identical, this implies that for such nodes, the non-malleable
1159 : : // satisfaction will also match the expected policy.
1160 : 83914 : const auto is_key_satisfiable = [script_ctx](const CPubKey& pubkey) -> bool {
1161 : 79818 : auto sig_ptr{TEST_DATA.GetSig(script_ctx, pubkey)};
1162 [ + - + + ]: 79818 : return sig_ptr != nullptr && sig_ptr->second;
1163 : 4096 : };
1164 [ + - ]: 4096 : bool satisfiable = node->IsSatisfiable([&](const Node& node) -> bool {
1165 [ + + + + : 51801 : switch (node.fragment) {
+ + + - ]
1166 : 20930 : case Fragment::PK_K:
1167 : 20930 : case Fragment::PK_H:
1168 : 20930 : return is_key_satisfiable(node.keys[0]);
1169 : 9626 : case Fragment::MULTI:
1170 : 9626 : case Fragment::MULTI_A: {
1171 : 9626 : size_t sats = std::count_if(node.keys.begin(), node.keys.end(), [&](const auto& key) {
1172 : 58888 : return size_t(is_key_satisfiable(key));
1173 : 9626 : });
1174 : 9626 : return sats >= node.k;
1175 : : }
1176 : 8438 : case Fragment::OLDER:
1177 : 8438 : case Fragment::AFTER:
1178 : 8438 : return node.k & 1;
1179 : 2919 : case Fragment::SHA256:
1180 : 2919 : return TEST_DATA.sha256_preimages.count(node.data);
1181 : 3686 : case Fragment::HASH256:
1182 : 3686 : return TEST_DATA.hash256_preimages.count(node.data);
1183 : 2951 : case Fragment::RIPEMD160:
1184 : 2951 : return TEST_DATA.ripemd160_preimages.count(node.data);
1185 : 3251 : case Fragment::HASH160:
1186 : 3251 : return TEST_DATA.hash160_preimages.count(node.data);
1187 : 0 : default:
1188 : 0 : assert(false);
1189 : : }
1190 : : return false;
1191 : : });
1192 [ - + ]: 4096 : assert(mal_success == satisfiable);
1193 : 4497 : }
1194 : :
1195 : : } // namespace
1196 : :
1197 : 3 : void FuzzInit()
1198 : : {
1199 [ + - + - : 3 : static ECC_Context ecc_context{};
+ - ]
1200 : 3 : TEST_DATA.Init();
1201 : 3 : }
1202 : :
1203 : 1 : void FuzzInitSmart()
1204 : : {
1205 : 1 : FuzzInit();
1206 : 1 : SMARTINFO.Init();
1207 : 1 : }
1208 : :
1209 : : /** Fuzz target that runs TestNode on nodes generated using ConsumeNodeStable. */
1210 [ + - ]: 2466 : FUZZ_TARGET(miniscript_stable, .init = FuzzInit)
1211 : : {
1212 : : // Run it under both P2WSH and Tapscript contexts.
1213 [ + + ]: 6060 : for (const auto script_ctx: {MsCtx::P2WSH, MsCtx::TAPSCRIPT}) {
1214 : 4040 : FuzzedDataProvider provider(buffer.data(), buffer.size());
1215 [ + - ]: 181342 : TestNode(script_ctx, GenNode(script_ctx, [&](Type needed_type) {
1216 [ + - ]: 177302 : return ConsumeNodeStable(script_ctx, provider, needed_type);
1217 : : }, ""_mst), provider);
1218 : : }
1219 : 2020 : }
1220 : :
1221 : : /** Fuzz target that runs TestNode on nodes generated using ConsumeNodeSmart. */
1222 [ + - ]: 2509 : FUZZ_TARGET(miniscript_smart, .init = FuzzInitSmart)
1223 : : {
1224 : : /** The set of types we aim to construct nodes for. Together they cover all. */
1225 : 2063 : static constexpr std::array<Type, 4> BASE_TYPES{"B"_mst, "V"_mst, "K"_mst, "W"_mst};
1226 : :
1227 : 2063 : FuzzedDataProvider provider(buffer.data(), buffer.size());
1228 : 2063 : const auto script_ctx{(MsCtx)provider.ConsumeBool()};
1229 [ + - ]: 165233 : TestNode(script_ctx, GenNode(script_ctx, [&](Type needed_type) {
1230 [ + - ]: 163170 : return ConsumeNodeSmart(script_ctx, provider, needed_type);
1231 : 2063 : }, PickValue(provider, BASE_TYPES), true), provider);
1232 : 2063 : }
1233 : :
1234 : : /* Fuzz tests that test parsing from a string, and roundtripping via string. */
1235 [ + - ]: 1495 : FUZZ_TARGET(miniscript_string, .init = FuzzInit)
1236 : : {
1237 [ + - ]: 1049 : if (buffer.empty()) return;
1238 : 1049 : FuzzedDataProvider provider(buffer.data(), buffer.size());
1239 : 1049 : auto str = provider.ConsumeBytesAsString(provider.remaining_bytes() - 1);
1240 : 1049 : const ParserContext parser_ctx{(MsCtx)provider.ConsumeBool()};
1241 [ + - ]: 1049 : auto parsed = miniscript::FromString(str, parser_ctx);
1242 [ + + ]: 1049 : if (!parsed) return;
1243 : :
1244 [ + - ]: 588 : const auto str2 = parsed->ToString(parser_ctx);
1245 [ - + ]: 588 : assert(str2);
1246 [ + - ]: 588 : auto parsed2 = miniscript::FromString(*str2, parser_ctx);
1247 [ - + ]: 588 : assert(parsed2);
1248 [ + - - + ]: 588 : assert(*parsed == *parsed2);
1249 : 1049 : }
1250 : :
1251 : : /* Fuzz tests that test parsing from a script, and roundtripping via script. */
1252 [ + - ]: 1417 : FUZZ_TARGET(miniscript_script)
1253 : : {
1254 : 971 : FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
1255 : 971 : const std::optional<CScript> script = ConsumeDeserializable<CScript>(fuzzed_data_provider);
1256 [ + + ]: 971 : if (!script) return;
1257 : :
1258 : 956 : const ScriptParserContext script_parser_ctx{(MsCtx)fuzzed_data_provider.ConsumeBool()};
1259 [ + - ]: 956 : const auto ms = miniscript::FromScript(*script, script_parser_ctx);
1260 [ + + ]: 956 : if (!ms) return;
1261 : :
1262 [ + - - + ]: 311 : assert(ms->ToScript(script_parser_ctx) == *script);
1263 : 1616 : }
|