Bitcoin Core  29.1.0
P2P Digital Currency
miniscript.h
Go to the documentation of this file.
1 // Copyright (c) 2019-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 #ifndef BITCOIN_SCRIPT_MINISCRIPT_H
6 #define BITCOIN_SCRIPT_MINISCRIPT_H
7 
8 #include <algorithm>
9 #include <compare>
10 #include <cstdint>
11 #include <cstdlib>
12 #include <iterator>
13 #include <memory>
14 #include <optional>
15 #include <set>
16 #include <stdexcept>
17 #include <tuple>
18 #include <utility>
19 #include <vector>
20 
21 #include <consensus/consensus.h>
22 #include <policy/policy.h>
23 #include <script/interpreter.h>
24 #include <script/parsing.h>
25 #include <script/script.h>
26 #include <serialize.h>
27 #include <span.h>
28 #include <util/check.h>
29 #include <util/strencodings.h>
30 #include <util/string.h>
31 #include <util/vector.h>
32 
33 namespace miniscript {
34 
126 class Type {
128  uint32_t m_flags;
129 
131  explicit constexpr Type(uint32_t flags) noexcept : m_flags(flags) {}
132 
133 public:
135  static consteval Type Make(uint32_t flags) noexcept { return Type(flags); }
136 
138  constexpr Type operator|(Type x) const { return Type(m_flags | x.m_flags); }
139 
141  constexpr Type operator&(Type x) const { return Type(m_flags & x.m_flags); }
142 
144  constexpr bool operator<<(Type x) const { return (x.m_flags & ~m_flags) == 0; }
145 
147  constexpr bool operator<(Type x) const { return m_flags < x.m_flags; }
148 
150  constexpr bool operator==(Type x) const { return m_flags == x.m_flags; }
151 
153  constexpr Type If(bool x) const { return Type(x ? m_flags : 0); }
154 };
155 
157 inline consteval Type operator""_mst(const char* c, size_t l)
158 {
159  Type typ{Type::Make(0)};
160 
161  for (const char *p = c; p < c + l; p++) {
162  typ = typ | Type::Make(
163  *p == 'B' ? 1 << 0 : // Base type
164  *p == 'V' ? 1 << 1 : // Verify type
165  *p == 'K' ? 1 << 2 : // Key type
166  *p == 'W' ? 1 << 3 : // Wrapped type
167  *p == 'z' ? 1 << 4 : // Zero-arg property
168  *p == 'o' ? 1 << 5 : // One-arg property
169  *p == 'n' ? 1 << 6 : // Nonzero arg property
170  *p == 'd' ? 1 << 7 : // Dissatisfiable property
171  *p == 'u' ? 1 << 8 : // Unit property
172  *p == 'e' ? 1 << 9 : // Expression property
173  *p == 'f' ? 1 << 10 : // Forced property
174  *p == 's' ? 1 << 11 : // Safe property
175  *p == 'm' ? 1 << 12 : // Nonmalleable property
176  *p == 'x' ? 1 << 13 : // Expensive verify
177  *p == 'g' ? 1 << 14 : // older: contains relative time timelock (csv_time)
178  *p == 'h' ? 1 << 15 : // older: contains relative height timelock (csv_height)
179  *p == 'i' ? 1 << 16 : // after: contains time timelock (cltv_time)
180  *p == 'j' ? 1 << 17 : // after: contains height timelock (cltv_height)
181  *p == 'k' ? 1 << 18 : // does not contain a combination of height and time locks
182  (throw std::logic_error("Unknown character in _mst literal"), 0)
183  );
184  }
185 
186  return typ;
187 }
188 
189 using Opcode = std::pair<opcodetype, std::vector<unsigned char>>;
190 
191 template<typename Key> struct Node;
192 template<typename Key> using NodeRef = std::unique_ptr<const Node<Key>>;
193 
195 template<typename Key, typename... Args>
196 NodeRef<Key> MakeNodeRef(Args&&... args) { return std::make_unique<const Node<Key>>(std::forward<Args>(args)...); }
197 
199 enum class Fragment {
200  JUST_0,
201  JUST_1,
202  PK_K,
203  PK_H,
204  OLDER,
205  AFTER,
206  SHA256,
207  HASH256,
208  RIPEMD160,
209  HASH160,
210  WRAP_A,
211  WRAP_S,
212  WRAP_C,
213  WRAP_D,
214  WRAP_V,
215  WRAP_J,
216  WRAP_N,
217  AND_V,
218  AND_B,
219  OR_B,
220  OR_C,
221  OR_D,
222  OR_I,
223  ANDOR,
224  THRESH,
225  MULTI,
226  MULTI_A,
227  // AND_N(X,Y) is represented as ANDOR(X,Y,0)
228  // WRAP_T(X) is represented as AND_V(X,1)
229  // WRAP_L(X) is represented as OR_I(0,X)
230  // WRAP_U(X) is represented as OR_I(X,0)
231 };
232 
233 enum class Availability {
234  NO,
235  YES,
236  MAYBE,
237 };
238 
239 enum class MiniscriptContext {
240  P2WSH,
241  TAPSCRIPT,
242 };
243 
245 constexpr bool IsTapscript(MiniscriptContext ms_ctx)
246 {
247  switch (ms_ctx) {
248  case MiniscriptContext::P2WSH: return false;
249  case MiniscriptContext::TAPSCRIPT: return true;
250  }
251  assert(false);
252 }
253 
254 namespace internal {
255 
257 static constexpr uint32_t MAX_TAPMINISCRIPT_STACK_ELEM_SIZE{65};
258 
260 constexpr uint32_t TX_OVERHEAD{4 + 4};
262 constexpr uint32_t TXIN_BYTES_NO_WITNESS{36 + 4 + 1};
264 constexpr uint32_t P2WSH_TXOUT_BYTES{8 + 1 + 1 + 33};
270 constexpr uint32_t MaxScriptSize(MiniscriptContext ms_ctx)
271 {
272  if (IsTapscript(ms_ctx)) {
273  // Leaf scripts under Tapscript are not explicitly limited in size. They are only implicitly
274  // bounded by the maximum standard size of a spending transaction. Let the maximum script
275  // size conservatively be small enough such that even a maximum sized witness and a reasonably
276  // sized spending transaction can spend an output paying to this script without running into
277  // the maximum standard tx size limit.
279  return max_size - GetSizeOfCompactSize(max_size);
280  }
282 }
283 
285 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);
286 
288 size_t ComputeScriptLen(Fragment fragment, Type sub0typ, size_t subsize, uint32_t k, size_t n_subs, size_t n_keys, MiniscriptContext ms_ctx);
289 
292 
294 struct InputStack {
302  bool has_sig = false;
304  bool malleable = false;
307  bool non_canon = false;
309  size_t size = 0;
311  std::vector<std::vector<unsigned char>> stack;
313  InputStack() = default;
315  InputStack(std::vector<unsigned char> in) : size(in.size() + 1), stack(Vector(std::move(in))) {}
323  InputStack& SetMalleable(bool x = true);
328 };
329 
331 static const auto ZERO = InputStack(std::vector<unsigned char>());
333 static const auto ZERO32 = InputStack(std::vector<unsigned char>(32, 0)).SetMalleable();
335 static const auto ONE = InputStack(Vector((unsigned char)1));
337 static const auto EMPTY = InputStack();
340 
342 struct InputResult {
344 
345  template<typename A, typename B>
346  InputResult(A&& in_nsat, B&& in_sat) : nsat(std::forward<A>(in_nsat)), sat(std::forward<B>(in_sat)) {}
347 };
348 
350 template<typename I>
351 struct MaxInt {
352  const bool valid;
353  const I value;
354 
355  MaxInt() : valid(false), value(0) {}
356  MaxInt(I val) : valid(true), value(val) {}
357 
358  friend MaxInt<I> operator+(const MaxInt<I>& a, const MaxInt<I>& b) {
359  if (!a.valid || !b.valid) return {};
360  return a.value + b.value;
361  }
362 
363  friend MaxInt<I> operator|(const MaxInt<I>& a, const MaxInt<I>& b) {
364  if (!a.valid) return b;
365  if (!b.valid) return a;
366  return std::max(a.value, b.value);
367  }
368 };
369 
370 struct Ops {
372  uint32_t count;
377 
378  Ops(uint32_t in_count, MaxInt<uint32_t> in_sat, MaxInt<uint32_t> in_dsat) : count(in_count), sat(in_sat), dsat(in_dsat) {};
379 };
380 
422 struct SatInfo {
424  const bool valid;
426  const int32_t netdiff;
428  const int32_t exec;
429 
431  constexpr SatInfo() noexcept : valid(false), netdiff(0), exec(0) {}
432 
434  constexpr SatInfo(int32_t in_netdiff, int32_t in_exec) noexcept :
435  valid{true}, netdiff{in_netdiff}, exec{in_exec} {}
436 
438  constexpr friend SatInfo operator|(const SatInfo& a, const SatInfo& b) noexcept
439  {
440  // Union with an empty set is itself.
441  if (!a.valid) return b;
442  if (!b.valid) return a;
443  // Otherwise the netdiff and exec of the union is the maximum of the individual values.
444  return {std::max(a.netdiff, b.netdiff), std::max(a.exec, b.exec)};
445  }
446 
448  constexpr friend SatInfo operator+(const SatInfo& a, const SatInfo& b) noexcept
449  {
450  // Concatenation with an empty set yields an empty set.
451  if (!a.valid || !b.valid) return {};
452  // Otherwise, the maximum stack size difference for the combined scripts is the sum of the
453  // netdiffs, and the maximum stack size difference anywhere is either b.exec (if the
454  // maximum occurred in b) or b.netdiff+a.exec (if the maximum occurred in a).
455  return {a.netdiff + b.netdiff, std::max(b.exec, b.netdiff + a.exec)};
456  }
457 
459  static constexpr SatInfo Empty() noexcept { return {0, 0}; }
461  static constexpr SatInfo Push() noexcept { return {-1, 0}; }
463  static constexpr SatInfo Hash() noexcept { return {0, 0}; }
465  static constexpr SatInfo Nop() noexcept { return {0, 0}; }
467  static constexpr SatInfo If() noexcept { return {1, 1}; }
469  static constexpr SatInfo BinaryOp() noexcept { return {1, 1}; }
470 
471  // Scripts for specific individual opcodes.
472  static constexpr SatInfo OP_DUP() noexcept { return {-1, 0}; }
473  static constexpr SatInfo OP_IFDUP(bool nonzero) noexcept { return {nonzero ? -1 : 0, 0}; }
474  static constexpr SatInfo OP_EQUALVERIFY() noexcept { return {2, 2}; }
475  static constexpr SatInfo OP_EQUAL() noexcept { return {1, 1}; }
476  static constexpr SatInfo OP_SIZE() noexcept { return {-1, 0}; }
477  static constexpr SatInfo OP_CHECKSIG() noexcept { return {1, 1}; }
478  static constexpr SatInfo OP_0NOTEQUAL() noexcept { return {0, 0}; }
479  static constexpr SatInfo OP_VERIFY() noexcept { return {1, 1}; }
480 };
481 
482 struct StackSize {
483  const SatInfo sat, dsat;
484 
485  constexpr StackSize(SatInfo in_sat, SatInfo in_dsat) noexcept : sat(in_sat), dsat(in_dsat) {};
486  constexpr StackSize(SatInfo in_both) noexcept : sat(in_both), dsat(in_both) {};
487 };
488 
489 struct WitnessSize {
494 
495  WitnessSize(MaxInt<uint32_t> in_sat, MaxInt<uint32_t> in_dsat) : sat(in_sat), dsat(in_dsat) {};
496 };
497 
498 struct NoDupCheck {};
499 
500 } // namespace internal
501 
503 template<typename Key>
504 struct Node {
508  const uint32_t k = 0;
510  const std::vector<Key> keys;
512  const std::vector<unsigned char> data;
514  mutable std::vector<NodeRef<Key>> subs;
517 
518  /* Destroy the shared pointers iteratively to avoid a stack-overflow due to recursive calls
519  * to the subs' destructors. */
520  ~Node() {
521  while (!subs.empty()) {
522  auto node = std::move(subs.back());
523  subs.pop_back();
524  while (!node->subs.empty()) {
525  subs.push_back(std::move(node->subs.back()));
526  node->subs.pop_back();
527  }
528  }
529  }
530 
532  {
533  // Use TreeEval() to avoid a stack-overflow due to recursion
534  auto upfn = [](const Node& node, Span<NodeRef<Key>> children) {
535  std::vector<NodeRef<Key>> new_subs;
536  for (auto child = children.begin(); child != children.end(); ++child) {
537  new_subs.emplace_back(std::move(*child));
538  }
539  // std::make_unique (and therefore MakeNodeRef) doesn't work on private constructors
540  return std::unique_ptr<Node>{new Node{internal::NoDupCheck{}, node.m_script_ctx, node.fragment, std::move(new_subs), node.keys, node.data, node.k}};
541  };
542  return TreeEval<NodeRef<Key>>(upfn);
543  }
544 
545 private:
553  const Type typ;
555  const size_t scriptlen;
561  mutable std::optional<bool> has_duplicate_keys;
562 
563  // Constructor which takes all of the data that a Node could possibly contain.
564  // This is kept private as no valid fragment has all of these arguments.
565  // Only used by Clone()
566  Node(internal::NoDupCheck, MiniscriptContext script_ctx, Fragment nt, std::vector<NodeRef<Key>> sub, std::vector<Key> key, std::vector<unsigned char> arg, uint32_t val)
567  : fragment(nt), k(val), keys(key), data(std::move(arg)), subs(std::move(sub)), m_script_ctx{script_ctx}, ops(CalcOps()), ss(CalcStackSize()), ws(CalcWitnessSize()), typ(CalcType()), scriptlen(CalcScriptLen()) {}
568 
570  size_t CalcScriptLen() const {
571  size_t subsize = 0;
572  for (const auto& sub : subs) {
573  subsize += sub->ScriptSize();
574  }
575  static constexpr auto NONE_MST{""_mst};
576  Type sub0type = subs.size() > 0 ? subs[0]->GetType() : NONE_MST;
577  return internal::ComputeScriptLen(fragment, sub0type, subsize, k, subs.size(), keys.size(), m_script_ctx);
578  }
579 
580  /* Apply a recursive algorithm to a Miniscript tree, without actual recursive calls.
581  *
582  * The algorithm is defined by two functions: downfn and upfn. Conceptually, the
583  * result can be thought of as first using downfn to compute a "state" for each node,
584  * from the root down to the leaves. Then upfn is used to compute a "result" for each
585  * node, from the leaves back up to the root, which is then returned. In the actual
586  * implementation, both functions are invoked in an interleaved fashion, performing a
587  * depth-first traversal of the tree.
588  *
589  * In more detail, it is invoked as node.TreeEvalMaybe<Result>(root, downfn, upfn):
590  * - root is the state of the root node, of type State.
591  * - downfn is a callable (State&, const Node&, size_t) -> State, which given a
592  * node, its state, and an index of one of its children, computes the state of that
593  * child. It can modify the state. Children of a given node will have downfn()
594  * called in order.
595  * - upfn is a callable (State&&, const Node&, Span<Result>) -> std::optional<Result>,
596  * which given a node, its state, and a Span of the results of its children,
597  * computes the result of the node. If std::nullopt is returned by upfn,
598  * TreeEvalMaybe() immediately returns std::nullopt.
599  * The return value of TreeEvalMaybe is the result of the root node.
600  *
601  * Result type cannot be bool due to the std::vector<bool> specialization.
602  */
603  template<typename Result, typename State, typename DownFn, typename UpFn>
604  std::optional<Result> TreeEvalMaybe(State root_state, DownFn downfn, UpFn upfn) const
605  {
607  struct StackElem
608  {
609  const Node& node;
610  size_t expanded;
611  State state;
612 
613  StackElem(const Node& node_, size_t exp_, State&& state_) :
614  node(node_), expanded(exp_), state(std::move(state_)) {}
615  };
616  /* Stack of tree nodes being explored. */
617  std::vector<StackElem> stack;
618  /* Results of subtrees so far. Their order and mapping to tree nodes
619  * is implicitly defined by stack. */
620  std::vector<Result> results;
621  stack.emplace_back(*this, 0, std::move(root_state));
622 
623  /* Here is a demonstration of the algorithm, for an example tree A(B,C(D,E),F).
624  * State variables are omitted for simplicity.
625  *
626  * First: stack=[(A,0)] results=[]
627  * stack=[(A,1),(B,0)] results=[]
628  * stack=[(A,1)] results=[B]
629  * stack=[(A,2),(C,0)] results=[B]
630  * stack=[(A,2),(C,1),(D,0)] results=[B]
631  * stack=[(A,2),(C,1)] results=[B,D]
632  * stack=[(A,2),(C,2),(E,0)] results=[B,D]
633  * stack=[(A,2),(C,2)] results=[B,D,E]
634  * stack=[(A,2)] results=[B,C]
635  * stack=[(A,3),(F,0)] results=[B,C]
636  * stack=[(A,3)] results=[B,C,F]
637  * Final: stack=[] results=[A]
638  */
639  while (stack.size()) {
640  const Node& node = stack.back().node;
641  if (stack.back().expanded < node.subs.size()) {
642  /* We encounter a tree node with at least one unexpanded child.
643  * Expand it. By the time we hit this node again, the result of
644  * that child (and all earlier children) will be at the end of `results`. */
645  size_t child_index = stack.back().expanded++;
646  State child_state = downfn(stack.back().state, node, child_index);
647  stack.emplace_back(*node.subs[child_index], 0, std::move(child_state));
648  continue;
649  }
650  // Invoke upfn with the last node.subs.size() elements of results as input.
651  assert(results.size() >= node.subs.size());
652  std::optional<Result> result{upfn(std::move(stack.back().state), node,
653  Span<Result>{results}.last(node.subs.size()))};
654  // If evaluation returns std::nullopt, abort immediately.
655  if (!result) return {};
656  // Replace the last node.subs.size() elements of results with the new result.
657  results.erase(results.end() - node.subs.size(), results.end());
658  results.push_back(std::move(*result));
659  stack.pop_back();
660  }
661  // The final remaining results element is the root result, return it.
662  assert(results.size() == 1);
663  return std::move(results[0]);
664  }
665 
668  template<typename Result, typename UpFn>
669  std::optional<Result> TreeEvalMaybe(UpFn upfn) const
670  {
671  struct DummyState {};
672  return TreeEvalMaybe<Result>(DummyState{},
673  [](DummyState, const Node&, size_t) { return DummyState{}; },
674  [&upfn](DummyState, const Node& node, Span<Result> subs) {
675  return upfn(node, subs);
676  }
677  );
678  }
679 
681  template<typename Result, typename State, typename DownFn, typename UpFn>
682  Result TreeEval(State root_state, DownFn&& downfn, UpFn upfn) const
683  {
684  // Invoke TreeEvalMaybe with upfn wrapped to return std::optional<Result>, and then
685  // unconditionally dereference the result (it cannot be std::nullopt).
686  return std::move(*TreeEvalMaybe<Result>(std::move(root_state),
687  std::forward<DownFn>(downfn),
688  [&upfn](State&& state, const Node& node, Span<Result> subs) {
689  Result res{upfn(std::move(state), node, subs)};
690  return std::optional<Result>(std::move(res));
691  }
692  ));
693  }
694 
697  template<typename Result, typename UpFn>
698  Result TreeEval(UpFn upfn) const
699  {
700  struct DummyState {};
701  return std::move(*TreeEvalMaybe<Result>(DummyState{},
702  [](DummyState, const Node&, size_t) { return DummyState{}; },
703  [&upfn](DummyState, const Node& node, Span<Result> subs) {
704  Result res{upfn(node, subs)};
705  return std::optional<Result>(std::move(res));
706  }
707  ));
708  }
709 
711  friend int Compare(const Node<Key>& node1, const Node<Key>& node2)
712  {
713  std::vector<std::pair<const Node<Key>&, const Node<Key>&>> queue;
714  queue.emplace_back(node1, node2);
715  while (!queue.empty()) {
716  const auto& [a, b] = queue.back();
717  queue.pop_back();
718  if (std::tie(a.fragment, a.k, a.keys, a.data) < std::tie(b.fragment, b.k, b.keys, b.data)) return -1;
719  if (std::tie(b.fragment, b.k, b.keys, b.data) < std::tie(a.fragment, a.k, a.keys, a.data)) return 1;
720  if (a.subs.size() < b.subs.size()) return -1;
721  if (b.subs.size() < a.subs.size()) return 1;
722  size_t n = a.subs.size();
723  for (size_t i = 0; i < n; ++i) {
724  queue.emplace_back(*a.subs[n - 1 - i], *b.subs[n - 1 - i]);
725  }
726  }
727  return 0;
728  }
729 
731  Type CalcType() const {
732  using namespace internal;
733 
734  // THRESH has a variable number of subexpressions
735  std::vector<Type> sub_types;
736  if (fragment == Fragment::THRESH) {
737  for (const auto& sub : subs) sub_types.push_back(sub->GetType());
738  }
739  // All other nodes than THRESH can be computed just from the types of the 0-3 subexpressions.
740  static constexpr auto NONE_MST{""_mst};
741  Type x = subs.size() > 0 ? subs[0]->GetType() : NONE_MST;
742  Type y = subs.size() > 1 ? subs[1]->GetType() : NONE_MST;
743  Type z = subs.size() > 2 ? subs[2]->GetType() : NONE_MST;
744 
745  return SanitizeType(ComputeType(fragment, x, y, z, sub_types, k, data.size(), subs.size(), keys.size(), m_script_ctx));
746  }
747 
748 public:
749  template<typename Ctx>
750  CScript ToScript(const Ctx& ctx) const
751  {
752  // To construct the CScript for a Miniscript object, we use the TreeEval algorithm.
753  // The State is a boolean: whether or not the node's script expansion is followed
754  // by an OP_VERIFY (which may need to be combined with the last script opcode).
755  auto downfn = [](bool verify, const Node& node, size_t index) {
756  // For WRAP_V, the subexpression is certainly followed by OP_VERIFY.
757  if (node.fragment == Fragment::WRAP_V) return true;
758  // The subexpression of WRAP_S, and the last subexpression of AND_V
759  // inherit the followed-by-OP_VERIFY property from the parent.
760  if (node.fragment == Fragment::WRAP_S ||
761  (node.fragment == Fragment::AND_V && index == 1)) return verify;
762  return false;
763  };
764  // The upward function computes for a node, given its followed-by-OP_VERIFY status
765  // and the CScripts of its child nodes, the CScript of the node.
766  const bool is_tapscript{IsTapscript(m_script_ctx)};
767  auto upfn = [&ctx, is_tapscript](bool verify, const Node& node, Span<CScript> subs) -> CScript {
768  switch (node.fragment) {
769  case Fragment::PK_K: return BuildScript(ctx.ToPKBytes(node.keys[0]));
770  case Fragment::PK_H: return BuildScript(OP_DUP, OP_HASH160, ctx.ToPKHBytes(node.keys[0]), OP_EQUALVERIFY);
778  case Fragment::WRAP_S: return BuildScript(OP_SWAP, subs[0]);
779  case Fragment::WRAP_C: return BuildScript(std::move(subs[0]), verify ? OP_CHECKSIGVERIFY : OP_CHECKSIG);
781  case Fragment::WRAP_V: {
782  if (node.subs[0]->GetType() << "x"_mst) {
783  return BuildScript(std::move(subs[0]), OP_VERIFY);
784  } else {
785  return std::move(subs[0]);
786  }
787  }
789  case Fragment::WRAP_N: return BuildScript(std::move(subs[0]), OP_0NOTEQUAL);
790  case Fragment::JUST_1: return BuildScript(OP_1);
791  case Fragment::JUST_0: return BuildScript(OP_0);
792  case Fragment::AND_V: return BuildScript(std::move(subs[0]), subs[1]);
793  case Fragment::AND_B: return BuildScript(std::move(subs[0]), subs[1], OP_BOOLAND);
794  case Fragment::OR_B: return BuildScript(std::move(subs[0]), subs[1], OP_BOOLOR);
795  case Fragment::OR_D: return BuildScript(std::move(subs[0]), OP_IFDUP, OP_NOTIF, subs[1], OP_ENDIF);
796  case Fragment::OR_C: return BuildScript(std::move(subs[0]), OP_NOTIF, subs[1], OP_ENDIF);
797  case Fragment::OR_I: return BuildScript(OP_IF, subs[0], OP_ELSE, subs[1], OP_ENDIF);
798  case Fragment::ANDOR: return BuildScript(std::move(subs[0]), OP_NOTIF, subs[2], OP_ELSE, subs[1], OP_ENDIF);
799  case Fragment::MULTI: {
800  CHECK_NONFATAL(!is_tapscript);
802  for (const auto& key : node.keys) {
803  script = BuildScript(std::move(script), ctx.ToPKBytes(key));
804  }
805  return BuildScript(std::move(script), node.keys.size(), verify ? OP_CHECKMULTISIGVERIFY : OP_CHECKMULTISIG);
806  }
807  case Fragment::MULTI_A: {
808  CHECK_NONFATAL(is_tapscript);
809  CScript script = BuildScript(ctx.ToPKBytes(*node.keys.begin()), OP_CHECKSIG);
810  for (auto it = node.keys.begin() + 1; it != node.keys.end(); ++it) {
811  script = BuildScript(std::move(script), ctx.ToPKBytes(*it), OP_CHECKSIGADD);
812  }
813  return BuildScript(std::move(script), node.k, verify ? OP_NUMEQUALVERIFY : OP_NUMEQUAL);
814  }
815  case Fragment::THRESH: {
816  CScript script = std::move(subs[0]);
817  for (size_t i = 1; i < subs.size(); ++i) {
818  script = BuildScript(std::move(script), subs[i], OP_ADD);
819  }
820  return BuildScript(std::move(script), node.k, verify ? OP_EQUALVERIFY : OP_EQUAL);
821  }
822  }
823  assert(false);
824  };
825  return TreeEval<CScript>(false, downfn, upfn);
826  }
827 
828  template<typename CTx>
829  std::optional<std::string> ToString(const CTx& ctx) const {
830  // To construct the std::string representation for a Miniscript object, we use
831  // the TreeEvalMaybe algorithm. The State is a boolean: whether the parent node is a
832  // wrapper. If so, non-wrapper expressions must be prefixed with a ":".
833  auto downfn = [](bool, const Node& node, size_t) {
834  return (node.fragment == Fragment::WRAP_A || node.fragment == Fragment::WRAP_S ||
835  node.fragment == Fragment::WRAP_D || node.fragment == Fragment::WRAP_V ||
836  node.fragment == Fragment::WRAP_J || node.fragment == Fragment::WRAP_N ||
837  node.fragment == Fragment::WRAP_C ||
838  (node.fragment == Fragment::AND_V && node.subs[1]->fragment == Fragment::JUST_1) ||
839  (node.fragment == Fragment::OR_I && node.subs[0]->fragment == Fragment::JUST_0) ||
840  (node.fragment == Fragment::OR_I && node.subs[1]->fragment == Fragment::JUST_0));
841  };
842  // The upward function computes for a node, given whether its parent is a wrapper,
843  // and the string representations of its child nodes, the string representation of the node.
844  const bool is_tapscript{IsTapscript(m_script_ctx)};
845  auto upfn = [&ctx, is_tapscript](bool wrapped, const Node& node, Span<std::string> subs) -> std::optional<std::string> {
846  std::string ret = wrapped ? ":" : "";
847 
848  switch (node.fragment) {
849  case Fragment::WRAP_A: return "a" + std::move(subs[0]);
850  case Fragment::WRAP_S: return "s" + std::move(subs[0]);
851  case Fragment::WRAP_C:
852  if (node.subs[0]->fragment == Fragment::PK_K) {
853  // pk(K) is syntactic sugar for c:pk_k(K)
854  auto key_str = ctx.ToString(node.subs[0]->keys[0]);
855  if (!key_str) return {};
856  return std::move(ret) + "pk(" + std::move(*key_str) + ")";
857  }
858  if (node.subs[0]->fragment == Fragment::PK_H) {
859  // pkh(K) is syntactic sugar for c:pk_h(K)
860  auto key_str = ctx.ToString(node.subs[0]->keys[0]);
861  if (!key_str) return {};
862  return std::move(ret) + "pkh(" + std::move(*key_str) + ")";
863  }
864  return "c" + std::move(subs[0]);
865  case Fragment::WRAP_D: return "d" + std::move(subs[0]);
866  case Fragment::WRAP_V: return "v" + std::move(subs[0]);
867  case Fragment::WRAP_J: return "j" + std::move(subs[0]);
868  case Fragment::WRAP_N: return "n" + std::move(subs[0]);
869  case Fragment::AND_V:
870  // t:X is syntactic sugar for and_v(X,1).
871  if (node.subs[1]->fragment == Fragment::JUST_1) return "t" + std::move(subs[0]);
872  break;
873  case Fragment::OR_I:
874  if (node.subs[0]->fragment == Fragment::JUST_0) return "l" + std::move(subs[1]);
875  if (node.subs[1]->fragment == Fragment::JUST_0) return "u" + std::move(subs[0]);
876  break;
877  default: break;
878  }
879  switch (node.fragment) {
880  case Fragment::PK_K: {
881  auto key_str = ctx.ToString(node.keys[0]);
882  if (!key_str) return {};
883  return std::move(ret) + "pk_k(" + std::move(*key_str) + ")";
884  }
885  case Fragment::PK_H: {
886  auto key_str = ctx.ToString(node.keys[0]);
887  if (!key_str) return {};
888  return std::move(ret) + "pk_h(" + std::move(*key_str) + ")";
889  }
890  case Fragment::AFTER: return std::move(ret) + "after(" + util::ToString(node.k) + ")";
891  case Fragment::OLDER: return std::move(ret) + "older(" + util::ToString(node.k) + ")";
892  case Fragment::HASH256: return std::move(ret) + "hash256(" + HexStr(node.data) + ")";
893  case Fragment::HASH160: return std::move(ret) + "hash160(" + HexStr(node.data) + ")";
894  case Fragment::SHA256: return std::move(ret) + "sha256(" + HexStr(node.data) + ")";
895  case Fragment::RIPEMD160: return std::move(ret) + "ripemd160(" + HexStr(node.data) + ")";
896  case Fragment::JUST_1: return std::move(ret) + "1";
897  case Fragment::JUST_0: return std::move(ret) + "0";
898  case Fragment::AND_V: return std::move(ret) + "and_v(" + std::move(subs[0]) + "," + std::move(subs[1]) + ")";
899  case Fragment::AND_B: return std::move(ret) + "and_b(" + std::move(subs[0]) + "," + std::move(subs[1]) + ")";
900  case Fragment::OR_B: return std::move(ret) + "or_b(" + std::move(subs[0]) + "," + std::move(subs[1]) + ")";
901  case Fragment::OR_D: return std::move(ret) + "or_d(" + std::move(subs[0]) + "," + std::move(subs[1]) + ")";
902  case Fragment::OR_C: return std::move(ret) + "or_c(" + std::move(subs[0]) + "," + std::move(subs[1]) + ")";
903  case Fragment::OR_I: return std::move(ret) + "or_i(" + std::move(subs[0]) + "," + std::move(subs[1]) + ")";
904  case Fragment::ANDOR:
905  // and_n(X,Y) is syntactic sugar for andor(X,Y,0).
906  if (node.subs[2]->fragment == Fragment::JUST_0) return std::move(ret) + "and_n(" + std::move(subs[0]) + "," + std::move(subs[1]) + ")";
907  return std::move(ret) + "andor(" + std::move(subs[0]) + "," + std::move(subs[1]) + "," + std::move(subs[2]) + ")";
908  case Fragment::MULTI: {
909  CHECK_NONFATAL(!is_tapscript);
910  auto str = std::move(ret) + "multi(" + util::ToString(node.k);
911  for (const auto& key : node.keys) {
912  auto key_str = ctx.ToString(key);
913  if (!key_str) return {};
914  str += "," + std::move(*key_str);
915  }
916  return std::move(str) + ")";
917  }
918  case Fragment::MULTI_A: {
919  CHECK_NONFATAL(is_tapscript);
920  auto str = std::move(ret) + "multi_a(" + util::ToString(node.k);
921  for (const auto& key : node.keys) {
922  auto key_str = ctx.ToString(key);
923  if (!key_str) return {};
924  str += "," + std::move(*key_str);
925  }
926  return std::move(str) + ")";
927  }
928  case Fragment::THRESH: {
929  auto str = std::move(ret) + "thresh(" + util::ToString(node.k);
930  for (auto& sub : subs) {
931  str += "," + std::move(sub);
932  }
933  return std::move(str) + ")";
934  }
935  default: break;
936  }
937  assert(false);
938  };
939 
940  return TreeEvalMaybe<std::string>(false, downfn, upfn);
941  }
942 
943 private:
945  switch (fragment) {
946  case Fragment::JUST_1: return {0, 0, {}};
947  case Fragment::JUST_0: return {0, {}, 0};
948  case Fragment::PK_K: return {0, 0, 0};
949  case Fragment::PK_H: return {3, 0, 0};
950  case Fragment::OLDER:
951  case Fragment::AFTER: return {1, 0, {}};
952  case Fragment::SHA256:
953  case Fragment::RIPEMD160:
954  case Fragment::HASH256:
955  case Fragment::HASH160: return {4, 0, {}};
956  case Fragment::AND_V: return {subs[0]->ops.count + subs[1]->ops.count, subs[0]->ops.sat + subs[1]->ops.sat, {}};
957  case Fragment::AND_B: {
958  const auto count{1 + subs[0]->ops.count + subs[1]->ops.count};
959  const auto sat{subs[0]->ops.sat + subs[1]->ops.sat};
960  const auto dsat{subs[0]->ops.dsat + subs[1]->ops.dsat};
961  return {count, sat, dsat};
962  }
963  case Fragment::OR_B: {
964  const auto count{1 + subs[0]->ops.count + subs[1]->ops.count};
965  const auto sat{(subs[0]->ops.sat + subs[1]->ops.dsat) | (subs[1]->ops.sat + subs[0]->ops.dsat)};
966  const auto dsat{subs[0]->ops.dsat + subs[1]->ops.dsat};
967  return {count, sat, dsat};
968  }
969  case Fragment::OR_D: {
970  const auto count{3 + subs[0]->ops.count + subs[1]->ops.count};
971  const auto sat{subs[0]->ops.sat | (subs[1]->ops.sat + subs[0]->ops.dsat)};
972  const auto dsat{subs[0]->ops.dsat + subs[1]->ops.dsat};
973  return {count, sat, dsat};
974  }
975  case Fragment::OR_C: {
976  const auto count{2 + subs[0]->ops.count + subs[1]->ops.count};
977  const auto sat{subs[0]->ops.sat | (subs[1]->ops.sat + subs[0]->ops.dsat)};
978  return {count, sat, {}};
979  }
980  case Fragment::OR_I: {
981  const auto count{3 + subs[0]->ops.count + subs[1]->ops.count};
982  const auto sat{subs[0]->ops.sat | subs[1]->ops.sat};
983  const auto dsat{subs[0]->ops.dsat | subs[1]->ops.dsat};
984  return {count, sat, dsat};
985  }
986  case Fragment::ANDOR: {
987  const auto count{3 + subs[0]->ops.count + subs[1]->ops.count + subs[2]->ops.count};
988  const auto sat{(subs[1]->ops.sat + subs[0]->ops.sat) | (subs[0]->ops.dsat + subs[2]->ops.sat)};
989  const auto dsat{subs[0]->ops.dsat + subs[2]->ops.dsat};
990  return {count, sat, dsat};
991  }
992  case Fragment::MULTI: return {1, (uint32_t)keys.size(), (uint32_t)keys.size()};
993  case Fragment::MULTI_A: return {(uint32_t)keys.size() + 1, 0, 0};
994  case Fragment::WRAP_S:
995  case Fragment::WRAP_C:
996  case Fragment::WRAP_N: return {1 + subs[0]->ops.count, subs[0]->ops.sat, subs[0]->ops.dsat};
997  case Fragment::WRAP_A: return {2 + subs[0]->ops.count, subs[0]->ops.sat, subs[0]->ops.dsat};
998  case Fragment::WRAP_D: return {3 + subs[0]->ops.count, subs[0]->ops.sat, 0};
999  case Fragment::WRAP_J: return {4 + subs[0]->ops.count, subs[0]->ops.sat, 0};
1000  case Fragment::WRAP_V: return {subs[0]->ops.count + (subs[0]->GetType() << "x"_mst), subs[0]->ops.sat, {}};
1001  case Fragment::THRESH: {
1002  uint32_t count = 0;
1003  auto sats = Vector(internal::MaxInt<uint32_t>(0));
1004  for (const auto& sub : subs) {
1005  count += sub->ops.count + 1;
1006  auto next_sats = Vector(sats[0] + sub->ops.dsat);
1007  for (size_t j = 1; j < sats.size(); ++j) next_sats.push_back((sats[j] + sub->ops.dsat) | (sats[j - 1] + sub->ops.sat));
1008  next_sats.push_back(sats[sats.size() - 1] + sub->ops.sat);
1009  sats = std::move(next_sats);
1010  }
1011  assert(k <= sats.size());
1012  return {count, sats[k], sats[0]};
1013  }
1014  }
1015  assert(false);
1016  }
1017 
1019  using namespace internal;
1020  switch (fragment) {
1021  case Fragment::JUST_0: return {{}, SatInfo::Push()};
1022  case Fragment::JUST_1: return {SatInfo::Push(), {}};
1023  case Fragment::OLDER:
1024  case Fragment::AFTER: return {SatInfo::Push() + SatInfo::Nop(), {}};
1025  case Fragment::PK_K: return {SatInfo::Push()};
1026  case Fragment::PK_H: return {SatInfo::OP_DUP() + SatInfo::Hash() + SatInfo::Push() + SatInfo::OP_EQUALVERIFY()};
1027  case Fragment::SHA256:
1028  case Fragment::RIPEMD160:
1029  case Fragment::HASH256:
1030  case Fragment::HASH160: return {
1031  SatInfo::OP_SIZE() + SatInfo::Push() + SatInfo::OP_EQUALVERIFY() + SatInfo::Hash() + SatInfo::Push() + SatInfo::OP_EQUAL(),
1032  {}
1033  };
1034  case Fragment::ANDOR: {
1035  const auto& x{subs[0]->ss};
1036  const auto& y{subs[1]->ss};
1037  const auto& z{subs[2]->ss};
1038  return {
1039  (x.sat + SatInfo::If() + y.sat) | (x.dsat + SatInfo::If() + z.sat),
1040  x.dsat + SatInfo::If() + z.dsat
1041  };
1042  }
1043  case Fragment::AND_V: {
1044  const auto& x{subs[0]->ss};
1045  const auto& y{subs[1]->ss};
1046  return {x.sat + y.sat, {}};
1047  }
1048  case Fragment::AND_B: {
1049  const auto& x{subs[0]->ss};
1050  const auto& y{subs[1]->ss};
1051  return {x.sat + y.sat + SatInfo::BinaryOp(), x.dsat + y.dsat + SatInfo::BinaryOp()};
1052  }
1053  case Fragment::OR_B: {
1054  const auto& x{subs[0]->ss};
1055  const auto& y{subs[1]->ss};
1056  return {
1057  ((x.sat + y.dsat) | (x.dsat + y.sat)) + SatInfo::BinaryOp(),
1058  x.dsat + y.dsat + SatInfo::BinaryOp()
1059  };
1060  }
1061  case Fragment::OR_C: {
1062  const auto& x{subs[0]->ss};
1063  const auto& y{subs[1]->ss};
1064  return {(x.sat + SatInfo::If()) | (x.dsat + SatInfo::If() + y.sat), {}};
1065  }
1066  case Fragment::OR_D: {
1067  const auto& x{subs[0]->ss};
1068  const auto& y{subs[1]->ss};
1069  return {
1070  (x.sat + SatInfo::OP_IFDUP(true) + SatInfo::If()) | (x.dsat + SatInfo::OP_IFDUP(false) + SatInfo::If() + y.sat),
1071  x.dsat + SatInfo::OP_IFDUP(false) + SatInfo::If() + y.dsat
1072  };
1073  }
1074  case Fragment::OR_I: {
1075  const auto& x{subs[0]->ss};
1076  const auto& y{subs[1]->ss};
1077  return {SatInfo::If() + (x.sat | y.sat), SatInfo::If() + (x.dsat | y.dsat)};
1078  }
1079  // multi(k, key1, key2, ..., key_n) starts off with k+1 stack elements (a 0, plus k
1080  // signatures), then reaches n+k+3 stack elements after pushing the n keys, plus k and
1081  // n itself, and ends with 1 stack element (success or failure). Thus, it net removes
1082  // k elements (from k+1 to 1), while reaching k+n+2 more than it ends with.
1083  case Fragment::MULTI: return {SatInfo(k, k + keys.size() + 2)};
1084  // multi_a(k, key1, key2, ..., key_n) starts off with n stack elements (the
1085  // signatures), reaches 1 more (after the first key push), and ends with 1. Thus it net
1086  // removes n-1 elements (from n to 1) while reaching n more than it ends with.
1087  case Fragment::MULTI_A: return {SatInfo(keys.size() - 1, keys.size())};
1088  case Fragment::WRAP_A:
1089  case Fragment::WRAP_N:
1090  case Fragment::WRAP_S: return subs[0]->ss;
1091  case Fragment::WRAP_C: return {
1092  subs[0]->ss.sat + SatInfo::OP_CHECKSIG(),
1093  subs[0]->ss.dsat + SatInfo::OP_CHECKSIG()
1094  };
1095  case Fragment::WRAP_D: return {
1096  SatInfo::OP_DUP() + SatInfo::If() + subs[0]->ss.sat,
1097  SatInfo::OP_DUP() + SatInfo::If()
1098  };
1099  case Fragment::WRAP_V: return {subs[0]->ss.sat + SatInfo::OP_VERIFY(), {}};
1100  case Fragment::WRAP_J: return {
1101  SatInfo::OP_SIZE() + SatInfo::OP_0NOTEQUAL() + SatInfo::If() + subs[0]->ss.sat,
1102  SatInfo::OP_SIZE() + SatInfo::OP_0NOTEQUAL() + SatInfo::If()
1103  };
1104  case Fragment::THRESH: {
1105  // sats[j] is the SatInfo corresponding to all traces reaching j satisfactions.
1106  auto sats = Vector(SatInfo::Empty());
1107  for (size_t i = 0; i < subs.size(); ++i) {
1108  // Loop over the subexpressions, processing them one by one. After adding
1109  // element i we need to add OP_ADD (if i>0).
1110  auto add = i ? SatInfo::BinaryOp() : SatInfo::Empty();
1111  // Construct a variable that will become the next sats, starting with index 0.
1112  auto next_sats = Vector(sats[0] + subs[i]->ss.dsat + add);
1113  // Then loop to construct next_sats[1..i].
1114  for (size_t j = 1; j < sats.size(); ++j) {
1115  next_sats.push_back(((sats[j] + subs[i]->ss.dsat) | (sats[j - 1] + subs[i]->ss.sat)) + add);
1116  }
1117  // Finally construct next_sats[i+1].
1118  next_sats.push_back(sats[sats.size() - 1] + subs[i]->ss.sat + add);
1119  // Switch over.
1120  sats = std::move(next_sats);
1121  }
1122  // To satisfy thresh we need k satisfactions; to dissatisfy we need 0. In both
1123  // cases a push of k and an OP_EQUAL follow.
1124  return {
1125  sats[k] + SatInfo::Push() + SatInfo::OP_EQUAL(),
1126  sats[0] + SatInfo::Push() + SatInfo::OP_EQUAL()
1127  };
1128  }
1129  }
1130  assert(false);
1131  }
1132 
1134  const uint32_t sig_size = IsTapscript(m_script_ctx) ? 1 + 65 : 1 + 72;
1135  const uint32_t pubkey_size = IsTapscript(m_script_ctx) ? 1 + 32 : 1 + 33;
1136  switch (fragment) {
1137  case Fragment::JUST_0: return {{}, 0};
1138  case Fragment::JUST_1:
1139  case Fragment::OLDER:
1140  case Fragment::AFTER: return {0, {}};
1141  case Fragment::PK_K: return {sig_size, 1};
1142  case Fragment::PK_H: return {sig_size + pubkey_size, 1 + pubkey_size};
1143  case Fragment::SHA256:
1144  case Fragment::RIPEMD160:
1145  case Fragment::HASH256:
1146  case Fragment::HASH160: return {1 + 32, {}};
1147  case Fragment::ANDOR: {
1148  const auto sat{(subs[0]->ws.sat + subs[1]->ws.sat) | (subs[0]->ws.dsat + subs[2]->ws.sat)};
1149  const auto dsat{subs[0]->ws.dsat + subs[2]->ws.dsat};
1150  return {sat, dsat};
1151  }
1152  case Fragment::AND_V: return {subs[0]->ws.sat + subs[1]->ws.sat, {}};
1153  case Fragment::AND_B: return {subs[0]->ws.sat + subs[1]->ws.sat, subs[0]->ws.dsat + subs[1]->ws.dsat};
1154  case Fragment::OR_B: {
1155  const auto sat{(subs[0]->ws.dsat + subs[1]->ws.sat) | (subs[0]->ws.sat + subs[1]->ws.dsat)};
1156  const auto dsat{subs[0]->ws.dsat + subs[1]->ws.dsat};
1157  return {sat, dsat};
1158  }
1159  case Fragment::OR_C: return {subs[0]->ws.sat | (subs[0]->ws.dsat + subs[1]->ws.sat), {}};
1160  case Fragment::OR_D: return {subs[0]->ws.sat | (subs[0]->ws.dsat + subs[1]->ws.sat), subs[0]->ws.dsat + subs[1]->ws.dsat};
1161  case Fragment::OR_I: return {(subs[0]->ws.sat + 1 + 1) | (subs[1]->ws.sat + 1), (subs[0]->ws.dsat + 1 + 1) | (subs[1]->ws.dsat + 1)};
1162  case Fragment::MULTI: return {k * sig_size + 1, k + 1};
1163  case Fragment::MULTI_A: return {k * sig_size + static_cast<uint32_t>(keys.size()) - k, static_cast<uint32_t>(keys.size())};
1164  case Fragment::WRAP_A:
1165  case Fragment::WRAP_N:
1166  case Fragment::WRAP_S:
1167  case Fragment::WRAP_C: return subs[0]->ws;
1168  case Fragment::WRAP_D: return {1 + 1 + subs[0]->ws.sat, 1};
1169  case Fragment::WRAP_V: return {subs[0]->ws.sat, {}};
1170  case Fragment::WRAP_J: return {subs[0]->ws.sat, 1};
1171  case Fragment::THRESH: {
1172  auto sats = Vector(internal::MaxInt<uint32_t>(0));
1173  for (const auto& sub : subs) {
1174  auto next_sats = Vector(sats[0] + sub->ws.dsat);
1175  for (size_t j = 1; j < sats.size(); ++j) next_sats.push_back((sats[j] + sub->ws.dsat) | (sats[j - 1] + sub->ws.sat));
1176  next_sats.push_back(sats[sats.size() - 1] + sub->ws.sat);
1177  sats = std::move(next_sats);
1178  }
1179  assert(k <= sats.size());
1180  return {sats[k], sats[0]};
1181  }
1182  }
1183  assert(false);
1184  }
1185 
1186  template<typename Ctx>
1187  internal::InputResult ProduceInput(const Ctx& ctx) const {
1188  using namespace internal;
1189 
1190  // Internal function which is invoked for every tree node, constructing satisfaction/dissatisfactions
1191  // given those of its subnodes.
1192  auto helper = [&ctx](const Node& node, Span<InputResult> subres) -> InputResult {
1193  switch (node.fragment) {
1194  case Fragment::PK_K: {
1195  std::vector<unsigned char> sig;
1196  Availability avail = ctx.Sign(node.keys[0], sig);
1197  return {ZERO, InputStack(std::move(sig)).SetWithSig().SetAvailable(avail)};
1198  }
1199  case Fragment::PK_H: {
1200  std::vector<unsigned char> key = ctx.ToPKBytes(node.keys[0]), sig;
1201  Availability avail = ctx.Sign(node.keys[0], sig);
1202  return {ZERO + InputStack(key), (InputStack(std::move(sig)).SetWithSig() + InputStack(key)).SetAvailable(avail)};
1203  }
1204  case Fragment::MULTI_A: {
1205  // sats[j] represents the best stack containing j valid signatures (out of the first i keys).
1206  // In the loop below, these stacks are built up using a dynamic programming approach.
1207  std::vector<InputStack> sats = Vector(EMPTY);
1208  for (size_t i = 0; i < node.keys.size(); ++i) {
1209  // Get the signature for the i'th key in reverse order (the signature for the first key needs to
1210  // be at the top of the stack, contrary to CHECKMULTISIG's satisfaction).
1211  std::vector<unsigned char> sig;
1212  Availability avail = ctx.Sign(node.keys[node.keys.size() - 1 - i], sig);
1213  // Compute signature stack for just this key.
1214  auto sat = InputStack(std::move(sig)).SetWithSig().SetAvailable(avail);
1215  // Compute the next sats vector: next_sats[0] is a copy of sats[0] (no signatures). All further
1216  // next_sats[j] are equal to either the existing sats[j] + ZERO, or sats[j-1] plus a signature
1217  // for the current (i'th) key. The very last element needs all signatures filled.
1218  std::vector<InputStack> next_sats;
1219  next_sats.push_back(sats[0] + ZERO);
1220  for (size_t j = 1; j < sats.size(); ++j) next_sats.push_back((sats[j] + ZERO) | (std::move(sats[j - 1]) + sat));
1221  next_sats.push_back(std::move(sats[sats.size() - 1]) + std::move(sat));
1222  // Switch over.
1223  sats = std::move(next_sats);
1224  }
1225  // The dissatisfaction consists of as many empty vectors as there are keys, which is the same as
1226  // satisfying 0 keys.
1227  auto& nsat{sats[0]};
1228  assert(node.k != 0);
1229  assert(node.k <= sats.size());
1230  return {std::move(nsat), std::move(sats[node.k])};
1231  }
1232  case Fragment::MULTI: {
1233  // sats[j] represents the best stack containing j valid signatures (out of the first i keys).
1234  // In the loop below, these stacks are built up using a dynamic programming approach.
1235  // sats[0] starts off being {0}, due to the CHECKMULTISIG bug that pops off one element too many.
1236  std::vector<InputStack> sats = Vector(ZERO);
1237  for (size_t i = 0; i < node.keys.size(); ++i) {
1238  std::vector<unsigned char> sig;
1239  Availability avail = ctx.Sign(node.keys[i], sig);
1240  // Compute signature stack for just the i'th key.
1241  auto sat = InputStack(std::move(sig)).SetWithSig().SetAvailable(avail);
1242  // Compute the next sats vector: next_sats[0] is a copy of sats[0] (no signatures). All further
1243  // next_sats[j] are equal to either the existing sats[j], or sats[j-1] plus a signature for the
1244  // current (i'th) key. The very last element needs all signatures filled.
1245  std::vector<InputStack> next_sats;
1246  next_sats.push_back(sats[0]);
1247  for (size_t j = 1; j < sats.size(); ++j) next_sats.push_back(sats[j] | (std::move(sats[j - 1]) + sat));
1248  next_sats.push_back(std::move(sats[sats.size() - 1]) + std::move(sat));
1249  // Switch over.
1250  sats = std::move(next_sats);
1251  }
1252  // The dissatisfaction consists of k+1 stack elements all equal to 0.
1253  InputStack nsat = ZERO;
1254  for (size_t i = 0; i < node.k; ++i) nsat = std::move(nsat) + ZERO;
1255  assert(node.k <= sats.size());
1256  return {std::move(nsat), std::move(sats[node.k])};
1257  }
1258  case Fragment::THRESH: {
1259  // sats[k] represents the best stack that satisfies k out of the *last* i subexpressions.
1260  // In the loop below, these stacks are built up using a dynamic programming approach.
1261  // sats[0] starts off empty.
1262  std::vector<InputStack> sats = Vector(EMPTY);
1263  for (size_t i = 0; i < subres.size(); ++i) {
1264  // Introduce an alias for the i'th last satisfaction/dissatisfaction.
1265  auto& res = subres[subres.size() - i - 1];
1266  // Compute the next sats vector: next_sats[0] is sats[0] plus res.nsat (thus containing all dissatisfactions
1267  // so far. next_sats[j] is either sats[j] + res.nsat (reusing j earlier satisfactions) or sats[j-1] + res.sat
1268  // (reusing j-1 earlier satisfactions plus a new one). The very last next_sats[j] is all satisfactions.
1269  std::vector<InputStack> next_sats;
1270  next_sats.push_back(sats[0] + res.nsat);
1271  for (size_t j = 1; j < sats.size(); ++j) next_sats.push_back((sats[j] + res.nsat) | (std::move(sats[j - 1]) + res.sat));
1272  next_sats.push_back(std::move(sats[sats.size() - 1]) + std::move(res.sat));
1273  // Switch over.
1274  sats = std::move(next_sats);
1275  }
1276  // At this point, sats[k].sat is the best satisfaction for the overall thresh() node. The best dissatisfaction
1277  // is computed by gathering all sats[i].nsat for i != k.
1278  InputStack nsat = INVALID;
1279  for (size_t i = 0; i < sats.size(); ++i) {
1280  // i==k is the satisfaction; i==0 is the canonical dissatisfaction;
1281  // the rest are non-canonical (a no-signature dissatisfaction - the i=0
1282  // form - is always available) and malleable (due to overcompleteness).
1283  // Marking the solutions malleable here is not strictly necessary, as they
1284  // should already never be picked in non-malleable solutions due to the
1285  // availability of the i=0 form.
1286  if (i != 0 && i != node.k) sats[i].SetMalleable().SetNonCanon();
1287  // Include all dissatisfactions (even these non-canonical ones) in nsat.
1288  if (i != node.k) nsat = std::move(nsat) | std::move(sats[i]);
1289  }
1290  assert(node.k <= sats.size());
1291  return {std::move(nsat), std::move(sats[node.k])};
1292  }
1293  case Fragment::OLDER: {
1294  return {INVALID, ctx.CheckOlder(node.k) ? EMPTY : INVALID};
1295  }
1296  case Fragment::AFTER: {
1297  return {INVALID, ctx.CheckAfter(node.k) ? EMPTY : INVALID};
1298  }
1299  case Fragment::SHA256: {
1300  std::vector<unsigned char> preimage;
1301  Availability avail = ctx.SatSHA256(node.data, preimage);
1302  return {ZERO32, InputStack(std::move(preimage)).SetAvailable(avail)};
1303  }
1304  case Fragment::RIPEMD160: {
1305  std::vector<unsigned char> preimage;
1306  Availability avail = ctx.SatRIPEMD160(node.data, preimage);
1307  return {ZERO32, InputStack(std::move(preimage)).SetAvailable(avail)};
1308  }
1309  case Fragment::HASH256: {
1310  std::vector<unsigned char> preimage;
1311  Availability avail = ctx.SatHASH256(node.data, preimage);
1312  return {ZERO32, InputStack(std::move(preimage)).SetAvailable(avail)};
1313  }
1314  case Fragment::HASH160: {
1315  std::vector<unsigned char> preimage;
1316  Availability avail = ctx.SatHASH160(node.data, preimage);
1317  return {ZERO32, InputStack(std::move(preimage)).SetAvailable(avail)};
1318  }
1319  case Fragment::AND_V: {
1320  auto& x = subres[0], &y = subres[1];
1321  // As the dissatisfaction here only consist of a single option, it doesn't
1322  // actually need to be listed (it's not required for reasoning about malleability of
1323  // other options), and is never required (no valid miniscript relies on the ability
1324  // to satisfy the type V left subexpression). It's still listed here for
1325  // completeness, as a hypothetical (not currently implemented) satisfier that doesn't
1326  // care about malleability might in some cases prefer it still.
1327  return {(y.nsat + x.sat).SetNonCanon(), y.sat + x.sat};
1328  }
1329  case Fragment::AND_B: {
1330  auto& x = subres[0], &y = subres[1];
1331  // Note that it is not strictly necessary to mark the 2nd and 3rd dissatisfaction here
1332  // as malleable. While they are definitely malleable, they are also non-canonical due
1333  // to the guaranteed existence of a no-signature other dissatisfaction (the 1st)
1334  // option. Because of that, the 2nd and 3rd option will never be chosen, even if they
1335  // weren't marked as malleable.
1336  return {(y.nsat + x.nsat) | (y.sat + x.nsat).SetMalleable().SetNonCanon() | (y.nsat + x.sat).SetMalleable().SetNonCanon(), y.sat + x.sat};
1337  }
1338  case Fragment::OR_B: {
1339  auto& x = subres[0], &z = subres[1];
1340  // The (sat(Z) sat(X)) solution is overcomplete (attacker can change either into dsat).
1341  return {z.nsat + x.nsat, (z.nsat + x.sat) | (z.sat + x.nsat) | (z.sat + x.sat).SetMalleable().SetNonCanon()};
1342  }
1343  case Fragment::OR_C: {
1344  auto& x = subres[0], &z = subres[1];
1345  return {INVALID, std::move(x.sat) | (z.sat + x.nsat)};
1346  }
1347  case Fragment::OR_D: {
1348  auto& x = subres[0], &z = subres[1];
1349  return {z.nsat + x.nsat, std::move(x.sat) | (z.sat + x.nsat)};
1350  }
1351  case Fragment::OR_I: {
1352  auto& x = subres[0], &z = subres[1];
1353  return {(x.nsat + ONE) | (z.nsat + ZERO), (x.sat + ONE) | (z.sat + ZERO)};
1354  }
1355  case Fragment::ANDOR: {
1356  auto& x = subres[0], &y = subres[1], &z = subres[2];
1357  return {(y.nsat + x.sat).SetNonCanon() | (z.nsat + x.nsat), (y.sat + x.sat) | (z.sat + x.nsat)};
1358  }
1359  case Fragment::WRAP_A:
1360  case Fragment::WRAP_S:
1361  case Fragment::WRAP_C:
1362  case Fragment::WRAP_N:
1363  return std::move(subres[0]);
1364  case Fragment::WRAP_D: {
1365  auto &x = subres[0];
1366  return {ZERO, x.sat + ONE};
1367  }
1368  case Fragment::WRAP_J: {
1369  auto &x = subres[0];
1370  // If a dissatisfaction with a nonzero top stack element exists, an alternative dissatisfaction exists.
1371  // As the dissatisfaction logic currently doesn't keep track of this nonzeroness property, and thus even
1372  // if a dissatisfaction with a top zero element is found, we don't know whether another one with a
1373  // nonzero top stack element exists. Make the conservative assumption that whenever the subexpression is weakly
1374  // dissatisfiable, this alternative dissatisfaction exists and leads to malleability.
1375  return {InputStack(ZERO).SetMalleable(x.nsat.available != Availability::NO && !x.nsat.has_sig), std::move(x.sat)};
1376  }
1377  case Fragment::WRAP_V: {
1378  auto &x = subres[0];
1379  return {INVALID, std::move(x.sat)};
1380  }
1381  case Fragment::JUST_0: return {EMPTY, INVALID};
1382  case Fragment::JUST_1: return {INVALID, EMPTY};
1383  }
1384  assert(false);
1385  return {INVALID, INVALID};
1386  };
1387 
1388  auto tester = [&helper](const Node& node, Span<InputResult> subres) -> InputResult {
1389  auto ret = helper(node, subres);
1390 
1391  // Do a consistency check between the satisfaction code and the type checker
1392  // (the actual satisfaction code in ProduceInputHelper does not use GetType)
1393 
1394  // For 'z' nodes, available satisfactions/dissatisfactions must have stack size 0.
1395  if (node.GetType() << "z"_mst && ret.nsat.available != Availability::NO) assert(ret.nsat.stack.size() == 0);
1396  if (node.GetType() << "z"_mst && ret.sat.available != Availability::NO) assert(ret.sat.stack.size() == 0);
1397 
1398  // For 'o' nodes, available satisfactions/dissatisfactions must have stack size 1.
1399  if (node.GetType() << "o"_mst && ret.nsat.available != Availability::NO) assert(ret.nsat.stack.size() == 1);
1400  if (node.GetType() << "o"_mst && ret.sat.available != Availability::NO) assert(ret.sat.stack.size() == 1);
1401 
1402  // For 'n' nodes, available satisfactions/dissatisfactions must have stack size 1 or larger. For satisfactions,
1403  // the top element cannot be 0.
1404  if (node.GetType() << "n"_mst && ret.sat.available != Availability::NO) assert(ret.sat.stack.size() >= 1);
1405  if (node.GetType() << "n"_mst && ret.nsat.available != Availability::NO) assert(ret.nsat.stack.size() >= 1);
1406  if (node.GetType() << "n"_mst && ret.sat.available != Availability::NO) assert(!ret.sat.stack.back().empty());
1407 
1408  // For 'd' nodes, a dissatisfaction must exist, and they must not need a signature. If it is non-malleable,
1409  // it must be canonical.
1410  if (node.GetType() << "d"_mst) assert(ret.nsat.available != Availability::NO);
1411  if (node.GetType() << "d"_mst) assert(!ret.nsat.has_sig);
1412  if (node.GetType() << "d"_mst && !ret.nsat.malleable) assert(!ret.nsat.non_canon);
1413 
1414  // For 'f'/'s' nodes, dissatisfactions/satisfactions must have a signature.
1415  if (node.GetType() << "f"_mst && ret.nsat.available != Availability::NO) assert(ret.nsat.has_sig);
1416  if (node.GetType() << "s"_mst && ret.sat.available != Availability::NO) assert(ret.sat.has_sig);
1417 
1418  // For non-malleable 'e' nodes, a non-malleable dissatisfaction must exist.
1419  if (node.GetType() << "me"_mst) assert(ret.nsat.available != Availability::NO);
1420  if (node.GetType() << "me"_mst) assert(!ret.nsat.malleable);
1421 
1422  // For 'm' nodes, if a satisfaction exists, it must be non-malleable.
1423  if (node.GetType() << "m"_mst && ret.sat.available != Availability::NO) assert(!ret.sat.malleable);
1424 
1425  // If a non-malleable satisfaction exists, it must be canonical.
1426  if (ret.sat.available != Availability::NO && !ret.sat.malleable) assert(!ret.sat.non_canon);
1427 
1428  return ret;
1429  };
1430 
1431  return TreeEval<InputResult>(tester);
1432  }
1433 
1434 public:
1440  template<typename Ctx> void DuplicateKeyCheck(const Ctx& ctx) const
1441  {
1442  // We cannot use a lambda here, as lambdas are non assignable, and the set operations
1443  // below require moving the comparators around.
1444  struct Comp {
1445  const Ctx* ctx_ptr;
1446  Comp(const Ctx& ctx) : ctx_ptr(&ctx) {}
1447  bool operator()(const Key& a, const Key& b) const { return ctx_ptr->KeyCompare(a, b); }
1448  };
1449 
1450  // state in the recursive computation:
1451  // - std::nullopt means "this node has duplicates"
1452  // - an std::set means "this node has no duplicate keys, and they are: ...".
1453  using keyset = std::set<Key, Comp>;
1454  using state = std::optional<keyset>;
1455 
1456  auto upfn = [&ctx](const Node& node, Span<state> subs) -> state {
1457  // If this node is already known to have duplicates, nothing left to do.
1458  if (node.has_duplicate_keys.has_value() && *node.has_duplicate_keys) return {};
1459 
1460  // Check if one of the children is already known to have duplicates.
1461  for (auto& sub : subs) {
1462  if (!sub.has_value()) {
1463  node.has_duplicate_keys = true;
1464  return {};
1465  }
1466  }
1467 
1468  // Start building the set of keys involved in this node and children.
1469  // Start by keys in this node directly.
1470  size_t keys_count = node.keys.size();
1471  keyset key_set{node.keys.begin(), node.keys.end(), Comp(ctx)};
1472  if (key_set.size() != keys_count) {
1473  // It already has duplicates; bail out.
1474  node.has_duplicate_keys = true;
1475  return {};
1476  }
1477 
1478  // Merge the keys from the children into this set.
1479  for (auto& sub : subs) {
1480  keys_count += sub->size();
1481  // Small optimization: std::set::merge is linear in the size of the second arg but
1482  // logarithmic in the size of the first.
1483  if (key_set.size() < sub->size()) std::swap(key_set, *sub);
1484  key_set.merge(*sub);
1485  if (key_set.size() != keys_count) {
1486  node.has_duplicate_keys = true;
1487  return {};
1488  }
1489  }
1490 
1491  node.has_duplicate_keys = false;
1492  return key_set;
1493  };
1494 
1495  TreeEval<state>(upfn);
1496  }
1497 
1499  size_t ScriptSize() const { return scriptlen; }
1500 
1502  std::optional<uint32_t> GetOps() const {
1503  if (!ops.sat.valid) return {};
1504  return ops.count + ops.sat.value;
1505  }
1506 
1508  uint32_t GetStaticOps() const { return ops.count; }
1509 
1511  bool CheckOpsLimit() const {
1512  if (IsTapscript(m_script_ctx)) return true;
1513  if (const auto ops = GetOps()) return *ops <= MAX_OPS_PER_SCRIPT;
1514  return true;
1515  }
1516 
1518  bool IsBKW() const {
1519  return !((GetType() & "BKW"_mst) == ""_mst);
1520  }
1521 
1523  std::optional<uint32_t> GetStackSize() const {
1524  if (!ss.sat.valid) return {};
1525  return ss.sat.netdiff + static_cast<int32_t>(IsBKW());
1526  }
1527 
1529  std::optional<uint32_t> GetExecStackSize() const {
1530  if (!ss.sat.valid) return {};
1531  return ss.sat.exec + static_cast<int32_t>(IsBKW());
1532  }
1533 
1535  bool CheckStackSize() const {
1536  // Since in Tapscript there is no standardness limit on the script and witness sizes, we may run
1537  // into the maximum stack size while executing the script. Make sure it doesn't happen.
1538  if (IsTapscript(m_script_ctx)) {
1539  if (const auto exec_ss = GetExecStackSize()) return exec_ss <= MAX_STACK_SIZE;
1540  return true;
1541  }
1542  if (const auto ss = GetStackSize()) return *ss <= MAX_STANDARD_P2WSH_STACK_ITEMS;
1543  return true;
1544  }
1545 
1547  bool IsNotSatisfiable() const { return !GetStackSize(); }
1548 
1551  std::optional<uint32_t> GetWitnessSize() const {
1552  if (!ws.sat.valid) return {};
1553  return ws.sat.value;
1554  }
1555 
1557  Type GetType() const { return typ; }
1558 
1561 
1563  const Node* FindInsaneSub() const {
1564  return TreeEval<const Node*>([](const Node& node, Span<const Node*> subs) -> const Node* {
1565  for (auto& sub: subs) if (sub) return sub;
1566  if (!node.IsSaneSubexpression()) return &node;
1567  return nullptr;
1568  });
1569  }
1570 
1573  template<typename F>
1574  bool IsSatisfiable(F fn) const
1575  {
1576  // TreeEval() doesn't support bool as NodeType, so use int instead.
1577  return TreeEval<int>([&fn](const Node& node, Span<int> subs) -> bool {
1578  switch (node.fragment) {
1579  case Fragment::JUST_0:
1580  return false;
1581  case Fragment::JUST_1:
1582  return true;
1583  case Fragment::PK_K:
1584  case Fragment::PK_H:
1585  case Fragment::MULTI:
1586  case Fragment::MULTI_A:
1587  case Fragment::AFTER:
1588  case Fragment::OLDER:
1589  case Fragment::HASH256:
1590  case Fragment::HASH160:
1591  case Fragment::SHA256:
1592  case Fragment::RIPEMD160:
1593  return bool{fn(node)};
1594  case Fragment::ANDOR:
1595  return (subs[0] && subs[1]) || subs[2];
1596  case Fragment::AND_V:
1597  case Fragment::AND_B:
1598  return subs[0] && subs[1];
1599  case Fragment::OR_B:
1600  case Fragment::OR_C:
1601  case Fragment::OR_D:
1602  case Fragment::OR_I:
1603  return subs[0] || subs[1];
1604  case Fragment::THRESH:
1605  return static_cast<uint32_t>(std::count(subs.begin(), subs.end(), true)) >= node.k;
1606  default: // wrappers
1607  assert(subs.size() == 1);
1608  return subs[0];
1609  }
1610  });
1611  }
1612 
1614  bool IsValid() const {
1615  if (GetType() == ""_mst) return false;
1617  }
1618 
1620  bool IsValidTopLevel() const { return IsValid() && GetType() << "B"_mst; }
1621 
1623  bool IsNonMalleable() const { return GetType() << "m"_mst; }
1624 
1626  bool NeedsSignature() const { return GetType() << "s"_mst; }
1627 
1629  bool CheckTimeLocksMix() const { return GetType() << "k"_mst; }
1630 
1633 
1635  bool ValidSatisfactions() const { return IsValid() && CheckOpsLimit() && CheckStackSize(); }
1636 
1639 
1641  bool IsSane() const { return IsValidTopLevel() && IsSaneSubexpression() && NeedsSignature(); }
1642 
1647  template<typename Ctx>
1648  Availability Satisfy(const Ctx& ctx, std::vector<std::vector<unsigned char>>& stack, bool nonmalleable = true) const {
1649  auto ret = ProduceInput(ctx);
1650  if (nonmalleable && (ret.sat.malleable || !ret.sat.has_sig)) return Availability::NO;
1651  stack = std::move(ret.sat.stack);
1652  return ret.sat.available;
1653  }
1654 
1656  bool operator==(const Node<Key>& arg) const { return Compare(*this, arg) == 0; }
1657 
1658  // Constructors with various argument combinations, which bypass the duplicate key check.
1659  Node(internal::NoDupCheck, MiniscriptContext script_ctx, Fragment nt, std::vector<NodeRef<Key>> sub, std::vector<unsigned char> arg, uint32_t val = 0)
1660  : fragment(nt), k(val), data(std::move(arg)), subs(std::move(sub)), m_script_ctx{script_ctx}, ops(CalcOps()), ss(CalcStackSize()), ws(CalcWitnessSize()), typ(CalcType()), scriptlen(CalcScriptLen()) {}
1661  Node(internal::NoDupCheck, MiniscriptContext script_ctx, Fragment nt, std::vector<unsigned char> arg, uint32_t val = 0)
1662  : fragment(nt), k(val), data(std::move(arg)), m_script_ctx{script_ctx}, ops(CalcOps()), ss(CalcStackSize()), ws(CalcWitnessSize()), typ(CalcType()), scriptlen(CalcScriptLen()) {}
1663  Node(internal::NoDupCheck, MiniscriptContext script_ctx, Fragment nt, std::vector<NodeRef<Key>> sub, std::vector<Key> key, uint32_t val = 0)
1664  : fragment(nt), k(val), keys(std::move(key)), m_script_ctx{script_ctx}, subs(std::move(sub)), ops(CalcOps()), ss(CalcStackSize()), ws(CalcWitnessSize()), typ(CalcType()), scriptlen(CalcScriptLen()) {}
1665  Node(internal::NoDupCheck, MiniscriptContext script_ctx, Fragment nt, std::vector<Key> key, uint32_t val = 0)
1666  : fragment(nt), k(val), keys(std::move(key)), m_script_ctx{script_ctx}, ops(CalcOps()), ss(CalcStackSize()), ws(CalcWitnessSize()), typ(CalcType()), scriptlen(CalcScriptLen()) {}
1667  Node(internal::NoDupCheck, MiniscriptContext script_ctx, Fragment nt, std::vector<NodeRef<Key>> sub, uint32_t val = 0)
1668  : fragment(nt), k(val), subs(std::move(sub)), m_script_ctx{script_ctx}, ops(CalcOps()), ss(CalcStackSize()), ws(CalcWitnessSize()), typ(CalcType()), scriptlen(CalcScriptLen()) {}
1669  Node(internal::NoDupCheck, MiniscriptContext script_ctx, Fragment nt, uint32_t val = 0)
1670  : fragment(nt), k(val), m_script_ctx{script_ctx}, ops(CalcOps()), ss(CalcStackSize()), ws(CalcWitnessSize()), typ(CalcType()), scriptlen(CalcScriptLen()) {}
1671 
1672  // Constructors with various argument combinations, which do perform the duplicate key check.
1673  template <typename Ctx> Node(const Ctx& ctx, Fragment nt, std::vector<NodeRef<Key>> sub, std::vector<unsigned char> arg, uint32_t val = 0)
1674  : Node(internal::NoDupCheck{}, ctx.MsContext(), nt, std::move(sub), std::move(arg), val) { DuplicateKeyCheck(ctx); }
1675  template <typename Ctx> Node(const Ctx& ctx, Fragment nt, std::vector<unsigned char> arg, uint32_t val = 0)
1676  : Node(internal::NoDupCheck{}, ctx.MsContext(), nt, std::move(arg), val) { DuplicateKeyCheck(ctx);}
1677  template <typename Ctx> Node(const Ctx& ctx, Fragment nt, std::vector<NodeRef<Key>> sub, std::vector<Key> key, uint32_t val = 0)
1678  : Node(internal::NoDupCheck{}, ctx.MsContext(), nt, std::move(sub), std::move(key), val) { DuplicateKeyCheck(ctx); }
1679  template <typename Ctx> Node(const Ctx& ctx, Fragment nt, std::vector<Key> key, uint32_t val = 0)
1680  : Node(internal::NoDupCheck{}, ctx.MsContext(), nt, std::move(key), val) { DuplicateKeyCheck(ctx); }
1681  template <typename Ctx> Node(const Ctx& ctx, Fragment nt, std::vector<NodeRef<Key>> sub, uint32_t val = 0)
1682  : Node(internal::NoDupCheck{}, ctx.MsContext(), nt, std::move(sub), val) { DuplicateKeyCheck(ctx); }
1683  template <typename Ctx> Node(const Ctx& ctx, Fragment nt, uint32_t val = 0)
1684  : Node(internal::NoDupCheck{}, ctx.MsContext(), nt, val) { DuplicateKeyCheck(ctx); }
1685 
1686  // Delete copy constructor and assignment operator, use Clone() instead
1687  Node(const Node&) = delete;
1688  Node& operator=(const Node&) = delete;
1689 };
1690 
1691 namespace internal {
1692 
1693 enum class ParseContext {
1695  WRAPPED_EXPR,
1697  EXPR,
1698 
1700  SWAP,
1702  ALT,
1704  CHECK,
1706  DUP_IF,
1708  VERIFY,
1710  NON_ZERO,
1712  ZERO_NOTEQUAL,
1714  WRAP_U,
1716  WRAP_T,
1717 
1719  AND_N,
1721  AND_V,
1723  AND_B,
1725  ANDOR,
1727  OR_B,
1729  OR_C,
1731  OR_D,
1733  OR_I,
1734 
1739  THRESH,
1740 
1742  COMMA,
1744  CLOSE_BRACKET,
1745 };
1746 
1747 int FindNextChar(Span<const char> in, const char m);
1748 
1750 template<typename Key, typename Ctx>
1751 std::optional<std::pair<Key, int>> ParseKeyEnd(Span<const char> in, const Ctx& ctx)
1752 {
1753  int key_size = FindNextChar(in, ')');
1754  if (key_size < 1) return {};
1755  auto key = ctx.FromString(in.begin(), in.begin() + key_size);
1756  if (!key) return {};
1757  return {{std::move(*key), key_size}};
1758 }
1759 
1761 template<typename Ctx>
1762 std::optional<std::pair<std::vector<unsigned char>, int>> ParseHexStrEnd(Span<const char> in, const size_t expected_size,
1763  const Ctx& ctx)
1764 {
1765  int hash_size = FindNextChar(in, ')');
1766  if (hash_size < 1) return {};
1767  std::string val = std::string(in.begin(), in.begin() + hash_size);
1768  if (!IsHex(val)) return {};
1769  auto hash = ParseHex(val);
1770  if (hash.size() != expected_size) return {};
1771  return {{std::move(hash), hash_size}};
1772 }
1773 
1775 template<typename Key>
1776 void BuildBack(const MiniscriptContext script_ctx, Fragment nt, std::vector<NodeRef<Key>>& constructed, const bool reverse = false)
1777 {
1778  NodeRef<Key> child = std::move(constructed.back());
1779  constructed.pop_back();
1780  if (reverse) {
1781  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, script_ctx, nt, Vector(std::move(child), std::move(constructed.back())));
1782  } else {
1783  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, script_ctx, nt, Vector(std::move(constructed.back()), std::move(child)));
1784  }
1785 }
1786 
1792 template<typename Key, typename Ctx>
1793 inline NodeRef<Key> Parse(Span<const char> in, const Ctx& ctx)
1794 {
1795  using namespace script;
1796 
1797  // Account for the minimum script size for all parsed fragments so far. It "borrows" 1
1798  // script byte from all leaf nodes, counting it instead whenever a space for a recursive
1799  // expression is added (through andor, and_*, or_*, thresh). This guarantees that all fragments
1800  // increment the script_size by at least one, except for:
1801  // - "0", "1": these leafs are only a single byte, so their subtracted-from increment is 0.
1802  // This is not an issue however, as "space" for them has to be created by combinators,
1803  // which do increment script_size.
1804  // - "v:": the v wrapper adds nothing as in some cases it results in no opcode being added
1805  // (instead transforming another opcode into its VERIFY form). However, the v: wrapper has
1806  // to be interleaved with other fragments to be valid, so this is not a concern.
1807  size_t script_size{1};
1808  size_t max_size{internal::MaxScriptSize(ctx.MsContext())};
1809 
1810  // The two integers are used to hold state for thresh()
1811  std::vector<std::tuple<ParseContext, int64_t, int64_t>> to_parse;
1812  std::vector<NodeRef<Key>> constructed;
1813 
1814  to_parse.emplace_back(ParseContext::WRAPPED_EXPR, -1, -1);
1815 
1816  // Parses a multi() or multi_a() from its string representation. Returns false on parsing error.
1817  const auto parse_multi_exp = [&](Span<const char>& in, const bool is_multi_a) -> bool {
1818  const auto max_keys{is_multi_a ? MAX_PUBKEYS_PER_MULTI_A : MAX_PUBKEYS_PER_MULTISIG};
1819  const auto required_ctx{is_multi_a ? MiniscriptContext::TAPSCRIPT : MiniscriptContext::P2WSH};
1820  if (ctx.MsContext() != required_ctx) return false;
1821  // Get threshold
1822  int next_comma = FindNextChar(in, ',');
1823  if (next_comma < 1) return false;
1824  const auto k_to_integral{ToIntegral<int64_t>(std::string_view(in.data(), next_comma))};
1825  if (!k_to_integral.has_value()) return false;
1826  const int64_t k{k_to_integral.value()};
1827  in = in.subspan(next_comma + 1);
1828  // Get keys. It is compatible for both compressed and x-only keys.
1829  std::vector<Key> keys;
1830  while (next_comma != -1) {
1831  next_comma = FindNextChar(in, ',');
1832  int key_length = (next_comma == -1) ? FindNextChar(in, ')') : next_comma;
1833  if (key_length < 1) return false;
1834  auto key = ctx.FromString(in.begin(), in.begin() + key_length);
1835  if (!key) return false;
1836  keys.push_back(std::move(*key));
1837  in = in.subspan(key_length + 1);
1838  }
1839  if (keys.size() < 1 || keys.size() > max_keys) return false;
1840  if (k < 1 || k > (int64_t)keys.size()) return false;
1841  if (is_multi_a) {
1842  // (push + xonly-key + CHECKSIG[ADD]) * n + k + OP_NUMEQUAL(VERIFY), minus one.
1843  script_size += (1 + 32 + 1) * keys.size() + BuildScript(k).size();
1844  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::MULTI_A, std::move(keys), k));
1845  } else {
1846  script_size += 2 + (keys.size() > 16) + (k > 16) + 34 * keys.size();
1847  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::MULTI, std::move(keys), k));
1848  }
1849  return true;
1850  };
1851 
1852  while (!to_parse.empty()) {
1853  if (script_size > max_size) return {};
1854 
1855  // Get the current context we are decoding within
1856  auto [cur_context, n, k] = to_parse.back();
1857  to_parse.pop_back();
1858 
1859  switch (cur_context) {
1860  case ParseContext::WRAPPED_EXPR: {
1861  std::optional<size_t> colon_index{};
1862  for (size_t i = 1; i < in.size(); ++i) {
1863  if (in[i] == ':') {
1864  colon_index = i;
1865  break;
1866  }
1867  if (in[i] < 'a' || in[i] > 'z') break;
1868  }
1869  // If there is no colon, this loop won't execute
1870  bool last_was_v{false};
1871  for (size_t j = 0; colon_index && j < *colon_index; ++j) {
1872  if (script_size > max_size) return {};
1873  if (in[j] == 'a') {
1874  script_size += 2;
1875  to_parse.emplace_back(ParseContext::ALT, -1, -1);
1876  } else if (in[j] == 's') {
1877  script_size += 1;
1878  to_parse.emplace_back(ParseContext::SWAP, -1, -1);
1879  } else if (in[j] == 'c') {
1880  script_size += 1;
1881  to_parse.emplace_back(ParseContext::CHECK, -1, -1);
1882  } else if (in[j] == 'd') {
1883  script_size += 3;
1884  to_parse.emplace_back(ParseContext::DUP_IF, -1, -1);
1885  } else if (in[j] == 'j') {
1886  script_size += 4;
1887  to_parse.emplace_back(ParseContext::NON_ZERO, -1, -1);
1888  } else if (in[j] == 'n') {
1889  script_size += 1;
1890  to_parse.emplace_back(ParseContext::ZERO_NOTEQUAL, -1, -1);
1891  } else if (in[j] == 'v') {
1892  // do not permit "...vv...:"; it's not valid, and also doesn't trigger early
1893  // failure as script_size isn't incremented.
1894  if (last_was_v) return {};
1895  to_parse.emplace_back(ParseContext::VERIFY, -1, -1);
1896  } else if (in[j] == 'u') {
1897  script_size += 4;
1898  to_parse.emplace_back(ParseContext::WRAP_U, -1, -1);
1899  } else if (in[j] == 't') {
1900  script_size += 1;
1901  to_parse.emplace_back(ParseContext::WRAP_T, -1, -1);
1902  } else if (in[j] == 'l') {
1903  // The l: wrapper is equivalent to or_i(0,X)
1904  script_size += 4;
1905  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::JUST_0));
1906  to_parse.emplace_back(ParseContext::OR_I, -1, -1);
1907  } else {
1908  return {};
1909  }
1910  last_was_v = (in[j] == 'v');
1911  }
1912  to_parse.emplace_back(ParseContext::EXPR, -1, -1);
1913  if (colon_index) in = in.subspan(*colon_index + 1);
1914  break;
1915  }
1916  case ParseContext::EXPR: {
1917  if (Const("0", in)) {
1918  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::JUST_0));
1919  } else if (Const("1", in)) {
1920  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::JUST_1));
1921  } else if (Const("pk(", in)) {
1922  auto res = ParseKeyEnd<Key, Ctx>(in, ctx);
1923  if (!res) return {};
1924  auto& [key, key_size] = *res;
1925  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_C, Vector(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::PK_K, Vector(std::move(key))))));
1926  in = in.subspan(key_size + 1);
1927  script_size += IsTapscript(ctx.MsContext()) ? 33 : 34;
1928  } else if (Const("pkh(", in)) {
1929  auto res = ParseKeyEnd<Key>(in, ctx);
1930  if (!res) return {};
1931  auto& [key, key_size] = *res;
1932  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_C, Vector(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::PK_H, Vector(std::move(key))))));
1933  in = in.subspan(key_size + 1);
1934  script_size += 24;
1935  } else if (Const("pk_k(", in)) {
1936  auto res = ParseKeyEnd<Key>(in, ctx);
1937  if (!res) return {};
1938  auto& [key, key_size] = *res;
1939  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::PK_K, Vector(std::move(key))));
1940  in = in.subspan(key_size + 1);
1941  script_size += IsTapscript(ctx.MsContext()) ? 32 : 33;
1942  } else if (Const("pk_h(", in)) {
1943  auto res = ParseKeyEnd<Key>(in, ctx);
1944  if (!res) return {};
1945  auto& [key, key_size] = *res;
1946  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::PK_H, Vector(std::move(key))));
1947  in = in.subspan(key_size + 1);
1948  script_size += 23;
1949  } else if (Const("sha256(", in)) {
1950  auto res = ParseHexStrEnd(in, 32, ctx);
1951  if (!res) return {};
1952  auto& [hash, hash_size] = *res;
1953  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::SHA256, std::move(hash)));
1954  in = in.subspan(hash_size + 1);
1955  script_size += 38;
1956  } else if (Const("ripemd160(", in)) {
1957  auto res = ParseHexStrEnd(in, 20, ctx);
1958  if (!res) return {};
1959  auto& [hash, hash_size] = *res;
1960  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::RIPEMD160, std::move(hash)));
1961  in = in.subspan(hash_size + 1);
1962  script_size += 26;
1963  } else if (Const("hash256(", in)) {
1964  auto res = ParseHexStrEnd(in, 32, ctx);
1965  if (!res) return {};
1966  auto& [hash, hash_size] = *res;
1967  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::HASH256, std::move(hash)));
1968  in = in.subspan(hash_size + 1);
1969  script_size += 38;
1970  } else if (Const("hash160(", in)) {
1971  auto res = ParseHexStrEnd(in, 20, ctx);
1972  if (!res) return {};
1973  auto& [hash, hash_size] = *res;
1974  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::HASH160, std::move(hash)));
1975  in = in.subspan(hash_size + 1);
1976  script_size += 26;
1977  } else if (Const("after(", in)) {
1978  int arg_size = FindNextChar(in, ')');
1979  if (arg_size < 1) return {};
1980  const auto num{ToIntegral<int64_t>(std::string_view(in.data(), arg_size))};
1981  if (!num.has_value() || *num < 1 || *num >= 0x80000000L) return {};
1982  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::AFTER, *num));
1983  in = in.subspan(arg_size + 1);
1984  script_size += 1 + (*num > 16) + (*num > 0x7f) + (*num > 0x7fff) + (*num > 0x7fffff);
1985  } else if (Const("older(", in)) {
1986  int arg_size = FindNextChar(in, ')');
1987  if (arg_size < 1) return {};
1988  const auto num{ToIntegral<int64_t>(std::string_view(in.data(), arg_size))};
1989  if (!num.has_value() || *num < 1 || *num >= 0x80000000L) return {};
1990  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::OLDER, *num));
1991  in = in.subspan(arg_size + 1);
1992  script_size += 1 + (*num > 16) + (*num > 0x7f) + (*num > 0x7fff) + (*num > 0x7fffff);
1993  } else if (Const("multi(", in)) {
1994  if (!parse_multi_exp(in, /* is_multi_a = */false)) return {};
1995  } else if (Const("multi_a(", in)) {
1996  if (!parse_multi_exp(in, /* is_multi_a = */true)) return {};
1997  } else if (Const("thresh(", in)) {
1998  int next_comma = FindNextChar(in, ',');
1999  if (next_comma < 1) return {};
2000  const auto k{ToIntegral<int64_t>(std::string_view(in.data(), next_comma))};
2001  if (!k.has_value() || *k < 1) return {};
2002  in = in.subspan(next_comma + 1);
2003  // n = 1 here because we read the first WRAPPED_EXPR before reaching THRESH
2004  to_parse.emplace_back(ParseContext::THRESH, 1, *k);
2005  to_parse.emplace_back(ParseContext::WRAPPED_EXPR, -1, -1);
2006  script_size += 2 + (*k > 16) + (*k > 0x7f) + (*k > 0x7fff) + (*k > 0x7fffff);
2007  } else if (Const("andor(", in)) {
2008  to_parse.emplace_back(ParseContext::ANDOR, -1, -1);
2009  to_parse.emplace_back(ParseContext::CLOSE_BRACKET, -1, -1);
2010  to_parse.emplace_back(ParseContext::WRAPPED_EXPR, -1, -1);
2011  to_parse.emplace_back(ParseContext::COMMA, -1, -1);
2012  to_parse.emplace_back(ParseContext::WRAPPED_EXPR, -1, -1);
2013  to_parse.emplace_back(ParseContext::COMMA, -1, -1);
2014  to_parse.emplace_back(ParseContext::WRAPPED_EXPR, -1, -1);
2015  script_size += 5;
2016  } else {
2017  if (Const("and_n(", in)) {
2018  to_parse.emplace_back(ParseContext::AND_N, -1, -1);
2019  script_size += 5;
2020  } else if (Const("and_b(", in)) {
2021  to_parse.emplace_back(ParseContext::AND_B, -1, -1);
2022  script_size += 2;
2023  } else if (Const("and_v(", in)) {
2024  to_parse.emplace_back(ParseContext::AND_V, -1, -1);
2025  script_size += 1;
2026  } else if (Const("or_b(", in)) {
2027  to_parse.emplace_back(ParseContext::OR_B, -1, -1);
2028  script_size += 2;
2029  } else if (Const("or_c(", in)) {
2030  to_parse.emplace_back(ParseContext::OR_C, -1, -1);
2031  script_size += 3;
2032  } else if (Const("or_d(", in)) {
2033  to_parse.emplace_back(ParseContext::OR_D, -1, -1);
2034  script_size += 4;
2035  } else if (Const("or_i(", in)) {
2036  to_parse.emplace_back(ParseContext::OR_I, -1, -1);
2037  script_size += 4;
2038  } else {
2039  return {};
2040  }
2041  to_parse.emplace_back(ParseContext::CLOSE_BRACKET, -1, -1);
2042  to_parse.emplace_back(ParseContext::WRAPPED_EXPR, -1, -1);
2043  to_parse.emplace_back(ParseContext::COMMA, -1, -1);
2044  to_parse.emplace_back(ParseContext::WRAPPED_EXPR, -1, -1);
2045  }
2046  break;
2047  }
2048  case ParseContext::ALT: {
2049  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_A, Vector(std::move(constructed.back())));
2050  break;
2051  }
2052  case ParseContext::SWAP: {
2053  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_S, Vector(std::move(constructed.back())));
2054  break;
2055  }
2056  case ParseContext::CHECK: {
2057  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_C, Vector(std::move(constructed.back())));
2058  break;
2059  }
2060  case ParseContext::DUP_IF: {
2061  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_D, Vector(std::move(constructed.back())));
2062  break;
2063  }
2064  case ParseContext::NON_ZERO: {
2065  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_J, Vector(std::move(constructed.back())));
2066  break;
2067  }
2068  case ParseContext::ZERO_NOTEQUAL: {
2069  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_N, Vector(std::move(constructed.back())));
2070  break;
2071  }
2072  case ParseContext::VERIFY: {
2073  script_size += (constructed.back()->GetType() << "x"_mst);
2074  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_V, Vector(std::move(constructed.back())));
2075  break;
2076  }
2077  case ParseContext::WRAP_U: {
2078  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::OR_I, Vector(std::move(constructed.back()), MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::JUST_0)));
2079  break;
2080  }
2081  case ParseContext::WRAP_T: {
2082  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::AND_V, Vector(std::move(constructed.back()), MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::JUST_1)));
2083  break;
2084  }
2085  case ParseContext::AND_B: {
2086  BuildBack(ctx.MsContext(), Fragment::AND_B, constructed);
2087  break;
2088  }
2089  case ParseContext::AND_N: {
2090  auto mid = std::move(constructed.back());
2091  constructed.pop_back();
2092  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::ANDOR, Vector(std::move(constructed.back()), std::move(mid), MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::JUST_0)));
2093  break;
2094  }
2095  case ParseContext::AND_V: {
2096  BuildBack(ctx.MsContext(), Fragment::AND_V, constructed);
2097  break;
2098  }
2099  case ParseContext::OR_B: {
2100  BuildBack(ctx.MsContext(), Fragment::OR_B, constructed);
2101  break;
2102  }
2103  case ParseContext::OR_C: {
2104  BuildBack(ctx.MsContext(), Fragment::OR_C, constructed);
2105  break;
2106  }
2107  case ParseContext::OR_D: {
2108  BuildBack(ctx.MsContext(), Fragment::OR_D, constructed);
2109  break;
2110  }
2111  case ParseContext::OR_I: {
2112  BuildBack(ctx.MsContext(), Fragment::OR_I, constructed);
2113  break;
2114  }
2115  case ParseContext::ANDOR: {
2116  auto right = std::move(constructed.back());
2117  constructed.pop_back();
2118  auto mid = std::move(constructed.back());
2119  constructed.pop_back();
2120  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::ANDOR, Vector(std::move(constructed.back()), std::move(mid), std::move(right)));
2121  break;
2122  }
2123  case ParseContext::THRESH: {
2124  if (in.size() < 1) return {};
2125  if (in[0] == ',') {
2126  in = in.subspan(1);
2127  to_parse.emplace_back(ParseContext::THRESH, n+1, k);
2128  to_parse.emplace_back(ParseContext::WRAPPED_EXPR, -1, -1);
2129  script_size += 2;
2130  } else if (in[0] == ')') {
2131  if (k > n) return {};
2132  in = in.subspan(1);
2133  // Children are constructed in reverse order, so iterate from end to beginning
2134  std::vector<NodeRef<Key>> subs;
2135  for (int i = 0; i < n; ++i) {
2136  subs.push_back(std::move(constructed.back()));
2137  constructed.pop_back();
2138  }
2139  std::reverse(subs.begin(), subs.end());
2140  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::THRESH, std::move(subs), k));
2141  } else {
2142  return {};
2143  }
2144  break;
2145  }
2146  case ParseContext::COMMA: {
2147  if (in.size() < 1 || in[0] != ',') return {};
2148  in = in.subspan(1);
2149  break;
2150  }
2151  case ParseContext::CLOSE_BRACKET: {
2152  if (in.size() < 1 || in[0] != ')') return {};
2153  in = in.subspan(1);
2154  break;
2155  }
2156  }
2157  }
2158 
2159  // Sanity checks on the produced miniscript
2160  assert(constructed.size() == 1);
2161  assert(constructed[0]->ScriptSize() == script_size);
2162  if (in.size() > 0) return {};
2163  NodeRef<Key> tl_node = std::move(constructed.front());
2164  tl_node->DuplicateKeyCheck(ctx);
2165  return tl_node;
2166 }
2167 
2176 std::optional<std::vector<Opcode>> DecomposeScript(const CScript& script);
2177 
2179 std::optional<int64_t> ParseScriptNumber(const Opcode& in);
2180 
2181 enum class DecodeContext {
2187  BKV_EXPR,
2189  W_EXPR,
2190 
2194  SWAP,
2197  ALT,
2199  CHECK,
2201  DUP_IF,
2203  VERIFY,
2205  NON_ZERO,
2207  ZERO_NOTEQUAL,
2208 
2213  MAYBE_AND_V,
2215  AND_V,
2217  AND_B,
2219  ANDOR,
2221  OR_B,
2223  OR_C,
2225  OR_D,
2226 
2230  THRESH_W,
2233  THRESH_E,
2234 
2238  ENDIF,
2242  ENDIF_NOTIF,
2246  ENDIF_ELSE,
2247 };
2248 
2250 template<typename Key, typename Ctx, typename I>
2251 inline NodeRef<Key> DecodeScript(I& in, I last, const Ctx& ctx)
2252 {
2253  // The two integers are used to hold state for thresh()
2254  std::vector<std::tuple<DecodeContext, int64_t, int64_t>> to_parse;
2255  std::vector<NodeRef<Key>> constructed;
2256 
2257  // This is the top level, so we assume the type is B
2258  // (in particular, disallowing top level W expressions)
2259  to_parse.emplace_back(DecodeContext::BKV_EXPR, -1, -1);
2260 
2261  while (!to_parse.empty()) {
2262  // Exit early if the Miniscript is not going to be valid.
2263  if (!constructed.empty() && !constructed.back()->IsValid()) return {};
2264 
2265  // Get the current context we are decoding within
2266  auto [cur_context, n, k] = to_parse.back();
2267  to_parse.pop_back();
2268 
2269  switch(cur_context) {
2270  case DecodeContext::SINGLE_BKV_EXPR: {
2271  if (in >= last) return {};
2272 
2273  // Constants
2274  if (in[0].first == OP_1) {
2275  ++in;
2276  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::JUST_1));
2277  break;
2278  }
2279  if (in[0].first == OP_0) {
2280  ++in;
2281  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::JUST_0));
2282  break;
2283  }
2284  // Public keys
2285  if (in[0].second.size() == 33 || in[0].second.size() == 32) {
2286  auto key = ctx.FromPKBytes(in[0].second.begin(), in[0].second.end());
2287  if (!key) return {};
2288  ++in;
2289  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::PK_K, Vector(std::move(*key))));
2290  break;
2291  }
2292  if (last - in >= 5 && in[0].first == OP_VERIFY && in[1].first == OP_EQUAL && in[3].first == OP_HASH160 && in[4].first == OP_DUP && in[2].second.size() == 20) {
2293  auto key = ctx.FromPKHBytes(in[2].second.begin(), in[2].second.end());
2294  if (!key) return {};
2295  in += 5;
2296  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::PK_H, Vector(std::move(*key))));
2297  break;
2298  }
2299  // Time locks
2300  std::optional<int64_t> num;
2301  if (last - in >= 2 && in[0].first == OP_CHECKSEQUENCEVERIFY && (num = ParseScriptNumber(in[1]))) {
2302  in += 2;
2303  if (*num < 1 || *num > 0x7FFFFFFFL) return {};
2304  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::OLDER, *num));
2305  break;
2306  }
2307  if (last - in >= 2 && in[0].first == OP_CHECKLOCKTIMEVERIFY && (num = ParseScriptNumber(in[1]))) {
2308  in += 2;
2309  if (num < 1 || num > 0x7FFFFFFFL) return {};
2310  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::AFTER, *num));
2311  break;
2312  }
2313  // Hashes
2314  if (last - in >= 7 && in[0].first == OP_EQUAL && in[3].first == OP_VERIFY && in[4].first == OP_EQUAL && (num = ParseScriptNumber(in[5])) && num == 32 && in[6].first == OP_SIZE) {
2315  if (in[2].first == OP_SHA256 && in[1].second.size() == 32) {
2316  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::SHA256, in[1].second));
2317  in += 7;
2318  break;
2319  } else if (in[2].first == OP_RIPEMD160 && in[1].second.size() == 20) {
2320  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::RIPEMD160, in[1].second));
2321  in += 7;
2322  break;
2323  } else if (in[2].first == OP_HASH256 && in[1].second.size() == 32) {
2324  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::HASH256, in[1].second));
2325  in += 7;
2326  break;
2327  } else if (in[2].first == OP_HASH160 && in[1].second.size() == 20) {
2328  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::HASH160, in[1].second));
2329  in += 7;
2330  break;
2331  }
2332  }
2333  // Multi
2334  if (last - in >= 3 && in[0].first == OP_CHECKMULTISIG) {
2335  if (IsTapscript(ctx.MsContext())) return {};
2336  std::vector<Key> keys;
2337  const auto n = ParseScriptNumber(in[1]);
2338  if (!n || last - in < 3 + *n) return {};
2339  if (*n < 1 || *n > 20) return {};
2340  for (int i = 0; i < *n; ++i) {
2341  if (in[2 + i].second.size() != 33) return {};
2342  auto key = ctx.FromPKBytes(in[2 + i].second.begin(), in[2 + i].second.end());
2343  if (!key) return {};
2344  keys.push_back(std::move(*key));
2345  }
2346  const auto k = ParseScriptNumber(in[2 + *n]);
2347  if (!k || *k < 1 || *k > *n) return {};
2348  in += 3 + *n;
2349  std::reverse(keys.begin(), keys.end());
2350  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::MULTI, std::move(keys), *k));
2351  break;
2352  }
2353  // Tapscript's equivalent of multi
2354  if (last - in >= 4 && in[0].first == OP_NUMEQUAL) {
2355  if (!IsTapscript(ctx.MsContext())) return {};
2356  // The necessary threshold of signatures.
2357  const auto k = ParseScriptNumber(in[1]);
2358  if (!k) return {};
2359  if (*k < 1 || *k > MAX_PUBKEYS_PER_MULTI_A) return {};
2360  if (last - in < 2 + *k * 2) return {};
2361  std::vector<Key> keys;
2362  keys.reserve(*k);
2363  // Walk through the expected (pubkey, CHECKSIG[ADD]) pairs.
2364  for (int pos = 2;; pos += 2) {
2365  if (last - in < pos + 2) return {};
2366  // Make sure it's indeed an x-only pubkey and a CHECKSIG[ADD], then parse the key.
2367  if (in[pos].first != OP_CHECKSIGADD && in[pos].first != OP_CHECKSIG) return {};
2368  if (in[pos + 1].second.size() != 32) return {};
2369  auto key = ctx.FromPKBytes(in[pos + 1].second.begin(), in[pos + 1].second.end());
2370  if (!key) return {};
2371  keys.push_back(std::move(*key));
2372  // Make sure early we don't parse an arbitrary large expression.
2373  if (keys.size() > MAX_PUBKEYS_PER_MULTI_A) return {};
2374  // OP_CHECKSIG means it was the last one to parse.
2375  if (in[pos].first == OP_CHECKSIG) break;
2376  }
2377  if (keys.size() < (size_t)*k) return {};
2378  in += 2 + keys.size() * 2;
2379  std::reverse(keys.begin(), keys.end());
2380  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::MULTI_A, std::move(keys), *k));
2381  break;
2382  }
2386  // c: wrapper
2387  if (in[0].first == OP_CHECKSIG) {
2388  ++in;
2389  to_parse.emplace_back(DecodeContext::CHECK, -1, -1);
2390  to_parse.emplace_back(DecodeContext::SINGLE_BKV_EXPR, -1, -1);
2391  break;
2392  }
2393  // v: wrapper
2394  if (in[0].first == OP_VERIFY) {
2395  ++in;
2396  to_parse.emplace_back(DecodeContext::VERIFY, -1, -1);
2397  to_parse.emplace_back(DecodeContext::SINGLE_BKV_EXPR, -1, -1);
2398  break;
2399  }
2400  // n: wrapper
2401  if (in[0].first == OP_0NOTEQUAL) {
2402  ++in;
2403  to_parse.emplace_back(DecodeContext::ZERO_NOTEQUAL, -1, -1);
2404  to_parse.emplace_back(DecodeContext::SINGLE_BKV_EXPR, -1, -1);
2405  break;
2406  }
2407  // Thresh
2408  if (last - in >= 3 && in[0].first == OP_EQUAL && (num = ParseScriptNumber(in[1]))) {
2409  if (*num < 1) return {};
2410  in += 2;
2411  to_parse.emplace_back(DecodeContext::THRESH_W, 0, *num);
2412  break;
2413  }
2414  // OP_ENDIF can be WRAP_J, WRAP_D, ANDOR, OR_C, OR_D, or OR_I
2415  if (in[0].first == OP_ENDIF) {
2416  ++in;
2417  to_parse.emplace_back(DecodeContext::ENDIF, -1, -1);
2418  to_parse.emplace_back(DecodeContext::BKV_EXPR, -1, -1);
2419  break;
2420  }
2426  // and_b
2427  if (in[0].first == OP_BOOLAND) {
2428  ++in;
2429  to_parse.emplace_back(DecodeContext::AND_B, -1, -1);
2430  to_parse.emplace_back(DecodeContext::SINGLE_BKV_EXPR, -1, -1);
2431  to_parse.emplace_back(DecodeContext::W_EXPR, -1, -1);
2432  break;
2433  }
2434  // or_b
2435  if (in[0].first == OP_BOOLOR) {
2436  ++in;
2437  to_parse.emplace_back(DecodeContext::OR_B, -1, -1);
2438  to_parse.emplace_back(DecodeContext::SINGLE_BKV_EXPR, -1, -1);
2439  to_parse.emplace_back(DecodeContext::W_EXPR, -1, -1);
2440  break;
2441  }
2442  // Unrecognised expression
2443  return {};
2444  }
2445  case DecodeContext::BKV_EXPR: {
2446  to_parse.emplace_back(DecodeContext::MAYBE_AND_V, -1, -1);
2447  to_parse.emplace_back(DecodeContext::SINGLE_BKV_EXPR, -1, -1);
2448  break;
2449  }
2450  case DecodeContext::W_EXPR: {
2451  // a: wrapper
2452  if (in >= last) return {};
2453  if (in[0].first == OP_FROMALTSTACK) {
2454  ++in;
2455  to_parse.emplace_back(DecodeContext::ALT, -1, -1);
2456  } else {
2457  to_parse.emplace_back(DecodeContext::SWAP, -1, -1);
2458  }
2459  to_parse.emplace_back(DecodeContext::BKV_EXPR, -1, -1);
2460  break;
2461  }
2462  case DecodeContext::MAYBE_AND_V: {
2463  // If we reach a potential AND_V top-level, check if the next part of the script could be another AND_V child
2464  // These op-codes cannot end any well-formed miniscript so cannot be used in an and_v node.
2465  if (in < last && in[0].first != OP_IF && in[0].first != OP_ELSE && in[0].first != OP_NOTIF && in[0].first != OP_TOALTSTACK && in[0].first != OP_SWAP) {
2466  to_parse.emplace_back(DecodeContext::AND_V, -1, -1);
2467  // BKV_EXPR can contain more AND_V nodes
2468  to_parse.emplace_back(DecodeContext::BKV_EXPR, -1, -1);
2469  }
2470  break;
2471  }
2472  case DecodeContext::SWAP: {
2473  if (in >= last || in[0].first != OP_SWAP || constructed.empty()) return {};
2474  ++in;
2475  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_S, Vector(std::move(constructed.back())));
2476  break;
2477  }
2478  case DecodeContext::ALT: {
2479  if (in >= last || in[0].first != OP_TOALTSTACK || constructed.empty()) return {};
2480  ++in;
2481  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_A, Vector(std::move(constructed.back())));
2482  break;
2483  }
2484  case DecodeContext::CHECK: {
2485  if (constructed.empty()) return {};
2486  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_C, Vector(std::move(constructed.back())));
2487  break;
2488  }
2489  case DecodeContext::DUP_IF: {
2490  if (constructed.empty()) return {};
2491  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_D, Vector(std::move(constructed.back())));
2492  break;
2493  }
2494  case DecodeContext::VERIFY: {
2495  if (constructed.empty()) return {};
2496  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_V, Vector(std::move(constructed.back())));
2497  break;
2498  }
2499  case DecodeContext::NON_ZERO: {
2500  if (constructed.empty()) return {};
2501  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_J, Vector(std::move(constructed.back())));
2502  break;
2503  }
2504  case DecodeContext::ZERO_NOTEQUAL: {
2505  if (constructed.empty()) return {};
2506  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_N, Vector(std::move(constructed.back())));
2507  break;
2508  }
2509  case DecodeContext::AND_V: {
2510  if (constructed.size() < 2) return {};
2511  BuildBack(ctx.MsContext(), Fragment::AND_V, constructed, /*reverse=*/true);
2512  break;
2513  }
2514  case DecodeContext::AND_B: {
2515  if (constructed.size() < 2) return {};
2516  BuildBack(ctx.MsContext(), Fragment::AND_B, constructed, /*reverse=*/true);
2517  break;
2518  }
2519  case DecodeContext::OR_B: {
2520  if (constructed.size() < 2) return {};
2521  BuildBack(ctx.MsContext(), Fragment::OR_B, constructed, /*reverse=*/true);
2522  break;
2523  }
2524  case DecodeContext::OR_C: {
2525  if (constructed.size() < 2) return {};
2526  BuildBack(ctx.MsContext(), Fragment::OR_C, constructed, /*reverse=*/true);
2527  break;
2528  }
2529  case DecodeContext::OR_D: {
2530  if (constructed.size() < 2) return {};
2531  BuildBack(ctx.MsContext(), Fragment::OR_D, constructed, /*reverse=*/true);
2532  break;
2533  }
2534  case DecodeContext::ANDOR: {
2535  if (constructed.size() < 3) return {};
2536  NodeRef<Key> left = std::move(constructed.back());
2537  constructed.pop_back();
2538  NodeRef<Key> right = std::move(constructed.back());
2539  constructed.pop_back();
2540  NodeRef<Key> mid = std::move(constructed.back());
2541  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::ANDOR, Vector(std::move(left), std::move(mid), std::move(right)));
2542  break;
2543  }
2544  case DecodeContext::THRESH_W: {
2545  if (in >= last) return {};
2546  if (in[0].first == OP_ADD) {
2547  ++in;
2548  to_parse.emplace_back(DecodeContext::THRESH_W, n+1, k);
2549  to_parse.emplace_back(DecodeContext::W_EXPR, -1, -1);
2550  } else {
2551  to_parse.emplace_back(DecodeContext::THRESH_E, n+1, k);
2552  // All children of thresh have type modifier d, so cannot be and_v
2553  to_parse.emplace_back(DecodeContext::SINGLE_BKV_EXPR, -1, -1);
2554  }
2555  break;
2556  }
2557  case DecodeContext::THRESH_E: {
2558  if (k < 1 || k > n || constructed.size() < static_cast<size_t>(n)) return {};
2559  std::vector<NodeRef<Key>> subs;
2560  for (int i = 0; i < n; ++i) {
2561  NodeRef<Key> sub = std::move(constructed.back());
2562  constructed.pop_back();
2563  subs.push_back(std::move(sub));
2564  }
2565  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::THRESH, std::move(subs), k));
2566  break;
2567  }
2568  case DecodeContext::ENDIF: {
2569  if (in >= last) return {};
2570 
2571  // could be andor or or_i
2572  if (in[0].first == OP_ELSE) {
2573  ++in;
2574  to_parse.emplace_back(DecodeContext::ENDIF_ELSE, -1, -1);
2575  to_parse.emplace_back(DecodeContext::BKV_EXPR, -1, -1);
2576  }
2577  // could be j: or d: wrapper
2578  else if (in[0].first == OP_IF) {
2579  if (last - in >= 2 && in[1].first == OP_DUP) {
2580  in += 2;
2581  to_parse.emplace_back(DecodeContext::DUP_IF, -1, -1);
2582  } else if (last - in >= 3 && in[1].first == OP_0NOTEQUAL && in[2].first == OP_SIZE) {
2583  in += 3;
2584  to_parse.emplace_back(DecodeContext::NON_ZERO, -1, -1);
2585  }
2586  else {
2587  return {};
2588  }
2589  // could be or_c or or_d
2590  } else if (in[0].first == OP_NOTIF) {
2591  ++in;
2592  to_parse.emplace_back(DecodeContext::ENDIF_NOTIF, -1, -1);
2593  }
2594  else {
2595  return {};
2596  }
2597  break;
2598  }
2599  case DecodeContext::ENDIF_NOTIF: {
2600  if (in >= last) return {};
2601  if (in[0].first == OP_IFDUP) {
2602  ++in;
2603  to_parse.emplace_back(DecodeContext::OR_D, -1, -1);
2604  } else {
2605  to_parse.emplace_back(DecodeContext::OR_C, -1, -1);
2606  }
2607  // or_c and or_d both require X to have type modifier d so, can't contain and_v
2608  to_parse.emplace_back(DecodeContext::SINGLE_BKV_EXPR, -1, -1);
2609  break;
2610  }
2611  case DecodeContext::ENDIF_ELSE: {
2612  if (in >= last) return {};
2613  if (in[0].first == OP_IF) {
2614  ++in;
2615  BuildBack(ctx.MsContext(), Fragment::OR_I, constructed, /*reverse=*/true);
2616  } else if (in[0].first == OP_NOTIF) {
2617  ++in;
2618  to_parse.emplace_back(DecodeContext::ANDOR, -1, -1);
2619  // andor requires X to have type modifier d, so it can't be and_v
2620  to_parse.emplace_back(DecodeContext::SINGLE_BKV_EXPR, -1, -1);
2621  } else {
2622  return {};
2623  }
2624  break;
2625  }
2626  }
2627  }
2628  if (constructed.size() != 1) return {};
2629  NodeRef<Key> tl_node = std::move(constructed.front());
2630  tl_node->DuplicateKeyCheck(ctx);
2631  // Note that due to how ComputeType works (only assign the type to the node if the
2632  // subs' types are valid) this would fail if any node of tree is badly typed.
2633  if (!tl_node->IsValidTopLevel()) return {};
2634  return tl_node;
2635 }
2636 
2637 } // namespace internal
2638 
2639 template<typename Ctx>
2640 inline NodeRef<typename Ctx::Key> FromString(const std::string& str, const Ctx& ctx) {
2641  return internal::Parse<typename Ctx::Key>(str, ctx);
2642 }
2643 
2644 template<typename Ctx>
2645 inline NodeRef<typename Ctx::Key> FromScript(const CScript& script, const Ctx& ctx) {
2646  using namespace internal;
2647  // A too large Script is necessarily invalid, don't bother parsing it.
2648  if (script.size() > MaxScriptSize(ctx.MsContext())) return {};
2649  auto decomposed = DecomposeScript(script);
2650  if (!decomposed) return {};
2651  auto it = decomposed->begin();
2652  auto ret = DecodeScript<typename Ctx::Key>(it, decomposed->end(), ctx);
2653  if (!ret) return {};
2654  if (it != decomposed->end()) return {};
2655  return ret;
2656 }
2657 
2658 } // namespace miniscript
2659 
2660 #endif // BITCOIN_SCRIPT_MINISCRIPT_H
CScript BuildScript(Ts &&... inputs)
Build a script by concatenating other scripts, or any argument accepted by CScript::operator<<.
Definition: script.h:616
OP_SIZE 32 OP_EQUALVERIFY OP_HASH160 [hash] OP_EQUAL.
Node(internal::NoDupCheck, MiniscriptContext script_ctx, Fragment nt, std::vector< unsigned char > arg, uint32_t val=0)
Definition: miniscript.h:1661
NodeRef< typename Ctx::Key > FromString(const std::string &str, const Ctx &ctx)
Definition: miniscript.h:2640
std::vector< std::vector< unsigned char > > stack
Data elements.
Definition: miniscript.h:311
A node in a miniscript expression.
Definition: miniscript.h:191
CONSTEXPR_IF_NOT_DEBUG Span< C > subspan(std::size_t offset) const noexcept
Definition: span.h:195
Potentially multiple SINGLE_BKV_EXPRs as children of (potentially multiple) and_v expressions...
[X] OP_VERIFY (or -VERIFY version of last opcode in X)
SWAP wraps the top constructed node with s:
int ret
static constexpr SatInfo BinaryOp() noexcept
A script consisting of just a binary operator (OP_BOOLAND, OP_BOOLOR, OP_ADD).
Definition: miniscript.h:469
bool IsNotSatisfiable() const
Whether no satisfaction exists for this node.
Definition: miniscript.h:1547
friend MaxInt< I > operator+(const MaxInt< I > &a, const MaxInt< I > &b)
Definition: miniscript.h:358
[X] OP_NOTIF [Z] OP_ELSE [Y] OP_ENDIF
Availability Satisfy(const Ctx &ctx, std::vector< std::vector< unsigned char >> &stack, bool nonmalleable=true) const
Produce a witness for this script, if possible and given the information available in the context...
Definition: miniscript.h:1648
static const auto ZERO32
A stack consisting of a single malleable 32-byte 0x0000...0000 element (for dissatisfying hash challe...
Definition: miniscript.h:333
Node(const Ctx &ctx, Fragment nt, std::vector< unsigned char > arg, uint32_t val=0)
Definition: miniscript.h:1675
std::optional< std::pair< Key, int > > ParseKeyEnd(Span< const char > in, const Ctx &ctx)
Parse a key string ending at the end of the fragment&#39;s text representation.
Definition: miniscript.h:1751
const MiniscriptContext m_script_ctx
The Script context for this node. Either P2WSH or Tapscript.
Definition: miniscript.h:516
std::vector< Byte > ParseHex(std::string_view hex_str)
Like TryParseHex, but returns an empty vector on invalid input.
Definition: strencodings.h:68
static const int WITNESS_SCALE_FACTOR
Definition: consensus.h:21
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:265
OP_DUP OP_HASH160 [keyhash] OP_EQUALVERIFY.
ALT wraps the top constructed node with a:
constexpr uint32_t TXIN_BYTES_NO_WITNESS
prevout + nSequence + scriptSig
Definition: miniscript.h:262
const std::vector< unsigned char > data
The data bytes in this expression (only for HASH160/HASH256/SHA256/RIPEMD10).
Definition: miniscript.h:512
assert(!tx.IsCoinBase())
VERIFY wraps the top constructed node with v:
OP_SIZE 32 OP_EQUALVERIFY OP_RIPEMD160 [hash] OP_EQUAL.
const Node * FindInsaneSub() const
Find an insane subnode which has no insane children. Nullptr if there is none.
Definition: miniscript.h:1563
std::optional< Result > TreeEvalMaybe(UpFn upfn) const
Like TreeEvalMaybe, but without downfn or State type.
Definition: miniscript.h:669
[k] [key_n]* [n] OP_CHECKMULTISIG (only available within P2WSH context)
Definition: script.h:125
std::optional< Result > TreeEvalMaybe(State root_state, DownFn downfn, UpFn upfn) const
Definition: miniscript.h:604
InputStack & SetMalleable(bool x=true)
Mark this input stack as malleable.
Definition: miniscript.cpp:321
[n] OP_CHECKLOCKTIMEVERIFY
A pair of a satisfaction and a dissatisfaction InputStack.
Definition: miniscript.h:342
Definition: script.h:161
constexpr SatInfo(int32_t in_netdiff, int32_t in_exec) noexcept
Script set with a single script in it, with specified netdiff and exec.
Definition: miniscript.h:434
bool CheckDuplicateKey() const
Check whether there is no duplicate key across this fragment and all its sub-fragments.
Definition: miniscript.h:1632
OP_TOALTSTACK [X] OP_FROMALTSTACK.
const uint32_t k
The k parameter (time for OLDER/AFTER, threshold for THRESH(_M))
Definition: miniscript.h:508
#define CHECK_NONFATAL(condition)
Identity function.
Definition: check.h:81
constexpr bool IsTapscript(MiniscriptContext ms_ctx)
Whether the context Tapscript, ensuring the only other possibility is P2WSH.
Definition: miniscript.h:245
bool IsHex(std::string_view str)
bool IsValid() const
Check whether this node is valid at all.
Definition: miniscript.h:1614
constexpr std::size_t size() const noexcept
Definition: span.h:187
If, inside an ENDIF context, we find an OP_NOTIF before finding an OP_ELSE, we could either be in an ...
std::optional< std::pair< std::vector< unsigned char >, int > > ParseHexStrEnd(Span< const char > in, const size_t expected_size, const Ctx &ctx)
Parse a hex string ending at the end of the fragment&#39;s text representation.
Definition: miniscript.h:1762
static consteval Type Make(uint32_t flags) noexcept
Construction function used by the ""_mst operator.
Definition: miniscript.h:135
const internal::WitnessSize ws
Cached witness size bounds.
Definition: miniscript.h:551
Type CalcType() const
Compute the type for this miniscript.
Definition: miniscript.h:731
Availability available
Whether this stack is valid for its intended purpose (satisfaction or dissatisfaction of a Node)...
Definition: miniscript.h:300
bool malleable
Whether this stack is malleable (can be turned into an equally valid other stack by a third party)...
Definition: miniscript.h:304
static const auto ONE
A stack consisting of a single 0x01 element (interpreted as 1 by the script interpreted in numeric co...
Definition: miniscript.h:335
static constexpr SatInfo Nop() noexcept
A script consisting of just a repurposed nop (OP_CHECKLOCKTIMEVERIFY, OP_CHECKSEQUENCEVERIFY).
Definition: miniscript.h:465
Node(const Ctx &ctx, Fragment nt, std::vector< NodeRef< Key >> sub, std::vector< Key > key, uint32_t val=0)
Definition: miniscript.h:1677
WRAP_U will construct an or_i(X,0) node from the top constructed node.
size_t CalcScriptLen() const
Compute the length of the script for this miniscript (including children).
Definition: miniscript.h:570
constexpr SatInfo() noexcept
Empty script set.
Definition: miniscript.h:431
Ops(uint32_t in_count, MaxInt< uint32_t > in_sat, MaxInt< uint32_t > in_dsat)
Definition: miniscript.h:378
ZERO_NOTEQUAL wraps the top constructed node with n:
std::optional< uint32_t > GetWitnessSize() const
Return the maximum size in bytes of a witness to satisfy this script non-malleably.
Definition: miniscript.h:1551
[X] OP_NOTIF [Y] OP_ENDIF
std::optional< bool > has_duplicate_keys
Whether a public key appears more than once in this node.
Definition: miniscript.h:561
WRAP_T will construct an and_v(X,1) node from the top constructed node.
Definition: script.h:76
NodeRef< Key > Clone() const
Definition: miniscript.h:531
MaxInt< uint32_t > dsat
Maximum witness size to dissatisfy;.
Definition: miniscript.h:493
Node & operator=(const Node &)=delete
MaxInt< uint32_t > sat
Maximum witness size to satisfy;.
Definition: miniscript.h:491
ENDIF signals that we are inside some sort of OP_IF structure, which could be or_d, or_c, or_i, andor, d:, or j: wrapper, depending on what follows.
bool IsSane() const
Check whether this node is safe as a script on its own.
Definition: miniscript.h:1641
Node(const Ctx &ctx, Fragment nt, uint32_t val=0)
Definition: miniscript.h:1683
constexpr Type If(bool x) const
The empty type if x is false, itself otherwise.
Definition: miniscript.h:153
NodeRef< Key > DecodeScript(I &in, I last, const Ctx &ctx)
Parse a miniscript from a bitcoin script.
Definition: miniscript.h:2251
AND_N will construct an andor(X,Y,0) node from the last two constructed nodes.
[X] OP_IFDUP OP_NOTIF [Y] OP_ENDIF
InputStack & SetAvailable(Availability avail)
Change availability.
Definition: miniscript.cpp:299
uint32_t GetStaticOps() const
Return the number of ops in the script (not counting the dynamic ones that depend on execution)...
Definition: miniscript.h:1508
static constexpr SatInfo OP_SIZE() noexcept
Definition: miniscript.h:476
const Type typ
Cached expression type (computed by CalcType and fed through SanitizeType).
Definition: miniscript.h:553
An expression which may be begin with wrappers followed by a colon.
const size_t scriptlen
Cached script length (computed by CalcScriptLen).
Definition: miniscript.h:555
State
The various states a (txhash,peer) pair can be in.
Definition: txrequest.cpp:42
static const int MAX_PUBKEYS_PER_MULTISIG
Definition: script.h:34
static constexpr SatInfo OP_0NOTEQUAL() noexcept
Definition: miniscript.h:478
CLOSE_BRACKET expects the next element to be &#39;)&#39; and fails if not.
const Fragment fragment
What node type this node is.
Definition: miniscript.h:506
bool has_sig
Whether this stack contains a digital signature.
Definition: miniscript.h:302
std::pair< opcodetype, std::vector< unsigned char > > Opcode
Definition: miniscript.h:189
[X1] ([Xn] OP_ADD)* [k] OP_EQUAL
Node(internal::NoDupCheck, MiniscriptContext script_ctx, Fragment nt, uint32_t val=0)
Definition: miniscript.h:1669
internal::InputResult ProduceInput(const Ctx &ctx) const
Definition: miniscript.h:1187
std::vector< typename std::common_type< Args... >::type > Vector(Args &&... args)
Construct a vector with the specified elements.
Definition: vector.h:23
const int32_t netdiff
How much higher the stack size at start of execution can be compared to at the end.
Definition: miniscript.h:426
const int32_t exec
Mow much higher the stack size can be during execution compared to at the end.
Definition: miniscript.h:428
int FindNextChar(Span< const char > sp, const char m)
Definition: miniscript.cpp:422
uint32_t count
Non-push opcodes.
Definition: miniscript.h:372
Definition: script.h:83
[X] [Y] OP_BOOLOR
constexpr bool operator==(Type x) const
Equality operator.
Definition: miniscript.h:150
constexpr StackSize(SatInfo in_both) noexcept
Definition: miniscript.h:486
Definition: script.h:104
A single expression of type B, K, or V.
In a thresh expression, all sub-expressions other than the first are W-type, and end in OP_ADD...
uint32_t m_flags
Internal bitmap of properties (see ""_mst operator for details).
Definition: miniscript.h:128
Type SanitizeType(Type e)
A helper sanitizer/checker for the output of CalcType.
Definition: miniscript.cpp:19
internal::Ops CalcOps() const
Definition: miniscript.h:944
std::optional< std::vector< Opcode > > DecomposeScript(const CScript &script)
Decode a script into opcode/push pairs.
Definition: miniscript.cpp:369
MaxInt< uint32_t > dsat
Number of keys in possibly executed OP_CHECKMULTISIG(VERIFY)s to dissatisfy.
Definition: miniscript.h:376
A miniscript expression which does not begin with wrappers.
bool IsNonMalleable() const
Check whether this script can always be satisfied in a non-malleable way.
Definition: miniscript.h:1623
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:39
ArgsManager & args
Definition: bitcoind.cpp:277
OP_IF [X] OP_ELSE [Y] OP_ENDIF.
static const auto EMPTY
The empty stack.
Definition: miniscript.h:337
[n] OP_CHECKSEQUENCEVERIFY
Node(const Ctx &ctx, Fragment nt, std::vector< NodeRef< Key >> sub, std::vector< unsigned char > arg, uint32_t val=0)
Definition: miniscript.h:1673
bool IsSaneSubexpression() const
Whether the apparent policy of this node matches its script semantics. Doesn&#39;t guarantee it is a safe...
Definition: miniscript.h:1638
constexpr friend SatInfo operator|(const SatInfo &a, const SatInfo &b) noexcept
Script set union.
Definition: miniscript.h:438
Node(internal::NoDupCheck, MiniscriptContext script_ctx, Fragment nt, std::vector< Key > key, uint32_t val=0)
Definition: miniscript.h:1665
#define B
Definition: util_tests.cpp:545
friend int Compare(const Node< Key > &node1, const Node< Key > &node2)
Compare two miniscript subtrees, using a non-recursive algorithm.
Definition: miniscript.h:711
A data structure to help the calculation of stack size limits.
Definition: miniscript.h:422
bool CheckOpsLimit() const
Check the ops limit of this script against the consensus limit.
Definition: miniscript.h:1511
MAYBE_AND_V will check if the next part of the script could be a valid miniscript sub-expression...
static constexpr unsigned int MAX_STANDARD_P2WSH_SCRIPT_SIZE
The maximum size in bytes of a standard witnessScript.
Definition: policy.h:56
bool NeedsSignature() const
Check whether this script always needs a signature.
Definition: miniscript.h:1626
MiniscriptContext GetMsCtx() const
Return the script context for this node.
Definition: miniscript.h:1560
constexpr uint32_t P2WSH_TXOUT_BYTES
nValue + script len + OP_0 + pushdata 32.
Definition: miniscript.h:264
InputResult(A &&in_nsat, B &&in_sat)
Definition: miniscript.h:346
static bool verify(const CScriptNum10 &bignum, const CScriptNum &scriptnum)
static constexpr unsigned int MAX_PUBKEYS_PER_MULTI_A
The limit of keys in OP_CHECKSIGADD-based scripts.
Definition: script.h:37
NON_ZERO wraps the top constructed node with j:
WitnessSize(MaxInt< uint32_t > in_sat, MaxInt< uint32_t > in_dsat)
Definition: miniscript.h:495
OP_DUP OP_IF [X] OP_ENDIF.
constexpr Type operator &(Type x) const
Compute the type with the intersection of properties.
Definition: miniscript.h:141
Class whose objects represent the maximum of a list of integers.
Definition: miniscript.h:351
const bool valid
Whether a canonical satisfaction/dissatisfaction is possible at all.
Definition: miniscript.h:424
COMMA expects the next element to be &#39;,&#39; and fails if not.
bool Const(const std::string &str, Span< const char > &sp)
Parse a constant.
Definition: parsing.cpp:15
#define CHECK(cond)
Unconditional failure on condition failure.
Definition: util.h:35
An object representing a sequence of witness stack elements.
Definition: miniscript.h:294
internal::WitnessSize CalcWitnessSize() const
Definition: miniscript.h:1133
static const auto ZERO
A stack consisting of a single zero-length element (interpreted as 0 by the script interpreter in num...
Definition: miniscript.h:331
size_t ScriptSize() const
Return the size of the script for this expression (faster than ToScript().size()).
Definition: miniscript.h:1499
[X] [Y] OP_BOOLAND
static constexpr SatInfo OP_CHECKSIG() noexcept
Definition: miniscript.h:477
THRESH_E constructs a thresh node from the appropriate number of constructed children.
friend InputStack operator+(InputStack a, InputStack b)
Concatenate two input stacks.
Definition: miniscript.cpp:326
static constexpr size_t TAPROOT_CONTROL_MAX_SIZE
Definition: interpreter.h:236
constexpr StackSize(SatInfo in_sat, SatInfo in_dsat) noexcept
Definition: miniscript.h:485
Node(internal::NoDupCheck, MiniscriptContext script_ctx, Fragment nt, std::vector< NodeRef< Key >> sub, std::vector< Key > key, std::vector< unsigned char > arg, uint32_t val)
Definition: miniscript.h:566
Node(const Ctx &ctx, Fragment nt, std::vector< Key > key, uint32_t val=0)
Definition: miniscript.h:1679
NodeRef< Key > Parse(Span< const char > in, const Ctx &ctx)
Parse a miniscript from its textual descriptor form.
Definition: miniscript.h:1793
std::unique_ptr< const Node< Key > > NodeRef
Definition: miniscript.h:192
std::optional< std::string > ToString(const CTx &ctx) const
Definition: miniscript.h:829
bool non_canon
Whether this stack is non-canonical (using a construction known to be unnecessary for satisfaction)...
Definition: miniscript.h:307
constexpr friend SatInfo operator+(const SatInfo &a, const SatInfo &b) noexcept
Script set concatenation.
Definition: miniscript.h:448
Definition: messages.h:20
MaxInt< uint32_t > sat
Number of keys in possibly executed OP_CHECKMULTISIG(VERIFY)s to satisfy.
Definition: miniscript.h:374
int flags
Definition: bitcoin-tx.cpp:536
constexpr C * begin() const noexcept
Definition: span.h:175
OP_SIZE OP_0NOTEQUAL OP_IF [X] OP_ENDIF.
const std::vector< Key > keys
The keys used by this expression (only for PK_K/PK_H/MULTI)
Definition: miniscript.h:510
bool operator==(const Node< Key > &arg) const
Equality testing.
Definition: miniscript.h:1656
static constexpr SatInfo Empty() noexcept
The empty script.
Definition: miniscript.h:459
static constexpr int32_t MAX_STANDARD_TX_WEIGHT
The maximum weight for transactions we&#39;re willing to relay/mine.
Definition: policy.h:34
bool IsSatisfiable(F fn) const
Determine whether a Miniscript node is satisfiable.
Definition: miniscript.h:1574
friend MaxInt< I > operator|(const MaxInt< I > &a, const MaxInt< I > &b)
Definition: miniscript.h:363
constexpr Type operator|(Type x) const
Compute the type with the union of properties.
Definition: miniscript.h:138
auto result
Definition: common-types.h:74
Result TreeEval(State root_state, DownFn &&downfn, UpFn upfn) const
Like TreeEvalMaybe, but always produces a result.
Definition: miniscript.h:682
std::optional< uint32_t > GetOps() const
Return the maximum number of ops needed to satisfy this script non-malleably.
Definition: miniscript.h:1502
bool CheckStackSize() const
Check the maximum stack size for this script against the policy limit.
Definition: miniscript.h:1535
Node(const Ctx &ctx, Fragment nt, std::vector< NodeRef< Key >> sub, uint32_t val=0)
Definition: miniscript.h:1681
InputStack & SetNonCanon()
Mark this input stack as non-canonical (known to not be necessary in non-malleable satisfactions)...
Definition: miniscript.cpp:316
constexpr uint32_t MAX_TAPSCRIPT_SAT_SIZE
Maximum possible stack size to spend a Taproot output (excluding the script itself).
Definition: miniscript.h:268
constexpr C * data() const noexcept
Definition: span.h:174
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:414
static const int MAX_OPS_PER_SCRIPT
Definition: script.h:31
Fragment
The different node types in miniscript.
Definition: miniscript.h:199
bool IsBKW() const
Whether this node is of type B, K or W.
Definition: miniscript.h:1518
static constexpr SatInfo Hash() noexcept
A script consisting of a single hash opcode.
Definition: miniscript.h:463
static constexpr SatInfo OP_DUP() noexcept
Definition: miniscript.h:472
size_t size
Serialized witness size.
Definition: miniscript.h:309
constexpr bool operator<<(Type x) const
Check whether the left hand&#39;s properties are superset of the right&#39;s (= left is a subtype of right)...
Definition: miniscript.h:144
InputStack & SetWithSig()
Mark this input stack as having a signature.
Definition: miniscript.cpp:311
static constexpr unsigned int MAX_STANDARD_P2WSH_STACK_ITEMS
The maximum number of witness stack items in a standard P2WSH script.
Definition: policy.h:50
InputStack()=default
Construct an empty stack (valid).
InputStack(std::vector< unsigned char > in)
Construct a valid single-element stack (with an element up to 75 bytes).
Definition: miniscript.h:315
static constexpr SatInfo OP_VERIFY() noexcept
Definition: miniscript.h:479
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: hex_base.cpp:29
std::vector< NodeRef< Key > > subs
Subexpressions (for WRAP_*/AND_*/OR_*/ANDOR/THRESH)
Definition: miniscript.h:514
static constexpr SatInfo OP_IFDUP(bool nonzero) noexcept
Definition: miniscript.h:473
NodeRef< Key > MakeNodeRef(Args &&... args)
Construct a miniscript node as a unique_ptr.
Definition: miniscript.h:196
std::optional< uint32_t > GetStackSize() const
Return the maximum number of stack elements needed to satisfy this script non-malleably.
Definition: miniscript.h:1523
DUP_IF wraps the top constructed node with d:
static int count
const internal::StackSize ss
Cached stack size bounds.
Definition: miniscript.h:549
bool IsValidTopLevel() const
Check whether this node is valid as a script on its own.
Definition: miniscript.h:1620
size_type size() const
Definition: prevector.h:294
std::optional< uint32_t > GetExecStackSize() const
Return the maximum size of the stack during execution of this script.
Definition: miniscript.h:1529
OP_SIZE 32 OP_EQUALVERIFY OP_SHA256 [hash] OP_EQUAL.
void DuplicateKeyCheck(const Ctx &ctx) const
Update duplicate key information in this Node.
Definition: miniscript.h:1440
An expression of type W (a: or s: wrappers).
constexpr bool operator<(Type x) const
Comparison operator to enable use in sets/maps (total ordering incompatible with <<).
Definition: miniscript.h:147
bool ValidSatisfactions() const
Whether successful non-malleable satisfactions are guaranteed to be valid.
Definition: miniscript.h:1635
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:97
uint256 Hash(const T &in1)
Compute the 256-bit hash of an object.
Definition: hash.h:75
constexpr Type(uint32_t flags) noexcept
Internal constructor.
Definition: miniscript.h:131
static constexpr SatInfo Push() noexcept
A script consisting of a single push opcode.
Definition: miniscript.h:461
Type GetType() const
Return the expression type.
Definition: miniscript.h:1557
NodeRef< typename Ctx::Key > FromScript(const CScript &script, const Ctx &ctx)
Definition: miniscript.h:2645
OP_SIZE 32 OP_EQUALVERIFY OP_HASH256 [hash] OP_EQUAL.
[key_0] OP_CHECKSIG ([key_n] OP_CHECKSIGADD)* [k] OP_NUMEQUAL (only within Tapscript ctx) ...
friend InputStack operator|(InputStack a, InputStack b)
Choose between two potential input stacks.
Definition: miniscript.cpp:340
static const std::vector< uint8_t > EMPTY
Definition: script.h:21
Node(internal::NoDupCheck, MiniscriptContext script_ctx, Fragment nt, std::vector< NodeRef< Key >> sub, uint32_t val=0)
Definition: miniscript.h:1667
Result TreeEval(UpFn upfn) const
Like TreeEval, but without downfn or State type.
Definition: miniscript.h:698
constexpr uint32_t MaxScriptSize(MiniscriptContext ms_ctx)
The maximum size of a script depending on the context.
Definition: miniscript.h:270
static const int MAX_STACK_SIZE
Definition: script.h:43
Node(internal::NoDupCheck, MiniscriptContext script_ctx, Fragment nt, std::vector< NodeRef< Key >> sub, std::vector< unsigned char > arg, uint32_t val=0)
Definition: miniscript.h:1659
CONSTEXPR_IF_NOT_DEBUG Span< C > last(std::size_t count) const noexcept
Definition: span.h:210
Node(internal::NoDupCheck, MiniscriptContext script_ctx, Fragment nt, std::vector< NodeRef< Key >> sub, std::vector< Key > key, uint32_t val=0)
Definition: miniscript.h:1663
constexpr unsigned int GetSizeOfCompactSize(uint64_t nSize)
Compact Size size < 253 – 1 byte size <= USHRT_MAX – 3 bytes (253 + 2 bytes) size <= UINT_MAX –...
Definition: serialize.h:297
If, inside an ENDIF context, we find an OP_ELSE, then we could be in either an or_i or an andor node...
void BuildBack(const MiniscriptContext script_ctx, Fragment nt, std::vector< NodeRef< Key >> &constructed, const bool reverse=false)
BuildBack pops the last two elements off constructed and wraps them in the specified Fragment...
Definition: miniscript.h:1776
constexpr uint32_t TX_BODY_LEEWAY_WEIGHT
Data other than the witness in a transaction. Overhead + vin count + one vin + vout count + one vout ...
Definition: miniscript.h:266
static constexpr SatInfo OP_EQUALVERIFY() noexcept
Definition: miniscript.h:474
This type encapsulates the miniscript type system properties.
Definition: miniscript.h:126
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:233
static const auto INVALID
A stack representing the lack of any (dis)satisfactions.
Definition: miniscript.h:339
static constexpr uint32_t MAX_TAPMINISCRIPT_STACK_ELEM_SIZE
The maximum size of a witness item for a Miniscript under Tapscript context. (A BIP340 signature with...
Definition: miniscript.h:257
static constexpr SatInfo If() noexcept
A script consisting of just OP_IF or OP_NOTIF.
Definition: miniscript.h:467
const internal::Ops ops
Cached ops counts.
Definition: miniscript.h:547
CScript ToScript(const Ctx &ctx) const
Definition: miniscript.h:750
std::optional< int64_t > ParseScriptNumber(const Opcode &in)
Determine whether the passed pair (created by DecomposeScript) is pushing a number.
Definition: miniscript.cpp:409
internal::StackSize CalcStackSize() const
Definition: miniscript.h:1018
constexpr uint32_t TX_OVERHEAD
version + nLockTime
Definition: miniscript.h:260
bool CheckTimeLocksMix() const
Check whether there is no satisfaction path that contains both timelocks and heightlocks.
Definition: miniscript.h:1629
static constexpr SatInfo OP_EQUAL() noexcept
Definition: miniscript.h:475