LCOV - code coverage report
Current view: top level - src/script - descriptor.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 92.3 % 1757 1622
Test Date: 2026-06-05 07:30:14 Functions: 86.0 % 236 203
Branches: 62.4 % 3005 1876

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2018-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                 :             : #include <script/descriptor.h>
       6                 :             : 
       7                 :             : #include <addresstype.h>
       8                 :             : #include <attributes.h>
       9                 :             : #include <consensus/consensus.h>
      10                 :             : #include <crypto/hex_base.h>
      11                 :             : #include <crypto/sha256.h>
      12                 :             : #include <hash.h>
      13                 :             : #include <key.h>
      14                 :             : #include <key_io.h>
      15                 :             : #include <musig.h>
      16                 :             : #include <primitives/transaction.h>
      17                 :             : #include <pubkey.h>
      18                 :             : #include <script/interpreter.h>
      19                 :             : #include <script/keyorigin.h>
      20                 :             : #include <script/miniscript.h>
      21                 :             : #include <script/parsing.h>
      22                 :             : #include <script/script.h>
      23                 :             : #include <script/signingprovider.h>
      24                 :             : #include <script/solver.h>
      25                 :             : #include <serialize.h>
      26                 :             : #include <tinyformat.h>
      27                 :             : #include <uint256.h>
      28                 :             : #include <util/bip32.h>
      29                 :             : #include <util/check.h>
      30                 :             : #include <util/strencodings.h>
      31                 :             : #include <util/string.h>
      32                 :             : #include <util/vector.h>
      33                 :             : 
      34                 :             : #include <algorithm>
      35                 :             : #include <iterator>
      36                 :             : #include <map>
      37                 :             : #include <memory>
      38                 :             : #include <numeric>
      39                 :             : #include <optional>
      40                 :             : #include <span>
      41                 :             : #include <stdexcept>
      42                 :             : #include <string>
      43                 :             : #include <tuple>
      44                 :             : #include <unordered_set>
      45                 :             : #include <utility>
      46                 :             : #include <vector>
      47                 :             : 
      48                 :             : using util::Split;
      49                 :             : 
      50                 :             : namespace {
      51                 :             : 
      52                 :             : ////////////////////////////////////////////////////////////////////////////
      53                 :             : // Checksum                                                               //
      54                 :             : ////////////////////////////////////////////////////////////////////////////
      55                 :             : 
      56                 :             : // This section implements a checksum algorithm for descriptors with the
      57                 :             : // following properties:
      58                 :             : // * Mistakes in a descriptor string are measured in "symbol errors". The higher
      59                 :             : //   the number of symbol errors, the harder it is to detect:
      60                 :             : //   * An error substituting a character from 0123456789()[],'/*abcdefgh@:$%{} for
      61                 :             : //     another in that set always counts as 1 symbol error.
      62                 :             : //     * Note that hex encoded keys are covered by these characters. Xprvs and
      63                 :             : //       xpubs use other characters too, but already have their own checksum
      64                 :             : //       mechanism.
      65                 :             : //     * Function names like "multi()" use other characters, but mistakes in
      66                 :             : //       these would generally result in an unparsable descriptor.
      67                 :             : //   * A case error always counts as 1 symbol error.
      68                 :             : //   * Any other 1 character substitution error counts as 1 or 2 symbol errors.
      69                 :             : // * Any 1 symbol error is always detected.
      70                 :             : // * Any 2 or 3 symbol error in a descriptor of up to 49154 characters is always detected.
      71                 :             : // * Any 4 symbol error in a descriptor of up to 507 characters is always detected.
      72                 :             : // * Any 5 symbol error in a descriptor of up to 77 characters is always detected.
      73                 :             : // * Is optimized to minimize the chance a 5 symbol error in a descriptor up to 387 characters is undetected
      74                 :             : // * Random errors have a chance of 1 in 2**40 of being undetected.
      75                 :             : //
      76                 :             : // These properties are achieved by expanding every group of 3 (non checksum) characters into
      77                 :             : // 4 GF(32) symbols, over which a cyclic code is defined.
      78                 :             : 
      79                 :             : /*
      80                 :             :  * Interprets c as 8 groups of 5 bits which are the coefficients of a degree 8 polynomial over GF(32),
      81                 :             :  * multiplies that polynomial by x, computes its remainder modulo a generator, and adds the constant term val.
      82                 :             :  *
      83                 :             :  * This generator is G(x) = x^8 + {30}x^7 + {23}x^6 + {15}x^5 + {14}x^4 + {10}x^3 + {6}x^2 + {12}x + {9}.
      84                 :             :  * It is chosen to define an cyclic error detecting code which is selected by:
      85                 :             :  * - Starting from all BCH codes over GF(32) of degree 8 and below, which by construction guarantee detecting
      86                 :             :  *   3 errors in windows up to 19000 symbols.
      87                 :             :  * - Taking all those generators, and for degree 7 ones, extend them to degree 8 by adding all degree-1 factors.
      88                 :             :  * - Selecting just the set of generators that guarantee detecting 4 errors in a window of length 512.
      89                 :             :  * - Selecting one of those with best worst-case behavior for 5 errors in windows of length up to 512.
      90                 :             :  *
      91                 :             :  * The generator and the constants to implement it can be verified using this Sage code:
      92                 :             :  *   B = GF(2) # Binary field
      93                 :             :  *   BP.<b> = B[] # Polynomials over the binary field
      94                 :             :  *   F_mod = b**5 + b**3 + 1
      95                 :             :  *   F.<f> = GF(32, modulus=F_mod, repr='int') # GF(32) definition
      96                 :             :  *   FP.<x> = F[] # Polynomials over GF(32)
      97                 :             :  *   E_mod = x**3 + x + F.fetch_int(8)
      98                 :             :  *   E.<e> = F.extension(E_mod) # Extension field definition
      99                 :             :  *   alpha = e**2743 # Choice of an element in extension field
     100                 :             :  *   for p in divisors(E.order() - 1): # Verify alpha has order 32767.
     101                 :             :  *       assert((alpha**p == 1) == (p % 32767 == 0))
     102                 :             :  *   G = lcm([(alpha**i).minpoly() for i in [1056,1057,1058]] + [x + 1])
     103                 :             :  *   print(G) # Print out the generator
     104                 :             :  *   for i in [1,2,4,8,16]: # Print out {1,2,4,8,16}*(G mod x^8), packed in hex integers.
     105                 :             :  *       v = 0
     106                 :             :  *       for coef in reversed((F.fetch_int(i)*(G % x**8)).coefficients(sparse=True)):
     107                 :             :  *           v = v*32 + coef.integer_representation()
     108                 :             :  *       print("0x%x" % v)
     109                 :             :  */
     110                 :   338145185 : uint64_t PolyMod(uint64_t c, int val)
     111                 :             : {
     112                 :   338145185 :     uint8_t c0 = c >> 35;
     113                 :   338145185 :     c = ((c & 0x7ffffffff) << 5) ^ val;
     114         [ +  + ]:   338145185 :     if (c0 & 1) c ^= 0xf5dee51989;
     115         [ +  + ]:   338145185 :     if (c0 & 2) c ^= 0xa9fdca3312;
     116         [ +  + ]:   338145185 :     if (c0 & 4) c ^= 0x1bab10e32d;
     117         [ +  + ]:   338145185 :     if (c0 & 8) c ^= 0x3706b1677a;
     118         [ +  + ]:   338145185 :     if (c0 & 16) c ^= 0x644d626ffd;
     119                 :   338145185 :     return c;
     120                 :             : }
     121                 :             : 
     122                 :      290183 : std::string DescriptorChecksum(const std::span<const char>& span)
     123                 :             : {
     124                 :             :     /** A character set designed such that:
     125                 :             :      *  - The most common 'unprotected' descriptor characters (hex, keypaths) are in the first group of 32.
     126                 :             :      *  - Case errors cause an offset that's a multiple of 32.
     127                 :             :      *  - As many alphabetic characters are in the same group (while following the above restrictions).
     128                 :             :      *
     129                 :             :      * If p(x) gives the position of a character c in this character set, every group of 3 characters
     130                 :             :      * (a,b,c) is encoded as the 4 symbols (p(a) & 31, p(b) & 31, p(c) & 31, (p(a) / 32) + 3 * (p(b) / 32) + 9 * (p(c) / 32).
     131                 :             :      * This means that changes that only affect the lower 5 bits of the position, or only the higher 2 bits, will just
     132                 :             :      * affect a single symbol.
     133                 :             :      *
     134                 :             :      * As a result, within-group-of-32 errors count as 1 symbol, as do cross-group errors that don't affect
     135                 :             :      * the position within the groups.
     136                 :             :      */
     137                 :      290183 :     static const std::string INPUT_CHARSET =
     138                 :             :         "0123456789()[],'/*abcdefgh@:$%{}"
     139                 :             :         "IJKLMNOPQRSTUVWXYZ&+-.;<=>?!^_|~"
     140   [ +  +  +  -  :      290683 :         "ijklmnopqrstuvwxyzABCDEFGH`#\"\\ ";
                   +  - ]
     141                 :             : 
     142                 :             :     /** The character set for the checksum itself (same as bech32). */
     143   [ +  +  +  -  :      290683 :     static const std::string CHECKSUM_CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
                   +  - ]
     144                 :             : 
     145                 :      290183 :     uint64_t c = 1;
     146                 :      290183 :     int cls = 0;
     147                 :      290183 :     int clscount = 0;
     148         [ +  + ]:   252082401 :     for (auto ch : span) {
     149                 :   251792219 :         auto pos = INPUT_CHARSET.find(ch);
     150         [ +  + ]:   251792219 :         if (pos == std::string::npos) return "";
     151                 :   251792218 :         c = PolyMod(c, pos & 31); // Emit a symbol for the position inside the group, for every character.
     152                 :   251792218 :         cls = cls * 3 + (pos >> 5); // Accumulate the group numbers
     153         [ +  + ]:   251792218 :         if (++clscount == 3) {
     154                 :             :             // Emit an extra symbol representing the group numbers, for every 3 characters.
     155                 :    83817146 :             c = PolyMod(c, cls);
     156                 :    83817146 :             cls = 0;
     157                 :    83817146 :             clscount = 0;
     158                 :             :         }
     159                 :             :     }
     160         [ +  + ]:      290182 :     if (clscount > 0) c = PolyMod(c, cls);
     161         [ +  + ]:     2611638 :     for (int j = 0; j < 8; ++j) c = PolyMod(c, 0); // Shift further to determine the checksum.
     162                 :      290182 :     c ^= 1; // Prevent appending zeroes from not affecting the checksum.
     163                 :             : 
     164                 :      290182 :     std::string ret(8, ' ');
     165         [ +  + ]:     2611638 :     for (int j = 0; j < 8; ++j) ret[j] = CHECKSUM_CHARSET[(c >> (5 * (7 - j))) & 31];
     166                 :      290182 :     return ret;
     167                 :      290182 : }
     168                 :             : 
     169   [ -  +  +  -  :      558680 : std::string AddChecksum(const std::string& str) { return str + "#" + DescriptorChecksum(str); }
                   +  - ]
     170                 :             : 
     171                 :             : ////////////////////////////////////////////////////////////////////////////
     172                 :             : // Internal representation                                                //
     173                 :             : ////////////////////////////////////////////////////////////////////////////
     174                 :             : 
     175                 :             : typedef std::vector<uint32_t> KeyPath;
     176                 :             : 
     177                 :             : /** Interface for public key objects in descriptors. */
     178                 :             : struct PubkeyProvider
     179                 :             : {
     180                 :             : public:
     181                 :             :     //! Index of this key expression in the descriptor
     182                 :             :     //! E.g. If this PubkeyProvider is key1 in multi(2, key1, key2, key3), then m_expr_index = 0
     183                 :             :     const uint32_t m_expr_index;
     184                 :             : 
     185                 :      939459 :     explicit PubkeyProvider(uint32_t exp_index) : m_expr_index(exp_index) {}
     186                 :             : 
     187                 :         343 :     virtual ~PubkeyProvider() = default;
     188                 :             : 
     189                 :             :     /** Compare two public keys represented by this provider.
     190                 :             :      * Used by the Miniscript descriptors to check for duplicate keys in the script.
     191                 :             :      */
     192                 :        4494 :     bool operator<(PubkeyProvider& other) const {
     193                 :        4494 :         FlatSigningProvider dummy;
     194                 :             : 
     195         [ +  - ]:        4494 :         std::optional<CPubKey> a = GetPubKey(0, dummy, dummy);
     196         [ +  - ]:        4494 :         std::optional<CPubKey> b = other.GetPubKey(0, dummy, dummy);
     197                 :             : 
     198                 :        4494 :         return a < b;
     199                 :        4494 :     }
     200                 :             : 
     201                 :             :     /** Derive a public key and put it into out.
     202                 :             :      *  read_cache is the cache to read keys from (if not nullptr)
     203                 :             :      *  write_cache is the cache to write keys to (if not nullptr)
     204                 :             :      *  Caches are not exclusive but this is not tested. Currently we use them exclusively
     205                 :             :      */
     206                 :             :     virtual std::optional<CPubKey> GetPubKey(int pos, const SigningProvider& arg, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const = 0;
     207                 :             : 
     208                 :             :     /** Whether this represent multiple public keys at different positions. */
     209                 :             :     virtual bool IsRange() const = 0;
     210                 :             : 
     211                 :             :     /** Get the size of the generated public key(s) in bytes (33 or 65). */
     212                 :             :     virtual size_t GetSize() const = 0;
     213                 :             : 
     214                 :             :     enum class StringType {
     215                 :             :         PUBLIC,
     216                 :             :         COMPAT // string calculation that mustn't change over time to stay compatible with previous software versions
     217                 :             :     };
     218                 :             : 
     219                 :             :     /** Get the descriptor string form. */
     220                 :             :     virtual std::string ToString(StringType type=StringType::PUBLIC) const = 0;
     221                 :             : 
     222                 :             :     /** Get the descriptor string form including private data (if available in arg).
     223                 :             :      *  If the private data is not available, the output string in the "out" parameter
     224                 :             :      *  will not contain any private key information,
     225                 :             :      *  and this function will return "false".
     226                 :             :      */
     227                 :             :     virtual bool ToPrivateString(const SigningProvider& arg, std::string& out) const = 0;
     228                 :             : 
     229                 :             :     /** Get the descriptor string form with the xpub at the last hardened derivation,
     230                 :             :      *  and always use h for hardened derivation.
     231                 :             :      */
     232                 :             :     virtual bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache = nullptr) const = 0;
     233                 :             : 
     234                 :             :     /** Derive a private key, if private data is available in arg and put it into out. */
     235                 :             :     virtual void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const = 0;
     236                 :             : 
     237                 :             :     /** Return the non-extended public key for this PubkeyProvider, if it has one. */
     238                 :             :     virtual std::optional<CPubKey> GetRootPubKey() const = 0;
     239                 :             :     /** Return the extended public key for this PubkeyProvider, if it has one. */
     240                 :             :     virtual std::optional<CExtPubKey> GetRootExtPubKey() const = 0;
     241                 :             : 
     242                 :             :     /** Make a deep copy of this PubkeyProvider */
     243                 :             :     virtual std::unique_ptr<PubkeyProvider> Clone() const = 0;
     244                 :             : 
     245                 :             :     /** Whether this PubkeyProvider is a BIP 32 extended key that can be derived from */
     246                 :             :     virtual bool IsBIP32() const = 0;
     247                 :             : 
     248                 :             :     /** Get the count of keys known by this PubkeyProvider. Usually one, but may be more for key aggregation schemes */
     249                 :         458 :     virtual size_t GetKeyCount() const { return 1; }
     250                 :             : };
     251                 :             : 
     252                 :             : class OriginPubkeyProvider final : public PubkeyProvider
     253                 :             : {
     254                 :             :     KeyOriginInfo m_origin;
     255                 :             :     std::unique_ptr<PubkeyProvider> m_provider;
     256                 :             :     bool m_apostrophe;
     257                 :             : 
     258                 :      116794 :     std::string OriginString(StringType type, bool normalized=false) const
     259                 :             :     {
     260                 :             :         // If StringType==COMPAT, always use the apostrophe to stay compatible with previous versions
     261   [ +  +  +  +  :      116794 :         bool use_apostrophe = (!normalized && m_apostrophe) || type == StringType::COMPAT;
                   +  + ]
     262   [ +  -  +  - ]:      233588 :         return HexStr(m_origin.fingerprint) + FormatHDKeypath(m_origin.path, use_apostrophe);
     263                 :             :     }
     264                 :             : 
     265                 :             : public:
     266                 :      449728 :     OriginPubkeyProvider(uint32_t exp_index, KeyOriginInfo info, std::unique_ptr<PubkeyProvider> provider, bool apostrophe) : PubkeyProvider(exp_index), m_origin(std::move(info)), m_provider(std::move(provider)), m_apostrophe(apostrophe) {}
     267                 :       61946 :     std::optional<CPubKey> GetPubKey(int pos, const SigningProvider& arg, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
     268                 :             :     {
     269                 :       61946 :         std::optional<CPubKey> pub = m_provider->GetPubKey(pos, arg, out, read_cache, write_cache);
     270         [ +  + ]:       61946 :         if (!pub) return std::nullopt;
     271         [ -  + ]:       61776 :         Assert(out.pubkeys.contains(pub->GetID()));
     272         [ -  + ]:       61776 :         auto& [pubkey, suborigin] = out.origins[pub->GetID()];
     273         [ -  + ]:       61776 :         Assert(pubkey == *pub); // m_provider must have a valid origin by this point.
     274                 :       61776 :         std::copy(std::begin(m_origin.fingerprint), std::end(m_origin.fingerprint), suborigin.fingerprint);
     275                 :       61776 :         suborigin.path.insert(suborigin.path.begin(), m_origin.path.begin(), m_origin.path.end());
     276                 :       61776 :         return pub;
     277                 :             :     }
     278                 :       10370 :     bool IsRange() const override { return m_provider->IsRange(); }
     279                 :       62378 :     size_t GetSize() const override { return m_provider->GetSize(); }
     280                 :         172 :     bool IsBIP32() const override { return m_provider->IsBIP32(); }
     281   [ +  -  +  -  :      348879 :     std::string ToString(StringType type) const override { return "[" + OriginString(type) + "]" + m_provider->ToString(type); }
                   +  - ]
     282                 :          93 :     bool ToPrivateString(const SigningProvider& arg, std::string& ret) const override
     283                 :             :     {
     284         [ +  - ]:          93 :         std::string sub;
     285         [ +  - ]:          93 :         bool has_priv_key{m_provider->ToPrivateString(arg, sub)};
     286   [ +  -  +  -  :         186 :         ret = "[" + OriginString(StringType::PUBLIC) + "]" + std::move(sub);
                   +  - ]
     287                 :          93 :         return has_priv_key;
     288                 :          93 :     }
     289                 :         408 :     bool ToNormalizedString(const SigningProvider& arg, std::string& ret, const DescriptorCache* cache) const override
     290                 :             :     {
     291         [ +  - ]:         408 :         std::string sub;
     292   [ +  -  +  - ]:         408 :         if (!m_provider->ToNormalizedString(arg, sub, cache)) return false;
     293                 :             :         // If m_provider is a BIP32PubkeyProvider, we may get a string formatted like a OriginPubkeyProvider
     294                 :             :         // In that case, we need to strip out the leading square bracket and fingerprint from the substring,
     295                 :             :         // and append that to our own origin string.
     296         [ +  + ]:         408 :         if (sub[0] == '[') {
     297         [ +  - ]:           4 :             sub = sub.substr(9);
     298   [ +  -  +  -  :           4 :             ret = "[" + OriginString(StringType::PUBLIC, /*normalized=*/true) + std::move(sub);
                   +  - ]
     299                 :             :         } else {
     300   [ +  -  +  -  :         808 :             ret = "[" + OriginString(StringType::PUBLIC, /*normalized=*/true) + "]" + std::move(sub);
                   +  - ]
     301                 :             :         }
     302                 :             :         return true;
     303                 :         408 :     }
     304                 :        3436 :     void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const override
     305                 :             :     {
     306                 :        3436 :         m_provider->GetPrivKey(pos, arg, out);
     307                 :        3436 :     }
     308                 :           0 :     std::optional<CPubKey> GetRootPubKey() const override
     309                 :             :     {
     310                 :           0 :         return m_provider->GetRootPubKey();
     311                 :             :     }
     312                 :           0 :     std::optional<CExtPubKey> GetRootExtPubKey() const override
     313                 :             :     {
     314                 :           0 :         return m_provider->GetRootExtPubKey();
     315                 :             :     }
     316                 :         110 :     std::unique_ptr<PubkeyProvider> Clone() const override
     317                 :             :     {
     318   [ +  -  -  + ]:         110 :         return std::make_unique<OriginPubkeyProvider>(m_expr_index, m_origin, m_provider->Clone(), m_apostrophe);
     319                 :             :     }
     320                 :             : };
     321                 :             : 
     322                 :             : /** An object representing a parsed constant public key in a descriptor. */
     323                 :         343 : class ConstPubkeyProvider final : public PubkeyProvider
     324                 :             : {
     325                 :             :     CPubKey m_pubkey;
     326                 :             :     bool m_xonly;
     327                 :             : 
     328                 :       56995 :     std::optional<CKey> GetPrivKey(const SigningProvider& arg) const
     329                 :             :     {
     330                 :       56995 :         CKey key;
     331   [ +  +  +  -  :       63262 :         if (!(m_xonly ? arg.GetKeyByXOnly(XOnlyPubKey(m_pubkey), key) :
                   +  + ]
     332   [ +  -  +  - ]:       57271 :                         arg.GetKey(m_pubkey.GetID(), key))) return std::nullopt;
     333                 :        5991 :         return key;
     334                 :       56995 :     }
     335                 :             : 
     336                 :             : public:
     337                 :      480610 :     ConstPubkeyProvider(uint32_t exp_index, const CPubKey& pubkey, bool xonly) : PubkeyProvider(exp_index), m_pubkey(pubkey), m_xonly(xonly) {}
     338                 :     1012546 :     std::optional<CPubKey> GetPubKey(int pos, const SigningProvider&, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
     339                 :             :     {
     340         [ +  - ]:     1012546 :         KeyOriginInfo info;
     341         [ +  - ]:     1012546 :         CKeyID keyid = m_pubkey.GetID();
     342                 :     1012546 :         std::copy(keyid.begin(), keyid.begin() + sizeof(info.fingerprint), info.fingerprint);
     343   [ +  -  +  - ]:     1012546 :         out.origins.emplace(keyid, std::make_pair(m_pubkey, info));
     344         [ +  - ]:     1012546 :         out.pubkeys.emplace(keyid, m_pubkey);
     345                 :     1012546 :         return m_pubkey;
     346                 :     1012546 :     }
     347                 :       24649 :     bool IsRange() const override { return false; }
     348                 :       76805 :     size_t GetSize() const override { return m_pubkey.size(); }
     349                 :           8 :     bool IsBIP32() const override { return false; }
     350   [ +  +  +  - ]:      389236 :     std::string ToString(StringType type) const override { return m_xonly ? HexStr(m_pubkey).substr(2) : HexStr(m_pubkey); }
     351                 :         423 :     bool ToPrivateString(const SigningProvider& arg, std::string& ret) const override
     352                 :             :     {
     353                 :         423 :         std::optional<CKey> key = GetPrivKey(arg);
     354         [ +  + ]:         423 :         if (!key) {
     355         [ +  - ]:         218 :             ret = ToString(StringType::PUBLIC);
     356                 :         218 :             return false;
     357                 :             :         }
     358         [ +  - ]:         205 :         ret = EncodeSecret(*key);
     359                 :         205 :         return true;
     360                 :         423 :     }
     361                 :       10179 :     bool ToNormalizedString(const SigningProvider& arg, std::string& ret, const DescriptorCache* cache) const override
     362                 :             :     {
     363                 :       10179 :         ret = ToString(StringType::PUBLIC);
     364                 :       10179 :         return true;
     365                 :             :     }
     366                 :       56572 :     void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const override
     367                 :             :     {
     368                 :       56572 :         std::optional<CKey> key = GetPrivKey(arg);
     369         [ +  + ]:       56572 :         if (!key) return;
     370   [ +  -  +  -  :        5786 :         out.keys.emplace(key->GetPubKey().GetID(), *key);
                   +  - ]
     371                 :       56572 :     }
     372                 :          12 :     std::optional<CPubKey> GetRootPubKey() const override
     373                 :             :     {
     374                 :          12 :         return m_pubkey;
     375                 :             :     }
     376                 :          12 :     std::optional<CExtPubKey> GetRootExtPubKey() const override
     377                 :             :     {
     378                 :          12 :         return std::nullopt;
     379                 :             :     }
     380                 :          27 :     std::unique_ptr<PubkeyProvider> Clone() const override
     381                 :             :     {
     382                 :          27 :         return std::make_unique<ConstPubkeyProvider>(m_expr_index, m_pubkey, m_xonly);
     383                 :             :     }
     384                 :             : };
     385                 :             : 
     386                 :             : enum class DeriveType {
     387                 :             :     NON_RANGED,
     388                 :             :     UNHARDENED_RANGED,
     389                 :             :     HARDENED_RANGED,
     390                 :             : };
     391                 :             : 
     392                 :             : /** An object representing a parsed extended public key in a descriptor. */
     393                 :             : class BIP32PubkeyProvider final : public PubkeyProvider
     394                 :             : {
     395                 :             :     // Root xpub, path, and final derivation step type being used, if any
     396                 :             :     CExtPubKey m_root_extkey;
     397                 :             :     KeyPath m_path;
     398                 :             :     DeriveType m_derive;
     399                 :             :     // Whether ' or h is used in harded derivation
     400                 :             :     bool m_apostrophe;
     401                 :             : 
     402                 :       39825 :     bool GetExtKey(const SigningProvider& arg, CExtKey& ret) const
     403                 :             :     {
     404                 :       39825 :         CKey key;
     405   [ +  -  +  -  :       39825 :         if (!arg.GetKey(m_root_extkey.pubkey.GetID(), key)) return false;
                   +  + ]
     406                 :       34782 :         ret.nDepth = m_root_extkey.nDepth;
     407                 :       34782 :         std::copy(m_root_extkey.vchFingerprint, m_root_extkey.vchFingerprint + sizeof(ret.vchFingerprint), ret.vchFingerprint);
     408                 :       34782 :         ret.nChild = m_root_extkey.nChild;
     409                 :       34782 :         ret.chaincode = m_root_extkey.chaincode;
     410         [ +  - ]:       34782 :         ret.key = key;
     411                 :             :         return true;
     412                 :       39825 :     }
     413                 :             : 
     414                 :             :     // Derives the last xprv
     415                 :       38493 :     bool GetDerivedExtKey(const SigningProvider& arg, CExtKey& xprv, CExtKey& last_hardened) const
     416                 :             :     {
     417         [ +  + ]:       38493 :         if (!GetExtKey(arg, xprv)) return false;
     418         [ +  + ]:      110807 :         for (auto entry : m_path) {
     419         [ +  - ]:       76994 :             if (!xprv.Derive(xprv, entry)) return false;
     420         [ +  + ]:       76994 :             if (entry >> 31) {
     421                 :       60353 :                 last_hardened = xprv;
     422                 :             :             }
     423                 :             :         }
     424                 :             :         return true;
     425                 :             :     }
     426                 :             : 
     427                 :       38650 :     bool IsHardened() const
     428                 :             :     {
     429         [ +  + ]:       38650 :         if (m_derive == DeriveType::HARDENED_RANGED) return true;
     430         [ +  + ]:       40215 :         for (auto entry : m_path) {
     431         [ +  + ]:       26604 :             if (entry >> 31) return true;
     432                 :             :         }
     433                 :             :         return false;
     434                 :             :     }
     435                 :             : 
     436                 :             : public:
     437                 :        8860 :     BIP32PubkeyProvider(uint32_t exp_index, const CExtPubKey& extkey, KeyPath path, DeriveType derive, bool apostrophe) : PubkeyProvider(exp_index), m_root_extkey(extkey), m_path(std::move(path)), m_derive(derive), m_apostrophe(apostrophe) {}
     438                 :      244965 :     bool IsRange() const override { return m_derive != DeriveType::NON_RANGED; }
     439                 :         562 :     size_t GetSize() const override { return 33; }
     440                 :         369 :     bool IsBIP32() const override { return true; }
     441                 :      689414 :     std::optional<CPubKey> GetPubKey(int pos, const SigningProvider& arg, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
     442                 :             :     {
     443         [ +  - ]:      689414 :         KeyOriginInfo info;
     444         [ +  - ]:      689414 :         CKeyID keyid = m_root_extkey.pubkey.GetID();
     445                 :      689414 :         std::copy(keyid.begin(), keyid.begin() + sizeof(info.fingerprint), info.fingerprint);
     446         [ +  - ]:      689414 :         info.path = m_path;
     447   [ +  +  +  - ]:      689414 :         if (m_derive == DeriveType::UNHARDENED_RANGED) info.path.push_back((uint32_t)pos);
     448   [ +  +  +  - ]:      689414 :         if (m_derive == DeriveType::HARDENED_RANGED) info.path.push_back(((uint32_t)pos) | 0x80000000L);
     449                 :             : 
     450                 :             :         // Derive keys or fetch them from cache
     451                 :      689414 :         CExtPubKey final_extkey = m_root_extkey;
     452                 :      689414 :         CExtPubKey parent_extkey = m_root_extkey;
     453         [ +  + ]:      689414 :         CExtPubKey last_hardened_extkey;
     454                 :      689414 :         bool der = true;
     455         [ +  + ]:      689414 :         if (read_cache) {
     456   [ +  -  +  + ]:      650764 :             if (!read_cache->GetCachedDerivedExtPubKey(m_expr_index, pos, final_extkey)) {
     457         [ +  + ]:      646384 :                 if (m_derive == DeriveType::HARDENED_RANGED) return std::nullopt;
     458                 :             :                 // Try to get the derivation parent
     459   [ +  -  +  + ]:      636261 :                 if (!read_cache->GetCachedParentExtPubKey(m_expr_index, parent_extkey)) return std::nullopt;
     460                 :      632040 :                 final_extkey = parent_extkey;
     461   [ +  +  +  - ]:      632040 :                 if (m_derive == DeriveType::UNHARDENED_RANGED) der = parent_extkey.Derive(final_extkey, pos);
     462                 :             :             }
     463         [ +  + ]:       38650 :         } else if (IsHardened()) {
     464         [ +  - ]:       25039 :             CExtKey xprv;
     465                 :       25039 :             CExtKey lh_xprv;
     466   [ +  -  +  + ]:       25039 :             if (!GetDerivedExtKey(arg, xprv, lh_xprv)) return std::nullopt;
     467         [ +  - ]:       24919 :             parent_extkey = xprv.Neuter();
     468   [ +  +  +  - ]:       24919 :             if (m_derive == DeriveType::UNHARDENED_RANGED) der = xprv.Derive(xprv, pos);
     469   [ +  +  +  - ]:       24919 :             if (m_derive == DeriveType::HARDENED_RANGED) der = xprv.Derive(xprv, pos | 0x80000000UL);
     470         [ +  - ]:       24919 :             final_extkey = xprv.Neuter();
     471         [ +  + ]:       24919 :             if (lh_xprv.key.IsValid()) {
     472         [ +  - ]:       21888 :                 last_hardened_extkey = lh_xprv.Neuter();
     473                 :             :             }
     474                 :       25039 :         } else {
     475         [ +  + ]:       31344 :             for (auto entry : m_path) {
     476   [ +  -  -  + ]:       17733 :                 if (!parent_extkey.Derive(parent_extkey, entry)) return std::nullopt;
     477                 :             :             }
     478                 :       13611 :             final_extkey = parent_extkey;
     479   [ +  +  +  - ]:       13611 :             if (m_derive == DeriveType::UNHARDENED_RANGED) der = parent_extkey.Derive(final_extkey, pos);
     480         [ -  + ]:       13611 :             assert(m_derive != DeriveType::HARDENED_RANGED);
     481                 :             :         }
     482         [ -  + ]:      668441 :         if (!der) return std::nullopt;
     483                 :             : 
     484   [ +  -  +  -  :      674950 :         out.origins.emplace(final_extkey.pubkey.GetID(), std::make_pair(final_extkey.pubkey, info));
                   +  - ]
     485   [ +  -  +  - ]:      674950 :         out.pubkeys.emplace(final_extkey.pubkey.GetID(), final_extkey.pubkey);
     486                 :             : 
     487         [ +  + ]:      674950 :         if (write_cache) {
     488                 :             :             // Only cache parent if there is any unhardened derivation
     489         [ +  + ]:       16165 :             if (m_derive != DeriveType::HARDENED_RANGED) {
     490         [ +  - ]:        6122 :                 write_cache->CacheParentExtPubKey(m_expr_index, parent_extkey);
     491                 :             :                 // Cache last hardened xpub if we have it
     492         [ +  + ]:        6122 :                 if (last_hardened_extkey.pubkey.IsValid()) {
     493         [ +  - ]:        3944 :                     write_cache->CacheLastHardenedExtPubKey(m_expr_index, last_hardened_extkey);
     494                 :             :                 }
     495   [ -  +  +  - ]:       10043 :             } else if (info.path.size() > 0) {
     496         [ +  - ]:       10043 :                 write_cache->CacheDerivedExtPubKey(m_expr_index, pos, final_extkey);
     497                 :             :             }
     498                 :             :         }
     499                 :             : 
     500                 :      674950 :         return final_extkey.pubkey;
     501                 :      689414 :     }
     502                 :      109052 :     std::string ToString(StringType type, bool normalized) const
     503                 :             :     {
     504                 :             :         // If StringType==COMPAT, always use the apostrophe to stay compatible with previous versions
     505   [ +  +  +  +  :      109052 :         const bool use_apostrophe = (!normalized && m_apostrophe) || type == StringType::COMPAT;
                   +  + ]
     506   [ +  -  +  - ]:      218104 :         std::string ret = EncodeExtPubKey(m_root_extkey) + FormatHDKeypath(m_path, /*apostrophe=*/use_apostrophe);
     507         [ +  + ]:      109052 :         if (IsRange()) {
     508         [ +  - ]:      104471 :             ret += "/*";
     509   [ +  +  +  + ]:      104471 :             if (m_derive == DeriveType::HARDENED_RANGED) ret += use_apostrophe ? '\'' : 'h';
     510                 :             :         }
     511                 :      109052 :         return ret;
     512                 :           0 :     }
     513                 :      109002 :     std::string ToString(StringType type=StringType::PUBLIC) const override
     514                 :             :     {
     515                 :      107620 :         return ToString(type, /*normalized=*/false);
     516                 :             :     }
     517                 :        1332 :     bool ToPrivateString(const SigningProvider& arg, std::string& out) const override
     518                 :             :     {
     519         [ +  - ]:        1332 :         CExtKey key;
     520   [ +  -  +  + ]:        1332 :         if (!GetExtKey(arg, key)) {
     521         [ +  - ]:         363 :             out = ToString(StringType::PUBLIC);
     522                 :         363 :             return false;
     523                 :             :         }
     524   [ +  -  +  -  :         969 :         out = EncodeExtKey(key) + FormatHDKeypath(m_path, /*apostrophe=*/m_apostrophe);
                   +  - ]
     525         [ +  + ]:         969 :         if (IsRange()) {
     526         [ +  - ]:         776 :             out += "/*";
     527   [ +  +  +  + ]:        1344 :             if (m_derive == DeriveType::HARDENED_RANGED) out += m_apostrophe ? '\'' : 'h';
     528                 :             :         }
     529                 :             :         return true;
     530                 :        1332 :     }
     531                 :       33157 :     bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache) const override
     532                 :             :     {
     533         [ +  + ]:       33157 :         if (m_derive == DeriveType::HARDENED_RANGED) {
     534                 :          50 :             out = ToString(StringType::PUBLIC, /*normalized=*/true);
     535                 :             : 
     536                 :          50 :             return true;
     537                 :             :         }
     538                 :             :         // Step backwards to find the last hardened step in the path
     539         [ -  + ]:       33107 :         int i = (int)m_path.size() - 1;
     540         [ +  + ]:       65591 :         for (; i >= 0; --i) {
     541         [ +  + ]:       64572 :             if (m_path.at(i) >> 31) {
     542                 :             :                 break;
     543                 :             :             }
     544                 :             :         }
     545                 :             :         // Either no derivation or all unhardened derivation
     546         [ +  + ]:       33107 :         if (i == -1) {
     547                 :        1019 :             out = ToString();
     548                 :        1019 :             return true;
     549                 :             :         }
     550                 :             :         // Get the path to the last hardened stup
     551                 :       32088 :         KeyOriginInfo origin;
     552                 :       32088 :         int k = 0;
     553         [ +  + ]:      128324 :         for (; k <= i; ++k) {
     554                 :             :             // Add to the path
     555   [ +  -  +  - ]:       96236 :             origin.path.push_back(m_path.at(k));
     556                 :             :         }
     557                 :             :         // Build the remaining path
     558                 :       32088 :         KeyPath end_path;
     559   [ -  +  +  + ]:       64115 :         for (; k < (int)m_path.size(); ++k) {
     560   [ +  -  +  - ]:       32027 :             end_path.push_back(m_path.at(k));
     561                 :             :         }
     562                 :             :         // Get the fingerprint
     563         [ +  - ]:       32088 :         CKeyID id = m_root_extkey.pubkey.GetID();
     564                 :       32088 :         std::copy(id.begin(), id.begin() + 4, origin.fingerprint);
     565                 :             : 
     566         [ +  + ]:       32088 :         CExtPubKey xpub;
     567         [ +  + ]:       32088 :         CExtKey lh_xprv;
     568                 :             :         // If we have the cache, just get the parent xpub
     569         [ +  + ]:       32088 :         if (cache != nullptr) {
     570         [ +  - ]:       32070 :             cache->GetCachedLastHardenedExtPubKey(m_expr_index, xpub);
     571                 :             :         }
     572         [ +  + ]:       32088 :         if (!xpub.pubkey.IsValid()) {
     573                 :             :             // Cache miss, or nor cache, or need privkey
     574         [ +  - ]:          18 :             CExtKey xprv;
     575   [ +  -  -  + ]:          18 :             if (!GetDerivedExtKey(arg, xprv, lh_xprv)) return false;
     576         [ +  - ]:          18 :             xpub = lh_xprv.Neuter();
     577                 :          18 :         }
     578         [ -  + ]:       32088 :         assert(xpub.pubkey.IsValid());
     579                 :             : 
     580                 :             :         // Build the string
     581   [ +  -  +  -  :       64176 :         std::string origin_str = HexStr(origin.fingerprint) + FormatHDKeypath(origin.path);
                   +  - ]
     582   [ +  -  +  -  :       64176 :         out = "[" + origin_str + "]" + EncodeExtPubKey(xpub) + FormatHDKeypath(end_path);
          +  -  +  -  +  
                      - ]
     583         [ +  + ]:       32088 :         if (IsRange()) {
     584         [ +  - ]:       32008 :             out += "/*";
     585         [ -  + ]:       32008 :             assert(m_derive == DeriveType::UNHARDENED_RANGED);
     586                 :             :         }
     587                 :       32088 :         return true;
     588                 :       64176 :     }
     589                 :       13436 :     void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const override
     590                 :             :     {
     591         [ +  - ]:       13436 :         CExtKey extkey;
     592                 :       13436 :         CExtKey dummy;
     593   [ +  -  +  + ]:       13436 :         if (!GetDerivedExtKey(arg, extkey, dummy)) return;
     594   [ +  +  +  -  :        8876 :         if (m_derive == DeriveType::UNHARDENED_RANGED && !extkey.Derive(extkey, pos)) return;
                   +  - ]
     595   [ +  +  +  -  :        8876 :         if (m_derive == DeriveType::HARDENED_RANGED && !extkey.Derive(extkey, pos | 0x80000000UL)) return;
                   +  - ]
     596   [ +  -  +  -  :        8876 :         out.keys.emplace(extkey.key.GetPubKey().GetID(), extkey.key);
                   +  - ]
     597                 :       13436 :     }
     598                 :         302 :     std::optional<CPubKey> GetRootPubKey() const override
     599                 :             :     {
     600                 :         302 :         return std::nullopt;
     601                 :             :     }
     602                 :         302 :     std::optional<CExtPubKey> GetRootExtPubKey() const override
     603                 :             :     {
     604                 :         302 :         return m_root_extkey;
     605                 :             :     }
     606                 :         296 :     std::unique_ptr<PubkeyProvider> Clone() const override
     607                 :             :     {
     608         [ -  + ]:         296 :         return std::make_unique<BIP32PubkeyProvider>(m_expr_index, m_root_extkey, m_path, m_derive, m_apostrophe);
     609                 :             :     }
     610                 :             : };
     611                 :             : 
     612                 :             : /** PubkeyProvider for a musig() expression */
     613                 :             : class MuSigPubkeyProvider final : public PubkeyProvider
     614                 :             : {
     615                 :             : private:
     616                 :             :     //! PubkeyProvider for the participants
     617                 :             :     const std::vector<std::unique_ptr<PubkeyProvider>> m_participants;
     618                 :             :     //! Derivation path
     619                 :             :     const KeyPath m_path;
     620                 :             :     //! PubkeyProvider for the aggregate pubkey if it can be cached (i.e. participants are not ranged)
     621                 :             :     mutable std::unique_ptr<PubkeyProvider> m_aggregate_provider;
     622                 :             :     mutable std::optional<CPubKey> m_aggregate_pubkey;
     623                 :             :     const DeriveType m_derive;
     624                 :             :     const bool m_ranged_participants;
     625                 :             : 
     626                 :        2793 :     bool IsRangedDerivation() const { return m_derive != DeriveType::NON_RANGED; }
     627                 :             : 
     628                 :             : public:
     629                 :         261 :     MuSigPubkeyProvider(
     630                 :             :         uint32_t exp_index,
     631                 :             :         std::vector<std::unique_ptr<PubkeyProvider>> providers,
     632                 :             :         KeyPath path,
     633                 :             :         DeriveType derive
     634                 :             :     )
     635                 :         261 :         : PubkeyProvider(exp_index),
     636                 :         261 :         m_participants(std::move(providers)),
     637         [ +  - ]:         261 :         m_path(std::move(path)),
     638         [ +  - ]:         261 :         m_derive(derive),
     639         [ +  - ]:         834 :         m_ranged_participants(std::any_of(m_participants.begin(), m_participants.end(), [](const auto& pubkey) { return pubkey->IsRange(); }))
     640                 :             :     {
     641   [ +  +  +  -  :         340 :         if (!Assume(!(m_ranged_participants && IsRangedDerivation()))) {
                   -  + ]
     642         [ #  # ]:           0 :             throw std::runtime_error("musig(): Cannot have both ranged participants and ranged derivation");
     643                 :             :         }
     644         [ -  + ]:         261 :         if (!Assume(m_derive != DeriveType::HARDENED_RANGED)) {
     645         [ #  # ]:           0 :             throw std::runtime_error("musig(): Cannot have hardened derivation");
     646                 :             :         }
     647                 :         261 :     }
     648                 :             : 
     649                 :        1415 :     std::optional<CPubKey> GetPubKey(int pos, const SigningProvider& arg, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
     650                 :             :     {
     651                 :        1415 :         FlatSigningProvider dummy;
     652                 :             :         // If the participants are not ranged, we can compute and cache the aggregate pubkey by creating a PubkeyProvider for it
     653   [ +  +  +  + ]:        1415 :         if (!m_aggregate_provider && !m_ranged_participants) {
     654                 :             :             // Retrieve the pubkeys from the providers
     655                 :         154 :             std::vector<CPubKey> pubkeys;
     656         [ +  + ]:         564 :             for (const auto& prov : m_participants) {
     657         [ +  - ]:         410 :                 std::optional<CPubKey> pubkey = prov->GetPubKey(0, arg, dummy, read_cache, write_cache);
     658         [ -  + ]:         410 :                 if (!pubkey.has_value()) {
     659                 :           0 :                     return std::nullopt;
     660                 :             :                 }
     661         [ +  - ]:         410 :                 pubkeys.push_back(pubkey.value());
     662                 :             :             }
     663                 :         154 :             std::sort(pubkeys.begin(), pubkeys.end());
     664                 :             : 
     665                 :             :             // Aggregate the pubkey
     666         [ +  - ]:         154 :             m_aggregate_pubkey = MuSig2AggregatePubkeys(pubkeys);
     667         [ -  + ]:         154 :             if (!Assume(m_aggregate_pubkey.has_value())) return std::nullopt;
     668                 :             : 
     669                 :             :             // Make our pubkey provider
     670   [ +  +  +  + ]:         154 :             if (IsRangedDerivation() || !m_path.empty()) {
     671                 :             :                 // Make the synthetic xpub and construct the BIP32PubkeyProvider
     672         [ +  - ]:         150 :                 CExtPubKey extpub = CreateMuSig2SyntheticXpub(m_aggregate_pubkey.value());
     673   [ +  -  -  + ]:         150 :                 m_aggregate_provider = std::make_unique<BIP32PubkeyProvider>(m_expr_index, extpub, m_path, m_derive, /*apostrophe=*/false);
     674                 :             :             } else {
     675         [ +  - ]:           4 :                 m_aggregate_provider = std::make_unique<ConstPubkeyProvider>(m_expr_index, m_aggregate_pubkey.value(), /*xonly=*/false);
     676                 :             :             }
     677                 :         154 :         }
     678                 :             : 
     679                 :             :         // Retrieve all participant pubkeys
     680                 :        1415 :         std::vector<CPubKey> pubkeys;
     681         [ +  + ]:        4897 :         for (const auto& prov : m_participants) {
     682         [ +  - ]:        3617 :             std::optional<CPubKey> pub = prov->GetPubKey(pos, arg, out, read_cache, write_cache);
     683         [ +  + ]:        3617 :             if (!pub) return std::nullopt;
     684         [ +  - ]:        3482 :             pubkeys.emplace_back(*pub);
     685                 :             :         }
     686                 :        1280 :         std::sort(pubkeys.begin(), pubkeys.end());
     687                 :             : 
     688         [ +  + ]:        1280 :         CPubKey pubout;
     689         [ +  + ]:        1280 :         if (m_aggregate_provider) {
     690                 :             :             // When we have a cached aggregate key, we are either returning it or deriving from it
     691                 :             :             // Either way, we can passthrough to its GetPubKey
     692                 :             :             // Use a dummy signing provider as private keys do not exist for the aggregate pubkey
     693         [ +  - ]:         937 :             std::optional<CPubKey> pub = m_aggregate_provider->GetPubKey(pos, dummy, out, read_cache, write_cache);
     694         [ -  + ]:         937 :             if (!pub) return std::nullopt;
     695         [ +  - ]:         937 :             pubout = *pub;
     696   [ +  -  +  - ]:         937 :             out.aggregate_pubkeys.emplace(m_aggregate_pubkey.value(), pubkeys);
     697                 :             :         } else {
     698   [ +  -  +  - ]:         343 :             if (!Assume(m_ranged_participants) || !Assume(m_path.empty())) return std::nullopt;
     699                 :             :             // Compute aggregate key from derived participants
     700         [ +  - ]:         343 :             std::optional<CPubKey> aggregate_pubkey = MuSig2AggregatePubkeys(pubkeys);
     701         [ -  + ]:         343 :             if (!aggregate_pubkey) return std::nullopt;
     702         [ +  - ]:         343 :             pubout = *aggregate_pubkey;
     703                 :             : 
     704         [ +  - ]:         343 :             std::unique_ptr<ConstPubkeyProvider> this_agg_provider = std::make_unique<ConstPubkeyProvider>(m_expr_index, aggregate_pubkey.value(), /*xonly=*/false);
     705         [ +  - ]:         343 :             this_agg_provider->GetPubKey(0, dummy, out, read_cache, write_cache);
     706         [ +  - ]:         343 :             out.aggregate_pubkeys.emplace(pubout, pubkeys);
     707                 :         343 :         }
     708                 :             : 
     709         [ -  + ]:        1280 :         if (!Assume(pubout.IsValid())) return std::nullopt;
     710                 :        1280 :         return pubout;
     711                 :        1415 :     }
     712   [ +  +  +  + ]:         959 :     bool IsRange() const override { return IsRangedDerivation() || m_ranged_participants; }
     713                 :             :     // musig() expressions can only be used in tr() contexts which have 32 byte xonly pubkeys
     714                 :           0 :     size_t GetSize() const override { return 32; }
     715                 :             : 
     716                 :        1389 :     std::string ToString(StringType type=StringType::PUBLIC) const override
     717                 :             :     {
     718                 :        1389 :         std::string out = "musig(";
     719   [ -  +  +  + ]:        5220 :         for (size_t i = 0; i < m_participants.size(); ++i) {
     720         [ +  - ]:        3831 :             const auto& pubkey = m_participants.at(i);
     721   [ +  +  +  - ]:        3831 :             if (i) out += ",";
     722         [ +  - ]:        7662 :             out += pubkey->ToString(type);
     723                 :             :         }
     724         [ +  - ]:        1389 :         out += ")";
     725         [ +  - ]:        2778 :         out += FormatHDKeypath(m_path);
     726         [ +  + ]:        1389 :         if (IsRangedDerivation()) {
     727         [ +  - ]:        1034 :             out += "/*";
     728                 :             :         }
     729                 :        1389 :         return out;
     730                 :           0 :     }
     731                 :          74 :     bool ToPrivateString(const SigningProvider& arg, std::string& out) const override
     732                 :             :     {
     733                 :          74 :         bool any_privkeys = false;
     734                 :          74 :         out = "musig(";
     735   [ -  +  +  + ]:         266 :         for (size_t i = 0; i < m_participants.size(); ++i) {
     736                 :         192 :             const auto& pubkey = m_participants.at(i);
     737         [ +  + ]:         192 :             if (i) out += ",";
     738         [ +  - ]:         192 :             std::string tmp;
     739   [ +  -  +  + ]:         192 :             if (pubkey->ToPrivateString(arg, tmp)) {
     740                 :          77 :                 any_privkeys = true;
     741                 :             :             }
     742         [ -  + ]:         384 :             out += tmp;
     743                 :         192 :         }
     744                 :          74 :         out += ")";
     745         [ -  + ]:         148 :         out += FormatHDKeypath(m_path);
     746         [ +  + ]:          74 :         if (IsRangedDerivation()) {
     747                 :          42 :             out += "/*";
     748                 :             :         }
     749                 :          74 :         return any_privkeys;
     750                 :             :     }
     751                 :         138 :     bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache = nullptr) const override
     752                 :             :     {
     753                 :         138 :         out = "musig(";
     754   [ -  +  +  + ]:         512 :         for (size_t i = 0; i < m_participants.size(); ++i) {
     755                 :         374 :             const auto& pubkey = m_participants.at(i);
     756         [ +  + ]:         374 :             if (i) out += ",";
     757         [ +  - ]:         374 :             std::string tmp;
     758   [ +  -  -  + ]:         374 :             if (!pubkey->ToNormalizedString(arg, tmp, cache)) {
     759                 :           0 :                 return false;
     760                 :             :             }
     761         [ -  + ]:         748 :             out += tmp;
     762                 :         374 :         }
     763                 :         138 :         out += ")";
     764         [ -  + ]:         276 :         out += FormatHDKeypath(m_path);
     765         [ +  + ]:         138 :         if (IsRangedDerivation()) {
     766                 :          99 :             out += "/*";
     767                 :             :         }
     768                 :             :         return true;
     769                 :             :     }
     770                 :             : 
     771                 :        1676 :     void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const override
     772                 :             :     {
     773                 :             :         // Get the private keys for any participants that we have
     774                 :             :         // If there is participant derivation, it will be done.
     775                 :             :         // If there is not, then the participant privkeys will be included directly
     776         [ +  + ]:        6329 :         for (const auto& prov : m_participants) {
     777                 :        4653 :             prov->GetPrivKey(pos, arg, out);
     778                 :             :         }
     779                 :        1676 :     }
     780                 :             : 
     781                 :             :     // Get RootPubKey and GetRootExtPubKey are used to return the single pubkey underlying the pubkey provider
     782                 :             :     // to be presented to the user in gethdkeys. As this is a multisig construction, there is no single underlying
     783                 :             :     // pubkey hence nothing should be returned.
     784                 :             :     // While the aggregate pubkey could be returned as the root (ext)pubkey, it is not a pubkey that anyone should
     785                 :             :     // be using by itself in a descriptor as it is unspendable without knowing its participants.
     786                 :           0 :     std::optional<CPubKey> GetRootPubKey() const override
     787                 :             :     {
     788                 :           0 :         return std::nullopt;
     789                 :             :     }
     790                 :           0 :     std::optional<CExtPubKey> GetRootExtPubKey() const override
     791                 :             :     {
     792                 :           0 :         return std::nullopt;
     793                 :             :     }
     794                 :             : 
     795                 :          29 :     std::unique_ptr<PubkeyProvider> Clone() const override
     796                 :             :     {
     797                 :          29 :         std::vector<std::unique_ptr<PubkeyProvider>> providers;
     798   [ -  +  +  - ]:          29 :         providers.reserve(m_participants.size());
     799         [ +  + ]:         107 :         for (const std::unique_ptr<PubkeyProvider>& p : m_participants) {
     800   [ +  -  +  - ]:          78 :             providers.emplace_back(p->Clone());
     801                 :             :         }
     802   [ +  -  -  + ]:          58 :         return std::make_unique<MuSigPubkeyProvider>(m_expr_index, std::move(providers), m_path, m_derive);
     803                 :          29 :     }
     804                 :           0 :     bool IsBIP32() const override
     805                 :             :     {
     806                 :             :         // musig() can only be a BIP 32 key if all participants are bip32 too
     807                 :           0 :         return std::all_of(m_participants.begin(), m_participants.end(), [](const auto& pubkey) { return pubkey->IsBIP32(); });
     808                 :             :     }
     809                 :          34 :     size_t GetKeyCount() const override
     810                 :             :     {
     811         [ -  + ]:          34 :         return 1 + m_participants.size();
     812                 :             :     }
     813                 :             : };
     814                 :             : 
     815                 :             : /** Base class for all Descriptor implementations. */
     816                 :             : class DescriptorImpl : public Descriptor
     817                 :             : {
     818                 :             : protected:
     819                 :             :     //! Public key arguments for this descriptor (size 1 for PK, PKH, WPKH; any size for WSH and Multisig).
     820                 :             :     const std::vector<std::unique_ptr<PubkeyProvider>> m_pubkey_args;
     821                 :             :     //! The string name of the descriptor function.
     822                 :             :     const std::string m_name;
     823                 :             :     //! Warnings (not including subdescriptors).
     824                 :             :     std::vector<std::string> m_warnings;
     825                 :             : 
     826                 :             :     //! The sub-descriptor arguments (empty for everything but SH and WSH).
     827                 :             :     //! In doc/descriptors.m this is referred to as SCRIPT expressions sh(SCRIPT)
     828                 :             :     //! and wsh(SCRIPT), and distinct from KEY expressions and ADDR expressions.
     829                 :             :     //! Subdescriptors can only ever generate a single script.
     830                 :             :     const std::vector<std::unique_ptr<DescriptorImpl>> m_subdescriptor_args;
     831                 :             : 
     832                 :             :     //! Return a serialization of anything except pubkey and script arguments, to be prepended to those.
     833                 :      319792 :     virtual std::string ToStringExtra() const { return ""; }
     834                 :             : 
     835                 :             :     /** A helper function to construct the scripts for this descriptor.
     836                 :             :      *
     837                 :             :      *  This function is invoked once by ExpandHelper.
     838                 :             :      *
     839                 :             :      *  @param pubkeys The evaluations of the m_pubkey_args field.
     840                 :             :      *  @param scripts The evaluations of m_subdescriptor_args (one for each m_subdescriptor_args element).
     841                 :             :      *  @param out A FlatSigningProvider to put scripts or public keys in that are necessary to the solver.
     842                 :             :      *             The origin info of the provided pubkeys is automatically added.
     843                 :             :      *  @return A vector with scriptPubKeys for this descriptor.
     844                 :             :      */
     845                 :             :     virtual std::vector<CScript> MakeScripts(const std::vector<CPubKey>& pubkeys, std::span<const CScript> scripts, FlatSigningProvider& out) const = 0;
     846                 :             : 
     847                 :             : public:
     848         [ -  + ]:      713158 :     DescriptorImpl(std::vector<std::unique_ptr<PubkeyProvider>> pubkeys, const std::string& name) : m_pubkey_args(std::move(pubkeys)), m_name(name), m_subdescriptor_args() {}
     849   [ -  +  +  - ]:       74010 :     DescriptorImpl(std::vector<std::unique_ptr<PubkeyProvider>> pubkeys, std::unique_ptr<DescriptorImpl> script, const std::string& name) : m_pubkey_args(std::move(pubkeys)), m_name(name), m_subdescriptor_args(Vector(std::move(script))) {}
     850         [ -  + ]:       15892 :     DescriptorImpl(std::vector<std::unique_ptr<PubkeyProvider>> pubkeys, std::vector<std::unique_ptr<DescriptorImpl>> scripts, const std::string& name) : m_pubkey_args(std::move(pubkeys)), m_name(name), m_subdescriptor_args(std::move(scripts)) {}
     851                 :             : 
     852                 :             :     enum class StringType
     853                 :             :     {
     854                 :             :         PUBLIC,
     855                 :             :         PRIVATE,
     856                 :             :         NORMALIZED,
     857                 :             :         COMPAT, // string calculation that mustn't change over time to stay compatible with previous software versions
     858                 :             :     };
     859                 :             : 
     860                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     861                 :        3868 :     bool IsSolvable() const override
     862                 :             :     {
     863         [ +  + ]:        5562 :         for (const auto& arg : m_subdescriptor_args) {
     864         [ +  - ]:        1694 :             if (!arg->IsSolvable()) return false;
     865                 :             :         }
     866                 :             :         return true;
     867                 :             :     }
     868                 :             : 
     869                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     870                 :         445 :     bool HavePrivateKeys(const SigningProvider& arg) const override
     871                 :             :     {
     872   [ +  +  +  + ]:         445 :         if (m_pubkey_args.empty() && m_subdescriptor_args.empty()) return false;
     873                 :             : 
     874         [ +  + ]:         514 :         for (const auto& sub: m_subdescriptor_args) {
     875         [ +  + ]:         167 :             if (!sub->HavePrivateKeys(arg)) return false;
     876                 :             :         }
     877                 :             : 
     878                 :         347 :         FlatSigningProvider tmp_provider;
     879         [ +  + ]:         586 :         for (const auto& pubkey : m_pubkey_args) {
     880                 :         377 :             tmp_provider.keys.clear();
     881         [ +  - ]:         377 :             pubkey->GetPrivKey(0, arg, tmp_provider);
     882         [ +  + ]:         377 :             if (tmp_provider.keys.empty()) return false;
     883                 :             :         }
     884                 :             : 
     885                 :             :         return true;
     886                 :         347 :     }
     887                 :             : 
     888                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     889                 :      129066 :     bool IsRange() const final
     890                 :             :     {
     891         [ +  + ]:      153995 :         for (const auto& pubkey : m_pubkey_args) {
     892         [ +  + ]:      127557 :             if (pubkey->IsRange()) return true;
     893                 :             :         }
     894         [ +  + ]:       27639 :         for (const auto& arg : m_subdescriptor_args) {
     895         [ +  + ]:        9897 :             if (arg->IsRange()) return true;
     896                 :             :         }
     897                 :             :         return false;
     898                 :             :     }
     899                 :             : 
     900                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     901                 :      316994 :     virtual bool ToStringSubScriptHelper(const SigningProvider* arg, std::string& ret, const StringType type, const DescriptorCache* cache = nullptr) const
     902                 :             :     {
     903                 :      316994 :         size_t pos = 0;
     904                 :      316994 :         bool is_private{type == StringType::PRIVATE};
     905                 :             :         // For private string output, track if at least one key has a private key available.
     906                 :             :         // Initialize to true for non-private types.
     907                 :      316994 :         bool any_success{!is_private};
     908         [ +  + ]:      360018 :         for (const auto& scriptarg : m_subdescriptor_args) {
     909         [ -  + ]:       43024 :             if (pos++) ret += ",";
     910         [ +  - ]:       43024 :             std::string tmp;
     911         [ +  - ]:       43024 :             bool subscript_res{scriptarg->ToStringHelper(arg, tmp, type, cache)};
     912         [ -  + ]:       43024 :             if (!is_private && !subscript_res) return false;
     913                 :       43024 :             any_success = any_success || subscript_res;
     914         [ -  + ]:       86048 :             ret += tmp;
     915                 :       43024 :         }
     916                 :             :         return any_success;
     917                 :             :     }
     918                 :             : 
     919                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     920                 :      326413 :     virtual bool ToStringHelper(const SigningProvider* arg, std::string& out, const StringType type, const DescriptorCache* cache = nullptr) const
     921                 :             :     {
     922                 :      326413 :         std::string extra = ToStringExtra();
     923   [ -  +  +  + ]:      326413 :         size_t pos = extra.size() > 0 ? 1 : 0;
     924   [ +  -  +  - ]:      326413 :         std::string ret = m_name + "(" + extra;
     925                 :      326413 :         bool is_private{type == StringType::PRIVATE};
     926                 :             :         // For private string output, track if at least one key has a private key available.
     927                 :             :         // Initialize to true for non-private types.
     928                 :      326413 :         bool any_success{!is_private};
     929                 :             : 
     930         [ +  + ]:      720245 :         for (const auto& pubkey : m_pubkey_args) {
     931   [ +  +  +  - ]:      393832 :             if (pos++) ret += ",";
     932   [ +  +  +  +  :      393832 :             std::string tmp;
                      - ]
     933   [ +  +  +  +  :      393832 :             switch (type) {
                      - ]
     934                 :       42596 :                 case StringType::NORMALIZED:
     935   [ +  -  -  + ]:       42596 :                     if (!pubkey->ToNormalizedString(*arg, tmp, cache)) return false;
     936                 :             :                     break;
     937                 :        1419 :                 case StringType::PRIVATE:
     938   [ +  -  +  +  :        1419 :                     any_success = pubkey->ToPrivateString(*arg, tmp) || any_success;
                   +  - ]
     939                 :             :                     break;
     940                 :      332855 :                 case StringType::PUBLIC:
     941         [ +  - ]:      332855 :                     tmp = pubkey->ToString();
     942                 :      332855 :                     break;
     943                 :       16962 :                 case StringType::COMPAT:
     944         [ +  - ]:       16962 :                     tmp = pubkey->ToString(PubkeyProvider::StringType::COMPAT);
     945                 :       16962 :                     break;
     946                 :             :             }
     947         [ -  + ]:      787664 :             ret += tmp;
     948                 :      393832 :         }
     949         [ +  - ]:      652826 :         std::string subscript;
     950         [ +  - ]:      326413 :         bool subscript_res{ToStringSubScriptHelper(arg, subscript, type, cache)};
     951         [ +  - ]:      326413 :         if (!is_private && !subscript_res) return false;
     952                 :      326413 :         any_success = any_success || subscript_res;
     953   [ +  +  +  +  :      609787 :         if (pos && subscript.size()) ret += ',';
                   +  - ]
     954         [ +  - ]:      652826 :         out = std::move(ret) + std::move(subscript) + ")";
     955                 :      326413 :         return any_success;
     956                 :      326413 :     }
     957                 :             : 
     958                 :      239998 :     std::string ToString(bool compat_format) const final
     959                 :             :     {
     960         [ +  + ]:      239998 :         std::string ret;
     961   [ +  +  +  - ]:      472656 :         ToStringHelper(nullptr, ret, compat_format ? StringType::COMPAT : StringType::PUBLIC);
     962         [ +  - ]:      239998 :         return AddChecksum(ret);
     963                 :      239998 :     }
     964                 :             : 
     965                 :        1080 :     bool ToPrivateString(const SigningProvider& arg, std::string& out) const override
     966                 :             :     {
     967                 :        1080 :         bool has_priv_key{ToStringHelper(&arg, out, StringType::PRIVATE)};
     968                 :        1080 :         out = AddChecksum(out);
     969                 :        1080 :         return has_priv_key;
     970                 :             :     }
     971                 :             : 
     972                 :       38262 :     bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache) const override final
     973                 :             :     {
     974                 :       38262 :         bool ret = ToStringHelper(&arg, out, StringType::NORMALIZED, cache);
     975                 :       38262 :         out = AddChecksum(out);
     976                 :       38262 :         return ret;
     977                 :             :     }
     978                 :             : 
     979                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     980                 :      738271 :     bool ExpandHelper(int pos, const SigningProvider& arg, const DescriptorCache* read_cache, std::vector<CScript>& output_scripts, FlatSigningProvider& out, DescriptorCache* write_cache) const
     981                 :             :     {
     982                 :      738271 :         FlatSigningProvider subprovider;
     983                 :      738271 :         std::vector<CPubKey> pubkeys;
     984   [ -  +  +  - ]:      738271 :         pubkeys.reserve(m_pubkey_args.size());
     985                 :             : 
     986                 :             :         // Construct temporary data in `pubkeys`, `subscripts`, and `subprovider` to avoid producing output in case of failure.
     987         [ +  + ]:     2412893 :         for (const auto& p : m_pubkey_args) {
     988         [ +  - ]:     1689080 :             std::optional<CPubKey> pubkey = p->GetPubKey(pos, arg, subprovider, read_cache, write_cache);
     989         [ +  + ]:     1689080 :             if (!pubkey) return false;
     990         [ +  - ]:     1674622 :             pubkeys.push_back(pubkey.value());
     991                 :             :         }
     992                 :      723813 :         std::vector<CScript> subscripts;
     993         [ +  + ]:      887855 :         for (const auto& subarg : m_subdescriptor_args) {
     994                 :      165468 :             std::vector<CScript> outscripts;
     995   [ +  -  +  + ]:      165468 :             if (!subarg->ExpandHelper(pos, arg, read_cache, outscripts, subprovider, write_cache)) return false;
     996   [ -  +  -  + ]:      164042 :             assert(outscripts.size() == 1);
     997         [ +  - ]:      164042 :             subscripts.emplace_back(std::move(outscripts[0]));
     998                 :      165468 :         }
     999         [ +  - ]:      722387 :         out.Merge(std::move(subprovider));
    1000                 :             : 
    1001   [ -  +  +  - ]:      722387 :         output_scripts = MakeScripts(pubkeys, std::span{subscripts}, out);
    1002                 :      722387 :         return true;
    1003                 :     1462084 :     }
    1004                 :             : 
    1005                 :       37710 :     bool Expand(int pos, const SigningProvider& provider, std::vector<CScript>& output_scripts, FlatSigningProvider& out, DescriptorCache* write_cache = nullptr) const final
    1006                 :             :     {
    1007                 :       37710 :         return ExpandHelper(pos, provider, nullptr, output_scripts, out, write_cache);
    1008                 :             :     }
    1009                 :             : 
    1010                 :      535093 :     bool ExpandFromCache(int pos, const DescriptorCache& read_cache, std::vector<CScript>& output_scripts, FlatSigningProvider& out) const final
    1011                 :             :     {
    1012                 :      535093 :         return ExpandHelper(pos, DUMMY_SIGNING_PROVIDER, &read_cache, output_scripts, out, nullptr);
    1013                 :             :     }
    1014                 :             : 
    1015                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
    1016                 :       17799 :     void ExpandPrivate(int pos, const SigningProvider& provider, FlatSigningProvider& out) const final
    1017                 :             :     {
    1018         [ +  + ]:       84453 :         for (const auto& p : m_pubkey_args) {
    1019                 :       66654 :             p->GetPrivKey(pos, provider, out);
    1020                 :             :         }
    1021         [ +  + ]:       21806 :         for (const auto& arg : m_subdescriptor_args) {
    1022                 :        4007 :             arg->ExpandPrivate(pos, provider, out);
    1023                 :             :         }
    1024                 :       17799 :     }
    1025                 :             : 
    1026                 :         411 :     std::optional<OutputType> GetOutputType() const override { return std::nullopt; }
    1027                 :             : 
    1028                 :           0 :     std::optional<int64_t> ScriptSize() const override { return {}; }
    1029                 :             : 
    1030                 :             :     /** A helper for MaxSatisfactionWeight.
    1031                 :             :      *
    1032                 :             :      * @param use_max_sig Whether to assume ECDSA signatures will have a high-r.
    1033                 :             :      * @return The maximum size of the satisfaction in raw bytes (with no witness meaning).
    1034                 :             :      */
    1035                 :           0 :     virtual std::optional<int64_t> MaxSatSize(bool use_max_sig) const { return {}; }
    1036                 :             : 
    1037                 :          18 :     std::optional<int64_t> MaxSatisfactionWeight(bool) const override { return {}; }
    1038                 :             : 
    1039                 :           4 :     std::optional<int64_t> MaxSatisfactionElems() const override { return {}; }
    1040                 :             : 
    1041                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
    1042                 :         380 :     void GetPubKeys(std::set<CPubKey>& pubkeys, std::set<CExtPubKey>& ext_pubs) const override
    1043                 :             :     {
    1044         [ +  + ]:         694 :         for (const auto& p : m_pubkey_args) {
    1045                 :         314 :             std::optional<CPubKey> pub = p->GetRootPubKey();
    1046         [ +  + ]:         314 :             if (pub) pubkeys.insert(*pub);
    1047                 :         314 :             std::optional<CExtPubKey> ext_pub = p->GetRootExtPubKey();
    1048         [ +  + ]:         314 :             if (ext_pub) ext_pubs.insert(*ext_pub);
    1049                 :             :         }
    1050         [ +  + ]:         449 :         for (const auto& arg : m_subdescriptor_args) {
    1051                 :          69 :             arg->GetPubKeys(pubkeys, ext_pubs);
    1052                 :             :         }
    1053                 :         380 :     }
    1054                 :             : 
    1055                 :             :     virtual std::unique_ptr<DescriptorImpl> Clone() const = 0;
    1056                 :             : 
    1057                 :        1109 :     bool HasScripts() const override { return true; }
    1058                 :             : 
    1059                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
    1060                 :        1352 :     std::vector<std::string> Warnings() const override {
    1061                 :        1352 :         std::vector<std::string> all = m_warnings;
    1062         [ +  + ]:        1918 :         for (const auto& sub : m_subdescriptor_args) {
    1063         [ +  - ]:         566 :             auto sub_w = sub->Warnings();
    1064         [ +  - ]:         566 :             all.insert(all.end(), sub_w.begin(), sub_w.end());
    1065                 :         566 :         }
    1066                 :        1352 :         return all;
    1067                 :           0 :     }
    1068                 :             : 
    1069                 :         232 :     uint32_t GetMaxKeyExpr() const final
    1070                 :             :     {
    1071                 :         232 :         uint32_t max_key_expr{0};
    1072                 :         232 :         std::vector<const DescriptorImpl*> todo = {this};
    1073         [ +  + ]:         640 :         while (!todo.empty()) {
    1074                 :         408 :             const DescriptorImpl* desc = todo.back();
    1075                 :         408 :             todo.pop_back();
    1076         [ +  + ]:         900 :             for (const auto& p : desc->m_pubkey_args) {
    1077         [ +  + ]:         720 :                 max_key_expr = std::max(max_key_expr, p->m_expr_index);
    1078                 :             :             }
    1079         [ +  + ]:         584 :             for (const auto& s : desc->m_subdescriptor_args) {
    1080         [ +  - ]:         176 :                 todo.push_back(s.get());
    1081                 :             :             }
    1082                 :             :         }
    1083                 :         232 :         return max_key_expr;
    1084                 :         232 :     }
    1085                 :             : 
    1086                 :         232 :     size_t GetKeyCount() const final
    1087                 :             :     {
    1088                 :         232 :         size_t count{0};
    1089                 :         232 :         std::vector<const DescriptorImpl*> todo = {this};
    1090         [ +  + ]:         640 :         while (!todo.empty()) {
    1091                 :         408 :             const DescriptorImpl* desc = todo.back();
    1092                 :         408 :             todo.pop_back();
    1093         [ +  + ]:         900 :             for (const auto& p : desc->m_pubkey_args) {
    1094         [ +  - ]:         492 :                 count += p->GetKeyCount();
    1095                 :             :             }
    1096         [ +  + ]:         584 :             for (const auto& s : desc->m_subdescriptor_args) {
    1097         [ +  - ]:         176 :                 todo.push_back(s.get());
    1098                 :             :             }
    1099                 :             :         }
    1100                 :         232 :         return count;
    1101                 :         232 :     }
    1102                 :             : };
    1103                 :             : 
    1104                 :             : /** A parsed addr(A) descriptor. */
    1105                 :             : class AddressDescriptor final : public DescriptorImpl
    1106                 :             : {
    1107                 :             :     const CTxDestination m_destination;
    1108                 :             : protected:
    1109                 :        2706 :     std::string ToStringExtra() const override { return EncodeDestination(m_destination); }
    1110         [ +  - ]:         254 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, std::span<const CScript>, FlatSigningProvider&) const override { return Vector(GetScriptForDestination(m_destination)); }
    1111                 :             : public:
    1112         [ +  - ]:        2705 :     AddressDescriptor(CTxDestination destination) : DescriptorImpl({}, "addr"), m_destination(std::move(destination)) {}
    1113                 :          14 :     bool IsSolvable() const final { return false; }
    1114                 :             : 
    1115                 :          33 :     std::optional<OutputType> GetOutputType() const override
    1116                 :             :     {
    1117                 :          33 :         return OutputTypeFromDestination(m_destination);
    1118                 :             :     }
    1119                 :           0 :     bool IsSingleType() const final { return true; }
    1120                 :           0 :     bool ToPrivateString(const SigningProvider& arg, std::string& out) const final { return false; }
    1121                 :             : 
    1122         [ #  # ]:           0 :     std::optional<int64_t> ScriptSize() const override { return GetScriptForDestination(m_destination).size(); }
    1123                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1124                 :             :     {
    1125         [ #  # ]:           0 :         return std::make_unique<AddressDescriptor>(m_destination);
    1126                 :             :     }
    1127                 :             : };
    1128                 :             : 
    1129                 :             : /** A parsed raw(H) descriptor. */
    1130                 :             : class RawDescriptor final : public DescriptorImpl
    1131                 :             : {
    1132                 :             :     const CScript m_script;
    1133                 :             : protected:
    1134         [ +  + ]:        4144 :     std::string ToStringExtra() const override { return HexStr(m_script); }
    1135                 :        1919 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, std::span<const CScript>, FlatSigningProvider&) const override { return Vector(m_script); }
    1136                 :             : public:
    1137         [ +  - ]:        3852 :     RawDescriptor(CScript script) : DescriptorImpl({}, "raw"), m_script(std::move(script)) {}
    1138                 :           0 :     bool IsSolvable() const final { return false; }
    1139                 :             : 
    1140                 :           5 :     std::optional<OutputType> GetOutputType() const override
    1141                 :             :     {
    1142                 :           5 :         CTxDestination dest;
    1143         [ +  - ]:           5 :         ExtractDestination(m_script, dest);
    1144         [ +  - ]:           5 :         return OutputTypeFromDestination(dest);
    1145                 :           5 :     }
    1146                 :           0 :     bool IsSingleType() const final { return true; }
    1147                 :           0 :     bool ToPrivateString(const SigningProvider& arg, std::string& out) const final { return false; }
    1148                 :             : 
    1149         [ #  # ]:           0 :     std::optional<int64_t> ScriptSize() const override { return m_script.size(); }
    1150                 :             : 
    1151                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1152                 :             :     {
    1153         [ #  # ]:           0 :         return std::make_unique<RawDescriptor>(m_script);
    1154                 :             :     }
    1155                 :             : };
    1156                 :             : 
    1157                 :             : /** A parsed pk(P) descriptor. */
    1158                 :             : class PKDescriptor final : public DescriptorImpl
    1159                 :             : {
    1160                 :             : private:
    1161                 :             :     const bool m_xonly;
    1162                 :             : protected:
    1163                 :       27873 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override
    1164                 :             :     {
    1165         [ +  + ]:       27873 :         if (m_xonly) {
    1166   [ +  -  +  - ]:       55130 :             CScript script = CScript() << ToByteVector(XOnlyPubKey(keys[0])) << OP_CHECKSIG;
    1167         [ +  - ]:       27565 :             return Vector(std::move(script));
    1168                 :       27565 :         } else {
    1169         [ +  - ]:         616 :             return Vector(GetScriptForRawPubKey(keys[0]));
    1170                 :             :         }
    1171                 :             :     }
    1172                 :             : public:
    1173   [ +  -  +  - ]:       22644 :     PKDescriptor(std::unique_ptr<PubkeyProvider> prov, bool xonly = false) : DescriptorImpl(Vector(std::move(prov)), "pk"), m_xonly(xonly) {}
    1174                 :           6 :     bool IsSingleType() const final { return true; }
    1175                 :             : 
    1176                 :          11 :     std::optional<int64_t> ScriptSize() const override {
    1177         [ +  - ]:          11 :         return 1 + (m_xonly ? 32 : m_pubkey_args[0]->GetSize()) + 1;
    1178                 :             :     }
    1179                 :             : 
    1180                 :          64 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
    1181         [ +  + ]:          59 :         const auto ecdsa_sig_size = use_max_sig ? 72 : 71;
    1182   [ +  -  +  - ]:          64 :         return 1 + (m_xonly ? 65 : ecdsa_sig_size);
    1183                 :             :     }
    1184                 :             : 
    1185                 :          58 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
    1186         [ +  + ]:          58 :         return *MaxSatSize(use_max_sig) * WITNESS_SCALE_FACTOR;
    1187                 :             :     }
    1188                 :             : 
    1189                 :          56 :     std::optional<int64_t> MaxSatisfactionElems() const override { return 1; }
    1190                 :             : 
    1191                 :          15 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1192                 :             :     {
    1193   [ +  -  -  + ]:          15 :         return std::make_unique<PKDescriptor>(m_pubkey_args.at(0)->Clone(), m_xonly);
    1194                 :             :     }
    1195                 :             : };
    1196                 :             : 
    1197                 :             : /** A parsed pkh(P) descriptor. */
    1198                 :             : class PKHDescriptor final : public DescriptorImpl
    1199                 :             : {
    1200                 :             : protected:
    1201                 :      129053 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override
    1202                 :             :     {
    1203                 :      129053 :         CKeyID id = keys[0].GetID();
    1204   [ +  -  +  - ]:      258106 :         return Vector(GetScriptForDestination(PKHash(id)));
    1205                 :             :     }
    1206                 :             : public:
    1207   [ +  -  +  - ]:      101311 :     PKHDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "pkh") {}
    1208                 :       77605 :     std::optional<OutputType> GetOutputType() const override { return OutputType::LEGACY; }
    1209                 :       17539 :     bool IsSingleType() const final { return true; }
    1210                 :             : 
    1211                 :          83 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 1 + 20 + 1 + 1; }
    1212                 :             : 
    1213                 :       57674 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
    1214         [ +  + ]:       57674 :         const auto sig_size = use_max_sig ? 72 : 71;
    1215                 :       57674 :         return 1 + sig_size + 1 + m_pubkey_args[0]->GetSize();
    1216                 :             :     }
    1217                 :             : 
    1218                 :       57603 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
    1219                 :       57603 :         return *MaxSatSize(use_max_sig) * WITNESS_SCALE_FACTOR;
    1220                 :             :     }
    1221                 :             : 
    1222                 :       57659 :     std::optional<int64_t> MaxSatisfactionElems() const override { return 2; }
    1223                 :             : 
    1224                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1225                 :             :     {
    1226   [ #  #  #  # ]:           0 :         return std::make_unique<PKHDescriptor>(m_pubkey_args.at(0)->Clone());
    1227                 :             :     }
    1228                 :             : };
    1229                 :             : 
    1230                 :             : /** A parsed wpkh(P) descriptor. */
    1231                 :             : class WPKHDescriptor final : public DescriptorImpl
    1232                 :             : {
    1233                 :             : protected:
    1234                 :      263749 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override
    1235                 :             :     {
    1236                 :      263749 :         CKeyID id = keys[0].GetID();
    1237   [ +  -  +  - ]:      527498 :         return Vector(GetScriptForDestination(WitnessV0KeyHash(id)));
    1238                 :             :     }
    1239                 :             : public:
    1240   [ +  -  +  - ]:      207718 :     WPKHDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "wpkh") {}
    1241                 :      178410 :     std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32; }
    1242                 :       28565 :     bool IsSingleType() const final { return true; }
    1243                 :             : 
    1244                 :        8483 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 20; }
    1245                 :             : 
    1246                 :      145258 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
    1247         [ +  + ]:      145125 :         const auto sig_size = use_max_sig ? 72 : 71;
    1248                 :      145258 :         return (1 + sig_size + 1 + 33);
    1249                 :             :     }
    1250                 :             : 
    1251                 :      136780 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
    1252         [ +  + ]:      136780 :         return MaxSatSize(use_max_sig);
    1253                 :             :     }
    1254                 :             : 
    1255                 :      145248 :     std::optional<int64_t> MaxSatisfactionElems() const override { return 2; }
    1256                 :             : 
    1257                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1258                 :             :     {
    1259   [ #  #  #  # ]:           0 :         return std::make_unique<WPKHDescriptor>(m_pubkey_args.at(0)->Clone());
    1260                 :             :     }
    1261                 :             : };
    1262                 :             : 
    1263                 :             : /** A parsed combo(P) descriptor. */
    1264                 :             : class ComboDescriptor final : public DescriptorImpl
    1265                 :             : {
    1266                 :             : protected:
    1267                 :       19246 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider& out) const override
    1268                 :             :     {
    1269                 :       19246 :         std::vector<CScript> ret;
    1270         [ +  - ]:       19246 :         CKeyID id = keys[0].GetID();
    1271   [ +  -  +  - ]:       19246 :         ret.emplace_back(GetScriptForRawPubKey(keys[0])); // P2PK
    1272   [ +  -  +  -  :       38492 :         ret.emplace_back(GetScriptForDestination(PKHash(id))); // P2PKH
                   +  - ]
    1273         [ +  + ]:       19246 :         if (keys[0].IsCompressed()) {
    1274         [ +  - ]:       19219 :             CScript p2wpkh = GetScriptForDestination(WitnessV0KeyHash(id));
    1275   [ +  -  +  - ]:       19219 :             out.scripts.emplace(CScriptID(p2wpkh), p2wpkh);
    1276         [ +  - ]:       19219 :             ret.emplace_back(p2wpkh);
    1277   [ +  -  +  -  :       38438 :             ret.emplace_back(GetScriptForDestination(ScriptHash(p2wpkh))); // P2SH-P2WPKH
                   +  - ]
    1278                 :       19219 :         }
    1279                 :       19246 :         return ret;
    1280                 :           0 :     }
    1281                 :             : public:
    1282   [ +  -  +  - ]:         546 :     ComboDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "combo") {}
    1283                 :           5 :     bool IsSingleType() const final { return false; }
    1284                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1285                 :             :     {
    1286   [ #  #  #  # ]:           0 :         return std::make_unique<ComboDescriptor>(m_pubkey_args.at(0)->Clone());
    1287                 :             :     }
    1288                 :             : };
    1289                 :             : 
    1290                 :             : /** A parsed multi(...) or sortedmulti(...) descriptor */
    1291                 :             : class MultisigDescriptor final : public DescriptorImpl
    1292                 :             : {
    1293                 :             :     const int m_threshold;
    1294                 :             :     const bool m_sorted;
    1295                 :             : protected:
    1296                 :        1041 :     std::string ToStringExtra() const override { return strprintf("%i", m_threshold); }
    1297                 :       18606 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override {
    1298         [ +  + ]:       18606 :         if (m_sorted) {
    1299                 :        2833 :             std::vector<CPubKey> sorted_keys(keys);
    1300                 :        2833 :             std::sort(sorted_keys.begin(), sorted_keys.end());
    1301   [ +  -  +  - ]:        5666 :             return Vector(GetScriptForMultisig(m_threshold, sorted_keys));
    1302                 :        2833 :         }
    1303         [ +  - ]:       31546 :         return Vector(GetScriptForMultisig(m_threshold, keys));
    1304                 :             :     }
    1305                 :             : public:
    1306   [ +  +  +  - ]:        1728 :     MultisigDescriptor(int threshold, std::vector<std::unique_ptr<PubkeyProvider>> providers, bool sorted = false) : DescriptorImpl(std::move(providers), sorted ? "sortedmulti" : "multi"), m_threshold(threshold), m_sorted(sorted) {}
    1307                 :           7 :     bool IsSingleType() const final { return true; }
    1308                 :             : 
    1309                 :         236 :     std::optional<int64_t> ScriptSize() const override {
    1310         [ -  + ]:         236 :         const auto n_keys = m_pubkey_args.size();
    1311                 :         735 :         auto op = [](int64_t acc, const std::unique_ptr<PubkeyProvider>& pk) { return acc + 1 + pk->GetSize();};
    1312                 :         236 :         const auto pubkeys_size{std::accumulate(m_pubkey_args.begin(), m_pubkey_args.end(), int64_t{0}, op)};
    1313   [ -  +  +  - ]:         472 :         return 1 + BuildScript(n_keys).size() + BuildScript(m_threshold).size() + pubkeys_size;
    1314                 :             :     }
    1315                 :             : 
    1316                 :         243 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
    1317         [ +  + ]:         236 :         const auto sig_size = use_max_sig ? 72 : 71;
    1318                 :         243 :         return (1 + (1 + sig_size) * m_threshold);
    1319                 :             :     }
    1320                 :             : 
    1321                 :          14 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
    1322         [ +  + ]:          14 :         return *MaxSatSize(use_max_sig) * WITNESS_SCALE_FACTOR;
    1323                 :             :     }
    1324                 :             : 
    1325                 :         221 :     std::optional<int64_t> MaxSatisfactionElems() const override { return 1 + m_threshold; }
    1326                 :             : 
    1327                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1328                 :             :     {
    1329                 :           0 :         std::vector<std::unique_ptr<PubkeyProvider>> providers;
    1330   [ #  #  #  # ]:           0 :         providers.reserve(m_pubkey_args.size());
    1331         [ #  # ]:           0 :         std::transform(m_pubkey_args.begin(), m_pubkey_args.end(), std::back_inserter(providers), [](const std::unique_ptr<PubkeyProvider>& p) { return p->Clone(); });
    1332   [ #  #  #  # ]:           0 :         return std::make_unique<MultisigDescriptor>(m_threshold, std::move(providers), m_sorted);
    1333                 :           0 :     }
    1334                 :             : };
    1335                 :             : 
    1336                 :             : /** A parsed (sorted)multi_a(...) descriptor. Always uses x-only pubkeys. */
    1337                 :             : class MultiADescriptor final : public DescriptorImpl
    1338                 :             : {
    1339                 :             :     const int m_threshold;
    1340                 :             :     const bool m_sorted;
    1341                 :             : protected:
    1342                 :         802 :     std::string ToStringExtra() const override { return strprintf("%i", m_threshold); }
    1343                 :        6950 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override {
    1344                 :        6950 :         CScript ret;
    1345                 :        6950 :         std::vector<XOnlyPubKey> xkeys;
    1346   [ -  +  +  - ]:        6950 :         xkeys.reserve(keys.size());
    1347   [ +  -  +  + ]:      999840 :         for (const auto& key : keys) xkeys.emplace_back(key);
    1348         [ +  + ]:        6950 :         if (m_sorted) std::sort(xkeys.begin(), xkeys.end());
    1349   [ +  -  +  - ]:       13900 :         ret << ToByteVector(xkeys[0]) << OP_CHECKSIG;
    1350   [ -  +  +  + ]:      992890 :         for (size_t i = 1; i < keys.size(); ++i) {
    1351   [ +  -  +  - ]:     2957820 :             ret << ToByteVector(xkeys[i]) << OP_CHECKSIGADD;
    1352                 :             :         }
    1353   [ +  -  +  - ]:        6950 :         ret << m_threshold << OP_NUMEQUAL;
    1354         [ +  - ]:        6950 :         return Vector(std::move(ret));
    1355                 :        6950 :     }
    1356                 :             : public:
    1357   [ +  +  +  - ]:        1802 :     MultiADescriptor(int threshold, std::vector<std::unique_ptr<PubkeyProvider>> providers, bool sorted = false) : DescriptorImpl(std::move(providers), sorted ? "sortedmulti_a" : "multi_a"), m_threshold(threshold), m_sorted(sorted) {}
    1358                 :           0 :     bool IsSingleType() const final { return true; }
    1359                 :             : 
    1360                 :           0 :     std::optional<int64_t> ScriptSize() const override {
    1361         [ #  # ]:           0 :         const auto n_keys = m_pubkey_args.size();
    1362         [ #  # ]:           0 :         return (1 + 32 + 1) * n_keys + BuildScript(m_threshold).size() + 1;
    1363                 :             :     }
    1364                 :             : 
    1365                 :           0 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
    1366         [ #  # ]:           0 :         return (1 + 65) * m_threshold + (m_pubkey_args.size() - m_threshold);
    1367                 :             :     }
    1368                 :             : 
    1369         [ #  # ]:           0 :     std::optional<int64_t> MaxSatisfactionElems() const override { return m_pubkey_args.size(); }
    1370                 :             : 
    1371                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1372                 :             :     {
    1373                 :           0 :         std::vector<std::unique_ptr<PubkeyProvider>> providers;
    1374   [ #  #  #  # ]:           0 :         providers.reserve(m_pubkey_args.size());
    1375         [ #  # ]:           0 :         for (const auto& arg : m_pubkey_args) {
    1376         [ #  # ]:           0 :             providers.push_back(arg->Clone());
    1377                 :             :         }
    1378   [ #  #  #  # ]:           0 :         return std::make_unique<MultiADescriptor>(m_threshold, std::move(providers), m_sorted);
    1379                 :           0 :     }
    1380                 :             : };
    1381                 :             : 
    1382                 :             : /** A parsed sh(...) descriptor. */
    1383                 :             : class SHDescriptor final : public DescriptorImpl
    1384                 :             : {
    1385                 :             : protected:
    1386                 :      111821 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, std::span<const CScript> scripts, FlatSigningProvider& out) const override
    1387                 :             :     {
    1388   [ +  -  +  - ]:      223642 :         auto ret = Vector(GetScriptForDestination(ScriptHash(scripts[0])));
    1389   [ -  +  +  -  :      111821 :         if (ret.size()) out.scripts.emplace(CScriptID(scripts[0]), scripts[0]);
             +  -  +  - ]
    1390                 :      111821 :         return ret;
    1391                 :           0 :     }
    1392                 :             : 
    1393         [ +  + ]:       21551 :     bool IsSegwit() const { return m_subdescriptor_args[0]->GetOutputType() == OutputType::BECH32; }
    1394                 :             : 
    1395                 :             : public:
    1396         [ +  - ]:       35908 :     SHDescriptor(std::unique_ptr<DescriptorImpl> desc) : DescriptorImpl({}, std::move(desc), "sh") {}
    1397                 :             : 
    1398                 :       12938 :     std::optional<OutputType> GetOutputType() const override
    1399                 :             :     {
    1400   [ -  +  -  + ]:       12938 :         assert(m_subdescriptor_args.size() == 1);
    1401         [ +  + ]:       12938 :         if (IsSegwit()) return OutputType::P2SH_SEGWIT;
    1402                 :         124 :         return OutputType::LEGACY;
    1403                 :             :     }
    1404                 :        1557 :     bool IsSingleType() const final { return true; }
    1405                 :             : 
    1406                 :          24 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 20 + 1; }
    1407                 :             : 
    1408                 :        8613 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
    1409         [ +  - ]:        8613 :         if (const auto sat_size = m_subdescriptor_args[0]->MaxSatSize(use_max_sig)) {
    1410         [ +  - ]:        8613 :             if (const auto subscript_size = m_subdescriptor_args[0]->ScriptSize()) {
    1411                 :             :                 // The subscript is never witness data.
    1412                 :        8613 :                 const auto subscript_weight = (1 + *subscript_size) * WITNESS_SCALE_FACTOR;
    1413                 :             :                 // The weight depends on whether the inner descriptor is satisfied using the witness stack.
    1414         [ +  + ]:        8613 :                 if (IsSegwit()) return subscript_weight + *sat_size;
    1415                 :          59 :                 return subscript_weight + *sat_size * WITNESS_SCALE_FACTOR;
    1416                 :             :             }
    1417                 :             :         }
    1418                 :           0 :         return {};
    1419                 :             :     }
    1420                 :             : 
    1421                 :        8589 :     std::optional<int64_t> MaxSatisfactionElems() const override {
    1422         [ +  - ]:        8589 :         if (const auto sub_elems = m_subdescriptor_args[0]->MaxSatisfactionElems()) return 1 + *sub_elems;
    1423                 :           0 :         return {};
    1424                 :             :     }
    1425                 :             : 
    1426                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1427                 :             :     {
    1428   [ #  #  #  # ]:           0 :         return std::make_unique<SHDescriptor>(m_subdescriptor_args.at(0)->Clone());
    1429                 :             :     }
    1430                 :             : };
    1431                 :             : 
    1432                 :             : /** A parsed wsh(...) descriptor. */
    1433                 :             : class WSHDescriptor final : public DescriptorImpl
    1434                 :             : {
    1435                 :             : protected:
    1436                 :       17083 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, std::span<const CScript> scripts, FlatSigningProvider& out) const override
    1437                 :             :     {
    1438   [ +  -  +  - ]:       34166 :         auto ret = Vector(GetScriptForDestination(WitnessV0ScriptHash(scripts[0])));
    1439   [ -  +  +  -  :       17083 :         if (ret.size()) out.scripts.emplace(CScriptID(scripts[0]), scripts[0]);
             +  -  +  - ]
    1440                 :       17083 :         return ret;
    1441                 :           0 :     }
    1442                 :             : public:
    1443         [ +  - ]:        1097 :     WSHDescriptor(std::unique_ptr<DescriptorImpl> desc) : DescriptorImpl({}, std::move(desc), "wsh") {}
    1444                 :         910 :     std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32; }
    1445                 :         410 :     bool IsSingleType() const final { return true; }
    1446                 :             : 
    1447                 :          94 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
    1448                 :             : 
    1449                 :         412 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
    1450         [ +  - ]:         412 :         if (const auto sat_size = m_subdescriptor_args[0]->MaxSatSize(use_max_sig)) {
    1451         [ +  - ]:         412 :             if (const auto subscript_size = m_subdescriptor_args[0]->ScriptSize()) {
    1452         [ +  + ]:         474 :                 return GetSizeOfCompactSize(*subscript_size) + *subscript_size + *sat_size;
    1453                 :             :             }
    1454                 :             :         }
    1455                 :           0 :         return {};
    1456                 :             :     }
    1457                 :             : 
    1458                 :         336 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
    1459                 :         336 :         return MaxSatSize(use_max_sig);
    1460                 :             :     }
    1461                 :             : 
    1462                 :         386 :     std::optional<int64_t> MaxSatisfactionElems() const override {
    1463         [ +  - ]:         386 :         if (const auto sub_elems = m_subdescriptor_args[0]->MaxSatisfactionElems()) return 1 + *sub_elems;
    1464                 :           0 :         return {};
    1465                 :             :     }
    1466                 :             : 
    1467                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1468                 :             :     {
    1469   [ #  #  #  # ]:           0 :         return std::make_unique<WSHDescriptor>(m_subdescriptor_args.at(0)->Clone());
    1470                 :             :     }
    1471                 :             : };
    1472                 :             : 
    1473                 :             : /** A parsed tr(...) descriptor. */
    1474                 :             : class TRDescriptor final : public DescriptorImpl
    1475                 :             : {
    1476                 :             :     std::vector<int> m_depths;
    1477                 :             : protected:
    1478                 :      122952 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript> scripts, FlatSigningProvider& out) const override
    1479                 :             :     {
    1480         [ -  + ]:      122952 :         TaprootBuilder builder;
    1481   [ -  +  -  + ]:      122952 :         assert(m_depths.size() == scripts.size());
    1482   [ -  +  +  + ]:      158080 :         for (size_t pos = 0; pos < m_depths.size(); ++pos) {
    1483   [ +  +  +  - ]:       70256 :             builder.Add(m_depths[pos], scripts[pos], TAPROOT_LEAF_TAPSCRIPT);
    1484                 :             :         }
    1485         [ -  + ]:      122952 :         if (!builder.IsComplete()) return {};
    1486   [ -  +  -  + ]:      122952 :         assert(keys.size() == 1);
    1487                 :      122952 :         XOnlyPubKey xpk(keys[0]);
    1488   [ +  -  -  + ]:      122952 :         if (!xpk.IsFullyValid()) return {};
    1489         [ +  - ]:      122952 :         builder.Finalize(xpk);
    1490         [ +  - ]:      122952 :         WitnessV1Taproot output = builder.GetOutput();
    1491   [ +  -  +  - ]:      122952 :         out.tr_trees[output] = builder;
    1492   [ +  -  +  - ]:      245904 :         return Vector(GetScriptForDestination(output));
    1493                 :      122952 :     }
    1494                 :        9419 :     bool ToStringSubScriptHelper(const SigningProvider* arg, std::string& ret, const StringType type, const DescriptorCache* cache = nullptr) const override
    1495                 :             :     {
    1496         [ +  + ]:        9419 :         if (m_depths.empty()) {
    1497                 :             :             // If there are no sub-descriptors and a PRIVATE string
    1498                 :             :             // is requested, return `false` to indicate that the presence
    1499                 :             :             // of a private key depends solely on the internal key (which is checked
    1500                 :             :             // in the caller), not on any sub-descriptor. This ensures correct behavior for
    1501                 :             :             // descriptors like tr(internal_key) when checking for private keys.
    1502                 :        7100 :             return type != StringType::PRIVATE;
    1503                 :             :         }
    1504                 :        2319 :         std::vector<bool> path;
    1505                 :        2319 :         bool is_private{type == StringType::PRIVATE};
    1506                 :             :         // For private string output, track if at least one key has a private key available.
    1507                 :             :         // Initialize to true for non-private types.
    1508                 :        2319 :         bool any_success{!is_private};
    1509                 :             : 
    1510   [ -  +  +  + ]:        7457 :         for (size_t pos = 0; pos < m_depths.size(); ++pos) {
    1511   [ +  +  +  - ]:        5138 :             if (pos) ret += ',';
    1512         [ +  + ]:       10276 :             while ((int)path.size() <= m_depths[pos]) {
    1513   [ +  +  +  - ]:        5138 :                 if (path.size()) ret += '{';
    1514         [ +  - ]:        5138 :                 path.push_back(false);
    1515                 :             :             }
    1516         [ +  - ]:        5138 :             std::string tmp;
    1517         [ +  - ]:        5138 :             bool subscript_res{m_subdescriptor_args[pos]->ToStringHelper(arg, tmp, type, cache)};
    1518         [ -  + ]:        5138 :             if (!is_private && !subscript_res) return false;
    1519                 :        5138 :             any_success = any_success || subscript_res;
    1520         [ -  + ]:        5138 :             ret += tmp;
    1521   [ +  -  +  + ]:        7957 :             while (!path.empty() && path.back()) {
    1522   [ +  -  +  - ]:        2819 :                 if (path.size() > 1) ret += '}';
    1523   [ -  +  +  - ]:       10776 :                 path.pop_back();
    1524                 :             :             }
    1525         [ +  - ]:        5138 :             if (!path.empty()) path.back() = true;
    1526                 :        5138 :         }
    1527                 :             :         return any_success;
    1528                 :        2319 :     }
    1529                 :             : public:
    1530                 :        7946 :     TRDescriptor(std::unique_ptr<PubkeyProvider> internal_key, std::vector<std::unique_ptr<DescriptorImpl>> descs, std::vector<int> depths) :
    1531   [ +  -  +  -  :        7946 :         DescriptorImpl(Vector(std::move(internal_key)), std::move(descs), "tr"), m_depths(std::move(depths))
                   -  + ]
    1532                 :             :     {
    1533   [ -  +  -  +  :        7946 :         assert(m_subdescriptor_args.size() == m_depths.size());
                   -  + ]
    1534                 :        7946 :     }
    1535                 :       10185 :     std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32M; }
    1536                 :        2007 :     bool IsSingleType() const final { return true; }
    1537                 :             : 
    1538                 :          28 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
    1539                 :             : 
    1540                 :        4993 :     std::optional<int64_t> MaxSatisfactionWeight(bool) const override {
    1541                 :             :         // FIXME: We assume keypath spend, which can lead to very large underestimations.
    1542                 :        4993 :         return 1 + 65;
    1543                 :             :     }
    1544                 :             : 
    1545                 :        4965 :     std::optional<int64_t> MaxSatisfactionElems() const override {
    1546                 :             :         // FIXME: See above, we assume keypath spend.
    1547                 :        4965 :         return 1;
    1548                 :             :     }
    1549                 :             : 
    1550                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1551                 :             :     {
    1552                 :           0 :         std::vector<std::unique_ptr<DescriptorImpl>> subdescs;
    1553   [ #  #  #  # ]:           0 :         subdescs.reserve(m_subdescriptor_args.size());
    1554         [ #  # ]:           0 :         std::transform(m_subdescriptor_args.begin(), m_subdescriptor_args.end(), std::back_inserter(subdescs), [](const std::unique_ptr<DescriptorImpl>& d) { return d->Clone(); });
    1555   [ #  #  #  #  :           0 :         return std::make_unique<TRDescriptor>(m_pubkey_args.at(0)->Clone(), std::move(subdescs), m_depths);
             #  #  #  # ]
    1556                 :           0 :     }
    1557                 :             : };
    1558                 :             : 
    1559                 :             : /* We instantiate Miniscript here with a simple integer as key type.
    1560                 :             :  * The value of these key integers are an index in the
    1561                 :             :  * DescriptorImpl::m_pubkey_args vector.
    1562                 :             :  */
    1563                 :             : 
    1564                 :             : /**
    1565                 :             :  * The context for converting a Miniscript descriptor into a Script.
    1566                 :             :  */
    1567                 :             : class ScriptMaker {
    1568                 :             :     //! Keys contained in the Miniscript (the evaluation of DescriptorImpl::m_pubkey_args).
    1569                 :             :     const std::vector<CPubKey>& m_keys;
    1570                 :             :     //! The script context we're operating within (Tapscript or P2WSH).
    1571                 :             :     const miniscript::MiniscriptContext m_script_ctx;
    1572                 :             : 
    1573                 :             :     //! Get the ripemd160(sha256()) hash of this key.
    1574                 :             :     //! Any key that is valid in a descriptor serializes as 32 bytes within a Tapscript context. So we
    1575                 :             :     //! must not hash the sign-bit byte in this case.
    1576                 :         512 :     uint160 GetHash160(uint32_t key) const {
    1577         [ +  + ]:         512 :         if (miniscript::IsTapscript(m_script_ctx)) {
    1578                 :         241 :             return Hash160(XOnlyPubKey{m_keys[key]});
    1579                 :             :         }
    1580                 :         271 :         return m_keys[key].GetID();
    1581                 :             :     }
    1582                 :             : 
    1583                 :             : public:
    1584                 :        1473 :     ScriptMaker(const std::vector<CPubKey>& keys LIFETIMEBOUND, const miniscript::MiniscriptContext script_ctx) : m_keys(keys), m_script_ctx{script_ctx} {}
    1585                 :             : 
    1586                 :        2773 :     std::vector<unsigned char> ToPKBytes(uint32_t key) const {
    1587                 :             :         // In Tapscript keys always serialize as x-only, whether an x-only key was used in the descriptor or not.
    1588         [ +  + ]:        2773 :         if (!miniscript::IsTapscript(m_script_ctx)) {
    1589                 :        1926 :             return {m_keys[key].begin(), m_keys[key].end()};
    1590                 :             :         }
    1591                 :         847 :         const XOnlyPubKey xonly_pubkey{m_keys[key]};
    1592                 :         847 :         return {xonly_pubkey.begin(), xonly_pubkey.end()};
    1593                 :             :     }
    1594                 :             : 
    1595                 :         512 :     std::vector<unsigned char> ToPKHBytes(uint32_t key) const {
    1596                 :         512 :         auto id = GetHash160(key);
    1597                 :         512 :         return {id.begin(), id.end()};
    1598                 :             :     }
    1599                 :             : };
    1600                 :             : 
    1601                 :             : /**
    1602                 :             :  * The context for converting a Miniscript descriptor to its textual form.
    1603                 :             :  */
    1604                 :             : class StringMaker {
    1605                 :             :     //! To convert private keys for private descriptors.
    1606                 :             :     const SigningProvider* m_arg;
    1607                 :             :     //! Keys contained in the Miniscript (a reference to DescriptorImpl::m_pubkey_args).
    1608                 :             :     const std::vector<std::unique_ptr<PubkeyProvider>>& m_pubkeys;
    1609                 :             :     //! StringType to serialize keys
    1610                 :             :     const DescriptorImpl::StringType m_type;
    1611                 :             :     const DescriptorCache* m_cache;
    1612                 :             : 
    1613                 :             : public:
    1614                 :        1089 :     StringMaker(const SigningProvider* arg LIFETIMEBOUND,
    1615                 :             :                 const std::vector<std::unique_ptr<PubkeyProvider>>& pubkeys LIFETIMEBOUND,
    1616                 :             :                 DescriptorImpl::StringType type,
    1617                 :             :                 const DescriptorCache* cache LIFETIMEBOUND)
    1618                 :        1089 :         : m_arg(arg), m_pubkeys(pubkeys), m_type(type), m_cache(cache) {}
    1619                 :             : 
    1620                 :        5122 :     std::optional<std::string> ToString(uint32_t key, bool& has_priv_key) const
    1621                 :             :     {
    1622   [ +  +  +  +  :        5122 :         std::string ret;
                      - ]
    1623                 :        5122 :         has_priv_key = false;
    1624   [ +  +  +  +  :        5122 :         switch (m_type) {
                      - ]
    1625                 :        4018 :         case DescriptorImpl::StringType::PUBLIC:
    1626         [ +  - ]:        4018 :             ret = m_pubkeys[key]->ToString();
    1627                 :        4018 :             break;
    1628                 :         218 :         case DescriptorImpl::StringType::PRIVATE:
    1629         [ +  - ]:         218 :             has_priv_key = m_pubkeys[key]->ToPrivateString(*m_arg, ret);
    1630                 :         218 :             break;
    1631                 :         504 :         case DescriptorImpl::StringType::NORMALIZED:
    1632   [ +  -  -  + ]:         504 :             if (!m_pubkeys[key]->ToNormalizedString(*m_arg, ret, m_cache)) return {};
    1633                 :             :             break;
    1634                 :         382 :         case DescriptorImpl::StringType::COMPAT:
    1635         [ +  - ]:         382 :             ret = m_pubkeys[key]->ToString(PubkeyProvider::StringType::COMPAT);
    1636                 :         382 :             break;
    1637                 :             :         }
    1638                 :        5122 :         return ret;
    1639                 :        5122 :     }
    1640                 :             : };
    1641                 :             : 
    1642                 :             : class MiniscriptDescriptor final : public DescriptorImpl
    1643                 :             : {
    1644                 :             : private:
    1645                 :             :     miniscript::Node<uint32_t> m_node;
    1646                 :             : 
    1647                 :             : protected:
    1648                 :        1473 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript> scripts,
    1649                 :             :                                      FlatSigningProvider& provider) const override
    1650                 :             :     {
    1651                 :        1473 :         const auto script_ctx{m_node.GetMsCtx()};
    1652         [ +  + ]:        4758 :         for (const auto& key : keys) {
    1653         [ +  + ]:        3285 :             if (miniscript::IsTapscript(script_ctx)) {
    1654                 :        1088 :                 provider.pubkeys.emplace(Hash160(XOnlyPubKey{key}), key);
    1655                 :             :             } else {
    1656                 :        2197 :                 provider.pubkeys.emplace(key.GetID(), key);
    1657                 :             :             }
    1658                 :             :         }
    1659         [ +  - ]:        2946 :         return Vector(m_node.ToScript(ScriptMaker(keys, script_ctx)));
    1660                 :             :     }
    1661                 :             : 
    1662                 :             : public:
    1663                 :         807 :     MiniscriptDescriptor(std::vector<std::unique_ptr<PubkeyProvider>> providers, miniscript::Node<uint32_t>&& node)
    1664         [ +  - ]:         807 :         : DescriptorImpl(std::move(providers), "?"), m_node(std::move(node))
    1665                 :             :     {
    1666                 :             :         // Traverse miniscript tree for unsafe use of older()
    1667         [ +  - ]:         807 :         miniscript::ForEachNode(m_node, [&](const miniscript::Node<uint32_t>& node) {
    1668         [ +  + ]:      995940 :             if (node.Fragment() == miniscript::Fragment::OLDER) {
    1669         [ +  + ]:         257 :                 const uint32_t raw = node.K();
    1670                 :         257 :                 const uint32_t value_part = raw & ~CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG;
    1671         [ +  + ]:         257 :                 if (value_part > CTxIn::SEQUENCE_LOCKTIME_MASK) {
    1672                 :           4 :                     const bool is_time_based = (raw & CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) != 0;
    1673         [ +  + ]:           4 :                     if (is_time_based) {
    1674         [ +  - ]:           2 :                         m_warnings.push_back(strprintf("time-based relative locktime: older(%u) > (65535 * 512) seconds is unsafe", raw));
    1675                 :             :                     } else {
    1676         [ +  - ]:           2 :                         m_warnings.push_back(strprintf("height-based relative locktime: older(%u) > 65535 blocks is unsafe", raw));
    1677                 :             :                     }
    1678                 :             :                 }
    1679                 :             :             }
    1680                 :      995940 :         });
    1681                 :         807 :     }
    1682                 :             : 
    1683                 :        1089 :     bool ToStringHelper(const SigningProvider* arg, std::string& out, const StringType type,
    1684                 :             :                         const DescriptorCache* cache = nullptr) const override
    1685                 :             :     {
    1686                 :        1089 :         bool has_priv_key{false};
    1687                 :        1089 :         auto res = m_node.ToString(StringMaker(arg, m_pubkey_args, type, cache), has_priv_key);
    1688   [ +  -  +  - ]:        1089 :         if (res) out = *res;
    1689         [ +  + ]:        1089 :         if (type == StringType::PRIVATE) {
    1690                 :          89 :             Assume(res.has_value());
    1691                 :          89 :             return has_priv_key;
    1692                 :             :         } else {
    1693                 :        1000 :             return res.has_value();
    1694                 :             :         }
    1695                 :        1089 :     }
    1696                 :             : 
    1697                 :         351 :     bool IsSolvable() const override { return true; }
    1698                 :           0 :     bool IsSingleType() const final { return true; }
    1699                 :             : 
    1700                 :         165 :     std::optional<int64_t> ScriptSize() const override { return m_node.ScriptSize(); }
    1701                 :             : 
    1702                 :         165 :     std::optional<int64_t> MaxSatSize(bool) const override
    1703                 :             :     {
    1704                 :             :         // For Miniscript we always assume high-R ECDSA signatures.
    1705   [ -  +  +  - ]:         330 :         return m_node.GetWitnessSize();
    1706                 :             :     }
    1707                 :             : 
    1708                 :         149 :     std::optional<int64_t> MaxSatisfactionElems() const override
    1709                 :             :     {
    1710         [ +  - ]:         149 :         return m_node.GetStackSize();
    1711                 :             :     }
    1712                 :             : 
    1713                 :           5 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1714                 :             :     {
    1715                 :           5 :         std::vector<std::unique_ptr<PubkeyProvider>> providers;
    1716   [ -  +  +  - ]:           5 :         providers.reserve(m_pubkey_args.size());
    1717         [ +  + ]:          10 :         for (const auto& arg : m_pubkey_args) {
    1718         [ +  - ]:          10 :             providers.push_back(arg->Clone());
    1719                 :             :         }
    1720   [ +  -  +  -  :          10 :         return std::make_unique<MiniscriptDescriptor>(std::move(providers), m_node.Clone());
                   -  + ]
    1721                 :           5 :     }
    1722                 :             : };
    1723                 :             : 
    1724                 :             : /** A parsed rawtr(...) descriptor. */
    1725                 :             : class RawTRDescriptor final : public DescriptorImpl
    1726                 :             : {
    1727                 :             : protected:
    1728                 :        1528 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript> scripts, FlatSigningProvider& out) const override
    1729                 :             :     {
    1730   [ -  +  -  + ]:        1528 :         assert(keys.size() == 1);
    1731                 :        1528 :         XOnlyPubKey xpk(keys[0]);
    1732         [ -  + ]:        1528 :         if (!xpk.IsFullyValid()) return {};
    1733         [ +  - ]:        1528 :         WitnessV1Taproot output{xpk};
    1734   [ +  -  +  - ]:        3056 :         return Vector(GetScriptForDestination(output));
    1735                 :             :     }
    1736                 :             : public:
    1737   [ +  -  +  - ]:       15185 :     RawTRDescriptor(std::unique_ptr<PubkeyProvider> output_key) : DescriptorImpl(Vector(std::move(output_key)), "rawtr") {}
    1738                 :         355 :     std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32M; }
    1739                 :         149 :     bool IsSingleType() const final { return true; }
    1740                 :             : 
    1741                 :          13 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
    1742                 :             : 
    1743                 :         183 :     std::optional<int64_t> MaxSatisfactionWeight(bool) const override {
    1744                 :             :         // We can't know whether there is a script path, so assume key path spend.
    1745                 :         183 :         return 1 + 65;
    1746                 :             :     }
    1747                 :             : 
    1748                 :         170 :     std::optional<int64_t> MaxSatisfactionElems() const override {
    1749                 :             :         // See above, we assume keypath spend.
    1750                 :         170 :         return 1;
    1751                 :             :     }
    1752                 :             : 
    1753                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1754                 :             :     {
    1755   [ #  #  #  # ]:           0 :         return std::make_unique<RawTRDescriptor>(m_pubkey_args.at(0)->Clone());
    1756                 :             :     }
    1757                 :             : };
    1758                 :             : 
    1759                 :             : /** A parsed unused(KEY) descriptor */
    1760                 :             : class UnusedDescriptor final : public DescriptorImpl
    1761                 :             : {
    1762                 :             : protected:
    1763                 :           7 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript> scripts, FlatSigningProvider& out) const override { return {}; }
    1764                 :             : public:
    1765   [ +  -  +  - ]:          13 :     UnusedDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "unused") {}
    1766                 :           0 :     bool IsSingleType() const final { return true; }
    1767                 :           6 :     bool HasScripts() const override { return false; }
    1768                 :             : 
    1769                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1770                 :             :     {
    1771   [ #  #  #  # ]:           0 :         return std::make_unique<UnusedDescriptor>(m_pubkey_args.at(0)->Clone());
    1772                 :             :     }
    1773                 :             : };
    1774                 :             : 
    1775                 :             : 
    1776                 :             : ////////////////////////////////////////////////////////////////////////////
    1777                 :             : // Parser                                                                 //
    1778                 :             : ////////////////////////////////////////////////////////////////////////////
    1779                 :             : 
    1780                 :             : enum class ParseScriptContext {
    1781                 :             :     TOP,     //!< Top-level context (script goes directly in scriptPubKey)
    1782                 :             :     P2SH,    //!< Inside sh() (script becomes P2SH redeemScript)
    1783                 :             :     P2WPKH,  //!< Inside wpkh() (no script, pubkey only)
    1784                 :             :     P2WSH,   //!< Inside wsh() (script becomes v0 witness script)
    1785                 :             :     P2TR,    //!< Inside tr() (either internal key, or BIP342 script leaf)
    1786                 :             :     MUSIG,   //!< Inside musig() (implies P2TR, cannot have nested musig())
    1787                 :             : };
    1788                 :             : 
    1789                 :       28444 : std::optional<uint32_t> ParseKeyPathNum(std::span<const char> elem, bool& apostrophe, std::string& error, bool& has_hardened)
    1790                 :             : {
    1791                 :       28444 :     bool hardened = false;
    1792         [ +  + ]:       28444 :     if (elem.size() > 0) {
    1793         [ +  + ]:       28438 :         const char last = elem[elem.size() - 1];
    1794         [ +  + ]:       28438 :         if (last == '\'' || last == 'h') {
    1795                 :       20504 :             elem = elem.first(elem.size() - 1);
    1796                 :       20504 :             hardened = true;
    1797                 :       20504 :             apostrophe = last == '\'';
    1798                 :             :         }
    1799                 :             :     }
    1800                 :       28444 :     const auto p{ToIntegral<uint32_t>(std::string_view{elem.begin(), elem.end()})};
    1801         [ +  + ]:       28444 :     if (!p) {
    1802                 :          14 :         error = strprintf("Key path value '%s' is not a valid uint32", std::string_view{elem.begin(), elem.end()});
    1803                 :          14 :         return std::nullopt;
    1804         [ +  + ]:       28430 :     } else if (*p > 0x7FFFFFFFUL) {
    1805                 :           2 :         error = strprintf("Key path value %u is out of range", *p);
    1806                 :           2 :         return std::nullopt;
    1807                 :             :     }
    1808   [ +  +  +  + ]:       28428 :     has_hardened = has_hardened || hardened;
    1809                 :             : 
    1810                 :       28428 :     return std::make_optional<uint32_t>(*p | (((uint32_t)hardened) << 31));
    1811                 :             : }
    1812                 :             : 
    1813                 :             : /**
    1814                 :             :  * Parse a key path, being passed a split list of elements (the first element is ignored because it is always the key).
    1815                 :             :  *
    1816                 :             :  * @param[in] split BIP32 path string, using either ' or h for hardened derivation
    1817                 :             :  * @param[out] out Vector of parsed key paths
    1818                 :             :  * @param[out] apostrophe only updated if hardened derivation is found
    1819                 :             :  * @param[out] error parsing error message
    1820                 :             :  * @param[in] allow_multipath Allows the parsed path to use the multipath specifier
    1821                 :             :  * @param[out] has_hardened Records whether the path contains any hardened derivation
    1822                 :             :  * @returns false if parsing failed
    1823                 :             :  **/
    1824                 :       13131 : [[nodiscard]] bool ParseKeyPath(const std::vector<std::span<const char>>& split, std::vector<KeyPath>& out, bool& apostrophe, std::string& error, bool allow_multipath, bool& has_hardened)
    1825                 :             : {
    1826                 :       13131 :     KeyPath path;
    1827                 :         327 :     struct MultipathSubstitutes {
    1828                 :             :         size_t placeholder_index;
    1829                 :             :         std::vector<uint32_t> values;
    1830                 :             :     };
    1831                 :       13131 :     std::optional<MultipathSubstitutes> substitutes;
    1832                 :       13131 :     has_hardened = false;
    1833                 :             : 
    1834   [ -  +  +  + ]:       41115 :     for (size_t i = 1; i < split.size(); ++i) {
    1835         [ +  - ]:       28010 :         const std::span<const char>& elem = split[i];
    1836                 :             : 
    1837                 :             :         // Check if element contains multipath specifier
    1838   [ +  -  +  +  :       28010 :         if (!elem.empty() && elem.front() == '<' && elem.back() == '>') {
                   +  + ]
    1839         [ +  + ]:         335 :             if (!allow_multipath) {
    1840   [ +  -  +  - ]:           4 :                 error = strprintf("Key path value '%s' specifies multipath in a section where multipath is not allowed", std::string(elem.begin(), elem.end()));
    1841                 :           2 :                 return false;
    1842                 :             :             }
    1843         [ +  + ]:         333 :             if (substitutes) {
    1844         [ +  - ]:       13131 :                 error = "Multiple multipath key path specifiers found";
    1845                 :             :                 return false;
    1846                 :             :             }
    1847                 :             : 
    1848                 :             :             // Parse each possible value
    1849         [ +  - ]:         331 :             std::vector<std::span<const char>> nums = Split(std::span(elem.begin()+1, elem.end()-1), ";");
    1850   [ -  +  +  + ]:         331 :             if (nums.size() < 2) {
    1851         [ +  - ]:          12 :                 error = "Multipath key path specifiers must have at least two items";
    1852                 :             :                 return false;
    1853                 :             :             }
    1854                 :             : 
    1855                 :         327 :             substitutes.emplace();
    1856                 :         327 :             std::unordered_set<uint32_t> seen_substitutes;
    1857         [ +  + ]:        1088 :             for (const auto& num : nums) {
    1858         [ +  - ]:         769 :                 const auto& op_num = ParseKeyPathNum(num, apostrophe, error, has_hardened);
    1859         [ +  + ]:         769 :                 if (!op_num) return false;
    1860   [ +  -  +  + ]:         763 :                 auto [_, inserted] = seen_substitutes.insert(*op_num);
    1861         [ +  + ]:         763 :                 if (!inserted) {
    1862         [ +  - ]:           2 :                     error = strprintf("Duplicated key path value %u in multipath specifier", *op_num);
    1863                 :           2 :                     return false;
    1864                 :             :                 }
    1865         [ +  - ]:         761 :                 substitutes->values.emplace_back(*op_num);
    1866                 :             :             }
    1867                 :             : 
    1868         [ +  - ]:         319 :             path.emplace_back(); // Placeholder for multipath segment
    1869         [ -  + ]:         319 :             substitutes->placeholder_index = path.size() - 1;
    1870                 :         339 :         } else {
    1871         [ +  - ]:       27675 :             const auto& op_num = ParseKeyPathNum(elem, apostrophe, error, has_hardened);
    1872         [ +  + ]:       27675 :             if (!op_num) return false;
    1873         [ +  - ]:       27665 :             path.emplace_back(*op_num);
    1874                 :             :         }
    1875                 :             :     }
    1876                 :             : 
    1877         [ +  + ]:       13105 :     if (!substitutes) {
    1878         [ +  - ]:       12788 :         out.emplace_back(std::move(path));
    1879                 :             :     } else {
    1880                 :             :         // Replace the multipath placeholder with each value while generating paths
    1881         [ +  + ]:        1066 :         for (uint32_t substitute : substitutes->values) {
    1882         [ +  - ]:         749 :             KeyPath branch_path = path;
    1883         [ +  - ]:         749 :             branch_path[substitutes->placeholder_index] = substitute;
    1884         [ +  - ]:         749 :             out.emplace_back(std::move(branch_path));
    1885                 :         749 :         }
    1886                 :             :     }
    1887                 :             :     return true;
    1888                 :       13131 : }
    1889                 :             : 
    1890                 :       13034 : [[nodiscard]] bool ParseKeyPath(const std::vector<std::span<const char>>& split, std::vector<KeyPath>& out, bool& apostrophe, std::string& error, bool allow_multipath)
    1891                 :             : {
    1892                 :       13034 :     bool dummy;
    1893                 :       13034 :     return ParseKeyPath(split, out, apostrophe, error, allow_multipath, /*has_hardened=*/dummy);
    1894                 :             : }
    1895                 :             : 
    1896                 :        8163 : static DeriveType ParseDeriveType(std::vector<std::span<const char>>& split, bool& apostrophe)
    1897                 :             : {
    1898                 :        8163 :     DeriveType type = DeriveType::NON_RANGED;
    1899         [ +  + ]:        8163 :     if (std::ranges::equal(split.back(), std::span{"*"}.first(1))) {
    1900                 :        7502 :         split.pop_back();
    1901                 :        7502 :         type = DeriveType::UNHARDENED_RANGED;
    1902   [ +  +  +  + ]:         661 :     } else if (std::ranges::equal(split.back(), std::span{"*'"}.first(2)) || std::ranges::equal(split.back(), std::span{"*h"}.first(2))) {
    1903                 :         177 :         apostrophe = std::ranges::equal(split.back(), std::span{"*'"}.first(2));
    1904                 :         177 :         split.pop_back();
    1905                 :         177 :         type = DeriveType::HARDENED_RANGED;
    1906                 :             :     }
    1907                 :        8163 :     return type;
    1908                 :             : }
    1909                 :             : 
    1910                 :             : /** Parse a public key that excludes origin information. */
    1911                 :       28061 : std::vector<std::unique_ptr<PubkeyProvider>> ParsePubkeyInner(uint32_t& key_exp_index, const std::span<const char>& sp, ParseScriptContext ctx, FlatSigningProvider& out, bool& apostrophe, std::string& error)
    1912                 :             : {
    1913                 :       28061 :     std::vector<std::unique_ptr<PubkeyProvider>> ret;
    1914                 :       28061 :     bool permit_uncompressed = ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH;
    1915         [ +  - ]:       28061 :     auto split = Split(sp, '/');
    1916   [ +  -  -  + ]:       56122 :     std::string str(split[0].begin(), split[0].end());
    1917   [ -  +  +  + ]:       28061 :     if (str.size() == 0) {
    1918         [ +  - ]:           4 :         error = "No key provided";
    1919                 :           4 :         return {};
    1920                 :             :     }
    1921   [ +  +  +  + ]:       28057 :     if (IsSpace(str.front()) || IsSpace(str.back())) {
    1922         [ +  - ]:          10 :         error = strprintf("Key '%s' is invalid due to whitespace", str);
    1923                 :          10 :         return {};
    1924                 :             :     }
    1925   [ -  +  +  + ]:       28047 :     if (split.size() == 1) {
    1926   [ +  -  +  + ]:       20282 :         if (IsHex(str)) {
    1927   [ -  +  +  - ]:       19529 :             std::vector<unsigned char> data = ParseHex(str);
    1928         [ -  + ]:       19529 :             CPubKey pubkey(data);
    1929   [ +  +  +  + ]:       19529 :             if (pubkey.IsValid() && !pubkey.IsValidNonHybrid()) {
    1930         [ +  - ]:           4 :                 error = "Hybrid public keys are not allowed";
    1931                 :           4 :                 return {};
    1932                 :             :             }
    1933   [ +  -  +  + ]:       19525 :             if (pubkey.IsFullyValid()) {
    1934   [ +  +  +  + ]:         952 :                 if (permit_uncompressed || pubkey.IsCompressed()) {
    1935   [ +  -  +  - ]:         948 :                     ret.emplace_back(std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, false));
    1936                 :         948 :                     ++key_exp_index;
    1937                 :         948 :                     return ret;
    1938                 :             :                 } else {
    1939         [ +  - ]:           4 :                     error = "Uncompressed keys are not allowed";
    1940                 :           4 :                     return {};
    1941                 :             :                 }
    1942   [ -  +  +  -  :       18573 :             } else if (data.size() == 32 && ctx == ParseScriptContext::P2TR) {
                   +  + ]
    1943                 :       18571 :                 unsigned char fullkey[33] = {0x02};
    1944                 :       18571 :                 std::copy(data.begin(), data.end(), fullkey + 1);
    1945                 :       18571 :                 pubkey.Set(std::begin(fullkey), std::end(fullkey));
    1946   [ +  -  +  - ]:       18571 :                 if (pubkey.IsFullyValid()) {
    1947   [ +  -  +  - ]:       18571 :                     ret.emplace_back(std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, true));
    1948                 :       18571 :                     ++key_exp_index;
    1949                 :       18571 :                     return ret;
    1950                 :             :                 }
    1951                 :             :             }
    1952         [ +  - ]:           2 :             error = strprintf("Pubkey '%s' is invalid", str);
    1953                 :           2 :             return {};
    1954                 :       19529 :         }
    1955         [ +  - ]:         753 :         CKey key = DecodeSecret(str);
    1956         [ +  + ]:         753 :         if (key.IsValid()) {
    1957   [ +  +  +  + ]:         451 :             if (permit_uncompressed || key.IsCompressed()) {
    1958         [ +  - ]:         446 :                 CPubKey pubkey = key.GetPubKey();
    1959   [ +  -  +  - ]:         446 :                 out.keys.emplace(pubkey.GetID(), key);
    1960   [ +  -  +  - ]:         446 :                 ret.emplace_back(std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, ctx == ParseScriptContext::P2TR));
    1961                 :         446 :                 ++key_exp_index;
    1962                 :         446 :                 return ret;
    1963                 :             :             } else {
    1964         [ +  - ]:           5 :                 error = "Uncompressed keys are not allowed";
    1965                 :           5 :                 return {};
    1966                 :             :             }
    1967                 :             :         }
    1968                 :         753 :     }
    1969         [ +  - ]:        8067 :     CExtKey extkey = DecodeExtKey(str);
    1970         [ +  - ]:        8067 :     CExtPubKey extpubkey = DecodeExtPubKey(str);
    1971   [ +  +  +  + ]:        8067 :     if (!extkey.key.IsValid() && !extpubkey.pubkey.IsValid()) {
    1972         [ +  - ]:           3 :         error = strprintf("key '%s' is not valid", str);
    1973                 :           3 :         return {};
    1974                 :             :     }
    1975                 :        8064 :     std::vector<KeyPath> paths;
    1976                 :        8064 :     DeriveType type = ParseDeriveType(split, apostrophe);
    1977   [ +  -  +  + ]:        8064 :     if (!ParseKeyPath(split, paths, apostrophe, error, /*allow_multipath=*/true)) return {};
    1978         [ +  + ]:        8040 :     if (extkey.key.IsValid()) {
    1979         [ +  - ]:         830 :         extpubkey = extkey.Neuter();
    1980   [ +  -  +  - ]:         830 :         out.keys.emplace(extpubkey.pubkey.GetID(), extkey.key);
    1981                 :             :     }
    1982         [ +  + ]:       16454 :     for (auto& path : paths) {
    1983   [ +  -  +  - ]:       16828 :         ret.emplace_back(std::make_unique<BIP32PubkeyProvider>(key_exp_index, extpubkey, std::move(path), type, apostrophe));
    1984                 :             :     }
    1985                 :        8040 :     ++key_exp_index;
    1986                 :        8040 :     return ret;
    1987                 :       44192 : }
    1988                 :             : 
    1989                 :             : /** Parse a public key including origin information (if enabled). */
    1990                 :             : // NOLINTNEXTLINE(misc-no-recursion)
    1991                 :       28241 : std::vector<std::unique_ptr<PubkeyProvider>> ParsePubkey(uint32_t& key_exp_index, const std::span<const char>& sp, ParseScriptContext ctx, FlatSigningProvider& out, std::string& error)
    1992                 :             : {
    1993                 :       28241 :     std::vector<std::unique_ptr<PubkeyProvider>> ret;
    1994                 :             : 
    1995                 :       28241 :     using namespace script;
    1996                 :             : 
    1997                 :             :     // musig cannot be nested inside of an origin
    1998                 :       28241 :     std::span<const char> span = sp;
    1999   [ +  -  +  -  :       28241 :     if (Const("musig(", span, /*skip=*/false)) {
                   +  + ]
    2000         [ +  + ]:         164 :         if (ctx != ParseScriptContext::P2TR) {
    2001         [ +  - ]:          12 :             error = "musig() is only allowed in tr() and rawtr()";
    2002                 :          12 :             return {};
    2003                 :             :         }
    2004                 :             : 
    2005                 :             :         // Split the span on the end parentheses. The end parentheses must
    2006                 :             :         // be included in the resulting span so that Expr is happy.
    2007         [ +  - ]:         152 :         auto split = Split(sp, ')', /*include_sep=*/true);
    2008   [ -  +  +  + ]:         152 :         if (split.size() > 2) {
    2009         [ +  - ]:           2 :             error = "Too many ')' in musig() expression";
    2010                 :           2 :             return {};
    2011                 :             :         }
    2012   [ +  -  +  -  :         150 :         std::span<const char> expr(split.at(0).begin(), split.at(0).end());
                   +  - ]
    2013   [ +  -  +  -  :         150 :         if (!Func("musig", expr)) {
                   -  + ]
    2014         [ #  # ]:           0 :             error = "Invalid musig() expression";
    2015                 :           0 :             return {};
    2016                 :             :         }
    2017                 :             : 
    2018                 :             :         // Parse the participant pubkeys
    2019                 :         150 :         bool any_ranged = false;
    2020                 :         150 :         bool all_bip32 = true;
    2021                 :         150 :         std::vector<std::vector<std::unique_ptr<PubkeyProvider>>> providers;
    2022                 :         150 :         bool any_key_parsed = false;
    2023                 :         150 :         size_t max_multipath_len = 0;
    2024         [ +  + ]:         543 :         while (expr.size()) {
    2025   [ +  +  +  -  :         638 :             if (any_key_parsed && !Const(",", expr)) {
          +  -  -  +  -  
                +  -  - ]
    2026         [ #  # ]:           0 :                 error = strprintf("musig(): expected ',', got '%c'", expr[0]);
    2027                 :           0 :                 return {};
    2028                 :             :             }
    2029         [ +  - ]:         393 :             auto arg = Expr(expr);
    2030         [ +  - ]:         393 :             auto pk = ParsePubkey(key_exp_index, arg, ParseScriptContext::MUSIG, out, error);
    2031         [ -  + ]:         393 :             if (pk.empty()) {
    2032         [ #  # ]:           0 :                 error = strprintf("musig(): %s", error);
    2033                 :           0 :                 return {};
    2034                 :             :             }
    2035                 :         393 :             any_key_parsed = true;
    2036                 :             : 
    2037   [ +  +  +  -  :         712 :             any_ranged = any_ranged || pk.at(0)->IsRange();
                   +  + ]
    2038   [ +  +  +  -  :         770 :             all_bip32 = all_bip32 &&  pk.at(0)->IsBIP32();
                   +  + ]
    2039                 :             : 
    2040   [ -  +  +  + ]:         393 :             max_multipath_len = std::max(max_multipath_len, pk.size());
    2041                 :             : 
    2042         [ +  - ]:         393 :             providers.emplace_back(std::move(pk));
    2043                 :         393 :         }
    2044         [ +  + ]:         150 :         if (!any_key_parsed) {
    2045         [ +  - ]:           2 :             error = "musig(): Must contain key expressions";
    2046                 :           2 :             return {};
    2047                 :             :         }
    2048                 :             : 
    2049                 :             :         // Parse any derivation
    2050                 :         148 :         DeriveType deriv_type = DeriveType::NON_RANGED;
    2051                 :         148 :         std::vector<KeyPath> derivation_multipaths;
    2052   [ -  +  +  -  :         444 :         if (split.size() == 2 && Const("/", split.at(1), /*skip=*/false)) {
          +  -  +  -  +  
                +  +  + ]
    2053         [ +  + ]:         107 :             if (!all_bip32) {
    2054         [ +  - ]:           4 :                 error = "musig(): derivation requires all participants to be xpubs or xprvs";
    2055                 :           4 :                 return {};
    2056                 :             :             }
    2057         [ +  + ]:         103 :             if (any_ranged) {
    2058         [ +  - ]:           4 :                 error = "musig(): Cannot have ranged participant keys if musig() also has derivation";
    2059                 :           4 :                 return {};
    2060                 :             :             }
    2061                 :          99 :             bool dummy = false;
    2062   [ +  -  +  - ]:          99 :             auto deriv_split = Split(split.at(1), '/');
    2063                 :          99 :             deriv_type = ParseDeriveType(deriv_split, dummy);
    2064         [ +  + ]:          99 :             if (deriv_type == DeriveType::HARDENED_RANGED) {
    2065         [ +  - ]:           2 :                 error = "musig(): Cannot have hardened child derivation";
    2066                 :           2 :                 return {};
    2067                 :             :             }
    2068                 :          97 :             bool has_hardened = false;
    2069   [ +  -  -  + ]:          97 :             if (!ParseKeyPath(deriv_split, derivation_multipaths, dummy, error, /*allow_multipath=*/true, has_hardened)) {
    2070         [ #  # ]:           0 :                 error = "musig(): " + error;
    2071                 :           0 :                 return {};
    2072                 :             :             }
    2073         [ +  + ]:          97 :             if (has_hardened) {
    2074         [ +  - ]:           2 :                 error = "musig(): cannot have hardened derivation steps";
    2075                 :           2 :                 return {};
    2076                 :             :             }
    2077                 :          99 :         } else {
    2078         [ +  - ]:          41 :             derivation_multipaths.emplace_back();
    2079                 :             :         }
    2080                 :             : 
    2081                 :             :         // Makes sure that all providers vectors in providers are the given length, or exactly length 1
    2082                 :             :         // Length 1 vectors have the single provider cloned until it matches the given length.
    2083                 :         217 :         const auto& clone_providers = [&providers](size_t length) -> bool {
    2084         [ +  + ]:         316 :             for (auto& multipath_providers : providers) {
    2085   [ -  +  +  + ]:         235 :                 if (multipath_providers.size() == 1) {
    2086         [ +  + ]:         324 :                     for (size_t i = 1; i < length; ++i) {
    2087         [ +  - ]:         176 :                         multipath_providers.emplace_back(multipath_providers.at(0)->Clone());
    2088                 :             :                     }
    2089         [ +  - ]:          87 :                 } else if (multipath_providers.size() != length) {
    2090                 :             :                     return false;
    2091                 :             :                 }
    2092                 :             :             }
    2093                 :             :             return true;
    2094                 :         136 :         };
    2095                 :             : 
    2096                 :             :         // Emplace the final MuSigPubkeyProvider into ret with the pubkey providers from the specified provider vectors index
    2097                 :             :         // and the path from the specified path index
    2098                 :         368 :         const auto& emplace_final_provider = [&ret, &key_exp_index, &deriv_type, &derivation_multipaths, &providers](size_t vec_idx, size_t path_idx) -> void {
    2099                 :         232 :             KeyPath& path = derivation_multipaths.at(path_idx);
    2100                 :         232 :             std::vector<std::unique_ptr<PubkeyProvider>> pubs;
    2101   [ -  +  +  - ]:         232 :             pubs.reserve(providers.size());
    2102         [ +  + ]:         879 :             for (auto& vec : providers) {
    2103   [ +  -  +  - ]:         647 :                 pubs.emplace_back(std::move(vec.at(vec_idx)));
    2104                 :             :             }
    2105   [ +  -  +  - ]:         232 :             ret.emplace_back(std::make_unique<MuSigPubkeyProvider>(key_exp_index, std::move(pubs), path, deriv_type));
    2106                 :         232 :         };
    2107                 :             : 
    2108   [ +  +  +  + ]:         170 :         if (max_multipath_len > 1 && derivation_multipaths.size() > 1) {
    2109         [ +  - ]:           2 :             error = "musig(): Cannot have multipath participant keys if musig() is also multipath";
    2110                 :           2 :             return {};
    2111         [ +  + ]:         134 :         } else if (max_multipath_len > 1) {
    2112   [ +  -  -  + ]:          32 :             if (!clone_providers(max_multipath_len)) {
    2113         [ #  # ]:           0 :                 error = strprintf("musig(): Multipath derivation paths have mismatched lengths");
    2114                 :           0 :                 return {};
    2115                 :             :             }
    2116         [ +  + ]:         106 :             for (size_t i = 0; i < max_multipath_len; ++i) {
    2117                 :             :                 // Final MuSigPubkeyProvider uses participant pubkey providers at each multipath position, and the first (and only) path
    2118         [ +  - ]:          74 :                 emplace_final_provider(i, 0);
    2119                 :             :             }
    2120   [ -  +  +  + ]:         102 :         } else if (derivation_multipaths.size() > 1) {
    2121                 :             :             // All key provider vectors should be length 1. Clone them until they have the same length as paths
    2122   [ +  -  -  + ]:          49 :             if (!Assume(clone_providers(derivation_multipaths.size()))) {
    2123         [ #  # ]:           0 :                 error = "musig(): Multipath derivation path with multipath participants is disallowed"; // This error is unreachable due to earlier check
    2124                 :           0 :                 return {};
    2125                 :             :             }
    2126   [ -  +  +  + ]:         154 :             for (size_t i = 0; i < derivation_multipaths.size(); ++i) {
    2127                 :             :                 // Final MuSigPubkeyProvider uses cloned participant pubkey providers, and the multipath derivation paths
    2128         [ +  - ]:         105 :                 emplace_final_provider(i, i);
    2129                 :             :             }
    2130                 :             :         } else {
    2131                 :             :             // No multipath derivation, MuSigPubkeyProvider uses the first (and only) participant pubkey providers, and the first (and only) path
    2132         [ +  - ]:          53 :             emplace_final_provider(0, 0);
    2133                 :             :         }
    2134                 :         134 :         ++key_exp_index; // Increment key expression index for the MuSigPubkeyProvider too
    2135                 :         134 :         return ret;
    2136                 :         302 :     }
    2137                 :             : 
    2138         [ +  - ]:       28077 :     auto origin_split = Split(sp, ']');
    2139   [ -  +  +  + ]:       28077 :     if (origin_split.size() > 2) {
    2140         [ +  - ]:           4 :         error = "Multiple ']' characters found for a single pubkey";
    2141                 :           4 :         return {};
    2142                 :             :     }
    2143                 :             :     // This is set if either the origin or path suffix contains a hardened derivation.
    2144                 :       28073 :     bool apostrophe = false;
    2145         [ +  + ]:       28073 :     if (origin_split.size() == 1) {
    2146         [ +  - ]:       23093 :         return ParsePubkeyInner(key_exp_index, origin_split[0], ctx, out, apostrophe, error);
    2147                 :             :     }
    2148   [ +  -  +  + ]:        4980 :     if (origin_split[0].empty() || origin_split[0][0] != '[') {
    2149                 :           6 :         error = strprintf("Key origin start '[ character expected but not found, got '%c' instead",
    2150   [ +  -  +  - ]:           2 :                           origin_split[0].empty() ? /** empty, implies split char */ ']' : origin_split[0][0]);
    2151                 :           2 :         return {};
    2152                 :             :     }
    2153         [ +  - ]:        4978 :     auto slash_split = Split(origin_split[0].subspan(1), '/');
    2154         [ +  + ]:        4978 :     if (slash_split[0].size() != 8) {
    2155         [ +  - ]:           6 :         error = strprintf("Fingerprint is not 4 bytes (%u characters instead of 8 characters)", slash_split[0].size());
    2156                 :           6 :         return {};
    2157                 :             :     }
    2158   [ +  -  -  + ]:        9944 :     std::string fpr_hex = std::string(slash_split[0].begin(), slash_split[0].end());
    2159   [ -  +  +  -  :        4972 :     if (!IsHex(fpr_hex)) {
                   +  + ]
    2160         [ +  - ]:           2 :         error = strprintf("Fingerprint '%s' is not hex", fpr_hex);
    2161                 :           2 :         return {};
    2162                 :             :     }
    2163   [ -  +  +  - ]:        4970 :     auto fpr_bytes = ParseHex(fpr_hex);
    2164         [ -  + ]:        4970 :     KeyOriginInfo info;
    2165                 :        4970 :     static_assert(sizeof(info.fingerprint) == 4, "Fingerprint must be 4 bytes");
    2166   [ -  +  -  + ]:        4970 :     assert(fpr_bytes.size() == 4);
    2167                 :        4970 :     std::copy(fpr_bytes.begin(), fpr_bytes.end(), info.fingerprint);
    2168                 :        4970 :     std::vector<KeyPath> path;
    2169   [ +  -  +  + ]:        4970 :     if (!ParseKeyPath(slash_split, path, apostrophe, error, /*allow_multipath=*/false)) return {};
    2170   [ +  -  +  - ]:        4968 :     info.path = path.at(0);
    2171         [ +  - ]:        4968 :     auto providers = ParsePubkeyInner(key_exp_index, origin_split[1], ctx, out, apostrophe, error);
    2172         [ +  + ]:        4968 :     if (providers.empty()) return {};
    2173   [ -  +  +  - ]:        4966 :     ret.reserve(providers.size());
    2174         [ +  + ]:       10027 :     for (auto& prov : providers) {
    2175   [ +  -  +  - ]:       10122 :         ret.emplace_back(std::make_unique<OriginPubkeyProvider>(prov->m_expr_index, info, std::move(prov), apostrophe));
    2176                 :             :     }
    2177                 :        4966 :     return ret;
    2178                 :       43161 : }
    2179                 :             : 
    2180                 :      326226 : std::unique_ptr<PubkeyProvider> InferPubkey(const CPubKey& pubkey, ParseScriptContext ctx, const SigningProvider& provider)
    2181                 :             : {
    2182                 :             :     // Key cannot be hybrid
    2183         [ +  + ]:      326226 :     if (!pubkey.IsValidNonHybrid()) {
    2184                 :           7 :         return nullptr;
    2185                 :             :     }
    2186                 :             :     // Uncompressed is only allowed in TOP and P2SH contexts
    2187   [ +  +  +  + ]:      326219 :     if (ctx != ParseScriptContext::TOP && ctx != ParseScriptContext::P2SH && !pubkey.IsCompressed()) {
    2188                 :           5 :         return nullptr;
    2189                 :             :     }
    2190                 :      326214 :     std::unique_ptr<PubkeyProvider> key_provider = std::make_unique<ConstPubkeyProvider>(0, pubkey, false);
    2191         [ +  - ]:      326214 :     KeyOriginInfo info;
    2192   [ +  -  +  -  :      326214 :     if (provider.GetKeyOrigin(pubkey.GetID(), info)) {
                   +  + ]
    2193   [ +  -  -  + ]:      325234 :         return std::make_unique<OriginPubkeyProvider>(0, std::move(info), std::move(key_provider), /*apostrophe=*/false);
    2194                 :             :     }
    2195                 :         980 :     return key_provider;
    2196                 :      326214 : }
    2197                 :             : 
    2198                 :      134057 : std::unique_ptr<PubkeyProvider> InferXOnlyPubkey(const XOnlyPubKey& xkey, ParseScriptContext ctx, const SigningProvider& provider)
    2199                 :             : {
    2200                 :      134057 :     CPubKey pubkey{xkey.GetEvenCorrespondingCPubKey()};
    2201                 :      134057 :     std::unique_ptr<PubkeyProvider> key_provider = std::make_unique<ConstPubkeyProvider>(0, pubkey, true);
    2202         [ +  - ]:      134057 :     KeyOriginInfo info;
    2203   [ +  -  +  + ]:      134057 :     if (provider.GetKeyOriginByXOnly(xkey, info)) {
    2204   [ +  -  -  + ]:      119323 :         return std::make_unique<OriginPubkeyProvider>(0, std::move(info), std::move(key_provider), /*apostrophe=*/false);
    2205                 :             :     }
    2206                 :       14734 :     return key_provider;
    2207                 :      134057 : }
    2208                 :             : 
    2209                 :             : /**
    2210                 :             :  * The context for parsing a Miniscript descriptor (either from Script or from its textual representation).
    2211                 :             :  */
    2212                 :        1164 : struct KeyParser {
    2213                 :             :     //! The Key type is an index in DescriptorImpl::m_pubkey_args
    2214                 :             :     using Key = uint32_t;
    2215                 :             :     //! Must not be nullptr if parsing from string.
    2216                 :             :     FlatSigningProvider* m_out;
    2217                 :             :     //! Must not be nullptr if parsing from Script.
    2218                 :             :     const SigningProvider* m_in;
    2219                 :             :     //! List of multipath expanded keys contained in the Miniscript.
    2220                 :             :     mutable std::vector<std::vector<std::unique_ptr<PubkeyProvider>>> m_keys;
    2221                 :             :     //! Used to detect key parsing errors within a Miniscript.
    2222                 :             :     mutable std::string m_key_parsing_error;
    2223                 :             :     //! The script context we're operating within (Tapscript or P2WSH).
    2224                 :             :     const miniscript::MiniscriptContext m_script_ctx;
    2225                 :             :     //! The current key expression index
    2226                 :             :     uint32_t& m_expr_index;
    2227                 :             : 
    2228                 :        1164 :     KeyParser(FlatSigningProvider* out LIFETIMEBOUND, const SigningProvider* in LIFETIMEBOUND,
    2229                 :             :               miniscript::MiniscriptContext ctx, uint32_t& key_exp_index LIFETIMEBOUND)
    2230                 :        1164 :         : m_out(out), m_in(in), m_script_ctx(ctx), m_expr_index(key_exp_index) {}
    2231                 :             : 
    2232                 :        4494 :     bool KeyCompare(const Key& a, const Key& b) const {
    2233                 :        4494 :         return *m_keys.at(a).at(0) < *m_keys.at(b).at(0);
    2234                 :             :     }
    2235                 :             : 
    2236                 :        1966 :     ParseScriptContext ParseContext() const {
    2237      [ +  -  + ]:        1966 :         switch (m_script_ctx) {
    2238                 :             :             case miniscript::MiniscriptContext::P2WSH: return ParseScriptContext::P2WSH;
    2239                 :         557 :             case miniscript::MiniscriptContext::TAPSCRIPT: return ParseScriptContext::P2TR;
    2240                 :             :         }
    2241                 :           0 :         assert(false);
    2242                 :             :     }
    2243                 :             : 
    2244                 :         439 :     std::optional<Key> FromString(std::span<const char>& in) const
    2245                 :             :     {
    2246         [ -  + ]:         439 :         assert(m_out);
    2247         [ -  + ]:         439 :         Key key = m_keys.size();
    2248                 :         439 :         auto pk = ParsePubkey(m_expr_index, in, ParseContext(), *m_out, m_key_parsing_error);
    2249         [ +  + ]:         439 :         if (pk.empty()) return {};
    2250         [ +  - ]:         437 :         m_keys.emplace_back(std::move(pk));
    2251                 :         437 :         return key;
    2252                 :         439 :     }
    2253                 :             : 
    2254                 :          30 :     std::optional<std::string> ToString(const Key& key, bool&) const
    2255                 :             :     {
    2256                 :          30 :         return m_keys.at(key).at(0)->ToString();
    2257                 :             :     }
    2258                 :             : 
    2259                 :        1205 :     template<typename I> std::optional<Key> FromPKBytes(I begin, I end) const
    2260                 :             :     {
    2261         [ -  + ]:        1205 :         assert(m_in);
    2262         [ -  + ]:        1205 :         Key key = m_keys.size();
    2263   [ +  +  +  - ]:        1205 :         if (miniscript::IsTapscript(m_script_ctx) && end - begin == 32) {
    2264                 :         274 :             XOnlyPubKey pubkey;
    2265                 :         274 :             std::copy(begin, end, pubkey.begin());
    2266         [ +  - ]:         274 :             if (auto pubkey_provider = InferXOnlyPubkey(pubkey, ParseContext(), *m_in)) {
    2267         [ +  - ]:         274 :                 m_keys.emplace_back();
    2268         [ +  - ]:         274 :                 m_keys.back().push_back(std::move(pubkey_provider));
    2269                 :         274 :                 return key;
    2270                 :             :             }
    2271         [ +  - ]:         931 :         } else if (!miniscript::IsTapscript(m_script_ctx)) {
    2272                 :         931 :             CPubKey pubkey(begin, end);
    2273         [ +  + ]:         931 :             if (auto pubkey_provider = InferPubkey(pubkey, ParseContext(), *m_in)) {
    2274         [ +  - ]:         929 :                 m_keys.emplace_back();
    2275         [ +  - ]:         929 :                 m_keys.back().push_back(std::move(pubkey_provider));
    2276                 :         929 :                 return key;
    2277                 :             :             }
    2278                 :             :         }
    2279                 :           2 :         return {};
    2280                 :             :     }
    2281                 :             : 
    2282         [ -  + ]:         322 :     template<typename I> std::optional<Key> FromPKHBytes(I begin, I end) const
    2283                 :             :     {
    2284         [ -  + ]:         322 :         assert(end - begin == 20);
    2285         [ -  + ]:         322 :         assert(m_in);
    2286                 :         322 :         uint160 hash;
    2287                 :         322 :         std::copy(begin, end, hash.begin());
    2288                 :         322 :         CKeyID keyid(hash);
    2289                 :         322 :         CPubKey pubkey;
    2290         [ +  - ]:         322 :         if (m_in->GetPubKey(keyid, pubkey)) {
    2291         [ +  + ]:         322 :             if (auto pubkey_provider = InferPubkey(pubkey, ParseContext(), *m_in)) {
    2292         [ -  + ]:         320 :                 Key key = m_keys.size();
    2293         [ +  - ]:         320 :                 m_keys.emplace_back();
    2294         [ +  - ]:         320 :                 m_keys.back().push_back(std::move(pubkey_provider));
    2295                 :         320 :                 return key;
    2296                 :             :             }
    2297                 :             :         }
    2298                 :           2 :         return {};
    2299                 :             :     }
    2300                 :             : 
    2301                 :      997480 :     miniscript::MiniscriptContext MsContext() const {
    2302   [ +  -  +  -  :      997480 :         return m_script_ctx;
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          -  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  -  
          +  -  +  -  -  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  +  +  -  
                   +  - ]
    2303                 :             :     }
    2304                 :             : };
    2305                 :             : 
    2306                 :             : /** Parse a script in a particular context. */
    2307                 :             : // NOLINTNEXTLINE(misc-no-recursion)
    2308                 :       13480 : std::vector<std::unique_ptr<DescriptorImpl>> ParseScript(uint32_t& key_exp_index, std::span<const char>& sp, ParseScriptContext ctx, FlatSigningProvider& out, std::string& error)
    2309                 :             : {
    2310                 :       13480 :     using namespace script;
    2311         [ +  - ]:       13480 :     Assume(ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH || ctx == ParseScriptContext::P2TR);
    2312                 :       13480 :     std::vector<std::unique_ptr<DescriptorImpl>> ret;
    2313         [ +  - ]:       13480 :     auto expr = Expr(sp);
    2314   [ +  -  +  -  :       13480 :     if (Func("pk", expr)) {
                   +  + ]
    2315         [ +  - ]:         665 :         auto pubkeys = ParsePubkey(key_exp_index, expr, ctx, out, error);
    2316         [ +  + ]:         665 :         if (pubkeys.empty()) {
    2317         [ +  - ]:          12 :             error = strprintf("pk(): %s", error);
    2318                 :          12 :             return {};
    2319                 :             :         }
    2320         [ +  + ]:        1424 :         for (auto& pubkey : pubkeys) {
    2321   [ +  -  +  - ]:        1542 :             ret.emplace_back(std::make_unique<PKDescriptor>(std::move(pubkey), ctx == ParseScriptContext::P2TR));
    2322                 :             :         }
    2323                 :         653 :         return ret;
    2324                 :         665 :     }
    2325   [ +  +  +  -  :       25409 :     if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH) && Func("pkh", expr)) {
          +  -  +  +  +  
                      + ]
    2326         [ +  - ]:        1689 :         auto pubkeys = ParsePubkey(key_exp_index, expr, ctx, out, error);
    2327         [ +  + ]:        1689 :         if (pubkeys.empty()) {
    2328         [ +  - ]:          19 :             error = strprintf("pkh(): %s", error);
    2329                 :          19 :             return {};
    2330                 :             :         }
    2331         [ +  + ]:        3360 :         for (auto& pubkey : pubkeys) {
    2332   [ +  -  +  - ]:        3380 :             ret.emplace_back(std::make_unique<PKHDescriptor>(std::move(pubkey)));
    2333                 :             :         }
    2334                 :        1670 :         return ret;
    2335                 :        1689 :     }
    2336   [ +  +  +  -  :       19978 :     if (ctx == ParseScriptContext::TOP && Func("combo", expr)) {
          +  -  +  +  +  
                      + ]
    2337         [ +  - ]:         551 :         auto pubkeys = ParsePubkey(key_exp_index, expr, ctx, out, error);
    2338         [ +  + ]:         551 :         if (pubkeys.empty()) {
    2339         [ +  - ]:           5 :             error = strprintf("combo(): %s", error);
    2340                 :           5 :             return {};
    2341                 :             :         }
    2342         [ +  + ]:        1092 :         for (auto& pubkey : pubkeys) {
    2343   [ +  -  +  - ]:        1092 :             ret.emplace_back(std::make_unique<ComboDescriptor>(std::move(pubkey)));
    2344                 :             :         }
    2345                 :         546 :         return ret;
    2346   [ +  -  +  -  :       11126 :     } else if (Func("combo", expr)) {
                   +  + ]
    2347         [ +  - ]:           2 :         error = "Can only have combo() at top level";
    2348                 :           2 :         return {};
    2349                 :             :     }
    2350   [ +  -  +  - ]:       10573 :     const bool multi = Func("multi", expr);
    2351   [ +  +  +  -  :       20929 :     const bool sortedmulti = !multi && Func("sortedmulti", expr);
             +  -  +  + ]
    2352   [ +  +  +  -  :       20911 :     const bool multi_a = !(multi || sortedmulti) && Func("multi_a", expr);
             +  -  +  + ]
    2353   [ +  +  +  +  :       20820 :     const bool sortedmulti_a = !(multi || sortedmulti || multi_a) && Func("sortedmulti_a", expr);
          +  -  +  -  +  
                      + ]
    2354   [ +  +  +  +  :       10573 :     if (((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH) && (multi || sortedmulti)) ||
             +  +  +  + ]
    2355   [ +  +  +  + ]:         221 :         (ctx == ParseScriptContext::P2TR && (multi_a || sortedmulti_a))) {
    2356         [ +  - ]:         368 :         auto threshold = Expr(expr);
    2357                 :         368 :         uint32_t thres;
    2358                 :         368 :         std::vector<std::vector<std::unique_ptr<PubkeyProvider>>> providers; // List of multipath expanded pubkeys
    2359         [ +  + ]:         368 :         if (const auto maybe_thres{ToIntegral<uint32_t>(std::string_view{threshold.begin(), threshold.end()})}) {
    2360                 :         364 :             thres = *maybe_thres;
    2361                 :             :         } else {
    2362   [ +  -  +  - ]:           8 :             error = strprintf("Multi threshold '%s' is not valid", std::string(threshold.begin(), threshold.end()));
    2363                 :           4 :             return {};
    2364                 :             :         }
    2365                 :         364 :         size_t script_size = 0;
    2366                 :         364 :         size_t max_providers_len = 0;
    2367         [ +  + ]:       19311 :         while (expr.size()) {
    2368   [ +  -  +  -  :       18962 :             if (!Const(",", expr)) {
                   +  + ]
    2369         [ +  - ]:           1 :                 error = strprintf("Multi: expected ',', got '%c'", expr[0]);
    2370                 :           1 :                 return {};
    2371                 :             :             }
    2372         [ +  - ]:       18961 :             auto arg = Expr(expr);
    2373         [ +  - ]:       18961 :             auto pks = ParsePubkey(key_exp_index, arg, ctx, out, error);
    2374         [ +  + ]:       18961 :             if (pks.empty()) {
    2375         [ +  - ]:          14 :                 error = strprintf("Multi: %s", error);
    2376                 :          14 :                 return {};
    2377                 :             :             }
    2378   [ +  -  +  - ]:       18947 :             script_size += pks.at(0)->GetSize() + 1;
    2379   [ -  +  +  + ]:       18947 :             max_providers_len = std::max(max_providers_len, pks.size());
    2380         [ +  - ]:       18947 :             providers.emplace_back(std::move(pks));
    2381                 :       18961 :         }
    2382   [ +  +  +  +  :         564 :         if ((multi || sortedmulti) && (providers.empty() || providers.size() > MAX_PUBKEYS_PER_MULTISIG)) {
             +  +  -  + ]
    2383   [ -  +  +  - ]:           1 :             error = strprintf("Cannot have %u keys in multisig; must have between 1 and %d keys, inclusive", providers.size(), MAX_PUBKEYS_PER_MULTISIG);
    2384                 :           1 :             return {};
    2385   [ +  +  +  +  :         480 :         } else if ((multi_a || sortedmulti_a) && (providers.empty() || providers.size() > MAX_PUBKEYS_PER_MULTI_A)) {
             +  +  -  + ]
    2386   [ -  +  +  - ]:           1 :             error = strprintf("Cannot have %u keys in multi_a; must have between 1 and %d keys, inclusive", providers.size(), MAX_PUBKEYS_PER_MULTI_A);
    2387                 :           1 :             return {};
    2388         [ +  + ]:         347 :         } else if (thres < 1) {
    2389         [ +  - ]:           2 :             error = strprintf("Multisig threshold cannot be %d, must be at least 1", thres);
    2390                 :           2 :             return {};
    2391   [ -  +  +  + ]:         345 :         } else if (thres > providers.size()) {
    2392         [ +  - ]:           2 :             error = strprintf("Multisig threshold cannot be larger than the number of keys; threshold is %d but only %u keys specified", thres, providers.size());
    2393                 :           2 :             return {};
    2394                 :             :         }
    2395         [ +  + ]:         343 :         if (ctx == ParseScriptContext::TOP) {
    2396         [ +  + ]:          24 :             if (providers.size() > 3) {
    2397         [ +  - ]:           2 :                 error = strprintf("Cannot have %u pubkeys in bare multisig; only at most 3 pubkeys", providers.size());
    2398                 :           2 :                 return {};
    2399                 :             :             }
    2400                 :             :         }
    2401         [ +  + ]:         341 :         if (ctx == ParseScriptContext::P2SH) {
    2402                 :             :             // This limits the maximum number of compressed pubkeys to 15.
    2403         [ +  + ]:          57 :             if (script_size + 3 > MAX_SCRIPT_ELEMENT_SIZE) {
    2404         [ +  - ]:           4 :                 error = strprintf("P2SH script is too large, %d bytes is larger than %d bytes", script_size + 3, MAX_SCRIPT_ELEMENT_SIZE);
    2405                 :           4 :                 return {};
    2406                 :             :             }
    2407                 :             :         }
    2408                 :             : 
    2409                 :             :         // Make sure all vecs are of the same length, or exactly length 1
    2410                 :             :         // For length 1 vectors, clone key providers until vector is the same length
    2411         [ +  + ]:       19199 :         for (auto& vec : providers) {
    2412   [ -  +  +  + ]:       18864 :             if (vec.size() == 1) {
    2413         [ +  + ]:       18832 :                 for (size_t i = 1; i < max_providers_len; ++i) {
    2414   [ +  -  +  -  :          18 :                     vec.emplace_back(vec.at(0)->Clone());
                   +  - ]
    2415                 :             :                 }
    2416         [ +  + ]:          50 :             } else if (vec.size() != max_providers_len) {
    2417         [ +  - ]:           2 :                 error = strprintf("multi(): Multipath derivation paths have mismatched lengths");
    2418                 :           2 :                 return {};
    2419                 :             :             }
    2420                 :             :         }
    2421                 :             : 
    2422                 :             :         // Build the final descriptors vector
    2423         [ +  + ]:         697 :         for (size_t i = 0; i < max_providers_len; ++i) {
    2424                 :             :             // Build final pubkeys vectors by retrieving the i'th subscript for each vector in subscripts
    2425                 :         362 :             std::vector<std::unique_ptr<PubkeyProvider>> pubs;
    2426   [ -  +  +  - ]:         362 :             pubs.reserve(providers.size());
    2427         [ +  + ]:       19294 :             for (auto& pub : providers) {
    2428   [ +  -  +  - ]:       18932 :                 pubs.emplace_back(std::move(pub.at(i)));
    2429                 :             :             }
    2430   [ +  +  +  + ]:         362 :             if (multi || sortedmulti) {
    2431   [ +  -  +  - ]:         460 :                 ret.emplace_back(std::make_unique<MultisigDescriptor>(thres, std::move(pubs), sortedmulti));
    2432                 :             :             } else {
    2433   [ +  -  +  - ]:         264 :                 ret.emplace_back(std::make_unique<MultiADescriptor>(thres, std::move(pubs), sortedmulti_a));
    2434                 :             :             }
    2435                 :         362 :         }
    2436                 :         335 :         return ret;
    2437   [ +  -  -  + ]:       10573 :     } else if (multi || sortedmulti) {
    2438         [ #  # ]:           0 :         error = "Can only have multi/sortedmulti at top level, in sh(), or in wsh()";
    2439                 :           0 :         return {};
    2440   [ +  -  -  + ]:       10205 :     } else if (multi_a || sortedmulti_a) {
    2441         [ #  # ]:           0 :         error = "Can only have multi_a/sortedmulti_a inside tr()";
    2442                 :           0 :         return {};
    2443                 :             :     }
    2444   [ +  +  +  -  :       20215 :     if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH) && Func("wpkh", expr)) {
          +  -  +  +  +  
                      + ]
    2445         [ +  - ]:        3491 :         auto pubkeys = ParsePubkey(key_exp_index, expr, ParseScriptContext::P2WPKH, out, error);
    2446         [ +  + ]:        3491 :         if (pubkeys.empty()) {
    2447         [ +  - ]:          27 :             error = strprintf("wpkh(): %s", error);
    2448                 :          27 :             return {};
    2449                 :             :         }
    2450         [ +  + ]:        6945 :         for (auto& pubkey : pubkeys) {
    2451   [ +  -  +  - ]:        6962 :             ret.emplace_back(std::make_unique<WPKHDescriptor>(std::move(pubkey)));
    2452                 :             :         }
    2453                 :        3464 :         return ret;
    2454   [ +  -  +  -  :       10205 :     } else if (Func("wpkh", expr)) {
                   +  + ]
    2455         [ +  - ]:           3 :         error = "Can only have wpkh() at top level or inside sh()";
    2456                 :           3 :         return {};
    2457                 :             :     }
    2458   [ +  +  +  -  :       13154 :     if (ctx == ParseScriptContext::TOP && Func("sh", expr)) {
          +  -  +  +  +  
                      + ]
    2459         [ +  - ]:        1823 :         auto descs = ParseScript(key_exp_index, expr, ParseScriptContext::P2SH, out, error);
    2460   [ +  +  +  - ]:        1823 :         if (descs.empty() || expr.size()) return {};
    2461                 :        1797 :         std::vector<std::unique_ptr<DescriptorImpl>> ret;
    2462   [ -  +  +  - ]:        1797 :         ret.reserve(descs.size());
    2463         [ +  + ]:        3613 :         for (auto& desc : descs) {
    2464   [ +  -  +  -  :        1816 :             ret.push_back(std::make_unique<SHDescriptor>(std::move(desc)));
                   -  + ]
    2465                 :             :         }
    2466                 :        1797 :         return ret;
    2467   [ +  -  +  -  :        6711 :     } else if (Func("sh", expr)) {
                   +  + ]
    2468         [ +  - ]:           6 :         error = "Can only have sh() at top level";
    2469                 :           6 :         return {};
    2470                 :             :     }
    2471   [ +  +  +  -  :        9575 :     if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH) && Func("wsh", expr)) {
          +  -  +  +  +  
                      + ]
    2472         [ +  - ]:         282 :         auto descs = ParseScript(key_exp_index, expr, ParseScriptContext::P2WSH, out, error);
    2473   [ +  +  +  - ]:         282 :         if (descs.empty() || expr.size()) return {};
    2474         [ +  + ]:         479 :         for (auto& desc : descs) {
    2475   [ +  -  +  - ]:         494 :             ret.emplace_back(std::make_unique<WSHDescriptor>(std::move(desc)));
    2476                 :             :         }
    2477                 :         232 :         return ret;
    2478   [ +  -  +  -  :        4882 :     } else if (Func("wsh", expr)) {
                   +  + ]
    2479         [ +  - ]:           3 :         error = "Can only have wsh() at top level or inside sh()";
    2480                 :           3 :         return {};
    2481                 :             :     }
    2482   [ +  +  +  -  :        9001 :     if (ctx == ParseScriptContext::TOP && Func("addr", expr)) {
          +  -  +  +  +  
                      + ]
    2483   [ +  -  +  - ]:         190 :         CTxDestination dest = DecodeDestination(std::string(expr.begin(), expr.end()));
    2484   [ +  -  +  + ]:          95 :         if (!IsValidDestination(dest)) {
    2485         [ +  - ]:           3 :             error = "Address is not valid";
    2486                 :           3 :             return {};
    2487                 :             :         }
    2488   [ +  -  +  - ]:          92 :         ret.emplace_back(std::make_unique<AddressDescriptor>(std::move(dest)));
    2489                 :          92 :         return ret;
    2490   [ +  -  +  -  :        4597 :     } else if (Func("addr", expr)) {
                   -  + ]
    2491         [ #  # ]:           0 :         error = "Can only have addr() at top level";
    2492                 :           0 :         return {};
    2493                 :             :     }
    2494   [ +  +  +  -  :        8811 :     if (ctx == ParseScriptContext::TOP && Func("tr", expr)) {
          +  -  +  +  +  
                      + ]
    2495         [ +  - ]:        1964 :         auto arg = Expr(expr);
    2496         [ +  - ]:        1964 :         auto internal_keys = ParsePubkey(key_exp_index, arg, ParseScriptContext::P2TR, out, error);
    2497         [ +  + ]:        1964 :         if (internal_keys.empty()) {
    2498         [ +  - ]:          20 :             error = strprintf("tr(): %s", error);
    2499                 :          20 :             return {};
    2500                 :             :         }
    2501         [ -  + ]:        1944 :         size_t max_providers_len = internal_keys.size();
    2502                 :        1944 :         std::vector<std::vector<std::unique_ptr<DescriptorImpl>>> subscripts; //!< list of multipath expanded script subexpressions
    2503                 :        1944 :         std::vector<int> depths; //!< depth in the tree of each subexpression (same length subscripts)
    2504         [ +  + ]:        1944 :         if (expr.size()) {
    2505   [ +  -  +  -  :         364 :             if (!Const(",", expr)) {
                   -  + ]
    2506         [ #  # ]:           0 :                 error = strprintf("tr: expected ',', got '%c'", expr[0]);
    2507                 :           0 :                 return {};
    2508                 :             :             }
    2509                 :             :             /** The path from the top of the tree to what we're currently processing.
    2510                 :             :              * branches[i] == false: left branch in the i'th step from the top; true: right branch.
    2511                 :             :              */
    2512                 :         364 :             std::vector<bool> branches;
    2513                 :             :             // Loop over all provided scripts. In every iteration exactly one script will be processed.
    2514                 :             :             // Use a do-loop because inside this if-branch we expect at least one script.
    2515                 :             :             do {
    2516                 :             :                 // First process all open braces.
    2517   [ +  -  +  -  :        1300 :                 while (Const("{", expr)) {
                   +  + ]
    2518         [ +  - ]:         479 :                     branches.push_back(false); // new left branch
    2519         [ -  + ]:         479 :                     if (branches.size() > TAPROOT_CONTROL_MAX_NODE_COUNT) {
    2520         [ #  # ]:           0 :                         error = strprintf("tr() supports at most %i nesting levels", TAPROOT_CONTROL_MAX_NODE_COUNT);
    2521                 :           0 :                         return {};
    2522                 :             :                     }
    2523                 :             :                 }
    2524                 :             :                 // Process the actual script expression.
    2525         [ +  - ]:         821 :                 auto sarg = Expr(expr);
    2526   [ +  -  +  - ]:         821 :                 subscripts.emplace_back(ParseScript(key_exp_index, sarg, ParseScriptContext::P2TR, out, error));
    2527         [ +  + ]:         821 :                 if (subscripts.back().empty()) return {};
    2528   [ -  +  +  + ]:         818 :                 max_providers_len = std::max(max_providers_len, subscripts.back().size());
    2529         [ +  - ]:         818 :                 depths.push_back(branches.size());
    2530                 :             :                 // Process closing braces; one is expected for every right branch we were in.
    2531         [ +  + ]:         914 :                 while (branches.size() && branches.back()) {
    2532   [ +  -  -  +  :         457 :                     if (!Const("}", expr)) {
                   +  - ]
    2533         [ #  # ]:           0 :                         error = strprintf("tr(): expected '}' after script expression");
    2534                 :           0 :                         return {};
    2535                 :             :                     }
    2536   [ -  +  +  + ]:        1732 :                     branches.pop_back(); // move up one level after encountering '}'
    2537                 :             :                 }
    2538                 :             :                 // If after that, we're at the end of a left branch, expect a comma.
    2539   [ +  +  +  - ]:         818 :                 if (branches.size() && !branches.back()) {
    2540   [ +  -  +  -  :         457 :                     if (!Const(",", expr)) {
                   -  + ]
    2541         [ #  # ]:           0 :                         error = strprintf("tr(): expected ',' after script expression");
    2542                 :           0 :                         return {};
    2543                 :             :                     }
    2544                 :         457 :                     branches.back() = true; // And now we're in a right branch.
    2545                 :             :                 }
    2546         [ +  + ]:         818 :             } while (branches.size());
    2547                 :             :             // After we've explored a whole tree, we must be at the end of the expression.
    2548         [ -  + ]:         361 :             if (expr.size()) {
    2549         [ #  # ]:           0 :                 error = strprintf("tr(): expected ')' after script expression");
    2550                 :           0 :                 return {};
    2551                 :             :             }
    2552                 :         364 :         }
    2553   [ +  -  -  + ]:        1941 :         assert(TaprootBuilder::ValidDepths(depths));
    2554                 :             : 
    2555                 :             :         // Make sure all vecs are of the same length, or exactly length 1
    2556                 :             :         // For length 1 vectors, clone subdescs until vector is the same length
    2557         [ +  + ]:        2753 :         for (auto& vec : subscripts) {
    2558   [ -  +  +  + ]:         816 :             if (vec.size() == 1) {
    2559         [ +  + ]:         753 :                 for (size_t i = 1; i < max_providers_len; ++i) {
    2560   [ +  -  +  -  :          20 :                     vec.emplace_back(vec.at(0)->Clone());
                   +  - ]
    2561                 :             :                 }
    2562         [ +  + ]:          83 :             } else if (vec.size() != max_providers_len) {
    2563         [ +  - ]:           4 :                 error = strprintf("tr(): Multipath subscripts have mismatched lengths");
    2564                 :           4 :                 return {};
    2565                 :             :             }
    2566                 :             :         }
    2567                 :             : 
    2568   [ -  +  +  +  :        1937 :         if (internal_keys.size() > 1 && internal_keys.size() != max_providers_len) {
                   +  + ]
    2569         [ +  - ]:           2 :             error = strprintf("tr(): Multipath internal key mismatches multipath subscripts lengths");
    2570                 :           2 :             return {};
    2571                 :             :         }
    2572                 :             : 
    2573   [ -  +  +  + ]:        1995 :         while (internal_keys.size() < max_providers_len) {
    2574   [ +  -  +  -  :          60 :             internal_keys.emplace_back(internal_keys.at(0)->Clone());
                   +  - ]
    2575                 :             :         }
    2576                 :             : 
    2577                 :             :         // Build the final descriptors vector
    2578         [ +  + ]:        3971 :         for (size_t i = 0; i < max_providers_len; ++i) {
    2579                 :             :             // Build final subscripts vectors by retrieving the i'th subscript for each vector in subscripts
    2580                 :        2036 :             std::vector<std::unique_ptr<DescriptorImpl>> this_subs;
    2581   [ -  +  +  - ]:        2036 :             this_subs.reserve(subscripts.size());
    2582         [ +  + ]:        2970 :             for (auto& subs : subscripts) {
    2583   [ +  -  +  - ]:         934 :                 this_subs.emplace_back(std::move(subs.at(i)));
    2584                 :             :             }
    2585   [ +  -  +  -  :        2036 :             ret.emplace_back(std::make_unique<TRDescriptor>(std::move(internal_keys.at(i)), std::move(this_subs), depths));
                   +  - ]
    2586                 :        2036 :         }
    2587                 :        1935 :         return ret;
    2588                 :             : 
    2589                 :             : 
    2590   [ +  -  +  -  :        4502 :     } else if (Func("tr", expr)) {
                   -  + ]
    2591         [ #  # ]:           0 :         error = "Can only have tr at top level";
    2592                 :           0 :         return {};
    2593                 :             :     }
    2594   [ +  +  +  -  :        4883 :     if (ctx == ParseScriptContext::TOP && Func("rawtr", expr)) {
          +  -  +  +  +  
                      + ]
    2595         [ +  - ]:          71 :         auto arg = Expr(expr);
    2596         [ +  + ]:          71 :         if (expr.size()) {
    2597         [ +  - ]:           1 :             error = strprintf("rawtr(): only one key expected.");
    2598                 :           1 :             return {};
    2599                 :             :         }
    2600         [ +  - ]:          70 :         auto output_keys = ParsePubkey(key_exp_index, arg, ParseScriptContext::P2TR, out, error);
    2601         [ -  + ]:          70 :         if (output_keys.empty()) {
    2602         [ #  # ]:           0 :             error = strprintf("rawtr(): %s", error);
    2603                 :           0 :             return {};
    2604                 :             :         }
    2605         [ +  + ]:         183 :         for (auto& pubkey : output_keys) {
    2606   [ +  -  +  - ]:         226 :             ret.emplace_back(std::make_unique<RawTRDescriptor>(std::move(pubkey)));
    2607                 :             :         }
    2608                 :          70 :         return ret;
    2609   [ +  -  +  -  :        2537 :     } else if (Func("rawtr", expr)) {
                   -  + ]
    2610         [ #  # ]:           0 :         error = "Can only have rawtr at top level";
    2611                 :           0 :         return {};
    2612                 :             :     }
    2613   [ +  +  +  -  :        4741 :     if (ctx == ParseScriptContext::TOP && Func("unused", expr)) {
          +  -  +  +  +  
                      + ]
    2614                 :             :         // Check for only one expression, should not find commas, brackets, or parentheses
    2615         [ +  - ]:          20 :         auto arg = Expr(expr);
    2616         [ +  + ]:          20 :         if (expr.size()) {
    2617         [ +  - ]:           2 :             error = strprintf("unused(): only one key expected");
    2618                 :           2 :             return {};
    2619                 :             :         }
    2620         [ +  - ]:          18 :         auto keys = ParsePubkey(key_exp_index, arg, ctx, out, error);
    2621         [ +  + ]:          18 :         if (keys.empty()) return {};
    2622         [ +  + ]:          28 :         for (auto& pubkey : keys) {
    2623   [ +  -  +  + ]:          15 :             if (pubkey->IsRange()) {
    2624         [ +  - ]:           2 :                 error = "unused(): key cannot be ranged";
    2625                 :           2 :                 return {};
    2626                 :             :             }
    2627   [ +  -  +  - ]:          26 :             ret.emplace_back(std::make_unique<UnusedDescriptor>(std::move(pubkey)));
    2628                 :             :         }
    2629                 :          13 :         return ret;
    2630   [ +  -  +  -  :        2465 :     } else if (Func("unused", expr)) {
                   +  + ]
    2631         [ +  - ]:           2 :         error = "Can only have unused at top level";
    2632                 :           2 :         return {};
    2633                 :             :     }
    2634   [ +  +  +  -  :        4699 :     if (ctx == ParseScriptContext::TOP && Func("raw", expr)) {
          +  -  +  +  +  
                      + ]
    2635   [ +  -  -  + ]:        3824 :         std::string str(expr.begin(), expr.end());
    2636   [ -  +  +  -  :        1912 :         if (!IsHex(str)) {
                   +  + ]
    2637         [ +  - ]:           2 :             error = "Raw script is not hex";
    2638                 :           2 :             return {};
    2639                 :             :         }
    2640   [ -  +  +  - ]:        1910 :         auto bytes = ParseHex(str);
    2641   [ +  -  +  - ]:        3820 :         ret.emplace_back(std::make_unique<RawDescriptor>(CScript(bytes.begin(), bytes.end())));
    2642                 :        1910 :         return ret;
    2643   [ +  -  +  -  :        4355 :     } else if (Func("raw", expr)) {
                   -  + ]
    2644         [ #  # ]:           0 :         error = "Can only have raw() at top level";
    2645                 :           0 :         return {};
    2646                 :             :     }
    2647                 :             :     // Process miniscript expressions.
    2648                 :         533 :     {
    2649                 :         533 :         const auto script_ctx{ctx == ParseScriptContext::P2WSH ? miniscript::MiniscriptContext::P2WSH : miniscript::MiniscriptContext::TAPSCRIPT};
    2650         [ +  - ]:         533 :         KeyParser parser(/*out = */&out, /* in = */nullptr, /* ctx = */script_ctx, key_exp_index);
    2651   [ +  -  -  + ]:        1599 :         auto node = miniscript::FromString(std::string(expr.begin(), expr.end()), parser);
    2652         [ +  + ]:         533 :         if (parser.m_key_parsing_error != "") {
    2653                 :           2 :             error = std::move(parser.m_key_parsing_error);
    2654                 :           2 :             return {};
    2655                 :             :         }
    2656         [ +  + ]:         531 :         if (node) {
    2657         [ +  + ]:         179 :             if (ctx != ParseScriptContext::P2WSH && ctx != ParseScriptContext::P2TR) {
    2658         [ +  - ]:           3 :                 error = "Miniscript expressions can only be used in wsh or tr.";
    2659                 :           3 :                 return {};
    2660                 :             :             }
    2661   [ +  +  +  + ]:         176 :             if (!node->IsSane() || node->IsNotSatisfiable()) {
    2662                 :             :                 // Try to find the first insane sub for better error reporting.
    2663         [ +  - ]:          14 :                 const auto* insane_node = &node.value();
    2664   [ +  -  +  + ]:          14 :                 if (const auto sub = node->FindInsaneSub()) insane_node = sub;
    2665         [ +  - ]:          14 :                 error = *insane_node->ToString(parser);
    2666         [ +  + ]:          14 :                 if (!insane_node->IsValid()) {
    2667         [ +  - ]:           4 :                     error += " is invalid";
    2668         [ +  + ]:          10 :                 } else if (!node->IsSane()) {
    2669         [ +  - ]:           9 :                     error += " is not sane";
    2670         [ +  + ]:           9 :                     if (!insane_node->IsNonMalleable()) {
    2671         [ +  - ]:           2 :                         error += ": malleable witnesses exist";
    2672   [ +  -  +  +  :           7 :                     } else if (insane_node == &node.value() && !insane_node->NeedsSignature()) {
                   +  + ]
    2673         [ +  - ]:           3 :                         error += ": witnesses without signature exist";
    2674         [ +  + ]:           4 :                     } else if (!insane_node->CheckTimeLocksMix()) {
    2675         [ +  - ]:           2 :                         error += ": contains mixes of timelocks expressed in blocks and seconds";
    2676         [ +  - ]:           2 :                     } else if (!insane_node->CheckDuplicateKey()) {
    2677         [ +  - ]:           2 :                         error += ": contains duplicate public keys";
    2678         [ #  # ]:           0 :                     } else if (!insane_node->ValidSatisfactions()) {
    2679         [ #  # ]:           0 :                         error += ": needs witnesses that may exceed resource limits";
    2680                 :             :                     }
    2681                 :             :                 } else {
    2682         [ +  - ]:           1 :                     error += " is not satisfiable";
    2683                 :             :                 }
    2684                 :          14 :                 return {};
    2685                 :             :             }
    2686                 :             :             // A signature check is required for a miniscript to be sane. Therefore no sane miniscript
    2687                 :             :             // may have an empty list of public keys.
    2688         [ +  - ]:         162 :             CHECK_NONFATAL(!parser.m_keys.empty());
    2689                 :             :             // Make sure all vecs are of the same length, or exactly length 1
    2690                 :             :             // For length 1 vectors, clone subdescs until vector is the same length
    2691         [ -  + ]:         162 :             size_t num_multipath = std::max_element(parser.m_keys.begin(), parser.m_keys.end(),
    2692                 :         237 :                     [](const std::vector<std::unique_ptr<PubkeyProvider>>& a, const std::vector<std::unique_ptr<PubkeyProvider>>& b) {
    2693   [ -  +  -  +  :         237 :                         return a.size() < b.size();
                   -  + ]
    2694         [ -  + ]:         162 :                     })->size();
    2695                 :             : 
    2696         [ +  + ]:         559 :             for (auto& vec : parser.m_keys) {
    2697   [ -  +  +  + ]:         399 :                 if (vec.size() == 1) {
    2698         [ -  + ]:         360 :                     for (size_t i = 1; i < num_multipath; ++i) {
    2699   [ #  #  #  #  :           0 :                         vec.emplace_back(vec.at(0)->Clone());
                   #  # ]
    2700                 :             :                     }
    2701         [ +  + ]:          39 :                 } else if (vec.size() != num_multipath) {
    2702         [ +  - ]:           2 :                     error = strprintf("Miniscript: Multipath derivation paths have mismatched lengths");
    2703                 :           2 :                     return {};
    2704                 :             :                 }
    2705                 :             :             }
    2706                 :             : 
    2707                 :             :             // Build the final descriptors vector
    2708         [ +  + ]:         344 :             for (size_t i = 0; i < num_multipath; ++i) {
    2709                 :             :                 // Build final pubkeys vectors by retrieving the i'th subscript for each vector in subscripts
    2710                 :         184 :                 std::vector<std::unique_ptr<PubkeyProvider>> pubs;
    2711   [ -  +  +  - ]:         184 :                 pubs.reserve(parser.m_keys.size());
    2712         [ +  + ]:         614 :                 for (auto& pub : parser.m_keys) {
    2713   [ +  -  +  - ]:         430 :                     pubs.emplace_back(std::move(pub.at(i)));
    2714                 :             :                 }
    2715   [ +  -  +  -  :         368 :                 ret.emplace_back(std::make_unique<MiniscriptDescriptor>(std::move(pubs), node->Clone()));
                   +  - ]
    2716                 :         184 :             }
    2717                 :         160 :             return ret;
    2718                 :             :         }
    2719                 :         714 :     }
    2720         [ +  + ]:         352 :     if (ctx == ParseScriptContext::P2SH) {
    2721         [ +  - ]:           4 :         error = "A function is needed within P2SH";
    2722                 :           4 :         return {};
    2723         [ +  + ]:         348 :     } else if (ctx == ParseScriptContext::P2WSH) {
    2724         [ +  - ]:           4 :         error = "A function is needed within P2WSH";
    2725                 :           4 :         return {};
    2726                 :             :     }
    2727   [ +  -  +  - ]:         688 :     error = strprintf("'%s' is not a valid descriptor function", std::string(expr.begin(), expr.end()));
    2728                 :         344 :     return {};
    2729                 :       13480 : }
    2730                 :             : 
    2731                 :        1042 : std::unique_ptr<DescriptorImpl> InferMultiA(const CScript& script, ParseScriptContext ctx, const SigningProvider& provider)
    2732                 :             : {
    2733                 :        1042 :     auto match = MatchMultiA(script);
    2734         [ +  + ]:        1042 :     if (!match) return {};
    2735                 :         790 :     std::vector<std::unique_ptr<PubkeyProvider>> keys;
    2736   [ -  +  +  - ]:         790 :     keys.reserve(match->second.size());
    2737         [ +  + ]:      110246 :     for (const auto keyspan : match->second) {
    2738         [ -  + ]:      109456 :         if (keyspan.size() != 32) return {};
    2739         [ +  - ]:      109456 :         auto key = InferXOnlyPubkey(XOnlyPubKey{keyspan}, ctx, provider);
    2740         [ -  + ]:      109456 :         if (!key) return {};
    2741         [ +  - ]:      109456 :         keys.push_back(std::move(key));
    2742                 :      109456 :     }
    2743   [ +  -  -  + ]:         790 :     return std::make_unique<MultiADescriptor>(match->first, std::move(keys));
    2744                 :        1832 : }
    2745                 :             : 
    2746                 :             : // NOLINTNEXTLINE(misc-no-recursion)
    2747                 :      388274 : std::unique_ptr<DescriptorImpl> InferScript(const CScript& script, ParseScriptContext ctx, const SigningProvider& provider)
    2748                 :             : {
    2749   [ +  +  +  +  :      395780 :     if (ctx == ParseScriptContext::P2TR && script.size() == 34 && script[0] == 32 && script[33] == OP_CHECKSIG) {
          +  +  +  -  +  
             -  +  -  +  
                      - ]
    2750                 :        3345 :         XOnlyPubKey key{std::span{script}.subspan(1, 32)};
    2751   [ +  -  -  + ]:        3345 :         return std::make_unique<PKDescriptor>(InferXOnlyPubkey(key, ctx, provider), true);
    2752                 :             :     }
    2753                 :             : 
    2754         [ +  + ]:      384929 :     if (ctx == ParseScriptContext::P2TR) {
    2755                 :        1042 :         auto ret = InferMultiA(script, ctx, provider);
    2756         [ +  + ]:        1042 :         if (ret) return ret;
    2757                 :        1042 :     }
    2758                 :             : 
    2759                 :      384139 :     std::vector<std::vector<unsigned char>> data;
    2760         [ +  - ]:      384139 :     TxoutType txntype = Solver(script, data);
    2761                 :             : 
    2762   [ +  +  +  - ]:      384139 :     if (txntype == TxoutType::PUBKEY && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
    2763         [ -  + ]:       18515 :         CPubKey pubkey(data[0]);
    2764   [ +  -  +  + ]:       18515 :         if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
    2765   [ +  -  -  + ]:       18513 :             return std::make_unique<PKDescriptor>(std::move(pubkey_provider));
    2766                 :       18515 :         }
    2767                 :             :     }
    2768   [ +  +  +  + ]:      365626 :     if (txntype == TxoutType::PUBKEYHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
    2769         [ -  + ]:      100041 :         uint160 hash(data[0]);
    2770         [ +  - ]:      100041 :         CKeyID keyid(hash);
    2771         [ +  - ]:      100041 :         CPubKey pubkey;
    2772   [ +  -  +  + ]:      100041 :         if (provider.GetPubKey(keyid, pubkey)) {
    2773   [ +  -  +  + ]:       99625 :             if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
    2774   [ +  -  -  + ]:       99621 :                 return std::make_unique<PKHDescriptor>(std::move(pubkey_provider));
    2775                 :       99625 :             }
    2776                 :             :         }
    2777                 :             :     }
    2778         [ +  + ]:      266005 :     if (txntype == TxoutType::WITNESS_V0_KEYHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH)) {
    2779         [ -  + ]:      205772 :         uint160 hash(data[0]);
    2780         [ +  - ]:      205772 :         CKeyID keyid(hash);
    2781         [ +  - ]:      205772 :         CPubKey pubkey;
    2782   [ +  -  +  + ]:      205772 :         if (provider.GetPubKey(keyid, pubkey)) {
    2783   [ +  -  +  + ]:      204239 :             if (auto pubkey_provider = InferPubkey(pubkey, ParseScriptContext::P2WPKH, provider)) {
    2784   [ +  -  -  + ]:      204237 :                 return std::make_unique<WPKHDescriptor>(std::move(pubkey_provider));
    2785                 :      204239 :             }
    2786                 :             :         }
    2787                 :             :     }
    2788   [ +  +  +  - ]:       61768 :     if (txntype == TxoutType::MULTISIG && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
    2789                 :         646 :         bool ok = true;
    2790                 :         646 :         std::vector<std::unique_ptr<PubkeyProvider>> providers;
    2791   [ -  +  +  + ]:        3240 :         for (size_t i = 1; i + 1 < data.size(); ++i) {
    2792         [ -  + ]:        2594 :             CPubKey pubkey(data[i]);
    2793   [ +  -  +  - ]:        2594 :             if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
    2794         [ +  - ]:        2594 :                 providers.push_back(std::move(pubkey_provider));
    2795                 :             :             } else {
    2796                 :           0 :                 ok = false;
    2797                 :           0 :                 break;
    2798                 :        2594 :             }
    2799                 :             :         }
    2800   [ +  -  -  + ]:         646 :         if (ok) return std::make_unique<MultisigDescriptor>((int)data[0][0], std::move(providers));
    2801                 :         646 :     }
    2802         [ +  + ]:       61122 :     if (txntype == TxoutType::SCRIPTHASH && ctx == ParseScriptContext::TOP) {
    2803         [ -  + ]:       34533 :         uint160 hash(data[0]);
    2804         [ +  - ]:       34533 :         CScriptID scriptid(hash);
    2805                 :       34533 :         CScript subscript;
    2806   [ +  -  +  + ]:       34533 :         if (provider.GetCScript(scriptid, subscript)) {
    2807         [ +  - ]:       34104 :             auto sub = InferScript(subscript, ParseScriptContext::P2SH, provider);
    2808   [ +  +  +  -  :       34104 :             if (sub) return std::make_unique<SHDescriptor>(std::move(sub));
                   -  + ]
    2809                 :       34104 :         }
    2810                 :       34533 :     }
    2811         [ +  + ]:       27030 :     if (txntype == TxoutType::WITNESS_V0_SCRIPTHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH)) {
    2812   [ -  +  +  - ]:        1031 :         CScriptID scriptid{RIPEMD160(data[0])};
    2813                 :        1031 :         CScript subscript;
    2814   [ +  -  +  + ]:        1031 :         if (provider.GetCScript(scriptid, subscript)) {
    2815         [ +  - ]:         863 :             auto sub = InferScript(subscript, ParseScriptContext::P2WSH, provider);
    2816   [ +  +  +  -  :         863 :             if (sub) return std::make_unique<WSHDescriptor>(std::move(sub));
                   -  + ]
    2817                 :         863 :         }
    2818                 :        1031 :     }
    2819         [ +  + ]:       26180 :     if (txntype == TxoutType::WITNESS_V1_TAPROOT && ctx == ParseScriptContext::TOP) {
    2820                 :             :         // Extract x-only pubkey from output.
    2821                 :       20982 :         XOnlyPubKey pubkey;
    2822                 :       20982 :         std::copy(data[0].begin(), data[0].end(), pubkey.begin());
    2823                 :             :         // Request spending data.
    2824         [ +  - ]:       20982 :         TaprootSpendData tap;
    2825   [ +  -  +  + ]:       20982 :         if (provider.GetTaprootSpendData(pubkey, tap)) {
    2826                 :             :             // If found, convert it back to tree form.
    2827         [ +  - ]:        5910 :             auto tree = InferTaprootTree(tap, pubkey);
    2828         [ +  - ]:        5910 :             if (tree) {
    2829                 :             :                 // If that works, try to infer subdescriptors for all leaves.
    2830                 :        5910 :                 bool ok = true;
    2831                 :        5910 :                 std::vector<std::unique_ptr<DescriptorImpl>> subscripts; //!< list of script subexpressions
    2832                 :        5910 :                 std::vector<int> depths; //!< depth in the tree of each subexpression (same length subscripts)
    2833   [ +  -  +  + ]:       10297 :                 for (const auto& [depth, script, leaf_ver] : *tree) {
    2834                 :        4387 :                     std::unique_ptr<DescriptorImpl> subdesc;
    2835         [ +  - ]:        4387 :                     if (leaf_ver == TAPROOT_LEAF_TAPSCRIPT) {
    2836         [ +  - ]:        8774 :                         subdesc = InferScript(CScript(script.begin(), script.end()), ParseScriptContext::P2TR, provider);
    2837                 :             :                     }
    2838         [ -  + ]:        4387 :                     if (!subdesc) {
    2839                 :           0 :                         ok = false;
    2840                 :           0 :                         break;
    2841                 :             :                     } else {
    2842         [ +  - ]:        4387 :                         subscripts.push_back(std::move(subdesc));
    2843         [ +  - ]:        4387 :                         depths.push_back(depth);
    2844                 :             :                     }
    2845                 :        4387 :                 }
    2846                 :           0 :                 if (ok) {
    2847         [ +  - ]:        5910 :                     auto key = InferXOnlyPubkey(tap.internal_key, ParseScriptContext::P2TR, provider);
    2848   [ +  -  -  + ]:        5910 :                     return std::make_unique<TRDescriptor>(std::move(key), std::move(subscripts), std::move(depths));
    2849                 :        5910 :                 }
    2850                 :        5910 :             }
    2851                 :        5910 :         }
    2852                 :             :         // If the above doesn't work, construct a rawtr() descriptor with just the encoded x-only pubkey.
    2853   [ +  -  +  - ]:       15072 :         if (pubkey.IsFullyValid()) {
    2854         [ +  - ]:       15072 :             auto key = InferXOnlyPubkey(pubkey, ParseScriptContext::P2TR, provider);
    2855         [ +  - ]:       15072 :             if (key) {
    2856   [ +  -  -  + ]:       15072 :                 return std::make_unique<RawTRDescriptor>(std::move(key));
    2857                 :             :             }
    2858                 :       15072 :         }
    2859                 :       20982 :     }
    2860                 :             : 
    2861         [ +  + ]:        5198 :     if (ctx == ParseScriptContext::P2WSH || ctx == ParseScriptContext::P2TR) {
    2862                 :         631 :         const auto script_ctx{ctx == ParseScriptContext::P2WSH ? miniscript::MiniscriptContext::P2WSH : miniscript::MiniscriptContext::TAPSCRIPT};
    2863                 :         631 :         uint32_t key_exp_index = 0;
    2864         [ +  - ]:         631 :         KeyParser parser(/* out = */nullptr, /* in = */&provider, /* ctx = */script_ctx, key_exp_index);
    2865         [ +  - ]:         631 :         auto node = miniscript::FromScript(script, parser);
    2866   [ +  +  -  + ]:         631 :         if (node && node->IsSane()) {
    2867                 :         618 :             std::vector<std::unique_ptr<PubkeyProvider>> keys;
    2868   [ -  +  +  - ]:         618 :             keys.reserve(parser.m_keys.size());
    2869         [ +  + ]:        2139 :             for (auto& key : parser.m_keys) {
    2870   [ +  -  +  - ]:        1521 :                 keys.emplace_back(std::move(key.at(0)));
    2871                 :             :             }
    2872   [ +  -  -  + ]:         618 :             return std::make_unique<MiniscriptDescriptor>(std::move(keys), std::move(*node));
    2873                 :         618 :         }
    2874                 :        1262 :     }
    2875                 :             : 
    2876                 :             :     // The following descriptors are all top-level only descriptors.
    2877                 :             :     // So if we are not at the top level, return early.
    2878         [ +  + ]:        4580 :     if (ctx != ParseScriptContext::TOP) return nullptr;
    2879                 :             : 
    2880                 :        4555 :     CTxDestination dest;
    2881   [ +  -  +  + ]:        4555 :     if (ExtractDestination(script, dest)) {
    2882   [ +  -  +  - ]:        2613 :         if (GetScriptForDestination(dest) == script) {
    2883   [ +  -  -  + ]:        2613 :             return std::make_unique<AddressDescriptor>(std::move(dest));
    2884                 :             :         }
    2885                 :             :     }
    2886                 :             : 
    2887   [ +  -  -  + ]:        1942 :     return std::make_unique<RawDescriptor>(script);
    2888                 :      384139 : }
    2889                 :             : 
    2890                 :             : 
    2891                 :             : } // namespace
    2892                 :             : 
    2893                 :             : /** Check a descriptor checksum, and update desc to be the checksum-less part. */
    2894                 :       10858 : bool CheckChecksum(std::span<const char>& sp, bool require_checksum, std::string& error, std::string* out_checksum = nullptr)
    2895                 :             : {
    2896                 :       10858 :     auto check_split = Split(sp, '#');
    2897   [ -  +  +  + ]:       10858 :     if (check_split.size() > 2) {
    2898         [ +  - ]:           2 :         error = "Multiple '#' symbols";
    2899                 :             :         return false;
    2900                 :             :     }
    2901   [ +  +  +  + ]:       10856 :     if (check_split.size() == 1 && require_checksum){
    2902         [ +  - ]:       10858 :         error = "Missing checksum";
    2903                 :             :         return false;
    2904                 :             :     }
    2905         [ +  + ]:       10849 :     if (check_split.size() == 2) {
    2906         [ +  + ]:        5932 :         if (check_split[1].size() != 8) {
    2907         [ +  - ]:           6 :             error = strprintf("Expected 8 character checksum, not %u characters", check_split[1].size());
    2908                 :           6 :             return false;
    2909                 :             :         }
    2910                 :             :     }
    2911         [ +  - ]:       10843 :     auto checksum = DescriptorChecksum(check_split[0]);
    2912         [ +  + ]:       10843 :     if (checksum.empty()) {
    2913         [ +  - ]:       10843 :         error = "Invalid characters in payload";
    2914                 :             :         return false;
    2915                 :             :     }
    2916   [ -  +  +  + ]:       10842 :     if (check_split.size() == 2) {
    2917   [ -  +  +  + ]:        5925 :         if (!std::equal(checksum.begin(), checksum.end(), check_split[1].begin())) {
    2918   [ +  -  +  - ]:          22 :             error = strprintf("Provided checksum '%s' does not match computed checksum '%s'", std::string(check_split[1].begin(), check_split[1].end()), checksum);
    2919                 :          11 :             return false;
    2920                 :             :         }
    2921                 :             :     }
    2922         [ +  + ]:       10831 :     if (out_checksum) *out_checksum = std::move(checksum);
    2923                 :       10831 :     sp = check_split[0];
    2924                 :       10831 :     return true;
    2925                 :       21701 : }
    2926                 :             : 
    2927                 :       10577 : std::vector<std::unique_ptr<Descriptor>> Parse(std::string_view descriptor, FlatSigningProvider& out, std::string& error, bool require_checksum)
    2928                 :             : {
    2929                 :       10577 :     std::span<const char> sp{descriptor};
    2930         [ +  + ]:       10577 :     if (!CheckChecksum(sp, require_checksum, error)) return {};
    2931                 :       10554 :     uint32_t key_exp_index = 0;
    2932                 :       10554 :     auto ret = ParseScript(key_exp_index, sp, ParseScriptContext::TOP, out, error);
    2933   [ +  -  +  + ]:       10554 :     if (sp.empty() && !ret.empty()) {
    2934                 :       10030 :         std::vector<std::unique_ptr<Descriptor>> descs;
    2935   [ -  +  +  - ]:       10030 :         descs.reserve(ret.size());
    2936         [ +  + ]:       20280 :         for (auto& r : ret) {
    2937         [ +  - ]:       10250 :             descs.emplace_back(std::unique_ptr<Descriptor>(std::move(r)));
    2938                 :             :         }
    2939                 :       10030 :         return descs;
    2940                 :       10030 :     }
    2941                 :         524 :     return {};
    2942                 :       10554 : }
    2943                 :             : 
    2944                 :         281 : std::string GetDescriptorChecksum(const std::string& descriptor)
    2945                 :             : {
    2946         [ -  + ]:         281 :     std::string ret;
    2947                 :         281 :     std::string error;
    2948         [ -  + ]:         281 :     std::span<const char> sp{descriptor};
    2949   [ +  -  +  +  :         281 :     if (!CheckChecksum(sp, false, error, &ret)) return "";
                   +  - ]
    2950                 :         277 :     return ret;
    2951                 :         281 : }
    2952                 :             : 
    2953                 :      348920 : std::unique_ptr<Descriptor> InferDescriptor(const CScript& script, const SigningProvider& provider)
    2954                 :             : {
    2955                 :      348920 :     return InferScript(script, ParseScriptContext::TOP, provider);
    2956                 :             : }
    2957                 :             : 
    2958                 :        7342 : uint256 DescriptorID(const Descriptor& desc)
    2959                 :             : {
    2960                 :        7342 :     std::string desc_str = desc.ToString(/*compat_format=*/true);
    2961                 :        7342 :     uint256 id;
    2962   [ +  -  +  -  :       14684 :     CSHA256().Write((unsigned char*)desc_str.data(), desc_str.size()).Finalize(id.begin());
                   +  - ]
    2963                 :        7342 :     return id;
    2964                 :        7342 : }
    2965                 :             : 
    2966                 :       18575 : void DescriptorCache::CacheParentExtPubKey(uint32_t key_exp_pos, const CExtPubKey& xpub)
    2967                 :             : {
    2968                 :       18575 :     m_parent_xpubs[key_exp_pos] = xpub;
    2969                 :       18575 : }
    2970                 :             : 
    2971                 :       30241 : void DescriptorCache::CacheDerivedExtPubKey(uint32_t key_exp_pos, uint32_t der_index, const CExtPubKey& xpub)
    2972                 :             : {
    2973                 :       30241 :     auto& xpubs = m_derived_xpubs[key_exp_pos];
    2974                 :       30241 :     xpubs[der_index] = xpub;
    2975                 :       30241 : }
    2976                 :             : 
    2977                 :       13930 : void DescriptorCache::CacheLastHardenedExtPubKey(uint32_t key_exp_pos, const CExtPubKey& xpub)
    2978                 :             : {
    2979                 :       13930 :     m_last_hardened_xpubs[key_exp_pos] = xpub;
    2980                 :       13930 : }
    2981                 :             : 
    2982                 :      641377 : bool DescriptorCache::GetCachedParentExtPubKey(uint32_t key_exp_pos, CExtPubKey& xpub) const
    2983                 :             : {
    2984                 :      641377 :     const auto& it = m_parent_xpubs.find(key_exp_pos);
    2985         [ +  + ]:      641377 :     if (it == m_parent_xpubs.end()) return false;
    2986                 :      632046 :     xpub = it->second;
    2987                 :      632046 :     return true;
    2988                 :             : }
    2989                 :             : 
    2990                 :      660771 : bool DescriptorCache::GetCachedDerivedExtPubKey(uint32_t key_exp_pos, uint32_t der_index, CExtPubKey& xpub) const
    2991                 :             : {
    2992                 :      660771 :     const auto& key_exp_it = m_derived_xpubs.find(key_exp_pos);
    2993         [ +  + ]:      660771 :     if (key_exp_it == m_derived_xpubs.end()) return false;
    2994                 :       24345 :     const auto& der_it = key_exp_it->second.find(der_index);
    2995         [ +  + ]:       24345 :     if (der_it == key_exp_it->second.end()) return false;
    2996                 :        4380 :     xpub = der_it->second;
    2997                 :        4380 :     return true;
    2998                 :             : }
    2999                 :             : 
    3000                 :       35960 : bool DescriptorCache::GetCachedLastHardenedExtPubKey(uint32_t key_exp_pos, CExtPubKey& xpub) const
    3001                 :             : {
    3002                 :       35960 :     const auto& it = m_last_hardened_xpubs.find(key_exp_pos);
    3003         [ +  + ]:       35960 :     if (it == m_last_hardened_xpubs.end()) return false;
    3004                 :       32070 :     xpub = it->second;
    3005                 :       32070 :     return true;
    3006                 :             : }
    3007                 :             : 
    3008                 :      413245 : DescriptorCache DescriptorCache::MergeAndDiff(const DescriptorCache& other)
    3009                 :             : {
    3010                 :      413245 :     DescriptorCache diff;
    3011   [ +  -  +  +  :      418361 :     for (const auto& parent_xpub_pair : other.GetCachedParentExtPubKeys()) {
                   +  - ]
    3012         [ +  - ]:        5116 :         CExtPubKey xpub;
    3013   [ +  +  +  - ]:        5116 :         if (GetCachedParentExtPubKey(parent_xpub_pair.first, xpub)) {
    3014         [ -  + ]:           6 :             if (xpub != parent_xpub_pair.second) {
    3015   [ #  #  #  # ]:           0 :                 throw std::runtime_error(std::string(__func__) + ": New cached parent xpub does not match already cached parent xpub");
    3016                 :             :             }
    3017                 :           6 :             continue;
    3018                 :             :         }
    3019         [ +  - ]:        5110 :         CacheParentExtPubKey(parent_xpub_pair.first, parent_xpub_pair.second);
    3020         [ +  - ]:        5110 :         diff.CacheParentExtPubKey(parent_xpub_pair.first, parent_xpub_pair.second);
    3021                 :           0 :     }
    3022   [ +  -  +  + ]:      423252 :     for (const auto& derived_xpub_map_pair : other.GetCachedDerivedExtPubKeys()) {
    3023   [ +  +  +  - ]:       20014 :         for (const auto& derived_xpub_pair : derived_xpub_map_pair.second) {
    3024         [ +  - ]:       10007 :             CExtPubKey xpub;
    3025   [ -  +  +  - ]:       10007 :             if (GetCachedDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, xpub)) {
    3026         [ #  # ]:           0 :                 if (xpub != derived_xpub_pair.second) {
    3027   [ #  #  #  # ]:           0 :                     throw std::runtime_error(std::string(__func__) + ": New cached derived xpub does not match already cached derived xpub");
    3028                 :             :                 }
    3029                 :           0 :                 continue;
    3030                 :             :             }
    3031         [ +  - ]:       10007 :             CacheDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, derived_xpub_pair.second);
    3032         [ +  - ]:       10007 :             diff.CacheDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, derived_xpub_pair.second);
    3033                 :             :         }
    3034                 :             :     }
    3035   [ +  -  +  +  :      417135 :     for (const auto& lh_xpub_pair : other.GetCachedLastHardenedExtPubKeys()) {
                   +  - ]
    3036         [ +  - ]:        3890 :         CExtPubKey xpub;
    3037   [ -  +  +  - ]:        3890 :         if (GetCachedLastHardenedExtPubKey(lh_xpub_pair.first, xpub)) {
    3038         [ #  # ]:           0 :             if (xpub != lh_xpub_pair.second) {
    3039   [ #  #  #  # ]:           0 :                 throw std::runtime_error(std::string(__func__) + ": New cached last hardened xpub does not match already cached last hardened xpub");
    3040                 :             :             }
    3041                 :           0 :             continue;
    3042                 :             :         }
    3043         [ +  - ]:        3890 :         CacheLastHardenedExtPubKey(lh_xpub_pair.first, lh_xpub_pair.second);
    3044         [ +  - ]:        3890 :         diff.CacheLastHardenedExtPubKey(lh_xpub_pair.first, lh_xpub_pair.second);
    3045                 :           0 :     }
    3046                 :      413245 :     return diff;
    3047                 :           0 : }
    3048                 :             : 
    3049                 :      827180 : ExtPubKeyMap DescriptorCache::GetCachedParentExtPubKeys() const
    3050                 :             : {
    3051                 :      827180 :     return m_parent_xpubs;
    3052                 :             : }
    3053                 :             : 
    3054                 :      827180 : std::unordered_map<uint32_t, ExtPubKeyMap> DescriptorCache::GetCachedDerivedExtPubKeys() const
    3055                 :             : {
    3056                 :      827180 :     return m_derived_xpubs;
    3057                 :             : }
    3058                 :             : 
    3059                 :      826534 : ExtPubKeyMap DescriptorCache::GetCachedLastHardenedExtPubKeys() const
    3060                 :             : {
    3061                 :      826534 :     return m_last_hardened_xpubs;
    3062                 :             : }
        

Generated by: LCOV version 2.0-1