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