Branch data Line data Source code
1 : : // Copyright (c) 2019-present The Bitcoin Core developers
2 : : // Distributed under the MIT software license, see the accompanying
3 : : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 : :
5 : : #ifndef BITCOIN_SCRIPT_MINISCRIPT_H
6 : : #define BITCOIN_SCRIPT_MINISCRIPT_H
7 : :
8 : : #include <algorithm>
9 : : #include <compare>
10 : : #include <concepts>
11 : : #include <cstdint>
12 : : #include <cstdlib>
13 : : #include <functional>
14 : : #include <iterator>
15 : : #include <memory>
16 : : #include <optional>
17 : : #include <set>
18 : : #include <stdexcept>
19 : : #include <tuple>
20 : : #include <utility>
21 : : #include <vector>
22 : :
23 : : #include <consensus/consensus.h>
24 : : #include <policy/policy.h>
25 : : #include <script/interpreter.h>
26 : : #include <script/parsing.h>
27 : : #include <script/script.h>
28 : : #include <serialize.h>
29 : : #include <span.h>
30 : : #include <util/check.h>
31 : : #include <util/strencodings.h>
32 : : #include <util/string.h>
33 : : #include <util/vector.h>
34 : :
35 : : namespace miniscript {
36 : :
37 : : /** This type encapsulates the miniscript type system properties.
38 : : *
39 : : * Every miniscript expression is one of 4 basic types, and additionally has
40 : : * a number of boolean type properties.
41 : : *
42 : : * The basic types are:
43 : : * - "B" Base:
44 : : * - Takes its inputs from the top of the stack.
45 : : * - When satisfied, pushes a nonzero value of up to 4 bytes onto the stack.
46 : : * - When dissatisfied, pushes a 0 onto the stack.
47 : : * - This is used for most expressions, and required for the top level one.
48 : : * - For example: older(n) = <n> OP_CHECKSEQUENCEVERIFY.
49 : : * - "V" Verify:
50 : : * - Takes its inputs from the top of the stack.
51 : : * - When satisfied, pushes nothing.
52 : : * - Cannot be dissatisfied.
53 : : * - This can be obtained by adding an OP_VERIFY to a B, modifying the last opcode
54 : : * of a B to its -VERIFY version (only for OP_CHECKSIG, OP_CHECKSIGVERIFY,
55 : : * OP_NUMEQUAL and OP_EQUAL), or by combining a V fragment under some conditions.
56 : : * - For example vc:pk_k(key) = <key> OP_CHECKSIGVERIFY
57 : : * - "K" Key:
58 : : * - Takes its inputs from the top of the stack.
59 : : * - Becomes a B when followed by OP_CHECKSIG.
60 : : * - Always pushes a public key onto the stack, for which a signature is to be
61 : : * provided to satisfy the expression.
62 : : * - For example pk_h(key) = OP_DUP OP_HASH160 <Hash160(key)> OP_EQUALVERIFY
63 : : * - "W" Wrapped:
64 : : * - Takes its input from one below the top of the stack.
65 : : * - When satisfied, pushes a nonzero value (like B) on top of the stack, or one below.
66 : : * - When dissatisfied, pushes 0 op top of the stack or one below.
67 : : * - Is always "OP_SWAP [B]" or "OP_TOALTSTACK [B] OP_FROMALTSTACK".
68 : : * - For example sc:pk_k(key) = OP_SWAP <key> OP_CHECKSIG
69 : : *
70 : : * There are type properties that help reasoning about correctness:
71 : : * - "z" Zero-arg:
72 : : * - Is known to always consume exactly 0 stack elements.
73 : : * - For example after(n) = <n> OP_CHECKLOCKTIMEVERIFY
74 : : * - "o" One-arg:
75 : : * - Is known to always consume exactly 1 stack element.
76 : : * - Conflicts with property 'z'
77 : : * - For example sha256(hash) = OP_SIZE 32 OP_EQUALVERIFY OP_SHA256 <hash> OP_EQUAL
78 : : * - "n" Nonzero:
79 : : * - For every way this expression can be satisfied, a satisfaction exists that never needs
80 : : * a zero top stack element.
81 : : * - Conflicts with property 'z' and with type 'W'.
82 : : * - "d" Dissatisfiable:
83 : : * - There is an easy way to construct a dissatisfaction for this expression.
84 : : * - Conflicts with type 'V'.
85 : : * - "u" Unit:
86 : : * - In case of satisfaction, an exact 1 is put on the stack (rather than just nonzero).
87 : : * - Conflicts with type 'V'.
88 : : *
89 : : * Additional type properties help reasoning about nonmalleability:
90 : : * - "e" Expression:
91 : : * - This implies property 'd', but the dissatisfaction is nonmalleable.
92 : : * - This generally requires 'e' for all subexpressions which are invoked for that
93 : : * dissatisfaction, and property 'f' for the unexecuted subexpressions in that case.
94 : : * - Conflicts with type 'V'.
95 : : * - "f" Forced:
96 : : * - Dissatisfactions (if any) for this expression always involve at least one signature.
97 : : * - Is always true for type 'V'.
98 : : * - "s" Safe:
99 : : * - Satisfactions for this expression always involve at least one signature.
100 : : * - "m" Nonmalleable:
101 : : * - For every way this expression can be satisfied (which may be none),
102 : : * a nonmalleable satisfaction exists.
103 : : * - This generally requires 'm' for all subexpressions, and 'e' for all subexpressions
104 : : * which are dissatisfied when satisfying the parent.
105 : : *
106 : : * One type property is an implementation detail:
107 : : * - "x" Expensive verify:
108 : : * - Expressions with this property have a script whose last opcode is not EQUAL, CHECKSIG, or CHECKMULTISIG.
109 : : * - Not having this property means that it can be converted to a V at no cost (by switching to the
110 : : * -VERIFY version of the last opcode).
111 : : *
112 : : * Five more type properties for representing timelock information. Spend paths
113 : : * in miniscripts containing conflicting timelocks and heightlocks cannot be spent together.
114 : : * This helps users detect if miniscript does not match the semantic behaviour the
115 : : * user expects.
116 : : * - "g" Whether the branch contains a relative time timelock
117 : : * - "h" Whether the branch contains a relative height timelock
118 : : * - "i" Whether the branch contains an absolute time timelock
119 : : * - "j" Whether the branch contains an absolute height timelock
120 : : * - "k"
121 : : * - Whether all satisfactions of this expression don't contain a mix of heightlock and timelock
122 : : * of the same type.
123 : : * - If the miniscript does not have the "k" property, the miniscript template will not match
124 : : * the user expectation of the corresponding spending policy.
125 : : * For each of these properties the subset rule holds: an expression with properties X, Y, and Z, is also
126 : : * valid in places where an X, a Y, a Z, an XY, ... is expected.
127 : : */
128 : : class Type {
129 : : //! Internal bitmap of properties (see ""_mst operator for details).
130 : : uint32_t m_flags;
131 : :
132 : : //! Internal constructor used by the ""_mst operator.
133 : 38925689 : explicit constexpr Type(uint32_t flags) : m_flags(flags) {}
134 : :
135 : : public:
136 : : //! The only way to publicly construct a Type is using this literal operator.
137 : : friend consteval Type operator""_mst(const char* c, size_t l);
138 : :
139 : : //! Compute the type with the union of properties.
140 [ + + + + : 9564624 : constexpr Type operator|(Type x) const { return Type(m_flags | x.m_flags); }
+ + + + +
+ + + +
+ ][ + - ]
141 : :
142 : : //! Compute the type with the intersection of properties.
143 [ + + + + : 18022847 : constexpr Type operator&(Type x) const { return Type(m_flags & x.m_flags); }
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + ]
144 : :
145 : : //! Check whether the left hand's properties are superset of the right's (= left is a subtype of right).
146 [ + + + + : 227386123 : constexpr bool operator<<(Type x) const { return (x.m_flags & ~m_flags) == 0; }
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ - + + +
- + + + -
+ + + - +
+ + - + +
+ - + + +
- + + + -
+ + + - +
+ + - + +
+ - + + +
- + + +
- ][ + + +
+ + + + +
+ + + + +
+ ]
147 : :
148 : : //! Comparison operator to enable use in sets/maps (total ordering incompatible with <<).
149 [ - - - - : 1458531 : constexpr bool operator<(Type x) const { return m_flags < x.m_flags; }
+ + + + +
+ + + + -
- - + + +
- - - + -
- - - - -
- - - - +
- - - - +
+ + + + +
+ + + + +
+ + - + -
+ - - - -
- - + + +
+ + - + +
- ]
150 : :
151 : : //! Equality operator.
152 [ + - + + : 5254860 : constexpr bool operator==(Type x) const { return m_flags == x.m_flags; }
+ + + + +
+ + + ]
153 : :
154 : : //! The empty type if x is false, itself otherwise.
155 [ + + + + : 18216259 : constexpr Type If(bool x) const { return Type(x ? m_flags : 0); }
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + +
+ ]
156 : : };
157 : :
158 : : //! Literal operator to construct Type objects.
159 : : inline consteval Type operator""_mst(const char* c, size_t l)
160 : : {
161 : : Type typ{0};
162 : :
163 : : for (const char *p = c; p < c + l; p++) {
164 : : typ = typ | Type(
165 : : *p == 'B' ? 1 << 0 : // Base type
166 : : *p == 'V' ? 1 << 1 : // Verify type
167 : : *p == 'K' ? 1 << 2 : // Key type
168 : : *p == 'W' ? 1 << 3 : // Wrapped type
169 : : *p == 'z' ? 1 << 4 : // Zero-arg property
170 : : *p == 'o' ? 1 << 5 : // One-arg property
171 : : *p == 'n' ? 1 << 6 : // Nonzero arg property
172 : : *p == 'd' ? 1 << 7 : // Dissatisfiable property
173 : : *p == 'u' ? 1 << 8 : // Unit property
174 : : *p == 'e' ? 1 << 9 : // Expression property
175 : : *p == 'f' ? 1 << 10 : // Forced property
176 : : *p == 's' ? 1 << 11 : // Safe property
177 : : *p == 'm' ? 1 << 12 : // Nonmalleable property
178 : : *p == 'x' ? 1 << 13 : // Expensive verify
179 : : *p == 'g' ? 1 << 14 : // older: contains relative time timelock (csv_time)
180 : : *p == 'h' ? 1 << 15 : // older: contains relative height timelock (csv_height)
181 : : *p == 'i' ? 1 << 16 : // after: contains time timelock (cltv_time)
182 : : *p == 'j' ? 1 << 17 : // after: contains height timelock (cltv_height)
183 : : *p == 'k' ? 1 << 18 : // does not contain a combination of height and time locks
184 : : (throw std::logic_error("Unknown character in _mst literal"), 0)
185 : : );
186 : : }
187 : :
188 : : return typ;
189 : : }
190 : :
191 : : using Opcode = std::pair<opcodetype, std::vector<unsigned char>>;
192 : :
193 : : template<typename Key> struct Node;
194 : : template<typename Key> using NodeRef = std::unique_ptr<const Node<Key>>;
195 : :
196 : : //! Construct a miniscript node as a unique_ptr.
197 : : template<typename Key, typename... Args>
198 : 15834582 : NodeRef<Key> MakeNodeRef(Args&&... args) { return std::make_unique<const Node<Key>>(std::forward<Args>(args)...); }
199 : :
200 : : //! Unordered traversal of a miniscript node tree.
201 : : template <typename Key, std::invocable<const Node<Key>&> Fn>
202 : 31335 : void ForEachNode(const Node<Key>& root, Fn&& fn)
203 : : {
204 : 31335 : std::vector<std::reference_wrapper<const Node<Key>>> stack{root};
205 [ + + ]: 1503073 : while (!stack.empty()) {
206 [ + - ]: 1471738 : const Node<Key>& node = stack.back();
207 : 1471738 : std::invoke(fn, node);
208 : 1471738 : stack.pop_back();
209 [ + - + + ]: 2912141 : for (const auto& sub : node.subs) {
210 [ + - ]: 1440403 : stack.emplace_back(*sub);
211 : : }
212 : : }
213 : 31335 : }
214 : :
215 : : //! The different node types in miniscript.
216 : : enum class Fragment {
217 : : JUST_0, //!< OP_0
218 : : JUST_1, //!< OP_1
219 : : PK_K, //!< [key]
220 : : PK_H, //!< OP_DUP OP_HASH160 [keyhash] OP_EQUALVERIFY
221 : : OLDER, //!< [n] OP_CHECKSEQUENCEVERIFY
222 : : AFTER, //!< [n] OP_CHECKLOCKTIMEVERIFY
223 : : SHA256, //!< OP_SIZE 32 OP_EQUALVERIFY OP_SHA256 [hash] OP_EQUAL
224 : : HASH256, //!< OP_SIZE 32 OP_EQUALVERIFY OP_HASH256 [hash] OP_EQUAL
225 : : RIPEMD160, //!< OP_SIZE 32 OP_EQUALVERIFY OP_RIPEMD160 [hash] OP_EQUAL
226 : : HASH160, //!< OP_SIZE 32 OP_EQUALVERIFY OP_HASH160 [hash] OP_EQUAL
227 : : WRAP_A, //!< OP_TOALTSTACK [X] OP_FROMALTSTACK
228 : : WRAP_S, //!< OP_SWAP [X]
229 : : WRAP_C, //!< [X] OP_CHECKSIG
230 : : WRAP_D, //!< OP_DUP OP_IF [X] OP_ENDIF
231 : : WRAP_V, //!< [X] OP_VERIFY (or -VERIFY version of last opcode in X)
232 : : WRAP_J, //!< OP_SIZE OP_0NOTEQUAL OP_IF [X] OP_ENDIF
233 : : WRAP_N, //!< [X] OP_0NOTEQUAL
234 : : AND_V, //!< [X] [Y]
235 : : AND_B, //!< [X] [Y] OP_BOOLAND
236 : : OR_B, //!< [X] [Y] OP_BOOLOR
237 : : OR_C, //!< [X] OP_NOTIF [Y] OP_ENDIF
238 : : OR_D, //!< [X] OP_IFDUP OP_NOTIF [Y] OP_ENDIF
239 : : OR_I, //!< OP_IF [X] OP_ELSE [Y] OP_ENDIF
240 : : ANDOR, //!< [X] OP_NOTIF [Z] OP_ELSE [Y] OP_ENDIF
241 : : THRESH, //!< [X1] ([Xn] OP_ADD)* [k] OP_EQUAL
242 : : MULTI, //!< [k] [key_n]* [n] OP_CHECKMULTISIG (only available within P2WSH context)
243 : : MULTI_A, //!< [key_0] OP_CHECKSIG ([key_n] OP_CHECKSIGADD)* [k] OP_NUMEQUAL (only within Tapscript ctx)
244 : : // AND_N(X,Y) is represented as ANDOR(X,Y,0)
245 : : // WRAP_T(X) is represented as AND_V(X,1)
246 : : // WRAP_L(X) is represented as OR_I(0,X)
247 : : // WRAP_U(X) is represented as OR_I(X,0)
248 : : };
249 : :
250 : : enum class Availability {
251 : : NO,
252 : : YES,
253 : : MAYBE,
254 : : };
255 : :
256 : : enum class MiniscriptContext {
257 : : P2WSH,
258 : : TAPSCRIPT,
259 : : };
260 : :
261 : : /** Whether the context Tapscript, ensuring the only other possibility is P2WSH. */
262 : 43693699 : constexpr bool IsTapscript(MiniscriptContext ms_ctx)
263 : : {
264 [ + - + ]: 43693699 : switch (ms_ctx) {
265 : : case MiniscriptContext::P2WSH: return false;
266 : 35363068 : case MiniscriptContext::TAPSCRIPT: return true;
267 : : }
268 : 0 : assert(false);
269 : : }
270 : :
271 : : namespace internal {
272 : :
273 : : //! The maximum size of a witness item for a Miniscript under Tapscript context. (A BIP340 signature with a sighash type byte.)
274 : : static constexpr uint32_t MAX_TAPMINISCRIPT_STACK_ELEM_SIZE{65};
275 : :
276 : : //! version + nLockTime
277 : : constexpr uint32_t TX_OVERHEAD{4 + 4};
278 : : //! prevout + nSequence + scriptSig
279 : : constexpr uint32_t TXIN_BYTES_NO_WITNESS{36 + 4 + 1};
280 : : //! nValue + script len + OP_0 + pushdata 32.
281 : : constexpr uint32_t P2WSH_TXOUT_BYTES{8 + 1 + 1 + 33};
282 : : //! Data other than the witness in a transaction. Overhead + vin count + one vin + vout count + one vout + segwit marker
283 : : constexpr uint32_t TX_BODY_LEEWAY_WEIGHT{(TX_OVERHEAD + GetSizeOfCompactSize(1) + TXIN_BYTES_NO_WITNESS + GetSizeOfCompactSize(1) + P2WSH_TXOUT_BYTES) * WITNESS_SCALE_FACTOR + 2};
284 : : //! Maximum possible stack size to spend a Taproot output (excluding the script itself).
285 : : constexpr uint32_t MAX_TAPSCRIPT_SAT_SIZE{GetSizeOfCompactSize(MAX_STACK_SIZE) + (GetSizeOfCompactSize(MAX_TAPMINISCRIPT_STACK_ELEM_SIZE) + MAX_TAPMINISCRIPT_STACK_ELEM_SIZE) * MAX_STACK_SIZE + GetSizeOfCompactSize(TAPROOT_CONTROL_MAX_SIZE) + TAPROOT_CONTROL_MAX_SIZE};
286 : : /** The maximum size of a script depending on the context. */
287 : 22469324 : constexpr uint32_t MaxScriptSize(MiniscriptContext ms_ctx)
288 : : {
289 [ + + + + : 22469324 : if (IsTapscript(ms_ctx)) {
+ + ][ - -
- + + - -
+ ][ + + +
+ + + + +
+ + + + +
+ ]
290 : : // Leaf scripts under Tapscript are not explicitly limited in size. They are only implicitly
291 : : // bounded by the maximum standard size of a spending transaction. Let the maximum script
292 : : // size conservatively be small enough such that even a maximum sized witness and a reasonably
293 : : // sized spending transaction can spend an output paying to this script without running into
294 : : // the maximum standard tx size limit.
295 : : constexpr auto max_size{MAX_STANDARD_TX_WEIGHT - TX_BODY_LEEWAY_WEIGHT - MAX_TAPSCRIPT_SAT_SIZE};
296 : : return max_size - GetSizeOfCompactSize(max_size);
297 : : }
298 : 3808331 : return MAX_STANDARD_P2WSH_SCRIPT_SIZE;
299 : : }
300 : :
301 : : //! Helper function for Node::CalcType.
302 : : 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);
303 : :
304 : : //! Helper function for Node::CalcScriptLen.
305 : : size_t ComputeScriptLen(Fragment fragment, Type sub0typ, size_t subsize, uint32_t k, size_t n_subs, size_t n_keys, MiniscriptContext ms_ctx);
306 : :
307 : : //! A helper sanitizer/checker for the output of CalcType.
308 : : Type SanitizeType(Type x);
309 : :
310 : : //! An object representing a sequence of witness stack elements.
311 : 7886736 : struct InputStack {
312 : : /** Whether this stack is valid for its intended purpose (satisfaction or dissatisfaction of a Node).
313 : : * The MAYBE value is used for size estimation, when keys/preimages may actually be unavailable,
314 : : * but may be available at signing time. This makes the InputStack structure and signing logic,
315 : : * filled with dummy signatures/preimages usable for witness size estimation.
316 : : */
317 : : Availability available = Availability::YES;
318 : : //! Whether this stack contains a digital signature.
319 : : bool has_sig = false;
320 : : //! Whether this stack is malleable (can be turned into an equally valid other stack by a third party).
321 : : bool malleable = false;
322 : : //! Whether this stack is non-canonical (using a construction known to be unnecessary for satisfaction).
323 : : //! Note that this flag does not affect the satisfaction algorithm; it is only used for sanity checking.
324 : : bool non_canon = false;
325 : : //! Serialized witness size.
326 : : size_t size = 0;
327 : : //! Data elements.
328 : : std::vector<std::vector<unsigned char>> stack;
329 : : //! Construct an empty stack (valid).
330 : : InputStack() = default;
331 : : //! Construct a valid single-element stack (with an element up to 75 bytes).
332 [ - + ]: 274584 : InputStack(std::vector<unsigned char> in) : size(in.size() + 1), stack(Vector(std::move(in))) {}
333 : : //! Change availability
334 : : InputStack& SetAvailable(Availability avail);
335 : : //! Mark this input stack as having a signature.
336 : : InputStack& SetWithSig();
337 : : //! Mark this input stack as non-canonical (known to not be necessary in non-malleable satisfactions).
338 : : InputStack& SetNonCanon();
339 : : //! Mark this input stack as malleable.
340 : : InputStack& SetMalleable(bool x = true);
341 : : //! Concatenate two input stacks.
342 : : friend InputStack operator+(InputStack a, InputStack b);
343 : : //! Choose between two potential input stacks.
344 : : friend InputStack operator|(InputStack a, InputStack b);
345 : : };
346 : :
347 : : /** A stack consisting of a single zero-length element (interpreted as 0 by the script interpreter in numeric context). */
348 : : static const auto ZERO = InputStack(std::vector<unsigned char>());
349 : : /** A stack consisting of a single malleable 32-byte 0x0000...0000 element (for dissatisfying hash challenges). */
350 : : static const auto ZERO32 = InputStack(std::vector<unsigned char>(32, 0)).SetMalleable();
351 : : /** A stack consisting of a single 0x01 element (interpreted as 1 by the script interpreted in numeric context). */
352 : : static const auto ONE = InputStack(Vector((unsigned char)1));
353 : : /** The empty stack. */
354 : : static const auto EMPTY = InputStack();
355 : : /** A stack representing the lack of any (dis)satisfactions. */
356 : : static const auto INVALID = InputStack().SetAvailable(Availability::NO);
357 : :
358 : : //! A pair of a satisfaction and a dissatisfaction InputStack.
359 : 2448357 : struct InputResult {
360 : : InputStack nsat, sat;
361 : :
362 : : template<typename A, typename B>
363 [ - - - - : 544266 : InputResult(A&& in_nsat, B&& in_sat) : nsat(std::forward<A>(in_nsat)), sat(std::forward<B>(in_sat)) {}
- - + - -
- - - ][ +
- + - +
- ]
364 : : };
365 : :
366 : : //! Class whose objects represent the maximum of a list of integers.
367 : : template<typename I>
368 : : struct MaxInt {
369 : : const bool valid;
370 : : const I value;
371 : :
372 : 168143239 : MaxInt() : valid(false), value(0) {}
373 : 87168514 : MaxInt(I val) : valid(true), value(val) {}
374 : :
375 : 194497928 : friend MaxInt<I> operator+(const MaxInt<I>& a, const MaxInt<I>& b) {
376 [ + + + + ]: 194497928 : if (!a.valid || !b.valid) return {};
377 : 46650541 : return a.value + b.value;
378 : : }
379 : :
380 : 96440336 : friend MaxInt<I> operator|(const MaxInt<I>& a, const MaxInt<I>& b) {
381 [ + + ]: 96440336 : if (!a.valid) return b;
382 [ + + ]: 23488782 : if (!b.valid) return a;
383 [ + + ]: 35599036 : return std::max(a.value, b.value);
384 : : }
385 : : };
386 : :
387 : : struct Ops {
388 : : //! Non-push opcodes.
389 : : uint32_t count;
390 : : //! Number of keys in possibly executed OP_CHECKMULTISIG(VERIFY)s to satisfy.
391 : : MaxInt<uint32_t> sat;
392 : : //! Number of keys in possibly executed OP_CHECKMULTISIG(VERIFY)s to dissatisfy.
393 : : MaxInt<uint32_t> dsat;
394 : :
395 : 4717133 : Ops(uint32_t in_count, MaxInt<uint32_t> in_sat, MaxInt<uint32_t> in_dsat) : count(in_count), sat(in_sat), dsat(in_dsat) {};
396 : : };
397 : :
398 : : /** A data structure to help the calculation of stack size limits.
399 : : *
400 : : * Conceptually, every SatInfo object corresponds to a (possibly empty) set of script execution
401 : : * traces (sequences of opcodes).
402 : : * - SatInfo{} corresponds to the empty set.
403 : : * - SatInfo{n, e} corresponds to a single trace whose net effect is removing n elements from the
404 : : * stack (may be negative for a net increase), and reaches a maximum of e stack elements more
405 : : * than it ends with.
406 : : * - operator| is the union operation: (a | b) corresponds to the union of the traces in a and the
407 : : * traces in b.
408 : : * - operator+ is the concatenation operator: (a + b) corresponds to the set of traces formed by
409 : : * concatenating any trace in a with any trace in b.
410 : : *
411 : : * Its fields are:
412 : : * - valid is true if the set is non-empty.
413 : : * - netdiff (if valid) is the largest difference between stack size at the beginning and at the
414 : : * end of the script across all traces in the set.
415 : : * - exec (if valid) is the largest difference between stack size anywhere during execution and at
416 : : * the end of the script, across all traces in the set (note that this is not necessarily due
417 : : * to the same trace as the one that resulted in the value for netdiff).
418 : : *
419 : : * This allows us to build up stack size limits for any script efficiently, by starting from the
420 : : * individual opcodes miniscripts correspond to, using concatenation to construct scripts, and
421 : : * using the union operation to choose between execution branches. Since any top-level script
422 : : * satisfaction ends with a single stack element, we know that for a full script:
423 : : * - netdiff+1 is the maximal initial stack size (relevant for P2WSH stack limits).
424 : : * - exec+1 is the maximal stack size reached during execution (relevant for P2TR stack limits).
425 : : *
426 : : * Mathematically, SatInfo forms a semiring:
427 : : * - operator| is the semiring addition operator, with identity SatInfo{}, and which is commutative
428 : : * and associative.
429 : : * - operator+ is the semiring multiplication operator, with identity SatInfo{0}, and which is
430 : : * associative.
431 : : * - operator+ is distributive over operator|, so (a + (b | c)) = (a+b | a+c). This means we do not
432 : : * need to actually materialize all possible full execution traces over the whole script (which
433 : : * may be exponential in the length of the script); instead we can use the union operation at the
434 : : * individual subexpression level, and concatenate the result with subexpressions before and
435 : : * after it.
436 : : * - It is not a commutative semiring, because a+b can differ from b+a. For example, "OP_1 OP_DROP"
437 : : * has exec=1, while "OP_DROP OP_1" has exec=0.
438 : : */
439 : : struct SatInfo {
440 : : //! Whether a canonical satisfaction/dissatisfaction is possible at all.
441 : : const bool valid;
442 : : //! How much higher the stack size at start of execution can be compared to at the end.
443 : : const int32_t netdiff;
444 : : //! Mow much higher the stack size can be during execution compared to at the end.
445 : : const int32_t exec;
446 : :
447 : : /** Empty script set. */
448 : : constexpr SatInfo() noexcept : valid(false), netdiff(0), exec(0) {}
449 : :
450 : : /** Script set with a single script in it, with specified netdiff and exec. */
451 : 45289070 : constexpr SatInfo(int32_t in_netdiff, int32_t in_exec) noexcept :
452 : 45289070 : valid{true}, netdiff{in_netdiff}, exec{in_exec} {}
453 : :
454 : : /** Script set union. */
455 : 48220168 : constexpr friend SatInfo operator|(const SatInfo& a, const SatInfo& b) noexcept
456 : : {
457 : : // Union with an empty set is itself.
458 [ + + ]: 48220168 : if (!a.valid) return b;
459 [ + + ]: 11737969 : if (!b.valid) return a;
460 : : // Otherwise the netdiff and exec of the union is the maximum of the individual values.
461 [ + + + + ]: 25469003 : return {std::max(a.netdiff, b.netdiff), std::max(a.exec, b.exec)};
462 : : }
463 : :
464 : : /** Script set concatenation. */
465 : 143840841 : constexpr friend SatInfo operator+(const SatInfo& a, const SatInfo& b) noexcept
466 : : {
467 : : // Concatenation with an empty set yields an empty set.
468 [ + + + + ]: 143840841 : if (!a.valid || !b.valid) return {};
469 : : // Otherwise, the maximum stack size difference for the combined scripts is the sum of the
470 : : // netdiffs, and the maximum stack size difference anywhere is either b.exec (if the
471 : : // maximum occurred in b) or b.netdiff+a.exec (if the maximum occurred in a).
472 [ + + ]: 40074918 : return {a.netdiff + b.netdiff, std::max(b.exec, b.netdiff + a.exec)};
473 : : }
474 : :
475 : : /** The empty script. */
476 : : static constexpr SatInfo Empty() noexcept { return {0, 0}; }
477 : : /** A script consisting of a single push opcode. */
478 : : static constexpr SatInfo Push() noexcept { return {-1, 0}; }
479 : : /** A script consisting of a single hash opcode. */
480 : : static constexpr SatInfo Hash() noexcept { return {0, 0}; }
481 : : /** A script consisting of just a repurposed nop (OP_CHECKLOCKTIMEVERIFY, OP_CHECKSEQUENCEVERIFY). */
482 : : static constexpr SatInfo Nop() noexcept { return {0, 0}; }
483 : : /** A script consisting of just OP_IF or OP_NOTIF. Note that OP_ELSE and OP_ENDIF have no stack effect. */
484 : : static constexpr SatInfo If() noexcept { return {1, 1}; }
485 : : /** A script consisting of just a binary operator (OP_BOOLAND, OP_BOOLOR, OP_ADD). */
486 : : static constexpr SatInfo BinaryOp() noexcept { return {1, 1}; }
487 : :
488 : : // Scripts for specific individual opcodes.
489 : : static constexpr SatInfo OP_DUP() noexcept { return {-1, 0}; }
490 : : static constexpr SatInfo OP_IFDUP(bool nonzero) noexcept { return {nonzero ? -1 : 0, 0}; }
491 : : static constexpr SatInfo OP_EQUALVERIFY() noexcept { return {2, 2}; }
492 : : static constexpr SatInfo OP_EQUAL() noexcept { return {1, 1}; }
493 : : static constexpr SatInfo OP_SIZE() noexcept { return {-1, 0}; }
494 : : static constexpr SatInfo OP_CHECKSIG() noexcept { return {1, 1}; }
495 : : static constexpr SatInfo OP_0NOTEQUAL() noexcept { return {0, 0}; }
496 : : static constexpr SatInfo OP_VERIFY() noexcept { return {1, 1}; }
497 : : };
498 : :
499 : : struct StackSize {
500 : : const SatInfo sat, dsat;
501 : :
502 : 481483 : constexpr StackSize(SatInfo in_sat, SatInfo in_dsat) noexcept : sat(in_sat), dsat(in_dsat) {};
503 : 59600 : constexpr StackSize(SatInfo in_both) noexcept : sat(in_both), dsat(in_both) {};
504 : : };
505 : :
506 : : struct WitnessSize {
507 : : //! Maximum witness size to satisfy;
508 : : MaxInt<uint32_t> sat;
509 : : //! Maximum witness size to dissatisfy;
510 : : MaxInt<uint32_t> dsat;
511 : :
512 : 4283279 : WitnessSize(MaxInt<uint32_t> in_sat, MaxInt<uint32_t> in_dsat) : sat(in_sat), dsat(in_dsat) {};
513 : : };
514 : :
515 : : struct NoDupCheck {};
516 : :
517 : : } // namespace internal
518 : :
519 : : //! A node in a miniscript expression.
520 : : template<typename Key>
521 : : struct Node {
522 : : //! What node type this node is.
523 : : const Fragment fragment;
524 : : //! The k parameter (time for OLDER/AFTER, threshold for THRESH(_M))
525 : : const uint32_t k = 0;
526 : : //! The keys used by this expression (only for PK_K/PK_H/MULTI)
527 : : const std::vector<Key> keys;
528 : : //! The data bytes in this expression (only for HASH160/HASH256/SHA256/RIPEMD10).
529 : : const std::vector<unsigned char> data;
530 : : //! Subexpressions (for WRAP_*/AND_*/OR_*/ANDOR/THRESH)
531 : : mutable std::vector<NodeRef<Key>> subs;
532 : : //! The Script context for this node. Either P2WSH or Tapscript.
533 : : const MiniscriptContext m_script_ctx;
534 : :
535 : : /* Destroy the shared pointers iteratively to avoid a stack-overflow due to recursive calls
536 : : * to the subs' destructors. */
537 : 16886389 : ~Node() {
538 [ + + ]: 28755992 : while (!subs.empty()) {
539 : 11869603 : auto node = std::move(subs.back());
540 : 11869603 : subs.pop_back();
541 [ + + ]: 23135125 : while (!node->subs.empty()) {
542 : 11265522 : subs.push_back(std::move(node->subs.back()));
543 : 11265522 : node->subs.pop_back();
544 : : }
545 : : }
546 : 16886389 : }
547 : :
548 : 20795 : NodeRef<Key> Clone() const
549 : : {
550 : : // Use TreeEval() to avoid a stack-overflow due to recursion
551 : 1051807 : auto upfn = [](const Node& node, std::span<NodeRef<Key>> children) {
552 : 1051807 : std::vector<NodeRef<Key>> new_subs;
553 [ + + ]: 2082819 : for (auto child = children.begin(); child != children.end(); ++child) {
554 [ + - ]: 1031012 : new_subs.emplace_back(std::move(*child));
555 : : }
556 : : // std::make_unique (and therefore MakeNodeRef) doesn't work on private constructors
557 [ + - + - : 2103614 : return std::unique_ptr<Node>{new Node{internal::NoDupCheck{}, node.m_script_ctx, node.fragment, std::move(new_subs), node.keys, node.data, node.k}};
+ - + - ]
558 : 1051807 : };
559 [ + - + - ]: 20795 : return TreeEval<NodeRef<Key>>(upfn);
560 : : }
561 : :
562 : : private:
563 : : //! Cached ops counts.
564 : : const internal::Ops ops;
565 : : //! Cached stack size bounds.
566 : : const internal::StackSize ss;
567 : : //! Cached witness size bounds.
568 : : const internal::WitnessSize ws;
569 : : //! Cached expression type (computed by CalcType and fed through SanitizeType).
570 : : const Type typ;
571 : : //! Cached script length (computed by CalcScriptLen).
572 : : const size_t scriptlen;
573 : : //! Whether a public key appears more than once in this node. This value is initialized
574 : : //! by all constructors except the NoDupCheck ones. The NoDupCheck ones skip the
575 : : //! computation, requiring it to be done manually by invoking DuplicateKeyCheck().
576 : : //! DuplicateKeyCheck(), or a non-NoDupCheck constructor, will compute has_duplicate_keys
577 : : //! for all subnodes as well.
578 : : mutable std::optional<bool> has_duplicate_keys;
579 : :
580 : : // Constructor which takes all of the data that a Node could possibly contain.
581 : : // This is kept private as no valid fragment has all of these arguments.
582 : : // Only used by Clone()
583 : 1051807 : Node(internal::NoDupCheck, MiniscriptContext script_ctx, Fragment nt, std::vector<NodeRef<Key>> sub, std::vector<Key> key, std::vector<unsigned char> arg, uint32_t val)
584 [ + - + - : 1051807 : : fragment(nt), k(val), keys(key), data(std::move(arg)), subs(std::move(sub)), m_script_ctx{script_ctx}, ops(CalcOps()), ss(CalcStackSize()), ws(CalcWitnessSize()), typ(CalcType()), scriptlen(CalcScriptLen()) {}
+ - + - +
- ]
585 : :
586 : : //! Compute the length of the script for this miniscript (including children).
587 : 16886389 : size_t CalcScriptLen() const {
588 : 16886389 : size_t subsize = 0;
589 [ + + ]: 28755992 : for (const auto& sub : subs) {
590 : 11869603 : subsize += sub->ScriptSize();
591 : : }
592 [ - + + + ]: 16886389 : Type sub0type = subs.size() > 0 ? subs[0]->GetType() : ""_mst;
593 [ - + ]: 16886389 : return internal::ComputeScriptLen(fragment, sub0type, subsize, k, subs.size(), keys.size(), m_script_ctx);
594 : : }
595 : :
596 : : /* Apply a recursive algorithm to a Miniscript tree, without actual recursive calls.
597 : : *
598 : : * The algorithm is defined by two functions: downfn and upfn. Conceptually, the
599 : : * result can be thought of as first using downfn to compute a "state" for each node,
600 : : * from the root down to the leaves. Then upfn is used to compute a "result" for each
601 : : * node, from the leaves back up to the root, which is then returned. In the actual
602 : : * implementation, both functions are invoked in an interleaved fashion, performing a
603 : : * depth-first traversal of the tree.
604 : : *
605 : : * In more detail, it is invoked as node.TreeEvalMaybe<Result>(root, downfn, upfn):
606 : : * - root is the state of the root node, of type State.
607 : : * - downfn is a callable (State&, const Node&, size_t) -> State, which given a
608 : : * node, its state, and an index of one of its children, computes the state of that
609 : : * child. It can modify the state. Children of a given node will have downfn()
610 : : * called in order.
611 : : * - upfn is a callable (State&&, const Node&, std::span<Result>) -> std::optional<Result>,
612 : : * which given a node, its state, and a span of the results of its children,
613 : : * computes the result of the node. If std::nullopt is returned by upfn,
614 : : * TreeEvalMaybe() immediately returns std::nullopt.
615 : : * The return value of TreeEvalMaybe is the result of the root node.
616 : : *
617 : : * Result type cannot be bool due to the std::vector<bool> specialization.
618 : : */
619 : : template<typename Result, typename State, typename DownFn, typename UpFn>
620 : 186007 : std::optional<Result> TreeEvalMaybe(State root_state, DownFn downfn, UpFn upfn) const
621 : : {
622 : : /** Entries of the explicit stack tracked in this algorithm. */
623 : : struct StackElem
624 : : {
625 : : const Node& node; //!< The node being evaluated.
626 : : size_t expanded; //!< How many children of this node have been expanded.
627 : : State state; //!< The state for that node.
628 : :
629 : 14790181 : StackElem(const Node& node_, size_t exp_, State&& state_) :
630 : 14790181 : node(node_), expanded(exp_), state(std::move(state_)) {}
631 : : };
632 : : /* Stack of tree nodes being explored. */
633 : 186007 : std::vector<StackElem> stack;
634 : : /* Results of subtrees so far. Their order and mapping to tree nodes
635 : : * is implicitly defined by stack. */
636 : 186007 : std::vector<Result> results;
637 [ + - ]: 186007 : stack.emplace_back(*this, 0, std::move(root_state));
638 : :
639 : : /* Here is a demonstration of the algorithm, for an example tree A(B,C(D,E),F).
640 : : * State variables are omitted for simplicity.
641 : : *
642 : : * First: stack=[(A,0)] results=[]
643 : : * stack=[(A,1),(B,0)] results=[]
644 : : * stack=[(A,1)] results=[B]
645 : : * stack=[(A,2),(C,0)] results=[B]
646 : : * stack=[(A,2),(C,1),(D,0)] results=[B]
647 : : * stack=[(A,2),(C,1)] results=[B,D]
648 : : * stack=[(A,2),(C,2),(E,0)] results=[B,D]
649 : : * stack=[(A,2),(C,2)] results=[B,D,E]
650 : : * stack=[(A,2)] results=[B,C]
651 : : * stack=[(A,3),(F,0)] results=[B,C]
652 : : * stack=[(A,3)] results=[B,C,F]
653 : : * Final: stack=[] results=[A]
654 : : */
655 [ - + + + ]: 41914742 : while (stack.size()) {
656 : 29394096 : const Node& node = stack.back().node;
657 [ - + + + ]: 29394096 : if (stack.back().expanded < node.subs.size()) {
658 : : /* We encounter a tree node with at least one unexpanded child.
659 : : * Expand it. By the time we hit this node again, the result of
660 : : * that child (and all earlier children) will be at the end of `results`. */
661 : 14604174 : size_t child_index = stack.back().expanded++;
662 : 16520195 : State child_state = downfn(stack.back().state, node, child_index);
663 [ + - ]: 14604174 : stack.emplace_back(*node.subs[child_index], 0, std::move(child_state));
664 : 14604174 : continue;
665 : 14604174 : }
666 : : // Invoke upfn with the last node.subs.size() elements of results as input.
667 [ - + ]: 14789922 : assert(results.size() >= node.subs.size());
668 [ - + ]: 14789922 : std::optional<Result> result{upfn(std::move(stack.back().state), node,
669 [ + - ]: 14789922 : std::span<Result>{results}.last(node.subs.size()))};
670 : : // If evaluation returns std::nullopt, abort immediately.
671 [ + + ]: 14789922 : if (!result) return {};
[ - + - - ]
672 : : // Replace the last node.subs.size() elements of results with the new result.
673 [ + + + - ]: 14789853 : results.erase(results.end() - node.subs.size(), results.end());
674 [ + - ]: 14789853 : results.push_back(std::move(*result));
[ + - + - ]
675 [ + - ]: 14789853 : stack.pop_back();
676 : : }
677 : : // The final remaining results element is the root result, return it.
678 [ - + ]: 185938 : assert(results.size() >= 1);
679 [ + - ]: 185938 : CHECK_NONFATAL(results.size() == 1);
680 : 185938 : return std::move(results[0]);
681 : 186007 : }
682 : :
683 : : /** Like TreeEvalMaybe, but without downfn or State type.
684 : : * upfn takes (const Node&, std::span<Result>) and returns std::optional<Result>. */
685 : : template<typename Result, typename UpFn>
686 : : std::optional<Result> TreeEvalMaybe(UpFn upfn) const
687 : : {
688 : : struct DummyState {};
689 : : return TreeEvalMaybe<Result>(DummyState{},
690 : : [](DummyState, const Node&, size_t) { return DummyState{}; },
691 : : [&upfn](DummyState, const Node& node, std::span<Result> subs) {
692 : : return upfn(node, subs);
693 : : }
694 : : );
695 : : }
696 : :
697 : : /** Like TreeEvalMaybe, but always produces a result. upfn must return Result. */
698 : : template<typename Result, typename State, typename DownFn, typename UpFn>
699 : 46937 : Result TreeEval(State root_state, DownFn&& downfn, UpFn upfn) const
700 : : {
701 : : // Invoke TreeEvalMaybe with upfn wrapped to return std::optional<Result>, and then
702 : : // unconditionally dereference the result (it cannot be std::nullopt).
703 : 46937 : return std::move(*TreeEvalMaybe<Result>(std::move(root_state),
704 : : std::forward<DownFn>(downfn),
705 : 1962958 : [&upfn](State&& state, const Node& node, std::span<Result> subs) {
706 : 1962958 : Result res{upfn(std::move(state), node, subs)};
707 : 1962958 : return std::optional<Result>(std::move(res));
708 : 1962958 : }
709 : 46937 : ));
710 : : }
711 : :
712 : : /** Like TreeEval, but without downfn or State type.
713 : : * upfn takes (const Node&, std::span<Result>) and returns Result. */
714 : : template<typename Result, typename UpFn>
715 : 84674 : Result TreeEval(UpFn upfn) const
716 : : {
717 : : struct DummyState {};
718 : 84674 : return std::move(*TreeEvalMaybe<Result>(DummyState{},
719 : : [](DummyState, const Node&, size_t) { return DummyState{}; },
720 : 10414409 : [&upfn](DummyState, const Node& node, std::span<Result> subs) {
721 : 10414409 : Result res{upfn(node, subs)};
722 : 6907388 : return std::optional<Result>(std::move(res));
723 : 4271290 : }
724 [ + - ]: 84674 : ));
725 : : }
726 : :
727 : : /** Compare two miniscript subtrees, using a non-recursive algorithm. */
728 : 6146 : friend int Compare(const Node<Key>& node1, const Node<Key>& node2)
729 : : {
730 : 6146 : std::vector<std::pair<const Node<Key>&, const Node<Key>&>> queue;
731 [ + - ]: 6146 : queue.emplace_back(node1, node2);
732 [ + + ]: 879260 : while (!queue.empty()) {
733 : 873114 : const auto& [a, b] = queue.back();
734 : 873114 : queue.pop_back();
735 [ + - ]: 873114 : if (std::tie(a.fragment, a.k, a.keys, a.data) < std::tie(b.fragment, b.k, b.keys, b.data)) return -1;
736 [ + - ]: 873114 : if (std::tie(b.fragment, b.k, b.keys, b.data) < std::tie(a.fragment, a.k, a.keys, a.data)) return 1;
737 [ - + - + : 873114 : if (a.subs.size() < b.subs.size()) return -1;
+ - ]
738 [ + - ]: 873114 : if (b.subs.size() < a.subs.size()) return 1;
739 : 873114 : size_t n = a.subs.size();
740 [ + + ]: 1740082 : for (size_t i = 0; i < n; ++i) {
741 [ + - ]: 866968 : queue.emplace_back(*a.subs[n - 1 - i], *b.subs[n - 1 - i]);
742 : : }
743 : : }
744 : : return 0;
745 : 6146 : }
746 : :
747 : : //! Compute the type for this miniscript.
748 : 16886389 : Type CalcType() const {
749 : : using namespace internal;
750 : :
751 : : // THRESH has a variable number of subexpressions
752 : 16886389 : std::vector<Type> sub_types;
753 [ + + ]: 16886389 : if (fragment == Fragment::THRESH) {
754 [ + - + + ]: 1034532 : for (const auto& sub : subs) sub_types.push_back(sub->GetType());
755 : : }
756 : : // All other nodes than THRESH can be computed just from the types of the 0-3 subexpressions.
757 [ - + + + ]: 16886389 : Type x = subs.size() > 0 ? subs[0]->GetType() : ""_mst;
758 [ + + ]: 16886389 : Type y = subs.size() > 1 ? subs[1]->GetType() : ""_mst;
759 [ + + ]: 16886389 : Type z = subs.size() > 2 ? subs[2]->GetType() : ""_mst;
760 : :
761 [ - + - + : 16886389 : return SanitizeType(ComputeType(fragment, x, y, z, sub_types, k, data.size(), subs.size(), keys.size(), m_script_ctx));
+ - + - ]
762 : 16886389 : }
763 : :
764 : : public:
765 : : template<typename Ctx>
766 : 46937 : CScript ToScript(const Ctx& ctx) const
767 : : {
768 : : // To construct the CScript for a Miniscript object, we use the TreeEval algorithm.
769 : : // The State is a boolean: whether or not the node's script expansion is followed
770 : : // by an OP_VERIFY (which may need to be combined with the last script opcode).
771 : 1916021 : auto downfn = [](bool verify, const Node& node, size_t index) {
772 : : // For WRAP_V, the subexpression is certainly followed by OP_VERIFY.
773 [ + + ]: 1916021 : if (node.fragment == Fragment::WRAP_V) return true;
[ + + + + ]
774 : : // The subexpression of WRAP_S, and the last subexpression of AND_V
775 : : // inherit the followed-by-OP_VERIFY property from the parent.
776 [ + + + + ]: 1797518 : if (node.fragment == Fragment::WRAP_S ||
[ + + + +
+ + + + ]
777 [ + + ]: 232296 : (node.fragment == Fragment::AND_V && index == 1)) return verify;
[ + + + + ]
778 : : return false;
779 : : };
780 : : // The upward function computes for a node, given its followed-by-OP_VERIFY status
781 : : // and the CScripts of its child nodes, the CScript of the node.
782 : 46937 : const bool is_tapscript{IsTapscript(m_script_ctx)};
783 : 2009895 : auto upfn = [&ctx, is_tapscript](bool verify, const Node& node, std::span<CScript> subs) -> CScript {
784 [ + + + + : 1962958 : switch (node.fragment) {
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + - ]
[ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + - +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ - ]
785 : 53020 : case Fragment::PK_K: return BuildScript(ctx.ToPKBytes(node.keys[0]));
786 [ + - ]: 65532 : case Fragment::PK_H: return BuildScript(OP_DUP, OP_HASH160, ctx.ToPKHBytes(node.keys[0]), OP_EQUALVERIFY);
[ + - + - ]
787 : 13889 : case Fragment::OLDER: return BuildScript(node.k, OP_CHECKSEQUENCEVERIFY);
788 : 11225 : case Fragment::AFTER: return BuildScript(node.k, OP_CHECKLOCKTIMEVERIFY);
789 [ + + ]: 14716 : case Fragment::SHA256: return BuildScript(OP_SIZE, 32, OP_EQUALVERIFY, OP_SHA256, node.data, verify ? OP_EQUALVERIFY : OP_EQUAL);
[ + + + + ]
790 [ + + ]: 15348 : case Fragment::RIPEMD160: return BuildScript(OP_SIZE, 32, OP_EQUALVERIFY, OP_RIPEMD160, node.data, verify ? OP_EQUALVERIFY : OP_EQUAL);
[ + + + + ]
791 [ + + ]: 16082 : case Fragment::HASH256: return BuildScript(OP_SIZE, 32, OP_EQUALVERIFY, OP_HASH256, node.data, verify ? OP_EQUALVERIFY : OP_EQUAL);
[ + + + + ]
792 [ + + ]: 15744 : case Fragment::HASH160: return BuildScript(OP_SIZE, 32, OP_EQUALVERIFY, OP_HASH160, node.data, verify ? OP_EQUALVERIFY : OP_EQUAL);
[ + + + + ]
793 : 83553 : case Fragment::WRAP_A: return BuildScript(OP_TOALTSTACK, subs[0], OP_FROMALTSTACK);
794 : 11750 : case Fragment::WRAP_S: return BuildScript(OP_SWAP, subs[0]);
795 [ + + ]: 118960 : case Fragment::WRAP_C: return BuildScript(std::move(subs[0]), verify ? OP_CHECKSIGVERIFY : OP_CHECKSIG);
[ + + + + ]
796 : 5161 : case Fragment::WRAP_D: return BuildScript(OP_DUP, OP_IF, subs[0], OP_ENDIF);
797 : 118503 : case Fragment::WRAP_V: {
798 [ + + ]: 118503 : if (node.subs[0]->GetType() << "x"_mst) {
[ + + + + ]
799 : 73474 : return BuildScript(std::move(subs[0]), OP_VERIFY);
800 : : } else {
801 : 45029 : return std::move(subs[0]);
802 : : }
803 : : }
804 : 79994 : case Fragment::WRAP_J: return BuildScript(OP_SIZE, OP_0NOTEQUAL, OP_IF, subs[0], OP_ENDIF);
805 : 496615 : case Fragment::WRAP_N: return BuildScript(std::move(subs[0]), OP_0NOTEQUAL);
806 : 69001 : case Fragment::JUST_1: return BuildScript(OP_1);
807 : 354337 : case Fragment::JUST_0: return BuildScript(OP_0);
808 : 110273 : case Fragment::AND_V: return BuildScript(std::move(subs[0]), subs[1]);
809 : 22502 : case Fragment::AND_B: return BuildScript(std::move(subs[0]), subs[1], OP_BOOLAND);
810 : 18582 : case Fragment::OR_B: return BuildScript(std::move(subs[0]), subs[1], OP_BOOLOR);
811 : 26496 : case Fragment::OR_D: return BuildScript(std::move(subs[0]), OP_IFDUP, OP_NOTIF, subs[1], OP_ENDIF);
812 : 12518 : case Fragment::OR_C: return BuildScript(std::move(subs[0]), OP_NOTIF, subs[1], OP_ENDIF);
813 : 235051 : case Fragment::OR_I: return BuildScript(OP_IF, subs[0], OP_ELSE, subs[1], OP_ENDIF);
814 : 39023 : case Fragment::ANDOR: return BuildScript(std::move(subs[0]), OP_NOTIF, subs[2], OP_ELSE, subs[1], OP_ENDIF);
815 : 27338 : case Fragment::MULTI: {
816 : 27338 : CHECK_NONFATAL(!is_tapscript);
817 : 27338 : CScript script = BuildScript(node.k);
818 [ + + ]: 148663 : for (const auto& key : node.keys) {
[ + + + + ]
819 [ + - ]: 121325 : script = BuildScript(std::move(script), ctx.ToPKBytes(key));
820 : : }
821 [ + + - + : 46468 : return BuildScript(std::move(script), node.keys.size(), verify ? OP_CHECKMULTISIGVERIFY : OP_CHECKMULTISIG);
+ - ][ + +
- + + - +
+ - + +
- ]
822 : 27338 : }
823 : 7962 : case Fragment::MULTI_A: {
824 : 7962 : CHECK_NONFATAL(is_tapscript);
825 [ + - ]: 7962 : CScript script = BuildScript(ctx.ToPKBytes(*node.keys.begin()), OP_CHECKSIG);
826 [ + + ]: 74950 : for (auto it = node.keys.begin() + 1; it != node.keys.end(); ++it) {
[ + + + + ]
827 [ + - + - ]: 133976 : script = BuildScript(std::move(script), ctx.ToPKBytes(*it), OP_CHECKSIGADD);
[ + - + -
+ - ]
828 : : }
829 [ + + + - ]: 12122 : return BuildScript(std::move(script), node.k, verify ? OP_NUMEQUALVERIFY : OP_NUMEQUAL);
[ + + + -
+ + + - ]
830 : 7962 : }
831 : 31113 : case Fragment::THRESH: {
832 : 31113 : CScript script = std::move(subs[0]);
833 [ + + ]: 85216 : for (size_t i = 1; i < subs.size(); ++i) {
[ + + + + ]
834 [ + - ]: 108206 : script = BuildScript(std::move(script), subs[i], OP_ADD);
[ + - + - ]
835 : : }
836 [ + + + - ]: 52929 : return BuildScript(std::move(script), node.k, verify ? OP_EQUALVERIFY : OP_EQUAL);
[ + + + -
+ + + - ]
837 : 31113 : }
838 : : }
839 : 0 : assert(false);
840 : : };
841 : 46937 : return TreeEval<CScript>(false, downfn, upfn);
842 : : }
843 : :
844 : : template<typename CTx>
845 : 9179 : std::optional<std::string> ToString(const CTx& ctx) const {
846 : 9179 : bool dummy{false};
847 [ + - ]: 9179 : return ToString(ctx, dummy);
848 : : }
849 : :
850 : : template<typename CTx>
851 : 54396 : std::optional<std::string> ToString(const CTx& ctx, bool& has_priv_key) const {
852 : : // To construct the std::string representation for a Miniscript object, we use
853 : : // the TreeEvalMaybe algorithm. The State is a boolean: whether the parent node is a
854 : : // wrapper. If so, non-wrapper expressions must be prefixed with a ":".
855 : 2358418 : auto downfn = [](bool, const Node& node, size_t) {
856 : 2358418 : return (node.fragment == Fragment::WRAP_A || node.fragment == Fragment::WRAP_S ||
857 [ + + + + : 2209163 : node.fragment == Fragment::WRAP_D || node.fragment == Fragment::WRAP_V ||
+ + + + ]
[ + + + + ]
858 [ + + + + : 2016151 : node.fragment == Fragment::WRAP_J || node.fragment == Fragment::WRAP_N ||
+ + + + ]
[ + + + + ]
859 [ + + + + ]: 1446502 : node.fragment == Fragment::WRAP_C ||
[ + + ]
860 [ + + + + : 1446502 : (node.fragment == Fragment::AND_V && node.subs[1]->fragment == Fragment::JUST_1) ||
+ + + + ]
[ + + + + ]
861 [ + + + + : 3577278 : (node.fragment == Fragment::OR_I && node.subs[0]->fragment == Fragment::JUST_0) ||
+ + + + +
+ + + ][ +
+ + + +
+ ]
862 [ + + + + ]: 321787 : (node.fragment == Fragment::OR_I && node.subs[1]->fragment == Fragment::JUST_0));
[ + + ]
863 : : };
864 : 360671 : auto toString = [&ctx, &has_priv_key](Key key) -> std::optional<std::string> {
865 : 306275 : bool fragment_has_priv_key{false};
866 [ + - + + ]: 306275 : auto key_str{ctx.ToString(key, fragment_has_priv_key)};
[ + - ]
867 [ + - + - : 451026 : if (key_str) has_priv_key = has_priv_key || fragment_has_priv_key;
+ - + + +
+ + + ][ +
- + + -
+ ]
868 : 306275 : return key_str;
869 : : };
870 : : // The upward function computes for a node, given whether its parent is a wrapper,
871 : : // and the string representations of its child nodes, the string representation of the node.
872 : 54396 : const bool is_tapscript{IsTapscript(m_script_ctx)};
873 : 2466951 : auto upfn = [is_tapscript, &toString](bool wrapped, const Node& node, std::span<std::string> subs) -> std::optional<std::string> {
874 [ + + + + ]: 3046588 : std::string ret = wrapped ? ":" : "";
[ + + ]
875 : :
876 [ + + + + : 2412555 : switch (node.fragment) {
+ + + + +
+ + + + +
+ + + + +
+ ][ + + +
+ + + + +
+ + ]
877 [ + - + - ]: 189418 : case Fragment::WRAP_A: return "a" + std::move(subs[0]);
[ + - ]
878 [ + - + - ]: 55976 : case Fragment::WRAP_S: return "s" + std::move(subs[0]);
[ + - ]
879 : 75561 : case Fragment::WRAP_C:
880 [ + + + + ]: 75561 : if (node.subs[0]->fragment == Fragment::PK_K) {
[ + + ]
881 : : // pk(K) is syntactic sugar for c:pk_k(K)
882 [ + - + - ]: 38189 : auto key_str = toString(node.subs[0]->keys[0]);
[ + - ]
883 [ - + - + ]: 38189 : if (!key_str) return {};
[ - + ]
884 [ + - + - : 114567 : return std::move(ret) + "pk(" + std::move(*key_str) + ")";
+ - + - ]
[ + - + - ]
885 : 38189 : }
886 [ + + + + ]: 37372 : if (node.subs[0]->fragment == Fragment::PK_H) {
[ + + ]
887 : : // pkh(K) is syntactic sugar for c:pk_h(K)
888 [ + - + - ]: 19553 : auto key_str = toString(node.subs[0]->keys[0]);
[ + - ]
889 [ - + - + ]: 19553 : if (!key_str) return {};
[ - + ]
890 [ + - + - : 58659 : return std::move(ret) + "pkh(" + std::move(*key_str) + ")";
+ - + - ]
[ + - + - ]
891 : 19553 : }
892 [ + - + - ]: 35638 : return "c" + std::move(subs[0]);
[ + - ]
893 [ + - + - ]: 53096 : case Fragment::WRAP_D: return "d" + std::move(subs[0]);
[ + - ]
894 [ + - + - ]: 280504 : case Fragment::WRAP_V: return "v" + std::move(subs[0]);
[ + - ]
895 [ + - + - ]: 105374 : case Fragment::WRAP_J: return "j" + std::move(subs[0]);
[ + - ]
896 [ + - + - ]: 988052 : case Fragment::WRAP_N: return "n" + std::move(subs[0]);
[ + - ]
897 : 169833 : case Fragment::AND_V:
898 : : // t:X is syntactic sugar for and_v(X,1).
899 [ + + + - : 283636 : if (node.subs[1]->fragment == Fragment::JUST_1) return "t" + std::move(subs[0]);
+ + + - ]
[ + + + - ]
900 : : break;
901 : 342369 : case Fragment::OR_I:
902 [ + + + - : 523853 : if (node.subs[0]->fragment == Fragment::JUST_0) return "l" + std::move(subs[1]);
+ + + - ]
[ + + + - ]
903 [ + + + - : 298917 : if (node.subs[1]->fragment == Fragment::JUST_0) return "u" + std::move(subs[0]);
+ + + - ]
[ + + + - ]
904 : : break;
905 : : default: break;
906 : : }
907 [ + + + + : 1067465 : switch (node.fragment) {
+ + + + +
+ + + + +
+ + + + +
+ - + + +
+ + + + +
+ + + + +
+ + + + +
+ + - ][ +
+ + + + +
+ + + + +
+ + + + +
+ + + +
- ]
908 : 48230 : case Fragment::PK_K: {
909 [ + - + - ]: 48230 : auto key_str = toString(node.keys[0]);
[ + - ]
910 [ - + + + ]: 48230 : if (!key_str) return {};
[ - + ]
911 [ + - + - : 144645 : return std::move(ret) + "pk_k(" + std::move(*key_str) + ")";
+ - + - ]
[ + - + - ]
912 : 48230 : }
913 : 24988 : case Fragment::PK_H: {
914 [ + - + - ]: 24988 : auto key_str = toString(node.keys[0]);
[ + - ]
915 [ - + + + ]: 24988 : if (!key_str) return {};
[ - + ]
916 [ + - + - : 74943 : return std::move(ret) + "pk_h(" + std::move(*key_str) + ")";
+ - + - ]
[ + - + - ]
917 : 24988 : }
918 [ + - + - : 55419 : case Fragment::AFTER: return std::move(ret) + "after(" + util::ToString(node.k) + ")";
+ - + - ]
[ + - + - ]
919 [ + - + - : 77457 : case Fragment::OLDER: return std::move(ret) + "older(" + util::ToString(node.k) + ")";
+ - + - ]
[ + - + - ]
920 [ - + + - : 15333 : case Fragment::HASH256: return std::move(ret) + "hash256(" + HexStr(node.data) + ")";
+ - - + +
- + - ][ -
+ + - +
- ]
921 [ - + + - : 16068 : case Fragment::HASH160: return std::move(ret) + "hash160(" + HexStr(node.data) + ")";
+ - - + +
- + - ][ -
+ + - +
- ]
922 [ - + + - : 13008 : case Fragment::SHA256: return std::move(ret) + "sha256(" + HexStr(node.data) + ")";
+ - - + +
- + - ][ -
+ + - +
- ]
923 [ - + + - : 14757 : case Fragment::RIPEMD160: return std::move(ret) + "ripemd160(" + HexStr(node.data) + ")";
+ - - + +
- + - ][ -
+ + - +
- ]
924 [ + - + - ]: 370660 : case Fragment::JUST_1: return std::move(ret) + "1";
[ + - ]
925 [ + - + - ]: 1002942 : case Fragment::JUST_0: return std::move(ret) + "0";
[ + - ]
926 [ + - + - : 224120 : case Fragment::AND_V: return std::move(ret) + "and_v(" + std::move(subs[0]) + "," + std::move(subs[1]) + ")";
+ - + - +
- + - ][ +
- + - +
- ]
927 [ + - + - : 84764 : case Fragment::AND_B: return std::move(ret) + "and_b(" + std::move(subs[0]) + "," + std::move(subs[1]) + ")";
+ - + - +
- + - ][ +
- + - +
- ]
928 [ + - + - : 62728 : case Fragment::OR_B: return std::move(ret) + "or_b(" + std::move(subs[0]) + "," + std::move(subs[1]) + ")";
+ - + - +
- + - ][ +
- + - +
- ]
929 [ + - + - : 78684 : case Fragment::OR_D: return std::move(ret) + "or_d(" + std::move(subs[0]) + "," + std::move(subs[1]) + ")";
+ - + - +
- + - ][ +
- + - +
- ]
930 [ + - + - : 42404 : case Fragment::OR_C: return std::move(ret) + "or_c(" + std::move(subs[0]) + "," + std::move(subs[1]) + ")";
+ - + - +
- + - ][ +
- + - +
- ]
931 [ + - + - : 91412 : case Fragment::OR_I: return std::move(ret) + "or_i(" + std::move(subs[0]) + "," + std::move(subs[1]) + ")";
+ - + - +
- + - ][ +
- + - +
- ]
932 : 34845 : case Fragment::ANDOR:
933 : : // and_n(X,Y) is syntactic sugar for andor(X,Y,0).
934 [ + + + - : 81567 : if (node.subs[2]->fragment == Fragment::JUST_0) return std::move(ret) + "and_n(" + std::move(subs[0]) + "," + std::move(subs[1]) + ")";
+ - + - +
+ + - + -
+ - ][ + +
+ - + - +
- ]
935 [ + - + - : 96355 : return std::move(ret) + "andor(" + std::move(subs[0]) + "," + std::move(subs[1]) + "," + std::move(subs[2]) + ")";
+ - + - +
- + - + -
+ - ][ + -
+ - + - +
- ]
936 : 21498 : case Fragment::MULTI: {
937 [ + - + - ]: 21498 : CHECK_NONFATAL(!is_tapscript);
[ + - ]
938 [ + - + - : 64494 : auto str = std::move(ret) + "multi(" + util::ToString(node.k);
+ - + - ]
[ + - + - ]
939 [ + + + + ]: 112131 : for (const auto& key : node.keys) {
[ + + ]
940 [ + - + - ]: 90633 : auto key_str = toString(key);
[ + - ]
941 [ - + + + ]: 90633 : if (!key_str) return {};
[ - + ]
942 [ + - + - ]: 181174 : str += "," + std::move(*key_str);
[ + - ]
943 : : }
944 : 21452 : return std::move(str) + ")";
945 : 21498 : }
946 : 9238 : case Fragment::MULTI_A: {
947 [ + - + - ]: 9238 : CHECK_NONFATAL(is_tapscript);
[ + - ]
948 [ + - + - : 27714 : auto str = std::move(ret) + "multi_a(" + util::ToString(node.k);
+ - + - ]
[ + - + - ]
949 [ + + + + ]: 93920 : for (const auto& key : node.keys) {
[ + + ]
950 [ + - + - ]: 84682 : auto key_str = toString(key);
[ + - ]
951 [ - + + + ]: 84682 : if (!key_str) return {};
[ - + ]
952 [ + - + - ]: 169362 : str += "," + std::move(*key_str);
[ + - ]
953 : : }
954 : 9237 : return std::move(str) + ")";
955 : 9238 : }
956 : 31823 : case Fragment::THRESH: {
957 [ + - + - : 95469 : auto str = std::move(ret) + "thresh(" + util::ToString(node.k);
+ - + - ]
[ + - + - ]
958 [ + + + + ]: 214910 : for (auto& sub : subs) {
[ + + ]
959 [ + - + - ]: 366174 : str += "," + std::move(sub);
[ + - ]
960 : : }
961 : 31823 : return std::move(str) + ")";
962 : 31823 : }
963 : : default: break;
964 : : }
965 : 0 : assert(false);
966 : 2412555 : };
967 : :
968 : 54396 : return TreeEvalMaybe<std::string>(false, downfn, upfn);
969 : : }
970 : :
971 : : private:
972 : 16886389 : internal::Ops CalcOps() const {
973 [ + + + + : 16886389 : switch (fragment) {
+ + + + +
+ + + + +
+ + + + +
+ + - ]
974 : 1229162 : case Fragment::JUST_1: return {0, 0, {}};
975 : 7426645 : case Fragment::JUST_0: return {0, {}, 0};
976 : 114495 : case Fragment::PK_K: return {0, 0, 0};
977 : 51778 : case Fragment::PK_H: return {3, 0, 0};
978 : 177587 : case Fragment::OLDER:
979 : 177587 : case Fragment::AFTER: return {1, 0, {}};
980 : 66908 : case Fragment::SHA256:
981 : : case Fragment::RIPEMD160:
982 : : case Fragment::HASH256:
983 : 66908 : case Fragment::HASH160: return {4, 0, {}};
984 : 716031 : case Fragment::AND_V: return {subs[0]->ops.count + subs[1]->ops.count, subs[0]->ops.sat + subs[1]->ops.sat, {}};
985 : 82139 : case Fragment::AND_B: {
986 : 82139 : const auto count{1 + subs[0]->ops.count + subs[1]->ops.count};
987 : 82139 : const auto sat{subs[0]->ops.sat + subs[1]->ops.sat};
988 : 82139 : const auto dsat{subs[0]->ops.dsat + subs[1]->ops.dsat};
989 : 82139 : return {count, sat, dsat};
990 : : }
991 : 94337 : case Fragment::OR_B: {
992 : 94337 : const auto count{1 + subs[0]->ops.count + subs[1]->ops.count};
993 : 94337 : const auto sat{(subs[0]->ops.sat + subs[1]->ops.dsat) | (subs[1]->ops.sat + subs[0]->ops.dsat)};
994 : 94337 : const auto dsat{subs[0]->ops.dsat + subs[1]->ops.dsat};
995 : 94337 : return {count, sat, dsat};
996 : : }
997 : 81569 : case Fragment::OR_D: {
998 : 81569 : const auto count{3 + subs[0]->ops.count + subs[1]->ops.count};
999 : 81569 : const auto sat{subs[0]->ops.sat | (subs[1]->ops.sat + subs[0]->ops.dsat)};
1000 : 81569 : const auto dsat{subs[0]->ops.dsat + subs[1]->ops.dsat};
1001 : 81569 : return {count, sat, dsat};
1002 : : }
1003 : 50110 : case Fragment::OR_C: {
1004 : 50110 : const auto count{2 + subs[0]->ops.count + subs[1]->ops.count};
1005 : 50110 : const auto sat{subs[0]->ops.sat | (subs[1]->ops.sat + subs[0]->ops.dsat)};
1006 : 50110 : return {count, sat, {}};
1007 : : }
1008 : 2127315 : case Fragment::OR_I: {
1009 : 2127315 : const auto count{3 + subs[0]->ops.count + subs[1]->ops.count};
1010 : 2127315 : const auto sat{subs[0]->ops.sat | subs[1]->ops.sat};
1011 : 2127315 : const auto dsat{subs[0]->ops.dsat | subs[1]->ops.dsat};
1012 : 2127315 : return {count, sat, dsat};
1013 : : }
1014 : 126128 : case Fragment::ANDOR: {
1015 : 126128 : const auto count{3 + subs[0]->ops.count + subs[1]->ops.count + subs[2]->ops.count};
1016 : 126128 : const auto sat{(subs[1]->ops.sat + subs[0]->ops.sat) | (subs[0]->ops.dsat + subs[2]->ops.sat)};
1017 : 126128 : const auto dsat{subs[0]->ops.dsat + subs[2]->ops.dsat};
1018 : 126128 : return {count, sat, dsat};
1019 : : }
1020 [ - + ]: 42776 : case Fragment::MULTI: return {1, (uint32_t)keys.size(), (uint32_t)keys.size()};
1021 [ - + ]: 16824 : case Fragment::MULTI_A: return {(uint32_t)keys.size() + 1, 0, 0};
1022 : 2555711 : case Fragment::WRAP_S:
1023 : : case Fragment::WRAP_C:
1024 : 2555711 : case Fragment::WRAP_N: return {1 + subs[0]->ops.count, subs[0]->ops.sat, subs[0]->ops.dsat};
1025 : 700759 : case Fragment::WRAP_A: return {2 + subs[0]->ops.count, subs[0]->ops.sat, subs[0]->ops.dsat};
1026 : 290230 : case Fragment::WRAP_D: return {3 + subs[0]->ops.count, subs[0]->ops.sat, 0};
1027 : 289952 : case Fragment::WRAP_J: return {4 + subs[0]->ops.count, subs[0]->ops.sat, 0};
1028 : 481483 : case Fragment::WRAP_V: return {subs[0]->ops.count + (subs[0]->GetType() << "x"_mst), subs[0]->ops.sat, {}};
1029 : 164450 : case Fragment::THRESH: {
1030 : 164450 : uint32_t count = 0;
1031 : 164450 : auto sats = Vector(internal::MaxInt<uint32_t>(0));
1032 [ + - + + ]: 1034532 : for (const auto& sub : subs) {
1033 : 870082 : count += sub->ops.count + 1;
1034 [ + - ]: 870082 : auto next_sats = Vector(sats[0] + sub->ops.dsat);
1035 [ + - - + : 44483476 : for (size_t j = 1; j < sats.size(); ++j) next_sats.push_back((sats[j] + sub->ops.dsat) | (sats[j - 1] + sub->ops.sat));
+ + ]
1036 [ + - ]: 870082 : next_sats.push_back(sats[sats.size() - 1] + sub->ops.sat);
1037 : 870082 : sats = std::move(next_sats);
1038 : : }
1039 [ - + - + ]: 164450 : assert(k < sats.size());
1040 : 164450 : return {count, sats[k], sats[0]};
1041 : 164450 : }
1042 : : }
1043 : 0 : assert(false);
1044 : : }
1045 : :
1046 : 16886389 : internal::StackSize CalcStackSize() const {
1047 : : using namespace internal;
1048 [ + + + + : 16886389 : switch (fragment) {
+ + + + +
+ + + + +
+ + + + +
+ + - ]
1049 : 7426645 : case Fragment::JUST_0: return {{}, SatInfo::Push()};
1050 : 1229162 : case Fragment::JUST_1: return {SatInfo::Push(), {}};
1051 : 177587 : case Fragment::OLDER:
1052 : 177587 : case Fragment::AFTER: return {SatInfo::Push() + SatInfo::Nop(), {}};
1053 : 114495 : case Fragment::PK_K: return {SatInfo::Push()};
1054 : 51778 : case Fragment::PK_H: return {SatInfo::OP_DUP() + SatInfo::Hash() + SatInfo::Push() + SatInfo::OP_EQUALVERIFY()};
1055 : 66908 : case Fragment::SHA256:
1056 : : case Fragment::RIPEMD160:
1057 : : case Fragment::HASH256:
1058 : : case Fragment::HASH160: return {
1059 : : SatInfo::OP_SIZE() + SatInfo::Push() + SatInfo::OP_EQUALVERIFY() + SatInfo::Hash() + SatInfo::Push() + SatInfo::OP_EQUAL(),
1060 : : {}
1061 : 66908 : };
1062 : 126128 : case Fragment::ANDOR: {
1063 : 126128 : const auto& x{subs[0]->ss};
1064 : 126128 : const auto& y{subs[1]->ss};
1065 : 126128 : const auto& z{subs[2]->ss};
1066 : : return {
1067 : 126128 : (x.sat + SatInfo::If() + y.sat) | (x.dsat + SatInfo::If() + z.sat),
1068 : 126128 : x.dsat + SatInfo::If() + z.dsat
1069 : 126128 : };
1070 : : }
1071 : 716031 : case Fragment::AND_V: {
1072 : 716031 : const auto& x{subs[0]->ss};
1073 : 716031 : const auto& y{subs[1]->ss};
1074 : 716031 : return {x.sat + y.sat, {}};
1075 : : }
1076 : 82139 : case Fragment::AND_B: {
1077 : 82139 : const auto& x{subs[0]->ss};
1078 : 82139 : const auto& y{subs[1]->ss};
1079 : 82139 : return {x.sat + y.sat + SatInfo::BinaryOp(), x.dsat + y.dsat + SatInfo::BinaryOp()};
1080 : : }
1081 : 94337 : case Fragment::OR_B: {
1082 : 94337 : const auto& x{subs[0]->ss};
1083 : 94337 : const auto& y{subs[1]->ss};
1084 : : return {
1085 : 94337 : ((x.sat + y.dsat) | (x.dsat + y.sat)) + SatInfo::BinaryOp(),
1086 : 94337 : x.dsat + y.dsat + SatInfo::BinaryOp()
1087 : 94337 : };
1088 : : }
1089 : 50110 : case Fragment::OR_C: {
1090 : 50110 : const auto& x{subs[0]->ss};
1091 : 50110 : const auto& y{subs[1]->ss};
1092 : 50110 : return {(x.sat + SatInfo::If()) | (x.dsat + SatInfo::If() + y.sat), {}};
1093 : : }
1094 : 81569 : case Fragment::OR_D: {
1095 : 81569 : const auto& x{subs[0]->ss};
1096 : 81569 : const auto& y{subs[1]->ss};
1097 : : return {
1098 : 81569 : (x.sat + SatInfo::OP_IFDUP(true) + SatInfo::If()) | (x.dsat + SatInfo::OP_IFDUP(false) + SatInfo::If() + y.sat),
1099 : 81569 : x.dsat + SatInfo::OP_IFDUP(false) + SatInfo::If() + y.dsat
1100 : 81569 : };
1101 : : }
1102 : 2127315 : case Fragment::OR_I: {
1103 : 2127315 : const auto& x{subs[0]->ss};
1104 : 2127315 : const auto& y{subs[1]->ss};
1105 : 2127315 : return {SatInfo::If() + (x.sat | y.sat), SatInfo::If() + (x.dsat | y.dsat)};
1106 : : }
1107 : : // multi(k, key1, key2, ..., key_n) starts off with k+1 stack elements (a 0, plus k
1108 : : // signatures), then reaches n+k+3 stack elements after pushing the n keys, plus k and
1109 : : // n itself, and ends with 1 stack element (success or failure). Thus, it net removes
1110 : : // k elements (from k+1 to 1), while reaching k+n+2 more than it ends with.
1111 [ - + ]: 42776 : case Fragment::MULTI: return {SatInfo(k, k + keys.size() + 2)};
1112 : : // multi_a(k, key1, key2, ..., key_n) starts off with n stack elements (the
1113 : : // signatures), reaches 1 more (after the first key push), and ends with 1. Thus it net
1114 : : // removes n-1 elements (from n to 1) while reaching n more than it ends with.
1115 [ - + ]: 16824 : case Fragment::MULTI_A: return {SatInfo(keys.size() - 1, keys.size())};
1116 : 3021313 : case Fragment::WRAP_A:
1117 : : case Fragment::WRAP_N:
1118 : 3021313 : case Fragment::WRAP_S: return subs[0]->ss;
1119 : 235157 : case Fragment::WRAP_C: return {
1120 : 235157 : subs[0]->ss.sat + SatInfo::OP_CHECKSIG(),
1121 : 235157 : subs[0]->ss.dsat + SatInfo::OP_CHECKSIG()
1122 : 235157 : };
1123 : 290230 : case Fragment::WRAP_D: return {
1124 : 290230 : SatInfo::OP_DUP() + SatInfo::If() + subs[0]->ss.sat,
1125 : : SatInfo::OP_DUP() + SatInfo::If()
1126 : 290230 : };
1127 : 481483 : case Fragment::WRAP_V: return {subs[0]->ss.sat + SatInfo::OP_VERIFY(), {}};
1128 : 289952 : case Fragment::WRAP_J: return {
1129 : 289952 : SatInfo::OP_SIZE() + SatInfo::OP_0NOTEQUAL() + SatInfo::If() + subs[0]->ss.sat,
1130 : : SatInfo::OP_SIZE() + SatInfo::OP_0NOTEQUAL() + SatInfo::If()
1131 : 289952 : };
1132 : 164450 : case Fragment::THRESH: {
1133 : : // sats[j] is the SatInfo corresponding to all traces reaching j satisfactions.
1134 : 164450 : auto sats = Vector(SatInfo::Empty());
1135 [ - + + + ]: 1034532 : for (size_t i = 0; i < subs.size(); ++i) {
1136 : : // Loop over the subexpressions, processing them one by one. After adding
1137 : : // element i we need to add OP_ADD (if i>0).
1138 [ + + ]: 870082 : auto add = i ? SatInfo::BinaryOp() : SatInfo::Empty();
1139 : : // Construct a variable that will become the next sats, starting with index 0.
1140 [ + - ]: 870082 : auto next_sats = Vector(sats[0] + subs[i]->ss.dsat + add);
1141 : : // Then loop to construct next_sats[1..i].
1142 [ - + + + ]: 44483476 : for (size_t j = 1; j < sats.size(); ++j) {
1143 [ + - ]: 43613394 : next_sats.push_back(((sats[j] + subs[i]->ss.dsat) | (sats[j - 1] + subs[i]->ss.sat)) + add);
1144 : : }
1145 : : // Finally construct next_sats[i+1].
1146 [ + - ]: 870082 : next_sats.push_back(sats[sats.size() - 1] + subs[i]->ss.sat + add);
1147 : : // Switch over.
1148 : 870082 : sats = std::move(next_sats);
1149 : : }
1150 : : // To satisfy thresh we need k satisfactions; to dissatisfy we need 0. In both
1151 : : // cases a push of k and an OP_EQUAL follow.
1152 : : return {
1153 : 164450 : sats[k] + SatInfo::Push() + SatInfo::OP_EQUAL(),
1154 : 164450 : sats[0] + SatInfo::Push() + SatInfo::OP_EQUAL()
1155 : 164450 : };
1156 : 164450 : }
1157 : : }
1158 : 0 : assert(false);
1159 : : }
1160 : :
1161 : 16886389 : internal::WitnessSize CalcWitnessSize() const {
1162 [ + + ]: 16886389 : const uint32_t sig_size = IsTapscript(m_script_ctx) ? 1 + 65 : 1 + 72;
1163 [ + + ]: 16886389 : const uint32_t pubkey_size = IsTapscript(m_script_ctx) ? 1 + 32 : 1 + 33;
1164 [ + + + + : 16886389 : switch (fragment) {
+ + + + +
+ + + + +
+ + + + +
- ]
1165 : 7426645 : case Fragment::JUST_0: return {{}, 0};
1166 : 1406749 : case Fragment::JUST_1:
1167 : : case Fragment::OLDER:
1168 : 1406749 : case Fragment::AFTER: return {0, {}};
1169 : 114495 : case Fragment::PK_K: return {sig_size, 1};
1170 : 51778 : case Fragment::PK_H: return {sig_size + pubkey_size, 1 + pubkey_size};
1171 : 66908 : case Fragment::SHA256:
1172 : : case Fragment::RIPEMD160:
1173 : : case Fragment::HASH256:
1174 : 66908 : case Fragment::HASH160: return {1 + 32, {}};
1175 : 126128 : case Fragment::ANDOR: {
1176 : 126128 : const auto sat{(subs[0]->ws.sat + subs[1]->ws.sat) | (subs[0]->ws.dsat + subs[2]->ws.sat)};
1177 : 126128 : const auto dsat{subs[0]->ws.dsat + subs[2]->ws.dsat};
1178 : 126128 : return {sat, dsat};
1179 : : }
1180 : 716031 : case Fragment::AND_V: return {subs[0]->ws.sat + subs[1]->ws.sat, {}};
1181 : 82139 : case Fragment::AND_B: return {subs[0]->ws.sat + subs[1]->ws.sat, subs[0]->ws.dsat + subs[1]->ws.dsat};
1182 : 94337 : case Fragment::OR_B: {
1183 : 94337 : const auto sat{(subs[0]->ws.dsat + subs[1]->ws.sat) | (subs[0]->ws.sat + subs[1]->ws.dsat)};
1184 : 94337 : const auto dsat{subs[0]->ws.dsat + subs[1]->ws.dsat};
1185 : 94337 : return {sat, dsat};
1186 : : }
1187 : 50110 : case Fragment::OR_C: return {subs[0]->ws.sat | (subs[0]->ws.dsat + subs[1]->ws.sat), {}};
1188 : 81569 : 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};
1189 : 2127315 : 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)};
1190 : 42776 : case Fragment::MULTI: return {k * sig_size + 1, k + 1};
1191 [ - + ]: 16824 : case Fragment::MULTI_A: return {k * sig_size + static_cast<uint32_t>(keys.size()) - k, static_cast<uint32_t>(keys.size())};
1192 : 3256470 : case Fragment::WRAP_A:
1193 : : case Fragment::WRAP_N:
1194 : : case Fragment::WRAP_S:
1195 : 3256470 : case Fragment::WRAP_C: return subs[0]->ws;
1196 : 290230 : case Fragment::WRAP_D: return {1 + 1 + subs[0]->ws.sat, 1};
1197 : 481483 : case Fragment::WRAP_V: return {subs[0]->ws.sat, {}};
1198 : 289952 : case Fragment::WRAP_J: return {subs[0]->ws.sat, 1};
1199 : 164450 : case Fragment::THRESH: {
1200 : 164450 : auto sats = Vector(internal::MaxInt<uint32_t>(0));
1201 [ + - + + ]: 1034532 : for (const auto& sub : subs) {
1202 [ + - ]: 870082 : auto next_sats = Vector(sats[0] + sub->ws.dsat);
1203 [ + - - + : 44483476 : for (size_t j = 1; j < sats.size(); ++j) next_sats.push_back((sats[j] + sub->ws.dsat) | (sats[j - 1] + sub->ws.sat));
+ + ]
1204 [ + - ]: 870082 : next_sats.push_back(sats[sats.size() - 1] + sub->ws.sat);
1205 : 870082 : sats = std::move(next_sats);
1206 : : }
1207 [ - + - + ]: 164450 : assert(k < sats.size());
1208 : 164450 : return {sats[k], sats[0]};
1209 : 164450 : }
1210 : : }
1211 : 0 : assert(false);
1212 : : }
1213 : :
1214 : : template<typename Ctx>
1215 : 10267 : internal::InputResult ProduceInput(const Ctx& ctx) const {
1216 : : using namespace internal;
1217 : :
1218 : : // Internal function which is invoked for every tree node, constructing satisfaction/dissatisfactions
1219 : : // given those of its subnodes.
1220 : 761374 : auto helper = [&ctx](const Node& node, std::span<InputResult> subres) -> InputResult {
1221 [ - - - - : 751107 : switch (node.fragment) {
- - - - -
- - - - -
- - - - -
- - - + -
- - - - -
+ + + - -
- - + + +
- - - + +
- - + + +
- ][ + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ - ]
1222 : 34986 : case Fragment::PK_K: {
1223 : 34986 : std::vector<unsigned char> sig;
1224 [ # # # # : 34986 : Availability avail = ctx.Sign(node.keys[0], sig);
# # # # ]
[ + - + - ]
1225 [ # # # # : 69972 : return {ZERO, InputStack(std::move(sig)).SetWithSig().SetAvailable(avail)};
# # # # #
# # # # #
# # ][ + -
+ - + - +
- ]
1226 : 34986 : }
1227 : 19128 : case Fragment::PK_H: {
1228 : 19128 : std::vector<unsigned char> key = ctx.ToPKBytes(node.keys[0]), sig;
1229 [ # # # # ]: 19128 : Availability avail = ctx.Sign(node.keys[0], sig);
[ + - ]
1230 [ # # # # : 38256 : return {ZERO + InputStack(key), (InputStack(std::move(sig)).SetWithSig() + InputStack(key)).SetAvailable(avail)};
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # ]
[ + - + -
+ - + - +
- + - + -
+ - + - +
- + - +
- ]
1231 : 19128 : }
1232 : 5288 : case Fragment::MULTI_A: {
1233 : : // sats[j] represents the best stack containing j valid signatures (out of the first i keys).
1234 : : // In the loop below, these stacks are built up using a dynamic programming approach.
1235 : 5288 : std::vector<InputStack> sats = Vector(EMPTY);
1236 [ # # # # : 62080 : for (size_t i = 0; i < node.keys.size(); ++i) {
# # # # ]
[ - + + + ]
1237 : : // Get the signature for the i'th key in reverse order (the signature for the first key needs to
1238 : : // be at the top of the stack, contrary to CHECKMULTISIG's satisfaction).
1239 : 56792 : std::vector<unsigned char> sig;
1240 [ # # # # : 56792 : Availability avail = ctx.Sign(node.keys[node.keys.size() - 1 - i], sig);
# # # # #
# # # ][ -
+ + - +
- ]
1241 : : // Compute signature stack for just this key.
1242 [ # # # # : 113584 : auto sat = InputStack(std::move(sig)).SetWithSig().SetAvailable(avail);
# # # # #
# # # # #
# # ][ + -
+ - + - +
- ]
1243 : : // Compute the next sats vector: next_sats[0] is a copy of sats[0] (no signatures). All further
1244 : : // next_sats[j] are equal to either the existing sats[j] + ZERO, or sats[j-1] plus a signature
1245 : : // for the current (i'th) key. The very last element needs all signatures filled.
1246 : 56792 : std::vector<InputStack> next_sats;
1247 [ # # # # : 113584 : next_sats.push_back(sats[0] + ZERO);
# # # # #
# # # ][ +
- + - +
- ]
1248 [ # # # # : 1987624 : for (size_t j = 1; j < sats.size(); ++j) next_sats.push_back((sats[j] + ZERO) | (std::move(sats[j - 1]) + sat));
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ][ +
- + - + -
+ - + - +
- - + +
+ ]
1249 [ # # # # : 113584 : next_sats.push_back(std::move(sats[sats.size() - 1]) + std::move(sat));
# # # # ]
[ - + + - ]
1250 : : // Switch over.
1251 : 56792 : sats = std::move(next_sats);
1252 : : }
1253 : : // The dissatisfaction consists of as many empty vectors as there are keys, which is the same as
1254 : : // satisfying 0 keys.
1255 : 5288 : auto& nsat{sats[0]};
1256 [ # # # # ]: 5288 : CHECK_NONFATAL(node.k != 0);
[ + - ]
1257 [ # # # # : 5288 : assert(node.k < sats.size());
# # # # ]
[ - + - + ]
1258 : 5288 : return {std::move(nsat), std::move(sats[node.k])};
1259 : 5288 : }
1260 : 19532 : case Fragment::MULTI: {
1261 : : // sats[j] represents the best stack containing j valid signatures (out of the first i keys).
1262 : : // In the loop below, these stacks are built up using a dynamic programming approach.
1263 : : // sats[0] starts off being {0}, due to the CHECKMULTISIG bug that pops off one element too many.
1264 : 19532 : std::vector<InputStack> sats = Vector(ZERO);
1265 [ # # # # : 108662 : for (size_t i = 0; i < node.keys.size(); ++i) {
# # # # ]
[ - + + + ]
1266 : 89130 : std::vector<unsigned char> sig;
1267 [ # # # # : 89130 : Availability avail = ctx.Sign(node.keys[i], sig);
# # # # ]
[ + - + - ]
1268 : : // Compute signature stack for just the i'th key.
1269 [ # # # # : 178260 : auto sat = InputStack(std::move(sig)).SetWithSig().SetAvailable(avail);
# # # # #
# # # # #
# # ][ + -
+ - + - +
- ]
1270 : : // Compute the next sats vector: next_sats[0] is a copy of sats[0] (no signatures). All further
1271 : : // next_sats[j] are equal to either the existing sats[j], or sats[j-1] plus a signature for the
1272 : : // current (i'th) key. The very last element needs all signatures filled.
1273 [ # # # # ]: 89130 : std::vector<InputStack> next_sats;
[ + - ]
1274 [ # # # # ]: 89130 : next_sats.push_back(sats[0]);
[ + - ]
1275 [ # # # # : 530726 : for (size_t j = 1; j < sats.size(); ++j) next_sats.push_back(sats[j] | (std::move(sats[j - 1]) + sat));
# # # # #
# # # # #
# # # # #
# # # #
# ][ + - +
- + - + -
- + + + ]
1276 [ # # # # : 178260 : next_sats.push_back(std::move(sats[sats.size() - 1]) + std::move(sat));
# # # # ]
[ - + + - ]
1277 : : // Switch over.
1278 : 89130 : sats = std::move(next_sats);
1279 : : }
1280 : : // The dissatisfaction consists of k+1 stack elements all equal to 0.
1281 [ # # # # ]: 19532 : InputStack nsat = ZERO;
[ + - ]
1282 [ # # # # : 83242 : for (size_t i = 0; i < node.k; ++i) nsat = std::move(nsat) + ZERO;
# # # # #
# # # ][ +
- + - +
+ ]
1283 [ # # # # : 19532 : assert(node.k < sats.size());
# # # # ]
[ - + - + ]
1284 : 39064 : return {std::move(nsat), std::move(sats[node.k])};
1285 : 19532 : }
1286 : 24427 : case Fragment::THRESH: {
1287 : : // sats[k] represents the best stack that satisfies k out of the *last* i subexpressions.
1288 : : // In the loop below, these stacks are built up using a dynamic programming approach.
1289 : : // sats[0] starts off empty.
1290 : 24427 : std::vector<InputStack> sats = Vector(EMPTY);
1291 [ - - + + ]: 81894 : for (size_t i = 0; i < subres.size(); ++i) {
[ + + ]
1292 : : // Introduce an alias for the i'th last satisfaction/dissatisfaction.
1293 [ - - + - ]: 57467 : auto& res = subres[subres.size() - i - 1];
[ + - ]
1294 : : // Compute the next sats vector: next_sats[0] is sats[0] plus res.nsat (thus containing all dissatisfactions
1295 : : // so far. next_sats[j] is either sats[j] + res.nsat (reusing j earlier satisfactions) or sats[j-1] + res.sat
1296 : : // (reusing j-1 earlier satisfactions plus a new one). The very last next_sats[j] is all satisfactions.
1297 : 57467 : std::vector<InputStack> next_sats;
1298 [ - - - - : 114934 : next_sats.push_back(sats[0] + res.nsat);
- - + - +
- + - ][ +
- + - +
- ]
1299 [ - - - - : 520201 : for (size_t j = 1; j < sats.size(); ++j) next_sats.push_back((sats[j] + res.nsat) | (std::move(sats[j - 1]) + res.sat));
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
+ - + ][ +
- + - + -
+ - + - +
- - + +
+ ]
1300 [ - - - - : 114934 : next_sats.push_back(std::move(sats[sats.size() - 1]) + std::move(res.sat));
- + + - ]
[ - + + - ]
1301 : : // Switch over.
1302 : 57467 : sats = std::move(next_sats);
1303 : : }
1304 : : // At this point, sats[k].sat is the best satisfaction for the overall thresh() node. The best dissatisfaction
1305 : : // is computed by gathering all sats[i].nsat for i != k.
1306 [ - - + - ]: 24427 : InputStack nsat = INVALID;
[ + - ]
1307 [ - - - - : 106321 : for (size_t i = 0; i < sats.size(); ++i) {
- + + + ]
[ - + + + ]
1308 : : // i==k is the satisfaction; i==0 is the canonical dissatisfaction;
1309 : : // the rest are non-canonical (a no-signature dissatisfaction - the i=0
1310 : : // form - is always available) and malleable (due to overcompleteness).
1311 : : // Marking the solutions malleable here is not strictly necessary, as they
1312 : : // should already never be picked in non-malleable solutions due to the
1313 : : // availability of the i=0 form.
1314 [ - - - - : 81894 : if (i != 0 && i != node.k) sats[i].SetMalleable().SetNonCanon();
- - - - +
+ - + - -
- - ][ + +
+ + + - +
- ]
1315 : : // Include all dissatisfactions (even these non-canonical ones) in nsat.
1316 [ - - - - : 81894 : if (i != node.k) nsat = std::move(nsat) | std::move(sats[i]);
+ + + - ]
[ + + + - ]
1317 : : }
1318 [ - - - + ]: 24427 : assert(node.k < sats.size());
[ - + ]
1319 : 48854 : return {std::move(nsat), std::move(sats[node.k])};
1320 : 24427 : }
1321 : 11308 : case Fragment::OLDER: {
1322 [ - - + + ]: 16122 : return {INVALID, ctx.CheckOlder(node.k) ? EMPTY : INVALID};
[ + + ]
1323 : : }
1324 : 10124 : case Fragment::AFTER: {
1325 [ - - + + ]: 14598 : return {INVALID, ctx.CheckAfter(node.k) ? EMPTY : INVALID};
[ + + ]
1326 : : }
1327 : 7982 : case Fragment::SHA256: {
1328 : 7982 : std::vector<unsigned char> preimage;
1329 [ # # # # : 7982 : Availability avail = ctx.SatSHA256(node.data, preimage);
# # # # ]
[ + - + - ]
1330 [ # # # # : 15964 : return {ZERO32, InputStack(std::move(preimage)).SetAvailable(avail)};
# # # # #
# # # ][ +
- + - +
- ]
1331 : 7982 : }
1332 : 8370 : case Fragment::RIPEMD160: {
1333 : 8370 : std::vector<unsigned char> preimage;
1334 [ # # # # : 8370 : Availability avail = ctx.SatRIPEMD160(node.data, preimage);
# # # # ]
[ + - + - ]
1335 [ # # # # : 16740 : return {ZERO32, InputStack(std::move(preimage)).SetAvailable(avail)};
# # # # #
# # # ][ +
- + - +
- ]
1336 : 8370 : }
1337 : 9110 : case Fragment::HASH256: {
1338 : 9110 : std::vector<unsigned char> preimage;
1339 [ # # # # : 9110 : Availability avail = ctx.SatHASH256(node.data, preimage);
# # # # ]
[ + - + - ]
1340 [ # # # # : 18220 : return {ZERO32, InputStack(std::move(preimage)).SetAvailable(avail)};
# # # # #
# # # ][ +
- + - +
- ]
1341 : 9110 : }
1342 : 8130 : case Fragment::HASH160: {
1343 : 8130 : std::vector<unsigned char> preimage;
1344 [ # # # # : 8130 : Availability avail = ctx.SatHASH160(node.data, preimage);
# # # # ]
[ + - + - ]
1345 [ # # # # : 16260 : return {ZERO32, InputStack(std::move(preimage)).SetAvailable(avail)};
# # # # #
# # # ][ +
- + - +
- ]
1346 : 8130 : }
1347 : 70677 : case Fragment::AND_V: {
1348 : 70677 : auto& x = subres[0], &y = subres[1];
1349 : : // As the dissatisfaction here only consist of a single option, it doesn't
1350 : : // actually need to be listed (it's not required for reasoning about malleability of
1351 : : // other options), and is never required (no valid miniscript relies on the ability
1352 : : // to satisfy the type V left subexpression). It's still listed here for
1353 : : // completeness, as a hypothetical (not currently implemented) satisfier that doesn't
1354 : : // care about malleability might in some cases prefer it still.
1355 [ - - - - : 141354 : return {(y.nsat + x.sat).SetNonCanon(), y.sat + x.sat};
- - - - -
- - - + -
+ - + - +
- + - +
- ][ + - +
- + - + -
+ - + - ]
1356 : : }
1357 : 19349 : case Fragment::AND_B: {
1358 : 19349 : auto& x = subres[0], &y = subres[1];
1359 : : // Note that it is not strictly necessary to mark the 2nd and 3rd dissatisfaction here
1360 : : // as malleable. While they are definitely malleable, they are also non-canonical due
1361 : : // to the guaranteed existence of a no-signature other dissatisfaction (the 1st)
1362 : : // option. Because of that, the 2nd and 3rd option will never be chosen, even if they
1363 : : // weren't marked as malleable.
1364 [ - - - - : 38698 : return {(y.nsat + x.nsat) | (y.sat + x.nsat).SetMalleable().SetNonCanon() | (y.nsat + x.sat).SetMalleable().SetNonCanon(), y.sat + x.sat};
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - ][ + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- ]
1365 : : }
1366 : 15377 : case Fragment::OR_B: {
1367 : 15377 : auto& x = subres[0], &z = subres[1];
1368 : : // The (sat(Z) sat(X)) solution is overcomplete (attacker can change either into dsat).
1369 [ - - - - : 30754 : return {z.nsat + x.nsat, (z.nsat + x.sat) | (z.sat + x.nsat) | (z.sat + x.sat).SetMalleable().SetNonCanon()};
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - +
- ][ + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - ]
1370 : : }
1371 : 10378 : case Fragment::OR_C: {
1372 : 10378 : auto& x = subres[0], &z = subres[1];
1373 [ # # # # : 20756 : return {INVALID, std::move(x.sat) | (z.sat + x.nsat)};
# # # # #
# # # ][ +
- + - +
- ]
1374 : : }
1375 : 22560 : case Fragment::OR_D: {
1376 : 22560 : auto& x = subres[0], &z = subres[1];
1377 [ # # # # : 45120 : return {z.nsat + x.nsat, std::move(x.sat) | (z.sat + x.nsat)};
# # # # #
# # # # #
# # # # #
# # # #
# ][ + - +
- + - + -
+ - + - ]
1378 : : }
1379 : 44950 : case Fragment::OR_I: {
1380 : 44950 : auto& x = subres[0], &z = subres[1];
1381 [ # # # # : 89900 : return {(x.nsat + ONE) | (z.nsat + ZERO), (x.sat + ONE) | (z.sat + ZERO)};
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ][ +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - +
- ]
1382 : : }
1383 : 33506 : case Fragment::ANDOR: {
1384 : 33506 : auto& x = subres[0], &y = subres[1], &z = subres[2];
1385 [ - - - - : 67012 : return {(y.nsat + x.sat).SetNonCanon() | (z.nsat + x.nsat), (y.sat + x.sat) | (z.sat + x.nsat)};
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- ][ + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - ]
1386 : : }
1387 : 130944 : case Fragment::WRAP_A:
1388 : : case Fragment::WRAP_S:
1389 : : case Fragment::WRAP_C:
1390 : : case Fragment::WRAP_N:
1391 : 130944 : return std::move(subres[0]);
1392 : 3046 : case Fragment::WRAP_D: {
1393 : 3046 : auto &x = subres[0];
1394 [ # # # # : 6092 : return {ZERO, x.sat + ONE};
# # # # ]
[ + - + - ]
1395 : : }
1396 : 6386 : case Fragment::WRAP_J: {
1397 : 6386 : auto &x = subres[0];
1398 : : // If a dissatisfaction with a nonzero top stack element exists, an alternative dissatisfaction exists.
1399 : : // As the dissatisfaction logic currently doesn't keep track of this nonzeroness property, and thus even
1400 : : // if a dissatisfaction with a top zero element is found, we don't know whether another one with a
1401 : : // nonzero top stack element exists. Make the conservative assumption that whenever the subexpression is weakly
1402 : : // dissatisfiable, this alternative dissatisfaction exists and leads to malleability.
1403 [ # # # # : 13856 : return {InputStack(ZERO).SetMalleable(x.nsat.available != Availability::NO && !x.nsat.has_sig), std::move(x.sat)};
# # # # #
# # # # #
# # ][ + +
+ + + - +
- ]
1404 : : }
1405 : 75897 : case Fragment::WRAP_V: {
1406 : 75897 : auto &x = subres[0];
1407 : 75897 : return {INVALID, std::move(x.sat)};
1408 : : }
1409 : 126416 : case Fragment::JUST_0: return {EMPTY, INVALID};
1410 : 33236 : case Fragment::JUST_1: return {INVALID, EMPTY};
1411 : : }
1412 : 0 : assert(false);
1413 : : return {INVALID, INVALID};
1414 : : };
1415 : :
1416 : 761374 : auto tester = [&helper](const Node& node, std::span<InputResult> subres) -> InputResult {
1417 : 751107 : auto ret = helper(node, subres);
1418 : :
1419 : : // Do a consistency check between the satisfaction code and the type checker
1420 : : // (the actual satisfaction code in ProduceInputHelper does not use GetType)
1421 : :
1422 : : // For 'z' nodes, available satisfactions/dissatisfactions must have stack size 0.
1423 [ + - - + : 271009 : if (node.GetType() << "z"_mst && ret.nsat.available != Availability::NO) CHECK_NONFATAL(ret.nsat.stack.size() == 0);
+ - + + -
+ + - ][ +
+ - + +
- ]
1424 [ - + - - : 271009 : if (node.GetType() << "z"_mst && ret.sat.available != Availability::NO) CHECK_NONFATAL(ret.sat.stack.size() == 0);
- - + + -
+ + - ][ +
+ - + +
- ]
1425 : :
1426 : : // For 'o' nodes, available satisfactions/dissatisfactions must have stack size 1.
1427 [ # # # # : 141954 : if (node.GetType() << "o"_mst && ret.nsat.available != Availability::NO) CHECK_NONFATAL(ret.nsat.stack.size() == 1);
# # # # #
# # # ][ +
+ - + +
- ]
1428 [ # # # # : 141954 : if (node.GetType() << "o"_mst && ret.sat.available != Availability::NO) CHECK_NONFATAL(ret.sat.stack.size() == 1);
# # # # #
# # # ][ +
+ - + +
- ]
1429 : :
1430 : : // For 'n' nodes, available satisfactions/dissatisfactions must have stack size 1 or larger. For satisfactions,
1431 : : // the top element cannot be 0.
1432 [ # # # # : 225488 : if (node.GetType() << "n"_mst && ret.sat.available != Availability::NO) CHECK_NONFATAL(ret.sat.stack.size() >= 1);
# # # # #
# # # ][ +
+ - + +
- ]
1433 [ # # # # : 225488 : if (node.GetType() << "n"_mst && ret.nsat.available != Availability::NO) CHECK_NONFATAL(ret.nsat.stack.size() >= 1);
# # # # #
# # # ][ +
+ - + +
- ]
1434 [ # # # # : 225488 : if (node.GetType() << "n"_mst && ret.sat.available != Availability::NO) CHECK_NONFATAL(!ret.sat.stack.back().empty());
# # # # ]
[ + + + - ]
1435 : :
1436 : : // For 'd' nodes, a dissatisfaction must exist, and they must not need a signature. If it is non-malleable,
1437 : : // it must be canonical.
1438 [ + - + - ]: 496069 : if (node.GetType() << "d"_mst) CHECK_NONFATAL(ret.nsat.available != Availability::NO);
[ + - ]
1439 [ + - + - ]: 496069 : if (node.GetType() << "d"_mst) CHECK_NONFATAL(!ret.nsat.has_sig);
[ + - ]
1440 [ + - + - : 496069 : if (node.GetType() << "d"_mst && !ret.nsat.malleable) CHECK_NONFATAL(!ret.nsat.non_canon);
+ - + - ]
[ + + + - ]
1441 : :
1442 : : // For 'f'/'s' nodes, dissatisfactions/satisfactions must have a signature.
1443 [ - - - - : 236522 : if (node.GetType() << "f"_mst && ret.nsat.available != Availability::NO) CHECK_NONFATAL(ret.nsat.has_sig);
- + - - ]
[ + + + - ]
1444 [ - + - - : 502971 : if (node.GetType() << "s"_mst && ret.sat.available != Availability::NO) CHECK_NONFATAL(ret.sat.has_sig);
- + - - ]
[ + + + - ]
1445 : :
1446 : : // For non-malleable 'e' nodes, a non-malleable dissatisfaction must exist.
1447 [ + - + - ]: 348661 : if (node.GetType() << "me"_mst) CHECK_NONFATAL(ret.nsat.available != Availability::NO);
[ + - ]
1448 [ + - + - ]: 348661 : if (node.GetType() << "me"_mst) CHECK_NONFATAL(!ret.nsat.malleable);
[ + - ]
1449 : :
1450 : : // For 'm' nodes, if a satisfaction exists, it must be non-malleable.
1451 [ - + - - : 650393 : if (node.GetType() << "m"_mst && ret.sat.available != Availability::NO) CHECK_NONFATAL(!ret.sat.malleable);
+ + + - ]
[ + + + - ]
1452 : :
1453 : : // If a non-malleable satisfaction exists, it must be canonical.
1454 [ - + - - : 751107 : if (ret.sat.available != Availability::NO && !ret.sat.malleable) CHECK_NONFATAL(!ret.sat.non_canon);
- - + + +
- + - ][ +
+ + + +
- ]
1455 : :
1456 : 751107 : return ret;
1457 : 0 : };
1458 : :
1459 : 10267 : return TreeEval<InputResult>(tester);
1460 : : }
1461 : :
1462 : : public:
1463 : : /** Update duplicate key information in this Node.
1464 : : *
1465 : : * This uses a custom key comparator provided by the context in order to still detect duplicates
1466 : : * for more complicated types.
1467 : : */
1468 : 45561 : template<typename Ctx> void DuplicateKeyCheck(const Ctx& ctx) const
1469 : : {
1470 : : // We cannot use a lambda here, as lambdas are non assignable, and the set operations
1471 : : // below require moving the comparators around.
1472 : : struct Comp {
1473 : : const Ctx* ctx_ptr;
1474 : 5938055 : Comp(const Ctx& ctx) : ctx_ptr(&ctx) {}
1475 [ - - - - : 1448977 : bool operator()(const Key& a, const Key& b) const { return ctx_ptr->KeyCompare(a, b); }
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- + + + +
+ + ][ + +
+ + - - -
- - - - -
+ + + + -
- - - - -
- - + + +
+ + + + +
+ + - - -
- - - - -
+ + + + +
+ + + + +
+ + ]
1476 : : };
1477 : :
1478 : : // state in the recursive computation:
1479 : : // - std::nullopt means "this node has duplicates"
1480 : : // - an std::set means "this node has no duplicate keys, and they are: ...".
1481 : : using keyset = std::set<Key, Comp>;
1482 : : using state = std::optional<keyset>;
1483 : :
1484 : 6201842 : auto upfn = [&ctx](const Node& node, std::span<state> subs) -> state {
1485 : : // If this node is already known to have duplicates, nothing left to do.
1486 [ - + - - ]: 6156281 : if (node.has_duplicate_keys.has_value() && *node.has_duplicate_keys) return {};
[ - + - -
- + - - ]
[ - + - -
- + - - -
+ - - ]
1487 : :
1488 : : // Check if one of the children is already known to have duplicates.
1489 [ + + + + ]: 11915024 : for (auto& sub : subs) {
[ - + + +
- + + + ]
[ + + + +
+ + + + +
+ + + ]
1490 [ + + ]: 5976969 : if (!sub.has_value()) {
[ - + - + ]
[ + + + +
+ + ]
1491 : 218226 : node.has_duplicate_keys = true;
1492 : 218226 : return {};
1493 : : }
1494 : : }
1495 : :
1496 : : // Start building the set of keys involved in this node and children.
1497 : : // Start by keys in this node directly.
1498 [ - + ]: 5938055 : size_t keys_count = node.keys.size();
[ - + - + ]
[ - + - +
- + ]
1499 : 5938055 : keyset key_set{node.keys.begin(), node.keys.end(), Comp(ctx)};
1500 [ + + ]: 5938055 : if (key_set.size() != keys_count) {
[ - + - + ]
[ + + + +
+ + ]
1501 : : // It already has duplicates; bail out.
1502 : 16140 : node.has_duplicate_keys = true;
1503 : 16140 : return {};
1504 : : }
1505 : :
1506 : : // Merge the keys from the children into this set.
1507 [ + + + + ]: 11565676 : for (auto& sub : subs) {
[ - + + +
+ + + + ]
[ + + + +
+ + + + +
+ + + ]
1508 [ + + ]: 5654124 : keys_count += sub->size();
[ - + + + ]
[ + + + +
+ + ]
1509 : : // Small optimization: std::set::merge is linear in the size of the second arg but
1510 : : // logarithmic in the size of the first.
1511 [ + + ]: 5654124 : if (key_set.size() < sub->size()) std::swap(key_set, *sub);
[ - + + + ]
[ + + + +
+ + ]
1512 [ + + ]: 5654124 : key_set.merge(*sub);
[ - + + + ]
[ + + + +
+ + ]
1513 [ + + ]: 5654124 : if (key_set.size() != keys_count) {
[ - + + + ]
[ + + + +
+ + ]
1514 : 10363 : node.has_duplicate_keys = true;
1515 : 10363 : return {};
1516 : : }
1517 : : }
1518 : :
1519 : 5911552 : node.has_duplicate_keys = false;
1520 : 5911552 : return key_set;
1521 : 5938055 : };
1522 : :
1523 : 45561 : TreeEval<state>(upfn);
1524 : 45561 : }
1525 : :
1526 : : //! Return the size of the script for this expression (faster than ToScript().size()).
1527 [ - + ][ - + : 11904273 : size_t ScriptSize() const { return scriptlen; }
- + - + +
+ + + ]
1528 : :
1529 : : //! Return the maximum number of ops needed to satisfy this script non-malleably.
1530 : 539395 : std::optional<uint32_t> GetOps() const {
1531 [ + + ]: 539395 : if (!ops.sat.valid) return {};
1532 : 250513 : return ops.count + ops.sat.value;
1533 : : }
1534 : :
1535 : : //! Return the number of ops in the script (not counting the dynamic ones that depend on execution).
1536 [ - + - + ]: 5511 : uint32_t GetStaticOps() const { return ops.count; }
1537 : :
1538 : : //! Check the ops limit of this script against the consensus limit.
1539 : 1330166 : bool CheckOpsLimit() const {
1540 [ + + ]: 1330166 : if (IsTapscript(m_script_ctx)) return true;
1541 [ + + ]: 538553 : if (const auto ops = GetOps()) return *ops <= MAX_OPS_PER_SCRIPT;
1542 : : return true;
1543 : : }
1544 : :
1545 : : /** Whether this node is of type B, K or W. (That is, anything but V.) */
1546 : 639939 : bool IsBKW() const {
1547 : 639939 : return !((GetType() & "BKW"_mst) == ""_mst);
1548 : : }
1549 : :
1550 : : /** Return the maximum number of stack elements needed to satisfy this script non-malleably. */
1551 : 555341 : std::optional<uint32_t> GetStackSize() const {
1552 [ + + ]: 555341 : if (!ss.sat.valid) return {};
1553 : 266303 : return ss.sat.netdiff + static_cast<int32_t>(IsBKW());
1554 : : }
1555 : :
1556 : : //! Return the maximum size of the stack during execution of this script.
1557 : 792455 : std::optional<uint32_t> GetExecStackSize() const {
1558 [ + + ]: 792455 : if (!ss.sat.valid) return {};
1559 : 373636 : return ss.sat.exec + static_cast<int32_t>(IsBKW());
1560 : : }
1561 : :
1562 : : //! Check the maximum stack size for this script against the policy limit.
1563 : 1329340 : bool CheckStackSize() const {
1564 : : // Since in Tapscript there is no standardness limit on the script and witness sizes, we may run
1565 : : // into the maximum stack size while executing the script. Make sure it doesn't happen.
1566 [ + + ]: 1329340 : if (IsTapscript(m_script_ctx)) {
1567 [ + + ]: 791613 : if (const auto exec_ss = GetExecStackSize()) return exec_ss <= MAX_STACK_SIZE;
1568 : : return true;
1569 : : }
1570 [ + + ]: 537727 : if (const auto ss = GetStackSize()) return *ss <= MAX_STANDARD_P2WSH_STACK_ITEMS;
1571 : : return true;
1572 : : }
1573 : :
1574 : : //! Whether no satisfaction exists for this node.
1575 [ + + ]: 12570 : bool IsNotSatisfiable() const { return !GetStackSize(); }
1576 : :
1577 : : /** Return the maximum size in bytes of a witness to satisfy this script non-malleably. Note this does
1578 : : * not include the witness script push. */
1579 : 8688 : std::optional<uint32_t> GetWitnessSize() const {
1580 [ - + ]: 8688 : if (!ws.sat.valid) return {};
1581 : 8688 : return ws.sat.value;
1582 : : }
1583 : :
1584 : : //! Return the expression type.
1585 [ + - + + ]: 26597187 : Type GetType() const { return typ; }
[ - - + -
+ - + - -
+ - + - +
- + - + +
- + - + -
- + + - +
- + - + -
+ + + + -
+ - + - +
- + - + +
+ + + + +
+ + + + +
+ + + +
- ][ + - +
- + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + - +
- + + + +
+ - + + +
+ + + + +
+ - + ]
1586 : :
1587 : : //! Return the script context for this node.
1588 : 35985 : MiniscriptContext GetMsCtx() const { return m_script_ctx; }
1589 : :
1590 : : //! Find an insane subnode which has no insane children. Nullptr if there is none.
1591 : 3033 : const Node* FindInsaneSub() const {
1592 [ + - ]: 3033 : return TreeEval<const Node*>([](const Node& node, std::span<const Node*> subs) -> const Node* {
1593 [ + + + + ]: 3130565 : for (auto& sub: subs) if (sub) return sub;
1594 [ + + ]: 1354157 : if (!node.IsSaneSubexpression()) return &node;
1595 : : return nullptr;
1596 : : });
1597 : : }
1598 : :
1599 : : //! Determine whether a Miniscript node is satisfiable. fn(node) will be invoked for all
1600 : : //! key, time, and hashing nodes, and should return their satisfiability.
1601 : : template<typename F>
1602 : 5018 : bool IsSatisfiable(F fn) const
1603 : : {
1604 : : // TreeEval() doesn't support bool as NodeType, so use int instead.
1605 [ + - ]: 5018 : return TreeEval<int>([&fn](const Node& node, std::span<int> subs) -> bool {
1606 [ + + + + : 371690 : switch (node.fragment) {
+ + + + ]
1607 : : case Fragment::JUST_0:
1608 : : return false;
1609 : 16527 : case Fragment::JUST_1:
1610 : 16527 : return true;
1611 : 66897 : case Fragment::PK_K:
1612 : : case Fragment::PK_H:
1613 : : case Fragment::MULTI:
1614 : : case Fragment::MULTI_A:
1615 : : case Fragment::AFTER:
1616 : : case Fragment::OLDER:
1617 : : case Fragment::HASH256:
1618 : : case Fragment::HASH160:
1619 : : case Fragment::SHA256:
1620 : : case Fragment::RIPEMD160:
1621 : 66897 : return bool{fn(node)};
1622 [ + + ]: 16709 : case Fragment::ANDOR:
1623 [ + + + + : 16709 : return (subs[0] && subs[1]) || subs[2];
+ + ]
1624 [ + + ]: 44010 : case Fragment::AND_V:
1625 : : case Fragment::AND_B:
1626 [ + + + + ]: 44010 : return subs[0] && subs[1];
1627 [ + + ]: 46622 : case Fragment::OR_B:
1628 : : case Fragment::OR_C:
1629 : : case Fragment::OR_D:
1630 : : case Fragment::OR_I:
1631 [ + + + + ]: 46622 : return subs[0] || subs[1];
1632 : 12171 : case Fragment::THRESH:
1633 : 12171 : return static_cast<uint32_t>(std::count(subs.begin(), subs.end(), true)) >= node.k;
1634 [ - + ]: 106590 : default: // wrappers
1635 [ - + ]: 106590 : assert(subs.size() >= 1);
1636 : 106590 : CHECK_NONFATAL(subs.size() == 1);
1637 : 106590 : return subs[0];
1638 : : }
1639 [ - + ]: 5018 : });
1640 : : }
1641 : :
1642 : : //! Check whether this node is valid at all.
1643 : 22038830 : bool IsValid() const {
1644 [ + + ]: 22038830 : if (GetType() == ""_mst) return false;
1645 : 43954442 : return ScriptSize() <= internal::MaxScriptSize(m_script_ctx);
1646 : : }
1647 : :
1648 : : //! Check whether this node is valid as a script on its own.
1649 [ + + + + ]: 54973 : bool IsValidTopLevel() const { return IsValid() && GetType() << "B"_mst; }
1650 : :
1651 : : //! Check whether this script can always be satisfied in a non-malleable way.
1652 : 1328889 : bool IsNonMalleable() const { return GetType() << "m"_mst; }
1653 : :
1654 : : //! Check whether this script always needs a signature.
1655 : 24785 : bool NeedsSignature() const { return GetType() << "s"_mst; }
1656 : :
1657 : : //! Check whether there is no satisfaction path that contains both timelocks and heightlocks
1658 : 1323080 : bool CheckTimeLocksMix() const { return GetType() << "k"_mst; }
1659 : :
1660 : : //! Check whether there is no duplicate key across this fragment and all its sub-fragments.
1661 [ + - + + : 1322114 : bool CheckDuplicateKey() const { return has_duplicate_keys && !*has_duplicate_keys; }
+ - + + ]
[ + - + + ]
1662 : :
1663 : : //! Whether successful non-malleable satisfactions are guaranteed to be valid.
1664 [ + + + + : 1385401 : bool ValidSatisfactions() const { return IsValid() && CheckOpsLimit() && CheckStackSize(); }
+ + ]
1665 : :
1666 : : //! Whether the apparent policy of this node matches its script semantics. Doesn't guarantee it is a safe script on its own.
1667 [ + + + + : 1383850 : bool IsSaneSubexpression() const { return ValidSatisfactions() && IsNonMalleable() && CheckTimeLocksMix() && CheckDuplicateKey(); }
+ + ]
1668 : :
1669 : : //! Check whether this node is safe as a script on its own.
1670 [ + + + + : 32406 : bool IsSane() const { return IsValidTopLevel() && IsSaneSubexpression() && NeedsSignature(); }
+ + ]
1671 : :
1672 : : //! Produce a witness for this script, if possible and given the information available in the context.
1673 : : //! The non-malleable satisfaction is guaranteed to be valid if it exists, and ValidSatisfaction()
1674 : : //! is true. If IsSane() holds, this satisfaction is guaranteed to succeed in case the node's
1675 : : //! conditions are satisfied (private keys and hash preimages available, locktimes satisfied).
1676 : : template<typename Ctx>
1677 : 10267 : Availability Satisfy(const Ctx& ctx, std::vector<std::vector<unsigned char>>& stack, bool nonmalleable = true) const {
1678 : 10267 : auto ret = ProduceInput(ctx);
1679 [ + + + + : 10267 : if (nonmalleable && (ret.sat.malleable || !ret.sat.has_sig)) return Availability::NO;
+ + ]
1680 : 6418 : stack = std::move(ret.sat.stack);
1681 : 6418 : return ret.sat.available;
1682 : 10267 : }
1683 : :
1684 : : //! Equality testing.
1685 [ + - + - ]: 6146 : bool operator==(const Node<Key>& arg) const { return Compare(*this, arg) == 0; }
1686 : :
1687 : : // Constructors with various argument combinations, which bypass the duplicate key check.
1688 : 391287 : Node(internal::NoDupCheck, MiniscriptContext script_ctx, Fragment nt, std::vector<NodeRef<Key>> sub, std::vector<unsigned char> arg, uint32_t val = 0)
1689 [ + - + - : 391287 : : 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()) {}
+ - + - +
- ]
1690 : 47799 : Node(internal::NoDupCheck, MiniscriptContext script_ctx, Fragment nt, std::vector<unsigned char> arg, uint32_t val = 0)
1691 [ + - + - : 47799 : : fragment(nt), k(val), data(std::move(arg)), m_script_ctx{script_ctx}, ops(CalcOps()), ss(CalcStackSize()), ws(CalcWitnessSize()), typ(CalcType()), scriptlen(CalcScriptLen()) {}
+ - + - +
- ]
1692 : : Node(internal::NoDupCheck, MiniscriptContext script_ctx, Fragment nt, std::vector<NodeRef<Key>> sub, std::vector<Key> key, uint32_t val = 0)
1693 : : : 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()) {}
1694 : 202985 : Node(internal::NoDupCheck, MiniscriptContext script_ctx, Fragment nt, std::vector<Key> key, uint32_t val = 0)
1695 [ + - + - : 202985 : : fragment(nt), k(val), keys(std::move(key)), m_script_ctx{script_ctx}, ops(CalcOps()), ss(CalcStackSize()), ws(CalcWitnessSize()), typ(CalcType()), scriptlen(CalcScriptLen()) {}
+ - + - +
- ]
1696 : 6753511 : Node(internal::NoDupCheck, MiniscriptContext script_ctx, Fragment nt, std::vector<NodeRef<Key>> sub, uint32_t val = 0)
1697 [ + - + - : 6753511 : : fragment(nt), k(val), subs(std::move(sub)), m_script_ctx{script_ctx}, ops(CalcOps()), ss(CalcStackSize()), ws(CalcWitnessSize()), typ(CalcType()), scriptlen(CalcScriptLen()) {}
+ - + - +
- ]
1698 : 8439000 : Node(internal::NoDupCheck, MiniscriptContext script_ctx, Fragment nt, uint32_t val = 0)
1699 [ + - + - : 8439000 : : fragment(nt), k(val), m_script_ctx{script_ctx}, ops(CalcOps()), ss(CalcStackSize()), ws(CalcWitnessSize()), typ(CalcType()), scriptlen(CalcScriptLen()) {}
+ - + - +
- ]
1700 : :
1701 : : // Constructors with various argument combinations, which do perform the duplicate key check.
1702 : : template <typename Ctx> Node(const Ctx& ctx, Fragment nt, std::vector<NodeRef<Key>> sub, std::vector<unsigned char> arg, uint32_t val = 0)
1703 : : : Node(internal::NoDupCheck{}, ctx.MsContext(), nt, std::move(sub), std::move(arg), val) { DuplicateKeyCheck(ctx); }
1704 : : template <typename Ctx> Node(const Ctx& ctx, Fragment nt, std::vector<unsigned char> arg, uint32_t val = 0)
1705 : : : Node(internal::NoDupCheck{}, ctx.MsContext(), nt, std::move(arg), val) { DuplicateKeyCheck(ctx);}
1706 : : template <typename Ctx> Node(const Ctx& ctx, Fragment nt, std::vector<NodeRef<Key>> sub, std::vector<Key> key, uint32_t val = 0)
1707 : : : Node(internal::NoDupCheck{}, ctx.MsContext(), nt, std::move(sub), std::move(key), val) { DuplicateKeyCheck(ctx); }
1708 : : template <typename Ctx> Node(const Ctx& ctx, Fragment nt, std::vector<Key> key, uint32_t val = 0)
1709 : : : Node(internal::NoDupCheck{}, ctx.MsContext(), nt, std::move(key), val) { DuplicateKeyCheck(ctx); }
1710 : : template <typename Ctx> Node(const Ctx& ctx, Fragment nt, std::vector<NodeRef<Key>> sub, uint32_t val = 0)
1711 : : : Node(internal::NoDupCheck{}, ctx.MsContext(), nt, std::move(sub), val) { DuplicateKeyCheck(ctx); }
1712 : : template <typename Ctx> Node(const Ctx& ctx, Fragment nt, uint32_t val = 0)
1713 : : : Node(internal::NoDupCheck{}, ctx.MsContext(), nt, val) { DuplicateKeyCheck(ctx); }
1714 : :
1715 : : // Delete copy constructor and assignment operator, use Clone() instead
1716 : : Node(const Node&) = delete;
1717 : : Node& operator=(const Node&) = delete;
1718 : : };
1719 : :
1720 : : namespace internal {
1721 : :
1722 : : enum class ParseContext {
1723 : : /** An expression which may be begin with wrappers followed by a colon. */
1724 : : WRAPPED_EXPR,
1725 : : /** A miniscript expression which does not begin with wrappers. */
1726 : : EXPR,
1727 : :
1728 : : /** SWAP wraps the top constructed node with s: */
1729 : : SWAP,
1730 : : /** ALT wraps the top constructed node with a: */
1731 : : ALT,
1732 : : /** CHECK wraps the top constructed node with c: */
1733 : : CHECK,
1734 : : /** DUP_IF wraps the top constructed node with d: */
1735 : : DUP_IF,
1736 : : /** VERIFY wraps the top constructed node with v: */
1737 : : VERIFY,
1738 : : /** NON_ZERO wraps the top constructed node with j: */
1739 : : NON_ZERO,
1740 : : /** ZERO_NOTEQUAL wraps the top constructed node with n: */
1741 : : ZERO_NOTEQUAL,
1742 : : /** WRAP_U will construct an or_i(X,0) node from the top constructed node. */
1743 : : WRAP_U,
1744 : : /** WRAP_T will construct an and_v(X,1) node from the top constructed node. */
1745 : : WRAP_T,
1746 : :
1747 : : /** AND_N will construct an andor(X,Y,0) node from the last two constructed nodes. */
1748 : : AND_N,
1749 : : /** AND_V will construct an and_v node from the last two constructed nodes. */
1750 : : AND_V,
1751 : : /** AND_B will construct an and_b node from the last two constructed nodes. */
1752 : : AND_B,
1753 : : /** ANDOR will construct an andor node from the last three constructed nodes. */
1754 : : ANDOR,
1755 : : /** OR_B will construct an or_b node from the last two constructed nodes. */
1756 : : OR_B,
1757 : : /** OR_C will construct an or_c node from the last two constructed nodes. */
1758 : : OR_C,
1759 : : /** OR_D will construct an or_d node from the last two constructed nodes. */
1760 : : OR_D,
1761 : : /** OR_I will construct an or_i node from the last two constructed nodes. */
1762 : : OR_I,
1763 : :
1764 : : /** THRESH will read a wrapped expression, and then look for a COMMA. If
1765 : : * no comma follows, it will construct a thresh node from the appropriate
1766 : : * number of constructed children. Otherwise, it will recurse with another
1767 : : * THRESH. */
1768 : : THRESH,
1769 : :
1770 : : /** COMMA expects the next element to be ',' and fails if not. */
1771 : : COMMA,
1772 : : /** CLOSE_BRACKET expects the next element to be ')' and fails if not. */
1773 : : CLOSE_BRACKET,
1774 : : };
1775 : :
1776 : : int FindNextChar(std::span<const char> in, char m);
1777 : :
1778 : : /** Parse a key string ending at the end of the fragment's text representation. */
1779 : : template<typename Key, typename Ctx>
1780 : 70006 : std::optional<std::pair<Key, int>> ParseKeyEnd(std::span<const char> in, const Ctx& ctx)
1781 : : {
1782 : 70006 : int key_size = FindNextChar(in, ')');
1783 [ + + ]: 70006 : if (key_size < 1) return {};
1784 [ + + ]: 69933 : auto key = ctx.FromString(in.begin(), in.begin() + key_size);
1785 [ + + ]: 69933 : if (!key) return {};
1786 : 69709 : return {{std::move(*key), key_size}};
1787 : : }
1788 : :
1789 : : /** Parse a hex string ending at the end of the fragment's text representation. */
1790 : : template<typename Ctx>
1791 : 22910 : std::optional<std::pair<std::vector<unsigned char>, int>> ParseHexStrEnd(std::span<const char> in, const size_t expected_size,
1792 : : const Ctx& ctx)
1793 : : {
1794 : 22910 : int hash_size = FindNextChar(in, ')');
1795 [ + + ]: 22910 : if (hash_size < 1) return {};
1796 [ - + ]: 22882 : std::string val = std::string(in.begin(), in.begin() + hash_size);
1797 [ + - + + ]: 22882 : if (!IsHex(val)) return {};
1798 [ + - ]: 22846 : auto hash = ParseHex(val);
1799 [ + + ]: 22846 : if (hash.size() != expected_size) return {};
1800 : 22824 : return {{std::move(hash), hash_size}};
1801 : 45728 : }
1802 : :
1803 : : /** BuildBack pops the last two elements off `constructed` and wraps them in the specified Fragment */
1804 : : template<typename Key>
1805 : 1671025 : void BuildBack(const MiniscriptContext script_ctx, Fragment nt, std::vector<NodeRef<Key>>& constructed, const bool reverse = false)
1806 : : {
1807 : 1671025 : NodeRef<Key> child = std::move(constructed.back());
1808 : 1671025 : constructed.pop_back();
1809 [ + + ]: 1671025 : if (reverse) {
1810 [ + - + - ]: 375577 : constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, script_ctx, nt, Vector(std::move(child), std::move(constructed.back())));
1811 : : } else {
1812 [ + - + - ]: 1295448 : constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, script_ctx, nt, Vector(std::move(constructed.back()), std::move(child)));
1813 : : }
1814 : 1671025 : }
1815 : :
1816 : : /**
1817 : : * Parse a miniscript from its textual descriptor form.
1818 : : * This does not check whether the script is valid, let alone sane. The caller is expected to use
1819 : : * the `IsValidTopLevel()` and `IsSaneTopLevel()` to check for these properties on the node.
1820 : : */
1821 : : template<typename Key, typename Ctx>
1822 : 26971 : inline NodeRef<Key> Parse(std::span<const char> in, const Ctx& ctx)
1823 : : {
1824 : : using namespace script;
1825 : :
1826 : : // Account for the minimum script size for all parsed fragments so far. It "borrows" 1
1827 : : // script byte from all leaf nodes, counting it instead whenever a space for a recursive
1828 : : // expression is added (through andor, and_*, or_*, thresh). This guarantees that all fragments
1829 : : // increment the script_size by at least one, except for:
1830 : : // - "0", "1": these leafs are only a single byte, so their subtracted-from increment is 0.
1831 : : // This is not an issue however, as "space" for them has to be created by combinators,
1832 : : // which do increment script_size.
1833 : : // - "v:": the v wrapper adds nothing as in some cases it results in no opcode being added
1834 : : // (instead transforming another opcode into its VERIFY form). However, the v: wrapper has
1835 : : // to be interleaved with other fragments to be valid, so this is not a concern.
1836 : 26971 : size_t script_size{1};
1837 : 26971 : size_t max_size{internal::MaxScriptSize(ctx.MsContext())};
1838 : :
1839 : : // The two integers are used to hold state for thresh()
1840 : 26971 : std::vector<std::tuple<ParseContext, int64_t, int64_t>> to_parse;
1841 : 26971 : std::vector<NodeRef<Key>> constructed;
1842 : :
1843 [ + - ]: 26971 : to_parse.emplace_back(ParseContext::WRAPPED_EXPR, -1, -1);
1844 : :
1845 : : // Parses a multi() or multi_a() from its string representation. Returns false on parsing error.
1846 : 53232 : const auto parse_multi_exp = [&](std::span<const char>& in, const bool is_multi_a) -> bool {
1847 [ + + ]: 26261 : const auto max_keys{is_multi_a ? MAX_PUBKEYS_PER_MULTI_A : MAX_PUBKEYS_PER_MULTISIG};
1848 : 16478 : const auto required_ctx{is_multi_a ? MiniscriptContext::TAPSCRIPT : MiniscriptContext::P2WSH};
1849 [ + + ]: 26261 : if (ctx.MsContext() != required_ctx) return false;
1850 : : // Get threshold
1851 : 26247 : int next_comma = FindNextChar(in, ',');
1852 [ + + ]: 26247 : if (next_comma < 1) return false;
1853 [ + + ]: 26231 : const auto k_to_integral{ToIntegral<int64_t>(std::string_view(in.data(), next_comma))};
1854 [ + + ]: 26231 : if (!k_to_integral.has_value()) return false;
1855 : 26057 : const int64_t k{k_to_integral.value()};
1856 : 26057 : in = in.subspan(next_comma + 1);
1857 : : // Get keys. It is compatible for both compressed and x-only keys.
1858 : 26057 : std::vector<Key> keys;
1859 [ + + ]: 188301 : while (next_comma != -1) {
1860 [ + - ]: 162430 : next_comma = FindNextChar(in, ',');
1861 [ + + + - ]: 162430 : int key_length = (next_comma == -1) ? FindNextChar(in, ')') : next_comma;
1862 [ + + ]: 162430 : if (key_length < 1) return false;
1863 [ + - ]: 162376 : auto key = ctx.FromString(in.begin(), in.begin() + key_length);
1864 [ + + ]: 162376 : if (!key) return false;
1865 [ + - ]: 162244 : keys.push_back(std::move(*key));
1866 : 162244 : in = in.subspan(key_length + 1);
1867 : : }
1868 [ + - + + ]: 25871 : if (keys.size() < 1 || keys.size() > max_keys) return false;
1869 [ + + + + ]: 25858 : if (k < 1 || k > (int64_t)keys.size()) return false;
1870 [ + + ]: 25816 : if (is_multi_a) {
1871 : : // (push + xonly-key + CHECKSIG[ADD]) * n + k + OP_NUMEQUAL(VERIFY), minus one.
1872 [ + - ]: 19064 : script_size += (1 + 32 + 1) * keys.size() + BuildScript(k).size();
1873 [ + - ]: 19064 : constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::MULTI_A, std::move(keys), k));
1874 : : } else {
1875 [ + + ]: 16284 : script_size += 2 + (keys.size() > 16) + (k > 16) + 34 * keys.size();
1876 [ + - ]: 32568 : constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::MULTI, std::move(keys), k));
1877 : : }
1878 : : return true;
1879 : 26057 : };
1880 : :
1881 [ + + ]: 9943215 : while (!to_parse.empty()) {
1882 [ + + ]: 9892974 : if (script_size > max_size) return {};
1883 : :
1884 : : // Get the current context we are decoding within
1885 [ + + + + : 9892961 : auto [cur_context, n, k] = to_parse.back();
+ + + + +
+ + + + +
+ + + + +
+ + + - ]
1886 : 9892961 : to_parse.pop_back();
1887 : :
1888 [ + + + + : 9892961 : switch (cur_context) {
+ + + + +
+ + + + +
+ + + + +
+ + + - ]
1889 : 1669935 : case ParseContext::WRAPPED_EXPR: {
1890 : 1669935 : std::optional<size_t> colon_index{};
1891 [ + + ]: 7369209 : for (size_t i = 1; i < in.size(); ++i) {
1892 [ + + ]: 7368795 : if (in[i] == ':') {
1893 : 764150 : colon_index = i;
1894 : 764150 : break;
1895 : : }
1896 [ + + + + ]: 6604645 : if (in[i] < 'a' || in[i] > 'z') break;
1897 : : }
1898 : : // If there is no colon, this loop won't execute
1899 : : bool last_was_v{false};
1900 [ + + + + ]: 6959948 : for (size_t j = 0; colon_index && j < *colon_index; ++j) {
1901 [ + + ]: 5290083 : if (script_size > max_size) return {};
1902 [ + + ]: 5290068 : if (in[j] == 'a') {
1903 : 666180 : script_size += 2;
1904 [ + - ]: 666180 : to_parse.emplace_back(ParseContext::ALT, -1, -1);
1905 [ + + ]: 4623888 : } else if (in[j] == 's') {
1906 : 109371 : script_size += 1;
1907 [ + - ]: 109371 : to_parse.emplace_back(ParseContext::SWAP, -1, -1);
1908 [ + + ]: 4514517 : } else if (in[j] == 'c') {
1909 : 138011 : script_size += 1;
1910 [ + - ]: 138011 : to_parse.emplace_back(ParseContext::CHECK, -1, -1);
1911 [ + + ]: 4376506 : } else if (in[j] == 'd') {
1912 : 316783 : script_size += 3;
1913 [ + - ]: 316783 : to_parse.emplace_back(ParseContext::DUP_IF, -1, -1);
1914 [ + + ]: 4059723 : } else if (in[j] == 'j') {
1915 : 210164 : script_size += 4;
1916 [ + - ]: 210164 : to_parse.emplace_back(ParseContext::NON_ZERO, -1, -1);
1917 [ + + ]: 3849559 : } else if (in[j] == 'n') {
1918 : 1251913 : script_size += 1;
1919 [ + - ]: 1251913 : to_parse.emplace_back(ParseContext::ZERO_NOTEQUAL, -1, -1);
1920 [ + + ]: 2597646 : } else if (in[j] == 'v') {
1921 : : // do not permit "...vv...:"; it's not valid, and also doesn't trigger early
1922 : : // failure as script_size isn't incremented.
1923 [ + + ]: 253818 : if (last_was_v) return {};
1924 [ + - ]: 253805 : to_parse.emplace_back(ParseContext::VERIFY, -1, -1);
1925 [ + + ]: 2343828 : } else if (in[j] == 'u') {
1926 : 649085 : script_size += 4;
1927 [ + - ]: 649085 : to_parse.emplace_back(ParseContext::WRAP_U, -1, -1);
1928 [ + + ]: 1694743 : } else if (in[j] == 't') {
1929 : 513057 : script_size += 1;
1930 [ + - ]: 513057 : to_parse.emplace_back(ParseContext::WRAP_T, -1, -1);
1931 [ + + ]: 1181686 : } else if (in[j] == 'l') {
1932 : : // The l: wrapper is equivalent to or_i(0,X)
1933 : 1181644 : script_size += 4;
1934 [ + - ]: 2363288 : constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::JUST_0));
1935 [ + - ]: 1181644 : to_parse.emplace_back(ParseContext::OR_I, -1, -1);
1936 : : } else {
1937 : 42 : return {};
1938 : : }
1939 : 5290013 : last_was_v = (in[j] == 'v');
1940 : : }
1941 [ + - ]: 1669865 : to_parse.emplace_back(ParseContext::EXPR, -1, -1);
1942 [ + + ]: 1669865 : if (colon_index) in = in.subspan(*colon_index + 1);
1943 : : break;
1944 : : }
1945 : 1669862 : case ParseContext::EXPR: {
1946 [ + - + - : 1669862 : if (Const("0", in)) {
+ + ]
1947 [ + - ]: 826214 : constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::JUST_0));
1948 [ + - + - : 1256755 : } else if (Const("1", in)) {
+ + ]
1949 [ + - ]: 998222 : constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::JUST_1));
1950 [ + - + - : 757644 : } else if (Const("pk(", in)) {
+ + ]
1951 [ + - ]: 38385 : auto res = ParseKeyEnd<Key, Ctx>(in, ctx);
1952 [ + + ]: 38385 : if (!res) return {};
1953 [ + - ]: 38234 : auto& [key, key_size] = *res;
1954 [ + - + - : 76468 : constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_C, Vector(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::PK_K, Vector(std::move(key))))));
+ - + - ]
1955 : 38234 : in = in.subspan(key_size + 1);
1956 [ + + ]: 48289 : script_size += IsTapscript(ctx.MsContext()) ? 33 : 34;
1957 [ + - + - : 719259 : } else if (Const("pkh(", in)) {
+ + ]
1958 [ + - ]: 12679 : auto res = ParseKeyEnd<Key>(in, ctx);
1959 [ + + ]: 12679 : if (!res) return {};
1960 [ + - ]: 12611 : auto& [key, key_size] = *res;
1961 [ + - + - : 25222 : constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_C, Vector(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::PK_H, Vector(std::move(key))))));
+ - + - ]
1962 : 12611 : in = in.subspan(key_size + 1);
1963 : 12611 : script_size += 24;
1964 [ + - + - : 706580 : } else if (Const("pk_k(", in)) {
+ + ]
1965 [ + - ]: 12359 : auto res = ParseKeyEnd<Key>(in, ctx);
1966 [ + + ]: 12359 : if (!res) return {};
1967 [ + - ]: 12316 : auto& [key, key_size] = *res;
1968 [ + - + - ]: 24632 : constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::PK_K, Vector(std::move(key))));
1969 : 12316 : in = in.subspan(key_size + 1);
1970 [ + + ]: 18688 : script_size += IsTapscript(ctx.MsContext()) ? 32 : 33;
1971 [ + - + - : 694221 : } else if (Const("pk_h(", in)) {
+ + ]
1972 [ + - ]: 6583 : auto res = ParseKeyEnd<Key>(in, ctx);
1973 [ + + ]: 6583 : if (!res) return {};
1974 [ + - ]: 6548 : auto& [key, key_size] = *res;
1975 [ + - + - ]: 13096 : constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::PK_H, Vector(std::move(key))));
1976 : 6548 : in = in.subspan(key_size + 1);
1977 : 6548 : script_size += 23;
1978 [ + - + - : 687638 : } else if (Const("sha256(", in)) {
+ + ]
1979 [ + - ]: 5290 : auto res = ParseHexStrEnd(in, 32, ctx);
1980 [ + + ]: 5290 : if (!res) return {};
1981 [ + - ]: 5251 : auto& [hash, hash_size] = *res;
1982 [ + - ]: 10502 : constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::SHA256, std::move(hash)));
1983 : 5251 : in = in.subspan(hash_size + 1);
1984 : 5251 : script_size += 38;
1985 [ + - + - : 687638 : } else if (Const("ripemd160(", in)) {
+ + ]
1986 [ + - ]: 6122 : auto res = ParseHexStrEnd(in, 20, ctx);
1987 [ + + ]: 6122 : if (!res) return {};
1988 [ + - ]: 6106 : auto& [hash, hash_size] = *res;
1989 [ + - ]: 12212 : constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::RIPEMD160, std::move(hash)));
1990 : 6106 : in = in.subspan(hash_size + 1);
1991 : 6106 : script_size += 26;
1992 [ + - + - : 682348 : } else if (Const("hash256(", in)) {
+ + ]
1993 [ + - ]: 5455 : auto res = ParseHexStrEnd(in, 32, ctx);
1994 [ + + ]: 5455 : if (!res) return {};
1995 [ + - ]: 5442 : auto& [hash, hash_size] = *res;
1996 [ + - ]: 10884 : constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::HASH256, std::move(hash)));
1997 : 5442 : in = in.subspan(hash_size + 1);
1998 : 5442 : script_size += 38;
1999 [ + - + - : 676226 : } else if (Const("hash160(", in)) {
+ + ]
2000 [ + - ]: 6043 : auto res = ParseHexStrEnd(in, 20, ctx);
2001 [ + + ]: 6043 : if (!res) return {};
2002 [ + - ]: 6025 : auto& [hash, hash_size] = *res;
2003 [ + - ]: 12050 : constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::HASH160, std::move(hash)));
2004 : 6025 : in = in.subspan(hash_size + 1);
2005 : 6025 : script_size += 26;
2006 [ + - + - : 670771 : } else if (Const("after(", in)) {
+ + ]
2007 [ + - ]: 65313 : int arg_size = FindNextChar(in, ')');
2008 [ + + ]: 65313 : if (arg_size < 1) return {};
2009 [ + + ]: 65289 : const auto num{ToIntegral<int64_t>(std::string_view(in.data(), arg_size))};
2010 [ + + + + : 65289 : if (!num.has_value() || *num < 1 || *num >= 0x80000000L) return {};
+ + ]
2011 [ + - ]: 130356 : constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::AFTER, *num));
2012 [ + + ]: 65178 : in = in.subspan(arg_size + 1);
2013 [ + + ]: 75390 : script_size += 1 + (*num > 16) + (*num > 0x7f) + (*num > 0x7fff) + (*num > 0x7fffff);
2014 [ + - + - : 599415 : } else if (Const("older(", in)) {
+ + ]
2015 [ + - ]: 51755 : int arg_size = FindNextChar(in, ')');
2016 [ + + ]: 51755 : if (arg_size < 1) return {};
2017 [ + + ]: 51730 : const auto num{ToIntegral<int64_t>(std::string_view(in.data(), arg_size))};
2018 [ + + + + : 51730 : if (!num.has_value() || *num < 1 || *num >= 0x80000000L) return {};
+ + ]
2019 [ + - ]: 103206 : constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::OLDER, *num));
2020 [ + + ]: 51603 : in = in.subspan(arg_size + 1);
2021 [ + + ]: 60231 : script_size += 1 + (*num > 16) + (*num > 0x7f) + (*num > 0x7fff) + (*num > 0x7fffff);
2022 [ + - + - : 547660 : } else if (Const("multi(", in)) {
+ + ]
2023 [ + - + + ]: 16478 : if (!parse_multi_exp(in, /* is_multi_a = */false)) return {};
2024 [ + - + - : 531182 : } else if (Const("multi_a(", in)) {
+ + ]
2025 [ + - + + ]: 9783 : if (!parse_multi_exp(in, /* is_multi_a = */true)) return {};
2026 [ + - + - : 521399 : } else if (Const("thresh(", in)) {
+ + ]
2027 [ + - ]: 121366 : int next_comma = FindNextChar(in, ',');
2028 [ + + ]: 121366 : if (next_comma < 1) return {};
2029 [ + + ]: 121340 : const auto k{ToIntegral<int64_t>(std::string_view(in.data(), next_comma))};
2030 [ + + + + ]: 121340 : if (!k.has_value() || *k < 1) return {};
2031 [ + - ]: 121271 : in = in.subspan(next_comma + 1);
2032 : : // n = 1 here because we read the first WRAPPED_EXPR before reaching THRESH
2033 [ + - ]: 121271 : to_parse.emplace_back(ParseContext::THRESH, 1, *k);
2034 [ + - ]: 121271 : to_parse.emplace_back(ParseContext::WRAPPED_EXPR, -1, -1);
2035 [ + + ]: 241634 : script_size += 2 + (*k > 16) + (*k > 0x7f) + (*k > 0x7fff) + (*k > 0x7fffff);
2036 [ + - + - : 400033 : } else if (Const("andor(", in)) {
+ + ]
2037 [ + - ]: 50785 : to_parse.emplace_back(ParseContext::ANDOR, -1, -1);
2038 [ + - ]: 50785 : to_parse.emplace_back(ParseContext::CLOSE_BRACKET, -1, -1);
2039 [ + - ]: 50785 : to_parse.emplace_back(ParseContext::WRAPPED_EXPR, -1, -1);
2040 [ + - ]: 50785 : to_parse.emplace_back(ParseContext::COMMA, -1, -1);
2041 [ + - ]: 50785 : to_parse.emplace_back(ParseContext::WRAPPED_EXPR, -1, -1);
2042 [ + - ]: 50785 : to_parse.emplace_back(ParseContext::COMMA, -1, -1);
2043 [ + - ]: 50785 : to_parse.emplace_back(ParseContext::WRAPPED_EXPR, -1, -1);
2044 : 50785 : script_size += 5;
2045 : : } else {
2046 [ + - + - : 349248 : if (Const("and_n(", in)) {
+ + ]
2047 [ + - ]: 32012 : to_parse.emplace_back(ParseContext::AND_N, -1, -1);
2048 : 32012 : script_size += 5;
2049 [ + - + - : 317236 : } else if (Const("and_b(", in)) {
+ + ]
2050 [ + - ]: 56377 : to_parse.emplace_back(ParseContext::AND_B, -1, -1);
2051 : 56377 : script_size += 2;
2052 [ + - + - : 260859 : } else if (Const("and_v(", in)) {
+ + ]
2053 [ + - ]: 56054 : to_parse.emplace_back(ParseContext::AND_V, -1, -1);
2054 : 56054 : script_size += 1;
2055 [ + - + - : 204805 : } else if (Const("or_b(", in)) {
+ + ]
2056 [ + - ]: 85179 : to_parse.emplace_back(ParseContext::OR_B, -1, -1);
2057 : 85179 : script_size += 2;
2058 [ + - + - : 119626 : } else if (Const("or_c(", in)) {
+ + ]
2059 [ + - ]: 34814 : to_parse.emplace_back(ParseContext::OR_C, -1, -1);
2060 : 34814 : script_size += 3;
2061 [ + - + - : 84812 : } else if (Const("or_d(", in)) {
+ + ]
2062 [ + - ]: 46318 : to_parse.emplace_back(ParseContext::OR_D, -1, -1);
2063 : 46318 : script_size += 4;
2064 [ + - + - : 38494 : } else if (Const("or_i(", in)) {
+ + ]
2065 [ + - ]: 37083 : to_parse.emplace_back(ParseContext::OR_I, -1, -1);
2066 : 37083 : script_size += 4;
2067 : : } else {
2068 : 1411 : return {};
2069 : : }
2070 [ + - ]: 347837 : to_parse.emplace_back(ParseContext::CLOSE_BRACKET, -1, -1);
2071 [ + - ]: 347837 : to_parse.emplace_back(ParseContext::WRAPPED_EXPR, -1, -1);
2072 [ + - ]: 347837 : to_parse.emplace_back(ParseContext::COMMA, -1, -1);
2073 [ + - ]: 347837 : to_parse.emplace_back(ParseContext::WRAPPED_EXPR, -1, -1);
2074 : : }
2075 : : break;
2076 : : }
2077 : 528359 : case ParseContext::ALT: {
2078 [ + - + - ]: 528359 : constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_A, Vector(std::move(constructed.back())));
2079 : 528359 : break;
2080 : : }
2081 : 100359 : case ParseContext::SWAP: {
2082 [ + - + - ]: 100359 : constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_S, Vector(std::move(constructed.back())));
2083 : 100359 : break;
2084 : : }
2085 : 110929 : case ParseContext::CHECK: {
2086 [ + - + - ]: 110929 : constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_C, Vector(std::move(constructed.back())));
2087 : 110929 : break;
2088 : : }
2089 : 273240 : case ParseContext::DUP_IF: {
2090 [ + - + - ]: 273240 : constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_D, Vector(std::move(constructed.back())));
2091 : 273240 : break;
2092 : : }
2093 : 193098 : case ParseContext::NON_ZERO: {
2094 [ + - + - ]: 193098 : constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_J, Vector(std::move(constructed.back())));
2095 : 193098 : break;
2096 : : }
2097 : 1116005 : case ParseContext::ZERO_NOTEQUAL: {
2098 [ + - + - ]: 1116005 : constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_N, Vector(std::move(constructed.back())));
2099 : 1116005 : break;
2100 : : }
2101 : 240090 : case ParseContext::VERIFY: {
2102 [ + - ]: 240090 : script_size += (constructed.back()->GetType() << "x"_mst);
2103 [ + - + - ]: 240090 : constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_V, Vector(std::move(constructed.back())));
2104 : 240090 : break;
2105 : : }
2106 : 629842 : case ParseContext::WRAP_U: {
2107 [ + - + - : 629842 : constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::OR_I, Vector(std::move(constructed.back()), MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::JUST_0)));
+ - ]
2108 : 629842 : break;
2109 : : }
2110 : 477710 : case ParseContext::WRAP_T: {
2111 [ + - + - : 477710 : constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::AND_V, Vector(std::move(constructed.back()), MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::JUST_1)));
+ - ]
2112 : 477710 : break;
2113 : : }
2114 [ + - ]: 41223 : case ParseContext::AND_B: {
2115 [ + - ]: 41223 : BuildBack(ctx.MsContext(), Fragment::AND_B, constructed);
2116 : : break;
2117 : : }
2118 : 27284 : case ParseContext::AND_N: {
2119 : 27284 : auto mid = std::move(constructed.back());
2120 : 27284 : constructed.pop_back();
2121 [ + - + - : 27284 : constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::ANDOR, Vector(std::move(constructed.back()), std::move(mid), MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::JUST_0)));
+ - ]
2122 : : break;
2123 : 27284 : }
2124 [ + - ]: 49953 : case ParseContext::AND_V: {
2125 [ + - ]: 49953 : BuildBack(ctx.MsContext(), Fragment::AND_V, constructed);
2126 : : break;
2127 : : }
2128 [ + - ]: 53703 : case ParseContext::OR_B: {
2129 [ + - ]: 53703 : BuildBack(ctx.MsContext(), Fragment::OR_B, constructed);
2130 : : break;
2131 : : }
2132 [ + - ]: 27154 : case ParseContext::OR_C: {
2133 [ + - ]: 27154 : BuildBack(ctx.MsContext(), Fragment::OR_C, constructed);
2134 : : break;
2135 : : }
2136 [ + - ]: 38790 : case ParseContext::OR_D: {
2137 [ + - ]: 38790 : BuildBack(ctx.MsContext(), Fragment::OR_D, constructed);
2138 : : break;
2139 : : }
2140 [ + - ]: 1084625 : case ParseContext::OR_I: {
2141 [ + - ]: 1084625 : BuildBack(ctx.MsContext(), Fragment::OR_I, constructed);
2142 : : break;
2143 : : }
2144 : 35491 : case ParseContext::ANDOR: {
2145 : 35491 : auto right = std::move(constructed.back());
2146 : 35491 : constructed.pop_back();
2147 : 35491 : auto mid = std::move(constructed.back());
2148 : 35491 : constructed.pop_back();
2149 [ + - + - ]: 35491 : constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::ANDOR, Vector(std::move(constructed.back()), std::move(mid), std::move(right)));
2150 : : break;
2151 : 35491 : }
2152 [ + + ]: 814770 : case ParseContext::THRESH: {
2153 [ + + ]: 814770 : if (in.size() < 1) return {};
2154 [ + + ]: 814615 : if (in[0] == ',') {
2155 : 720786 : in = in.subspan(1);
2156 [ + - ]: 720786 : to_parse.emplace_back(ParseContext::THRESH, n+1, k);
2157 [ + - ]: 720786 : to_parse.emplace_back(ParseContext::WRAPPED_EXPR, -1, -1);
2158 : 720786 : script_size += 2;
2159 [ + + ]: 93829 : } else if (in[0] == ')') {
2160 [ + + ]: 93673 : if (k > n) return {};
2161 : 93633 : in = in.subspan(1);
2162 : : // Children are constructed in reverse order, so iterate from end to beginning
2163 : 93633 : std::vector<NodeRef<Key>> subs;
2164 [ + + ]: 788145 : for (int i = 0; i < n; ++i) {
2165 [ + - ]: 694512 : subs.push_back(std::move(constructed.back()));
2166 : 694512 : constructed.pop_back();
2167 : : }
2168 : 93633 : std::reverse(subs.begin(), subs.end());
2169 [ + - ]: 187266 : constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::THRESH, std::move(subs), k));
2170 : 93633 : } else {
2171 : 156 : return {};
2172 : : }
2173 : : break;
2174 : : }
2175 [ + + ]: 402549 : case ParseContext::COMMA: {
2176 [ + + + + ]: 402549 : if (in.size() < 1 || in[0] != ',') return {};
2177 : 402289 : in = in.subspan(1);
2178 : 402289 : break;
2179 : : }
2180 [ + + ]: 307990 : case ParseContext::CLOSE_BRACKET: {
2181 [ + + + + ]: 307990 : if (in.size() < 1 || in[0] != ')') return {};
2182 : 307604 : in = in.subspan(1);
2183 : 307604 : break;
2184 : : }
2185 : : }
2186 : : }
2187 : :
2188 : : // Sanity checks on the produced miniscript
2189 [ - + ]: 23270 : assert(constructed.size() >= 1);
2190 [ + - ]: 23270 : CHECK_NONFATAL(constructed.size() == 1);
2191 [ - + ]: 23270 : assert(constructed[0]->ScriptSize() == script_size);
2192 [ + + ]: 23270 : if (in.size() > 0) return {};
2193 [ + - ]: 22994 : NodeRef<Key> tl_node = std::move(constructed.front());
2194 [ + - ]: 22994 : tl_node->DuplicateKeyCheck(ctx);
2195 : 22994 : return tl_node;
2196 : 26971 : }
2197 : :
2198 : : /** Decode a script into opcode/push pairs.
2199 : : *
2200 : : * Construct a vector with one element per opcode in the script, in reverse order.
2201 : : * Each element is a pair consisting of the opcode, as well as the data pushed by
2202 : : * the opcode (including OP_n), if any. OP_CHECKSIGVERIFY, OP_CHECKMULTISIGVERIFY,
2203 : : * OP_NUMEQUALVERIFY and OP_EQUALVERIFY are decomposed into OP_CHECKSIG, OP_CHECKMULTISIG,
2204 : : * OP_EQUAL and OP_NUMEQUAL respectively, plus OP_VERIFY.
2205 : : */
2206 : : std::optional<std::vector<Opcode>> DecomposeScript(const CScript& script);
2207 : :
2208 : : /** Determine whether the passed pair (created by DecomposeScript) is pushing a number. */
2209 : : std::optional<int64_t> ParseScriptNumber(const Opcode& in);
2210 : :
2211 : : enum class DecodeContext {
2212 : : /** A single expression of type B, K, or V. Specifically, this can't be an
2213 : : * and_v or an expression of type W (a: and s: wrappers). */
2214 : : SINGLE_BKV_EXPR,
2215 : : /** Potentially multiple SINGLE_BKV_EXPRs as children of (potentially multiple)
2216 : : * and_v expressions. Syntactic sugar for MAYBE_AND_V + SINGLE_BKV_EXPR. */
2217 : : BKV_EXPR,
2218 : : /** An expression of type W (a: or s: wrappers). */
2219 : : W_EXPR,
2220 : :
2221 : : /** SWAP expects the next element to be OP_SWAP (inside a W-type expression that
2222 : : * didn't end with FROMALTSTACK), and wraps the top of the constructed stack
2223 : : * with s: */
2224 : : SWAP,
2225 : : /** ALT expects the next element to be TOALTSTACK (we must have already read a
2226 : : * FROMALTSTACK earlier), and wraps the top of the constructed stack with a: */
2227 : : ALT,
2228 : : /** CHECK wraps the top constructed node with c: */
2229 : : CHECK,
2230 : : /** DUP_IF wraps the top constructed node with d: */
2231 : : DUP_IF,
2232 : : /** VERIFY wraps the top constructed node with v: */
2233 : : VERIFY,
2234 : : /** NON_ZERO wraps the top constructed node with j: */
2235 : : NON_ZERO,
2236 : : /** ZERO_NOTEQUAL wraps the top constructed node with n: */
2237 : : ZERO_NOTEQUAL,
2238 : :
2239 : : /** MAYBE_AND_V will check if the next part of the script could be a valid
2240 : : * miniscript sub-expression, and if so it will push AND_V and SINGLE_BKV_EXPR
2241 : : * to decode it and construct the and_v node. This is recursive, to deal with
2242 : : * multiple and_v nodes inside each other. */
2243 : : MAYBE_AND_V,
2244 : : /** AND_V will construct an and_v node from the last two constructed nodes. */
2245 : : AND_V,
2246 : : /** AND_B will construct an and_b node from the last two constructed nodes. */
2247 : : AND_B,
2248 : : /** ANDOR will construct an andor node from the last three constructed nodes. */
2249 : : ANDOR,
2250 : : /** OR_B will construct an or_b node from the last two constructed nodes. */
2251 : : OR_B,
2252 : : /** OR_C will construct an or_c node from the last two constructed nodes. */
2253 : : OR_C,
2254 : : /** OR_D will construct an or_d node from the last two constructed nodes. */
2255 : : OR_D,
2256 : :
2257 : : /** In a thresh expression, all sub-expressions other than the first are W-type,
2258 : : * and end in OP_ADD. THRESH_W will check for this OP_ADD and either push a W_EXPR
2259 : : * or a SINGLE_BKV_EXPR and jump to THRESH_E accordingly. */
2260 : : THRESH_W,
2261 : : /** THRESH_E constructs a thresh node from the appropriate number of constructed
2262 : : * children. */
2263 : : THRESH_E,
2264 : :
2265 : : /** ENDIF signals that we are inside some sort of OP_IF structure, which could be
2266 : : * or_d, or_c, or_i, andor, d:, or j: wrapper, depending on what follows. We read
2267 : : * a BKV_EXPR and then deal with the next opcode case-by-case. */
2268 : : ENDIF,
2269 : : /** If, inside an ENDIF context, we find an OP_NOTIF before finding an OP_ELSE,
2270 : : * we could either be in an or_d or an or_c node. We then check for IFDUP to
2271 : : * distinguish these cases. */
2272 : : ENDIF_NOTIF,
2273 : : /** If, inside an ENDIF context, we find an OP_ELSE, then we could be in either an
2274 : : * or_i or an andor node. Read the next BKV_EXPR and find either an OP_IF or an
2275 : : * OP_NOTIF. */
2276 : : ENDIF_ELSE,
2277 : : };
2278 : :
2279 : : //! Parse a miniscript from a bitcoin script
2280 : : template<typename Key, typename Ctx, typename I>
2281 : 27820 : inline NodeRef<Key> DecodeScript(I& in, I last, const Ctx& ctx)
2282 : : {
2283 : : // The two integers are used to hold state for thresh()
2284 : 27820 : std::vector<std::tuple<DecodeContext, int64_t, int64_t>> to_parse;
2285 : 27820 : std::vector<NodeRef<Key>> constructed;
2286 : :
2287 : : // This is the top level, so we assume the type is B
2288 : : // (in particular, disallowing top level W expressions)
2289 [ + - ]: 27820 : to_parse.emplace_back(DecodeContext::BKV_EXPR, -1, -1);
2290 : :
2291 [ + + ]: 20697662 : while (!to_parse.empty()) {
2292 : : // Exit early if the Miniscript is not going to be valid.
2293 [ + + + + ]: 20680606 : if (!constructed.empty() && !constructed.back()->IsValid()) return {};
2294 : :
2295 : : // Get the current context we are decoding within
2296 [ + + + + : 20678887 : auto [cur_context, n, k] = to_parse.back();
+ + + + +
+ + + + +
+ + + + +
+ + + - ]
2297 : 20678887 : to_parse.pop_back();
2298 : :
2299 [ + + + + : 20678887 : switch(cur_context) {
+ + + + +
+ + + + +
+ + + + +
+ + + - ]
2300 [ + + ]: 7015952 : case DecodeContext::SINGLE_BKV_EXPR: {
2301 [ + + ]: 7015952 : if (in >= last) return {};
2302 : :
2303 : : // Constants
2304 [ + + ]: 7010842 : if (in[0].first == OP_1) {
2305 : 207014 : ++in;
2306 [ + - ]: 414028 : constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::JUST_1));
2307 : 207014 : break;
2308 : : }
2309 [ + + ]: 6803828 : if (in[0].first == OP_0) {
2310 : 4838926 : ++in;
2311 [ + - ]: 9677852 : constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::JUST_0));
2312 : 4838926 : break;
2313 : : }
2314 : : // Public keys
2315 [ - + + + : 1964902 : if (in[0].second.size() == 33 || in[0].second.size() == 32) {
+ + ]
2316 [ + + ]: 30508 : auto key = ctx.FromPKBytes(in[0].second.begin(), in[0].second.end());
2317 [ + + ]: 30508 : if (!key) return {};
2318 [ + - ]: 30451 : ++in;
2319 [ + - + - ]: 60902 : constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::PK_K, Vector(std::move(*key))));
2320 : : break;
2321 : 4035 : }
2322 [ + + + + : 1934394 : 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) {
+ + + + +
+ - + +
+ ]
2323 [ + + ]: 17360 : auto key = ctx.FromPKHBytes(in[2].second.begin(), in[2].second.end());
[ + - # # ]
2324 [ + + ]: 17360 : if (!key) return {};
2325 [ + - ]: 17282 : in += 5;
2326 [ + - + - ]: 34564 : constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::PK_H, Vector(std::move(*key))));
2327 : : break;
2328 : 5416 : }
2329 : : // Time locks
2330 [ + + ]: 1917034 : std::optional<int64_t> num;
2331 [ + + + + : 1917034 : if (last - in >= 2 && in[0].first == OP_CHECKSEQUENCEVERIFY && (num = ParseScriptNumber(in[1]))) {
+ - + + ]
2332 [ + + ]: 24869 : in += 2;
2333 [ + + + - ]: 24869 : if (*num < 1 || *num > 0x7FFFFFFFL) return {};
2334 [ + - ]: 49590 : constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::OLDER, *num));
2335 : 24795 : break;
2336 : : }
2337 [ + + + + : 1892165 : if (last - in >= 2 && in[0].first == OP_CHECKLOCKTIMEVERIFY && (num = ParseScriptNumber(in[1]))) {
+ - + + ]
2338 : 22832 : in += 2;
2339 [ + - + - : 45664 : if (num < 1 || num > 0x7FFFFFFFL) return {};
+ - ]
2340 [ + - ]: 45572 : constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::AFTER, *num));
2341 : 22786 : break;
2342 : : }
2343 : : // Hashes
2344 [ + + + + : 1869349 : 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) {
+ + + + +
- + + + +
+ + + + ]
2345 [ + + - + : 24991 : if (in[2].first == OP_SHA256 && in[1].second.size() == 32) {
+ + ]
2346 [ + - ]: 10166 : constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::SHA256, in[1].second));
2347 : 5083 : in += 7;
2348 : : break;
2349 [ + + - + : 19908 : } else if (in[2].first == OP_RIPEMD160 && in[1].second.size() == 20) {
+ + ]
2350 [ + - ]: 12846 : constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::RIPEMD160, in[1].second));
2351 : 6423 : in += 7;
2352 : : break;
2353 [ + + - + : 13485 : } else if (in[2].first == OP_HASH256 && in[1].second.size() == 32) {
+ + ]
2354 [ + - ]: 14334 : constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::HASH256, in[1].second));
2355 : 7167 : in += 7;
2356 : : break;
2357 [ + + - + : 6318 : } else if (in[2].first == OP_HASH160 && in[1].second.size() == 20) {
+ + ]
2358 [ + - ]: 12604 : constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::HASH160, in[1].second));
2359 : 6302 : in += 7;
2360 : : break;
2361 : : }
2362 : : }
2363 : : // Multi
2364 [ + + + + ]: 1844358 : if (last - in >= 3 && in[0].first == OP_CHECKMULTISIG) {
2365 [ + + ]: 13299 : if (IsTapscript(ctx.MsContext())) return {};
2366 [ + - ]: 13220 : std::vector<Key> keys;
2367 [ + - ]: 13220 : const auto n = ParseScriptNumber(in[1]);
2368 [ + + + + ]: 13220 : if (!n || last - in < 3 + *n) return {};
2369 [ + + + + ]: 13174 : if (*n < 1 || *n > 20) return {};
2370 [ + + ]: 67773 : for (int i = 0; i < *n; ++i) {
2371 [ - + + + ]: 54627 : if (in[2 + i].second.size() != 33) return {};
2372 [ + - ]: 54617 : auto key = ctx.FromPKBytes(in[2 + i].second.begin(), in[2 + i].second.end());
2373 [ + + ]: 54617 : if (!key) return {};
2374 [ + - ]: 54616 : keys.push_back(std::move(*key));
2375 : : }
2376 [ + - ]: 13146 : const auto k = ParseScriptNumber(in[2 + *n]);
2377 [ + + + + : 13146 : if (!k || *k < 1 || *k > *n) return {};
+ + ]
2378 : 13129 : in += 3 + *n;
2379 [ + - ]: 13129 : std::reverse(keys.begin(), keys.end());
2380 [ + - ]: 26258 : constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::MULTI, std::move(keys), *k));
2381 : : break;
2382 : 13220 : }
2383 : : // Tapscript's equivalent of multi
2384 [ + + + + ]: 1831059 : if (last - in >= 4 && in[0].first == OP_NUMEQUAL) {
2385 [ + + ]: 3862 : if (!IsTapscript(ctx.MsContext())) return {};
2386 : : // The necessary threshold of signatures.
2387 [ + - ]: 3845 : const auto k = ParseScriptNumber(in[1]);
2388 [ + + ]: 3845 : if (!k) return {};
2389 [ + + + + ]: 3788 : if (*k < 1 || *k > MAX_PUBKEYS_PER_MULTI_A) return {};
2390 [ + + ]: 3715 : if (last - in < 2 + *k * 2) return {};
2391 [ + - ]: 3685 : std::vector<Key> keys;
2392 [ + - ]: 3685 : keys.reserve(*k);
2393 : : // Walk through the expected (pubkey, CHECKSIG[ADD]) pairs.
2394 [ - + ]: 140 : for (int pos = 2;; pos += 2) {
2395 [ + + ]: 34441 : if (last - in < pos + 2) return {};
2396 : : // Make sure it's indeed an x-only pubkey and a CHECKSIG[ADD], then parse the key.
2397 [ + + + + ]: 34421 : if (in[pos].first != OP_CHECKSIGADD && in[pos].first != OP_CHECKSIG) return {};
2398 [ - + + + ]: 34339 : if (in[pos + 1].second.size() != 32) return {};
2399 [ + + ]: 34292 : auto key = ctx.FromPKBytes(in[pos + 1].second.begin(), in[pos + 1].second.end());
2400 [ - + ]: 34292 : if (!key) return {};
2401 [ + - - + ]: 34292 : keys.push_back(std::move(*key));
2402 : : // Make sure early we don't parse an arbitrary large expression.
2403 [ - + ]: 34292 : if (keys.size() > MAX_PUBKEYS_PER_MULTI_A) return {};
2404 : : // OP_CHECKSIG means it was the last one to parse.
2405 [ + + ]: 34292 : if (in[pos].first == OP_CHECKSIG) break;
2406 : : }
2407 [ + + ]: 3536 : if (keys.size() < (size_t)*k) return {};
2408 : 3519 : in += 2 + keys.size() * 2;
2409 [ + - ]: 3519 : std::reverse(keys.begin(), keys.end());
2410 [ + - ]: 7038 : constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::MULTI_A, std::move(keys), *k));
2411 : : break;
2412 : 3685 : }
2413 : : /** In the following wrappers, we only need to push SINGLE_BKV_EXPR rather
2414 : : * than BKV_EXPR, because and_v commutes with these wrappers. For example,
2415 : : * c:and_v(X,Y) produces the same script as and_v(X,c:Y). */
2416 : : // c: wrapper
2417 [ + + ]: 1827197 : if (in[0].first == OP_CHECKSIG) {
2418 : 38669 : ++in;
2419 [ + - ]: 38669 : to_parse.emplace_back(DecodeContext::CHECK, -1, -1);
2420 [ + - ]: 38669 : to_parse.emplace_back(DecodeContext::SINGLE_BKV_EXPR, -1, -1);
2421 : : break;
2422 : : }
2423 : : // v: wrapper
2424 [ + + ]: 1788528 : if (in[0].first == OP_VERIFY) {
2425 : 189185 : ++in;
2426 [ + - ]: 189185 : to_parse.emplace_back(DecodeContext::VERIFY, -1, -1);
2427 [ + - ]: 189185 : to_parse.emplace_back(DecodeContext::SINGLE_BKV_EXPR, -1, -1);
2428 : : break;
2429 : : }
2430 : : // n: wrapper
2431 [ + + ]: 1599343 : if (in[0].first == OP_0NOTEQUAL) {
2432 : 806905 : ++in;
2433 [ + - ]: 806905 : to_parse.emplace_back(DecodeContext::ZERO_NOTEQUAL, -1, -1);
2434 [ + - ]: 806905 : to_parse.emplace_back(DecodeContext::SINGLE_BKV_EXPR, -1, -1);
2435 : : break;
2436 : : }
2437 : : // Thresh
2438 [ + + + + : 792438 : if (last - in >= 3 && in[0].first == OP_EQUAL && (num = ParseScriptNumber(in[1]))) {
+ - + + ]
2439 [ + + ]: 64755 : if (*num < 1) return {};
2440 [ + - ]: 64663 : in += 2;
2441 [ + - ]: 64663 : to_parse.emplace_back(DecodeContext::THRESH_W, 0, *num);
2442 : : break;
2443 : : }
2444 : : // OP_ENDIF can be WRAP_J, WRAP_D, ANDOR, OR_C, OR_D, or OR_I
2445 [ + + ]: 727683 : if (in[0].first == OP_ENDIF) {
2446 : 370747 : ++in;
2447 [ + - ]: 370747 : to_parse.emplace_back(DecodeContext::ENDIF, -1, -1);
2448 [ + - ]: 370747 : to_parse.emplace_back(DecodeContext::BKV_EXPR, -1, -1);
2449 : : break;
2450 : : }
2451 : : /** In and_b and or_b nodes, we only look for SINGLE_BKV_EXPR, because
2452 : : * or_b(and_v(X,Y),Z) has script [X] [Y] [Z] OP_BOOLOR, the same as
2453 : : * and_v(X,or_b(Y,Z)). In this example, the former of these is invalid as
2454 : : * miniscript, while the latter is valid. So we leave the and_v "outside"
2455 : : * while decoding. */
2456 : : // and_b
2457 [ + + ]: 356936 : if (in[0].first == OP_BOOLAND) {
2458 : 49552 : ++in;
2459 [ + - ]: 49552 : to_parse.emplace_back(DecodeContext::AND_B, -1, -1);
2460 [ + - ]: 49552 : to_parse.emplace_back(DecodeContext::SINGLE_BKV_EXPR, -1, -1);
2461 [ + - ]: 49552 : to_parse.emplace_back(DecodeContext::W_EXPR, -1, -1);
2462 : : break;
2463 : : }
2464 : : // or_b
2465 [ + + ]: 307384 : if (in[0].first == OP_BOOLOR) {
2466 : 304857 : ++in;
2467 [ + - ]: 304857 : to_parse.emplace_back(DecodeContext::OR_B, -1, -1);
2468 [ + - ]: 304857 : to_parse.emplace_back(DecodeContext::SINGLE_BKV_EXPR, -1, -1);
2469 [ + - ]: 304857 : to_parse.emplace_back(DecodeContext::W_EXPR, -1, -1);
2470 : : break;
2471 : : }
2472 : : // Unrecognised expression
2473 : 2527 : return {};
2474 : : }
2475 : 5762744 : case DecodeContext::BKV_EXPR: {
2476 [ + - ]: 5762744 : to_parse.emplace_back(DecodeContext::MAYBE_AND_V, -1, -1);
2477 [ + - ]: 5762744 : to_parse.emplace_back(DecodeContext::SINGLE_BKV_EXPR, -1, -1);
2478 : : break;
2479 : : }
2480 [ + + ]: 442462 : case DecodeContext::W_EXPR: {
2481 : : // a: wrapper
2482 [ + + ]: 442462 : if (in >= last) return {};
2483 [ + + ]: 442408 : if (in[0].first == OP_FROMALTSTACK) {
2484 : 135785 : ++in;
2485 [ + - ]: 135785 : to_parse.emplace_back(DecodeContext::ALT, -1, -1);
2486 : : } else {
2487 [ + - ]: 306623 : to_parse.emplace_back(DecodeContext::SWAP, -1, -1);
2488 : : }
2489 [ + - ]: 442408 : to_parse.emplace_back(DecodeContext::BKV_EXPR, -1, -1);
2490 : : break;
2491 : : }
2492 [ + + ]: 5355840 : case DecodeContext::MAYBE_AND_V: {
2493 : : // If we reach a potential AND_V top-level, check if the next part of the script could be another AND_V child
2494 : : // These op-codes cannot end any well-formed miniscript so cannot be used in an and_v node.
2495 [ + + + + : 5355840 : 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) {
+ + + + +
+ + + ]
2496 [ + - ]: 4723006 : to_parse.emplace_back(DecodeContext::AND_V, -1, -1);
2497 : : // BKV_EXPR can contain more AND_V nodes
2498 [ + - ]: 4723006 : to_parse.emplace_back(DecodeContext::BKV_EXPR, -1, -1);
2499 : : }
2500 : : break;
2501 : : }
2502 [ + + ]: 24000 : case DecodeContext::SWAP: {
2503 [ + + + + : 24000 : if (in >= last || in[0].first != OP_SWAP || constructed.empty()) return {};
+ - ]
2504 : 23940 : ++in;
2505 [ + - + - ]: 23940 : constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_S, Vector(std::move(constructed.back())));
2506 : 23940 : break;
2507 : : }
2508 [ + + ]: 123445 : case DecodeContext::ALT: {
2509 [ + + + + : 123445 : if (in >= last || in[0].first != OP_TOALTSTACK || constructed.empty()) return {};
+ - ]
2510 : 123381 : ++in;
2511 [ + - + - ]: 123381 : constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_A, Vector(std::move(constructed.back())));
2512 : 123381 : break;
2513 : : }
2514 : 34318 : case DecodeContext::CHECK: {
2515 [ - + ]: 34318 : if (constructed.empty()) return {};
2516 [ + - + - ]: 34318 : constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_C, Vector(std::move(constructed.back())));
2517 : 34318 : break;
2518 : : }
2519 : 14189 : case DecodeContext::DUP_IF: {
2520 [ - + ]: 14189 : if (constructed.empty()) return {};
2521 [ + - + - ]: 14189 : constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_D, Vector(std::move(constructed.back())));
2522 : 14189 : break;
2523 : : }
2524 : 170518 : case DecodeContext::VERIFY: {
2525 [ - + ]: 170518 : if (constructed.empty()) return {};
2526 [ + - + - ]: 170518 : constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_V, Vector(std::move(constructed.back())));
2527 : 170518 : break;
2528 : : }
2529 : 15889 : case DecodeContext::NON_ZERO: {
2530 [ - + ]: 15889 : if (constructed.empty()) return {};
2531 [ + - + - ]: 15889 : constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_J, Vector(std::move(constructed.back())));
2532 : 15889 : break;
2533 : : }
2534 : 724715 : case DecodeContext::ZERO_NOTEQUAL: {
2535 [ - + ]: 724715 : if (constructed.empty()) return {};
2536 [ + - + - ]: 724715 : constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::WRAP_N, Vector(std::move(constructed.back())));
2537 : 724715 : break;
2538 : : }
2539 [ - + ]: 123491 : case DecodeContext::AND_V: {
2540 [ - + ]: 123491 : if (constructed.size() < 2) return {};
2541 [ + - ]: 123491 : BuildBack(ctx.MsContext(), Fragment::AND_V, constructed, /*reverse=*/true);
2542 : : break;
2543 : : }
2544 [ - + ]: 29709 : case DecodeContext::AND_B: {
2545 [ - + ]: 29709 : if (constructed.size() < 2) return {};
2546 [ + - ]: 29709 : BuildBack(ctx.MsContext(), Fragment::AND_B, constructed, /*reverse=*/true);
2547 : : break;
2548 : : }
2549 [ - + ]: 31875 : case DecodeContext::OR_B: {
2550 [ - + ]: 31875 : if (constructed.size() < 2) return {};
2551 [ + - ]: 31875 : BuildBack(ctx.MsContext(), Fragment::OR_B, constructed, /*reverse=*/true);
2552 : : break;
2553 : : }
2554 [ - + ]: 17152 : case DecodeContext::OR_C: {
2555 [ - + ]: 17152 : if (constructed.size() < 2) return {};
2556 [ + - ]: 17152 : BuildBack(ctx.MsContext(), Fragment::OR_C, constructed, /*reverse=*/true);
2557 : : break;
2558 : : }
2559 [ - + ]: 29402 : case DecodeContext::OR_D: {
2560 [ - + ]: 29402 : if (constructed.size() < 2) return {};
2561 [ + - ]: 29402 : BuildBack(ctx.MsContext(), Fragment::OR_D, constructed, /*reverse=*/true);
2562 : : break;
2563 : : }
2564 [ - + ]: 43142 : case DecodeContext::ANDOR: {
2565 [ - + ]: 43142 : if (constructed.size() < 3) return {};
2566 : 43142 : NodeRef<Key> left = std::move(constructed.back());
2567 : 43142 : constructed.pop_back();
2568 : 43142 : NodeRef<Key> right = std::move(constructed.back());
2569 : 43142 : constructed.pop_back();
2570 [ + - ]: 43142 : NodeRef<Key> mid = std::move(constructed.back());
2571 [ + - + - ]: 43142 : constructed.back() = MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::ANDOR, Vector(std::move(left), std::move(mid), std::move(right)));
2572 : : break;
2573 : 43142 : }
2574 [ + + ]: 146888 : case DecodeContext::THRESH_W: {
2575 [ + + ]: 146888 : if (in >= last) return {};
2576 [ + + ]: 146885 : if (in[0].first == OP_ADD) {
2577 : 88053 : ++in;
2578 [ + - ]: 88053 : to_parse.emplace_back(DecodeContext::THRESH_W, n+1, k);
2579 [ + - ]: 88053 : to_parse.emplace_back(DecodeContext::W_EXPR, -1, -1);
2580 : : } else {
2581 [ + - ]: 58832 : to_parse.emplace_back(DecodeContext::THRESH_E, n+1, k);
2582 : : // All children of thresh have type modifier d, so cannot be and_v
2583 [ + - ]: 58832 : to_parse.emplace_back(DecodeContext::SINGLE_BKV_EXPR, -1, -1);
2584 : : }
2585 : : break;
2586 : : }
2587 : 55592 : case DecodeContext::THRESH_E: {
2588 [ + - + + : 111101 : if (k < 1 || k > n || constructed.size() < static_cast<size_t>(n)) return {};
+ - ]
2589 : 55509 : std::vector<NodeRef<Key>> subs;
2590 [ + + ]: 183825 : for (int i = 0; i < n; ++i) {
2591 : 128316 : NodeRef<Key> sub = std::move(constructed.back());
2592 [ + - ]: 128316 : constructed.pop_back();
2593 : 128316 : subs.push_back(std::move(sub));
2594 : : }
2595 [ + - ]: 111018 : constructed.push_back(MakeNodeRef<Key>(internal::NoDupCheck{}, ctx.MsContext(), Fragment::THRESH, std::move(subs), k));
2596 : : break;
2597 : 55509 : }
2598 [ + + ]: 278957 : case DecodeContext::ENDIF: {
2599 [ + + ]: 278957 : if (in >= last) return {};
2600 : :
2601 : : // could be andor or or_i
2602 [ + + ]: 278917 : if (in[0].first == OP_ELSE) {
2603 : 198763 : ++in;
2604 [ + - ]: 198763 : to_parse.emplace_back(DecodeContext::ENDIF_ELSE, -1, -1);
2605 [ + - ]: 198763 : to_parse.emplace_back(DecodeContext::BKV_EXPR, -1, -1);
2606 : : }
2607 : : // could be j: or d: wrapper
2608 [ + + ]: 80154 : else if (in[0].first == OP_IF) {
2609 [ + + + + ]: 30175 : if (last - in >= 2 && in[1].first == OP_DUP) {
2610 : 14189 : in += 2;
2611 [ + - ]: 14189 : to_parse.emplace_back(DecodeContext::DUP_IF, -1, -1);
2612 [ + + + + : 15986 : } else if (last - in >= 3 && in[1].first == OP_0NOTEQUAL && in[2].first == OP_SIZE) {
+ + ]
2613 : 15889 : in += 3;
2614 [ + - ]: 15889 : to_parse.emplace_back(DecodeContext::NON_ZERO, -1, -1);
2615 : : }
2616 : : else {
2617 : 97 : return {};
2618 : : }
2619 : : // could be or_c or or_d
2620 [ + + ]: 49979 : } else if (in[0].first == OP_NOTIF) {
2621 : 49935 : ++in;
2622 [ + - ]: 49935 : to_parse.emplace_back(DecodeContext::ENDIF_NOTIF, -1, -1);
2623 : : }
2624 : : else {
2625 : 44 : return {};
2626 : : }
2627 : : break;
2628 : : }
2629 [ + + ]: 49935 : case DecodeContext::ENDIF_NOTIF: {
2630 [ + + ]: 49935 : if (in >= last) return {};
2631 [ + + ]: 49927 : if (in[0].first == OP_IFDUP) {
2632 : 31233 : ++in;
2633 [ + - ]: 31233 : to_parse.emplace_back(DecodeContext::OR_D, -1, -1);
2634 : : } else {
2635 [ + - ]: 18694 : to_parse.emplace_back(DecodeContext::OR_C, -1, -1);
2636 : : }
2637 : : // or_c and or_d both require X to have type modifier d so, can't contain and_v
2638 [ + - ]: 49927 : to_parse.emplace_back(DecodeContext::SINGLE_BKV_EXPR, -1, -1);
2639 : : break;
2640 : : }
2641 [ + + ]: 188672 : case DecodeContext::ENDIF_ELSE: {
2642 [ + + ]: 188672 : if (in >= last) return {};
2643 [ + + ]: 188609 : if (in[0].first == OP_IF) {
2644 [ + - ]: 143948 : ++in;
2645 [ + - ]: 143948 : BuildBack(ctx.MsContext(), Fragment::OR_I, constructed, /*reverse=*/true);
2646 [ + + ]: 44661 : } else if (in[0].first == OP_NOTIF) {
2647 : 44629 : ++in;
2648 [ + - ]: 44629 : to_parse.emplace_back(DecodeContext::ANDOR, -1, -1);
2649 : : // andor requires X to have type modifier d, so it can't be and_v
2650 [ + - ]: 44629 : to_parse.emplace_back(DecodeContext::SINGLE_BKV_EXPR, -1, -1);
2651 : : } else {
2652 : 32 : return {};
2653 : : }
2654 : : break;
2655 : : }
2656 : : }
2657 : : }
2658 [ - + ]: 17056 : if (constructed.size() != 1) return {};
2659 [ + - ]: 17056 : NodeRef<Key> tl_node = std::move(constructed.front());
2660 [ + - ]: 17056 : tl_node->DuplicateKeyCheck(ctx);
2661 : : // Note that due to how ComputeType works (only assign the type to the node if the
2662 : : // subs' types are valid) this would fail if any node of tree is badly typed.
2663 [ + + ]: 17056 : if (!tl_node->IsValidTopLevel()) return {};
2664 : 16635 : return tl_node;
2665 : 27820 : }
2666 : :
2667 : : } // namespace internal
2668 : :
2669 : : template<typename Ctx>
2670 [ - + ][ - + : 26971 : inline NodeRef<typename Ctx::Key> FromString(const std::string& str, const Ctx& ctx) {
- + - + ]
2671 [ + - ][ + - : 26971 : return internal::Parse<typename Ctx::Key>(str, ctx);
+ - + - ]
2672 : : }
2673 : :
2674 : : template<typename Ctx>
2675 : 31027 : inline NodeRef<typename Ctx::Key> FromScript(const CScript& script, const Ctx& ctx) {
2676 : : using namespace internal;
2677 : : // A too large Script is necessarily invalid, don't bother parsing it.
2678 [ + + + + ]: 80662 : if (script.size() > MaxScriptSize(ctx.MsContext())) return {};
2679 [ + + ]: 31023 : auto decomposed = DecomposeScript(script);
2680 [ + + ]: 31023 : if (!decomposed) return {};
2681 [ + - ]: 27820 : auto it = decomposed->begin();
2682 [ + - ]: 27820 : auto ret = DecodeScript<typename Ctx::Key>(it, decomposed->end(), ctx);
2683 [ + + ]: 27820 : if (!ret) return {};
2684 [ + + ]: 16635 : if (it != decomposed->end()) return {};
2685 : 16462 : return ret;
2686 : 58843 : }
2687 : :
2688 : : } // namespace miniscript
2689 : :
2690 : : #endif // BITCOIN_SCRIPT_MINISCRIPT_H
|