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