Bitcoin Core  28.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::shared_ptr<const Node<Key>>;
193 
195 template<typename Key, typename... Args>
196 NodeRef<Key> MakeNodeRef(Args&&... args) { return std::make_shared<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 
531 private:
539  const Type typ;
541  const size_t scriptlen;
547  mutable std::optional<bool> has_duplicate_keys;
548 
549 
551  size_t CalcScriptLen() const {
552  size_t subsize = 0;
553  for (const auto& sub : subs) {
554  subsize += sub->ScriptSize();
555  }
556  static constexpr auto NONE_MST{""_mst};
557  Type sub0type = subs.size() > 0 ? subs[0]->GetType() : NONE_MST;
558  return internal::ComputeScriptLen(fragment, sub0type, subsize, k, subs.size(), keys.size(), m_script_ctx);
559  }
560 
561  /* Apply a recursive algorithm to a Miniscript tree, without actual recursive calls.
562  *
563  * The algorithm is defined by two functions: downfn and upfn. Conceptually, the
564  * result can be thought of as first using downfn to compute a "state" for each node,
565  * from the root down to the leaves. Then upfn is used to compute a "result" for each
566  * node, from the leaves back up to the root, which is then returned. In the actual
567  * implementation, both functions are invoked in an interleaved fashion, performing a
568  * depth-first traversal of the tree.
569  *
570  * In more detail, it is invoked as node.TreeEvalMaybe<Result>(root, downfn, upfn):
571  * - root is the state of the root node, of type State.
572  * - downfn is a callable (State&, const Node&, size_t) -> State, which given a
573  * node, its state, and an index of one of its children, computes the state of that
574  * child. It can modify the state. Children of a given node will have downfn()
575  * called in order.
576  * - upfn is a callable (State&&, const Node&, Span<Result>) -> std::optional<Result>,
577  * which given a node, its state, and a Span of the results of its children,
578  * computes the result of the node. If std::nullopt is returned by upfn,
579  * TreeEvalMaybe() immediately returns std::nullopt.
580  * The return value of TreeEvalMaybe is the result of the root node.
581  *
582  * Result type cannot be bool due to the std::vector<bool> specialization.
583  */
584  template<typename Result, typename State, typename DownFn, typename UpFn>
585  std::optional<Result> TreeEvalMaybe(State root_state, DownFn downfn, UpFn upfn) const
586  {
588  struct StackElem
589  {
590  const Node& node;
591  size_t expanded;
592  State state;
593 
594  StackElem(const Node& node_, size_t exp_, State&& state_) :
595  node(node_), expanded(exp_), state(std::move(state_)) {}
596  };
597  /* Stack of tree nodes being explored. */
598  std::vector<StackElem> stack;
599  /* Results of subtrees so far. Their order and mapping to tree nodes
600  * is implicitly defined by stack. */
601  std::vector<Result> results;
602  stack.emplace_back(*this, 0, std::move(root_state));
603 
604  /* Here is a demonstration of the algorithm, for an example tree A(B,C(D,E),F).
605  * State variables are omitted for simplicity.
606  *
607  * First: stack=[(A,0)] results=[]
608  * stack=[(A,1),(B,0)] results=[]
609  * stack=[(A,1)] results=[B]
610  * stack=[(A,2),(C,0)] results=[B]
611  * stack=[(A,2),(C,1),(D,0)] results=[B]
612  * stack=[(A,2),(C,1)] results=[B,D]
613  * stack=[(A,2),(C,2),(E,0)] results=[B,D]
614  * stack=[(A,2),(C,2)] results=[B,D,E]
615  * stack=[(A,2)] results=[B,C]
616  * stack=[(A,3),(F,0)] results=[B,C]
617  * stack=[(A,3)] results=[B,C,F]
618  * Final: stack=[] results=[A]
619  */
620  while (stack.size()) {
621  const Node& node = stack.back().node;
622  if (stack.back().expanded < node.subs.size()) {
623  /* We encounter a tree node with at least one unexpanded child.
624  * Expand it. By the time we hit this node again, the result of
625  * that child (and all earlier children) will be at the end of `results`. */
626  size_t child_index = stack.back().expanded++;
627  State child_state = downfn(stack.back().state, node, child_index);
628  stack.emplace_back(*node.subs[child_index], 0, std::move(child_state));
629  continue;
630  }
631  // Invoke upfn with the last node.subs.size() elements of results as input.
632  assert(results.size() >= node.subs.size());
633  std::optional<Result> result{upfn(std::move(stack.back().state), node,
634  Span<Result>{results}.last(node.subs.size()))};
635  // If evaluation returns std::nullopt, abort immediately.
636  if (!result) return {};
637  // Replace the last node.subs.size() elements of results with the new result.
638  results.erase(results.end() - node.subs.size(), results.end());
639  results.push_back(std::move(*result));
640  stack.pop_back();
641  }
642  // The final remaining results element is the root result, return it.
643  assert(results.size() == 1);
644  return std::move(results[0]);
645  }
646 
649  template<typename Result, typename UpFn>
650  std::optional<Result> TreeEvalMaybe(UpFn upfn) const
651  {
652  struct DummyState {};
653  return TreeEvalMaybe<Result>(DummyState{},
654  [](DummyState, const Node&, size_t) { return DummyState{}; },
655  [&upfn](DummyState, const Node& node, Span<Result> subs) {
656  return upfn(node, subs);
657  }
658  );
659  }
660 
662  template<typename Result, typename State, typename DownFn, typename UpFn>
663  Result TreeEval(State root_state, DownFn&& downfn, UpFn upfn) const
664  {
665  // Invoke TreeEvalMaybe with upfn wrapped to return std::optional<Result>, and then
666  // unconditionally dereference the result (it cannot be std::nullopt).
667  return std::move(*TreeEvalMaybe<Result>(std::move(root_state),
668  std::forward<DownFn>(downfn),
669  [&upfn](State&& state, const Node& node, Span<Result> subs) {
670  Result res{upfn(std::move(state), node, subs)};
671  return std::optional<Result>(std::move(res));
672  }
673  ));
674  }
675 
678  template<typename Result, typename UpFn>
679  Result TreeEval(UpFn upfn) const
680  {
681  struct DummyState {};
682  return std::move(*TreeEvalMaybe<Result>(DummyState{},
683  [](DummyState, const Node&, size_t) { return DummyState{}; },
684  [&upfn](DummyState, const Node& node, Span<Result> subs) {
685  Result res{upfn(node, subs)};
686  return std::optional<Result>(std::move(res));
687  }
688  ));
689  }
690 
692  friend int Compare(const Node<Key>& node1, const Node<Key>& node2)
693  {
694  std::vector<std::pair<const Node<Key>&, const Node<Key>&>> queue;
695  queue.emplace_back(node1, node2);
696  while (!queue.empty()) {
697  const auto& [a, b] = queue.back();
698  queue.pop_back();
699  if (std::tie(a.fragment, a.k, a.keys, a.data) < std::tie(b.fragment, b.k, b.keys, b.data)) return -1;
700  if (std::tie(b.fragment, b.k, b.keys, b.data) < std::tie(a.fragment, a.k, a.keys, a.data)) return 1;
701  if (a.subs.size() < b.subs.size()) return -1;
702  if (b.subs.size() < a.subs.size()) return 1;
703  size_t n = a.subs.size();
704  for (size_t i = 0; i < n; ++i) {
705  queue.emplace_back(*a.subs[n - 1 - i], *b.subs[n - 1 - i]);
706  }
707  }
708  return 0;
709  }
710 
712  Type CalcType() const {
713  using namespace internal;
714 
715  // THRESH has a variable number of subexpressions
716  std::vector<Type> sub_types;
717  if (fragment == Fragment::THRESH) {
718  for (const auto& sub : subs) sub_types.push_back(sub->GetType());
719  }
720  // All other nodes than THRESH can be computed just from the types of the 0-3 subexpressions.
721  static constexpr auto NONE_MST{""_mst};
722  Type x = subs.size() > 0 ? subs[0]->GetType() : NONE_MST;
723  Type y = subs.size() > 1 ? subs[1]->GetType() : NONE_MST;
724  Type z = subs.size() > 2 ? subs[2]->GetType() : NONE_MST;
725 
726  return SanitizeType(ComputeType(fragment, x, y, z, sub_types, k, data.size(), subs.size(), keys.size(), m_script_ctx));
727  }
728 
729 public:
730  template<typename Ctx>
731  CScript ToScript(const Ctx& ctx) const
732  {
733  // To construct the CScript for a Miniscript object, we use the TreeEval algorithm.
734  // The State is a boolean: whether or not the node's script expansion is followed
735  // by an OP_VERIFY (which may need to be combined with the last script opcode).
736  auto downfn = [](bool verify, const Node& node, size_t index) {
737  // For WRAP_V, the subexpression is certainly followed by OP_VERIFY.
738  if (node.fragment == Fragment::WRAP_V) return true;
739  // The subexpression of WRAP_S, and the last subexpression of AND_V
740  // inherit the followed-by-OP_VERIFY property from the parent.
741  if (node.fragment == Fragment::WRAP_S ||
742  (node.fragment == Fragment::AND_V && index == 1)) return verify;
743  return false;
744  };
745  // The upward function computes for a node, given its followed-by-OP_VERIFY status
746  // and the CScripts of its child nodes, the CScript of the node.
747  const bool is_tapscript{IsTapscript(m_script_ctx)};
748  auto upfn = [&ctx, is_tapscript](bool verify, const Node& node, Span<CScript> subs) -> CScript {
749  switch (node.fragment) {
750  case Fragment::PK_K: return BuildScript(ctx.ToPKBytes(node.keys[0]));
751  case Fragment::PK_H: return BuildScript(OP_DUP, OP_HASH160, ctx.ToPKHBytes(node.keys[0]), OP_EQUALVERIFY);
759  case Fragment::WRAP_S: return BuildScript(OP_SWAP, subs[0]);
760  case Fragment::WRAP_C: return BuildScript(std::move(subs[0]), verify ? OP_CHECKSIGVERIFY : OP_CHECKSIG);
762  case Fragment::WRAP_V: {
763  if (node.subs[0]->GetType() << "x"_mst) {
764  return BuildScript(std::move(subs[0]), OP_VERIFY);
765  } else {
766  return std::move(subs[0]);
767  }
768  }
770  case Fragment::WRAP_N: return BuildScript(std::move(subs[0]), OP_0NOTEQUAL);
771  case Fragment::JUST_1: return BuildScript(OP_1);
772  case Fragment::JUST_0: return BuildScript(OP_0);
773  case Fragment::AND_V: return BuildScript(std::move(subs[0]), subs[1]);
774  case Fragment::AND_B: return BuildScript(std::move(subs[0]), subs[1], OP_BOOLAND);
775  case Fragment::OR_B: return BuildScript(std::move(subs[0]), subs[1], OP_BOOLOR);
776  case Fragment::OR_D: return BuildScript(std::move(subs[0]), OP_IFDUP, OP_NOTIF, subs[1], OP_ENDIF);
777  case Fragment::OR_C: return BuildScript(std::move(subs[0]), OP_NOTIF, subs[1], OP_ENDIF);
778  case Fragment::OR_I: return BuildScript(OP_IF, subs[0], OP_ELSE, subs[1], OP_ENDIF);
779  case Fragment::ANDOR: return BuildScript(std::move(subs[0]), OP_NOTIF, subs[2], OP_ELSE, subs[1], OP_ENDIF);
780  case Fragment::MULTI: {
781  CHECK_NONFATAL(!is_tapscript);
783  for (const auto& key : node.keys) {
784  script = BuildScript(std::move(script), ctx.ToPKBytes(key));
785  }
786  return BuildScript(std::move(script), node.keys.size(), verify ? OP_CHECKMULTISIGVERIFY : OP_CHECKMULTISIG);
787  }
788  case Fragment::MULTI_A: {
789  CHECK_NONFATAL(is_tapscript);
790  CScript script = BuildScript(ctx.ToPKBytes(*node.keys.begin()), OP_CHECKSIG);
791  for (auto it = node.keys.begin() + 1; it != node.keys.end(); ++it) {
792  script = BuildScript(std::move(script), ctx.ToPKBytes(*it), OP_CHECKSIGADD);
793  }
794  return BuildScript(std::move(script), node.k, verify ? OP_NUMEQUALVERIFY : OP_NUMEQUAL);
795  }
796  case Fragment::THRESH: {
797  CScript script = std::move(subs[0]);
798  for (size_t i = 1; i < subs.size(); ++i) {
799  script = BuildScript(std::move(script), subs[i], OP_ADD);
800  }
801  return BuildScript(std::move(script), node.k, verify ? OP_EQUALVERIFY : OP_EQUAL);
802  }
803  }
804  assert(false);
805  };
806  return TreeEval<CScript>(false, downfn, upfn);
807  }
808 
809  template<typename CTx>
810  std::optional<std::string> ToString(const CTx& ctx) const {
811  // To construct the std::string representation for a Miniscript object, we use
812  // the TreeEvalMaybe algorithm. The State is a boolean: whether the parent node is a
813  // wrapper. If so, non-wrapper expressions must be prefixed with a ":".
814  auto downfn = [](bool, const Node& node, size_t) {
815  return (node.fragment == Fragment::WRAP_A || node.fragment == Fragment::WRAP_S ||
816  node.fragment == Fragment::WRAP_D || node.fragment == Fragment::WRAP_V ||
817  node.fragment == Fragment::WRAP_J || node.fragment == Fragment::WRAP_N ||
818  node.fragment == Fragment::WRAP_C ||
819  (node.fragment == Fragment::AND_V && node.subs[1]->fragment == Fragment::JUST_1) ||
820  (node.fragment == Fragment::OR_I && node.subs[0]->fragment == Fragment::JUST_0) ||
821  (node.fragment == Fragment::OR_I && node.subs[1]->fragment == Fragment::JUST_0));
822  };
823  // The upward function computes for a node, given whether its parent is a wrapper,
824  // and the string representations of its child nodes, the string representation of the node.
825  const bool is_tapscript{IsTapscript(m_script_ctx)};
826  auto upfn = [&ctx, is_tapscript](bool wrapped, const Node& node, Span<std::string> subs) -> std::optional<std::string> {
827  std::string ret = wrapped ? ":" : "";
828 
829  switch (node.fragment) {
830  case Fragment::WRAP_A: return "a" + std::move(subs[0]);
831  case Fragment::WRAP_S: return "s" + std::move(subs[0]);
832  case Fragment::WRAP_C:
833  if (node.subs[0]->fragment == Fragment::PK_K) {
834  // pk(K) is syntactic sugar for c:pk_k(K)
835  auto key_str = ctx.ToString(node.subs[0]->keys[0]);
836  if (!key_str) return {};
837  return std::move(ret) + "pk(" + std::move(*key_str) + ")";
838  }
839  if (node.subs[0]->fragment == Fragment::PK_H) {
840  // pkh(K) is syntactic sugar for c:pk_h(K)
841  auto key_str = ctx.ToString(node.subs[0]->keys[0]);
842  if (!key_str) return {};
843  return std::move(ret) + "pkh(" + std::move(*key_str) + ")";
844  }
845  return "c" + std::move(subs[0]);
846  case Fragment::WRAP_D: return "d" + std::move(subs[0]);
847  case Fragment::WRAP_V: return "v" + std::move(subs[0]);
848  case Fragment::WRAP_J: return "j" + std::move(subs[0]);
849  case Fragment::WRAP_N: return "n" + std::move(subs[0]);
850  case Fragment::AND_V:
851  // t:X is syntactic sugar for and_v(X,1).
852  if (node.subs[1]->fragment == Fragment::JUST_1) return "t" + std::move(subs[0]);
853  break;
854  case Fragment::OR_I:
855  if (node.subs[0]->fragment == Fragment::JUST_0) return "l" + std::move(subs[1]);
856  if (node.subs[1]->fragment == Fragment::JUST_0) return "u" + std::move(subs[0]);
857  break;
858  default: break;
859  }
860  switch (node.fragment) {
861  case Fragment::PK_K: {
862  auto key_str = ctx.ToString(node.keys[0]);
863  if (!key_str) return {};
864  return std::move(ret) + "pk_k(" + std::move(*key_str) + ")";
865  }
866  case Fragment::PK_H: {
867  auto key_str = ctx.ToString(node.keys[0]);
868  if (!key_str) return {};
869  return std::move(ret) + "pk_h(" + std::move(*key_str) + ")";
870  }
871  case Fragment::AFTER: return std::move(ret) + "after(" + util::ToString(node.k) + ")";
872  case Fragment::OLDER: return std::move(ret) + "older(" + util::ToString(node.k) + ")";
873  case Fragment::HASH256: return std::move(ret) + "hash256(" + HexStr(node.data) + ")";
874  case Fragment::HASH160: return std::move(ret) + "hash160(" + HexStr(node.data) + ")";
875  case Fragment::SHA256: return std::move(ret) + "sha256(" + HexStr(node.data) + ")";
876  case Fragment::RIPEMD160: return std::move(ret) + "ripemd160(" + HexStr(node.data) + ")";
877  case Fragment::JUST_1: return std::move(ret) + "1";
878  case Fragment::JUST_0: return std::move(ret) + "0";
879  case Fragment::AND_V: return std::move(ret) + "and_v(" + std::move(subs[0]) + "," + std::move(subs[1]) + ")";
880  case Fragment::AND_B: return std::move(ret) + "and_b(" + std::move(subs[0]) + "," + std::move(subs[1]) + ")";
881  case Fragment::OR_B: return std::move(ret) + "or_b(" + std::move(subs[0]) + "," + std::move(subs[1]) + ")";
882  case Fragment::OR_D: return std::move(ret) + "or_d(" + std::move(subs[0]) + "," + std::move(subs[1]) + ")";
883  case Fragment::OR_C: return std::move(ret) + "or_c(" + std::move(subs[0]) + "," + std::move(subs[1]) + ")";
884  case Fragment::OR_I: return std::move(ret) + "or_i(" + std::move(subs[0]) + "," + std::move(subs[1]) + ")";
885  case Fragment::ANDOR:
886  // and_n(X,Y) is syntactic sugar for andor(X,Y,0).
887  if (node.subs[2]->fragment == Fragment::JUST_0) return std::move(ret) + "and_n(" + std::move(subs[0]) + "," + std::move(subs[1]) + ")";
888  return std::move(ret) + "andor(" + std::move(subs[0]) + "," + std::move(subs[1]) + "," + std::move(subs[2]) + ")";
889  case Fragment::MULTI: {
890  CHECK_NONFATAL(!is_tapscript);
891  auto str = std::move(ret) + "multi(" + util::ToString(node.k);
892  for (const auto& key : node.keys) {
893  auto key_str = ctx.ToString(key);
894  if (!key_str) return {};
895  str += "," + std::move(*key_str);
896  }
897  return std::move(str) + ")";
898  }
899  case Fragment::MULTI_A: {
900  CHECK_NONFATAL(is_tapscript);
901  auto str = std::move(ret) + "multi_a(" + util::ToString(node.k);
902  for (const auto& key : node.keys) {
903  auto key_str = ctx.ToString(key);
904  if (!key_str) return {};
905  str += "," + std::move(*key_str);
906  }
907  return std::move(str) + ")";
908  }
909  case Fragment::THRESH: {
910  auto str = std::move(ret) + "thresh(" + util::ToString(node.k);
911  for (auto& sub : subs) {
912  str += "," + std::move(sub);
913  }
914  return std::move(str) + ")";
915  }
916  default: break;
917  }
918  assert(false);
919  };
920 
921  return TreeEvalMaybe<std::string>(false, downfn, upfn);
922  }
923 
924 private:
926  switch (fragment) {
927  case Fragment::JUST_1: return {0, 0, {}};
928  case Fragment::JUST_0: return {0, {}, 0};
929  case Fragment::PK_K: return {0, 0, 0};
930  case Fragment::PK_H: return {3, 0, 0};
931  case Fragment::OLDER:
932  case Fragment::AFTER: return {1, 0, {}};
933  case Fragment::SHA256:
934  case Fragment::RIPEMD160:
935  case Fragment::HASH256:
936  case Fragment::HASH160: return {4, 0, {}};
937  case Fragment::AND_V: return {subs[0]->ops.count + subs[1]->ops.count, subs[0]->ops.sat + subs[1]->ops.sat, {}};
938  case Fragment::AND_B: {
939  const auto count{1 + subs[0]->ops.count + subs[1]->ops.count};
940  const auto sat{subs[0]->ops.sat + subs[1]->ops.sat};
941  const auto dsat{subs[0]->ops.dsat + subs[1]->ops.dsat};
942  return {count, sat, dsat};
943  }
944  case Fragment::OR_B: {
945  const auto count{1 + subs[0]->ops.count + subs[1]->ops.count};
946  const auto sat{(subs[0]->ops.sat + subs[1]->ops.dsat) | (subs[1]->ops.sat + subs[0]->ops.dsat)};
947  const auto dsat{subs[0]->ops.dsat + subs[1]->ops.dsat};
948  return {count, sat, dsat};
949  }
950  case Fragment::OR_D: {
951  const auto count{3 + subs[0]->ops.count + subs[1]->ops.count};
952  const auto sat{subs[0]->ops.sat | (subs[1]->ops.sat + subs[0]->ops.dsat)};
953  const auto dsat{subs[0]->ops.dsat + subs[1]->ops.dsat};
954  return {count, sat, dsat};
955  }
956  case Fragment::OR_C: {
957  const auto count{2 + subs[0]->ops.count + subs[1]->ops.count};
958  const auto sat{subs[0]->ops.sat | (subs[1]->ops.sat + subs[0]->ops.dsat)};
959  return {count, sat, {}};
960  }
961  case Fragment::OR_I: {
962  const auto count{3 + subs[0]->ops.count + subs[1]->ops.count};
963  const auto sat{subs[0]->ops.sat | subs[1]->ops.sat};
964  const auto dsat{subs[0]->ops.dsat | subs[1]->ops.dsat};
965  return {count, sat, dsat};
966  }
967  case Fragment::ANDOR: {
968  const auto count{3 + subs[0]->ops.count + subs[1]->ops.count + subs[2]->ops.count};
969  const auto sat{(subs[1]->ops.sat + subs[0]->ops.sat) | (subs[0]->ops.dsat + subs[2]->ops.sat)};
970  const auto dsat{subs[0]->ops.dsat + subs[2]->ops.dsat};
971  return {count, sat, dsat};
972  }
973  case Fragment::MULTI: return {1, (uint32_t)keys.size(), (uint32_t)keys.size()};
974  case Fragment::MULTI_A: return {(uint32_t)keys.size() + 1, 0, 0};
975  case Fragment::WRAP_S:
976  case Fragment::WRAP_C:
977  case Fragment::WRAP_N: return {1 + subs[0]->ops.count, subs[0]->ops.sat, subs[0]->ops.dsat};
978  case Fragment::WRAP_A: return {2 + subs[0]->ops.count, subs[0]->ops.sat, subs[0]->ops.dsat};
979  case Fragment::WRAP_D: return {3 + subs[0]->ops.count, subs[0]->ops.sat, 0};
980  case Fragment::WRAP_J: return {4 + subs[0]->ops.count, subs[0]->ops.sat, 0};
981  case Fragment::WRAP_V: return {subs[0]->ops.count + (subs[0]->GetType() << "x"_mst), subs[0]->ops.sat, {}};
982  case Fragment::THRESH: {
983  uint32_t count = 0;
984  auto sats = Vector(internal::MaxInt<uint32_t>(0));
985  for (const auto& sub : subs) {
986  count += sub->ops.count + 1;
987  auto next_sats = Vector(sats[0] + sub->ops.dsat);
988  for (size_t j = 1; j < sats.size(); ++j) next_sats.push_back((sats[j] + sub->ops.dsat) | (sats[j - 1] + sub->ops.sat));
989  next_sats.push_back(sats[sats.size() - 1] + sub->ops.sat);
990  sats = std::move(next_sats);
991  }
992  assert(k <= sats.size());
993  return {count, sats[k], sats[0]};
994  }
995  }
996  assert(false);
997  }
998 
1000  using namespace internal;
1001  switch (fragment) {
1002  case Fragment::JUST_0: return {{}, SatInfo::Push()};
1003  case Fragment::JUST_1: return {SatInfo::Push(), {}};
1004  case Fragment::OLDER:
1005  case Fragment::AFTER: return {SatInfo::Push() + SatInfo::Nop(), {}};
1006  case Fragment::PK_K: return {SatInfo::Push()};
1007  case Fragment::PK_H: return {SatInfo::OP_DUP() + SatInfo::Hash() + SatInfo::Push() + SatInfo::OP_EQUALVERIFY()};
1008  case Fragment::SHA256:
1009  case Fragment::RIPEMD160:
1010  case Fragment::HASH256:
1011  case Fragment::HASH160: return {
1012  SatInfo::OP_SIZE() + SatInfo::Push() + SatInfo::OP_EQUALVERIFY() + SatInfo::Hash() + SatInfo::Push() + SatInfo::OP_EQUAL(),
1013  {}
1014  };
1015  case Fragment::ANDOR: {
1016  const auto& x{subs[0]->ss};
1017  const auto& y{subs[1]->ss};
1018  const auto& z{subs[2]->ss};
1019  return {
1020  (x.sat + SatInfo::If() + y.sat) | (x.dsat + SatInfo::If() + z.sat),
1021  x.dsat + SatInfo::If() + z.dsat
1022  };
1023  }
1024  case Fragment::AND_V: {
1025  const auto& x{subs[0]->ss};
1026  const auto& y{subs[1]->ss};
1027  return {x.sat + y.sat, {}};
1028  }
1029  case Fragment::AND_B: {
1030  const auto& x{subs[0]->ss};
1031  const auto& y{subs[1]->ss};
1032  return {x.sat + y.sat + SatInfo::BinaryOp(), x.dsat + y.dsat + SatInfo::BinaryOp()};
1033  }
1034  case Fragment::OR_B: {
1035  const auto& x{subs[0]->ss};
1036  const auto& y{subs[1]->ss};
1037  return {
1038  ((x.sat + y.dsat) | (x.dsat + y.sat)) + SatInfo::BinaryOp(),
1039  x.dsat + y.dsat + SatInfo::BinaryOp()
1040  };
1041  }
1042  case Fragment::OR_C: {
1043  const auto& x{subs[0]->ss};
1044  const auto& y{subs[1]->ss};
1045  return {(x.sat + SatInfo::If()) | (x.dsat + SatInfo::If() + y.sat), {}};
1046  }
1047  case Fragment::OR_D: {
1048  const auto& x{subs[0]->ss};
1049  const auto& y{subs[1]->ss};
1050  return {
1051  (x.sat + SatInfo::OP_IFDUP(true) + SatInfo::If()) | (x.dsat + SatInfo::OP_IFDUP(false) + SatInfo::If() + y.sat),
1052  x.dsat + SatInfo::OP_IFDUP(false) + SatInfo::If() + y.dsat
1053  };
1054  }
1055  case Fragment::OR_I: {
1056  const auto& x{subs[0]->ss};
1057  const auto& y{subs[1]->ss};
1058  return {SatInfo::If() + (x.sat | y.sat), SatInfo::If() + (x.dsat | y.dsat)};
1059  }
1060  // multi(k, key1, key2, ..., key_n) starts off with k+1 stack elements (a 0, plus k
1061  // signatures), then reaches n+k+3 stack elements after pushing the n keys, plus k and
1062  // n itself, and ends with 1 stack element (success or failure). Thus, it net removes
1063  // k elements (from k+1 to 1), while reaching k+n+2 more than it ends with.
1064  case Fragment::MULTI: return {SatInfo(k, k + keys.size() + 2)};
1065  // multi_a(k, key1, key2, ..., key_n) starts off with n stack elements (the
1066  // signatures), reaches 1 more (after the first key push), and ends with 1. Thus it net
1067  // removes n-1 elements (from n to 1) while reaching n more than it ends with.
1068  case Fragment::MULTI_A: return {SatInfo(keys.size() - 1, keys.size())};
1069  case Fragment::WRAP_A:
1070  case Fragment::WRAP_N:
1071  case Fragment::WRAP_S: return subs[0]->ss;
1072  case Fragment::WRAP_C: return {
1073  subs[0]->ss.sat + SatInfo::OP_CHECKSIG(),
1074  subs[0]->ss.dsat + SatInfo::OP_CHECKSIG()
1075  };
1076  case Fragment::WRAP_D: return {
1077  SatInfo::OP_DUP() + SatInfo::If() + subs[0]->ss.sat,
1078  SatInfo::OP_DUP() + SatInfo::If()
1079  };
1080  case Fragment::WRAP_V: return {subs[0]->ss.sat + SatInfo::OP_VERIFY(), {}};
1081  case Fragment::WRAP_J: return {
1082  SatInfo::OP_SIZE() + SatInfo::OP_0NOTEQUAL() + SatInfo::If() + subs[0]->ss.sat,
1083  SatInfo::OP_SIZE() + SatInfo::OP_0NOTEQUAL() + SatInfo::If()
1084  };
1085  case Fragment::THRESH: {
1086  // sats[j] is the SatInfo corresponding to all traces reaching j satisfactions.
1087  auto sats = Vector(SatInfo::Empty());
1088  for (size_t i = 0; i < subs.size(); ++i) {
1089  // Loop over the subexpressions, processing them one by one. After adding
1090  // element i we need to add OP_ADD (if i>0).
1091  auto add = i ? SatInfo::BinaryOp() : SatInfo::Empty();
1092  // Construct a variable that will become the next sats, starting with index 0.
1093  auto next_sats = Vector(sats[0] + subs[i]->ss.dsat + add);
1094  // Then loop to construct next_sats[1..i].
1095  for (size_t j = 1; j < sats.size(); ++j) {
1096  next_sats.push_back(((sats[j] + subs[i]->ss.dsat) | (sats[j - 1] + subs[i]->ss.sat)) + add);
1097  }
1098  // Finally construct next_sats[i+1].
1099  next_sats.push_back(sats[sats.size() - 1] + subs[i]->ss.sat + add);
1100  // Switch over.
1101  sats = std::move(next_sats);
1102  }
1103  // To satisfy thresh we need k satisfactions; to dissatisfy we need 0. In both
1104  // cases a push of k and an OP_EQUAL follow.
1105  return {
1106  sats[k] + SatInfo::Push() + SatInfo::OP_EQUAL(),
1107  sats[0] + SatInfo::Push() + SatInfo::OP_EQUAL()
1108  };
1109  }
1110  }
1111  assert(false);
1112  }
1113 
1115  const uint32_t sig_size = IsTapscript(m_script_ctx) ? 1 + 65 : 1 + 72;
1116  const uint32_t pubkey_size = IsTapscript(m_script_ctx) ? 1 + 32 : 1 + 33;
1117  switch (fragment) {
1118  case Fragment::JUST_0: return {{}, 0};
1119  case Fragment::JUST_1:
1120  case Fragment::OLDER:
1121  case Fragment::AFTER: return {0, {}};
1122  case Fragment::PK_K: return {sig_size, 1};
1123  case Fragment::PK_H: return {sig_size + pubkey_size, 1 + pubkey_size};
1124  case Fragment::SHA256:
1125  case Fragment::RIPEMD160:
1126  case Fragment::HASH256:
1127  case Fragment::HASH160: return {1 + 32, {}};
1128  case Fragment::ANDOR: {
1129  const auto sat{(subs[0]->ws.sat + subs[1]->ws.sat) | (subs[0]->ws.dsat + subs[2]->ws.sat)};
1130  const auto dsat{subs[0]->ws.dsat + subs[2]->ws.dsat};
1131  return {sat, dsat};
1132  }
1133  case Fragment::AND_V: return {subs[0]->ws.sat + subs[1]->ws.sat, {}};
1134  case Fragment::AND_B: return {subs[0]->ws.sat + subs[1]->ws.sat, subs[0]->ws.dsat + subs[1]->ws.dsat};
1135  case Fragment::OR_B: {
1136  const auto sat{(subs[0]->ws.dsat + subs[1]->ws.sat) | (subs[0]->ws.sat + subs[1]->ws.dsat)};
1137  const auto dsat{subs[0]->ws.dsat + subs[1]->ws.dsat};
1138  return {sat, dsat};
1139  }
1140  case Fragment::OR_C: return {subs[0]->ws.sat | (subs[0]->ws.dsat + subs[1]->ws.sat), {}};
1141  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};
1142  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)};
1143  case Fragment::MULTI: return {k * sig_size + 1, k + 1};
1144  case Fragment::MULTI_A: return {k * sig_size + static_cast<uint32_t>(keys.size()) - k, static_cast<uint32_t>(keys.size())};
1145  case Fragment::WRAP_A:
1146  case Fragment::WRAP_N:
1147  case Fragment::WRAP_S:
1148  case Fragment::WRAP_C: return subs[0]->ws;
1149  case Fragment::WRAP_D: return {1 + 1 + subs[0]->ws.sat, 1};
1150  case Fragment::WRAP_V: return {subs[0]->ws.sat, {}};
1151  case Fragment::WRAP_J: return {subs[0]->ws.sat, 1};
1152  case Fragment::THRESH: {
1153  auto sats = Vector(internal::MaxInt<uint32_t>(0));
1154  for (const auto& sub : subs) {
1155  auto next_sats = Vector(sats[0] + sub->ws.dsat);
1156  for (size_t j = 1; j < sats.size(); ++j) next_sats.push_back((sats[j] + sub->ws.dsat) | (sats[j - 1] + sub->ws.sat));
1157  next_sats.push_back(sats[sats.size() - 1] + sub->ws.sat);
1158  sats = std::move(next_sats);
1159  }
1160  assert(k <= sats.size());
1161  return {sats[k], sats[0]};
1162  }
1163  }
1164  assert(false);
1165  }
1166 
1167  template<typename Ctx>
1168  internal::InputResult ProduceInput(const Ctx& ctx) const {
1169  using namespace internal;
1170 
1171  // Internal function which is invoked for every tree node, constructing satisfaction/dissatisfactions
1172  // given those of its subnodes.
1173  auto helper = [&ctx](const Node& node, Span<InputResult> subres) -> InputResult {
1174  switch (node.fragment) {
1175  case Fragment::PK_K: {
1176  std::vector<unsigned char> sig;
1177  Availability avail = ctx.Sign(node.keys[0], sig);
1178  return {ZERO, InputStack(std::move(sig)).SetWithSig().SetAvailable(avail)};
1179  }
1180  case Fragment::PK_H: {
1181  std::vector<unsigned char> key = ctx.ToPKBytes(node.keys[0]), sig;
1182  Availability avail = ctx.Sign(node.keys[0], sig);
1183  return {ZERO + InputStack(key), (InputStack(std::move(sig)).SetWithSig() + InputStack(key)).SetAvailable(avail)};
1184  }
1185  case Fragment::MULTI_A: {
1186  // sats[j] represents the best stack containing j valid signatures (out of the first i keys).
1187  // In the loop below, these stacks are built up using a dynamic programming approach.
1188  std::vector<InputStack> sats = Vector(EMPTY);
1189  for (size_t i = 0; i < node.keys.size(); ++i) {
1190  // Get the signature for the i'th key in reverse order (the signature for the first key needs to
1191  // be at the top of the stack, contrary to CHECKMULTISIG's satisfaction).
1192  std::vector<unsigned char> sig;
1193  Availability avail = ctx.Sign(node.keys[node.keys.size() - 1 - i], sig);
1194  // Compute signature stack for just this key.
1195  auto sat = InputStack(std::move(sig)).SetWithSig().SetAvailable(avail);
1196  // Compute the next sats vector: next_sats[0] is a copy of sats[0] (no signatures). All further
1197  // next_sats[j] are equal to either the existing sats[j] + ZERO, or sats[j-1] plus a signature
1198  // for the current (i'th) key. The very last element needs all signatures filled.
1199  std::vector<InputStack> next_sats;
1200  next_sats.push_back(sats[0] + ZERO);
1201  for (size_t j = 1; j < sats.size(); ++j) next_sats.push_back((sats[j] + ZERO) | (std::move(sats[j - 1]) + sat));
1202  next_sats.push_back(std::move(sats[sats.size() - 1]) + std::move(sat));
1203  // Switch over.
1204  sats = std::move(next_sats);
1205  }
1206  // The dissatisfaction consists of as many empty vectors as there are keys, which is the same as
1207  // satisfying 0 keys.
1208  auto& nsat{sats[0]};
1209  assert(node.k != 0);
1210  assert(node.k <= sats.size());
1211  return {std::move(nsat), std::move(sats[node.k])};
1212  }
1213  case Fragment::MULTI: {
1214  // sats[j] represents the best stack containing j valid signatures (out of the first i keys).
1215  // In the loop below, these stacks are built up using a dynamic programming approach.
1216  // sats[0] starts off being {0}, due to the CHECKMULTISIG bug that pops off one element too many.
1217  std::vector<InputStack> sats = Vector(ZERO);
1218  for (size_t i = 0; i < node.keys.size(); ++i) {
1219  std::vector<unsigned char> sig;
1220  Availability avail = ctx.Sign(node.keys[i], sig);
1221  // Compute signature stack for just the i'th key.
1222  auto sat = InputStack(std::move(sig)).SetWithSig().SetAvailable(avail);
1223  // Compute the next sats vector: next_sats[0] is a copy of sats[0] (no signatures). All further
1224  // next_sats[j] are equal to either the existing sats[j], or sats[j-1] plus a signature for the
1225  // current (i'th) key. The very last element needs all signatures filled.
1226  std::vector<InputStack> next_sats;
1227  next_sats.push_back(sats[0]);
1228  for (size_t j = 1; j < sats.size(); ++j) next_sats.push_back(sats[j] | (std::move(sats[j - 1]) + sat));
1229  next_sats.push_back(std::move(sats[sats.size() - 1]) + std::move(sat));
1230  // Switch over.
1231  sats = std::move(next_sats);
1232  }
1233  // The dissatisfaction consists of k+1 stack elements all equal to 0.
1234  InputStack nsat = ZERO;
1235  for (size_t i = 0; i < node.k; ++i) nsat = std::move(nsat) + ZERO;
1236  assert(node.k <= sats.size());
1237  return {std::move(nsat), std::move(sats[node.k])};
1238  }
1239  case Fragment::THRESH: {
1240  // sats[k] represents the best stack that satisfies k out of the *last* i subexpressions.
1241  // In the loop below, these stacks are built up using a dynamic programming approach.
1242  // sats[0] starts off empty.
1243  std::vector<InputStack> sats = Vector(EMPTY);
1244  for (size_t i = 0; i < subres.size(); ++i) {
1245  // Introduce an alias for the i'th last satisfaction/dissatisfaction.
1246  auto& res = subres[subres.size() - i - 1];
1247  // Compute the next sats vector: next_sats[0] is sats[0] plus res.nsat (thus containing all dissatisfactions
1248  // so far. next_sats[j] is either sats[j] + res.nsat (reusing j earlier satisfactions) or sats[j-1] + res.sat
1249  // (reusing j-1 earlier satisfactions plus a new one). The very last next_sats[j] is all satisfactions.
1250  std::vector<InputStack> next_sats;
1251  next_sats.push_back(sats[0] + res.nsat);
1252  for (size_t j = 1; j < sats.size(); ++j) next_sats.push_back((sats[j] + res.nsat) | (std::move(sats[j - 1]) + res.sat));
1253  next_sats.push_back(std::move(sats[sats.size() - 1]) + std::move(res.sat));
1254  // Switch over.
1255  sats = std::move(next_sats);
1256  }
1257  // At this point, sats[k].sat is the best satisfaction for the overall thresh() node. The best dissatisfaction
1258  // is computed by gathering all sats[i].nsat for i != k.
1259  InputStack nsat = INVALID;
1260  for (size_t i = 0; i < sats.size(); ++i) {
1261  // i==k is the satisfaction; i==0 is the canonical dissatisfaction;
1262  // the rest are non-canonical (a no-signature dissatisfaction - the i=0
1263  // form - is always available) and malleable (due to overcompleteness).
1264  // Marking the solutions malleable here is not strictly necessary, as they
1265  // should already never be picked in non-malleable solutions due to the
1266  // availability of the i=0 form.
1267  if (i != 0 && i != node.k) sats[i].SetMalleable().SetNonCanon();
1268  // Include all dissatisfactions (even these non-canonical ones) in nsat.
1269  if (i != node.k) nsat = std::move(nsat) | std::move(sats[i]);
1270  }
1271  assert(node.k <= sats.size());
1272  return {std::move(nsat), std::move(sats[node.k])};
1273  }
1274  case Fragment::OLDER: {
1275  return {INVALID, ctx.CheckOlder(node.k) ? EMPTY : INVALID};
1276  }
1277  case Fragment::AFTER: {
1278  return {INVALID, ctx.CheckAfter(node.k) ? EMPTY : INVALID};
1279  }
1280  case Fragment::SHA256: {
1281  std::vector<unsigned char> preimage;
1282  Availability avail = ctx.SatSHA256(node.data, preimage);
1283  return {ZERO32, InputStack(std::move(preimage)).SetAvailable(avail)};
1284  }
1285  case Fragment::RIPEMD160: {
1286  std::vector<unsigned char> preimage;
1287  Availability avail = ctx.SatRIPEMD160(node.data, preimage);
1288  return {ZERO32, InputStack(std::move(preimage)).SetAvailable(avail)};
1289  }
1290  case Fragment::HASH256: {
1291  std::vector<unsigned char> preimage;
1292  Availability avail = ctx.SatHASH256(node.data, preimage);
1293  return {ZERO32, InputStack(std::move(preimage)).SetAvailable(avail)};
1294  }
1295  case Fragment::HASH160: {
1296  std::vector<unsigned char> preimage;
1297  Availability avail = ctx.SatHASH160(node.data, preimage);
1298  return {ZERO32, InputStack(std::move(preimage)).SetAvailable(avail)};
1299  }
1300  case Fragment::AND_V: {
1301  auto& x = subres[0], &y = subres[1];
1302  // As the dissatisfaction here only consist of a single option, it doesn't
1303  // actually need to be listed (it's not required for reasoning about malleability of
1304  // other options), and is never required (no valid miniscript relies on the ability
1305  // to satisfy the type V left subexpression). It's still listed here for
1306  // completeness, as a hypothetical (not currently implemented) satisfier that doesn't
1307  // care about malleability might in some cases prefer it still.
1308  return {(y.nsat + x.sat).SetNonCanon(), y.sat + x.sat};
1309  }
1310  case Fragment::AND_B: {
1311  auto& x = subres[0], &y = subres[1];
1312  // Note that it is not strictly necessary to mark the 2nd and 3rd dissatisfaction here
1313  // as malleable. While they are definitely malleable, they are also non-canonical due
1314  // to the guaranteed existence of a no-signature other dissatisfaction (the 1st)
1315  // option. Because of that, the 2nd and 3rd option will never be chosen, even if they
1316  // weren't marked as malleable.
1317  return {(y.nsat + x.nsat) | (y.sat + x.nsat).SetMalleable().SetNonCanon() | (y.nsat + x.sat).SetMalleable().SetNonCanon(), y.sat + x.sat};
1318  }
1319  case Fragment::OR_B: {
1320  auto& x = subres[0], &z = subres[1];
1321  // The (sat(Z) sat(X)) solution is overcomplete (attacker can change either into dsat).
1322  return {z.nsat + x.nsat, (z.nsat + x.sat) | (z.sat + x.nsat) | (z.sat + x.sat).SetMalleable().SetNonCanon()};
1323  }
1324  case Fragment::OR_C: {
1325  auto& x = subres[0], &z = subres[1];
1326  return {INVALID, std::move(x.sat) | (z.sat + x.nsat)};
1327  }
1328  case Fragment::OR_D: {
1329  auto& x = subres[0], &z = subres[1];
1330  return {z.nsat + x.nsat, std::move(x.sat) | (z.sat + x.nsat)};
1331  }
1332  case Fragment::OR_I: {
1333  auto& x = subres[0], &z = subres[1];
1334  return {(x.nsat + ONE) | (z.nsat + ZERO), (x.sat + ONE) | (z.sat + ZERO)};
1335  }
1336  case Fragment::ANDOR: {
1337  auto& x = subres[0], &y = subres[1], &z = subres[2];
1338  return {(y.nsat + x.sat).SetNonCanon() | (z.nsat + x.nsat), (y.sat + x.sat) | (z.sat + x.nsat)};
1339  }
1340  case Fragment::WRAP_A:
1341  case Fragment::WRAP_S:
1342  case Fragment::WRAP_C:
1343  case Fragment::WRAP_N:
1344  return std::move(subres[0]);
1345  case Fragment::WRAP_D: {
1346  auto &x = subres[0];
1347  return {ZERO, x.sat + ONE};
1348  }
1349  case Fragment::WRAP_J: {
1350  auto &x = subres[0];
1351  // If a dissatisfaction with a nonzero top stack element exists, an alternative dissatisfaction exists.
1352  // As the dissatisfaction logic currently doesn't keep track of this nonzeroness property, and thus even
1353  // if a dissatisfaction with a top zero element is found, we don't know whether another one with a
1354  // nonzero top stack element exists. Make the conservative assumption that whenever the subexpression is weakly
1355  // dissatisfiable, this alternative dissatisfaction exists and leads to malleability.
1356  return {InputStack(ZERO).SetMalleable(x.nsat.available != Availability::NO && !x.nsat.has_sig), std::move(x.sat)};
1357  }
1358  case Fragment::WRAP_V: {
1359  auto &x = subres[0];
1360  return {INVALID, std::move(x.sat)};
1361  }
1362  case Fragment::JUST_0: return {EMPTY, INVALID};
1363  case Fragment::JUST_1: return {INVALID, EMPTY};
1364  }
1365  assert(false);
1366  return {INVALID, INVALID};
1367  };
1368 
1369  auto tester = [&helper](const Node& node, Span<InputResult> subres) -> InputResult {
1370  auto ret = helper(node, subres);
1371 
1372  // Do a consistency check between the satisfaction code and the type checker
1373  // (the actual satisfaction code in ProduceInputHelper does not use GetType)
1374 
1375  // For 'z' nodes, available satisfactions/dissatisfactions must have stack size 0.
1376  if (node.GetType() << "z"_mst && ret.nsat.available != Availability::NO) assert(ret.nsat.stack.size() == 0);
1377  if (node.GetType() << "z"_mst && ret.sat.available != Availability::NO) assert(ret.sat.stack.size() == 0);
1378 
1379  // For 'o' nodes, available satisfactions/dissatisfactions must have stack size 1.
1380  if (node.GetType() << "o"_mst && ret.nsat.available != Availability::NO) assert(ret.nsat.stack.size() == 1);
1381  if (node.GetType() << "o"_mst && ret.sat.available != Availability::NO) assert(ret.sat.stack.size() == 1);
1382 
1383  // For 'n' nodes, available satisfactions/dissatisfactions must have stack size 1 or larger. For satisfactions,
1384  // the top element cannot be 0.
1385  if (node.GetType() << "n"_mst && ret.sat.available != Availability::NO) assert(ret.sat.stack.size() >= 1);
1386  if (node.GetType() << "n"_mst && ret.nsat.available != Availability::NO) assert(ret.nsat.stack.size() >= 1);
1387  if (node.GetType() << "n"_mst && ret.sat.available != Availability::NO) assert(!ret.sat.stack.back().empty());
1388 
1389  // For 'd' nodes, a dissatisfaction must exist, and they must not need a signature. If it is non-malleable,
1390  // it must be canonical.
1391  if (node.GetType() << "d"_mst) assert(ret.nsat.available != Availability::NO);
1392  if (node.GetType() << "d"_mst) assert(!ret.nsat.has_sig);
1393  if (node.GetType() << "d"_mst && !ret.nsat.malleable) assert(!ret.nsat.non_canon);
1394 
1395  // For 'f'/'s' nodes, dissatisfactions/satisfactions must have a signature.
1396  if (node.GetType() << "f"_mst && ret.nsat.available != Availability::NO) assert(ret.nsat.has_sig);
1397  if (node.GetType() << "s"_mst && ret.sat.available != Availability::NO) assert(ret.sat.has_sig);
1398 
1399  // For non-malleable 'e' nodes, a non-malleable dissatisfaction must exist.
1400  if (node.GetType() << "me"_mst) assert(ret.nsat.available != Availability::NO);
1401  if (node.GetType() << "me"_mst) assert(!ret.nsat.malleable);
1402 
1403  // For 'm' nodes, if a satisfaction exists, it must be non-malleable.
1404  if (node.GetType() << "m"_mst && ret.sat.available != Availability::NO) assert(!ret.sat.malleable);
1405 
1406  // If a non-malleable satisfaction exists, it must be canonical.
1407  if (ret.sat.available != Availability::NO && !ret.sat.malleable) assert(!ret.sat.non_canon);
1408 
1409  return ret;
1410  };
1411 
1412  return TreeEval<InputResult>(tester);
1413  }
1414 
1415 public:
1421  template<typename Ctx> void DuplicateKeyCheck(const Ctx& ctx) const
1422  {
1423  // We cannot use a lambda here, as lambdas are non assignable, and the set operations
1424  // below require moving the comparators around.
1425  struct Comp {
1426  const Ctx* ctx_ptr;
1427  Comp(const Ctx& ctx) : ctx_ptr(&ctx) {}
1428  bool operator()(const Key& a, const Key& b) const { return ctx_ptr->KeyCompare(a, b); }
1429  };
1430 
1431  // state in the recursive computation:
1432  // - std::nullopt means "this node has duplicates"
1433  // - an std::set means "this node has no duplicate keys, and they are: ...".
1434  using keyset = std::set<Key, Comp>;
1435  using state = std::optional<keyset>;
1436 
1437  auto upfn = [&ctx](const Node& node, Span<state> subs) -> state {
1438  // If this node is already known to have duplicates, nothing left to do.
1439  if (node.has_duplicate_keys.has_value() && *node.has_duplicate_keys) return {};
1440 
1441  // Check if one of the children is already known to have duplicates.
1442  for (auto& sub : subs) {
1443  if (!sub.has_value()) {
1444  node.has_duplicate_keys = true;
1445  return {};
1446  }
1447  }
1448 
1449  // Start building the set of keys involved in this node and children.
1450  // Start by keys in this node directly.
1451  size_t keys_count = node.keys.size();
1452  keyset key_set{node.keys.begin(), node.keys.end(), Comp(ctx)};
1453  if (key_set.size() != keys_count) {
1454  // It already has duplicates; bail out.
1455  node.has_duplicate_keys = true;
1456  return {};
1457  }
1458 
1459  // Merge the keys from the children into this set.
1460  for (auto& sub : subs) {
1461  keys_count += sub->size();
1462  // Small optimization: std::set::merge is linear in the size of the second arg but
1463  // logarithmic in the size of the first.
1464  if (key_set.size() < sub->size()) std::swap(key_set, *sub);
1465  key_set.merge(*sub);
1466  if (key_set.size() != keys_count) {
1467  node.has_duplicate_keys = true;
1468  return {};
1469  }
1470  }
1471 
1472  node.has_duplicate_keys = false;
1473  return key_set;
1474  };
1475 
1476  TreeEval<state>(upfn);
1477  }
1478 
1480  size_t ScriptSize() const { return scriptlen; }
1481 
1483  std::optional<uint32_t> GetOps() const {
1484  if (!ops.sat.valid) return {};
1485  return ops.count + ops.sat.value;
1486  }
1487 
1489  uint32_t GetStaticOps() const { return ops.count; }
1490 
1492  bool CheckOpsLimit() const {
1493  if (IsTapscript(m_script_ctx)) return true;
1494  if (const auto ops = GetOps()) return *ops <= MAX_OPS_PER_SCRIPT;
1495  return true;
1496  }
1497 
1499  bool IsBKW() const {
1500  return !((GetType() & "BKW"_mst) == ""_mst);
1501  }
1502 
1504  std::optional<uint32_t> GetStackSize() const {
1505  if (!ss.sat.valid) return {};
1506  return ss.sat.netdiff + static_cast<int32_t>(IsBKW());
1507  }
1508 
1510  std::optional<uint32_t> GetExecStackSize() const {
1511  if (!ss.sat.valid) return {};
1512  return ss.sat.exec + static_cast<int32_t>(IsBKW());
1513  }
1514 
1516  bool CheckStackSize() const {
1517  // Since in Tapscript there is no standardness limit on the script and witness sizes, we may run
1518  // into the maximum stack size while executing the script. Make sure it doesn't happen.
1519  if (IsTapscript(m_script_ctx)) {
1520  if (const auto exec_ss = GetExecStackSize()) return exec_ss <= MAX_STACK_SIZE;
1521  return true;
1522  }
1523  if (const auto ss = GetStackSize()) return *ss <= MAX_STANDARD_P2WSH_STACK_ITEMS;
1524  return true;
1525  }
1526 
1528  bool IsNotSatisfiable() const { return !GetStackSize(); }
1529 
1532  std::optional<uint32_t> GetWitnessSize() const {
1533  if (!ws.sat.valid) return {};
1534  return ws.sat.value;
1535  }
1536 
1538  Type GetType() const { return typ; }
1539 
1542 
1544  const Node* FindInsaneSub() const {
1545  return TreeEval<const Node*>([](const Node& node, Span<const Node*> subs) -> const Node* {
1546  for (auto& sub: subs) if (sub) return sub;
1547  if (!node.IsSaneSubexpression()) return &node;
1548  return nullptr;
1549  });
1550  }
1551 
1554  template<typename F>
1555  bool IsSatisfiable(F fn) const
1556  {
1557  // TreeEval() doesn't support bool as NodeType, so use int instead.
1558  return TreeEval<int>([&fn](const Node& node, Span<int> subs) -> bool {
1559  switch (node.fragment) {
1560  case Fragment::JUST_0:
1561  return false;
1562  case Fragment::JUST_1:
1563  return true;
1564  case Fragment::PK_K:
1565  case Fragment::PK_H:
1566  case Fragment::MULTI:
1567  case Fragment::MULTI_A:
1568  case Fragment::AFTER:
1569  case Fragment::OLDER:
1570  case Fragment::HASH256:
1571  case Fragment::HASH160:
1572  case Fragment::SHA256:
1573  case Fragment::RIPEMD160:
1574  return bool{fn(node)};
1575  case Fragment::ANDOR:
1576  return (subs[0] && subs[1]) || subs[2];
1577  case Fragment::AND_V:
1578  case Fragment::AND_B:
1579  return subs[0] && subs[1];
1580  case Fragment::OR_B:
1581  case Fragment::OR_C:
1582  case Fragment::OR_D:
1583  case Fragment::OR_I:
1584  return subs[0] || subs[1];
1585  case Fragment::THRESH:
1586  return static_cast<uint32_t>(std::count(subs.begin(), subs.end(), true)) >= node.k;
1587  default: // wrappers
1588  assert(subs.size() == 1);
1589  return subs[0];
1590  }
1591  });
1592  }
1593 
1595  bool IsValid() const {
1596  if (GetType() == ""_mst) return false;
1598  }
1599 
1601  bool IsValidTopLevel() const { return IsValid() && GetType() << "B"_mst; }
1602 
1604  bool IsNonMalleable() const { return GetType() << "m"_mst; }
1605 
1607  bool NeedsSignature() const { return GetType() << "s"_mst; }
1608 
1610  bool CheckTimeLocksMix() const { return GetType() << "k"_mst; }
1611 
1614 
1616  bool ValidSatisfactions() const { return IsValid() && CheckOpsLimit() && CheckStackSize(); }
1617 
1620 
1622  bool IsSane() const { return IsValidTopLevel() && IsSaneSubexpression() && NeedsSignature(); }
1623 
1628  template<typename Ctx>
1629  Availability Satisfy(const Ctx& ctx, std::vector<std::vector<unsigned char>>& stack, bool nonmalleable = true) const {
1630  auto ret = ProduceInput(ctx);
1631  if (nonmalleable && (ret.sat.malleable || !ret.sat.has_sig)) return Availability::NO;
1632  stack = std::move(ret.sat.stack);
1633  return ret.sat.available;
1634  }
1635 
1637  bool operator==(const Node<Key>& arg) const { return Compare(*this, arg) == 0; }
1638 
1639  // Constructors with various argument combinations, which bypass the duplicate key check.
1640  Node(internal::NoDupCheck, MiniscriptContext script_ctx, Fragment nt, std::vector<NodeRef<Key>> sub, std::vector<unsigned char> arg, uint32_t val = 0)
1641  : 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()) {}
1642  Node(internal::NoDupCheck, MiniscriptContext script_ctx, Fragment nt, std::vector<unsigned char> arg, uint32_t val = 0)
1643  : fragment(nt), k(val), data(std::move(arg)), m_script_ctx{script_ctx}, ops(CalcOps()), ss(CalcStackSize()), ws(CalcWitnessSize()), typ(CalcType()), scriptlen(CalcScriptLen()) {}
1644  Node(internal::NoDupCheck, MiniscriptContext script_ctx, Fragment nt, std::vector<NodeRef<Key>> sub, std::vector<Key> key, uint32_t val = 0)
1645  : 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()) {}
1646  Node(internal::NoDupCheck, MiniscriptContext script_ctx, Fragment nt, std::vector<Key> key, uint32_t val = 0)
1647  : fragment(nt), k(val), keys(std::move(key)), m_script_ctx{script_ctx}, ops(CalcOps()), ss(CalcStackSize()), ws(CalcWitnessSize()), typ(CalcType()), scriptlen(CalcScriptLen()) {}
1648  Node(internal::NoDupCheck, MiniscriptContext script_ctx, Fragment nt, std::vector<NodeRef<Key>> sub, uint32_t val = 0)
1649  : fragment(nt), k(val), subs(std::move(sub)), m_script_ctx{script_ctx}, ops(CalcOps()), ss(CalcStackSize()), ws(CalcWitnessSize()), typ(CalcType()), scriptlen(CalcScriptLen()) {}
1650  Node(internal::NoDupCheck, MiniscriptContext script_ctx, Fragment nt, uint32_t val = 0)
1651  : fragment(nt), k(val), m_script_ctx{script_ctx}, ops(CalcOps()), ss(CalcStackSize()), ws(CalcWitnessSize()), typ(CalcType()), scriptlen(CalcScriptLen()) {}
1652 
1653  // Constructors with various argument combinations, which do perform the duplicate key check.
1654  template <typename Ctx> Node(const Ctx& ctx, Fragment nt, std::vector<NodeRef<Key>> sub, std::vector<unsigned char> arg, uint32_t val = 0)
1655  : Node(internal::NoDupCheck{}, ctx.MsContext(), nt, std::move(sub), std::move(arg), val) { DuplicateKeyCheck(ctx); }
1656  template <typename Ctx> Node(const Ctx& ctx, Fragment nt, std::vector<unsigned char> arg, uint32_t val = 0)
1657  : Node(internal::NoDupCheck{}, ctx.MsContext(), nt, std::move(arg), val) { DuplicateKeyCheck(ctx);}
1658  template <typename Ctx> Node(const Ctx& ctx, Fragment nt, std::vector<NodeRef<Key>> sub, std::vector<Key> key, uint32_t val = 0)
1659  : Node(internal::NoDupCheck{}, ctx.MsContext(), nt, std::move(sub), std::move(key), val) { DuplicateKeyCheck(ctx); }
1660  template <typename Ctx> Node(const Ctx& ctx, Fragment nt, std::vector<Key> key, uint32_t val = 0)
1661  : Node(internal::NoDupCheck{}, ctx.MsContext(), nt, std::move(key), val) { DuplicateKeyCheck(ctx); }
1662  template <typename Ctx> Node(const Ctx& ctx, Fragment nt, std::vector<NodeRef<Key>> sub, uint32_t val = 0)
1663  : Node(internal::NoDupCheck{}, ctx.MsContext(), nt, std::move(sub), val) { DuplicateKeyCheck(ctx); }
1664  template <typename Ctx> Node(const Ctx& ctx, Fragment nt, uint32_t val = 0)
1665  : Node(internal::NoDupCheck{}, ctx.MsContext(), nt, val) { DuplicateKeyCheck(ctx); }
1666 };
1667 
1668 namespace internal {
1669 
1670 enum class ParseContext {
1672  WRAPPED_EXPR,
1674  EXPR,
1675 
1677  SWAP,
1679  ALT,
1681  CHECK,
1683  DUP_IF,
1685  VERIFY,
1687  NON_ZERO,
1689  ZERO_NOTEQUAL,
1691  WRAP_U,
1693  WRAP_T,
1694 
1696  AND_N,
1698  AND_V,
1700  AND_B,
1702  ANDOR,
1704  OR_B,
1706  OR_C,
1708  OR_D,
1710  OR_I,
1711 
1716  THRESH,
1717 
1719  COMMA,
1721  CLOSE_BRACKET,
1722 };
1723 
1724 int FindNextChar(Span<const char> in, const char m);
1725 
1727 template<typename Key, typename Ctx>
1728 std::optional<std::pair<Key, int>> ParseKeyEnd(Span<const char> in, const Ctx& ctx)
1729 {
1730  int key_size = FindNextChar(in, ')');
1731  if (key_size < 1) return {};
1732  auto key = ctx.FromString(in.begin(), in.begin() + key_size);
1733  if (!key) return {};
1734  return {{std::move(*key), key_size}};
1735 }
1736 
1738 template<typename Ctx>
1739 std::optional<std::pair<std::vector<unsigned char>, int>> ParseHexStrEnd(Span<const char> in, const size_t expected_size,
1740  const Ctx& ctx)
1741 {
1742  int hash_size = FindNextChar(in, ')');
1743  if (hash_size < 1) return {};
1744  std::string val = std::string(in.begin(), in.begin() + hash_size);
1745  if (!IsHex(val)) return {};
1746  auto hash = ParseHex(val);
1747  if (hash.size() != expected_size) return {};
1748  return {{std::move(hash), hash_size}};
1749 }
1750 
1752 template<typename Key>
1753 void BuildBack(const MiniscriptContext script_ctx, Fragment nt, std::vector<NodeRef<Key>>& constructed, const bool reverse = false)
1754 {
1755  NodeRef<Key> child = std::move(constructed.back());
1756  constructed.pop_back();
1757  if (reverse) {
1758  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, script_ctx, nt, Vector(std::move(child), std::move(constructed.back())));
1759  } else {
1760  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, script_ctx, nt, Vector(std::move(constructed.back()), std::move(child)));
1761  }
1762 }
1763 
1769 template<typename Key, typename Ctx>
1770 inline NodeRef<Key> Parse(Span<const char> in, const Ctx& ctx)
1771 {
1772  using namespace script;
1773 
1774  // Account for the minimum script size for all parsed fragments so far. It "borrows" 1
1775  // script byte from all leaf nodes, counting it instead whenever a space for a recursive
1776  // expression is added (through andor, and_*, or_*, thresh). This guarantees that all fragments
1777  // increment the script_size by at least one, except for:
1778  // - "0", "1": these leafs are only a single byte, so their subtracted-from increment is 0.
1779  // This is not an issue however, as "space" for them has to be created by combinators,
1780  // which do increment script_size.
1781  // - "v:": the v wrapper adds nothing as in some cases it results in no opcode being added
1782  // (instead transforming another opcode into its VERIFY form). However, the v: wrapper has
1783  // to be interleaved with other fragments to be valid, so this is not a concern.
1784  size_t script_size{1};
1785  size_t max_size{internal::MaxScriptSize(ctx.MsContext())};
1786 
1787  // The two integers are used to hold state for thresh()
1788  std::vector<std::tuple<ParseContext, int64_t, int64_t>> to_parse;
1789  std::vector<NodeRef<Key>> constructed;
1790 
1791  to_parse.emplace_back(ParseContext::WRAPPED_EXPR, -1, -1);
1792 
1793  // Parses a multi() or multi_a() from its string representation. Returns false on parsing error.
1794  const auto parse_multi_exp = [&](Span<const char>& in, const bool is_multi_a) -> bool {
1795  const auto max_keys{is_multi_a ? MAX_PUBKEYS_PER_MULTI_A : MAX_PUBKEYS_PER_MULTISIG};
1796  const auto required_ctx{is_multi_a ? MiniscriptContext::TAPSCRIPT : MiniscriptContext::P2WSH};
1797  if (ctx.MsContext() != required_ctx) return false;
1798  // Get threshold
1799  int next_comma = FindNextChar(in, ',');
1800  if (next_comma < 1) return false;
1801  const auto k_to_integral{ToIntegral<int64_t>(std::string_view(in.begin(), next_comma))};
1802  if (!k_to_integral.has_value()) return false;
1803  const int64_t k{k_to_integral.value()};
1804  in = in.subspan(next_comma + 1);
1805  // Get keys. It is compatible for both compressed and x-only keys.
1806  std::vector<Key> keys;
1807  while (next_comma != -1) {
1808  next_comma = FindNextChar(in, ',');
1809  int key_length = (next_comma == -1) ? FindNextChar(in, ')') : next_comma;
1810  if (key_length < 1) return false;
1811  auto key = ctx.FromString(in.begin(), in.begin() + key_length);
1812  if (!key) return false;
1813  keys.push_back(std::move(*key));
1814  in = in.subspan(key_length + 1);
1815  }
1816  if (keys.size() < 1 || keys.size() > max_keys) return false;
1817  if (k < 1 || k > (int64_t)keys.size()) return false;
1818  if (is_multi_a) {
1819  // (push + xonly-key + CHECKSIG[ADD]) * n + k + OP_NUMEQUAL(VERIFY), minus one.
1820  script_size += (1 + 32 + 1) * keys.size() + BuildScript(k).size();
1821  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::MULTI_A, std::move(keys), k));
1822  } else {
1823  script_size += 2 + (keys.size() > 16) + (k > 16) + 34 * keys.size();
1824  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::MULTI, std::move(keys), k));
1825  }
1826  return true;
1827  };
1828 
1829  while (!to_parse.empty()) {
1830  if (script_size > max_size) return {};
1831 
1832  // Get the current context we are decoding within
1833  auto [cur_context, n, k] = to_parse.back();
1834  to_parse.pop_back();
1835 
1836  switch (cur_context) {
1837  case ParseContext::WRAPPED_EXPR: {
1838  std::optional<size_t> colon_index{};
1839  for (size_t i = 1; i < in.size(); ++i) {
1840  if (in[i] == ':') {
1841  colon_index = i;
1842  break;
1843  }
1844  if (in[i] < 'a' || in[i] > 'z') break;
1845  }
1846  // If there is no colon, this loop won't execute
1847  bool last_was_v{false};
1848  for (size_t j = 0; colon_index && j < *colon_index; ++j) {
1849  if (script_size > max_size) return {};
1850  if (in[j] == 'a') {
1851  script_size += 2;
1852  to_parse.emplace_back(ParseContext::ALT, -1, -1);
1853  } else if (in[j] == 's') {
1854  script_size += 1;
1855  to_parse.emplace_back(ParseContext::SWAP, -1, -1);
1856  } else if (in[j] == 'c') {
1857  script_size += 1;
1858  to_parse.emplace_back(ParseContext::CHECK, -1, -1);
1859  } else if (in[j] == 'd') {
1860  script_size += 3;
1861  to_parse.emplace_back(ParseContext::DUP_IF, -1, -1);
1862  } else if (in[j] == 'j') {
1863  script_size += 4;
1864  to_parse.emplace_back(ParseContext::NON_ZERO, -1, -1);
1865  } else if (in[j] == 'n') {
1866  script_size += 1;
1867  to_parse.emplace_back(ParseContext::ZERO_NOTEQUAL, -1, -1);
1868  } else if (in[j] == 'v') {
1869  // do not permit "...vv...:"; it's not valid, and also doesn't trigger early
1870  // failure as script_size isn't incremented.
1871  if (last_was_v) return {};
1872  to_parse.emplace_back(ParseContext::VERIFY, -1, -1);
1873  } else if (in[j] == 'u') {
1874  script_size += 4;
1875  to_parse.emplace_back(ParseContext::WRAP_U, -1, -1);
1876  } else if (in[j] == 't') {
1877  script_size += 1;
1878  to_parse.emplace_back(ParseContext::WRAP_T, -1, -1);
1879  } else if (in[j] == 'l') {
1880  // The l: wrapper is equivalent to or_i(0,X)
1881  script_size += 4;
1882  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::JUST_0));
1883  to_parse.emplace_back(ParseContext::OR_I, -1, -1);
1884  } else {
1885  return {};
1886  }
1887  last_was_v = (in[j] == 'v');
1888  }
1889  to_parse.emplace_back(ParseContext::EXPR, -1, -1);
1890  if (colon_index) in = in.subspan(*colon_index + 1);
1891  break;
1892  }
1893  case ParseContext::EXPR: {
1894  if (Const("0", in)) {
1895  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::JUST_0));
1896  } else if (Const("1", in)) {
1897  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::JUST_1));
1898  } else if (Const("pk(", in)) {
1899  auto res = ParseKeyEnd<Key, Ctx>(in, ctx);
1900  if (!res) return {};
1901  auto& [key, key_size] = *res;
1902  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))))));
1903  in = in.subspan(key_size + 1);
1904  script_size += IsTapscript(ctx.MsContext()) ? 33 : 34;
1905  } else if (Const("pkh(", in)) {
1906  auto res = ParseKeyEnd<Key>(in, ctx);
1907  if (!res) return {};
1908  auto& [key, key_size] = *res;
1909  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))))));
1910  in = in.subspan(key_size + 1);
1911  script_size += 24;
1912  } else if (Const("pk_k(", in)) {
1913  auto res = ParseKeyEnd<Key>(in, ctx);
1914  if (!res) return {};
1915  auto& [key, key_size] = *res;
1916  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::PK_K, Vector(std::move(key))));
1917  in = in.subspan(key_size + 1);
1918  script_size += IsTapscript(ctx.MsContext()) ? 32 : 33;
1919  } else if (Const("pk_h(", in)) {
1920  auto res = ParseKeyEnd<Key>(in, ctx);
1921  if (!res) return {};
1922  auto& [key, key_size] = *res;
1923  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::PK_H, Vector(std::move(key))));
1924  in = in.subspan(key_size + 1);
1925  script_size += 23;
1926  } else if (Const("sha256(", in)) {
1927  auto res = ParseHexStrEnd(in, 32, ctx);
1928  if (!res) return {};
1929  auto& [hash, hash_size] = *res;
1930  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::SHA256, std::move(hash)));
1931  in = in.subspan(hash_size + 1);
1932  script_size += 38;
1933  } else if (Const("ripemd160(", in)) {
1934  auto res = ParseHexStrEnd(in, 20, ctx);
1935  if (!res) return {};
1936  auto& [hash, hash_size] = *res;
1937  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::RIPEMD160, std::move(hash)));
1938  in = in.subspan(hash_size + 1);
1939  script_size += 26;
1940  } else if (Const("hash256(", in)) {
1941  auto res = ParseHexStrEnd(in, 32, ctx);
1942  if (!res) return {};
1943  auto& [hash, hash_size] = *res;
1944  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::HASH256, std::move(hash)));
1945  in = in.subspan(hash_size + 1);
1946  script_size += 38;
1947  } else if (Const("hash160(", in)) {
1948  auto res = ParseHexStrEnd(in, 20, ctx);
1949  if (!res) return {};
1950  auto& [hash, hash_size] = *res;
1951  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::HASH160, std::move(hash)));
1952  in = in.subspan(hash_size + 1);
1953  script_size += 26;
1954  } else if (Const("after(", in)) {
1955  int arg_size = FindNextChar(in, ')');
1956  if (arg_size < 1) return {};
1957  const auto num{ToIntegral<int64_t>(std::string_view(in.begin(), arg_size))};
1958  if (!num.has_value() || *num < 1 || *num >= 0x80000000L) return {};
1959  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::AFTER, *num));
1960  in = in.subspan(arg_size + 1);
1961  script_size += 1 + (*num > 16) + (*num > 0x7f) + (*num > 0x7fff) + (*num > 0x7fffff);
1962  } else if (Const("older(", in)) {
1963  int arg_size = FindNextChar(in, ')');
1964  if (arg_size < 1) return {};
1965  const auto num{ToIntegral<int64_t>(std::string_view(in.begin(), arg_size))};
1966  if (!num.has_value() || *num < 1 || *num >= 0x80000000L) return {};
1967  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::OLDER, *num));
1968  in = in.subspan(arg_size + 1);
1969  script_size += 1 + (*num > 16) + (*num > 0x7f) + (*num > 0x7fff) + (*num > 0x7fffff);
1970  } else if (Const("multi(", in)) {
1971  if (!parse_multi_exp(in, /* is_multi_a = */false)) return {};
1972  } else if (Const("multi_a(", in)) {
1973  if (!parse_multi_exp(in, /* is_multi_a = */true)) return {};
1974  } else if (Const("thresh(", in)) {
1975  int next_comma = FindNextChar(in, ',');
1976  if (next_comma < 1) return {};
1977  const auto k{ToIntegral<int64_t>(std::string_view(in.begin(), next_comma))};
1978  if (!k.has_value() || *k < 1) return {};
1979  in = in.subspan(next_comma + 1);
1980  // n = 1 here because we read the first WRAPPED_EXPR before reaching THRESH
1981  to_parse.emplace_back(ParseContext::THRESH, 1, *k);
1982  to_parse.emplace_back(ParseContext::WRAPPED_EXPR, -1, -1);
1983  script_size += 2 + (*k > 16) + (*k > 0x7f) + (*k > 0x7fff) + (*k > 0x7fffff);
1984  } else if (Const("andor(", in)) {
1985  to_parse.emplace_back(ParseContext::ANDOR, -1, -1);
1986  to_parse.emplace_back(ParseContext::CLOSE_BRACKET, -1, -1);
1987  to_parse.emplace_back(ParseContext::WRAPPED_EXPR, -1, -1);
1988  to_parse.emplace_back(ParseContext::COMMA, -1, -1);
1989  to_parse.emplace_back(ParseContext::WRAPPED_EXPR, -1, -1);
1990  to_parse.emplace_back(ParseContext::COMMA, -1, -1);
1991  to_parse.emplace_back(ParseContext::WRAPPED_EXPR, -1, -1);
1992  script_size += 5;
1993  } else {
1994  if (Const("and_n(", in)) {
1995  to_parse.emplace_back(ParseContext::AND_N, -1, -1);
1996  script_size += 5;
1997  } else if (Const("and_b(", in)) {
1998  to_parse.emplace_back(ParseContext::AND_B, -1, -1);
1999  script_size += 2;
2000  } else if (Const("and_v(", in)) {
2001  to_parse.emplace_back(ParseContext::AND_V, -1, -1);
2002  script_size += 1;
2003  } else if (Const("or_b(", in)) {
2004  to_parse.emplace_back(ParseContext::OR_B, -1, -1);
2005  script_size += 2;
2006  } else if (Const("or_c(", in)) {
2007  to_parse.emplace_back(ParseContext::OR_C, -1, -1);
2008  script_size += 3;
2009  } else if (Const("or_d(", in)) {
2010  to_parse.emplace_back(ParseContext::OR_D, -1, -1);
2011  script_size += 4;
2012  } else if (Const("or_i(", in)) {
2013  to_parse.emplace_back(ParseContext::OR_I, -1, -1);
2014  script_size += 4;
2015  } else {
2016  return {};
2017  }
2018  to_parse.emplace_back(ParseContext::CLOSE_BRACKET, -1, -1);
2019  to_parse.emplace_back(ParseContext::WRAPPED_EXPR, -1, -1);
2020  to_parse.emplace_back(ParseContext::COMMA, -1, -1);
2021  to_parse.emplace_back(ParseContext::WRAPPED_EXPR, -1, -1);
2022  }
2023  break;
2024  }
2025  case ParseContext::ALT: {
2026  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_A, Vector(std::move(constructed.back())));
2027  break;
2028  }
2029  case ParseContext::SWAP: {
2030  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_S, Vector(std::move(constructed.back())));
2031  break;
2032  }
2033  case ParseContext::CHECK: {
2034  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_C, Vector(std::move(constructed.back())));
2035  break;
2036  }
2037  case ParseContext::DUP_IF: {
2038  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_D, Vector(std::move(constructed.back())));
2039  break;
2040  }
2041  case ParseContext::NON_ZERO: {
2042  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_J, Vector(std::move(constructed.back())));
2043  break;
2044  }
2045  case ParseContext::ZERO_NOTEQUAL: {
2046  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_N, Vector(std::move(constructed.back())));
2047  break;
2048  }
2049  case ParseContext::VERIFY: {
2050  script_size += (constructed.back()->GetType() << "x"_mst);
2051  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_V, Vector(std::move(constructed.back())));
2052  break;
2053  }
2054  case ParseContext::WRAP_U: {
2055  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)));
2056  break;
2057  }
2058  case ParseContext::WRAP_T: {
2059  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)));
2060  break;
2061  }
2062  case ParseContext::AND_B: {
2063  BuildBack(ctx.MsContext(), Fragment::AND_B, constructed);
2064  break;
2065  }
2066  case ParseContext::AND_N: {
2067  auto mid = std::move(constructed.back());
2068  constructed.pop_back();
2069  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)));
2070  break;
2071  }
2072  case ParseContext::AND_V: {
2073  BuildBack(ctx.MsContext(), Fragment::AND_V, constructed);
2074  break;
2075  }
2076  case ParseContext::OR_B: {
2077  BuildBack(ctx.MsContext(), Fragment::OR_B, constructed);
2078  break;
2079  }
2080  case ParseContext::OR_C: {
2081  BuildBack(ctx.MsContext(), Fragment::OR_C, constructed);
2082  break;
2083  }
2084  case ParseContext::OR_D: {
2085  BuildBack(ctx.MsContext(), Fragment::OR_D, constructed);
2086  break;
2087  }
2088  case ParseContext::OR_I: {
2089  BuildBack(ctx.MsContext(), Fragment::OR_I, constructed);
2090  break;
2091  }
2092  case ParseContext::ANDOR: {
2093  auto right = std::move(constructed.back());
2094  constructed.pop_back();
2095  auto mid = std::move(constructed.back());
2096  constructed.pop_back();
2097  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::ANDOR, Vector(std::move(constructed.back()), std::move(mid), std::move(right)));
2098  break;
2099  }
2100  case ParseContext::THRESH: {
2101  if (in.size() < 1) return {};
2102  if (in[0] == ',') {
2103  in = in.subspan(1);
2104  to_parse.emplace_back(ParseContext::THRESH, n+1, k);
2105  to_parse.emplace_back(ParseContext::WRAPPED_EXPR, -1, -1);
2106  script_size += 2;
2107  } else if (in[0] == ')') {
2108  if (k > n) return {};
2109  in = in.subspan(1);
2110  // Children are constructed in reverse order, so iterate from end to beginning
2111  std::vector<NodeRef<Key>> subs;
2112  for (int i = 0; i < n; ++i) {
2113  subs.push_back(std::move(constructed.back()));
2114  constructed.pop_back();
2115  }
2116  std::reverse(subs.begin(), subs.end());
2117  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::THRESH, std::move(subs), k));
2118  } else {
2119  return {};
2120  }
2121  break;
2122  }
2123  case ParseContext::COMMA: {
2124  if (in.size() < 1 || in[0] != ',') return {};
2125  in = in.subspan(1);
2126  break;
2127  }
2128  case ParseContext::CLOSE_BRACKET: {
2129  if (in.size() < 1 || in[0] != ')') return {};
2130  in = in.subspan(1);
2131  break;
2132  }
2133  }
2134  }
2135 
2136  // Sanity checks on the produced miniscript
2137  assert(constructed.size() == 1);
2138  assert(constructed[0]->ScriptSize() == script_size);
2139  if (in.size() > 0) return {};
2140  NodeRef<Key> tl_node = std::move(constructed.front());
2141  tl_node->DuplicateKeyCheck(ctx);
2142  return tl_node;
2143 }
2144 
2153 std::optional<std::vector<Opcode>> DecomposeScript(const CScript& script);
2154 
2156 std::optional<int64_t> ParseScriptNumber(const Opcode& in);
2157 
2158 enum class DecodeContext {
2164  BKV_EXPR,
2166  W_EXPR,
2167 
2171  SWAP,
2174  ALT,
2176  CHECK,
2178  DUP_IF,
2180  VERIFY,
2182  NON_ZERO,
2184  ZERO_NOTEQUAL,
2185 
2190  MAYBE_AND_V,
2192  AND_V,
2194  AND_B,
2196  ANDOR,
2198  OR_B,
2200  OR_C,
2202  OR_D,
2203 
2207  THRESH_W,
2210  THRESH_E,
2211 
2215  ENDIF,
2219  ENDIF_NOTIF,
2223  ENDIF_ELSE,
2224 };
2225 
2227 template<typename Key, typename Ctx, typename I>
2228 inline NodeRef<Key> DecodeScript(I& in, I last, const Ctx& ctx)
2229 {
2230  // The two integers are used to hold state for thresh()
2231  std::vector<std::tuple<DecodeContext, int64_t, int64_t>> to_parse;
2232  std::vector<NodeRef<Key>> constructed;
2233 
2234  // This is the top level, so we assume the type is B
2235  // (in particular, disallowing top level W expressions)
2236  to_parse.emplace_back(DecodeContext::BKV_EXPR, -1, -1);
2237 
2238  while (!to_parse.empty()) {
2239  // Exit early if the Miniscript is not going to be valid.
2240  if (!constructed.empty() && !constructed.back()->IsValid()) return {};
2241 
2242  // Get the current context we are decoding within
2243  auto [cur_context, n, k] = to_parse.back();
2244  to_parse.pop_back();
2245 
2246  switch(cur_context) {
2247  case DecodeContext::SINGLE_BKV_EXPR: {
2248  if (in >= last) return {};
2249 
2250  // Constants
2251  if (in[0].first == OP_1) {
2252  ++in;
2253  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::JUST_1));
2254  break;
2255  }
2256  if (in[0].first == OP_0) {
2257  ++in;
2258  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::JUST_0));
2259  break;
2260  }
2261  // Public keys
2262  if (in[0].second.size() == 33 || in[0].second.size() == 32) {
2263  auto key = ctx.FromPKBytes(in[0].second.begin(), in[0].second.end());
2264  if (!key) return {};
2265  ++in;
2266  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::PK_K, Vector(std::move(*key))));
2267  break;
2268  }
2269  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) {
2270  auto key = ctx.FromPKHBytes(in[2].second.begin(), in[2].second.end());
2271  if (!key) return {};
2272  in += 5;
2273  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::PK_H, Vector(std::move(*key))));
2274  break;
2275  }
2276  // Time locks
2277  std::optional<int64_t> num;
2278  if (last - in >= 2 && in[0].first == OP_CHECKSEQUENCEVERIFY && (num = ParseScriptNumber(in[1]))) {
2279  in += 2;
2280  if (*num < 1 || *num > 0x7FFFFFFFL) return {};
2281  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::OLDER, *num));
2282  break;
2283  }
2284  if (last - in >= 2 && in[0].first == OP_CHECKLOCKTIMEVERIFY && (num = ParseScriptNumber(in[1]))) {
2285  in += 2;
2286  if (num < 1 || num > 0x7FFFFFFFL) return {};
2287  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::AFTER, *num));
2288  break;
2289  }
2290  // Hashes
2291  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) {
2292  if (in[2].first == OP_SHA256 && in[1].second.size() == 32) {
2293  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::SHA256, in[1].second));
2294  in += 7;
2295  break;
2296  } else if (in[2].first == OP_RIPEMD160 && in[1].second.size() == 20) {
2297  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::RIPEMD160, in[1].second));
2298  in += 7;
2299  break;
2300  } else if (in[2].first == OP_HASH256 && in[1].second.size() == 32) {
2301  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::HASH256, in[1].second));
2302  in += 7;
2303  break;
2304  } else if (in[2].first == OP_HASH160 && in[1].second.size() == 20) {
2305  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::HASH160, in[1].second));
2306  in += 7;
2307  break;
2308  }
2309  }
2310  // Multi
2311  if (last - in >= 3 && in[0].first == OP_CHECKMULTISIG) {
2312  if (IsTapscript(ctx.MsContext())) return {};
2313  std::vector<Key> keys;
2314  const auto n = ParseScriptNumber(in[1]);
2315  if (!n || last - in < 3 + *n) return {};
2316  if (*n < 1 || *n > 20) return {};
2317  for (int i = 0; i < *n; ++i) {
2318  if (in[2 + i].second.size() != 33) return {};
2319  auto key = ctx.FromPKBytes(in[2 + i].second.begin(), in[2 + i].second.end());
2320  if (!key) return {};
2321  keys.push_back(std::move(*key));
2322  }
2323  const auto k = ParseScriptNumber(in[2 + *n]);
2324  if (!k || *k < 1 || *k > *n) return {};
2325  in += 3 + *n;
2326  std::reverse(keys.begin(), keys.end());
2327  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::MULTI, std::move(keys), *k));
2328  break;
2329  }
2330  // Tapscript's equivalent of multi
2331  if (last - in >= 4 && in[0].first == OP_NUMEQUAL) {
2332  if (!IsTapscript(ctx.MsContext())) return {};
2333  // The necessary threshold of signatures.
2334  const auto k = ParseScriptNumber(in[1]);
2335  if (!k) return {};
2336  if (*k < 1 || *k > MAX_PUBKEYS_PER_MULTI_A) return {};
2337  if (last - in < 2 + *k * 2) return {};
2338  std::vector<Key> keys;
2339  keys.reserve(*k);
2340  // Walk through the expected (pubkey, CHECKSIG[ADD]) pairs.
2341  for (int pos = 2;; pos += 2) {
2342  if (last - in < pos + 2) return {};
2343  // Make sure it's indeed an x-only pubkey and a CHECKSIG[ADD], then parse the key.
2344  if (in[pos].first != OP_CHECKSIGADD && in[pos].first != OP_CHECKSIG) return {};
2345  if (in[pos + 1].second.size() != 32) return {};
2346  auto key = ctx.FromPKBytes(in[pos + 1].second.begin(), in[pos + 1].second.end());
2347  if (!key) return {};
2348  keys.push_back(std::move(*key));
2349  // Make sure early we don't parse an arbitrary large expression.
2350  if (keys.size() > MAX_PUBKEYS_PER_MULTI_A) return {};
2351  // OP_CHECKSIG means it was the last one to parse.
2352  if (in[pos].first == OP_CHECKSIG) break;
2353  }
2354  if (keys.size() < (size_t)*k) return {};
2355  in += 2 + keys.size() * 2;
2356  std::reverse(keys.begin(), keys.end());
2357  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::MULTI_A, std::move(keys), *k));
2358  break;
2359  }
2363  // c: wrapper
2364  if (in[0].first == OP_CHECKSIG) {
2365  ++in;
2366  to_parse.emplace_back(DecodeContext::CHECK, -1, -1);
2367  to_parse.emplace_back(DecodeContext::SINGLE_BKV_EXPR, -1, -1);
2368  break;
2369  }
2370  // v: wrapper
2371  if (in[0].first == OP_VERIFY) {
2372  ++in;
2373  to_parse.emplace_back(DecodeContext::VERIFY, -1, -1);
2374  to_parse.emplace_back(DecodeContext::SINGLE_BKV_EXPR, -1, -1);
2375  break;
2376  }
2377  // n: wrapper
2378  if (in[0].first == OP_0NOTEQUAL) {
2379  ++in;
2380  to_parse.emplace_back(DecodeContext::ZERO_NOTEQUAL, -1, -1);
2381  to_parse.emplace_back(DecodeContext::SINGLE_BKV_EXPR, -1, -1);
2382  break;
2383  }
2384  // Thresh
2385  if (last - in >= 3 && in[0].first == OP_EQUAL && (num = ParseScriptNumber(in[1]))) {
2386  if (*num < 1) return {};
2387  in += 2;
2388  to_parse.emplace_back(DecodeContext::THRESH_W, 0, *num);
2389  break;
2390  }
2391  // OP_ENDIF can be WRAP_J, WRAP_D, ANDOR, OR_C, OR_D, or OR_I
2392  if (in[0].first == OP_ENDIF) {
2393  ++in;
2394  to_parse.emplace_back(DecodeContext::ENDIF, -1, -1);
2395  to_parse.emplace_back(DecodeContext::BKV_EXPR, -1, -1);
2396  break;
2397  }
2403  // and_b
2404  if (in[0].first == OP_BOOLAND) {
2405  ++in;
2406  to_parse.emplace_back(DecodeContext::AND_B, -1, -1);
2407  to_parse.emplace_back(DecodeContext::SINGLE_BKV_EXPR, -1, -1);
2408  to_parse.emplace_back(DecodeContext::W_EXPR, -1, -1);
2409  break;
2410  }
2411  // or_b
2412  if (in[0].first == OP_BOOLOR) {
2413  ++in;
2414  to_parse.emplace_back(DecodeContext::OR_B, -1, -1);
2415  to_parse.emplace_back(DecodeContext::SINGLE_BKV_EXPR, -1, -1);
2416  to_parse.emplace_back(DecodeContext::W_EXPR, -1, -1);
2417  break;
2418  }
2419  // Unrecognised expression
2420  return {};
2421  }
2422  case DecodeContext::BKV_EXPR: {
2423  to_parse.emplace_back(DecodeContext::MAYBE_AND_V, -1, -1);
2424  to_parse.emplace_back(DecodeContext::SINGLE_BKV_EXPR, -1, -1);
2425  break;
2426  }
2427  case DecodeContext::W_EXPR: {
2428  // a: wrapper
2429  if (in >= last) return {};
2430  if (in[0].first == OP_FROMALTSTACK) {
2431  ++in;
2432  to_parse.emplace_back(DecodeContext::ALT, -1, -1);
2433  } else {
2434  to_parse.emplace_back(DecodeContext::SWAP, -1, -1);
2435  }
2436  to_parse.emplace_back(DecodeContext::BKV_EXPR, -1, -1);
2437  break;
2438  }
2439  case DecodeContext::MAYBE_AND_V: {
2440  // If we reach a potential AND_V top-level, check if the next part of the script could be another AND_V child
2441  // These op-codes cannot end any well-formed miniscript so cannot be used in an and_v node.
2442  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) {
2443  to_parse.emplace_back(DecodeContext::AND_V, -1, -1);
2444  // BKV_EXPR can contain more AND_V nodes
2445  to_parse.emplace_back(DecodeContext::BKV_EXPR, -1, -1);
2446  }
2447  break;
2448  }
2449  case DecodeContext::SWAP: {
2450  if (in >= last || in[0].first != OP_SWAP || constructed.empty()) return {};
2451  ++in;
2452  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_S, Vector(std::move(constructed.back())));
2453  break;
2454  }
2455  case DecodeContext::ALT: {
2456  if (in >= last || in[0].first != OP_TOALTSTACK || constructed.empty()) return {};
2457  ++in;
2458  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_A, Vector(std::move(constructed.back())));
2459  break;
2460  }
2461  case DecodeContext::CHECK: {
2462  if (constructed.empty()) return {};
2463  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_C, Vector(std::move(constructed.back())));
2464  break;
2465  }
2466  case DecodeContext::DUP_IF: {
2467  if (constructed.empty()) return {};
2468  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_D, Vector(std::move(constructed.back())));
2469  break;
2470  }
2471  case DecodeContext::VERIFY: {
2472  if (constructed.empty()) return {};
2473  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_V, Vector(std::move(constructed.back())));
2474  break;
2475  }
2476  case DecodeContext::NON_ZERO: {
2477  if (constructed.empty()) return {};
2478  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_J, Vector(std::move(constructed.back())));
2479  break;
2480  }
2481  case DecodeContext::ZERO_NOTEQUAL: {
2482  if (constructed.empty()) return {};
2483  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_N, Vector(std::move(constructed.back())));
2484  break;
2485  }
2486  case DecodeContext::AND_V: {
2487  if (constructed.size() < 2) return {};
2488  BuildBack(ctx.MsContext(), Fragment::AND_V, constructed, /*reverse=*/true);
2489  break;
2490  }
2491  case DecodeContext::AND_B: {
2492  if (constructed.size() < 2) return {};
2493  BuildBack(ctx.MsContext(), Fragment::AND_B, constructed, /*reverse=*/true);
2494  break;
2495  }
2496  case DecodeContext::OR_B: {
2497  if (constructed.size() < 2) return {};
2498  BuildBack(ctx.MsContext(), Fragment::OR_B, constructed, /*reverse=*/true);
2499  break;
2500  }
2501  case DecodeContext::OR_C: {
2502  if (constructed.size() < 2) return {};
2503  BuildBack(ctx.MsContext(), Fragment::OR_C, constructed, /*reverse=*/true);
2504  break;
2505  }
2506  case DecodeContext::OR_D: {
2507  if (constructed.size() < 2) return {};
2508  BuildBack(ctx.MsContext(), Fragment::OR_D, constructed, /*reverse=*/true);
2509  break;
2510  }
2511  case DecodeContext::ANDOR: {
2512  if (constructed.size() < 3) return {};
2513  NodeRef<Key> left = std::move(constructed.back());
2514  constructed.pop_back();
2515  NodeRef<Key> right = std::move(constructed.back());
2516  constructed.pop_back();
2517  NodeRef<Key> mid = std::move(constructed.back());
2518  constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::ANDOR, Vector(std::move(left), std::move(mid), std::move(right)));
2519  break;
2520  }
2521  case DecodeContext::THRESH_W: {
2522  if (in >= last) return {};
2523  if (in[0].first == OP_ADD) {
2524  ++in;
2525  to_parse.emplace_back(DecodeContext::THRESH_W, n+1, k);
2526  to_parse.emplace_back(DecodeContext::W_EXPR, -1, -1);
2527  } else {
2528  to_parse.emplace_back(DecodeContext::THRESH_E, n+1, k);
2529  // All children of thresh have type modifier d, so cannot be and_v
2530  to_parse.emplace_back(DecodeContext::SINGLE_BKV_EXPR, -1, -1);
2531  }
2532  break;
2533  }
2534  case DecodeContext::THRESH_E: {
2535  if (k < 1 || k > n || constructed.size() < static_cast<size_t>(n)) return {};
2536  std::vector<NodeRef<Key>> subs;
2537  for (int i = 0; i < n; ++i) {
2538  NodeRef<Key> sub = std::move(constructed.back());
2539  constructed.pop_back();
2540  subs.push_back(std::move(sub));
2541  }
2542  constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::THRESH, std::move(subs), k));
2543  break;
2544  }
2545  case DecodeContext::ENDIF: {
2546  if (in >= last) return {};
2547 
2548  // could be andor or or_i
2549  if (in[0].first == OP_ELSE) {
2550  ++in;
2551  to_parse.emplace_back(DecodeContext::ENDIF_ELSE, -1, -1);
2552  to_parse.emplace_back(DecodeContext::BKV_EXPR, -1, -1);
2553  }
2554  // could be j: or d: wrapper
2555  else if (in[0].first == OP_IF) {
2556  if (last - in >= 2 && in[1].first == OP_DUP) {
2557  in += 2;
2558  to_parse.emplace_back(DecodeContext::DUP_IF, -1, -1);
2559  } else if (last - in >= 3 && in[1].first == OP_0NOTEQUAL && in[2].first == OP_SIZE) {
2560  in += 3;
2561  to_parse.emplace_back(DecodeContext::NON_ZERO, -1, -1);
2562  }
2563  else {
2564  return {};
2565  }
2566  // could be or_c or or_d
2567  } else if (in[0].first == OP_NOTIF) {
2568  ++in;
2569  to_parse.emplace_back(DecodeContext::ENDIF_NOTIF, -1, -1);
2570  }
2571  else {
2572  return {};
2573  }
2574  break;
2575  }
2576  case DecodeContext::ENDIF_NOTIF: {
2577  if (in >= last) return {};
2578  if (in[0].first == OP_IFDUP) {
2579  ++in;
2580  to_parse.emplace_back(DecodeContext::OR_D, -1, -1);
2581  } else {
2582  to_parse.emplace_back(DecodeContext::OR_C, -1, -1);
2583  }
2584  // or_c and or_d both require X to have type modifier d so, can't contain and_v
2585  to_parse.emplace_back(DecodeContext::SINGLE_BKV_EXPR, -1, -1);
2586  break;
2587  }
2588  case DecodeContext::ENDIF_ELSE: {
2589  if (in >= last) return {};
2590  if (in[0].first == OP_IF) {
2591  ++in;
2592  BuildBack(ctx.MsContext(), Fragment::OR_I, constructed, /*reverse=*/true);
2593  } else if (in[0].first == OP_NOTIF) {
2594  ++in;
2595  to_parse.emplace_back(DecodeContext::ANDOR, -1, -1);
2596  // andor requires X to have type modifier d, so it can't be and_v
2597  to_parse.emplace_back(DecodeContext::SINGLE_BKV_EXPR, -1, -1);
2598  } else {
2599  return {};
2600  }
2601  break;
2602  }
2603  }
2604  }
2605  if (constructed.size() != 1) return {};
2606  NodeRef<Key> tl_node = std::move(constructed.front());
2607  tl_node->DuplicateKeyCheck(ctx);
2608  // Note that due to how ComputeType works (only assign the type to the node if the
2609  // subs' types are valid) this would fail if any node of tree is badly typed.
2610  if (!tl_node->IsValidTopLevel()) return {};
2611  return tl_node;
2612 }
2613 
2614 } // namespace internal
2615 
2616 template<typename Ctx>
2617 inline NodeRef<typename Ctx::Key> FromString(const std::string& str, const Ctx& ctx) {
2618  return internal::Parse<typename Ctx::Key>(str, ctx);
2619 }
2620 
2621 template<typename Ctx>
2622 inline NodeRef<typename Ctx::Key> FromScript(const CScript& script, const Ctx& ctx) {
2623  using namespace internal;
2624  // A too large Script is necessarily invalid, don't bother parsing it.
2625  if (script.size() > MaxScriptSize(ctx.MsContext())) return {};
2626  auto decomposed = DecomposeScript(script);
2627  if (!decomposed) return {};
2628  auto it = decomposed->begin();
2629  auto ret = DecodeScript<typename Ctx::Key>(it, decomposed->end(), ctx);
2630  if (!ret) return {};
2631  if (it != decomposed->end()) return {};
2632  return ret;
2633 }
2634 
2635 } // namespace miniscript
2636 
2637 #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:605
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:1642
NodeRef< typename Ctx::Key > FromString(const std::string &str, const Ctx &ctx)
Definition: miniscript.h:2617
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:1528
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:1629
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:1656
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:1728
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:66
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:1544
std::optional< Result > TreeEvalMaybe(UpFn upfn) const
Like TreeEvalMaybe, but without downfn or State type.
Definition: miniscript.h:650
[k] [key_n]* [n] OP_CHECKMULTISIG (only available within P2WSH context)
Definition: script.h:124
std::optional< Result > TreeEvalMaybe(State root_state, DownFn downfn, UpFn upfn) const
Definition: miniscript.h:585
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:160
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:1613
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:73
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:1595
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:1739
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:537
Type CalcType() const
Compute the type for this miniscript.
Definition: miniscript.h:712
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:1658
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:551
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:1532
[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:547
WRAP_T will construct an and_v(X,1) node from the top constructed node.
Definition: script.h:75
MaxInt< uint32_t > dsat
Maximum witness size to dissatisfy;.
Definition: miniscript.h:493
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:1622
Node(const Ctx &ctx, Fragment nt, uint32_t val=0)
Definition: miniscript.h:1664
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:2228
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:1489
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:539
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:541
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:33
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
std::shared_ptr< const Node< Key > > NodeRef
Definition: miniscript.h:192
[X1] ([Xn] OP_ADD)* [k] OP_EQUAL
Node(internal::NoDupCheck, MiniscriptContext script_ctx, Fragment nt, uint32_t val=0)
Definition: miniscript.h:1650
internal::InputResult ProduceInput(const Ctx &ctx) const
Definition: miniscript.h:1168
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:82
[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:103
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:925
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:1604
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:270
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:1654
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:1619
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:1646
#define B
Definition: util_tests.cpp:498
friend int Compare(const Node< Key > &node1, const Node< Key > &node2)
Compare two miniscript subtrees, using a non-recursive algorithm.
Definition: miniscript.h:692
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:1492
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:47
bool NeedsSignature() const
Check whether this script always needs a signature.
Definition: miniscript.h:1607
MiniscriptContext GetMsCtx() const
Return the script context for this node.
Definition: miniscript.h:1541
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:36
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:1114
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:1480
[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(const Ctx &ctx, Fragment nt, std::vector< Key > key, uint32_t val=0)
Definition: miniscript.h:1660
NodeRef< Key > Parse(Span< const char > in, const Ctx &ctx)
Parse a miniscript from its textual descriptor form.
Definition: miniscript.h:1770
std::optional< std::string > ToString(const CTx &ctx) const
Definition: miniscript.h:810
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:533
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:1637
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:27
bool IsSatisfiable(F fn) const
Determine whether a Miniscript node is satisfiable.
Definition: miniscript.h:1555
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
Result TreeEval(State root_state, DownFn &&downfn, UpFn upfn) const
Like TreeEvalMaybe, but always produces a result.
Definition: miniscript.h:663
std::optional< uint32_t > GetOps() const
Return the maximum number of ops needed to satisfy this script non-malleably.
Definition: miniscript.h:1483
bool CheckStackSize() const
Check the maximum stack size for this script against the policy limit.
Definition: miniscript.h:1516
Node(const Ctx &ctx, Fragment nt, std::vector< NodeRef< Key >> sub, uint32_t val=0)
Definition: miniscript.h:1662
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
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:413
static const int MAX_OPS_PER_SCRIPT
Definition: script.h:30
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:1499
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:41
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 shared_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:1504
DUP_IF wraps the top constructed node with d:
static int count
const internal::StackSize ss
Cached stack size bounds.
Definition: miniscript.h:535
bool IsValidTopLevel() const
Check whether this node is valid as a script on its own.
Definition: miniscript.h:1601
size_type size() const
Definition: prevector.h:296
std::optional< uint32_t > GetExecStackSize() const
Return the maximum size of the stack during execution of this script.
Definition: miniscript.h:1510
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:1421
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:1616
A Span is an object that can refer to a contiguous sequence of objects.
Definition: solver.h:20
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:1538
NodeRef< typename Ctx::Key > FromScript(const CScript &script, const Ctx &ctx)
Definition: miniscript.h:2622
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:1648
Result TreeEval(UpFn upfn) const
Like TreeEval, but without downfn or State type.
Definition: miniscript.h:679
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:42
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:1640
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:1644
constexpr unsigned int GetSizeOfCompactSize(uint64_t nSize)
Compact Size size < 253 – 1 byte size <= USHRT_MAX – 3 bytes (253 + 2 bytes) size <= UINT_MAX – 5 ...
Definition: serialize.h:295
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:1753
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:156
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:533
CScript ToScript(const Ctx &ctx) const
Definition: miniscript.h:731
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:999
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:1610
static constexpr SatInfo OP_EQUAL() noexcept
Definition: miniscript.h:475