LCOV - code coverage report
Current view: top level - src/script - miniscript.h (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 99.4 % 1244 1237
Test Date: 2024-12-04 04:00:22 Functions: 96.1 % 229 220
Branches: 57.3 % 4823 2765

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

Generated by: LCOV version 2.0-1