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