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