Bitcoin Core  27.99.0
P2P Digital Currency
miniscript.cpp
Go to the documentation of this file.
1 // Copyright (c) 2021-2022 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>
12 #include <test/fuzz/fuzz.h>
13 #include <test/fuzz/util.h>
14 #include <util/strencodings.h>
15 
16 namespace {
17 
20 using Node = miniscript::Node<CPubKey>;
21 using Type = miniscript::Type;
22 using MsCtx = miniscript::MiniscriptContext;
23 using miniscript::operator"" _mst;
24 
26 struct TestData {
27  typedef CPubKey Key;
28 
29  // Precomputed public keys, and a dummy signature for each of them.
30  std::vector<Key> dummy_keys;
31  std::map<Key, int> dummy_key_idx_map;
32  std::map<CKeyID, Key> dummy_keys_map;
33  std::map<Key, std::pair<std::vector<unsigned char>, bool>> dummy_sigs;
34  std::map<XOnlyPubKey, std::pair<std::vector<unsigned char>, bool>> schnorr_sigs;
35 
36  // Precomputed hashes of each kind.
37  std::vector<std::vector<unsigned char>> sha256;
38  std::vector<std::vector<unsigned char>> ripemd160;
39  std::vector<std::vector<unsigned char>> hash256;
40  std::vector<std::vector<unsigned char>> hash160;
41  std::map<std::vector<unsigned char>, std::vector<unsigned char>> sha256_preimages;
42  std::map<std::vector<unsigned char>, std::vector<unsigned char>> ripemd160_preimages;
43  std::map<std::vector<unsigned char>, std::vector<unsigned char>> hash256_preimages;
44  std::map<std::vector<unsigned char>, std::vector<unsigned char>> hash160_preimages;
45 
47  void Init() {
48  unsigned char keydata[32] = {1};
49  // All our signatures sign (and are required to sign) this constant message.
50  auto const MESSAGE_HASH{uint256S("f5cd94e18b6fe77dd7aca9e35c2b0c9cbd86356c80a71065")};
51  // We don't pass additional randomness when creating a schnorr signature.
52  auto const EMPTY_AUX{uint256S("")};
53 
54  for (size_t i = 0; i < 256; i++) {
55  keydata[31] = i;
56  CKey privkey;
57  privkey.Set(keydata, keydata + 32, true);
58  const Key pubkey = privkey.GetPubKey();
59 
60  dummy_keys.push_back(pubkey);
61  dummy_key_idx_map.emplace(pubkey, i);
62  dummy_keys_map.insert({pubkey.GetID(), pubkey});
63  XOnlyPubKey xonly_pubkey{pubkey};
64  dummy_key_idx_map.emplace(xonly_pubkey, i);
65  uint160 xonly_hash{Hash160(xonly_pubkey)};
66  dummy_keys_map.emplace(xonly_hash, pubkey);
67 
68  std::vector<unsigned char> sig, schnorr_sig(64);
69  privkey.Sign(MESSAGE_HASH, sig);
70  sig.push_back(1); // SIGHASH_ALL
71  dummy_sigs.insert({pubkey, {sig, i & 1}});
72  assert(privkey.SignSchnorr(MESSAGE_HASH, schnorr_sig, nullptr, EMPTY_AUX));
73  schnorr_sig.push_back(1); // Maximally-sized signature has sighash byte
74  schnorr_sigs.emplace(XOnlyPubKey{pubkey}, std::make_pair(std::move(schnorr_sig), i & 1));
75 
76  std::vector<unsigned char> hash;
77  hash.resize(32);
78  CSHA256().Write(keydata, 32).Finalize(hash.data());
79  sha256.push_back(hash);
80  if (i & 1) sha256_preimages[hash] = std::vector<unsigned char>(keydata, keydata + 32);
81  CHash256().Write(keydata).Finalize(hash);
82  hash256.push_back(hash);
83  if (i & 1) hash256_preimages[hash] = std::vector<unsigned char>(keydata, keydata + 32);
84  hash.resize(20);
85  CRIPEMD160().Write(keydata, 32).Finalize(hash.data());
86  assert(hash.size() == 20);
87  ripemd160.push_back(hash);
88  if (i & 1) ripemd160_preimages[hash] = std::vector<unsigned char>(keydata, keydata + 32);
89  CHash160().Write(keydata).Finalize(hash);
90  hash160.push_back(hash);
91  if (i & 1) hash160_preimages[hash] = std::vector<unsigned char>(keydata, keydata + 32);
92  }
93  }
94 
96  const std::pair<std::vector<unsigned char>, bool>* GetSig(const MsCtx script_ctx, const Key& key) const {
97  if (!miniscript::IsTapscript(script_ctx)) {
98  const auto it = dummy_sigs.find(key);
99  if (it == dummy_sigs.end()) return nullptr;
100  return &it->second;
101  } else {
102  const auto it = schnorr_sigs.find(XOnlyPubKey{key});
103  if (it == schnorr_sigs.end()) return nullptr;
104  return &it->second;
105  }
106  }
107 } TEST_DATA;
108 
114 struct ParserContext {
115  typedef CPubKey Key;
116 
117  const MsCtx script_ctx;
118 
119  constexpr ParserContext(MsCtx ctx) noexcept : script_ctx(ctx) {}
120 
121  bool KeyCompare(const Key& a, const Key& b) const {
122  return a < b;
123  }
124 
125  std::optional<std::string> ToString(const Key& key) const
126  {
127  auto it = TEST_DATA.dummy_key_idx_map.find(key);
128  if (it == TEST_DATA.dummy_key_idx_map.end()) return {};
129  uint8_t idx = it->second;
130  return HexStr(Span{&idx, 1});
131  }
132 
133  std::vector<unsigned char> ToPKBytes(const Key& key) const {
134  if (!miniscript::IsTapscript(script_ctx)) {
135  return {key.begin(), key.end()};
136  }
137  const XOnlyPubKey xonly_pubkey{key};
138  return {xonly_pubkey.begin(), xonly_pubkey.end()};
139  }
140 
141  std::vector<unsigned char> ToPKHBytes(const Key& key) const {
142  if (!miniscript::IsTapscript(script_ctx)) {
143  const auto h = Hash160(key);
144  return {h.begin(), h.end()};
145  }
146  const auto h = Hash160(XOnlyPubKey{key});
147  return {h.begin(), h.end()};
148  }
149 
150  template<typename I>
151  std::optional<Key> FromString(I first, I last) const {
152  if (last - first != 2) return {};
153  auto idx = ParseHex(std::string(first, last));
154  if (idx.size() != 1) return {};
155  return TEST_DATA.dummy_keys[idx[0]];
156  }
157 
158  template<typename I>
159  std::optional<Key> FromPKBytes(I first, I last) const {
160  if (!miniscript::IsTapscript(script_ctx)) {
161  Key key{first, last};
162  if (key.IsValid()) return key;
163  return {};
164  }
165  if (last - first != 32) return {};
166  XOnlyPubKey xonly_pubkey;
167  std::copy(first, last, xonly_pubkey.begin());
168  return xonly_pubkey.GetEvenCorrespondingCPubKey();
169  }
170 
171  template<typename I>
172  std::optional<Key> FromPKHBytes(I first, I last) const {
173  assert(last - first == 20);
174  CKeyID keyid;
175  std::copy(first, last, keyid.begin());
176  const auto it = TEST_DATA.dummy_keys_map.find(keyid);
177  if (it == TEST_DATA.dummy_keys_map.end()) return {};
178  return it->second;
179  }
180 
181  MsCtx MsContext() const {
182  return script_ctx;
183  }
184 };
185 
187 struct ScriptParserContext {
188  const MsCtx script_ctx;
189 
190  constexpr ScriptParserContext(MsCtx ctx) noexcept : script_ctx(ctx) {}
191 
193  struct Key {
194  bool is_hash;
195  std::vector<unsigned char> data;
196  };
197 
198  bool KeyCompare(const Key& a, const Key& b) const {
199  return a.data < b.data;
200  }
201 
202  const std::vector<unsigned char>& ToPKBytes(const Key& key) const
203  {
204  assert(!key.is_hash);
205  return key.data;
206  }
207 
208  std::vector<unsigned char> ToPKHBytes(const Key& key) const
209  {
210  if (key.is_hash) return key.data;
211  const auto h = Hash160(key.data);
212  return {h.begin(), h.end()};
213  }
214 
215  template<typename I>
216  std::optional<Key> FromPKBytes(I first, I last) const
217  {
218  Key key;
219  key.data.assign(first, last);
220  key.is_hash = false;
221  return key;
222  }
223 
224  template<typename I>
225  std::optional<Key> FromPKHBytes(I first, I last) const
226  {
227  Key key;
228  key.data.assign(first, last);
229  key.is_hash = true;
230  return key;
231  }
232 
233  MsCtx MsContext() const {
234  return script_ctx;
235  }
236 };
237 
239 struct SatisfierContext : ParserContext {
240 
241  constexpr SatisfierContext(MsCtx ctx) noexcept : ParserContext(ctx) {}
242 
243  // Timelock challenges satisfaction. Make the value (deterministically) vary to explore different
244  // paths.
245  bool CheckAfter(uint32_t value) const { return value % 2; }
246  bool CheckOlder(uint32_t value) const { return value % 2; }
247 
248  // Signature challenges fulfilled with a dummy signature, if it was one of our dummy keys.
249  miniscript::Availability Sign(const CPubKey& key, std::vector<unsigned char>& sig) const {
250  bool sig_available{false};
251  if (auto res = TEST_DATA.GetSig(script_ctx, key)) {
252  std::tie(sig, sig_available) = *res;
253  }
255  }
256 
258  miniscript::Availability LookupHash(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage,
259  const std::map<std::vector<unsigned char>, std::vector<unsigned char>>& map) const
260  {
261  const auto it = map.find(hash);
262  if (it == map.end()) return miniscript::Availability::NO;
263  preimage = it->second;
265  }
266  miniscript::Availability SatSHA256(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
267  return LookupHash(hash, preimage, TEST_DATA.sha256_preimages);
268  }
269  miniscript::Availability SatRIPEMD160(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
270  return LookupHash(hash, preimage, TEST_DATA.ripemd160_preimages);
271  }
272  miniscript::Availability SatHASH256(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
273  return LookupHash(hash, preimage, TEST_DATA.hash256_preimages);
274  }
275  miniscript::Availability SatHASH160(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
276  return LookupHash(hash, preimage, TEST_DATA.hash160_preimages);
277  }
278 };
279 
281 const struct CheckerContext: BaseSignatureChecker {
282  // Signature checker methods. Checks the right dummy signature is used.
283  bool CheckECDSASignature(const std::vector<unsigned char>& sig, const std::vector<unsigned char>& vchPubKey,
284  const CScript& scriptCode, SigVersion sigversion) const override
285  {
286  const CPubKey key{vchPubKey};
287  const auto it = TEST_DATA.dummy_sigs.find(key);
288  if (it == TEST_DATA.dummy_sigs.end()) return false;
289  return it->second.first == sig;
290  }
292  ScriptExecutionData&, ScriptError*) const override {
293  XOnlyPubKey pk{pubkey};
294  auto it = TEST_DATA.schnorr_sigs.find(pk);
295  if (it == TEST_DATA.schnorr_sigs.end()) return false;
296  return it->second.first == sig;
297  }
298  bool CheckLockTime(const CScriptNum& nLockTime) const override { return nLockTime.GetInt64() & 1; }
299  bool CheckSequence(const CScriptNum& nSequence) const override { return nSequence.GetInt64() & 1; }
300 } CHECKER_CTX;
301 
303 const struct KeyComparator {
304  bool KeyCompare(const CPubKey& a, const CPubKey& b) const {
305  return a < b;
306  }
307 } KEY_COMP;
308 
309 // A dummy scriptsig to pass to VerifyScript (we always use Segwit v0).
310 const CScript DUMMY_SCRIPTSIG;
311 
313 const std::vector<unsigned char> NUMS_PK{ParseHex("50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0")};
314 
316 template<typename... Args> NodeRef MakeNodeRef(Args&&... args) {
317  return miniscript::MakeNodeRef<CPubKey>(miniscript::internal::NoDupCheck{}, std::forward<Args>(args)...);
318 }
319 
321 struct NodeInfo {
323  Fragment fragment;
325  uint32_t k;
327  std::vector<CPubKey> keys;
329  std::vector<unsigned char> hash;
331  std::vector<Type> subtypes;
332 
333  NodeInfo(Fragment frag): fragment(frag), k(0) {}
334  NodeInfo(Fragment frag, CPubKey key): fragment(frag), k(0), keys({key}) {}
335  NodeInfo(Fragment frag, uint32_t _k): fragment(frag), k(_k) {}
336  NodeInfo(Fragment frag, std::vector<unsigned char> h): fragment(frag), k(0), hash(std::move(h)) {}
337  NodeInfo(std::vector<Type> subt, Fragment frag): fragment(frag), k(0), subtypes(std::move(subt)) {}
338  NodeInfo(std::vector<Type> subt, Fragment frag, uint32_t _k): fragment(frag), k(_k), subtypes(std::move(subt)) {}
339  NodeInfo(Fragment frag, uint32_t _k, std::vector<CPubKey> _keys): fragment(frag), k(_k), keys(std::move(_keys)) {}
340 };
341 
343 template<typename T, typename A>
344 T ConsumeIndex(FuzzedDataProvider& provider, A& col) {
345  const uint8_t i = provider.ConsumeIntegral<uint8_t>();
346  return col[i];
347 }
348 
349 CPubKey ConsumePubKey(FuzzedDataProvider& provider) {
350  return ConsumeIndex<CPubKey>(provider, TEST_DATA.dummy_keys);
351 }
352 
353 std::vector<unsigned char> ConsumeSha256(FuzzedDataProvider& provider) {
354  return ConsumeIndex<std::vector<unsigned char>>(provider, TEST_DATA.sha256);
355 }
356 
357 std::vector<unsigned char> ConsumeHash256(FuzzedDataProvider& provider) {
358  return ConsumeIndex<std::vector<unsigned char>>(provider, TEST_DATA.hash256);
359 }
360 
361 std::vector<unsigned char> ConsumeRipemd160(FuzzedDataProvider& provider) {
362  return ConsumeIndex<std::vector<unsigned char>>(provider, TEST_DATA.ripemd160);
363 }
364 
365 std::vector<unsigned char> ConsumeHash160(FuzzedDataProvider& provider) {
366  return ConsumeIndex<std::vector<unsigned char>>(provider, TEST_DATA.hash160);
367 }
368 
369 std::optional<uint32_t> ConsumeTimeLock(FuzzedDataProvider& provider) {
370  const uint32_t k = provider.ConsumeIntegral<uint32_t>();
371  if (k == 0 || k >= 0x80000000) return {};
372  return k;
373 }
374 
389 std::optional<NodeInfo> ConsumeNodeStable(MsCtx script_ctx, FuzzedDataProvider& provider, Type type_needed) {
390  bool allow_B = (type_needed == ""_mst) || (type_needed << "B"_mst);
391  bool allow_K = (type_needed == ""_mst) || (type_needed << "K"_mst);
392  bool allow_V = (type_needed == ""_mst) || (type_needed << "V"_mst);
393  bool allow_W = (type_needed == ""_mst) || (type_needed << "W"_mst);
394  static constexpr auto B{"B"_mst}, K{"K"_mst}, V{"V"_mst}, W{"W"_mst};
395 
396  switch (provider.ConsumeIntegral<uint8_t>()) {
397  case 0:
398  if (!allow_B) return {};
399  return {{Fragment::JUST_0}};
400  case 1:
401  if (!allow_B) return {};
402  return {{Fragment::JUST_1}};
403  case 2:
404  if (!allow_K) return {};
405  return {{Fragment::PK_K, ConsumePubKey(provider)}};
406  case 3:
407  if (!allow_K) return {};
408  return {{Fragment::PK_H, ConsumePubKey(provider)}};
409  case 4: {
410  if (!allow_B) return {};
411  const auto k = ConsumeTimeLock(provider);
412  if (!k) return {};
413  return {{Fragment::OLDER, *k}};
414  }
415  case 5: {
416  if (!allow_B) return {};
417  const auto k = ConsumeTimeLock(provider);
418  if (!k) return {};
419  return {{Fragment::AFTER, *k}};
420  }
421  case 6:
422  if (!allow_B) return {};
423  return {{Fragment::SHA256, ConsumeSha256(provider)}};
424  case 7:
425  if (!allow_B) return {};
426  return {{Fragment::HASH256, ConsumeHash256(provider)}};
427  case 8:
428  if (!allow_B) return {};
429  return {{Fragment::RIPEMD160, ConsumeRipemd160(provider)}};
430  case 9:
431  if (!allow_B) return {};
432  return {{Fragment::HASH160, ConsumeHash160(provider)}};
433  case 10: {
434  if (!allow_B || IsTapscript(script_ctx)) return {};
435  const auto k = provider.ConsumeIntegral<uint8_t>();
436  const auto n_keys = provider.ConsumeIntegral<uint8_t>();
437  if (n_keys > 20 || k == 0 || k > n_keys) return {};
438  std::vector<CPubKey> keys{n_keys};
439  for (auto& key: keys) key = ConsumePubKey(provider);
440  return {{Fragment::MULTI, k, std::move(keys)}};
441  }
442  case 11:
443  if (!(allow_B || allow_K || allow_V)) return {};
444  return {{{B, type_needed, type_needed}, Fragment::ANDOR}};
445  case 12:
446  if (!(allow_B || allow_K || allow_V)) return {};
447  return {{{V, type_needed}, Fragment::AND_V}};
448  case 13:
449  if (!allow_B) return {};
450  return {{{B, W}, Fragment::AND_B}};
451  case 15:
452  if (!allow_B) return {};
453  return {{{B, W}, Fragment::OR_B}};
454  case 16:
455  if (!allow_V) return {};
456  return {{{B, V}, Fragment::OR_C}};
457  case 17:
458  if (!allow_B) return {};
459  return {{{B, B}, Fragment::OR_D}};
460  case 18:
461  if (!(allow_B || allow_K || allow_V)) return {};
462  return {{{type_needed, type_needed}, Fragment::OR_I}};
463  case 19: {
464  if (!allow_B) return {};
465  auto k = provider.ConsumeIntegral<uint8_t>();
466  auto n_subs = provider.ConsumeIntegral<uint8_t>();
467  if (k == 0 || k > n_subs) return {};
468  std::vector<Type> subtypes;
469  subtypes.reserve(n_subs);
470  subtypes.emplace_back("B"_mst);
471  for (size_t i = 1; i < n_subs; ++i) subtypes.emplace_back("W"_mst);
472  return {{std::move(subtypes), Fragment::THRESH, k}};
473  }
474  case 20:
475  if (!allow_W) return {};
476  return {{{B}, Fragment::WRAP_A}};
477  case 21:
478  if (!allow_W) return {};
479  return {{{B}, Fragment::WRAP_S}};
480  case 22:
481  if (!allow_B) return {};
482  return {{{K}, Fragment::WRAP_C}};
483  case 23:
484  if (!allow_B) return {};
485  return {{{V}, Fragment::WRAP_D}};
486  case 24:
487  if (!allow_V) return {};
488  return {{{B}, Fragment::WRAP_V}};
489  case 25:
490  if (!allow_B) return {};
491  return {{{B}, Fragment::WRAP_J}};
492  case 26:
493  if (!allow_B) return {};
494  return {{{B}, Fragment::WRAP_N}};
495  case 27: {
496  if (!allow_B || !IsTapscript(script_ctx)) return {};
497  const auto k = provider.ConsumeIntegral<uint16_t>();
498  const auto n_keys = provider.ConsumeIntegral<uint16_t>();
499  if (n_keys > 999 || k == 0 || k > n_keys) return {};
500  std::vector<CPubKey> keys{n_keys};
501  for (auto& key: keys) key = ConsumePubKey(provider);
502  return {{Fragment::MULTI_A, k, std::move(keys)}};
503  }
504  default:
505  break;
506  }
507  return {};
508 }
509 
510 /* This structure contains a table which for each "target" Type a list of recipes
511  * to construct it, automatically inferred from the behavior of ComputeType.
512  * Note that the Types here are not the final types of the constructed Nodes, but
513  * just the subset that are required. For example, a recipe for the "Bo" type
514  * might construct a "Bondu" sha256() NodeInfo, but cannot construct a "Bz" older().
515  * Each recipe is a Fragment together with a list of required types for its subnodes.
516  */
517 struct SmartInfo
518 {
519  using recipe = std::pair<Fragment, std::vector<Type>>;
520  std::map<Type, std::vector<recipe>> wsh_table, tap_table;
521 
522  void Init()
523  {
524  Init(wsh_table, MsCtx::P2WSH);
525  Init(tap_table, MsCtx::TAPSCRIPT);
526  }
527 
528  void Init(std::map<Type, std::vector<recipe>>& table, MsCtx script_ctx)
529  {
530  /* Construct a set of interesting type requirements to reason with (sections of BKVWzondu). */
531  std::vector<Type> types;
532  static constexpr auto B_mst{"B"_mst}, K_mst{"K"_mst}, V_mst{"V"_mst}, W_mst{"W"_mst};
533  static constexpr auto d_mst{"d"_mst}, n_mst{"n"_mst}, o_mst{"o"_mst}, u_mst{"u"_mst}, z_mst{"z"_mst};
534  static constexpr auto NONE_mst{""_mst};
535  for (int base = 0; base < 4; ++base) { /* select from B,K,V,W */
536  Type type_base = base == 0 ? B_mst : base == 1 ? K_mst : base == 2 ? V_mst : W_mst;
537  for (int zo = 0; zo < 3; ++zo) { /* select from z,o,(none) */
538  Type type_zo = zo == 0 ? z_mst : zo == 1 ? o_mst : NONE_mst;
539  for (int n = 0; n < 2; ++n) { /* select from (none),n */
540  if (zo == 0 && n == 1) continue; /* z conflicts with n */
541  if (base == 3 && n == 1) continue; /* W conflicts with n */
542  Type type_n = n == 0 ? NONE_mst : n_mst;
543  for (int d = 0; d < 2; ++d) { /* select from (none),d */
544  if (base == 2 && d == 1) continue; /* V conflicts with d */
545  Type type_d = d == 0 ? NONE_mst : d_mst;
546  for (int u = 0; u < 2; ++u) { /* select from (none),u */
547  if (base == 2 && u == 1) continue; /* V conflicts with u */
548  Type type_u = u == 0 ? NONE_mst : u_mst;
549  Type type = type_base | type_zo | type_n | type_d | type_u;
550  types.push_back(type);
551  }
552  }
553  }
554  }
555  }
556 
557  /* We define a recipe a to be a super-recipe of recipe b if they use the same
558  * fragment, the same number of subexpressions, and each of a's subexpression
559  * types is a supertype of the corresponding subexpression type of b.
560  * Within the set of recipes for the construction of a given type requirement,
561  * no recipe should be a super-recipe of another (as the super-recipe is
562  * applicable in every place the sub-recipe is, the sub-recipe is redundant). */
563  auto is_super_of = [](const recipe& a, const recipe& b) {
564  if (a.first != b.first) return false;
565  if (a.second.size() != b.second.size()) return false;
566  for (size_t i = 0; i < a.second.size(); ++i) {
567  if (!(b.second[i] << a.second[i])) return false;
568  }
569  return true;
570  };
571 
572  /* Sort the type requirements. Subtypes will always sort later (e.g. Bondu will
573  * sort after Bo or Bu). As we'll be constructing recipes using these types, in
574  * order, in what follows, we'll construct super-recipes before sub-recipes.
575  * That means we never need to go back and delete a sub-recipe because a
576  * super-recipe got added. */
577  std::sort(types.begin(), types.end());
578 
579  // Iterate over all possible fragments.
580  for (int fragidx = 0; fragidx <= int(Fragment::MULTI_A); ++fragidx) {
581  int sub_count = 0;
582  int sub_range = 1;
583  size_t data_size = 0;
584  size_t n_keys = 0;
585  uint32_t k = 0;
586  Fragment frag{fragidx};
587 
588  // Only produce recipes valid in the given context.
589  if ((!miniscript::IsTapscript(script_ctx) && frag == Fragment::MULTI_A)
590  || (miniscript::IsTapscript(script_ctx) && frag == Fragment::MULTI)) {
591  continue;
592  }
593 
594  // Based on the fragment, determine #subs/data/k/keys to pass to ComputeType. */
595  switch (frag) {
596  case Fragment::PK_K:
597  case Fragment::PK_H:
598  n_keys = 1;
599  break;
600  case Fragment::MULTI:
601  case Fragment::MULTI_A:
602  n_keys = 1;
603  k = 1;
604  break;
605  case Fragment::OLDER:
606  case Fragment::AFTER:
607  k = 1;
608  break;
609  case Fragment::SHA256:
610  case Fragment::HASH256:
611  data_size = 32;
612  break;
613  case Fragment::RIPEMD160:
614  case Fragment::HASH160:
615  data_size = 20;
616  break;
617  case Fragment::JUST_0:
618  case Fragment::JUST_1:
619  break;
620  case Fragment::WRAP_A:
621  case Fragment::WRAP_S:
622  case Fragment::WRAP_C:
623  case Fragment::WRAP_D:
624  case Fragment::WRAP_V:
625  case Fragment::WRAP_J:
626  case Fragment::WRAP_N:
627  sub_count = 1;
628  break;
629  case Fragment::AND_V:
630  case Fragment::AND_B:
631  case Fragment::OR_B:
632  case Fragment::OR_C:
633  case Fragment::OR_D:
634  case Fragment::OR_I:
635  sub_count = 2;
636  break;
637  case Fragment::ANDOR:
638  sub_count = 3;
639  break;
640  case Fragment::THRESH:
641  // Thresh logic is executed for 1 and 2 arguments. Larger numbers use ad-hoc code to extend.
642  sub_count = 1;
643  sub_range = 2;
644  k = 1;
645  break;
646  }
647 
648  // Iterate over the number of subnodes (sub_count...sub_count+sub_range-1).
649  std::vector<Type> subt;
650  for (int subs = sub_count; subs < sub_count + sub_range; ++subs) {
651  // Iterate over the possible subnode types (at most 3).
652  for (Type x : types) {
653  for (Type y : types) {
654  for (Type z : types) {
655  // Compute the resulting type of a node with the selected fragment / subnode types.
656  subt.clear();
657  if (subs > 0) subt.push_back(x);
658  if (subs > 1) subt.push_back(y);
659  if (subs > 2) subt.push_back(z);
660  Type res = miniscript::internal::ComputeType(frag, x, y, z, subt, k, data_size, subs, n_keys, script_ctx);
661  // Continue if the result is not a valid node.
662  if ((res << "K"_mst) + (res << "V"_mst) + (res << "B"_mst) + (res << "W"_mst) != 1) continue;
663 
664  recipe entry{frag, subt};
665  auto super_of_entry = [&](const recipe& rec) { return is_super_of(rec, entry); };
666  // Iterate over all supertypes of res (because if e.g. our selected fragment/subnodes result
667  // in a Bondu, they can form a recipe that is also applicable for constructing a B, Bou, Bdu, ...).
668  for (Type s : types) {
669  if ((res & "BKVWzondu"_mst) << s) {
670  auto& recipes = table[s];
671  // If we don't already have a super-recipe to the new one, add it.
672  if (!std::any_of(recipes.begin(), recipes.end(), super_of_entry)) {
673  recipes.push_back(entry);
674  }
675  }
676  }
677 
678  if (subs <= 2) break;
679  }
680  if (subs <= 1) break;
681  }
682  if (subs <= 0) break;
683  }
684  }
685  }
686 
687  /* Find which types are useful. The fuzzer logic only cares about constructing
688  * B,V,K,W nodes, so any type that isn't needed in any recipe (directly or
689  * indirectly) for the construction of those is uninteresting. */
690  std::set<Type> useful_types{B_mst, V_mst, K_mst, W_mst};
691  // Find the transitive closure by adding types until the set of types does not change.
692  while (true) {
693  size_t set_size = useful_types.size();
694  for (const auto& [type, recipes] : table) {
695  if (useful_types.count(type) != 0) {
696  for (const auto& [_, subtypes] : recipes) {
697  for (auto subtype : subtypes) useful_types.insert(subtype);
698  }
699  }
700  }
701  if (useful_types.size() == set_size) break;
702  }
703  // Remove all rules that construct uninteresting types.
704  for (auto type_it = table.begin(); type_it != table.end();) {
705  if (useful_types.count(type_it->first) == 0) {
706  type_it = table.erase(type_it);
707  } else {
708  ++type_it;
709  }
710  }
711 
712  /* Find which types are constructible. A type is constructible if there is a leaf
713  * node recipe for constructing it, or a recipe whose subnodes are all constructible.
714  * Types can be non-constructible because they have no recipes to begin with,
715  * because they can only be constructed using recipes that involve otherwise
716  * non-constructible types, or because they require infinite recursion. */
717  std::set<Type> constructible_types{};
718  auto known_constructible = [&](Type type) { return constructible_types.count(type) != 0; };
719  // Find the transitive closure by adding types until the set of types does not change.
720  while (true) {
721  size_t set_size = constructible_types.size();
722  // Iterate over all types we have recipes for.
723  for (const auto& [type, recipes] : table) {
724  if (!known_constructible(type)) {
725  // For not (yet known to be) constructible types, iterate over their recipes.
726  for (const auto& [_, subt] : recipes) {
727  // If any recipe involves only (already known to be) constructible types,
728  // add the recipe's type to the set.
729  if (std::all_of(subt.begin(), subt.end(), known_constructible)) {
730  constructible_types.insert(type);
731  break;
732  }
733  }
734  }
735  }
736  if (constructible_types.size() == set_size) break;
737  }
738  for (auto type_it = table.begin(); type_it != table.end();) {
739  // Remove all recipes which involve non-constructible types.
740  type_it->second.erase(std::remove_if(type_it->second.begin(), type_it->second.end(),
741  [&](const recipe& rec) {
742  return !std::all_of(rec.second.begin(), rec.second.end(), known_constructible);
743  }), type_it->second.end());
744  // Delete types entirely which have no recipes left.
745  if (type_it->second.empty()) {
746  type_it = table.erase(type_it);
747  } else {
748  ++type_it;
749  }
750  }
751 
752  for (auto& [type, recipes] : table) {
753  // Sort recipes for determinism, and place those using fewer subnodes first.
754  // This avoids runaway expansion (when reaching the end of the fuzz input,
755  // all zeroes are read, resulting in the first available recipe being picked).
756  std::sort(recipes.begin(), recipes.end(),
757  [](const recipe& a, const recipe& b) {
758  if (a.second.size() < b.second.size()) return true;
759  if (a.second.size() > b.second.size()) return false;
760  return a < b;
761  }
762  );
763  }
764  }
765 } SMARTINFO;
766 
777 std::optional<NodeInfo> ConsumeNodeSmart(MsCtx script_ctx, FuzzedDataProvider& provider, Type type_needed) {
779  const auto& table{IsTapscript(script_ctx) ? SMARTINFO.tap_table : SMARTINFO.wsh_table};
780  auto recipes_it = table.find(type_needed);
781  assert(recipes_it != table.end());
783  const auto& [frag, subt] = PickValue(provider, recipes_it->second);
784 
785  // Based on the fragment the recipe uses, fill in other data (k, keys, data).
786  switch (frag) {
787  case Fragment::PK_K:
788  case Fragment::PK_H:
789  return {{frag, ConsumePubKey(provider)}};
790  case Fragment::MULTI: {
791  const auto n_keys = provider.ConsumeIntegralInRange<uint8_t>(1, 20);
792  const auto k = provider.ConsumeIntegralInRange<uint8_t>(1, n_keys);
793  std::vector<CPubKey> keys{n_keys};
794  for (auto& key: keys) key = ConsumePubKey(provider);
795  return {{frag, k, std::move(keys)}};
796  }
797  case Fragment::MULTI_A: {
798  const auto n_keys = provider.ConsumeIntegralInRange<uint16_t>(1, 999);
799  const auto k = provider.ConsumeIntegralInRange<uint16_t>(1, n_keys);
800  std::vector<CPubKey> keys{n_keys};
801  for (auto& key: keys) key = ConsumePubKey(provider);
802  return {{frag, k, std::move(keys)}};
803  }
804  case Fragment::OLDER:
805  case Fragment::AFTER:
806  return {{frag, provider.ConsumeIntegralInRange<uint32_t>(1, 0x7FFFFFF)}};
807  case Fragment::SHA256:
808  return {{frag, PickValue(provider, TEST_DATA.sha256)}};
809  case Fragment::HASH256:
810  return {{frag, PickValue(provider, TEST_DATA.hash256)}};
811  case Fragment::RIPEMD160:
812  return {{frag, PickValue(provider, TEST_DATA.ripemd160)}};
813  case Fragment::HASH160:
814  return {{frag, PickValue(provider, TEST_DATA.hash160)}};
815  case Fragment::JUST_0:
816  case Fragment::JUST_1:
817  case Fragment::WRAP_A:
818  case Fragment::WRAP_S:
819  case Fragment::WRAP_C:
820  case Fragment::WRAP_D:
821  case Fragment::WRAP_V:
822  case Fragment::WRAP_J:
823  case Fragment::WRAP_N:
824  case Fragment::AND_V:
825  case Fragment::AND_B:
826  case Fragment::OR_B:
827  case Fragment::OR_C:
828  case Fragment::OR_D:
829  case Fragment::OR_I:
830  case Fragment::ANDOR:
831  return {{subt, frag}};
832  case Fragment::THRESH: {
833  uint32_t children;
834  if (subt.size() < 2) {
835  children = subt.size();
836  } else {
837  // If we hit a thresh with 2 subnodes, artificially extend it to any number
838  // (2 or larger) by replicating the type of the last subnode.
839  children = provider.ConsumeIntegralInRange<uint32_t>(2, MAX_OPS_PER_SCRIPT / 2);
840  }
841  auto k = provider.ConsumeIntegralInRange<uint32_t>(1, children);
842  std::vector<Type> subs = subt;
843  while (subs.size() < children) subs.push_back(subs.back());
844  return {{std::move(subs), frag, k}};
845  }
846  }
847 
848  assert(false);
849 }
850 
859 template<typename F>
860 NodeRef GenNode(MsCtx script_ctx, F ConsumeNode, Type root_type, bool strict_valid = false) {
862  std::vector<NodeRef> stack;
864  std::vector<std::pair<Type, std::optional<NodeInfo>>> todo{{root_type, {}}};
866  uint32_t ops{0};
869  uint32_t scriptsize{1};
870 
871  while (!todo.empty()) {
872  // The expected type we have to construct.
873  auto type_needed = todo.back().first;
874  if (!todo.back().second) {
875  // Fragment/children have not been decided yet. Decide them.
876  auto node_info = ConsumeNode(type_needed);
877  if (!node_info) return {};
878  // Update predicted resource limits. Since every leaf Miniscript node is at least one
879  // byte long, we move one byte from each child to their parent. A similar technique is
880  // used in the miniscript::internal::Parse function to prevent runaway string parsing.
881  scriptsize += miniscript::internal::ComputeScriptLen(node_info->fragment, ""_mst, node_info->subtypes.size(), node_info->k, node_info->subtypes.size(),
882  node_info->keys.size(), script_ctx) - 1;
883  if (scriptsize > MAX_STANDARD_P2WSH_SCRIPT_SIZE) return {};
884  switch (node_info->fragment) {
885  case Fragment::JUST_0:
886  case Fragment::JUST_1:
887  break;
888  case Fragment::PK_K:
889  break;
890  case Fragment::PK_H:
891  ops += 3;
892  break;
893  case Fragment::OLDER:
894  case Fragment::AFTER:
895  ops += 1;
896  break;
897  case Fragment::RIPEMD160:
898  case Fragment::SHA256:
899  case Fragment::HASH160:
900  case Fragment::HASH256:
901  ops += 4;
902  break;
903  case Fragment::ANDOR:
904  ops += 3;
905  break;
906  case Fragment::AND_V:
907  break;
908  case Fragment::AND_B:
909  case Fragment::OR_B:
910  ops += 1;
911  break;
912  case Fragment::OR_C:
913  ops += 2;
914  break;
915  case Fragment::OR_D:
916  ops += 3;
917  break;
918  case Fragment::OR_I:
919  ops += 3;
920  break;
921  case Fragment::THRESH:
922  ops += node_info->subtypes.size();
923  break;
924  case Fragment::MULTI:
925  ops += 1;
926  break;
927  case Fragment::MULTI_A:
928  ops += node_info->keys.size() + 1;
929  break;
930  case Fragment::WRAP_A:
931  ops += 2;
932  break;
933  case Fragment::WRAP_S:
934  ops += 1;
935  break;
936  case Fragment::WRAP_C:
937  ops += 1;
938  break;
939  case Fragment::WRAP_D:
940  ops += 3;
941  break;
942  case Fragment::WRAP_V:
943  // We don't account for OP_VERIFY here; that will be corrected for when the actual
944  // node is constructed below.
945  break;
946  case Fragment::WRAP_J:
947  ops += 4;
948  break;
949  case Fragment::WRAP_N:
950  ops += 1;
951  break;
952  }
953  if (ops > MAX_OPS_PER_SCRIPT) return {};
954  auto subtypes = node_info->subtypes;
955  todo.back().second = std::move(node_info);
956  todo.reserve(todo.size() + subtypes.size());
957  // As elements on the todo stack are processed back to front, construct
958  // them in reverse order (so that the first subnode is generated first).
959  for (size_t i = 0; i < subtypes.size(); ++i) {
960  todo.emplace_back(*(subtypes.rbegin() + i), std::nullopt);
961  }
962  } else {
963  // The back of todo has fragment and number of children decided, and
964  // those children have been constructed at the back of stack. Pop
965  // that entry off todo, and use it to construct a new NodeRef on
966  // stack.
967  NodeInfo& info = *todo.back().second;
968  // Gather children from the back of stack.
969  std::vector<NodeRef> sub;
970  sub.reserve(info.subtypes.size());
971  for (size_t i = 0; i < info.subtypes.size(); ++i) {
972  sub.push_back(std::move(*(stack.end() - info.subtypes.size() + i)));
973  }
974  stack.erase(stack.end() - info.subtypes.size(), stack.end());
975  // Construct new NodeRef.
976  NodeRef node;
977  if (info.keys.empty()) {
978  node = MakeNodeRef(script_ctx, info.fragment, std::move(sub), std::move(info.hash), info.k);
979  } else {
980  assert(sub.empty());
981  assert(info.hash.empty());
982  node = MakeNodeRef(script_ctx, info.fragment, std::move(info.keys), info.k);
983  }
984  // Verify acceptability.
985  if (!node || (node->GetType() & "KVWB"_mst) == ""_mst) {
986  assert(!strict_valid);
987  return {};
988  }
989  if (!(type_needed == ""_mst)) {
990  assert(node->GetType() << type_needed);
991  }
992  if (!node->IsValid()) return {};
993  // Update resource predictions.
994  if (node->fragment == Fragment::WRAP_V && node->subs[0]->GetType() << "x"_mst) {
995  ops += 1;
996  scriptsize += 1;
997  }
998  if (!miniscript::IsTapscript(script_ctx) && ops > MAX_OPS_PER_SCRIPT) return {};
999  if (scriptsize > miniscript::internal::MaxScriptSize(script_ctx)) {
1000  return {};
1001  }
1002  // Move it to the stack.
1003  stack.push_back(std::move(node));
1004  todo.pop_back();
1005  }
1006  }
1007  assert(stack.size() == 1);
1008  assert(stack[0]->GetStaticOps() == ops);
1009  assert(stack[0]->ScriptSize() == scriptsize);
1010  stack[0]->DuplicateKeyCheck(KEY_COMP);
1011  return std::move(stack[0]);
1012 }
1013 
1015 CScript ScriptPubKey(MsCtx ctx, const CScript& script, TaprootBuilder& builder)
1016 {
1017  if (!miniscript::IsTapscript(ctx)) return CScript() << OP_0 << WitnessV0ScriptHash(script);
1018 
1019  // For Taproot outputs we always use a tree with a single script and a dummy internal key.
1020  builder.Add(0, script, TAPROOT_LEAF_TAPSCRIPT);
1021  builder.Finalize(XOnlyPubKey{NUMS_PK});
1022  return GetScriptForDestination(builder.GetOutput());
1023 }
1024 
1026 void SatisfactionToWitness(MsCtx ctx, CScriptWitness& witness, const CScript& script, TaprootBuilder& builder) {
1027  // For P2WSH, it's only the witness script.
1028  witness.stack.emplace_back(script.begin(), script.end());
1029  if (!miniscript::IsTapscript(ctx)) return;
1030  // For Tapscript we also need the control block.
1031  witness.stack.push_back(*builder.GetSpendData().scripts.begin()->second.begin());
1032 }
1033 
1035 void TestNode(const MsCtx script_ctx, const NodeRef& node, FuzzedDataProvider& provider)
1036 {
1037  if (!node) return;
1038 
1039  // Check that it roundtrips to text representation
1040  const ParserContext parser_ctx{script_ctx};
1041  std::optional<std::string> str{node->ToString(parser_ctx)};
1042  assert(str);
1043  auto parsed = miniscript::FromString(*str, parser_ctx);
1044  assert(parsed);
1045  assert(*parsed == *node);
1046 
1047  // Check consistency between script size estimation and real size.
1048  auto script = node->ToScript(parser_ctx);
1049  assert(node->ScriptSize() == script.size());
1050 
1051  // Check consistency of "x" property with the script (type K is excluded, because it can end
1052  // with a push of a key, which could match these opcodes).
1053  if (!(node->GetType() << "K"_mst)) {
1054  bool ends_in_verify = !(node->GetType() << "x"_mst);
1055  assert(ends_in_verify == (script.back() == OP_CHECKSIG || script.back() == OP_CHECKMULTISIG || script.back() == OP_EQUAL || script.back() == OP_NUMEQUAL));
1056  }
1057 
1058  // The rest of the checks only apply when testing a valid top-level script.
1059  if (!node->IsValidTopLevel()) return;
1060 
1061  // Check roundtrip to script
1062  auto decoded = miniscript::FromScript(script, parser_ctx);
1063  assert(decoded);
1064  // Note we can't use *decoded == *node because the miniscript representation may differ, so we check that:
1065  // - The script corresponding to that decoded form matches exactly
1066  // - The type matches exactly
1067  assert(decoded->ToScript(parser_ctx) == script);
1068  assert(decoded->GetType() == node->GetType());
1069 
1070  // Optionally pad the script or the witness in order to increase the sensitivity of the tests of
1071  // the resources limits logic.
1072  CScriptWitness witness_mal, witness_nonmal;
1073  if (provider.ConsumeBool()) {
1074  // Under P2WSH, optionally pad the script with OP_NOPs to max op the ops limit of the constructed script.
1075  // This makes the script obviously not actually miniscript-compatible anymore, but the
1076  // signatures constructed in this test don't commit to the script anyway, so the same
1077  // miniscript satisfier will work. This increases the sensitivity of the test to the ops
1078  // counting logic being too low, especially for simple scripts.
1079  // Do this optionally because we're not solely interested in cases where the number of ops is
1080  // maximal.
1081  // Do not pad more than what would cause MAX_STANDARD_P2WSH_SCRIPT_SIZE to be reached, however,
1082  // as that also invalidates scripts.
1083  const auto node_ops{node->GetOps()};
1084  if (!IsTapscript(script_ctx) && node_ops && *node_ops < MAX_OPS_PER_SCRIPT
1085  && node->ScriptSize() < MAX_STANDARD_P2WSH_SCRIPT_SIZE) {
1086  int add = std::min<int>(
1087  MAX_OPS_PER_SCRIPT - *node_ops,
1088  MAX_STANDARD_P2WSH_SCRIPT_SIZE - node->ScriptSize());
1089  for (int i = 0; i < add; ++i) script.push_back(OP_NOP);
1090  }
1091 
1092  // Under Tapscript, optionally pad the stack up to the limit minus the calculated maximum execution stack
1093  // size to assert a Miniscript would never add more elements to the stack during execution than anticipated.
1094  const auto node_exec_ss{node->GetExecStackSize()};
1095  if (miniscript::IsTapscript(script_ctx) && node_exec_ss && *node_exec_ss < MAX_STACK_SIZE) {
1096  unsigned add{(unsigned)MAX_STACK_SIZE - *node_exec_ss};
1097  witness_mal.stack.resize(add);
1098  witness_nonmal.stack.resize(add);
1099  script.reserve(add);
1100  for (unsigned i = 0; i < add; ++i) script.push_back(OP_NIP);
1101  }
1102  }
1103 
1104  const SatisfierContext satisfier_ctx{script_ctx};
1105 
1106  // Get the ScriptPubKey for this script, filling spend data if it's Taproot.
1107  TaprootBuilder builder;
1108  const CScript script_pubkey{ScriptPubKey(script_ctx, script, builder)};
1109 
1110  // Run malleable satisfaction algorithm.
1111  std::vector<std::vector<unsigned char>> stack_mal;
1112  const bool mal_success = node->Satisfy(satisfier_ctx, stack_mal, false) == miniscript::Availability::YES;
1113 
1114  // Run non-malleable satisfaction algorithm.
1115  std::vector<std::vector<unsigned char>> stack_nonmal;
1116  const bool nonmal_success = node->Satisfy(satisfier_ctx, stack_nonmal, true) == miniscript::Availability::YES;
1117 
1118  if (nonmal_success) {
1119  // Non-malleable satisfactions are bounded by the satisfaction size plus:
1120  // - For P2WSH spends, the witness script
1121  // - For Tapscript spends, both the witness script and the control block
1122  const size_t max_stack_size{*node->GetStackSize() + 1 + miniscript::IsTapscript(script_ctx)};
1123  assert(stack_nonmal.size() <= max_stack_size);
1124  // If a non-malleable satisfaction exists, the malleable one must also exist, and be identical to it.
1125  assert(mal_success);
1126  assert(stack_nonmal == stack_mal);
1127  // Compute witness size (excluding script push, control block, and witness count encoding).
1128  const size_t wit_size = GetSerializeSize(stack_nonmal) - GetSizeOfCompactSize(stack_nonmal.size());
1129  assert(wit_size <= *node->GetWitnessSize());
1130 
1131  // Test non-malleable satisfaction.
1132  witness_nonmal.stack.insert(witness_nonmal.stack.end(), std::make_move_iterator(stack_nonmal.begin()), std::make_move_iterator(stack_nonmal.end()));
1133  SatisfactionToWitness(script_ctx, witness_nonmal, script, builder);
1134  ScriptError serror;
1135  bool res = VerifyScript(DUMMY_SCRIPTSIG, script_pubkey, &witness_nonmal, STANDARD_SCRIPT_VERIFY_FLAGS, CHECKER_CTX, &serror);
1136  // Non-malleable satisfactions are guaranteed to be valid if ValidSatisfactions().
1137  if (node->ValidSatisfactions()) assert(res);
1138  // More detailed: non-malleable satisfactions must be valid, or could fail with ops count error (if CheckOpsLimit failed),
1139  // or with a stack size error (if CheckStackSize check failed).
1140  assert(res ||
1141  (!node->CheckOpsLimit() && serror == ScriptError::SCRIPT_ERR_OP_COUNT) ||
1142  (!node->CheckStackSize() && serror == ScriptError::SCRIPT_ERR_STACK_SIZE));
1143  }
1144 
1145  if (mal_success && (!nonmal_success || witness_mal.stack != witness_nonmal.stack)) {
1146  // Test malleable satisfaction only if it's different from the non-malleable one.
1147  witness_mal.stack.insert(witness_mal.stack.end(), std::make_move_iterator(stack_mal.begin()), std::make_move_iterator(stack_mal.end()));
1148  SatisfactionToWitness(script_ctx, witness_mal, script, builder);
1149  ScriptError serror;
1150  bool res = VerifyScript(DUMMY_SCRIPTSIG, script_pubkey, &witness_mal, STANDARD_SCRIPT_VERIFY_FLAGS, CHECKER_CTX, &serror);
1151  // Malleable satisfactions are not guaranteed to be valid under any conditions, but they can only
1152  // fail due to stack or ops limits.
1154  }
1155 
1156  if (node->IsSane()) {
1157  // For sane nodes, the two algorithms behave identically.
1158  assert(mal_success == nonmal_success);
1159  }
1160 
1161  // Verify that if a node is policy-satisfiable, the malleable satisfaction
1162  // algorithm succeeds. Given that under IsSane() both satisfactions
1163  // are identical, this implies that for such nodes, the non-malleable
1164  // satisfaction will also match the expected policy.
1165  const auto is_key_satisfiable = [script_ctx](const CPubKey& pubkey) -> bool {
1166  auto sig_ptr{TEST_DATA.GetSig(script_ctx, pubkey)};
1167  return sig_ptr != nullptr && sig_ptr->second;
1168  };
1169  bool satisfiable = node->IsSatisfiable([&](const Node& node) -> bool {
1170  switch (node.fragment) {
1171  case Fragment::PK_K:
1172  case Fragment::PK_H:
1173  return is_key_satisfiable(node.keys[0]);
1174  case Fragment::MULTI:
1175  case Fragment::MULTI_A: {
1176  size_t sats = std::count_if(node.keys.begin(), node.keys.end(), [&](const auto& key) {
1177  return size_t(is_key_satisfiable(key));
1178  });
1179  return sats >= node.k;
1180  }
1181  case Fragment::OLDER:
1182  case Fragment::AFTER:
1183  return node.k & 1;
1184  case Fragment::SHA256:
1185  return TEST_DATA.sha256_preimages.count(node.data);
1186  case Fragment::HASH256:
1187  return TEST_DATA.hash256_preimages.count(node.data);
1188  case Fragment::RIPEMD160:
1189  return TEST_DATA.ripemd160_preimages.count(node.data);
1190  case Fragment::HASH160:
1191  return TEST_DATA.hash160_preimages.count(node.data);
1192  default:
1193  assert(false);
1194  }
1195  return false;
1196  });
1197  assert(mal_success == satisfiable);
1198 }
1199 
1200 } // namespace
1201 
1202 void FuzzInit()
1203 {
1204  ECC_Start();
1205  TEST_DATA.Init();
1206 }
1207 
1209 {
1210  FuzzInit();
1211  SMARTINFO.Init();
1212 }
1213 
1215 FUZZ_TARGET(miniscript_stable, .init = FuzzInit)
1216 {
1217  // Run it under both P2WSH and Tapscript contexts.
1218  for (const auto script_ctx: {MsCtx::P2WSH, MsCtx::TAPSCRIPT}) {
1219  FuzzedDataProvider provider(buffer.data(), buffer.size());
1220  TestNode(script_ctx, GenNode(script_ctx, [&](Type needed_type) {
1221  return ConsumeNodeStable(script_ctx, provider, needed_type);
1222  }, ""_mst), provider);
1223  }
1224 }
1225 
1227 FUZZ_TARGET(miniscript_smart, .init = FuzzInitSmart)
1228 {
1230  static constexpr std::array<Type, 4> BASE_TYPES{"B"_mst, "V"_mst, "K"_mst, "W"_mst};
1231 
1232  FuzzedDataProvider provider(buffer.data(), buffer.size());
1233  const auto script_ctx{(MsCtx)provider.ConsumeBool()};
1234  TestNode(script_ctx, GenNode(script_ctx, [&](Type needed_type) {
1235  return ConsumeNodeSmart(script_ctx, provider, needed_type);
1236  }, PickValue(provider, BASE_TYPES), true), provider);
1237 }
1238 
1239 /* Fuzz tests that test parsing from a string, and roundtripping via string. */
1240 FUZZ_TARGET(miniscript_string, .init = FuzzInit)
1241 {
1242  if (buffer.empty()) return;
1243  FuzzedDataProvider provider(buffer.data(), buffer.size());
1244  auto str = provider.ConsumeBytesAsString(provider.remaining_bytes() - 1);
1245  const ParserContext parser_ctx{(MsCtx)provider.ConsumeBool()};
1246  auto parsed = miniscript::FromString(str, parser_ctx);
1247  if (!parsed) return;
1248 
1249  const auto str2 = parsed->ToString(parser_ctx);
1250  assert(str2);
1251  auto parsed2 = miniscript::FromString(*str2, parser_ctx);
1252  assert(parsed2);
1253  assert(*parsed == *parsed2);
1254 }
1255 
1256 /* Fuzz tests that test parsing from a script, and roundtripping via script. */
1257 FUZZ_TARGET(miniscript_script)
1258 {
1259  FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
1260  const std::optional<CScript> script = ConsumeDeserializable<CScript>(fuzzed_data_provider);
1261  if (!script) return;
1262 
1263  const ScriptParserContext script_parser_ctx{(MsCtx)fuzzed_data_provider.ConsumeBool()};
1264  const auto ms = miniscript::FromScript(*script, script_parser_ctx);
1265  if (!ms) return;
1266 
1267  assert(ms->ToScript(script_parser_ctx) == *script);
1268 }
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
ECC_Start()
Definition: key.cpp:435
ArgsManager & args
Definition: bitcoind.cpp:266
virtual bool CheckLockTime(const CScriptNum &nLockTime) const
Definition: interpreter.h:258
virtual bool CheckSchnorrSignature(Span< const unsigned char > sig, Span< const unsigned char > pubkey, SigVersion sigversion, ScriptExecutionData &execdata, ScriptError *serror=nullptr) const
Definition: interpreter.h:253
virtual bool CheckSequence(const CScriptNum &nSequence) const
Definition: interpreter.h:263
virtual bool CheckECDSASignature(const std::vector< unsigned char > &scriptSig, const std::vector< unsigned char > &vchPubKey, const CScript &scriptCode, SigVersion sigversion) const
Definition: interpreter.h:248
A hasher class for Bitcoin's 160-bit hash (SHA-256 + RIPEMD-160).
Definition: hash.h:49
void Finalize(Span< unsigned char > output)
Definition: hash.h:55
CHash160 & Write(Span< const unsigned char > input)
Definition: hash.h:62
A hasher class for Bitcoin's 256-bit hash (double SHA-256).
Definition: hash.h:24
CHash256 & Write(Span< const unsigned char > input)
Definition: hash.h:37
void Finalize(Span< unsigned char > output)
Definition: hash.h:30
An encapsulated private key.
Definition: key.h:33
bool SignSchnorr(const uint256 &hash, Span< unsigned char > sig, const uint256 *merkle_root, const uint256 &aux) const
Create a BIP-340 Schnorr signature, for the xonly-pubkey corresponding to *this, optionally tweaked b...
Definition: key.cpp:278
bool Sign(const uint256 &hash, std::vector< unsigned char > &vchSig, bool grind=true, uint32_t test_case=0) const
Create a DER-serialized signature.
Definition: key.cpp:214
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:188
void Set(const T pbegin, const T pend, bool fCompressedIn)
Initialize using begin and end iterators to byte data.
Definition: key.h:99
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:24
An encapsulated public key.
Definition: pubkey.h:34
A hasher class for RIPEMD-160.
Definition: ripemd160.h:13
CRIPEMD160 & Write(const unsigned char *data, size_t len)
Definition: ripemd160.cpp:247
void Finalize(unsigned char hash[OUTPUT_SIZE])
Definition: ripemd160.cpp:273
A hasher class for SHA-256.
Definition: sha256.h:14
void Finalize(unsigned char hash[OUTPUT_SIZE])
Definition: sha256.cpp:728
CSHA256 & Write(const unsigned char *data, size_t len)
Definition: sha256.cpp:702
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:414
int64_t GetInt64() const
Definition: script.h:341
std::string ConsumeBytesAsString(size_t num_bytes)
T ConsumeIntegralInRange(T min, T max)
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:98
CONSTEXPR_IF_NOT_DEBUG Span< C > first(std::size_t count) const noexcept
Definition: span.h:205
Utility class to construct Taproot outputs from internal key and script tree.
WitnessV1Taproot GetOutput()
Compute scriptPubKey (after Finalize()).
TaprootSpendData GetSpendData() const
Compute spending data (after Finalize()).
TaprootBuilder & Add(int depth, Span< const unsigned char > script, int leaf_version, bool track=true)
Add a new script at a certain depth in the tree.
TaprootBuilder & Finalize(const XOnlyPubKey &internal_key)
Finalize the construction.
const unsigned char * begin() const
Definition: pubkey.h:290
CPubKey GetEvenCorrespondingCPubKey() const
Definition: pubkey.cpp:207
static constexpr unsigned int size()
Definition: uint256.h:74
constexpr unsigned char * begin()
Definition: uint256.h:68
This type encapsulates the miniscript type system properties.
Definition: miniscript.h:122
size_type size() const
Definition: prevector.h:296
T & back()
Definition: prevector.h:459
iterator begin()
Definition: prevector.h:304
iterator end()
Definition: prevector.h:306
void reserve(size_type new_capacity)
Definition: prevector.h:347
void push_back(const T &value)
Definition: prevector.h:443
160-bit opaque blob.
Definition: uint256.h:95
uint160 Hash160(const T1 &in1)
Compute the 160-bit hash an object.
Definition: hash.h:92
uint160 RIPEMD160(Span< const unsigned char > data)
Compute the 160-bit RIPEMD-160 hash of an array.
Definition: hash.h:222
#define T(expected, seed, data)
bool VerifyScript(const CScript &scriptSig, const CScript &scriptPubKey, const CScriptWitness *witness, unsigned int flags, const BaseSignatureChecker &checker, ScriptError *serror)
SigVersion
Definition: interpreter.h:191
static constexpr uint8_t TAPROOT_LEAF_TAPSCRIPT
Definition: interpreter.h:232
size_t ComputeScriptLen(Fragment fragment, Type sub0typ, size_t subsize, uint32_t k, size_t n_subs, size_t n_keys, MiniscriptContext ms_ctx)
Helper function for Node::CalcScriptLen.
Definition: miniscript.cpp:262
constexpr uint32_t MaxScriptSize(MiniscriptContext ms_ctx)
The maximum size of a script depending on the context.
Definition: miniscript.h:265
Type ComputeType(Fragment fragment, Type x, Type y, Type z, const std::vector< Type > &sub_types, uint32_t k, size_t data_size, size_t n_subs, size_t n_keys, MiniscriptContext ms_ctx)
Helper function for Node::CalcType.
Definition: miniscript.cpp:36
std::shared_ptr< const Node< Key > > NodeRef
Definition: miniscript.h:187
constexpr bool IsTapscript(MiniscriptContext ms_ctx)
Whether the context Tapscript, ensuring the only other possibility is P2WSH.
Definition: miniscript.h:240
NodeRef< Key > MakeNodeRef(Args &&... args)
Construct a miniscript node as a shared_ptr.
Definition: miniscript.h:191
NodeRef< typename Ctx::Key > FromScript(const CScript &script, const Ctx &ctx)
Definition: miniscript.h:2618
NodeRef< typename Ctx::Key > FromString(const std::string &str, const Ctx &ctx)
Definition: miniscript.h:2613
Fragment
The different node types in miniscript.
Definition: miniscript.h:194
Definition: init.h:25
Internal RIPEMD-160 implementation.
Definition: ripemd160.cpp:16
Internal SHA-256 implementation.
Definition: sha256.cpp:71
static constexpr unsigned int STANDARD_SCRIPT_VERIFY_FLAGS
Standard script verification flags that standard transactions will comply with.
Definition: policy.h:103
static constexpr unsigned int MAX_STANDARD_P2WSH_SCRIPT_SIZE
The maximum size in bytes of a standard witnessScript.
Definition: policy.h:47
@ OP_CHECKMULTISIG
Definition: script.h:191
@ OP_CHECKSIG
Definition: script.h:189
@ OP_EQUAL
Definition: script.h:145
@ OP_NUMEQUAL
Definition: script.h:170
@ OP_NOP
Definition: script.h:101
@ OP_NIP
Definition: script.h:125
@ OP_0
Definition: script.h:75
static const int MAX_STACK_SIZE
Definition: script.h:42
static const int MAX_OPS_PER_SCRIPT
Definition: script.h:30
enum ScriptError_t ScriptError
@ SCRIPT_ERR_OP_COUNT
Definition: script_error.h:21
@ SCRIPT_ERR_STACK_SIZE
Definition: script_error.h:22
size_t GetSerializeSize(const T &t)
Definition: serialize.h:1116
constexpr unsigned int GetSizeOfCompactSize(uint64_t nSize)
Compact Size size < 253 – 1 byte size <= USHRT_MAX – 3 bytes (253 + 2 bytes) size <= UINT_MAX – 5 byt...
Definition: serialize.h:310
std::vector< Byte > ParseHex(std::string_view hex_str)
Like TryParseHex, but returns an empty vector on invalid input.
Definition: strencodings.h:65
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:110
std::vector< std::vector< unsigned char > > stack
Definition: script.h:569
std::map< std::pair< std::vector< unsigned char >, int >, std::set< std::vector< unsigned char >, ShortestVectorFirstComparator > > scripts
Map from (script, leaf_version) to (sets of) control blocks.
A node in a miniscript expression.
Definition: miniscript.h:499
FUZZ_TARGET(miniscript_stable,.init=FuzzInit)
Fuzz target that runs TestNode on nodes generated using ConsumeNodeStable.
void FuzzInit()
void FuzzInitSmart()
auto ConsumeNode(FuzzedDataProvider &fuzzed_data_provider, const std::optional< NodeId > &node_id_in=std::nullopt) noexcept
Definition: net.h:109
auto & PickValue(FuzzedDataProvider &fuzzed_data_provider, Collection &col)
Definition: util.h:47
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:74
uint256 uint256S(const char *str)
Definition: uint256.h:119
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
#define B
Definition: util_tests.cpp:489
assert(!tx.IsCoinBase())