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