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