LCOV - code coverage report
Current view: top level - src/script - descriptor.cpp (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 94.1 % 1681 1581
Test Date: 2026-01-10 04:21:25 Functions: 86.7 % 225 195
Branches: 64.4 % 2939 1892

             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 <hash.h>
       8                 :             : #include <key_io.h>
       9                 :             : #include <pubkey.h>
      10                 :             : #include <musig.h>
      11                 :             : #include <script/miniscript.h>
      12                 :             : #include <script/parsing.h>
      13                 :             : #include <script/script.h>
      14                 :             : #include <script/signingprovider.h>
      15                 :             : #include <script/solver.h>
      16                 :             : #include <uint256.h>
      17                 :             : 
      18                 :             : #include <common/args.h>
      19                 :             : #include <span.h>
      20                 :             : #include <util/bip32.h>
      21                 :             : #include <util/check.h>
      22                 :             : #include <util/strencodings.h>
      23                 :             : #include <util/vector.h>
      24                 :             : 
      25                 :             : #include <algorithm>
      26                 :             : #include <memory>
      27                 :             : #include <numeric>
      28                 :             : #include <optional>
      29                 :             : #include <string>
      30                 :             : #include <vector>
      31                 :             : 
      32                 :             : using util::Split;
      33                 :             : 
      34                 :             : namespace {
      35                 :             : 
      36                 :             : ////////////////////////////////////////////////////////////////////////////
      37                 :             : // Checksum                                                               //
      38                 :             : ////////////////////////////////////////////////////////////////////////////
      39                 :             : 
      40                 :             : // This section implements a checksum algorithm for descriptors with the
      41                 :             : // following properties:
      42                 :             : // * Mistakes in a descriptor string are measured in "symbol errors". The higher
      43                 :             : //   the number of symbol errors, the harder it is to detect:
      44                 :             : //   * An error substituting a character from 0123456789()[],'/*abcdefgh@:$%{} for
      45                 :             : //     another in that set always counts as 1 symbol error.
      46                 :             : //     * Note that hex encoded keys are covered by these characters. Xprvs and
      47                 :             : //       xpubs use other characters too, but already have their own checksum
      48                 :             : //       mechanism.
      49                 :             : //     * Function names like "multi()" use other characters, but mistakes in
      50                 :             : //       these would generally result in an unparsable descriptor.
      51                 :             : //   * A case error always counts as 1 symbol error.
      52                 :             : //   * Any other 1 character substitution error counts as 1 or 2 symbol errors.
      53                 :             : // * Any 1 symbol error is always detected.
      54                 :             : // * Any 2 or 3 symbol error in a descriptor of up to 49154 characters is always detected.
      55                 :             : // * Any 4 symbol error in a descriptor of up to 507 characters is always detected.
      56                 :             : // * Any 5 symbol error in a descriptor of up to 77 characters is always detected.
      57                 :             : // * Is optimized to minimize the chance a 5 symbol error in a descriptor up to 387 characters is undetected
      58                 :             : // * Random errors have a chance of 1 in 2**40 of being undetected.
      59                 :             : //
      60                 :             : // These properties are achieved by expanding every group of 3 (non checksum) characters into
      61                 :             : // 4 GF(32) symbols, over which a cyclic code is defined.
      62                 :             : 
      63                 :             : /*
      64                 :             :  * Interprets c as 8 groups of 5 bits which are the coefficients of a degree 8 polynomial over GF(32),
      65                 :             :  * multiplies that polynomial by x, computes its remainder modulo a generator, and adds the constant term val.
      66                 :             :  *
      67                 :             :  * 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}.
      68                 :             :  * It is chosen to define an cyclic error detecting code which is selected by:
      69                 :             :  * - Starting from all BCH codes over GF(32) of degree 8 and below, which by construction guarantee detecting
      70                 :             :  *   3 errors in windows up to 19000 symbols.
      71                 :             :  * - Taking all those generators, and for degree 7 ones, extend them to degree 8 by adding all degree-1 factors.
      72                 :             :  * - Selecting just the set of generators that guarantee detecting 4 errors in a window of length 512.
      73                 :             :  * - Selecting one of those with best worst-case behavior for 5 errors in windows of length up to 512.
      74                 :             :  *
      75                 :             :  * The generator and the constants to implement it can be verified using this Sage code:
      76                 :             :  *   B = GF(2) # Binary field
      77                 :             :  *   BP.<b> = B[] # Polynomials over the binary field
      78                 :             :  *   F_mod = b**5 + b**3 + 1
      79                 :             :  *   F.<f> = GF(32, modulus=F_mod, repr='int') # GF(32) definition
      80                 :             :  *   FP.<x> = F[] # Polynomials over GF(32)
      81                 :             :  *   E_mod = x**3 + x + F.fetch_int(8)
      82                 :             :  *   E.<e> = F.extension(E_mod) # Extension field definition
      83                 :             :  *   alpha = e**2743 # Choice of an element in extension field
      84                 :             :  *   for p in divisors(E.order() - 1): # Verify alpha has order 32767.
      85                 :             :  *       assert((alpha**p == 1) == (p % 32767 == 0))
      86                 :             :  *   G = lcm([(alpha**i).minpoly() for i in [1056,1057,1058]] + [x + 1])
      87                 :             :  *   print(G) # Print out the generator
      88                 :             :  *   for i in [1,2,4,8,16]: # Print out {1,2,4,8,16}*(G mod x^8), packed in hex integers.
      89                 :             :  *       v = 0
      90                 :             :  *       for coef in reversed((F.fetch_int(i)*(G % x**8)).coefficients(sparse=True)):
      91                 :             :  *           v = v*32 + coef.integer_representation()
      92                 :             :  *       print("0x%x" % v)
      93                 :             :  */
      94                 :  1797297899 : uint64_t PolyMod(uint64_t c, int val)
      95                 :             : {
      96                 :  1797297899 :     uint8_t c0 = c >> 35;
      97                 :  1797297899 :     c = ((c & 0x7ffffffff) << 5) ^ val;
      98         [ +  + ]:  1797297899 :     if (c0 & 1) c ^= 0xf5dee51989;
      99         [ +  + ]:  1797297899 :     if (c0 & 2) c ^= 0xa9fdca3312;
     100         [ +  + ]:  1797297899 :     if (c0 & 4) c ^= 0x1bab10e32d;
     101         [ +  + ]:  1797297899 :     if (c0 & 8) c ^= 0x3706b1677a;
     102         [ +  + ]:  1797297899 :     if (c0 & 16) c ^= 0x644d626ffd;
     103                 :  1797297899 :     return c;
     104                 :             : }
     105                 :             : 
     106                 :     2349350 : std::string DescriptorChecksum(const std::span<const char>& span)
     107                 :             : {
     108                 :             :     /** A character set designed such that:
     109                 :             :      *  - The most common 'unprotected' descriptor characters (hex, keypaths) are in the first group of 32.
     110                 :             :      *  - Case errors cause an offset that's a multiple of 32.
     111                 :             :      *  - As many alphabetic characters are in the same group (while following the above restrictions).
     112                 :             :      *
     113                 :             :      * If p(x) gives the position of a character c in this character set, every group of 3 characters
     114                 :             :      * (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).
     115                 :             :      * This means that changes that only affect the lower 5 bits of the position, or only the higher 2 bits, will just
     116                 :             :      * affect a single symbol.
     117                 :             :      *
     118                 :             :      * As a result, within-group-of-32 errors count as 1 symbol, as do cross-group errors that don't affect
     119                 :             :      * the position within the groups.
     120                 :             :      */
     121                 :     2349350 :     static const std::string INPUT_CHARSET =
     122                 :             :         "0123456789()[],'/*abcdefgh@:$%{}"
     123                 :             :         "IJKLMNOPQRSTUVWXYZ&+-.;<=>?!^_|~"
     124   [ +  +  +  -  :     2349359 :         "ijklmnopqrstuvwxyzABCDEFGH`#\"\\ ";
                   +  - ]
     125                 :             : 
     126                 :             :     /** The character set for the checksum itself (same as bech32). */
     127   [ +  +  +  -  :     2349359 :     static const std::string CHECKSUM_CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
                   +  - ]
     128                 :             : 
     129                 :     2349350 :     uint64_t c = 1;
     130                 :     2349350 :     int cls = 0;
     131                 :     2349350 :     int clscount = 0;
     132         [ +  + ]:  1335404663 :     for (auto ch : span) {
     133                 :  1333055586 :         auto pos = INPUT_CHARSET.find(ch);
     134         [ +  + ]:  1333055586 :         if (pos == std::string::npos) return "";
     135                 :  1333055313 :         c = PolyMod(c, pos & 31); // Emit a symbol for the position inside the group, for every character.
     136                 :  1333055313 :         cls = cls * 3 + (pos >> 5); // Accumulate the group numbers
     137         [ +  + ]:  1333055313 :         if (++clscount == 3) {
     138                 :             :             // Emit an extra symbol representing the group numbers, for every 3 characters.
     139                 :   443383688 :             c = PolyMod(c, cls);
     140                 :   443383688 :             cls = 0;
     141                 :   443383688 :             clscount = 0;
     142                 :             :         }
     143                 :             :     }
     144         [ +  + ]:     2349077 :     if (clscount > 0) c = PolyMod(c, cls);
     145         [ +  + ]:    21141693 :     for (int j = 0; j < 8; ++j) c = PolyMod(c, 0); // Shift further to determine the checksum.
     146                 :     2349077 :     c ^= 1; // Prevent appending zeroes from not affecting the checksum.
     147                 :             : 
     148                 :     2349077 :     std::string ret(8, ' ');
     149         [ +  + ]:    21141693 :     for (int j = 0; j < 8; ++j) ret[j] = CHECKSUM_CHARSET[(c >> (5 * (7 - j))) & 31];
     150                 :     2349077 :     return ret;
     151                 :     2349077 : }
     152                 :             : 
     153   [ -  +  +  -  :     4606014 : std::string AddChecksum(const std::string& str) { return str + "#" + DescriptorChecksum(str); }
                   +  - ]
     154                 :             : 
     155                 :             : ////////////////////////////////////////////////////////////////////////////
     156                 :             : // Internal representation                                                //
     157                 :             : ////////////////////////////////////////////////////////////////////////////
     158                 :             : 
     159                 :             : typedef std::vector<uint32_t> KeyPath;
     160                 :             : 
     161                 :             : /** Interface for public key objects in descriptors. */
     162                 :             : struct PubkeyProvider
     163                 :             : {
     164                 :             : protected:
     165                 :             :     //! Index of this key expression in the descriptor
     166                 :             :     //! E.g. If this PubkeyProvider is key1 in multi(2, key1, key2, key3), then m_expr_index = 0
     167                 :             :     uint32_t m_expr_index;
     168                 :             : 
     169                 :             : public:
     170                 :     5939062 :     explicit PubkeyProvider(uint32_t exp_index) : m_expr_index(exp_index) {}
     171                 :             : 
     172                 :       10337 :     virtual ~PubkeyProvider() = default;
     173                 :             : 
     174                 :             :     /** Compare two public keys represented by this provider.
     175                 :             :      * Used by the Miniscript descriptors to check for duplicate keys in the script.
     176                 :             :      */
     177                 :      432592 :     bool operator<(PubkeyProvider& other) const {
     178                 :      432592 :         FlatSigningProvider dummy;
     179                 :             : 
     180         [ +  - ]:      432592 :         std::optional<CPubKey> a = GetPubKey(0, dummy, dummy);
     181         [ +  - ]:      432592 :         std::optional<CPubKey> b = other.GetPubKey(0, dummy, dummy);
     182                 :             : 
     183                 :      432592 :         return a < b;
     184                 :      432592 :     }
     185                 :             : 
     186                 :             :     /** Derive a public key and put it into out.
     187                 :             :      *  read_cache is the cache to read keys from (if not nullptr)
     188                 :             :      *  write_cache is the cache to write keys to (if not nullptr)
     189                 :             :      *  Caches are not exclusive but this is not tested. Currently we use them exclusively
     190                 :             :      */
     191                 :             :     virtual std::optional<CPubKey> GetPubKey(int pos, const SigningProvider& arg, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const = 0;
     192                 :             : 
     193                 :             :     /** Whether this represent multiple public keys at different positions. */
     194                 :             :     virtual bool IsRange() const = 0;
     195                 :             : 
     196                 :             :     /** Get the size of the generated public key(s) in bytes (33 or 65). */
     197                 :             :     virtual size_t GetSize() const = 0;
     198                 :             : 
     199                 :             :     enum class StringType {
     200                 :             :         PUBLIC,
     201                 :             :         COMPAT // string calculation that mustn't change over time to stay compatible with previous software versions
     202                 :             :     };
     203                 :             : 
     204                 :             :     /** Get the descriptor string form. */
     205                 :             :     virtual std::string ToString(StringType type=StringType::PUBLIC) const = 0;
     206                 :             : 
     207                 :             :     /** Get the descriptor string form including private data (if available in arg). */
     208                 :             :     virtual bool ToPrivateString(const SigningProvider& arg, std::string& out) const = 0;
     209                 :             : 
     210                 :             :     /** Get the descriptor string form with the xpub at the last hardened derivation,
     211                 :             :      *  and always use h for hardened derivation.
     212                 :             :      */
     213                 :             :     virtual bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache = nullptr) const = 0;
     214                 :             : 
     215                 :             :     /** Derive a private key, if private data is available in arg and put it into out. */
     216                 :             :     virtual void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const = 0;
     217                 :             : 
     218                 :             :     /** Return the non-extended public key for this PubkeyProvider, if it has one. */
     219                 :             :     virtual std::optional<CPubKey> GetRootPubKey() const = 0;
     220                 :             :     /** Return the extended public key for this PubkeyProvider, if it has one. */
     221                 :             :     virtual std::optional<CExtPubKey> GetRootExtPubKey() const = 0;
     222                 :             : 
     223                 :             :     /** Make a deep copy of this PubkeyProvider */
     224                 :             :     virtual std::unique_ptr<PubkeyProvider> Clone() const = 0;
     225                 :             : 
     226                 :             :     /** Whether this PubkeyProvider is a BIP 32 extended key that can be derived from */
     227                 :             :     virtual bool IsBIP32() const = 0;
     228                 :             : };
     229                 :             : 
     230                 :             : class OriginPubkeyProvider final : public PubkeyProvider
     231                 :             : {
     232                 :             :     KeyOriginInfo m_origin;
     233                 :             :     std::unique_ptr<PubkeyProvider> m_provider;
     234                 :             :     bool m_apostrophe;
     235                 :             : 
     236                 :     2067368 :     std::string OriginString(StringType type, bool normalized=false) const
     237                 :             :     {
     238                 :             :         // If StringType==COMPAT, always use the apostrophe to stay compatible with previous versions
     239   [ +  +  +  +  :     2067368 :         bool use_apostrophe = (!normalized && m_apostrophe) || type == StringType::COMPAT;
                   +  + ]
     240   [ +  -  +  - ]:     4134736 :         return HexStr(m_origin.fingerprint) + FormatHDKeypath(m_origin.path, use_apostrophe);
     241                 :             :     }
     242                 :             : 
     243                 :             : public:
     244                 :     1951206 :     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) {}
     245                 :     3036213 :     std::optional<CPubKey> GetPubKey(int pos, const SigningProvider& arg, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
     246                 :             :     {
     247                 :     3036213 :         std::optional<CPubKey> pub = m_provider->GetPubKey(pos, arg, out, read_cache, write_cache);
     248         [ +  + ]:     3036213 :         if (!pub) return std::nullopt;
     249         [ -  + ]:     3000395 :         Assert(out.pubkeys.contains(pub->GetID()));
     250         [ -  + ]:     3000395 :         auto& [pubkey, suborigin] = out.origins[pub->GetID()];
     251         [ -  + ]:     3000395 :         Assert(pubkey == *pub); // m_provider must have a valid origin by this point.
     252                 :     3000395 :         std::copy(std::begin(m_origin.fingerprint), std::end(m_origin.fingerprint), suborigin.fingerprint);
     253                 :     3000395 :         suborigin.path.insert(suborigin.path.begin(), m_origin.path.begin(), m_origin.path.end());
     254                 :     3000395 :         return pub;
     255                 :             :     }
     256                 :     1479166 :     bool IsRange() const override { return m_provider->IsRange(); }
     257                 :       78207 :     size_t GetSize() const override { return m_provider->GetSize(); }
     258                 :      129841 :     bool IsBIP32() const override { return m_provider->IsBIP32(); }
     259   [ +  -  +  -  :     3691971 :     std::string ToString(StringType type) const override { return "[" + OriginString(type) + "]" + m_provider->ToString(type); }
                   +  - ]
     260                 :       39358 :     bool ToPrivateString(const SigningProvider& arg, std::string& ret) const override
     261                 :             :     {
     262         [ +  - ]:       39358 :         std::string sub;
     263   [ +  -  +  + ]:       39358 :         if (!m_provider->ToPrivateString(arg, sub)) return false;
     264   [ +  -  +  -  :       54596 :         ret = "[" + OriginString(StringType::PUBLIC) + "]" + std::move(sub);
                   +  - ]
     265                 :       27298 :         return true;
     266                 :       39358 :     }
     267                 :      809717 :     bool ToNormalizedString(const SigningProvider& arg, std::string& ret, const DescriptorCache* cache) const override
     268                 :             :     {
     269         [ +  - ]:      809717 :         std::string sub;
     270   [ +  -  +  + ]:      809717 :         if (!m_provider->ToNormalizedString(arg, sub, cache)) return false;
     271                 :             :         // If m_provider is a BIP32PubkeyProvider, we may get a string formatted like a OriginPubkeyProvider
     272                 :             :         // In that case, we need to strip out the leading square bracket and fingerprint from the substring,
     273                 :             :         // and append that to our own origin string.
     274         [ +  + ]:      809413 :         if (sub[0] == '[') {
     275         [ +  - ]:      269847 :             sub = sub.substr(9);
     276   [ +  -  +  -  :      269847 :             ret = "[" + OriginString(StringType::PUBLIC, /*normalized=*/true) + std::move(sub);
                   +  - ]
     277                 :             :         } else {
     278   [ +  -  +  -  :     1079132 :             ret = "[" + OriginString(StringType::PUBLIC, /*normalized=*/true) + "]" + std::move(sub);
                   +  - ]
     279                 :             :         }
     280                 :             :         return true;
     281                 :      809717 :     }
     282                 :      817878 :     void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const override
     283                 :             :     {
     284                 :      817878 :         m_provider->GetPrivKey(pos, arg, out);
     285                 :      817878 :     }
     286                 :           0 :     std::optional<CPubKey> GetRootPubKey() const override
     287                 :             :     {
     288                 :           0 :         return m_provider->GetRootPubKey();
     289                 :             :     }
     290                 :           0 :     std::optional<CExtPubKey> GetRootExtPubKey() const override
     291                 :             :     {
     292                 :           0 :         return m_provider->GetRootExtPubKey();
     293                 :             :     }
     294                 :      654455 :     std::unique_ptr<PubkeyProvider> Clone() const override
     295                 :             :     {
     296   [ +  -  -  + ]:      654455 :         return std::make_unique<OriginPubkeyProvider>(m_expr_index, m_origin, m_provider->Clone(), m_apostrophe);
     297                 :             :     }
     298                 :             : };
     299                 :             : 
     300                 :             : /** An object representing a parsed constant public key in a descriptor. */
     301                 :       10337 : class ConstPubkeyProvider final : public PubkeyProvider
     302                 :             : {
     303                 :             :     CPubKey m_pubkey;
     304                 :             :     bool m_xonly;
     305                 :             : 
     306                 :      640603 :     std::optional<CKey> GetPrivKey(const SigningProvider& arg) const
     307                 :             :     {
     308                 :      640603 :         CKey key;
     309   [ +  +  +  -  :      917195 :         if (!(m_xonly ? arg.GetKeyByXOnly(XOnlyPubKey(m_pubkey), key) :
                   +  + ]
     310   [ +  -  +  - ]:      502432 :                         arg.GetKey(m_pubkey.GetID(), key))) return std::nullopt;
     311                 :      414763 :         return key;
     312                 :      640603 :     }
     313                 :             : 
     314                 :             : public:
     315                 :     1950517 :     ConstPubkeyProvider(uint32_t exp_index, const CPubKey& pubkey, bool xonly) : PubkeyProvider(exp_index), m_pubkey(pubkey), m_xonly(xonly) {}
     316                 :     3360584 :     std::optional<CPubKey> GetPubKey(int pos, const SigningProvider&, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
     317                 :             :     {
     318         [ +  - ]:     3360584 :         KeyOriginInfo info;
     319         [ +  - ]:     3360584 :         CKeyID keyid = m_pubkey.GetID();
     320                 :     3360584 :         std::copy(keyid.begin(), keyid.begin() + sizeof(info.fingerprint), info.fingerprint);
     321   [ +  -  +  - ]:     3360584 :         out.origins.emplace(keyid, std::make_pair(m_pubkey, info));
     322         [ +  - ]:     3360584 :         out.pubkeys.emplace(keyid, m_pubkey);
     323                 :     3360584 :         return m_pubkey;
     324                 :     3360584 :     }
     325                 :      817754 :     bool IsRange() const override { return false; }
     326                 :      147489 :     size_t GetSize() const override { return m_pubkey.size(); }
     327                 :       11956 :     bool IsBIP32() const override { return false; }
     328   [ +  +  +  - ]:     4367569 :     std::string ToString(StringType type) const override { return m_xonly ? HexStr(m_pubkey).substr(2) : HexStr(m_pubkey); }
     329                 :      129110 :     bool ToPrivateString(const SigningProvider& arg, std::string& ret) const override
     330                 :             :     {
     331                 :      129110 :         std::optional<CKey> key = GetPrivKey(arg);
     332         [ +  + ]:      129110 :         if (!key) return false;
     333         [ +  - ]:       75155 :         ret = EncodeSecret(*key);
     334                 :       75155 :         return true;
     335                 :      129110 :     }
     336                 :      557498 :     bool ToNormalizedString(const SigningProvider& arg, std::string& ret, const DescriptorCache* cache) const override
     337                 :             :     {
     338                 :      557498 :         ret = ToString(StringType::PUBLIC);
     339                 :      557498 :         return true;
     340                 :             :     }
     341                 :      511493 :     void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const override
     342                 :             :     {
     343                 :      511493 :         std::optional<CKey> key = GetPrivKey(arg);
     344         [ +  + ]:      511493 :         if (!key) return;
     345   [ +  -  +  -  :      339608 :         out.keys.emplace(key->GetPubKey().GetID(), *key);
                   +  - ]
     346                 :      511493 :     }
     347                 :           0 :     std::optional<CPubKey> GetRootPubKey() const override
     348                 :             :     {
     349                 :           0 :         return m_pubkey;
     350                 :             :     }
     351                 :           0 :     std::optional<CExtPubKey> GetRootExtPubKey() const override
     352                 :             :     {
     353                 :           0 :         return std::nullopt;
     354                 :             :     }
     355                 :      470507 :     std::unique_ptr<PubkeyProvider> Clone() const override
     356                 :             :     {
     357                 :      470507 :         return std::make_unique<ConstPubkeyProvider>(m_expr_index, m_pubkey, m_xonly);
     358                 :             :     }
     359                 :             : };
     360                 :             : 
     361                 :             : enum class DeriveType {
     362                 :             :     NO,
     363                 :             :     UNHARDENED,
     364                 :             :     HARDENED,
     365                 :             : };
     366                 :             : 
     367                 :             : /** An object representing a parsed extended public key in a descriptor. */
     368                 :             : class BIP32PubkeyProvider final : public PubkeyProvider
     369                 :             : {
     370                 :             :     // Root xpub, path, and final derivation step type being used, if any
     371                 :             :     CExtPubKey m_root_extkey;
     372                 :             :     KeyPath m_path;
     373                 :             :     DeriveType m_derive;
     374                 :             :     // Whether ' or h is used in harded derivation
     375                 :             :     bool m_apostrophe;
     376                 :             : 
     377                 :     3185039 :     bool GetExtKey(const SigningProvider& arg, CExtKey& ret) const
     378                 :             :     {
     379                 :     3185039 :         CKey key;
     380   [ +  -  +  -  :     3185039 :         if (!arg.GetKey(m_root_extkey.pubkey.GetID(), key)) return false;
                   +  + ]
     381                 :     2554474 :         ret.nDepth = m_root_extkey.nDepth;
     382                 :     2554474 :         std::copy(m_root_extkey.vchFingerprint, m_root_extkey.vchFingerprint + sizeof(ret.vchFingerprint), ret.vchFingerprint);
     383                 :     2554474 :         ret.nChild = m_root_extkey.nChild;
     384                 :     2554474 :         ret.chaincode = m_root_extkey.chaincode;
     385         [ +  - ]:     2554474 :         ret.key = key;
     386                 :             :         return true;
     387                 :     3185039 :     }
     388                 :             : 
     389                 :             :     // Derives the last xprv
     390                 :     2707005 :     bool GetDerivedExtKey(const SigningProvider& arg, CExtKey& xprv, CExtKey& last_hardened) const
     391                 :             :     {
     392         [ +  + ]:     2707005 :         if (!GetExtKey(arg, xprv)) return false;
     393         [ +  + ]:     5418054 :         for (auto entry : m_path) {
     394         [ +  - ]:     3127925 :             if (!xprv.Derive(xprv, entry)) return false;
     395         [ +  + ]:     3127925 :             if (entry >> 31) {
     396                 :     1116528 :                 last_hardened = xprv;
     397                 :             :             }
     398                 :             :         }
     399                 :             :         return true;
     400                 :             :     }
     401                 :             : 
     402                 :     3222210 :     bool IsHardened() const
     403                 :             :     {
     404         [ +  + ]:     3222210 :         if (m_derive == DeriveType::HARDENED) return true;
     405         [ +  + ]:     6186764 :         for (auto entry : m_path) {
     406         [ +  + ]:     3590383 :             if (entry >> 31) return true;
     407                 :             :         }
     408                 :             :         return false;
     409                 :             :     }
     410                 :             : 
     411                 :             : public:
     412                 :     1985770 :     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) {}
     413                 :     7799634 :     bool IsRange() const override { return m_derive != DeriveType::NO; }
     414                 :      224302 :     size_t GetSize() const override { return 33; }
     415                 :      137403 :     bool IsBIP32() const override { return true; }
     416                 :     5889909 :     std::optional<CPubKey> GetPubKey(int pos, const SigningProvider& arg, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
     417                 :             :     {
     418         [ +  - ]:     5889909 :         KeyOriginInfo info;
     419         [ +  - ]:     5889909 :         CKeyID keyid = m_root_extkey.pubkey.GetID();
     420                 :     5889909 :         std::copy(keyid.begin(), keyid.begin() + sizeof(info.fingerprint), info.fingerprint);
     421         [ +  - ]:     5889909 :         info.path = m_path;
     422   [ +  +  +  - ]:     5889909 :         if (m_derive == DeriveType::UNHARDENED) info.path.push_back((uint32_t)pos);
     423   [ +  +  +  - ]:     5889909 :         if (m_derive == DeriveType::HARDENED) info.path.push_back(((uint32_t)pos) | 0x80000000L);
     424                 :             : 
     425                 :             :         // Derive keys or fetch them from cache
     426                 :     5889909 :         CExtPubKey final_extkey = m_root_extkey;
     427                 :     5889909 :         CExtPubKey parent_extkey = m_root_extkey;
     428         [ +  + ]:     5889909 :         CExtPubKey last_hardened_extkey;
     429                 :     5889909 :         bool der = true;
     430         [ +  + ]:     5889909 :         if (read_cache) {
     431   [ +  -  +  + ]:     2667699 :             if (!read_cache->GetCachedDerivedExtPubKey(m_expr_index, pos, final_extkey)) {
     432         [ +  + ]:     2551769 :                 if (m_derive == DeriveType::HARDENED) return std::nullopt;
     433                 :             :                 // Try to get the derivation parent
     434   [ +  -  +  + ]:     2541297 :                 if (!read_cache->GetCachedParentExtPubKey(m_expr_index, parent_extkey)) return std::nullopt;
     435                 :     2522542 :                 final_extkey = parent_extkey;
     436   [ +  +  +  - ]:     2522542 :                 if (m_derive == DeriveType::UNHARDENED) der = parent_extkey.Derive(final_extkey, pos);
     437                 :             :             }
     438         [ +  + ]:     3222210 :         } else if (IsHardened()) {
     439         [ +  - ]:      625829 :             CExtKey xprv;
     440                 :      625829 :             CExtKey lh_xprv;
     441   [ +  -  +  + ]:      625829 :             if (!GetDerivedExtKey(arg, xprv, lh_xprv)) return std::nullopt;
     442         [ +  - ]:      590720 :             parent_extkey = xprv.Neuter();
     443   [ +  +  +  - ]:      590720 :             if (m_derive == DeriveType::UNHARDENED) der = xprv.Derive(xprv, pos);
     444   [ +  +  +  - ]:      590720 :             if (m_derive == DeriveType::HARDENED) der = xprv.Derive(xprv, pos | 0x80000000UL);
     445         [ +  - ]:      590720 :             final_extkey = xprv.Neuter();
     446         [ +  + ]:      590720 :             if (lh_xprv.key.IsValid()) {
     447         [ +  - ]:      491690 :                 last_hardened_extkey = lh_xprv.Neuter();
     448                 :             :             }
     449                 :      625829 :         } else {
     450         [ +  + ]:     5299546 :             for (auto entry : m_path) {
     451   [ +  -  -  + ]:     2703165 :                 if (!parent_extkey.Derive(parent_extkey, entry)) return std::nullopt;
     452                 :             :             }
     453                 :     2596381 :             final_extkey = parent_extkey;
     454   [ +  +  +  - ]:     2596381 :             if (m_derive == DeriveType::UNHARDENED) der = parent_extkey.Derive(final_extkey, pos);
     455         [ -  + ]:     2596381 :             assert(m_derive != DeriveType::HARDENED);
     456                 :             :         }
     457         [ -  + ]:     3582295 :         if (!der) return std::nullopt;
     458                 :             : 
     459   [ +  -  +  -  :     5825573 :         out.origins.emplace(final_extkey.pubkey.GetID(), std::make_pair(final_extkey.pubkey, info));
                   +  - ]
     460   [ +  -  +  - ]:     5825573 :         out.pubkeys.emplace(final_extkey.pubkey.GetID(), final_extkey.pubkey);
     461                 :             : 
     462         [ +  + ]:     5825573 :         if (write_cache) {
     463                 :             :             // Only cache parent if there is any unhardened derivation
     464         [ +  + ]:     2941132 :             if (m_derive != DeriveType::HARDENED) {
     465         [ +  - ]:     2841039 :                 write_cache->CacheParentExtPubKey(m_expr_index, parent_extkey);
     466                 :             :                 // Cache last hardened xpub if we have it
     467         [ +  + ]:     2841039 :                 if (last_hardened_extkey.pubkey.IsValid()) {
     468         [ +  - ]:      490627 :                     write_cache->CacheLastHardenedExtPubKey(m_expr_index, last_hardened_extkey);
     469                 :             :                 }
     470   [ -  +  +  - ]:      100093 :             } else if (info.path.size() > 0) {
     471         [ +  - ]:      100093 :                 write_cache->CacheDerivedExtPubKey(m_expr_index, pos, final_extkey);
     472                 :             :             }
     473                 :             :         }
     474                 :             : 
     475                 :     5825573 :         return final_extkey.pubkey;
     476                 :     5889909 :     }
     477                 :     4636081 :     std::string ToString(StringType type, bool normalized) const
     478                 :             :     {
     479                 :             :         // If StringType==COMPAT, always use the apostrophe to stay compatible with previous versions
     480   [ +  +  +  +  :     4636081 :         const bool use_apostrophe = (!normalized && m_apostrophe) || type == StringType::COMPAT;
                   +  + ]
     481   [ +  -  +  - ]:     9272162 :         std::string ret = EncodeExtPubKey(m_root_extkey) + FormatHDKeypath(m_path, /*apostrophe=*/use_apostrophe);
     482         [ +  + ]:     4636081 :         if (IsRange()) {
     483         [ +  - ]:      659404 :             ret += "/*";
     484   [ +  +  +  + ]:      659404 :             if (m_derive == DeriveType::HARDENED) ret += use_apostrophe ? '\'' : 'h';
     485                 :             :         }
     486                 :     4636081 :         return ret;
     487                 :           0 :     }
     488                 :     4582613 :     std::string ToString(StringType type=StringType::PUBLIC) const override
     489                 :             :     {
     490                 :     3170607 :         return ToString(type, /*normalized=*/false);
     491                 :             :     }
     492                 :      478034 :     bool ToPrivateString(const SigningProvider& arg, std::string& out) const override
     493                 :             :     {
     494         [ +  - ]:      478034 :         CExtKey key;
     495   [ +  -  +  + ]:      478034 :         if (!GetExtKey(arg, key)) return false;
     496   [ +  -  +  -  :      264345 :         out = EncodeExtKey(key) + FormatHDKeypath(m_path, /*apostrophe=*/m_apostrophe);
                   +  - ]
     497         [ +  + ]:      264345 :         if (IsRange()) {
     498         [ +  - ]:       11279 :             out += "/*";
     499   [ +  +  +  + ]:      483103 :             if (m_derive == DeriveType::HARDENED) out += m_apostrophe ? '\'' : 'h';
     500                 :             :         }
     501                 :             :         return true;
     502                 :      478034 :     }
     503                 :     1769649 :     bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache) const override
     504                 :             :     {
     505         [ +  + ]:     1769649 :         if (m_derive == DeriveType::HARDENED) {
     506                 :       53468 :             out = ToString(StringType::PUBLIC, /*normalized=*/true);
     507                 :             : 
     508                 :       53468 :             return true;
     509                 :             :         }
     510                 :             :         // Step backwards to find the last hardened step in the path
     511         [ -  + ]:     1716181 :         int i = (int)m_path.size() - 1;
     512         [ +  + ]:     3300819 :         for (; i >= 0; --i) {
     513         [ +  + ]:     1888813 :             if (m_path.at(i) >> 31) {
     514                 :             :                 break;
     515                 :             :             }
     516                 :             :         }
     517                 :             :         // Either no derivation or all unhardened derivation
     518         [ +  + ]:     1716181 :         if (i == -1) {
     519                 :     1412006 :             out = ToString();
     520                 :     1412006 :             return true;
     521                 :             :         }
     522                 :             :         // Get the path to the last hardened stup
     523                 :      304175 :         KeyOriginInfo origin;
     524                 :      304175 :         int k = 0;
     525         [ +  + ]:      818692 :         for (; k <= i; ++k) {
     526                 :             :             // Add to the path
     527   [ +  -  +  - ]:      514517 :             origin.path.push_back(m_path.at(k));
     528                 :             :         }
     529                 :             :         // Build the remaining path
     530                 :      304175 :         KeyPath end_path;
     531   [ -  +  +  + ]:      312854 :         for (; k < (int)m_path.size(); ++k) {
     532   [ +  -  +  - ]:        8679 :             end_path.push_back(m_path.at(k));
     533                 :             :         }
     534                 :             :         // Get the fingerprint
     535         [ +  - ]:      304175 :         CKeyID id = m_root_extkey.pubkey.GetID();
     536                 :      304175 :         std::copy(id.begin(), id.begin() + 4, origin.fingerprint);
     537                 :             : 
     538         [ +  + ]:      304175 :         CExtPubKey xpub;
     539         [ +  + ]:      304175 :         CExtKey lh_xprv;
     540                 :             :         // If we have the cache, just get the parent xpub
     541         [ +  + ]:      304175 :         if (cache != nullptr) {
     542         [ +  - ]:        2896 :             cache->GetCachedLastHardenedExtPubKey(m_expr_index, xpub);
     543                 :             :         }
     544         [ +  + ]:      304175 :         if (!xpub.pubkey.IsValid()) {
     545                 :             :             // Cache miss, or nor cache, or need privkey
     546         [ +  - ]:      301279 :             CExtKey xprv;
     547   [ +  -  +  + ]:      301279 :             if (!GetDerivedExtKey(arg, xprv, lh_xprv)) return false;
     548         [ +  - ]:      298817 :             xpub = lh_xprv.Neuter();
     549                 :      301279 :         }
     550         [ -  + ]:      301713 :         assert(xpub.pubkey.IsValid());
     551                 :             : 
     552                 :             :         // Build the string
     553   [ +  -  +  -  :      603426 :         std::string origin_str = HexStr(origin.fingerprint) + FormatHDKeypath(origin.path);
                   +  - ]
     554   [ +  -  +  -  :      603426 :         out = "[" + origin_str + "]" + EncodeExtPubKey(xpub) + FormatHDKeypath(end_path);
          +  -  +  -  +  
                      - ]
     555         [ +  + ]:      301713 :         if (IsRange()) {
     556         [ +  - ]:         782 :             out += "/*";
     557         [ -  + ]:         782 :             assert(m_derive == DeriveType::UNHARDENED);
     558                 :             :         }
     559                 :      301713 :         return true;
     560                 :      605888 :     }
     561                 :     1779897 :     void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const override
     562                 :             :     {
     563         [ +  - ]:     1779897 :         CExtKey extkey;
     564                 :     1779897 :         CExtKey dummy;
     565   [ +  -  +  + ]:     1779897 :         if (!GetDerivedExtKey(arg, extkey, dummy)) return;
     566   [ +  +  +  -  :     1400592 :         if (m_derive == DeriveType::UNHARDENED && !extkey.Derive(extkey, pos)) return;
                   +  - ]
     567   [ +  +  +  -  :     1400592 :         if (m_derive == DeriveType::HARDENED && !extkey.Derive(extkey, pos | 0x80000000UL)) return;
                   +  - ]
     568   [ +  -  +  -  :     1400592 :         out.keys.emplace(extkey.key.GetPubKey().GetID(), extkey.key);
                   +  - ]
     569                 :     1779897 :     }
     570                 :           0 :     std::optional<CPubKey> GetRootPubKey() const override
     571                 :             :     {
     572                 :           0 :         return std::nullopt;
     573                 :             :     }
     574                 :           0 :     std::optional<CExtPubKey> GetRootExtPubKey() const override
     575                 :             :     {
     576                 :           0 :         return m_root_extkey;
     577                 :             :     }
     578                 :     1499648 :     std::unique_ptr<PubkeyProvider> Clone() const override
     579                 :             :     {
     580         [ -  + ]:     1499648 :         return std::make_unique<BIP32PubkeyProvider>(m_expr_index, m_root_extkey, m_path, m_derive, m_apostrophe);
     581                 :             :     }
     582                 :             : };
     583                 :             : 
     584                 :             : /** PubkeyProvider for a musig() expression */
     585                 :             : class MuSigPubkeyProvider final : public PubkeyProvider
     586                 :             : {
     587                 :             : private:
     588                 :             :     //! PubkeyProvider for the participants
     589                 :             :     const std::vector<std::unique_ptr<PubkeyProvider>> m_participants;
     590                 :             :     //! Derivation path
     591                 :             :     const KeyPath m_path;
     592                 :             :     //! PubkeyProvider for the aggregate pubkey if it can be cached (i.e. participants are not ranged)
     593                 :             :     mutable std::unique_ptr<PubkeyProvider> m_aggregate_provider;
     594                 :             :     mutable std::optional<CPubKey> m_aggregate_pubkey;
     595                 :             :     const DeriveType m_derive;
     596                 :             :     const bool m_ranged_participants;
     597                 :             : 
     598                 :      232813 :     bool IsRangedDerivation() const { return m_derive != DeriveType::NO; }
     599                 :             : 
     600                 :             : public:
     601                 :       51569 :     MuSigPubkeyProvider(
     602                 :             :         uint32_t exp_index,
     603                 :             :         std::vector<std::unique_ptr<PubkeyProvider>> providers,
     604                 :             :         KeyPath path,
     605                 :             :         DeriveType derive
     606                 :             :     )
     607                 :       51569 :         : PubkeyProvider(exp_index),
     608                 :       51569 :         m_participants(std::move(providers)),
     609         [ +  - ]:       51569 :         m_path(std::move(path)),
     610         [ +  - ]:       51569 :         m_derive(derive),
     611         [ +  - ]:     1144011 :         m_ranged_participants(std::any_of(m_participants.begin(), m_participants.end(), [](const auto& pubkey) { return pubkey->IsRange(); }))
     612                 :             :     {
     613   [ +  +  +  -  :       55208 :         if (!Assume(!(m_ranged_participants && IsRangedDerivation()))) {
                   +  - ]
     614         [ #  # ]:           0 :             throw std::runtime_error("musig(): Cannot have both ranged participants and ranged derivation");
     615                 :             :         }
     616         [ +  - ]:       51569 :         if (!Assume(m_derive != DeriveType::HARDENED)) {
     617         [ #  # ]:           0 :             throw std::runtime_error("musig(): Cannot have hardened derivation");
     618                 :             :         }
     619                 :       51569 :     }
     620                 :             : 
     621                 :       99083 :     std::optional<CPubKey> GetPubKey(int pos, const SigningProvider& arg, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
     622                 :             :     {
     623                 :       99083 :         FlatSigningProvider dummy;
     624                 :             :         // If the participants are not ranged, we can compute and cache the aggregate pubkey by creating a PubkeyProvider for it
     625   [ +  +  +  + ]:       99083 :         if (!m_aggregate_provider && !m_ranged_participants) {
     626                 :             :             // Retrieve the pubkeys from the providers
     627                 :       40825 :             std::vector<CPubKey> pubkeys;
     628         [ +  + ]:     1004194 :             for (const auto& prov : m_participants) {
     629         [ +  - ]:      964355 :                 std::optional<CPubKey> pubkey = prov->GetPubKey(0, arg, dummy, read_cache, write_cache);
     630         [ +  + ]:      964355 :                 if (!pubkey.has_value()) {
     631                 :         986 :                     return std::nullopt;
     632                 :             :                 }
     633         [ +  - ]:      963369 :                 pubkeys.push_back(pubkey.value());
     634                 :             :             }
     635                 :       39839 :             std::sort(pubkeys.begin(), pubkeys.end());
     636                 :             : 
     637                 :             :             // Aggregate the pubkey
     638         [ +  - ]:       39839 :             m_aggregate_pubkey = MuSig2AggregatePubkeys(pubkeys);
     639         [ +  - ]:       39839 :             if (!Assume(m_aggregate_pubkey.has_value())) return std::nullopt;
     640                 :             : 
     641                 :             :             // Make our pubkey provider
     642   [ +  +  +  + ]:       39839 :             if (IsRangedDerivation() || !m_path.empty()) {
     643                 :             :                 // Make the synthetic xpub and construct the BIP32PubkeyProvider
     644         [ +  - ]:        3457 :                 CExtPubKey extpub = CreateMuSig2SyntheticXpub(m_aggregate_pubkey.value());
     645   [ +  -  -  + ]:        3457 :                 m_aggregate_provider = std::make_unique<BIP32PubkeyProvider>(m_expr_index, extpub, m_path, m_derive, /*apostrophe=*/false);
     646                 :             :             } else {
     647         [ +  - ]:       36382 :                 m_aggregate_provider = std::make_unique<ConstPubkeyProvider>(m_expr_index, m_aggregate_pubkey.value(), /*xonly=*/false);
     648                 :             :             }
     649                 :       40825 :         }
     650                 :             : 
     651                 :             :         // Retrieve all participant pubkeys
     652                 :       98097 :         std::vector<CPubKey> pubkeys;
     653         [ +  + ]:     2796391 :         for (const auto& prov : m_participants) {
     654         [ +  - ]:     2701397 :             std::optional<CPubKey> pub = prov->GetPubKey(pos, arg, out, read_cache, write_cache);
     655         [ +  + ]:     2701397 :             if (!pub) return std::nullopt;
     656         [ +  - ]:     2698294 :             pubkeys.emplace_back(*pub);
     657                 :             :         }
     658                 :       94994 :         std::sort(pubkeys.begin(), pubkeys.end());
     659                 :             : 
     660         [ +  + ]:       94994 :         CPubKey pubout;
     661         [ +  + ]:       94994 :         if (m_aggregate_provider) {
     662                 :             :             // When we have a cached aggregate key, we are either returning it or deriving from it
     663                 :             :             // Either way, we can passthrough to its GetPubKey
     664                 :             :             // Use a dummy signing provider as private keys do not exist for the aggregate pubkey
     665         [ +  - ]:       84657 :             std::optional<CPubKey> pub = m_aggregate_provider->GetPubKey(pos, dummy, out, read_cache, write_cache);
     666         [ -  + ]:       84657 :             if (!pub) return std::nullopt;
     667         [ +  - ]:       84657 :             pubout = *pub;
     668   [ +  -  +  - ]:       84657 :             out.aggregate_pubkeys.emplace(m_aggregate_pubkey.value(), pubkeys);
     669                 :             :         } else {
     670   [ -  +  +  -  :       10337 :             if (!Assume(m_ranged_participants) || !Assume(m_path.empty())) return std::nullopt;
                   +  - ]
     671                 :             :             // Compute aggregate key from derived participants
     672         [ +  - ]:       10337 :             std::optional<CPubKey> aggregate_pubkey = MuSig2AggregatePubkeys(pubkeys);
     673         [ -  + ]:       10337 :             if (!aggregate_pubkey) return std::nullopt;
     674         [ +  - ]:       10337 :             pubout = *aggregate_pubkey;
     675                 :             : 
     676         [ +  - ]:       10337 :             std::unique_ptr<ConstPubkeyProvider> this_agg_provider = std::make_unique<ConstPubkeyProvider>(m_expr_index, aggregate_pubkey.value(), /*xonly=*/false);
     677         [ +  - ]:       10337 :             this_agg_provider->GetPubKey(0, dummy, out, read_cache, write_cache);
     678         [ +  - ]:       10337 :             out.aggregate_pubkeys.emplace(pubout, pubkeys);
     679                 :       10337 :         }
     680                 :             : 
     681         [ +  - ]:       94994 :         if (!Assume(pubout.IsValid())) return std::nullopt;
     682                 :       94994 :         return pubout;
     683                 :       99083 :     }
     684   [ +  +  +  + ]:       87262 :     bool IsRange() const override { return IsRangedDerivation() || m_ranged_participants; }
     685                 :             :     // musig() expressions can only be used in tr() contexts which have 32 byte xonly pubkeys
     686                 :       14359 :     size_t GetSize() const override { return 32; }
     687                 :             : 
     688                 :       53746 :     std::string ToString(StringType type=StringType::PUBLIC) const override
     689                 :             :     {
     690                 :       53746 :         std::string out = "musig(";
     691   [ -  +  +  + ]:     1539022 :         for (size_t i = 0; i < m_participants.size(); ++i) {
     692         [ +  - ]:     1485276 :             const auto& pubkey = m_participants.at(i);
     693   [ +  +  +  - ]:     1485276 :             if (i) out += ",";
     694         [ +  - ]:     2970552 :             out += pubkey->ToString(type);
     695                 :             :         }
     696         [ +  - ]:       53746 :         out += ")";
     697         [ +  - ]:      107492 :         out += FormatHDKeypath(m_path);
     698         [ +  + ]:       53746 :         if (IsRangedDerivation()) {
     699         [ +  - ]:        1853 :             out += "/*";
     700                 :             :         }
     701                 :       53746 :         return out;
     702                 :           0 :     }
     703                 :        8750 :     bool ToPrivateString(const SigningProvider& arg, std::string& out) const override
     704                 :             :     {
     705                 :        8750 :         bool any_privkeys = false;
     706                 :        8750 :         out = "musig(";
     707   [ -  +  +  + ]:      466035 :         for (size_t i = 0; i < m_participants.size(); ++i) {
     708                 :      457285 :             const auto& pubkey = m_participants.at(i);
     709         [ +  + ]:      457285 :             if (i) out += ",";
     710         [ +  - ]:      457285 :             std::string tmp;
     711   [ +  -  +  + ]:      457285 :             if (pubkey->ToPrivateString(arg, tmp)) {
     712                 :      220949 :                 any_privkeys = true;
     713         [ -  + ]:      678234 :                 out += tmp;
     714                 :             :             } else {
     715         [ +  - ]:      472672 :                 out += pubkey->ToString();
     716                 :             :             }
     717                 :      457285 :         }
     718                 :        8750 :         out += ")";
     719         [ -  + ]:       17500 :         out += FormatHDKeypath(m_path);
     720         [ +  + ]:        8750 :         if (IsRangedDerivation()) {
     721                 :         547 :             out += "/*";
     722                 :             :         }
     723         [ +  + ]:        8750 :         if (!any_privkeys) out.clear();
     724                 :        8750 :         return any_privkeys;
     725                 :             :     }
     726                 :       40348 :     bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache = nullptr) const override
     727                 :             :     {
     728                 :       40348 :         out = "musig(";
     729   [ -  +  +  + ]:     1134319 :         for (size_t i = 0; i < m_participants.size(); ++i) {
     730                 :     1094742 :             const auto& pubkey = m_participants.at(i);
     731         [ +  + ]:     1094742 :             if (i) out += ",";
     732         [ +  - ]:     1094742 :             std::string tmp;
     733   [ +  -  +  + ]:     1094742 :             if (!pubkey->ToNormalizedString(arg, tmp, cache)) {
     734                 :         771 :                 return false;
     735                 :             :             }
     736         [ -  + ]:     2187942 :             out += tmp;
     737                 :     1094742 :         }
     738                 :       39577 :         out += ")";
     739         [ -  + ]:       79154 :         out += FormatHDKeypath(m_path);
     740         [ +  + ]:       39577 :         if (IsRangedDerivation()) {
     741                 :        1297 :             out += "/*";
     742                 :             :         }
     743                 :             :         return true;
     744                 :             :     }
     745                 :             : 
     746                 :       41433 :     void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const override
     747                 :             :     {
     748                 :             :         // Get the private keys for any participants that we have
     749                 :             :         // If there is participant derivation, it will be done.
     750                 :             :         // If there is not, then the participant privkeys will be included directly
     751         [ +  + ]:     1133813 :         for (const auto& prov : m_participants) {
     752                 :     1092380 :             prov->GetPrivKey(pos, arg, out);
     753                 :             :         }
     754                 :       41433 :     }
     755                 :             : 
     756                 :             :     // Get RootPubKey and GetRootExtPubKey are used to return the single pubkey underlying the pubkey provider
     757                 :             :     // to be presented to the user in gethdkeys. As this is a multisig construction, there is no single underlying
     758                 :             :     // pubkey hence nothing should be returned.
     759                 :             :     // While the aggregate pubkey could be returned as the root (ext)pubkey, it is not a pubkey that anyone should
     760                 :             :     // be using by itself in a descriptor as it is unspendable without knowing its participants.
     761                 :           0 :     std::optional<CPubKey> GetRootPubKey() const override
     762                 :             :     {
     763                 :           0 :         return std::nullopt;
     764                 :             :     }
     765                 :           0 :     std::optional<CExtPubKey> GetRootExtPubKey() const override
     766                 :             :     {
     767                 :           0 :         return std::nullopt;
     768                 :             :     }
     769                 :             : 
     770                 :       23159 :     std::unique_ptr<PubkeyProvider> Clone() const override
     771                 :             :     {
     772                 :       23159 :         std::vector<std::unique_ptr<PubkeyProvider>> providers;
     773   [ -  +  +  - ]:       23159 :         providers.reserve(m_participants.size());
     774         [ +  + ]:      351060 :         for (const std::unique_ptr<PubkeyProvider>& p : m_participants) {
     775   [ +  -  +  - ]:      327901 :             providers.emplace_back(p->Clone());
     776                 :             :         }
     777   [ +  -  -  + ]:       46318 :         return std::make_unique<MuSigPubkeyProvider>(m_expr_index, std::move(providers), m_path, m_derive);
     778                 :       23159 :     }
     779                 :           0 :     bool IsBIP32() const override
     780                 :             :     {
     781                 :             :         // musig() can only be a BIP 32 key if all participants are bip32 too
     782                 :           0 :         return std::all_of(m_participants.begin(), m_participants.end(), [](const auto& pubkey) { return pubkey->IsBIP32(); });
     783                 :             :     }
     784                 :             : };
     785                 :             : 
     786                 :             : /** Base class for all Descriptor implementations. */
     787                 :             : class DescriptorImpl : public Descriptor
     788                 :             : {
     789                 :             : protected:
     790                 :             :     //! Public key arguments for this descriptor (size 1 for PK, PKH, WPKH; any size for WSH and Multisig).
     791                 :             :     const std::vector<std::unique_ptr<PubkeyProvider>> m_pubkey_args;
     792                 :             :     //! The string name of the descriptor function.
     793                 :             :     const std::string m_name;
     794                 :             :     //! Warnings (not including subdescriptors).
     795                 :             :     std::vector<std::string> m_warnings;
     796                 :             : 
     797                 :             :     //! The sub-descriptor arguments (empty for everything but SH and WSH).
     798                 :             :     //! In doc/descriptors.m this is referred to as SCRIPT expressions sh(SCRIPT)
     799                 :             :     //! and wsh(SCRIPT), and distinct from KEY expressions and ADDR expressions.
     800                 :             :     //! Subdescriptors can only ever generate a single script.
     801                 :             :     const std::vector<std::unique_ptr<DescriptorImpl>> m_subdescriptor_args;
     802                 :             : 
     803                 :             :     //! Return a serialization of anything except pubkey and script arguments, to be prepended to those.
     804                 :      839627 :     virtual std::string ToStringExtra() const { return ""; }
     805                 :             : 
     806                 :             :     /** A helper function to construct the scripts for this descriptor.
     807                 :             :      *
     808                 :             :      *  This function is invoked once by ExpandHelper.
     809                 :             :      *
     810                 :             :      *  @param pubkeys The evaluations of the m_pubkey_args field.
     811                 :             :      *  @param scripts The evaluations of m_subdescriptor_args (one for each m_subdescriptor_args element).
     812                 :             :      *  @param out A FlatSigningProvider to put scripts or public keys in that are necessary to the solver.
     813                 :             :      *             The origin info of the provided pubkeys is automatically added.
     814                 :             :      *  @return A vector with scriptPubKeys for this descriptor.
     815                 :             :      */
     816                 :             :     virtual std::vector<CScript> MakeScripts(const std::vector<CPubKey>& pubkeys, std::span<const CScript> scripts, FlatSigningProvider& out) const = 0;
     817                 :             : 
     818                 :             : public:
     819         [ -  + ]:     3723578 :     DescriptorImpl(std::vector<std::unique_ptr<PubkeyProvider>> pubkeys, const std::string& name) : m_pubkey_args(std::move(pubkeys)), m_name(name), m_subdescriptor_args() {}
     820   [ -  +  +  - ]:      115132 :     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))) {}
     821         [ -  + ]:      131482 :     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)) {}
     822                 :             : 
     823                 :             :     enum class StringType
     824                 :             :     {
     825                 :             :         PUBLIC,
     826                 :             :         PRIVATE,
     827                 :             :         NORMALIZED,
     828                 :             :         COMPAT, // string calculation that mustn't change over time to stay compatible with previous software versions
     829                 :             :     };
     830                 :             : 
     831                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     832                 :       83516 :     bool IsSolvable() const override
     833                 :             :     {
     834         [ +  + ]:      155447 :         for (const auto& arg : m_subdescriptor_args) {
     835         [ +  - ]:       71931 :             if (!arg->IsSolvable()) return false;
     836                 :             :         }
     837                 :             :         return true;
     838                 :             :     }
     839                 :             : 
     840                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     841                 :      904260 :     bool IsRange() const final
     842                 :             :     {
     843         [ +  + ]:     2679212 :         for (const auto& pubkey : m_pubkey_args) {
     844         [ +  + ]:     2225323 :             if (pubkey->IsRange()) return true;
     845                 :             :         }
     846         [ +  + ]:      602800 :         for (const auto& arg : m_subdescriptor_args) {
     847         [ +  + ]:      330061 :             if (arg->IsRange()) return true;
     848                 :             :         }
     849                 :             :         return false;
     850                 :             :     }
     851                 :             : 
     852                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     853                 :     2293794 :     virtual bool ToStringSubScriptHelper(const SigningProvider* arg, std::string& ret, const StringType type, const DescriptorCache* cache = nullptr) const
     854                 :             :     {
     855                 :     2293794 :         size_t pos = 0;
     856         [ +  + ]:     2511843 :         for (const auto& scriptarg : m_subdescriptor_args) {
     857         [ -  + ]:      233045 :             if (pos++) ret += ",";
     858         [ +  - ]:      233045 :             std::string tmp;
     859   [ +  -  +  + ]:      233045 :             if (!scriptarg->ToStringHelper(arg, tmp, type, cache)) return false;
     860         [ -  + ]:      436098 :             ret += tmp;
     861                 :      233045 :         }
     862                 :             :         return true;
     863                 :             :     }
     864                 :             : 
     865                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     866                 :     2535263 :     virtual bool ToStringHelper(const SigningProvider* arg, std::string& out, const StringType type, const DescriptorCache* cache = nullptr) const
     867                 :             :     {
     868                 :     2535263 :         std::string extra = ToStringExtra();
     869   [ -  +  +  + ]:     2535263 :         size_t pos = extra.size() > 0 ? 1 : 0;
     870   [ +  -  +  - ]:     2535263 :         std::string ret = m_name + "(" + extra;
     871         [ +  + ]:     7103174 :         for (const auto& pubkey : m_pubkey_args) {
     872   [ +  +  +  - ]:     4587654 :             if (pos++) ret += ",";
     873   [ +  +  +  +  :     4587654 :             std::string tmp;
                      - ]
     874   [ +  +  +  +  :     4587654 :             switch (type) {
                      - ]
     875                 :     1147028 :                 case StringType::NORMALIZED:
     876   [ +  -  +  + ]:     1147028 :                     if (!pubkey->ToNormalizedString(*arg, tmp, cache)) return false;
     877                 :             :                     break;
     878                 :      113058 :                 case StringType::PRIVATE:
     879   [ +  -  +  + ]:      113058 :                     if (!pubkey->ToPrivateString(*arg, tmp)) return false;
     880                 :             :                     break;
     881                 :     3216983 :                 case StringType::PUBLIC:
     882         [ +  - ]:     3216983 :                     tmp = pubkey->ToString();
     883                 :     3216983 :                     break;
     884                 :      110585 :                 case StringType::COMPAT:
     885         [ +  - ]:      110585 :                     tmp = pubkey->ToString(PubkeyProvider::StringType::COMPAT);
     886                 :      110585 :                     break;
     887                 :             :             }
     888         [ -  + ]:     9135822 :             ret += tmp;
     889                 :     4587654 :         }
     890         [ +  - ]:     5031040 :         std::string subscript;
     891   [ +  -  +  + ]:     2515520 :         if (!ToStringSubScriptHelper(arg, subscript, type, cache)) return false;
     892   [ +  +  +  +  :     4482162 :         if (pos && subscript.size()) ret += ',';
                   +  - ]
     893         [ +  - ]:     4982814 :         out = std::move(ret) + std::move(subscript) + ")";
     894                 :     2491407 :         return true;
     895                 :     5070526 :     }
     896                 :             : 
     897                 :     2179549 :     std::string ToString(bool compat_format) const final
     898                 :             :     {
     899         [ +  + ]:     2179549 :         std::string ret;
     900   [ +  +  +  - ]:     4334771 :         ToStringHelper(nullptr, ret, compat_format ? StringType::COMPAT : StringType::PUBLIC);
     901         [ +  - ]:     2179549 :         return AddChecksum(ret);
     902                 :     2179549 :     }
     903                 :             : 
     904                 :       58229 :     bool ToPrivateString(const SigningProvider& arg, std::string& out) const override
     905                 :             :     {
     906                 :       58229 :         bool ret = ToStringHelper(&arg, out, StringType::PRIVATE);
     907                 :       58229 :         out = AddChecksum(out);
     908                 :       58229 :         return ret;
     909                 :             :     }
     910                 :             : 
     911                 :       65229 :     bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache) const override final
     912                 :             :     {
     913                 :       65229 :         bool ret = ToStringHelper(&arg, out, StringType::NORMALIZED, cache);
     914                 :       65229 :         out = AddChecksum(out);
     915                 :       65229 :         return ret;
     916                 :             :     }
     917                 :             : 
     918                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     919                 :      888909 :     bool ExpandHelper(int pos, const SigningProvider& arg, const DescriptorCache* read_cache, std::vector<CScript>& output_scripts, FlatSigningProvider& out, DescriptorCache* write_cache) const
     920                 :             :     {
     921                 :      888909 :         FlatSigningProvider subprovider;
     922                 :      888909 :         std::vector<CPubKey> pubkeys;
     923   [ -  +  +  - ]:      888909 :         pubkeys.reserve(m_pubkey_args.size());
     924                 :             : 
     925                 :             :         // Construct temporary data in `pubkeys`, `subscripts`, and `subprovider` to avoid producing output in case of failure.
     926         [ +  + ]:     5580455 :         for (const auto& p : m_pubkey_args) {
     927         [ +  - ]:     4723646 :             std::optional<CPubKey> pubkey = p->GetPubKey(pos, arg, subprovider, read_cache, write_cache);
     928         [ +  + ]:     4723646 :             if (!pubkey) return false;
     929         [ +  - ]:     4691546 :             pubkeys.push_back(pubkey.value());
     930                 :             :         }
     931                 :      856809 :         std::vector<CScript> subscripts;
     932         [ +  + ]:     1174666 :         for (const auto& subarg : m_subdescriptor_args) {
     933                 :      331893 :             std::vector<CScript> outscripts;
     934   [ +  -  +  + ]:      331893 :             if (!subarg->ExpandHelper(pos, arg, read_cache, outscripts, subprovider, write_cache)) return false;
     935   [ -  +  -  + ]:      317857 :             assert(outscripts.size() == 1);
     936         [ +  - ]:      317857 :             subscripts.emplace_back(std::move(outscripts[0]));
     937                 :      331893 :         }
     938         [ +  - ]:      842773 :         out.Merge(std::move(subprovider));
     939                 :             : 
     940   [ -  +  +  - ]:      842773 :         output_scripts = MakeScripts(pubkeys, std::span{subscripts}, out);
     941                 :      842773 :         return true;
     942                 :     1745718 :     }
     943                 :             : 
     944                 :       88120 :     bool Expand(int pos, const SigningProvider& provider, std::vector<CScript>& output_scripts, FlatSigningProvider& out, DescriptorCache* write_cache = nullptr) const final
     945                 :             :     {
     946                 :       88120 :         return ExpandHelper(pos, provider, nullptr, output_scripts, out, write_cache);
     947                 :             :     }
     948                 :             : 
     949                 :      468896 :     bool ExpandFromCache(int pos, const DescriptorCache& read_cache, std::vector<CScript>& output_scripts, FlatSigningProvider& out) const final
     950                 :             :     {
     951                 :      468896 :         return ExpandHelper(pos, DUMMY_SIGNING_PROVIDER, &read_cache, output_scripts, out, nullptr);
     952                 :             :     }
     953                 :             : 
     954                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     955                 :      139013 :     void ExpandPrivate(int pos, const SigningProvider& provider, FlatSigningProvider& out) const final
     956                 :             :     {
     957         [ +  + ]:     1379456 :         for (const auto& p : m_pubkey_args) {
     958                 :     1240443 :             p->GetPrivKey(pos, provider, out);
     959                 :             :         }
     960         [ +  + ]:      211377 :         for (const auto& arg : m_subdescriptor_args) {
     961                 :       72364 :             arg->ExpandPrivate(pos, provider, out);
     962                 :             :         }
     963                 :      139013 :     }
     964                 :             : 
     965                 :       19304 :     std::optional<OutputType> GetOutputType() const override { return std::nullopt; }
     966                 :             : 
     967                 :           0 :     std::optional<int64_t> ScriptSize() const override { return {}; }
     968                 :             : 
     969                 :             :     /** A helper for MaxSatisfactionWeight.
     970                 :             :      *
     971                 :             :      * @param use_max_sig Whether to assume ECDSA signatures will have a high-r.
     972                 :             :      * @return The maximum size of the satisfaction in raw bytes (with no witness meaning).
     973                 :             :      */
     974                 :           0 :     virtual std::optional<int64_t> MaxSatSize(bool use_max_sig) const { return {}; }
     975                 :             : 
     976                 :        3832 :     std::optional<int64_t> MaxSatisfactionWeight(bool) const override { return {}; }
     977                 :             : 
     978                 :        1916 :     std::optional<int64_t> MaxSatisfactionElems() const override { return {}; }
     979                 :             : 
     980                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     981                 :           0 :     void GetPubKeys(std::set<CPubKey>& pubkeys, std::set<CExtPubKey>& ext_pubs) const override
     982                 :             :     {
     983         [ #  # ]:           0 :         for (const auto& p : m_pubkey_args) {
     984                 :           0 :             std::optional<CPubKey> pub = p->GetRootPubKey();
     985         [ #  # ]:           0 :             if (pub) pubkeys.insert(*pub);
     986                 :           0 :             std::optional<CExtPubKey> ext_pub = p->GetRootExtPubKey();
     987         [ #  # ]:           0 :             if (ext_pub) ext_pubs.insert(*ext_pub);
     988                 :             :         }
     989         [ #  # ]:           0 :         for (const auto& arg : m_subdescriptor_args) {
     990                 :           0 :             arg->GetPubKeys(pubkeys, ext_pubs);
     991                 :             :         }
     992                 :           0 :     }
     993                 :             : 
     994                 :             :     virtual std::unique_ptr<DescriptorImpl> Clone() const = 0;
     995                 :             : 
     996                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     997                 :           0 :     std::vector<std::string> Warnings() const override {
     998                 :           0 :         std::vector<std::string> all = m_warnings;
     999         [ #  # ]:           0 :         for (const auto& sub : m_subdescriptor_args) {
    1000         [ #  # ]:           0 :             auto sub_w = sub->Warnings();
    1001         [ #  # ]:           0 :             all.insert(all.end(), sub_w.begin(), sub_w.end());
    1002                 :           0 :         }
    1003                 :           0 :         return all;
    1004                 :           0 :     }
    1005                 :             : };
    1006                 :             : 
    1007                 :             : /** A parsed addr(A) descriptor. */
    1008                 :             : class AddressDescriptor final : public DescriptorImpl
    1009                 :             : {
    1010                 :             :     const CTxDestination m_destination;
    1011                 :             : protected:
    1012                 :      363947 :     std::string ToStringExtra() const override { return EncodeDestination(m_destination); }
    1013         [ +  - ]:         128 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, std::span<const CScript>, FlatSigningProvider&) const override { return Vector(GetScriptForDestination(m_destination)); }
    1014                 :             : public:
    1015         [ +  - ]:      364131 :     AddressDescriptor(CTxDestination destination) : DescriptorImpl({}, "addr"), m_destination(std::move(destination)) {}
    1016                 :           0 :     bool IsSolvable() const final { return false; }
    1017                 :             : 
    1018                 :         105 :     std::optional<OutputType> GetOutputType() const override
    1019                 :             :     {
    1020                 :         105 :         return OutputTypeFromDestination(m_destination);
    1021                 :             :     }
    1022                 :         210 :     bool IsSingleType() const final { return true; }
    1023                 :           5 :     bool ToPrivateString(const SigningProvider& arg, std::string& out) const final { return false; }
    1024                 :             : 
    1025         [ #  # ]:           0 :     std::optional<int64_t> ScriptSize() const override { return GetScriptForDestination(m_destination).size(); }
    1026                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1027                 :             :     {
    1028         [ #  # ]:           0 :         return std::make_unique<AddressDescriptor>(m_destination);
    1029                 :             :     }
    1030                 :             : };
    1031                 :             : 
    1032                 :             : /** A parsed raw(H) descriptor. */
    1033                 :             : class RawDescriptor final : public DescriptorImpl
    1034                 :             : {
    1035                 :             :     const CScript m_script;
    1036                 :             : protected:
    1037         [ +  + ]:     2501678 :     std::string ToStringExtra() const override { return HexStr(m_script); }
    1038                 :        6236 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, std::span<const CScript>, FlatSigningProvider&) const override { return Vector(m_script); }
    1039                 :             : public:
    1040         [ +  - ]:     1245499 :     RawDescriptor(CScript script) : DescriptorImpl({}, "raw"), m_script(std::move(script)) {}
    1041                 :         418 :     bool IsSolvable() const final { return false; }
    1042                 :             : 
    1043                 :        5252 :     std::optional<OutputType> GetOutputType() const override
    1044                 :             :     {
    1045                 :        5252 :         CTxDestination dest;
    1046         [ +  - ]:        5252 :         ExtractDestination(m_script, dest);
    1047         [ +  - ]:        5252 :         return OutputTypeFromDestination(dest);
    1048                 :        5252 :     }
    1049                 :        6235 :     bool IsSingleType() const final { return true; }
    1050                 :         842 :     bool ToPrivateString(const SigningProvider& arg, std::string& out) const final { return false; }
    1051                 :             : 
    1052         [ +  + ]:         416 :     std::optional<int64_t> ScriptSize() const override { return m_script.size(); }
    1053                 :             : 
    1054                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1055                 :             :     {
    1056         [ #  # ]:           0 :         return std::make_unique<RawDescriptor>(m_script);
    1057                 :             :     }
    1058                 :             : };
    1059                 :             : 
    1060                 :             : /** A parsed pk(P) descriptor. */
    1061                 :             : class PKDescriptor final : public DescriptorImpl
    1062                 :             : {
    1063                 :             : private:
    1064                 :             :     const bool m_xonly;
    1065                 :             : protected:
    1066                 :       28793 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override
    1067                 :             :     {
    1068         [ +  + ]:       28793 :         if (m_xonly) {
    1069   [ +  -  +  - ]:       43844 :             CScript script = CScript() << ToByteVector(XOnlyPubKey(keys[0])) << OP_CHECKSIG;
    1070         [ +  - ]:       21922 :             return Vector(std::move(script));
    1071                 :       21922 :         } else {
    1072         [ +  - ]:       13742 :             return Vector(GetScriptForRawPubKey(keys[0]));
    1073                 :             :         }
    1074                 :             :     }
    1075                 :             : public:
    1076   [ +  -  +  - ]:       52866 :     PKDescriptor(std::unique_ptr<PubkeyProvider> prov, bool xonly = false) : DescriptorImpl(Vector(std::move(prov)), "pk"), m_xonly(xonly) {}
    1077                 :        1990 :     bool IsSingleType() const final { return true; }
    1078                 :             : 
    1079                 :        2500 :     std::optional<int64_t> ScriptSize() const override {
    1080         [ +  - ]:        2500 :         return 1 + (m_xonly ? 32 : m_pubkey_args[0]->GetSize()) + 1;
    1081                 :             :     }
    1082                 :             : 
    1083                 :        3344 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
    1084         [ -  + ]:        1678 :         const auto ecdsa_sig_size = use_max_sig ? 72 : 71;
    1085   [ +  -  +  - ]:        3344 :         return 1 + (m_xonly ? 65 : ecdsa_sig_size);
    1086                 :             :     }
    1087                 :             : 
    1088                 :        1666 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
    1089         [ -  + ]:        1666 :         return *MaxSatSize(use_max_sig) * WITNESS_SCALE_FACTOR;
    1090                 :             :     }
    1091                 :             : 
    1092                 :        1672 :     std::optional<int64_t> MaxSatisfactionElems() const override { return 1; }
    1093                 :             : 
    1094                 :        2907 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1095                 :             :     {
    1096   [ +  -  -  + ]:        2907 :         return std::make_unique<PKDescriptor>(m_pubkey_args.at(0)->Clone(), m_xonly);
    1097                 :             :     }
    1098                 :             : };
    1099                 :             : 
    1100                 :             : /** A parsed pkh(P) descriptor. */
    1101                 :             : class PKHDescriptor final : public DescriptorImpl
    1102                 :             : {
    1103                 :             : protected:
    1104                 :      109449 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override
    1105                 :             :     {
    1106                 :      109449 :         CKeyID id = keys[0].GetID();
    1107   [ +  -  +  - ]:      218898 :         return Vector(GetScriptForDestination(PKHash(id)));
    1108                 :             :     }
    1109                 :             : public:
    1110   [ +  -  +  - ]:        8277 :     PKHDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "pkh") {}
    1111                 :       57886 :     std::optional<OutputType> GetOutputType() const override { return OutputType::LEGACY; }
    1112                 :      106669 :     bool IsSingleType() const final { return true; }
    1113                 :             : 
    1114                 :        2533 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 1 + 20 + 1 + 1; }
    1115                 :             : 
    1116                 :        3360 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
    1117         [ +  + ]:        3360 :         const auto sig_size = use_max_sig ? 72 : 71;
    1118                 :        3360 :         return 1 + sig_size + 1 + m_pubkey_args[0]->GetSize();
    1119                 :             :     }
    1120                 :             : 
    1121                 :        1504 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
    1122                 :        1504 :         return *MaxSatSize(use_max_sig) * WITNESS_SCALE_FACTOR;
    1123                 :             :     }
    1124                 :             : 
    1125                 :        1751 :     std::optional<int64_t> MaxSatisfactionElems() const override { return 2; }
    1126                 :             : 
    1127                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1128                 :             :     {
    1129   [ #  #  #  # ]:           0 :         return std::make_unique<PKHDescriptor>(m_pubkey_args.at(0)->Clone());
    1130                 :             :     }
    1131                 :             : };
    1132                 :             : 
    1133                 :             : /** A parsed wpkh(P) descriptor. */
    1134                 :             : class WPKHDescriptor final : public DescriptorImpl
    1135                 :             : {
    1136                 :             : protected:
    1137                 :      152357 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override
    1138                 :             :     {
    1139                 :      152357 :         CKeyID id = keys[0].GetID();
    1140   [ +  -  +  - ]:      304714 :         return Vector(GetScriptForDestination(WitnessV0KeyHash(id)));
    1141                 :             :     }
    1142                 :             : public:
    1143   [ +  -  +  - ]:        9678 :     WPKHDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "wpkh") {}
    1144                 :       82311 :     std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32; }
    1145                 :       16816 :     bool IsSingleType() const final { return true; }
    1146                 :             : 
    1147                 :        1450 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 20; }
    1148                 :             : 
    1149                 :        2003 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
    1150         [ +  + ]:        1077 :         const auto sig_size = use_max_sig ? 72 : 71;
    1151                 :        2003 :         return (1 + sig_size + 1 + 33);
    1152                 :             :     }
    1153                 :             : 
    1154                 :         988 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
    1155         [ +  + ]:         988 :         return MaxSatSize(use_max_sig);
    1156                 :             :     }
    1157                 :             : 
    1158                 :        1137 :     std::optional<int64_t> MaxSatisfactionElems() const override { return 2; }
    1159                 :             : 
    1160                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1161                 :             :     {
    1162   [ #  #  #  # ]:           0 :         return std::make_unique<WPKHDescriptor>(m_pubkey_args.at(0)->Clone());
    1163                 :             :     }
    1164                 :             : };
    1165                 :             : 
    1166                 :             : /** A parsed combo(P) descriptor. */
    1167                 :             : class ComboDescriptor final : public DescriptorImpl
    1168                 :             : {
    1169                 :             : protected:
    1170                 :        4929 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider& out) const override
    1171                 :             :     {
    1172                 :        4929 :         std::vector<CScript> ret;
    1173         [ +  - ]:        4929 :         CKeyID id = keys[0].GetID();
    1174   [ +  -  +  - ]:        4929 :         ret.emplace_back(GetScriptForRawPubKey(keys[0])); // P2PK
    1175   [ +  -  +  -  :        9858 :         ret.emplace_back(GetScriptForDestination(PKHash(id))); // P2PKH
                   +  - ]
    1176         [ +  + ]:        4929 :         if (keys[0].IsCompressed()) {
    1177         [ +  - ]:        4905 :             CScript p2wpkh = GetScriptForDestination(WitnessV0KeyHash(id));
    1178   [ +  -  +  - ]:        4905 :             out.scripts.emplace(CScriptID(p2wpkh), p2wpkh);
    1179         [ +  - ]:        4905 :             ret.emplace_back(p2wpkh);
    1180   [ +  -  +  -  :        9810 :             ret.emplace_back(GetScriptForDestination(ScriptHash(p2wpkh))); // P2SH-P2WPKH
                   +  - ]
    1181                 :        4905 :         }
    1182                 :        4929 :         return ret;
    1183                 :           0 :     }
    1184                 :             : public:
    1185   [ +  -  +  - ]:        2257 :     ComboDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "combo") {}
    1186                 :        3265 :     bool IsSingleType() const final { return false; }
    1187                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1188                 :             :     {
    1189   [ #  #  #  # ]:           0 :         return std::make_unique<ComboDescriptor>(m_pubkey_args.at(0)->Clone());
    1190                 :             :     }
    1191                 :             : };
    1192                 :             : 
    1193                 :             : /** A parsed multi(...) or sortedmulti(...) descriptor */
    1194                 :             : class MultisigDescriptor final : public DescriptorImpl
    1195                 :             : {
    1196                 :             :     const int m_threshold;
    1197                 :             :     const bool m_sorted;
    1198                 :             : protected:
    1199                 :       49684 :     std::string ToStringExtra() const override { return strprintf("%i", m_threshold); }
    1200                 :       15830 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override {
    1201         [ +  + ]:       15830 :         if (m_sorted) {
    1202                 :        8414 :             std::vector<CPubKey> sorted_keys(keys);
    1203                 :        8414 :             std::sort(sorted_keys.begin(), sorted_keys.end());
    1204   [ +  -  +  - ]:       16828 :             return Vector(GetScriptForMultisig(m_threshold, sorted_keys));
    1205                 :        8414 :         }
    1206         [ +  - ]:       14832 :         return Vector(GetScriptForMultisig(m_threshold, keys));
    1207                 :             :     }
    1208                 :             : public:
    1209   [ +  +  +  - ]:       76107 :     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) {}
    1210                 :        1229 :     bool IsSingleType() const final { return true; }
    1211                 :             : 
    1212                 :       10619 :     std::optional<int64_t> ScriptSize() const override {
    1213         [ -  + ]:       10619 :         const auto n_keys = m_pubkey_args.size();
    1214                 :      100226 :         auto op = [](int64_t acc, const std::unique_ptr<PubkeyProvider>& pk) { return acc + 1 + pk->GetSize();};
    1215                 :       10619 :         const auto pubkeys_size{std::accumulate(m_pubkey_args.begin(), m_pubkey_args.end(), int64_t{0}, op)};
    1216   [ -  +  +  - ]:       21238 :         return 1 + BuildScript(n_keys).size() + BuildScript(m_threshold).size() + pubkeys_size;
    1217                 :             :     }
    1218                 :             : 
    1219                 :       11126 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
    1220         [ -  + ]:       10142 :         const auto sig_size = use_max_sig ? 72 : 71;
    1221                 :       11126 :         return (1 + (1 + sig_size) * m_threshold);
    1222                 :             :     }
    1223                 :             : 
    1224                 :         984 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
    1225         [ -  + ]:         984 :         return *MaxSatSize(use_max_sig) * WITNESS_SCALE_FACTOR;
    1226                 :             :     }
    1227                 :             : 
    1228                 :        5563 :     std::optional<int64_t> MaxSatisfactionElems() const override { return 1 + m_threshold; }
    1229                 :             : 
    1230                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1231                 :             :     {
    1232                 :           0 :         std::vector<std::unique_ptr<PubkeyProvider>> providers;
    1233   [ #  #  #  # ]:           0 :         providers.reserve(m_pubkey_args.size());
    1234         [ #  # ]:           0 :         std::transform(m_pubkey_args.begin(), m_pubkey_args.end(), providers.begin(), [](const std::unique_ptr<PubkeyProvider>& p) { return p->Clone(); });
    1235   [ #  #  #  # ]:           0 :         return std::make_unique<MultisigDescriptor>(m_threshold, std::move(providers), m_sorted);
    1236                 :           0 :     }
    1237                 :             : };
    1238                 :             : 
    1239                 :             : /** A parsed (sorted)multi_a(...) descriptor. Always uses x-only pubkeys. */
    1240                 :             : class MultiADescriptor final : public DescriptorImpl
    1241                 :             : {
    1242                 :             :     const int m_threshold;
    1243                 :             :     const bool m_sorted;
    1244                 :             : protected:
    1245                 :       31166 :     std::string ToStringExtra() const override { return strprintf("%i", m_threshold); }
    1246                 :       26748 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override {
    1247                 :       26748 :         CScript ret;
    1248                 :       26748 :         std::vector<XOnlyPubKey> xkeys;
    1249   [ -  +  +  - ]:       26748 :         xkeys.reserve(keys.size());
    1250   [ +  -  +  + ]:     3498029 :         for (const auto& key : keys) xkeys.emplace_back(key);
    1251         [ +  + ]:       26748 :         if (m_sorted) std::sort(xkeys.begin(), xkeys.end());
    1252   [ +  -  +  - ]:       53496 :         ret << ToByteVector(xkeys[0]) << OP_CHECKSIG;
    1253   [ -  +  +  + ]:     3471281 :         for (size_t i = 1; i < keys.size(); ++i) {
    1254   [ +  -  +  - ]:    10333599 :             ret << ToByteVector(xkeys[i]) << OP_CHECKSIGADD;
    1255                 :             :         }
    1256   [ +  -  +  - ]:       26748 :         ret << m_threshold << OP_NUMEQUAL;
    1257         [ +  - ]:       26748 :         return Vector(std::move(ret));
    1258                 :       26748 :     }
    1259                 :             : public:
    1260   [ +  +  +  - ]:       35172 :     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) {}
    1261                 :           0 :     bool IsSingleType() const final { return true; }
    1262                 :             : 
    1263                 :           0 :     std::optional<int64_t> ScriptSize() const override {
    1264         [ #  # ]:           0 :         const auto n_keys = m_pubkey_args.size();
    1265         [ #  # ]:           0 :         return (1 + 32 + 1) * n_keys + BuildScript(m_threshold).size() + 1;
    1266                 :             :     }
    1267                 :             : 
    1268                 :           0 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
    1269         [ #  # ]:           0 :         return (1 + 65) * m_threshold + (m_pubkey_args.size() - m_threshold);
    1270                 :             :     }
    1271                 :             : 
    1272         [ #  # ]:           0 :     std::optional<int64_t> MaxSatisfactionElems() const override { return m_pubkey_args.size(); }
    1273                 :             : 
    1274                 :        1455 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1275                 :             :     {
    1276                 :        1455 :         std::vector<std::unique_ptr<PubkeyProvider>> providers;
    1277   [ -  +  +  - ]:        1455 :         providers.reserve(m_pubkey_args.size());
    1278         [ +  + ]:       11084 :         for (const auto& arg : m_pubkey_args) {
    1279         [ +  - ]:       19258 :             providers.push_back(arg->Clone());
    1280                 :             :         }
    1281   [ +  -  -  + ]:        2910 :         return std::make_unique<MultiADescriptor>(m_threshold, std::move(providers), m_sorted);
    1282                 :        1455 :     }
    1283                 :             : };
    1284                 :             : 
    1285                 :             : /** A parsed sh(...) descriptor. */
    1286                 :             : class SHDescriptor final : public DescriptorImpl
    1287                 :             : {
    1288                 :             : protected:
    1289                 :      154937 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, std::span<const CScript> scripts, FlatSigningProvider& out) const override
    1290                 :             :     {
    1291   [ +  -  +  - ]:      309874 :         auto ret = Vector(GetScriptForDestination(ScriptHash(scripts[0])));
    1292   [ -  +  +  -  :      154937 :         if (ret.size()) out.scripts.emplace(CScriptID(scripts[0]), scripts[0]);
             +  -  +  - ]
    1293                 :      154937 :         return ret;
    1294                 :           0 :     }
    1295                 :             : 
    1296         [ +  + ]:      101513 :     bool IsSegwit() const { return m_subdescriptor_args[0]->GetOutputType() == OutputType::BECH32; }
    1297                 :             : 
    1298                 :             : public:
    1299         [ +  - ]:       18679 :     SHDescriptor(std::unique_ptr<DescriptorImpl> desc) : DescriptorImpl({}, std::move(desc), "sh") {}
    1300                 :             : 
    1301                 :       87816 :     std::optional<OutputType> GetOutputType() const override
    1302                 :             :     {
    1303   [ -  +  -  + ]:       87816 :         assert(m_subdescriptor_args.size() == 1);
    1304         [ +  + ]:       87816 :         if (IsSegwit()) return OutputType::P2SH_SEGWIT;
    1305                 :        9120 :         return OutputType::LEGACY;
    1306                 :             :     }
    1307                 :      156452 :     bool IsSingleType() const final { return true; }
    1308                 :             : 
    1309                 :        6636 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 20 + 1; }
    1310                 :             : 
    1311                 :       13697 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
    1312         [ +  - ]:       13697 :         if (const auto sat_size = m_subdescriptor_args[0]->MaxSatSize(use_max_sig)) {
    1313         [ +  - ]:       13697 :             if (const auto subscript_size = m_subdescriptor_args[0]->ScriptSize()) {
    1314                 :             :                 // The subscript is never witness data.
    1315                 :       13697 :                 const auto subscript_weight = (1 + *subscript_size) * WITNESS_SCALE_FACTOR;
    1316                 :             :                 // The weight depends on whether the inner descriptor is satisfied using the witness stack.
    1317         [ +  + ]:       13697 :                 if (IsSegwit()) return subscript_weight + *sat_size;
    1318                 :        5638 :                 return subscript_weight + *sat_size * WITNESS_SCALE_FACTOR;
    1319                 :             :             }
    1320                 :             :         }
    1321                 :           0 :         return {};
    1322                 :             :     }
    1323                 :             : 
    1324                 :        6953 :     std::optional<int64_t> MaxSatisfactionElems() const override {
    1325         [ +  - ]:        6953 :         if (const auto sub_elems = m_subdescriptor_args[0]->MaxSatisfactionElems()) return 1 + *sub_elems;
    1326                 :           0 :         return {};
    1327                 :             :     }
    1328                 :             : 
    1329                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1330                 :             :     {
    1331   [ #  #  #  # ]:           0 :         return std::make_unique<SHDescriptor>(m_subdescriptor_args.at(0)->Clone());
    1332                 :             :     }
    1333                 :             : };
    1334                 :             : 
    1335                 :             : /** A parsed wsh(...) descriptor. */
    1336                 :             : class WSHDescriptor final : public DescriptorImpl
    1337                 :             : {
    1338                 :             : protected:
    1339                 :       43359 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, std::span<const CScript> scripts, FlatSigningProvider& out) const override
    1340                 :             :     {
    1341   [ +  -  +  - ]:       86718 :         auto ret = Vector(GetScriptForDestination(WitnessV0ScriptHash(scripts[0])));
    1342   [ -  +  +  -  :       43359 :         if (ret.size()) out.scripts.emplace(CScriptID(scripts[0]), scripts[0]);
             +  -  +  - ]
    1343                 :       43359 :         return ret;
    1344                 :           0 :     }
    1345                 :             : public:
    1346         [ +  - ]:       38887 :     WSHDescriptor(std::unique_ptr<DescriptorImpl> desc) : DescriptorImpl({}, std::move(desc), "wsh") {}
    1347                 :       49421 :     std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32; }
    1348                 :       35761 :     bool IsSingleType() const final { return true; }
    1349                 :             : 
    1350                 :       21971 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
    1351                 :             : 
    1352                 :       38030 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
    1353         [ +  - ]:       38030 :         if (const auto sat_size = m_subdescriptor_args[0]->MaxSatSize(use_max_sig)) {
    1354         [ +  - ]:       38030 :             if (const auto subscript_size = m_subdescriptor_args[0]->ScriptSize()) {
    1355         [ +  + ]:       47486 :                 return GetSizeOfCompactSize(*subscript_size) + *subscript_size + *sat_size;
    1356                 :             :             }
    1357                 :             :         }
    1358                 :           0 :         return {};
    1359                 :             :     }
    1360                 :             : 
    1361                 :       30986 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
    1362                 :       30986 :         return MaxSatSize(use_max_sig);
    1363                 :             :     }
    1364                 :             : 
    1365                 :       19015 :     std::optional<int64_t> MaxSatisfactionElems() const override {
    1366         [ +  - ]:       19015 :         if (const auto sub_elems = m_subdescriptor_args[0]->MaxSatisfactionElems()) return 1 + *sub_elems;
    1367                 :           0 :         return {};
    1368                 :             :     }
    1369                 :             : 
    1370                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1371                 :             :     {
    1372   [ #  #  #  # ]:           0 :         return std::make_unique<WSHDescriptor>(m_subdescriptor_args.at(0)->Clone());
    1373                 :             :     }
    1374                 :             : };
    1375                 :             : 
    1376                 :             : /** A parsed tr(...) descriptor. */
    1377                 :             : class TRDescriptor final : public DescriptorImpl
    1378                 :             : {
    1379                 :             :     std::vector<int> m_depths;
    1380                 :             : protected:
    1381                 :      191997 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript> scripts, FlatSigningProvider& out) const override
    1382                 :             :     {
    1383         [ -  + ]:      191997 :         TaprootBuilder builder;
    1384   [ -  +  -  + ]:      191997 :         assert(m_depths.size() == scripts.size());
    1385   [ -  +  +  + ]:      308078 :         for (size_t pos = 0; pos < m_depths.size(); ++pos) {
    1386   [ +  +  +  - ]:      232162 :             builder.Add(m_depths[pos], scripts[pos], TAPROOT_LEAF_TAPSCRIPT);
    1387                 :             :         }
    1388         [ -  + ]:      191997 :         if (!builder.IsComplete()) return {};
    1389   [ -  +  -  + ]:      191997 :         assert(keys.size() == 1);
    1390                 :      191997 :         XOnlyPubKey xpk(keys[0]);
    1391   [ +  -  -  + ]:      191997 :         if (!xpk.IsFullyValid()) return {};
    1392         [ +  - ]:      191997 :         builder.Finalize(xpk);
    1393         [ +  - ]:      191997 :         WitnessV1Taproot output = builder.GetOutput();
    1394   [ +  -  +  - ]:      191997 :         out.tr_trees[output] = builder;
    1395   [ +  -  +  - ]:      383994 :         return Vector(GetScriptForDestination(output));
    1396                 :      191997 :     }
    1397                 :      221726 :     bool ToStringSubScriptHelper(const SigningProvider* arg, std::string& ret, const StringType type, const DescriptorCache* cache = nullptr) const override
    1398                 :             :     {
    1399         [ +  + ]:      221726 :         if (m_depths.empty()) return true;
    1400                 :       63313 :         std::vector<bool> path;
    1401   [ -  +  +  + ]:      182482 :         for (size_t pos = 0; pos < m_depths.size(); ++pos) {
    1402   [ +  +  +  - ]:      128286 :             if (pos) ret += ',';
    1403         [ +  + ]:      261647 :             while ((int)path.size() <= m_depths[pos]) {
    1404   [ +  +  +  - ]:      133361 :                 if (path.size()) ret += '{';
    1405         [ +  - ]:      133361 :                 path.push_back(false);
    1406                 :             :             }
    1407         [ +  - ]:      128286 :             std::string tmp;
    1408   [ +  -  +  + ]:      128286 :             if (!m_subdescriptor_args[pos]->ToStringHelper(arg, tmp, type, cache)) return false;
    1409         [ -  + ]:      119169 :             ret += tmp;
    1410   [ +  -  +  + ]:      182381 :             while (!path.empty() && path.back()) {
    1411   [ +  -  +  - ]:       63212 :                 if (path.size() > 1) ret += '}';
    1412   [ -  +  +  - ]:      245593 :                 path.pop_back();
    1413                 :             :             }
    1414         [ +  - ]:      119169 :             if (!path.empty()) path.back() = true;
    1415                 :      128286 :         }
    1416                 :             :         return true;
    1417                 :       63313 :     }
    1418                 :             : public:
    1419                 :       65741 :     TRDescriptor(std::unique_ptr<PubkeyProvider> internal_key, std::vector<std::unique_ptr<DescriptorImpl>> descs, std::vector<int> depths) :
    1420   [ +  -  +  -  :       65741 :         DescriptorImpl(Vector(std::move(internal_key)), std::move(descs), "tr"), m_depths(std::move(depths))
                   -  + ]
    1421                 :             :     {
    1422   [ -  +  -  +  :       65741 :         assert(m_subdescriptor_args.size() == m_depths.size());
                   -  + ]
    1423                 :       65741 :     }
    1424                 :      134028 :     std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32M; }
    1425                 :      194372 :     bool IsSingleType() const final { return true; }
    1426                 :             : 
    1427                 :       27915 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
    1428                 :             : 
    1429                 :       60373 :     std::optional<int64_t> MaxSatisfactionWeight(bool) const override {
    1430                 :             :         // FIXME: We assume keypath spend, which can lead to very large underestimations.
    1431                 :       60373 :         return 1 + 65;
    1432                 :             :     }
    1433                 :             : 
    1434                 :       30440 :     std::optional<int64_t> MaxSatisfactionElems() const override {
    1435                 :             :         // FIXME: See above, we assume keypath spend.
    1436                 :       30440 :         return 1;
    1437                 :             :     }
    1438                 :             : 
    1439                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1440                 :             :     {
    1441                 :           0 :         std::vector<std::unique_ptr<DescriptorImpl>> subdescs;
    1442   [ #  #  #  # ]:           0 :         subdescs.reserve(m_subdescriptor_args.size());
    1443         [ #  # ]:           0 :         std::transform(m_subdescriptor_args.begin(), m_subdescriptor_args.end(), subdescs.begin(), [](const std::unique_ptr<DescriptorImpl>& d) { return d->Clone(); });
    1444   [ #  #  #  #  :           0 :         return std::make_unique<TRDescriptor>(m_pubkey_args.at(0)->Clone(), std::move(subdescs), m_depths);
             #  #  #  # ]
    1445                 :           0 :     }
    1446                 :             : };
    1447                 :             : 
    1448                 :             : /* We instantiate Miniscript here with a simple integer as key type.
    1449                 :             :  * The value of these key integers are an index in the
    1450                 :             :  * DescriptorImpl::m_pubkey_args vector.
    1451                 :             :  */
    1452                 :             : 
    1453                 :             : /**
    1454                 :             :  * The context for converting a Miniscript descriptor into a Script.
    1455                 :             :  */
    1456                 :             : class ScriptMaker {
    1457                 :             :     //! Keys contained in the Miniscript (the evaluation of DescriptorImpl::m_pubkey_args).
    1458                 :             :     const std::vector<CPubKey>& m_keys;
    1459                 :             :     //! The script context we're operating within (Tapscript or P2WSH).
    1460                 :             :     const miniscript::MiniscriptContext m_script_ctx;
    1461                 :             : 
    1462                 :             :     //! Get the ripemd160(sha256()) hash of this key.
    1463                 :             :     //! Any key that is valid in a descriptor serializes as 32 bytes within a Tapscript context. So we
    1464                 :             :     //! must not hash the sign-bit byte in this case.
    1465                 :       19826 :     uint160 GetHash160(uint32_t key) const {
    1466         [ +  + ]:       19826 :         if (miniscript::IsTapscript(m_script_ctx)) {
    1467                 :       14488 :             return Hash160(XOnlyPubKey{m_keys[key]});
    1468                 :             :         }
    1469                 :        5338 :         return m_keys[key].GetID();
    1470                 :             :     }
    1471                 :             : 
    1472                 :             : public:
    1473                 :      105801 :     ScriptMaker(const std::vector<CPubKey>& keys LIFETIMEBOUND, const miniscript::MiniscriptContext script_ctx) : m_keys(keys), m_script_ctx{script_ctx} {}
    1474                 :             : 
    1475                 :      175556 :     std::vector<unsigned char> ToPKBytes(uint32_t key) const {
    1476                 :             :         // In Tapscript keys always serialize as x-only, whether an x-only key was used in the descriptor or not.
    1477         [ +  + ]:      175556 :         if (!miniscript::IsTapscript(m_script_ctx)) {
    1478                 :       85561 :             return {m_keys[key].begin(), m_keys[key].end()};
    1479                 :             :         }
    1480                 :       89995 :         const XOnlyPubKey xonly_pubkey{m_keys[key]};
    1481                 :       89995 :         return {xonly_pubkey.begin(), xonly_pubkey.end()};
    1482                 :             :     }
    1483                 :             : 
    1484                 :       19826 :     std::vector<unsigned char> ToPKHBytes(uint32_t key) const {
    1485                 :       19826 :         auto id = GetHash160(key);
    1486                 :       19826 :         return {id.begin(), id.end()};
    1487                 :             :     }
    1488                 :             : };
    1489                 :             : 
    1490                 :             : /**
    1491                 :             :  * The context for converting a Miniscript descriptor to its textual form.
    1492                 :             :  */
    1493                 :             : class StringMaker {
    1494                 :             :     //! To convert private keys for private descriptors.
    1495                 :             :     const SigningProvider* m_arg;
    1496                 :             :     //! Keys contained in the Miniscript (a reference to DescriptorImpl::m_pubkey_args).
    1497                 :             :     const std::vector<std::unique_ptr<PubkeyProvider>>& m_pubkeys;
    1498                 :             :     //! StringType to serialize keys
    1499                 :             :     const DescriptorImpl::StringType m_type;
    1500                 :             :     const DescriptorCache* m_cache;
    1501                 :             : 
    1502                 :             : public:
    1503                 :      129075 :     StringMaker(const SigningProvider* arg LIFETIMEBOUND,
    1504                 :             :                 const std::vector<std::unique_ptr<PubkeyProvider>>& pubkeys LIFETIMEBOUND,
    1505                 :             :                 DescriptorImpl::StringType type,
    1506                 :             :                 const DescriptorCache* cache LIFETIMEBOUND)
    1507                 :      129075 :         : m_arg(arg), m_pubkeys(pubkeys), m_type(type), m_cache(cache) {}
    1508                 :             : 
    1509                 :      338718 :     std::optional<std::string> ToString(uint32_t key) const
    1510                 :             :     {
    1511   [ +  +  +  +  :      338718 :         std::string ret;
                      - ]
    1512   [ +  +  +  +  :      338718 :         switch (m_type) {
                      - ]
    1513                 :      163440 :         case DescriptorImpl::StringType::PUBLIC:
    1514         [ +  - ]:      163440 :             ret = m_pubkeys[key]->ToString();
    1515                 :      163440 :             break;
    1516                 :       45551 :         case DescriptorImpl::StringType::PRIVATE:
    1517   [ +  -  +  + ]:       45551 :             if (!m_pubkeys[key]->ToPrivateString(*m_arg, ret)) return {};
    1518                 :             :             break;
    1519                 :      125725 :         case DescriptorImpl::StringType::NORMALIZED:
    1520   [ +  -  +  + ]:      125725 :             if (!m_pubkeys[key]->ToNormalizedString(*m_arg, ret, m_cache)) return {};
    1521                 :             :             break;
    1522                 :        4002 :         case DescriptorImpl::StringType::COMPAT:
    1523         [ +  - ]:        4002 :             ret = m_pubkeys[key]->ToString(PubkeyProvider::StringType::COMPAT);
    1524                 :        4002 :             break;
    1525                 :             :         }
    1526                 :      323949 :         return ret;
    1527                 :      338718 :     }
    1528                 :             : };
    1529                 :             : 
    1530                 :             : class MiniscriptDescriptor final : public DescriptorImpl
    1531                 :             : {
    1532                 :             : private:
    1533                 :             :     miniscript::NodeRef<uint32_t> m_node;
    1534                 :             : 
    1535                 :             : protected:
    1536                 :      105801 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript> scripts,
    1537                 :             :                                      FlatSigningProvider& provider) const override
    1538                 :             :     {
    1539                 :      105801 :         const auto script_ctx{m_node->GetMsCtx()};
    1540         [ +  + ]:      301183 :         for (const auto& key : keys) {
    1541         [ +  + ]:      195382 :             if (miniscript::IsTapscript(script_ctx)) {
    1542                 :      104483 :                 provider.pubkeys.emplace(Hash160(XOnlyPubKey{key}), key);
    1543                 :             :             } else {
    1544                 :       90899 :                 provider.pubkeys.emplace(key.GetID(), key);
    1545                 :             :             }
    1546                 :             :         }
    1547         [ +  - ]:      211602 :         return Vector(m_node->ToScript(ScriptMaker(keys, script_ctx)));
    1548                 :             :     }
    1549                 :             : 
    1550                 :             : public:
    1551                 :      105717 :     MiniscriptDescriptor(std::vector<std::unique_ptr<PubkeyProvider>> providers, miniscript::NodeRef<uint32_t> node)
    1552   [ +  -  +  - ]:      105717 :         : DescriptorImpl(std::move(providers), "?"), m_node(std::move(node))
    1553                 :             :     {
    1554                 :             :         // Traverse miniscript tree for unsafe use of older()
    1555         [ +  - ]:      105717 :         miniscript::ForEachNode(*m_node, [&](const miniscript::Node<uint32_t>& node) {
    1556         [ +  + ]:     3710508 :             if (node.fragment == miniscript::Fragment::OLDER) {
    1557                 :        3651 :                 const uint32_t raw = node.k;
    1558                 :        3651 :                 const uint32_t value_part = raw & ~CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG;
    1559         [ +  + ]:        3651 :                 if (value_part > CTxIn::SEQUENCE_LOCKTIME_MASK) {
    1560                 :        1667 :                     const bool is_time_based = (raw & CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) != 0;
    1561         [ +  + ]:        1667 :                     if (is_time_based) {
    1562         [ +  - ]:        1018 :                         m_warnings.push_back(strprintf("time-based relative locktime: older(%u) > (65535 * 512) seconds is unsafe", raw));
    1563                 :             :                     } else {
    1564         [ +  - ]:         649 :                         m_warnings.push_back(strprintf("height-based relative locktime: older(%u) > 65535 blocks is unsafe", raw));
    1565                 :             :                     }
    1566                 :             :                 }
    1567                 :             :             }
    1568                 :     3710508 :         });
    1569                 :      105717 :     }
    1570                 :             : 
    1571                 :      129075 :     bool ToStringHelper(const SigningProvider* arg, std::string& out, const StringType type,
    1572                 :             :                         const DescriptorCache* cache = nullptr) const override
    1573                 :             :     {
    1574         [ +  + ]:      129075 :         if (const auto res = m_node->ToString(StringMaker(arg, m_pubkey_args, type, cache))) {
    1575         [ +  - ]:      114306 :             out = *res;
    1576                 :      114306 :             return true;
    1577                 :      114306 :         }
    1578                 :       14769 :         return false;
    1579                 :             :     }
    1580                 :             : 
    1581                 :       45345 :     bool IsSolvable() const override { return true; }
    1582                 :           0 :     bool IsSingleType() const final { return true; }
    1583                 :             : 
    1584                 :       29992 :     std::optional<int64_t> ScriptSize() const override { return m_node->ScriptSize(); }
    1585                 :             : 
    1586                 :       29992 :     std::optional<int64_t> MaxSatSize(bool) const override {
    1587                 :             :         // For Miniscript we always assume high-R ECDSA signatures.
    1588   [ -  +  +  - ]:       59984 :         return m_node->GetWitnessSize();
    1589                 :             :     }
    1590                 :             : 
    1591                 :       14996 :     std::optional<int64_t> MaxSatisfactionElems() const override {
    1592         [ +  - ]:       14996 :         return m_node->GetStackSize();
    1593                 :             :     }
    1594                 :             : 
    1595                 :       20769 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1596                 :             :     {
    1597                 :       20769 :         std::vector<std::unique_ptr<PubkeyProvider>> providers;
    1598   [ -  +  +  - ]:       20769 :         providers.reserve(m_pubkey_args.size());
    1599         [ +  + ]:       42474 :         for (const auto& arg : m_pubkey_args) {
    1600         [ +  - ]:       43410 :             providers.push_back(arg->Clone());
    1601                 :             :         }
    1602   [ +  -  +  -  :       41538 :         return std::make_unique<MiniscriptDescriptor>(std::move(providers), m_node->Clone());
                   -  + ]
    1603                 :       20769 :     }
    1604                 :             : };
    1605                 :             : 
    1606                 :             : /** A parsed rawtr(...) descriptor. */
    1607                 :             : class RawTRDescriptor final : public DescriptorImpl
    1608                 :             : {
    1609                 :             : protected:
    1610                 :        2273 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript> scripts, FlatSigningProvider& out) const override
    1611                 :             :     {
    1612   [ -  +  -  + ]:        2273 :         assert(keys.size() == 1);
    1613                 :        2273 :         XOnlyPubKey xpk(keys[0]);
    1614         [ -  + ]:        2273 :         if (!xpk.IsFullyValid()) return {};
    1615         [ +  - ]:        2273 :         WitnessV1Taproot output{xpk};
    1616   [ +  -  +  - ]:        4546 :         return Vector(GetScriptForDestination(output));
    1617                 :             :     }
    1618                 :             : public:
    1619   [ +  -  +  - ]:       11753 :     RawTRDescriptor(std::unique_ptr<PubkeyProvider> output_key) : DescriptorImpl(Vector(std::move(output_key)), "rawtr") {}
    1620                 :        2079 :     std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32M; }
    1621                 :        2385 :     bool IsSingleType() const final { return true; }
    1622                 :             : 
    1623                 :         735 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
    1624                 :             : 
    1625                 :        1516 :     std::optional<int64_t> MaxSatisfactionWeight(bool) const override {
    1626                 :             :         // We can't know whether there is a script path, so assume key path spend.
    1627                 :        1516 :         return 1 + 65;
    1628                 :             :     }
    1629                 :             : 
    1630                 :         758 :     std::optional<int64_t> MaxSatisfactionElems() const override {
    1631                 :             :         // See above, we assume keypath spend.
    1632                 :         758 :         return 1;
    1633                 :             :     }
    1634                 :             : 
    1635                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1636                 :             :     {
    1637   [ #  #  #  # ]:           0 :         return std::make_unique<RawTRDescriptor>(m_pubkey_args.at(0)->Clone());
    1638                 :             :     }
    1639                 :             : };
    1640                 :             : 
    1641                 :             : ////////////////////////////////////////////////////////////////////////////
    1642                 :             : // Parser                                                                 //
    1643                 :             : ////////////////////////////////////////////////////////////////////////////
    1644                 :             : 
    1645                 :             : enum class ParseScriptContext {
    1646                 :             :     TOP,     //!< Top-level context (script goes directly in scriptPubKey)
    1647                 :             :     P2SH,    //!< Inside sh() (script becomes P2SH redeemScript)
    1648                 :             :     P2WPKH,  //!< Inside wpkh() (no script, pubkey only)
    1649                 :             :     P2WSH,   //!< Inside wsh() (script becomes v0 witness script)
    1650                 :             :     P2TR,    //!< Inside tr() (either internal key, or BIP342 script leaf)
    1651                 :             :     MUSIG,   //!< Inside musig() (implies P2TR, cannot have nested musig())
    1652                 :             : };
    1653                 :             : 
    1654                 :      675130 : std::optional<uint32_t> ParseKeyPathNum(std::span<const char> elem, bool& apostrophe, std::string& error, bool& has_hardened)
    1655                 :             : {
    1656                 :      675130 :     bool hardened = false;
    1657         [ +  + ]:      675130 :     if (elem.size() > 0) {
    1658         [ +  + ]:      675114 :         const char last = elem[elem.size() - 1];
    1659         [ +  + ]:      675114 :         if (last == '\'' || last == 'h') {
    1660                 :      124252 :             elem = elem.first(elem.size() - 1);
    1661                 :      124252 :             hardened = true;
    1662                 :      124252 :             apostrophe = last == '\'';
    1663                 :             :         }
    1664                 :             :     }
    1665                 :      675130 :     const auto p{ToIntegral<uint32_t>(std::string_view{elem.begin(), elem.end()})};
    1666         [ +  + ]:      675130 :     if (!p) {
    1667                 :         219 :         error = strprintf("Key path value '%s' is not a valid uint32", std::string_view{elem.begin(), elem.end()});
    1668                 :         219 :         return std::nullopt;
    1669         [ +  + ]:      674911 :     } else if (*p > 0x7FFFFFFFUL) {
    1670                 :          22 :         error = strprintf("Key path value %u is out of range", *p);
    1671                 :          22 :         return std::nullopt;
    1672                 :             :     }
    1673   [ +  +  +  + ]:      674889 :     has_hardened = has_hardened || hardened;
    1674                 :             : 
    1675                 :      674889 :     return std::make_optional<uint32_t>(*p | (((uint32_t)hardened) << 31));
    1676                 :             : }
    1677                 :             : 
    1678                 :             : /**
    1679                 :             :  * Parse a key path, being passed a split list of elements (the first element is ignored because it is always the key).
    1680                 :             :  *
    1681                 :             :  * @param[in] split BIP32 path string, using either ' or h for hardened derivation
    1682                 :             :  * @param[out] out Vector of parsed key paths
    1683                 :             :  * @param[out] apostrophe only updated if hardened derivation is found
    1684                 :             :  * @param[out] error parsing error message
    1685                 :             :  * @param[in] allow_multipath Allows the parsed path to use the multipath specifier
    1686                 :             :  * @param[out] has_hardened Records whether the path contains any hardened derivation
    1687                 :             :  * @returns false if parsing failed
    1688                 :             :  **/
    1689                 :      614406 : [[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)
    1690                 :             : {
    1691                 :      614406 :     KeyPath path;
    1692                 :       13136 :     struct MultipathSubstitutes {
    1693                 :             :         size_t placeholder_index;
    1694                 :             :         std::vector<uint32_t> values;
    1695                 :             :     };
    1696                 :      614406 :     std::optional<MultipathSubstitutes> substitutes;
    1697                 :      614406 :     has_hardened = false;
    1698                 :             : 
    1699   [ -  +  +  + ]:     1179469 :     for (size_t i = 1; i < split.size(); ++i) {
    1700         [ +  + ]:      565440 :         const std::span<const char>& elem = split[i];
    1701                 :             : 
    1702                 :             :         // Check if element contains multipath specifier
    1703   [ +  +  +  +  :      565440 :         if (!elem.empty() && elem.front() == '<' && elem.back() == '>') {
                   +  + ]
    1704         [ +  + ]:       13250 :             if (!allow_multipath) {
    1705   [ +  -  +  - ]:         206 :                 error = strprintf("Key path value '%s' specifies multipath in a section where multipath is not allowed", std::string(elem.begin(), elem.end()));
    1706                 :         103 :                 return false;
    1707                 :             :             }
    1708         [ +  + ]:       13147 :             if (substitutes) {
    1709         [ +  - ]:      614406 :                 error = "Multiple multipath key path specifiers found";
    1710                 :             :                 return false;
    1711                 :             :             }
    1712                 :             : 
    1713                 :             :             // Parse each possible value
    1714         [ +  - ]:       13142 :             std::vector<std::span<const char>> nums = Split(std::span(elem.begin()+1, elem.end()-1), ";");
    1715   [ -  +  +  + ]:       13142 :             if (nums.size() < 2) {
    1716         [ +  - ]:          62 :                 error = "Multipath key path specifiers must have at least two items";
    1717                 :             :                 return false;
    1718                 :             :             }
    1719                 :             : 
    1720                 :       13136 :             substitutes.emplace();
    1721                 :       13136 :             std::unordered_set<uint32_t> seen_substitutes;
    1722         [ +  + ]:      136020 :             for (const auto& num : nums) {
    1723         [ +  - ]:      122940 :                 const auto& op_num = ParseKeyPathNum(num, apostrophe, error, has_hardened);
    1724         [ +  + ]:      122940 :                 if (!op_num) return false;
    1725   [ +  -  +  + ]:      122906 :                 auto [_, inserted] = seen_substitutes.insert(*op_num);
    1726         [ +  + ]:      122906 :                 if (!inserted) {
    1727         [ +  - ]:          22 :                     error = strprintf("Duplicated key path value %u in multipath specifier", *op_num);
    1728                 :          22 :                     return false;
    1729                 :             :                 }
    1730         [ +  - ]:      122884 :                 substitutes->values.emplace_back(*op_num);
    1731                 :             :             }
    1732                 :             : 
    1733         [ +  - ]:       13080 :             path.emplace_back(); // Placeholder for multipath segment
    1734         [ -  + ]:       13080 :             substitutes->placeholder_index = path.size() - 1;
    1735                 :       13198 :         } else {
    1736         [ +  - ]:      552190 :             const auto& op_num = ParseKeyPathNum(elem, apostrophe, error, has_hardened);
    1737         [ +  + ]:      552190 :             if (!op_num) return false;
    1738         [ +  - ]:      551983 :             path.emplace_back(*op_num);
    1739                 :             :         }
    1740                 :             :     }
    1741                 :             : 
    1742         [ +  + ]:      614029 :     if (!substitutes) {
    1743         [ +  - ]:      600956 :         out.emplace_back(std::move(path));
    1744                 :             :     } else {
    1745                 :             :         // Replace the multipath placeholder with each value while generating paths
    1746         [ +  + ]:      135575 :         for (uint32_t substitute : substitutes->values) {
    1747         [ +  - ]:      122502 :             KeyPath branch_path = path;
    1748         [ +  - ]:      122502 :             branch_path[substitutes->placeholder_index] = substitute;
    1749         [ +  - ]:      122502 :             out.emplace_back(std::move(branch_path));
    1750                 :      122502 :         }
    1751                 :             :     }
    1752                 :             :     return true;
    1753                 :      614406 : }
    1754                 :             : 
    1755                 :      613855 : [[nodiscard]] bool ParseKeyPath(const std::vector<std::span<const char>>& split, std::vector<KeyPath>& out, bool& apostrophe, std::string& error, bool allow_multipath)
    1756                 :             : {
    1757                 :      613855 :     bool dummy;
    1758                 :      613855 :     return ParseKeyPath(split, out, apostrophe, error, allow_multipath, /*has_hardened=*/dummy);
    1759                 :             : }
    1760                 :             : 
    1761                 :      374588 : static DeriveType ParseDeriveType(std::vector<std::span<const char>>& split, bool& apostrophe)
    1762                 :             : {
    1763                 :      374588 :     DeriveType type = DeriveType::NO;
    1764         [ +  + ]:      374588 :     if (std::ranges::equal(split.back(), std::span{"*"}.first(1))) {
    1765                 :       17546 :         split.pop_back();
    1766                 :       17546 :         type = DeriveType::UNHARDENED;
    1767   [ +  +  +  + ]:      357042 :     } else if (std::ranges::equal(split.back(), std::span{"*'"}.first(2)) || std::ranges::equal(split.back(), std::span{"*h"}.first(2))) {
    1768                 :       11813 :         apostrophe = std::ranges::equal(split.back(), std::span{"*'"}.first(2));
    1769                 :       11813 :         split.pop_back();
    1770                 :       11813 :         type = DeriveType::HARDENED;
    1771                 :             :     }
    1772                 :      374588 :     return type;
    1773                 :             : }
    1774                 :             : 
    1775                 :             : /** Parse a public key that excludes origin information. */
    1776                 :      598940 : 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)
    1777                 :             : {
    1778                 :      598940 :     std::vector<std::unique_ptr<PubkeyProvider>> ret;
    1779                 :      598940 :     bool permit_uncompressed = ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH;
    1780         [ +  - ]:      598940 :     auto split = Split(sp, '/');
    1781   [ +  -  -  + ]:     1197880 :     std::string str(split[0].begin(), split[0].end());
    1782   [ -  +  +  + ]:      598940 :     if (str.size() == 0) {
    1783         [ +  - ]:          89 :         error = "No key provided";
    1784                 :          89 :         return {};
    1785                 :             :     }
    1786   [ +  +  +  + ]:      598851 :     if (IsSpace(str.front()) || IsSpace(str.back())) {
    1787         [ +  - ]:          23 :         error = strprintf("Key '%s' is invalid due to whitespace", str);
    1788                 :          23 :         return {};
    1789                 :             :     }
    1790   [ -  +  +  + ]:      598828 :     if (split.size() == 1) {
    1791   [ +  -  +  + ]:      293492 :         if (IsHex(str)) {
    1792   [ -  +  +  - ]:      120290 :             std::vector<unsigned char> data = ParseHex(str);
    1793         [ -  + ]:      120290 :             CPubKey pubkey(data);
    1794   [ +  +  +  + ]:      120290 :             if (pubkey.IsValid() && !pubkey.IsValidNonHybrid()) {
    1795         [ +  - ]:          14 :                 error = "Hybrid public keys are not allowed";
    1796                 :          14 :                 return {};
    1797                 :             :             }
    1798   [ +  -  +  + ]:      120276 :             if (pubkey.IsFullyValid()) {
    1799   [ +  +  +  + ]:       73980 :                 if (permit_uncompressed || pubkey.IsCompressed()) {
    1800   [ +  -  +  - ]:       73973 :                     ret.emplace_back(std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, false));
    1801                 :       73973 :                     return ret;
    1802                 :             :                 } else {
    1803         [ +  - ]:           7 :                     error = "Uncompressed keys are not allowed";
    1804                 :           7 :                     return {};
    1805                 :             :                 }
    1806   [ -  +  +  +  :       46296 :             } else if (data.size() == 32 && ctx == ParseScriptContext::P2TR) {
                   +  + ]
    1807                 :       46122 :                 unsigned char fullkey[33] = {0x02};
    1808                 :       46122 :                 std::copy(data.begin(), data.end(), fullkey + 1);
    1809                 :       46122 :                 pubkey.Set(std::begin(fullkey), std::end(fullkey));
    1810   [ +  -  +  + ]:       46122 :                 if (pubkey.IsFullyValid()) {
    1811   [ +  -  +  - ]:       46100 :                     ret.emplace_back(std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, true));
    1812                 :       46100 :                     return ret;
    1813                 :             :                 }
    1814                 :             :             }
    1815         [ +  - ]:         196 :             error = strprintf("Pubkey '%s' is invalid", str);
    1816                 :         196 :             return {};
    1817                 :      120290 :         }
    1818         [ +  - ]:      173202 :         CKey key = DecodeSecret(str);
    1819         [ +  + ]:      173202 :         if (key.IsValid()) {
    1820   [ +  +  -  + ]:      103984 :             if (permit_uncompressed || key.IsCompressed()) {
    1821         [ +  - ]:      103984 :                 CPubKey pubkey = key.GetPubKey();
    1822   [ +  -  +  - ]:      103984 :                 out.keys.emplace(pubkey.GetID(), key);
    1823   [ +  -  +  - ]:      103984 :                 ret.emplace_back(std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, ctx == ParseScriptContext::P2TR));
    1824                 :      103984 :                 return ret;
    1825                 :             :             } else {
    1826         [ #  # ]:           0 :                 error = "Uncompressed keys are not allowed";
    1827                 :           0 :                 return {};
    1828                 :             :             }
    1829                 :             :         }
    1830                 :      173202 :     }
    1831         [ +  - ]:      374554 :     CExtKey extkey = DecodeExtKey(str);
    1832         [ +  - ]:      374554 :     CExtPubKey extpubkey = DecodeExtPubKey(str);
    1833   [ +  +  +  + ]:      374554 :     if (!extkey.key.IsValid() && !extpubkey.pubkey.IsValid()) {
    1834         [ +  - ]:         521 :         error = strprintf("key '%s' is not valid", str);
    1835                 :         521 :         return {};
    1836                 :             :     }
    1837                 :      374033 :     std::vector<KeyPath> paths;
    1838                 :      374033 :     DeriveType type = ParseDeriveType(split, apostrophe);
    1839   [ +  -  +  + ]:      374033 :     if (!ParseKeyPath(split, paths, apostrophe, error, /*allow_multipath=*/true)) return {};
    1840         [ +  + ]:      373875 :     if (extkey.key.IsValid()) {
    1841         [ +  - ]:      338483 :         extpubkey = extkey.Neuter();
    1842   [ +  -  +  - ]:      338483 :         out.keys.emplace(extpubkey.pubkey.GetID(), extkey.key);
    1843                 :             :     }
    1844         [ +  + ]:      856540 :     for (auto& path : paths) {
    1845   [ +  -  +  - ]:      965330 :         ret.emplace_back(std::make_unique<BIP32PubkeyProvider>(key_exp_index, extpubkey, std::move(path), type, apostrophe));
    1846                 :             :     }
    1847                 :      373875 :     return ret;
    1848                 :     1347527 : }
    1849                 :             : 
    1850                 :             : /** Parse a public key including origin information (if enabled). */
    1851                 :             : // NOLINTNEXTLINE(misc-no-recursion)
    1852                 :      615643 : 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)
    1853                 :             : {
    1854                 :      615643 :     std::vector<std::unique_ptr<PubkeyProvider>> ret;
    1855                 :             : 
    1856                 :      615643 :     using namespace script;
    1857                 :             : 
    1858                 :             :     // musig cannot be nested inside of an origin
    1859                 :      615643 :     std::span<const char> span = sp;
    1860   [ +  -  +  -  :      615643 :     if (Const("musig(", span, /*skip=*/false)) {
                   +  + ]
    1861         [ +  + ]:       16419 :         if (ctx != ParseScriptContext::P2TR) {
    1862         [ +  - ]:          10 :             error = "musig() is only allowed in tr() and rawtr()";
    1863                 :          10 :             return {};
    1864                 :             :         }
    1865                 :             : 
    1866                 :             :         // Split the span on the end parentheses. The end parentheses must
    1867                 :             :         // be included in the resulting span so that Expr is happy.
    1868         [ +  - ]:       16409 :         auto split = Split(sp, ')', /*include_sep=*/true);
    1869   [ -  +  +  + ]:       16409 :         if (split.size() > 2) {
    1870         [ +  - ]:         136 :             error = "Too many ')' in musig() expression";
    1871                 :         136 :             return {};
    1872                 :             :         }
    1873   [ +  -  +  -  :       16273 :         std::span<const char> expr(split.at(0).begin(), split.at(0).end());
                   +  - ]
    1874   [ +  -  +  -  :       16273 :         if (!Func("musig", expr)) {
                   +  + ]
    1875         [ +  - ]:          10 :             error = "Invalid musig() expression";
    1876                 :          10 :             return {};
    1877                 :             :         }
    1878                 :             : 
    1879                 :             :         // Parse the participant pubkeys
    1880                 :       16263 :         bool any_ranged = false;
    1881                 :       16263 :         bool all_bip32 = true;
    1882                 :       16263 :         std::vector<std::vector<std::unique_ptr<PubkeyProvider>>> providers;
    1883                 :       16263 :         bool any_key_parsed = false;
    1884                 :       16263 :         size_t max_multipath_len = 0;
    1885         [ +  + ]:      222633 :         while (expr.size()) {
    1886   [ +  +  +  -  :      396737 :             if (any_key_parsed && !Const(",", expr)) {
          +  -  +  +  +  
                +  -  - ]
    1887         [ +  - ]:          11 :                 error = strprintf("musig(): expected ',', got '%c'", expr[0]);
    1888                 :          11 :                 return {};
    1889                 :             :             }
    1890         [ +  - ]:      206486 :             auto arg = Expr(expr);
    1891         [ +  - ]:      206486 :             auto pk = ParsePubkey(key_exp_index, arg, ParseScriptContext::MUSIG, out, error);
    1892         [ +  + ]:      206486 :             if (pk.empty()) {
    1893         [ +  - ]:         116 :                 error = strprintf("musig(): %s", error);
    1894                 :         116 :                 return {};
    1895                 :             :             }
    1896                 :      206370 :             any_key_parsed = true;
    1897                 :             : 
    1898   [ +  +  +  -  :      391116 :             any_ranged = any_ranged || pk.at(0)->IsRange();
                   +  + ]
    1899   [ +  +  +  -  :      355729 :             all_bip32 = all_bip32 &&  pk.at(0)->IsBIP32();
                   +  + ]
    1900                 :             : 
    1901   [ -  +  +  + ]:      206370 :             max_multipath_len = std::max(max_multipath_len, pk.size());
    1902                 :             : 
    1903         [ +  - ]:      206370 :             providers.emplace_back(std::move(pk));
    1904                 :      206370 :             key_exp_index++;
    1905                 :      206486 :         }
    1906         [ +  + ]:       16136 :         if (!any_key_parsed) {
    1907         [ +  - ]:           6 :             error = "musig(): Must contain key expressions";
    1908                 :           6 :             return {};
    1909                 :             :         }
    1910                 :             : 
    1911                 :             :         // Parse any derivation
    1912                 :       16130 :         DeriveType deriv_type = DeriveType::NO;
    1913                 :       16130 :         std::vector<KeyPath> derivation_multipaths;
    1914   [ -  +  +  -  :       48390 :         if (split.size() == 2 && Const("/", split.at(1), /*skip=*/false)) {
          +  -  +  -  +  
                +  +  + ]
    1915         [ +  + ]:         572 :             if (!all_bip32) {
    1916         [ +  - ]:          12 :                 error = "musig(): derivation requires all participants to be xpubs or xprvs";
    1917                 :          12 :                 return {};
    1918                 :             :             }
    1919         [ +  + ]:         560 :             if (any_ranged) {
    1920         [ +  - ]:           5 :                 error = "musig(): Cannot have ranged participant keys if musig() also has derivation";
    1921                 :           5 :                 return {};
    1922                 :             :             }
    1923                 :         555 :             bool dummy = false;
    1924   [ +  -  +  - ]:         555 :             auto deriv_split = Split(split.at(1), '/');
    1925                 :         555 :             deriv_type = ParseDeriveType(deriv_split, dummy);
    1926         [ +  + ]:         555 :             if (deriv_type == DeriveType::HARDENED) {
    1927         [ +  - ]:           4 :                 error = "musig(): Cannot have hardened child derivation";
    1928                 :           4 :                 return {};
    1929                 :             :             }
    1930                 :         551 :             bool has_hardened = false;
    1931   [ +  -  +  + ]:         551 :             if (!ParseKeyPath(deriv_split, derivation_multipaths, dummy, error, /*allow_multipath=*/true, has_hardened)) {
    1932         [ +  - ]:           7 :                 error = "musig(): " + error;
    1933                 :           7 :                 return {};
    1934                 :             :             }
    1935         [ +  + ]:         544 :             if (has_hardened) {
    1936         [ +  - ]:           8 :                 error = "musig(): cannot have hardened derivation steps";
    1937                 :           8 :                 return {};
    1938                 :             :             }
    1939                 :         555 :         } else {
    1940         [ +  - ]:       15558 :             derivation_multipaths.emplace_back();
    1941                 :             :         }
    1942                 :             : 
    1943                 :             :         // Makes sure that all providers vectors in providers are the given length, or exactly length 1
    1944                 :             :         // Length 1 vectors have the single provider cloned until it matches the given length.
    1945                 :       17866 :         const auto& clone_providers = [&providers](size_t length) -> bool {
    1946         [ +  + ]:       56324 :             for (auto& multipath_providers : providers) {
    1947   [ -  +  +  + ]:       54558 :                 if (multipath_providers.size() == 1) {
    1948         [ +  + ]:      685115 :                     for (size_t i = 1; i < length; ++i) {
    1949         [ +  - ]:      632956 :                         multipath_providers.emplace_back(multipath_providers.at(0)->Clone());
    1950                 :             :                     }
    1951         [ +  + ]:        2399 :                 } else if (multipath_providers.size() != length) {
    1952                 :             :                     return false;
    1953                 :             :                 }
    1954                 :             :             }
    1955                 :             :             return true;
    1956                 :       16094 :         };
    1957                 :             : 
    1958                 :             :         // Emplace the final MuSigPubkeyProvider into ret with the pubkey providers from the specified provider vectors index
    1959                 :             :         // and the path from the specified path index
    1960                 :       44504 :         const auto& emplace_final_provider = [&ret, &key_exp_index, &deriv_type, &derivation_multipaths, &providers](size_t vec_idx, size_t path_idx) -> void {
    1961                 :       28410 :             KeyPath& path = derivation_multipaths.at(path_idx);
    1962                 :       28410 :             std::vector<std::unique_ptr<PubkeyProvider>> pubs;
    1963   [ -  +  +  - ]:       28410 :             pubs.reserve(providers.size());
    1964         [ +  + ]:      885246 :             for (auto& vec : providers) {
    1965   [ +  -  +  - ]:      856836 :                 pubs.emplace_back(std::move(vec.at(vec_idx)));
    1966                 :             :             }
    1967   [ +  -  +  - ]:       28410 :             ret.emplace_back(std::make_unique<MuSigPubkeyProvider>(key_exp_index, std::move(pubs), path, deriv_type));
    1968                 :       28410 :         };
    1969                 :             : 
    1970   [ +  +  +  + ]:       17698 :         if (max_multipath_len > 1 && derivation_multipaths.size() > 1) {
    1971         [ +  - ]:           4 :             error = "musig(): Cannot have multipath participant keys if musig() is also multipath";
    1972                 :           4 :             return {};
    1973         [ +  + ]:       16090 :         } else if (max_multipath_len > 1) {
    1974   [ +  -  +  + ]:        1600 :             if (!clone_providers(max_multipath_len)) {
    1975         [ +  - ]:           6 :                 error = strprintf("musig(): Multipath derivation paths have mismatched lengths");
    1976                 :           6 :                 return {};
    1977                 :             :             }
    1978         [ +  + ]:       14935 :             for (size_t i = 0; i < max_multipath_len; ++i) {
    1979                 :             :                 // Final MuSigPubkeyProvider uses participant pubkey providers at each multipath position, and the first (and only) path
    1980         [ +  - ]:       13341 :                 emplace_final_provider(i, 0);
    1981                 :             :             }
    1982   [ -  +  +  + ]:       14490 :         } else if (derivation_multipaths.size() > 1) {
    1983                 :             :             // All key provider vectors should be length 1. Clone them until they have the same length as paths
    1984   [ +  -  -  +  :         172 :             if (!Assume(clone_providers(derivation_multipaths.size()))) {
                   -  + ]
    1985         [ #  # ]:           0 :                 error = "musig(): Multipath derivation path with multipath participants is disallowed"; // This error is unreachable due to earlier check
    1986                 :           0 :                 return {};
    1987                 :             :             }
    1988   [ -  +  +  + ]:         923 :             for (size_t i = 0; i < derivation_multipaths.size(); ++i) {
    1989                 :             :                 // Final MuSigPubkeyProvider uses cloned participant pubkey providers, and the multipath derivation paths
    1990         [ +  - ]:         751 :                 emplace_final_provider(i, i);
    1991                 :             :             }
    1992                 :             :         } else {
    1993                 :             :             // No multipath derivation, MuSigPubkeyProvider uses the first (and only) participant pubkey providers, and the first (and only) path
    1994         [ +  - ]:       14318 :             emplace_final_provider(0, 0);
    1995                 :             :         }
    1996                 :       16084 :         return ret;
    1997                 :       32672 :     }
    1998                 :             : 
    1999         [ +  - ]:      599224 :     auto origin_split = Split(sp, ']');
    2000   [ -  +  +  + ]:      599224 :     if (origin_split.size() > 2) {
    2001         [ +  - ]:          11 :         error = "Multiple ']' characters found for a single pubkey";
    2002                 :          11 :         return {};
    2003                 :             :     }
    2004                 :             :     // This is set if either the origin or path suffix contains a hardened derivation.
    2005                 :      599213 :     bool apostrophe = false;
    2006         [ +  + ]:      599213 :     if (origin_split.size() == 1) {
    2007         [ +  - ]:      359330 :         return ParsePubkeyInner(key_exp_index, origin_split[0], ctx, out, apostrophe, error);
    2008                 :             :     }
    2009   [ +  +  +  + ]:      239883 :     if (origin_split[0].empty() || origin_split[0][0] != '[') {
    2010                 :          87 :         error = strprintf("Key origin start '[ character expected but not found, got '%c' instead",
    2011   [ +  +  +  - ]:          29 :                           origin_split[0].empty() ? /** empty, implies split char */ ']' : origin_split[0][0]);
    2012                 :          29 :         return {};
    2013                 :             :     }
    2014         [ +  - ]:      239854 :     auto slash_split = Split(origin_split[0].subspan(1), '/');
    2015         [ +  + ]:      239854 :     if (slash_split[0].size() != 8) {
    2016         [ +  - ]:          19 :         error = strprintf("Fingerprint is not 4 bytes (%u characters instead of 8 characters)", slash_split[0].size());
    2017                 :          19 :         return {};
    2018                 :             :     }
    2019   [ +  -  -  + ]:      479670 :     std::string fpr_hex = std::string(slash_split[0].begin(), slash_split[0].end());
    2020   [ -  +  +  -  :      239835 :     if (!IsHex(fpr_hex)) {
                   +  + ]
    2021         [ +  - ]:          13 :         error = strprintf("Fingerprint '%s' is not hex", fpr_hex);
    2022                 :          13 :         return {};
    2023                 :             :     }
    2024   [ -  +  +  - ]:      239822 :     auto fpr_bytes = ParseHex(fpr_hex);
    2025         [ -  + ]:      239822 :     KeyOriginInfo info;
    2026                 :      239822 :     static_assert(sizeof(info.fingerprint) == 4, "Fingerprint must be 4 bytes");
    2027   [ -  +  -  + ]:      239822 :     assert(fpr_bytes.size() == 4);
    2028                 :      239822 :     std::copy(fpr_bytes.begin(), fpr_bytes.end(), info.fingerprint);
    2029                 :      239822 :     std::vector<KeyPath> path;
    2030   [ +  -  +  + ]:      239822 :     if (!ParseKeyPath(slash_split, path, apostrophe, error, /*allow_multipath=*/false)) return {};
    2031   [ +  -  +  - ]:      239610 :     info.path = path.at(0);
    2032         [ +  - ]:      239610 :     auto providers = ParsePubkeyInner(key_exp_index, origin_split[1], ctx, out, apostrophe, error);
    2033         [ +  + ]:      239610 :     if (providers.empty()) return {};
    2034   [ -  +  +  - ]:      239499 :     ret.reserve(providers.size());
    2035         [ +  + ]:      495623 :     for (auto& prov : providers) {
    2036   [ +  -  +  - ]:      512248 :         ret.emplace_back(std::make_unique<OriginPubkeyProvider>(key_exp_index, info, std::move(prov), apostrophe));
    2037                 :             :     }
    2038                 :      239499 :     return ret;
    2039                 :     1335154 : }
    2040                 :             : 
    2041                 :      254059 : std::unique_ptr<PubkeyProvider> InferPubkey(const CPubKey& pubkey, ParseScriptContext ctx, const SigningProvider& provider)
    2042                 :             : {
    2043                 :             :     // Key cannot be hybrid
    2044         [ +  + ]:      254059 :     if (!pubkey.IsValidNonHybrid()) {
    2045                 :        5181 :         return nullptr;
    2046                 :             :     }
    2047                 :             :     // Uncompressed is only allowed in TOP and P2SH contexts
    2048   [ +  +  -  + ]:      248878 :     if (ctx != ParseScriptContext::TOP && ctx != ParseScriptContext::P2SH && !pubkey.IsCompressed()) {
    2049                 :           0 :         return nullptr;
    2050                 :             :     }
    2051                 :      248878 :     std::unique_ptr<PubkeyProvider> key_provider = std::make_unique<ConstPubkeyProvider>(0, pubkey, false);
    2052         [ +  - ]:      248878 :     KeyOriginInfo info;
    2053   [ +  -  +  -  :      248878 :     if (provider.GetKeyOrigin(pubkey.GetID(), info)) {
                   +  + ]
    2054   [ +  -  -  + ]:       90251 :         return std::make_unique<OriginPubkeyProvider>(0, std::move(info), std::move(key_provider), /*apostrophe=*/false);
    2055                 :             :     }
    2056                 :      158627 :     return key_provider;
    2057                 :      248878 : }
    2058                 :             : 
    2059                 :      960356 : std::unique_ptr<PubkeyProvider> InferXOnlyPubkey(const XOnlyPubKey& xkey, ParseScriptContext ctx, const SigningProvider& provider)
    2060                 :             : {
    2061                 :      960356 :     CPubKey pubkey{xkey.GetEvenCorrespondingCPubKey()};
    2062                 :      960356 :     std::unique_ptr<PubkeyProvider> key_provider = std::make_unique<ConstPubkeyProvider>(0, pubkey, true);
    2063         [ +  - ]:      960356 :     KeyOriginInfo info;
    2064   [ +  -  +  + ]:      960356 :     if (provider.GetKeyOriginByXOnly(xkey, info)) {
    2065   [ +  -  -  + ]:      950376 :         return std::make_unique<OriginPubkeyProvider>(0, std::move(info), std::move(key_provider), /*apostrophe=*/false);
    2066                 :             :     }
    2067                 :        9980 :     return key_provider;
    2068                 :      960356 : }
    2069                 :             : 
    2070                 :             : /**
    2071                 :             :  * The context for parsing a Miniscript descriptor (either from Script or from its textual representation).
    2072                 :             :  */
    2073                 :       70678 : struct KeyParser {
    2074                 :             :     //! The Key type is an index in DescriptorImpl::m_pubkey_args
    2075                 :             :     using Key = uint32_t;
    2076                 :             :     //! Must not be nullptr if parsing from string.
    2077                 :             :     FlatSigningProvider* m_out;
    2078                 :             :     //! Must not be nullptr if parsing from Script.
    2079                 :             :     const SigningProvider* m_in;
    2080                 :             :     //! List of multipath expanded keys contained in the Miniscript.
    2081                 :             :     mutable std::vector<std::vector<std::unique_ptr<PubkeyProvider>>> m_keys;
    2082                 :             :     //! Used to detect key parsing errors within a Miniscript.
    2083                 :             :     mutable std::string m_key_parsing_error;
    2084                 :             :     //! The script context we're operating within (Tapscript or P2WSH).
    2085                 :             :     const miniscript::MiniscriptContext m_script_ctx;
    2086                 :             :     //! The number of keys that were parsed before starting to parse this Miniscript descriptor.
    2087                 :             :     uint32_t m_offset;
    2088                 :             : 
    2089                 :       70678 :     KeyParser(FlatSigningProvider* out LIFETIMEBOUND, const SigningProvider* in LIFETIMEBOUND,
    2090                 :             :               miniscript::MiniscriptContext ctx, uint32_t offset = 0)
    2091                 :       70678 :         : m_out(out), m_in(in), m_script_ctx(ctx), m_offset(offset) {}
    2092                 :             : 
    2093                 :      432592 :     bool KeyCompare(const Key& a, const Key& b) const {
    2094                 :      432592 :         return *m_keys.at(a).at(0) < *m_keys.at(b).at(0);
    2095                 :             :     }
    2096                 :             : 
    2097                 :      178609 :     ParseScriptContext ParseContext() const {
    2098      [ +  -  + ]:      178609 :         switch (m_script_ctx) {
    2099                 :             :             case miniscript::MiniscriptContext::P2WSH: return ParseScriptContext::P2WSH;
    2100                 :      109715 :             case miniscript::MiniscriptContext::TAPSCRIPT: return ParseScriptContext::P2TR;
    2101                 :             :         }
    2102                 :           0 :         assert(false);
    2103                 :             :     }
    2104                 :             : 
    2105                 :       95163 :     template<typename I> std::optional<Key> FromString(I begin, I end) const
    2106                 :             :     {
    2107         [ -  + ]:       95163 :         assert(m_out);
    2108         [ -  + ]:       95163 :         Key key = m_keys.size();
    2109                 :       95163 :         uint32_t exp_index = m_offset + key;
    2110                 :       95163 :         auto pk = ParsePubkey(exp_index, {&*begin, &*end}, ParseContext(), *m_out, m_key_parsing_error);
    2111         [ +  + ]:       95163 :         if (pk.empty()) return {};
    2112         [ +  - ]:       94806 :         m_keys.emplace_back(std::move(pk));
    2113                 :       94806 :         return key;
    2114                 :       95163 :     }
    2115                 :             : 
    2116                 :       33088 :     std::optional<std::string> ToString(const Key& key) const
    2117                 :             :     {
    2118                 :       33088 :         return m_keys.at(key).at(0)->ToString();
    2119                 :             :     }
    2120                 :             : 
    2121                 :       77656 :     template<typename I> std::optional<Key> FromPKBytes(I begin, I end) const
    2122                 :             :     {
    2123         [ -  + ]:       77656 :         assert(m_in);
    2124         [ -  + ]:       77656 :         Key key = m_keys.size();
    2125   [ +  +  +  - ]:       77656 :         if (miniscript::IsTapscript(m_script_ctx) && end - begin == 32) {
    2126                 :       40281 :             XOnlyPubKey pubkey;
    2127                 :       40281 :             std::copy(begin, end, pubkey.begin());
    2128         [ +  - ]:       40281 :             if (auto pubkey_provider = InferXOnlyPubkey(pubkey, ParseContext(), *m_in)) {
    2129         [ +  - ]:       40281 :                 m_keys.emplace_back();
    2130         [ +  - ]:       40281 :                 m_keys.back().push_back(std::move(pubkey_provider));
    2131                 :       40281 :                 return key;
    2132                 :             :             }
    2133         [ +  - ]:       37375 :         } else if (!miniscript::IsTapscript(m_script_ctx)) {
    2134                 :       37375 :             CPubKey pubkey(begin, end);
    2135         [ +  + ]:       37375 :             if (auto pubkey_provider = InferPubkey(pubkey, ParseContext(), *m_in)) {
    2136         [ +  - ]:       37362 :                 m_keys.emplace_back();
    2137         [ +  - ]:       37362 :                 m_keys.back().push_back(std::move(pubkey_provider));
    2138                 :       37362 :                 return key;
    2139                 :             :             }
    2140                 :             :         }
    2141                 :          13 :         return {};
    2142                 :             :     }
    2143                 :             : 
    2144         [ -  + ]:        5791 :     template<typename I> std::optional<Key> FromPKHBytes(I begin, I end) const
    2145                 :             :     {
    2146         [ -  + ]:        5791 :         assert(end - begin == 20);
    2147         [ -  + ]:        5791 :         assert(m_in);
    2148                 :        5791 :         uint160 hash;
    2149                 :        5791 :         std::copy(begin, end, hash.begin());
    2150                 :        5791 :         CKeyID keyid(hash);
    2151                 :        5791 :         CPubKey pubkey;
    2152         [ +  + ]:        5791 :         if (m_in->GetPubKey(keyid, pubkey)) {
    2153         [ +  - ]:        5790 :             if (auto pubkey_provider = InferPubkey(pubkey, ParseContext(), *m_in)) {
    2154         [ -  + ]:        5790 :                 Key key = m_keys.size();
    2155         [ +  - ]:        5790 :                 m_keys.emplace_back();
    2156         [ +  - ]:        5790 :                 m_keys.back().push_back(std::move(pubkey_provider));
    2157                 :        5790 :                 return key;
    2158                 :             :             }
    2159                 :             :         }
    2160                 :           1 :         return {};
    2161                 :             :     }
    2162                 :             : 
    2163                 :    13226939 :     miniscript::MiniscriptContext MsContext() const {
    2164   [ +  -  +  -  :    13226939 :         return m_script_ctx;
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  +  +  
                -  +  - ]
    2165                 :             :     }
    2166                 :             : };
    2167                 :             : 
    2168                 :             : /** Parse a script in a particular context. */
    2169                 :             : // NOLINTNEXTLINE(misc-no-recursion)
    2170                 :       80625 : std::vector<std::unique_ptr<DescriptorImpl>> ParseScript(uint32_t& key_exp_index, std::span<const char>& sp, ParseScriptContext ctx, FlatSigningProvider& out, std::string& error)
    2171                 :             : {
    2172                 :       80625 :     using namespace script;
    2173   [ +  +  -  +  :       80625 :     Assume(ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH || ctx == ParseScriptContext::P2TR);
                   -  + ]
    2174                 :       80625 :     std::vector<std::unique_ptr<DescriptorImpl>> ret;
    2175         [ +  - ]:       80625 :     auto expr = Expr(sp);
    2176   [ +  -  +  -  :       80625 :     if (Func("pk", expr)) {
                   +  + ]
    2177         [ +  - ]:       11086 :         auto pubkeys = ParsePubkey(key_exp_index, expr, ctx, out, error);
    2178         [ +  + ]:       11086 :         if (pubkeys.empty()) {
    2179         [ +  - ]:         325 :             error = strprintf("pk(): %s", error);
    2180                 :         325 :             return {};
    2181                 :             :         }
    2182                 :       10761 :         ++key_exp_index;
    2183         [ +  + ]:       24056 :         for (auto& pubkey : pubkeys) {
    2184   [ +  -  +  - ]:       26590 :             ret.emplace_back(std::make_unique<PKDescriptor>(std::move(pubkey), ctx == ParseScriptContext::P2TR));
    2185                 :             :         }
    2186                 :       10761 :         return ret;
    2187                 :       11086 :     }
    2188   [ +  +  +  -  :      119800 :     if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH) && Func("pkh", expr)) {
          +  -  +  +  +  
                      + ]
    2189         [ +  - ]:        4751 :         auto pubkeys = ParsePubkey(key_exp_index, expr, ctx, out, error);
    2190         [ +  + ]:        4751 :         if (pubkeys.empty()) {
    2191         [ +  - ]:          23 :             error = strprintf("pkh(): %s", error);
    2192                 :          23 :             return {};
    2193                 :             :         }
    2194                 :        4728 :         ++key_exp_index;
    2195         [ +  + ]:       11256 :         for (auto& pubkey : pubkeys) {
    2196   [ +  -  +  - ]:       13056 :             ret.emplace_back(std::make_unique<PKHDescriptor>(std::move(pubkey)));
    2197                 :             :         }
    2198                 :        4728 :         return ret;
    2199                 :        4751 :     }
    2200   [ +  +  +  -  :      100406 :     if (ctx == ParseScriptContext::TOP && Func("combo", expr)) {
          +  -  +  +  +  
                      + ]
    2201         [ +  - ]:         672 :         auto pubkeys = ParsePubkey(key_exp_index, expr, ctx, out, error);
    2202         [ +  + ]:         672 :         if (pubkeys.empty()) {
    2203         [ +  - ]:          26 :             error = strprintf("combo(): %s", error);
    2204                 :          26 :             return {};
    2205                 :             :         }
    2206                 :         646 :         ++key_exp_index;
    2207         [ +  + ]:        2903 :         for (auto& pubkey : pubkeys) {
    2208   [ +  -  +  - ]:        4514 :             ret.emplace_back(std::make_unique<ComboDescriptor>(std::move(pubkey)));
    2209                 :             :         }
    2210                 :         646 :         return ret;
    2211   [ +  -  +  -  :       64788 :     } else if (Func("combo", expr)) {
                   +  + ]
    2212         [ +  - ]:           6 :         error = "Can only have combo() at top level";
    2213                 :           6 :         return {};
    2214                 :             :     }
    2215   [ +  -  +  - ]:       64110 :     const bool multi = Func("multi", expr);
    2216   [ +  +  +  -  :      127043 :     const bool sortedmulti = !multi && Func("sortedmulti", expr);
             +  -  +  + ]
    2217   [ +  +  +  -  :      126354 :     const bool multi_a = !(multi || sortedmulti) && Func("multi_a", expr);
             +  -  +  + ]
    2218   [ +  +  +  +  :      124369 :     const bool sortedmulti_a = !(multi || sortedmulti || multi_a) && Func("sortedmulti_a", expr);
          +  -  +  -  +  
                      + ]
    2219   [ +  +  +  +  :       64110 :     if (((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH) && (multi || sortedmulti)) ||
             +  +  +  + ]
    2220   [ +  +  +  + ]:       19278 :         (ctx == ParseScriptContext::P2TR && (multi_a || sortedmulti_a))) {
    2221         [ +  - ]:        5542 :         auto threshold = Expr(expr);
    2222                 :        5542 :         uint32_t thres;
    2223                 :        5542 :         std::vector<std::vector<std::unique_ptr<PubkeyProvider>>> providers; // List of multipath expanded pubkeys
    2224         [ +  + ]:        5542 :         if (const auto maybe_thres{ToIntegral<uint32_t>(std::string_view{threshold.begin(), threshold.end()})}) {
    2225                 :        5363 :             thres = *maybe_thres;
    2226                 :             :         } else {
    2227   [ +  -  +  - ]:         358 :             error = strprintf("Multi threshold '%s' is not valid", std::string(threshold.begin(), threshold.end()));
    2228                 :         179 :             return {};
    2229                 :             :         }
    2230                 :        5363 :         size_t script_size = 0;
    2231                 :        5363 :         size_t max_providers_len = 0;
    2232         [ +  + ]:      285427 :         while (expr.size()) {
    2233   [ +  -  +  -  :      280413 :             if (!Const(",", expr)) {
                   +  + ]
    2234         [ +  - ]:          10 :                 error = strprintf("Multi: expected ',', got '%c'", expr[0]);
    2235                 :          10 :                 return {};
    2236                 :             :             }
    2237         [ +  - ]:      280403 :             auto arg = Expr(expr);
    2238         [ +  - ]:      280403 :             auto pks = ParsePubkey(key_exp_index, arg, ctx, out, error);
    2239         [ +  + ]:      280403 :             if (pks.empty()) {
    2240         [ +  - ]:         339 :                 error = strprintf("Multi: %s", error);
    2241                 :         339 :                 return {};
    2242                 :             :             }
    2243   [ +  -  +  - ]:      280064 :             script_size += pks.at(0)->GetSize() + 1;
    2244   [ -  +  +  + ]:      280064 :             max_providers_len = std::max(max_providers_len, pks.size());
    2245         [ +  - ]:      280064 :             providers.emplace_back(std::move(pks));
    2246                 :      280064 :             key_exp_index++;
    2247                 :      280403 :         }
    2248   [ +  +  +  +  :        6448 :         if ((multi || sortedmulti) && (providers.empty() || providers.size() > MAX_PUBKEYS_PER_MULTISIG)) {
             +  +  +  + ]
    2249   [ -  +  +  - ]:          42 :             error = strprintf("Cannot have %u keys in multisig; must have between 1 and %d keys, inclusive", providers.size(), MAX_PUBKEYS_PER_MULTISIG);
    2250                 :          42 :             return {};
    2251   [ +  +  +  +  :        8517 :         } else if ((multi_a || sortedmulti_a) && (providers.empty() || providers.size() > MAX_PUBKEYS_PER_MULTI_A)) {
             +  +  +  + ]
    2252   [ -  +  +  - ]:          21 :             error = strprintf("Cannot have %u keys in multi_a; must have between 1 and %d keys, inclusive", providers.size(), MAX_PUBKEYS_PER_MULTI_A);
    2253                 :          21 :             return {};
    2254         [ +  + ]:        4951 :         } else if (thres < 1) {
    2255         [ +  - ]:          12 :             error = strprintf("Multisig threshold cannot be %d, must be at least 1", thres);
    2256                 :          12 :             return {};
    2257   [ -  +  +  + ]:        4939 :         } else if (thres > providers.size()) {
    2258         [ +  - ]:          19 :             error = strprintf("Multisig threshold cannot be larger than the number of keys; threshold is %d but only %u keys specified", thres, providers.size());
    2259                 :          19 :             return {};
    2260                 :             :         }
    2261         [ +  + ]:        4920 :         if (ctx == ParseScriptContext::TOP) {
    2262         [ +  + ]:         465 :             if (providers.size() > 3) {
    2263         [ +  - ]:          21 :                 error = strprintf("Cannot have %u pubkeys in bare multisig; only at most 3 pubkeys", providers.size());
    2264                 :          21 :                 return {};
    2265                 :             :             }
    2266                 :             :         }
    2267         [ +  + ]:        4899 :         if (ctx == ParseScriptContext::P2SH) {
    2268                 :             :             // This limits the maximum number of compressed pubkeys to 15.
    2269         [ +  + ]:         545 :             if (script_size + 3 > MAX_SCRIPT_ELEMENT_SIZE) {
    2270         [ +  - ]:          10 :                 error = strprintf("P2SH script is too large, %d bytes is larger than %d bytes", script_size + 3, MAX_SCRIPT_ELEMENT_SIZE);
    2271                 :          10 :                 return {};
    2272                 :             :             }
    2273                 :             :         }
    2274                 :             : 
    2275                 :             :         // Make sure all vecs are of the same length, or exactly length 1
    2276                 :             :         // For length 1 vectors, clone key providers until vector is the same length
    2277         [ +  + ]:      251434 :         for (auto& vec : providers) {
    2278   [ -  +  +  + ]:      246563 :             if (vec.size() == 1) {
    2279         [ +  + ]:     1196579 :                 for (size_t i = 1; i < max_providers_len; ++i) {
    2280   [ +  -  +  -  :      952130 :                     vec.emplace_back(vec.at(0)->Clone());
                   +  - ]
    2281                 :             :                 }
    2282         [ +  + ]:        2114 :             } else if (vec.size() != max_providers_len) {
    2283         [ +  - ]:          18 :                 error = strprintf("multi(): Multipath derivation paths have mismatched lengths");
    2284                 :          18 :                 return {};
    2285                 :             :             }
    2286                 :             :         }
    2287                 :             : 
    2288                 :             :         // Build the final descriptors vector
    2289         [ +  + ]:       22593 :         for (size_t i = 0; i < max_providers_len; ++i) {
    2290                 :             :             // Build final pubkeys vectors by retrieving the i'th subscript for each vector in subscripts
    2291                 :       17722 :             std::vector<std::unique_ptr<PubkeyProvider>> pubs;
    2292   [ -  +  +  - ]:       17722 :             pubs.reserve(providers.size());
    2293         [ +  + ]:     1231658 :             for (auto& pub : providers) {
    2294   [ +  -  +  - ]:     1213936 :                 pubs.emplace_back(std::move(pub.at(i)));
    2295                 :             :             }
    2296   [ +  +  +  + ]:       17722 :             if (multi || sortedmulti) {
    2297   [ +  -  +  - ]:       13372 :                 ret.emplace_back(std::make_unique<MultisigDescriptor>(thres, std::move(pubs), sortedmulti));
    2298                 :             :             } else {
    2299   [ +  -  +  - ]:       22072 :                 ret.emplace_back(std::make_unique<MultiADescriptor>(thres, std::move(pubs), sortedmulti_a));
    2300                 :             :             }
    2301                 :       17722 :         }
    2302                 :        4871 :         return ret;
    2303   [ +  +  +  + ]:       64110 :     } else if (multi || sortedmulti) {
    2304         [ +  - ]:          13 :         error = "Can only have multi/sortedmulti at top level, in sh(), or in wsh()";
    2305                 :          13 :         return {};
    2306   [ +  +  +  + ]:       58555 :     } else if (multi_a || sortedmulti_a) {
    2307         [ +  - ]:          11 :         error = "Can only have multi_a/sortedmulti_a inside tr()";
    2308                 :          11 :         return {};
    2309                 :             :     }
    2310   [ +  +  +  -  :       96166 :     if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH) && Func("wpkh", expr)) {
          +  -  +  +  +  
                      + ]
    2311         [ +  - ]:        6068 :         auto pubkeys = ParsePubkey(key_exp_index, expr, ParseScriptContext::P2WPKH, out, error);
    2312         [ +  + ]:        6068 :         if (pubkeys.empty()) {
    2313         [ +  - ]:          18 :             error = strprintf("wpkh(): %s", error);
    2314                 :          18 :             return {};
    2315                 :             :         }
    2316                 :        6050 :         key_exp_index++;
    2317         [ +  + ]:       13113 :         for (auto& pubkey : pubkeys) {
    2318   [ +  -  +  - ]:       14126 :             ret.emplace_back(std::make_unique<WPKHDescriptor>(std::move(pubkey)));
    2319                 :             :         }
    2320                 :        6050 :         return ret;
    2321   [ +  -  +  -  :       58544 :     } else if (Func("wpkh", expr)) {
                   +  + ]
    2322         [ +  - ]:           5 :         error = "Can only have wpkh() at top level or inside sh()";
    2323                 :           5 :         return {};
    2324                 :             :     }
    2325   [ +  +  +  -  :       83506 :     if (ctx == ParseScriptContext::TOP && Func("sh", expr)) {
          +  -  +  +  +  
                      + ]
    2326         [ +  - ]:        4300 :         auto descs = ParseScript(key_exp_index, expr, ParseScriptContext::P2SH, out, error);
    2327   [ +  +  +  + ]:        4300 :         if (descs.empty() || expr.size()) return {};
    2328                 :        4014 :         std::vector<std::unique_ptr<DescriptorImpl>> ret;
    2329   [ -  +  +  - ]:        4014 :         ret.reserve(descs.size());
    2330         [ +  + ]:       14314 :         for (auto& desc : descs) {
    2331   [ +  -  +  -  :       10300 :             ret.push_back(std::make_unique<SHDescriptor>(std::move(desc)));
                   -  + ]
    2332                 :             :         }
    2333                 :        4014 :         return ret;
    2334   [ +  -  +  -  :       52471 :     } else if (Func("sh", expr)) {
                   +  + ]
    2335         [ +  - ]:           6 :         error = "Can only have sh() at top level";
    2336                 :           6 :         return {};
    2337                 :             :     }
    2338   [ +  +  +  -  :       75413 :     if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH) && Func("wsh", expr)) {
          +  -  +  +  +  
                      + ]
    2339         [ +  - ]:        5876 :         auto descs = ParseScript(key_exp_index, expr, ParseScriptContext::P2WSH, out, error);
    2340   [ +  +  +  + ]:        5876 :         if (descs.empty() || expr.size()) return {};
    2341         [ +  + ]:       23026 :         for (auto& desc : descs) {
    2342   [ +  -  +  - ]:       40618 :             ret.emplace_back(std::make_unique<WSHDescriptor>(std::move(desc)));
    2343                 :             :         }
    2344                 :        2717 :         return ret;
    2345   [ +  -  +  -  :       48165 :     } else if (Func("wsh", expr)) {
                   +  + ]
    2346         [ +  - ]:           6 :         error = "Can only have wsh() at top level or inside sh()";
    2347                 :           6 :         return {};
    2348                 :             :     }
    2349   [ +  +  +  -  :       63578 :     if (ctx == ParseScriptContext::TOP && Func("addr", expr)) {
          +  -  +  +  +  
                      + ]
    2350   [ +  -  +  - ]:        1956 :         CTxDestination dest = DecodeDestination(std::string(expr.begin(), expr.end()));
    2351   [ +  -  +  + ]:         978 :         if (!IsValidDestination(dest)) {
    2352         [ +  - ]:         928 :             error = "Address is not valid";
    2353                 :         928 :             return {};
    2354                 :             :         }
    2355   [ +  -  +  - ]:          50 :         ret.emplace_back(std::make_unique<AddressDescriptor>(std::move(dest)));
    2356                 :          50 :         return ret;
    2357   [ +  -  +  -  :       42283 :     } else if (Func("addr", expr)) {
                   +  + ]
    2358         [ +  - ]:           7 :         error = "Can only have addr() at top level";
    2359                 :           7 :         return {};
    2360                 :             :     }
    2361   [ +  +  +  -  :       61615 :     if (ctx == ParseScriptContext::TOP && Func("tr", expr)) {
          +  -  +  +  +  
                      + ]
    2362         [ +  - ]:       10781 :         auto arg = Expr(expr);
    2363         [ +  - ]:       10781 :         auto internal_keys = ParsePubkey(key_exp_index, arg, ParseScriptContext::P2TR, out, error);
    2364         [ +  + ]:       10781 :         if (internal_keys.empty()) {
    2365         [ +  - ]:         387 :             error = strprintf("tr(): %s", error);
    2366                 :         387 :             return {};
    2367                 :             :         }
    2368         [ -  + ]:       10394 :         size_t max_providers_len = internal_keys.size();
    2369                 :       10394 :         ++key_exp_index;
    2370                 :       10394 :         std::vector<std::vector<std::unique_ptr<DescriptorImpl>>> subscripts; //!< list of multipath expanded script subexpressions
    2371                 :       10394 :         std::vector<int> depths; //!< depth in the tree of each subexpression (same length subscripts)
    2372         [ +  + ]:       10394 :         if (expr.size()) {
    2373   [ +  -  +  -  :        5487 :             if (!Const(",", expr)) {
                   +  + ]
    2374         [ +  - ]:          13 :                 error = strprintf("tr: expected ',', got '%c'", expr[0]);
    2375                 :          13 :                 return {};
    2376                 :             :             }
    2377                 :             :             /** The path from the top of the tree to what we're currently processing.
    2378                 :             :              * branches[i] == false: left branch in the i'th step from the top; true: right branch.
    2379                 :             :              */
    2380                 :        5474 :             std::vector<bool> branches;
    2381                 :             :             // Loop over all provided scripts. In every iteration exactly one script will be processed.
    2382                 :             :             // Use a do-loop because inside this if-branch we expect at least one script.
    2383                 :             :             do {
    2384                 :             :                 // First process all open braces.
    2385   [ +  -  +  -  :       56091 :                 while (Const("{", expr)) {
                   +  + ]
    2386         [ +  - ]:       30463 :                     branches.push_back(false); // new left branch
    2387         [ +  + ]:       30463 :                     if (branches.size() > TAPROOT_CONTROL_MAX_NODE_COUNT) {
    2388         [ +  - ]:          31 :                         error = strprintf("tr() supports at most %i nesting levels", TAPROOT_CONTROL_MAX_NODE_COUNT);
    2389                 :          31 :                         return {};
    2390                 :             :                     }
    2391                 :             :                 }
    2392                 :             :                 // Process the actual script expression.
    2393         [ +  - ]:       25628 :                 auto sarg = Expr(expr);
    2394   [ +  -  +  - ]:       25628 :                 subscripts.emplace_back(ParseScript(key_exp_index, sarg, ParseScriptContext::P2TR, out, error));
    2395         [ +  + ]:       25628 :                 if (subscripts.back().empty()) return {};
    2396   [ -  +  +  + ]:       24461 :                 max_providers_len = std::max(max_providers_len, subscripts.back().size());
    2397         [ +  - ]:       24461 :                 depths.push_back(branches.size());
    2398                 :             :                 // Process closing braces; one is expected for every right branch we were in.
    2399         [ +  + ]:       28263 :                 while (branches.size() && branches.back()) {
    2400   [ +  -  +  +  :        8034 :                     if (!Const("}", expr)) {
                   +  - ]
    2401         [ +  - ]:          47 :                         error = strprintf("tr(): expected '}' after script expression");
    2402                 :          47 :                         return {};
    2403                 :             :                     }
    2404   [ -  +  +  + ]:       40435 :                     branches.pop_back(); // move up one level after encountering '}'
    2405                 :             :                 }
    2406                 :             :                 // If after that, we're at the end of a left branch, expect a comma.
    2407   [ +  +  +  - ]:       24414 :                 if (branches.size() && !branches.back()) {
    2408   [ +  -  +  -  :       20229 :                     if (!Const(",", expr)) {
                   +  + ]
    2409         [ +  - ]:          44 :                         error = strprintf("tr(): expected ',' after script expression");
    2410                 :          44 :                         return {};
    2411                 :             :                     }
    2412                 :       20185 :                     branches.back() = true; // And now we're in a right branch.
    2413                 :             :                 }
    2414         [ +  + ]:       24370 :             } while (branches.size());
    2415                 :             :             // After we've explored a whole tree, we must be at the end of the expression.
    2416         [ +  + ]:        4185 :             if (expr.size()) {
    2417         [ +  - ]:          28 :                 error = strprintf("tr(): expected ')' after script expression");
    2418                 :          28 :                 return {};
    2419                 :             :             }
    2420                 :        5474 :         }
    2421   [ +  -  -  + ]:        9064 :         assert(TaprootBuilder::ValidDepths(depths));
    2422                 :             : 
    2423                 :             :         // Make sure all vecs are of the same length, or exactly length 1
    2424                 :             :         // For length 1 vectors, clone subdescs until vector is the same length
    2425         [ +  + ]:       19932 :         for (auto& vec : subscripts) {
    2426   [ -  +  +  + ]:       10878 :             if (vec.size() == 1) {
    2427         [ +  + ]:       35042 :                 for (size_t i = 1; i < max_providers_len; ++i) {
    2428   [ +  -  +  -  :       25131 :                     vec.emplace_back(vec.at(0)->Clone());
                   +  - ]
    2429                 :             :                 }
    2430         [ +  + ]:         967 :             } else if (vec.size() != max_providers_len) {
    2431         [ +  - ]:          10 :                 error = strprintf("tr(): Multipath subscripts have mismatched lengths");
    2432                 :          10 :                 return {};
    2433                 :             :             }
    2434                 :             :         }
    2435                 :             : 
    2436   [ -  +  +  +  :        9054 :         if (internal_keys.size() > 1 && internal_keys.size() != max_providers_len) {
                   +  + ]
    2437         [ +  - ]:           5 :             error = strprintf("tr(): Multipath internal key mismatches multipath subscripts lengths");
    2438                 :           5 :             return {};
    2439                 :             :         }
    2440                 :             : 
    2441   [ -  +  +  + ]:       23836 :         while (internal_keys.size() < max_providers_len) {
    2442   [ +  -  +  -  :       14787 :             internal_keys.emplace_back(internal_keys.at(0)->Clone());
                   +  - ]
    2443                 :             :         }
    2444                 :             : 
    2445                 :             :         // Build the final descriptors vector
    2446         [ +  + ]:       46185 :         for (size_t i = 0; i < max_providers_len; ++i) {
    2447                 :             :             // Build final subscripts vectors by retrieving the i'th subscript for each vector in subscripts
    2448                 :       37136 :             std::vector<std::unique_ptr<DescriptorImpl>> this_subs;
    2449   [ -  +  +  - ]:       37136 :             this_subs.reserve(subscripts.size());
    2450         [ +  + ]:       87658 :             for (auto& subs : subscripts) {
    2451   [ +  -  +  - ]:       50522 :                 this_subs.emplace_back(std::move(subs.at(i)));
    2452                 :             :             }
    2453   [ +  -  +  -  :       37136 :             ret.emplace_back(std::make_unique<TRDescriptor>(std::move(internal_keys.at(i)), std::move(this_subs), depths));
                   +  - ]
    2454                 :       37136 :         }
    2455                 :        9049 :         return ret;
    2456                 :             : 
    2457                 :             : 
    2458   [ +  -  +  -  :       41298 :     } else if (Func("tr", expr)) {
                   +  + ]
    2459         [ +  - ]:           8 :         error = "Can only have tr at top level";
    2460                 :           8 :         return {};
    2461                 :             :     }
    2462   [ +  +  +  -  :       40045 :     if (ctx == ParseScriptContext::TOP && Func("rawtr", expr)) {
          +  -  +  +  +  
                      + ]
    2463         [ +  - ]:         239 :         auto arg = Expr(expr);
    2464         [ +  + ]:         239 :         if (expr.size()) {
    2465         [ +  - ]:           6 :             error = strprintf("rawtr(): only one key expected.");
    2466                 :           6 :             return {};
    2467                 :             :         }
    2468         [ +  - ]:         233 :         auto output_keys = ParsePubkey(key_exp_index, arg, ParseScriptContext::P2TR, out, error);
    2469         [ +  + ]:         233 :         if (output_keys.empty()) {
    2470         [ +  - ]:          36 :             error = strprintf("rawtr(): %s", error);
    2471                 :          36 :             return {};
    2472                 :             :         }
    2473                 :         197 :         ++key_exp_index;
    2474         [ +  + ]:        1228 :         for (auto& pubkey : output_keys) {
    2475   [ +  -  +  - ]:        2062 :             ret.emplace_back(std::make_unique<RawTRDescriptor>(std::move(pubkey)));
    2476                 :             :         }
    2477                 :         197 :         return ret;
    2478   [ +  -  +  -  :       30503 :     } else if (Func("rawtr", expr)) {
                   +  + ]
    2479         [ +  - ]:           8 :         error = "Can only have rawtr at top level";
    2480                 :           8 :         return {};
    2481                 :             :     }
    2482   [ +  +  +  -  :       39559 :     if (ctx == ParseScriptContext::TOP && Func("raw", expr)) {
          +  -  +  +  +  
                      + ]
    2483   [ +  -  -  + ]:       11226 :         std::string str(expr.begin(), expr.end());
    2484   [ -  +  +  -  :        5613 :         if (!IsHex(str)) {
                   +  + ]
    2485         [ +  - ]:          24 :             error = "Raw script is not hex";
    2486                 :          24 :             return {};
    2487                 :             :         }
    2488   [ -  +  +  - ]:        5589 :         auto bytes = ParseHex(str);
    2489   [ +  -  +  - ]:       11178 :         ret.emplace_back(std::make_unique<RawDescriptor>(CScript(bytes.begin(), bytes.end())));
    2490                 :        5589 :         return ret;
    2491   [ +  -  +  -  :       35851 :     } else if (Func("raw", expr)) {
                   +  + ]
    2492         [ +  - ]:           6 :         error = "Can only have raw() at top level";
    2493                 :           6 :         return {};
    2494                 :             :     }
    2495                 :             :     // Process miniscript expressions.
    2496                 :       24643 :     {
    2497                 :       24643 :         const auto script_ctx{ctx == ParseScriptContext::P2WSH ? miniscript::MiniscriptContext::P2WSH : miniscript::MiniscriptContext::TAPSCRIPT};
    2498         [ +  - ]:       24643 :         KeyParser parser(/*out = */&out, /* in = */nullptr, /* ctx = */script_ctx, key_exp_index);
    2499   [ +  -  -  + ]:       73929 :         auto node = miniscript::FromString(std::string(expr.begin(), expr.end()), parser);
    2500         [ +  + ]:       24643 :         if (parser.m_key_parsing_error != "") {
    2501                 :         357 :             error = std::move(parser.m_key_parsing_error);
    2502                 :         357 :             return {};
    2503                 :             :         }
    2504         [ +  + ]:       24286 :         if (node) {
    2505         [ +  + ]:       20955 :             if (ctx != ParseScriptContext::P2WSH && ctx != ParseScriptContext::P2TR) {
    2506         [ +  - ]:         872 :                 error = "Miniscript expressions can only be used in wsh or tr.";
    2507                 :         872 :                 return {};
    2508                 :             :             }
    2509   [ +  +  +  + ]:       20083 :             if (!node->IsSane() || node->IsNotSatisfiable()) {
    2510                 :             :                 // Try to find the first insane sub for better error reporting.
    2511         [ +  - ]:        3139 :                 auto insane_node = node.get();
    2512   [ +  -  +  + ]:        3139 :                 if (const auto sub = node->FindInsaneSub()) insane_node = sub;
    2513   [ +  -  +  -  :        6278 :                 if (const auto str = insane_node->ToString(parser)) error = *str;
                   +  - ]
    2514         [ +  + ]:        3139 :                 if (!insane_node->IsValid()) {
    2515         [ +  - ]:        1839 :                     error += " is invalid";
    2516         [ +  + ]:        1300 :                 } else if (!node->IsSane()) {
    2517         [ +  - ]:        1062 :                     error += " is not sane";
    2518         [ +  + ]:        1062 :                     if (!insane_node->IsNonMalleable()) {
    2519         [ +  - ]:         260 :                         error += ": malleable witnesses exist";
    2520   [ +  +  +  + ]:         802 :                     } else if (insane_node == node.get() && !insane_node->NeedsSignature()) {
    2521         [ +  - ]:         141 :                         error += ": witnesses without signature exist";
    2522         [ +  + ]:         661 :                     } else if (!insane_node->CheckTimeLocksMix()) {
    2523         [ +  - ]:          84 :                         error += ": contains mixes of timelocks expressed in blocks and seconds";
    2524         [ +  - ]:         577 :                     } else if (!insane_node->CheckDuplicateKey()) {
    2525         [ +  - ]:         414 :                         error += ": contains duplicate public keys";
    2526         [ +  + ]:         163 :                     } else if (!insane_node->ValidSatisfactions()) {
    2527         [ +  - ]:          80 :                         error += ": needs witnesses that may exceed resource limits";
    2528                 :             :                     }
    2529                 :             :                 } else {
    2530         [ +  - ]:         238 :                     error += " is not satisfiable";
    2531                 :             :                 }
    2532                 :        3139 :                 return {};
    2533                 :             :             }
    2534                 :             :             // A signature check is required for a miniscript to be sane. Therefore no sane miniscript
    2535                 :             :             // may have an empty list of public keys.
    2536         [ +  - ]:       16944 :             CHECK_NONFATAL(!parser.m_keys.empty());
    2537         [ -  + ]:       16944 :             key_exp_index += parser.m_keys.size();
    2538                 :             :             // Make sure all vecs are of the same length, or exactly length 1
    2539                 :             :             // For length 1 vectors, clone subdescs until vector is the same length
    2540         [ -  + ]:       16944 :             size_t num_multipath = std::max_element(parser.m_keys.begin(), parser.m_keys.end(),
    2541                 :        7982 :                     [](const std::vector<std::unique_ptr<PubkeyProvider>>& a, const std::vector<std::unique_ptr<PubkeyProvider>>& b) {
    2542   [ -  +  -  +  :        7982 :                         return a.size() < b.size();
                   +  + ]
    2543         [ -  + ]:       16944 :                     })->size();
    2544                 :             : 
    2545         [ +  + ]:       41819 :             for (auto& vec : parser.m_keys) {
    2546   [ -  +  +  + ]:       24889 :                 if (vec.size() == 1) {
    2547         [ +  + ]:       54346 :                     for (size_t i = 1; i < num_multipath; ++i) {
    2548   [ +  -  +  -  :       31299 :                         vec.emplace_back(vec.at(0)->Clone());
                   +  - ]
    2549                 :             :                     }
    2550         [ +  + ]:        1842 :                 } else if (vec.size() != num_multipath) {
    2551         [ +  - ]:          14 :                     error = strprintf("Miniscript: Multipath derivation paths have mismatched lengths");
    2552                 :          14 :                     return {};
    2553                 :             :                 }
    2554                 :             :             }
    2555                 :             : 
    2556                 :             :             // Build the final descriptors vector
    2557         [ +  + ]:       56834 :             for (size_t i = 0; i < num_multipath; ++i) {
    2558                 :             :                 // Build final pubkeys vectors by retrieving the i'th subscript for each vector in subscripts
    2559                 :       39904 :                 std::vector<std::unique_ptr<PubkeyProvider>> pubs;
    2560   [ -  +  +  - ]:       39904 :                 pubs.reserve(parser.m_keys.size());
    2561         [ +  + ]:      119359 :                 for (auto& pub : parser.m_keys) {
    2562   [ +  -  +  - ]:       79455 :                     pubs.emplace_back(std::move(pub.at(i)));
    2563                 :             :                 }
    2564   [ +  -  +  -  :       79808 :                 ret.emplace_back(std::make_unique<MiniscriptDescriptor>(std::move(pubs), node->Clone()));
                   +  - ]
    2565                 :       39904 :             }
    2566                 :       16930 :             return ret;
    2567                 :             :         }
    2568                 :       45955 :     }
    2569         [ +  + ]:        3331 :     if (ctx == ParseScriptContext::P2SH) {
    2570         [ +  - ]:          34 :         error = "A function is needed within P2SH";
    2571                 :          34 :         return {};
    2572         [ +  + ]:        3297 :     } else if (ctx == ParseScriptContext::P2WSH) {
    2573         [ +  - ]:         406 :         error = "A function is needed within P2WSH";
    2574                 :         406 :         return {};
    2575                 :             :     }
    2576   [ +  -  +  - ]:        5782 :     error = strprintf("'%s' is not a valid descriptor function", std::string(expr.begin(), expr.end()));
    2577                 :        2891 :     return {};
    2578                 :       80625 : }
    2579                 :             : 
    2580                 :       39369 : std::unique_ptr<DescriptorImpl> InferMultiA(const CScript& script, ParseScriptContext ctx, const SigningProvider& provider)
    2581                 :             : {
    2582                 :       39369 :     auto match = MatchMultiA(script);
    2583         [ +  + ]:       39369 :     if (!match) return {};
    2584                 :        9169 :     std::vector<std::unique_ptr<PubkeyProvider>> keys;
    2585   [ -  +  +  - ]:        9169 :     keys.reserve(match->second.size());
    2586         [ +  + ]:      884424 :     for (const auto keyspan : match->second) {
    2587         [ -  + ]:      875255 :         if (keyspan.size() != 32) return {};
    2588         [ +  - ]:      875255 :         auto key = InferXOnlyPubkey(XOnlyPubKey{keyspan}, ctx, provider);
    2589         [ -  + ]:      875255 :         if (!key) return {};
    2590         [ +  - ]:      875255 :         keys.push_back(std::move(key));
    2591                 :      875255 :     }
    2592   [ +  -  -  + ]:        9169 :     return std::make_unique<MultiADescriptor>(match->first, std::move(keys));
    2593                 :       48538 : }
    2594                 :             : 
    2595                 :             : // NOLINTNEXTLINE(misc-no-recursion)
    2596                 :     1799796 : std::unique_ptr<DescriptorImpl> InferScript(const CScript& script, ParseScriptContext ctx, const SigningProvider& provider)
    2597                 :             : {
    2598   [ +  +  +  +  :     1840081 :     if (ctx == ParseScriptContext::P2TR && script.size() == 34 && script[0] == 32 && script[33] == OP_CHECKSIG) {
          +  +  +  -  +  
             +  +  -  +  
                      - ]
    2599                 :        5493 :         XOnlyPubKey key{std::span{script}.subspan(1, 32)};
    2600   [ +  -  -  + ]:        5493 :         return std::make_unique<PKDescriptor>(InferXOnlyPubkey(key, ctx, provider), true);
    2601                 :             :     }
    2602                 :             : 
    2603         [ +  + ]:     1794303 :     if (ctx == ParseScriptContext::P2TR) {
    2604                 :       39369 :         auto ret = InferMultiA(script, ctx, provider);
    2605         [ +  + ]:       39369 :         if (ret) return ret;
    2606                 :       39369 :     }
    2607                 :             : 
    2608                 :     1785134 :     std::vector<std::vector<unsigned char>> data;
    2609         [ +  - ]:     1785134 :     TxoutType txntype = Solver(script, data);
    2610                 :             : 
    2611   [ +  +  +  - ]:     1785134 :     if (txntype == TxoutType::PUBKEY && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
    2612         [ -  + ]:       34054 :         CPubKey pubkey(data[0]);
    2613   [ +  -  +  + ]:       34054 :         if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
    2614   [ +  -  -  + ]:       31171 :             return std::make_unique<PKDescriptor>(std::move(pubkey_provider));
    2615                 :       34054 :         }
    2616                 :             :     }
    2617   [ +  +  +  + ]:     1753963 :     if (txntype == TxoutType::PUBKEYHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
    2618         [ -  + ]:       27895 :         uint160 hash(data[0]);
    2619         [ +  - ]:       27895 :         CKeyID keyid(hash);
    2620         [ +  - ]:       27895 :         CPubKey pubkey;
    2621   [ +  -  +  + ]:       27895 :         if (provider.GetPubKey(keyid, pubkey)) {
    2622   [ +  -  +  - ]:        1749 :             if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
    2623   [ +  -  -  + ]:        1749 :                 return std::make_unique<PKHDescriptor>(std::move(pubkey_provider));
    2624                 :        1749 :             }
    2625                 :             :         }
    2626                 :             :     }
    2627         [ +  + ]:     1752214 :     if (txntype == TxoutType::WITNESS_V0_KEYHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH)) {
    2628         [ -  + ]:       73733 :         uint160 hash(data[0]);
    2629         [ +  - ]:       73733 :         CKeyID keyid(hash);
    2630         [ +  - ]:       73733 :         CPubKey pubkey;
    2631   [ +  -  +  + ]:       73733 :         if (provider.GetPubKey(keyid, pubkey)) {
    2632   [ +  -  +  - ]:        2615 :             if (auto pubkey_provider = InferPubkey(pubkey, ParseScriptContext::P2WPKH, provider)) {
    2633   [ +  -  -  + ]:        2615 :                 return std::make_unique<WPKHDescriptor>(std::move(pubkey_provider));
    2634                 :        2615 :             }
    2635                 :             :         }
    2636                 :             :     }
    2637   [ +  +  +  - ]:     1749599 :     if (txntype == TxoutType::MULTISIG && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
    2638                 :       35550 :         bool ok = true;
    2639                 :       35550 :         std::vector<std::unique_ptr<PubkeyProvider>> providers;
    2640   [ -  +  +  + ]:      205741 :         for (size_t i = 1; i + 1 < data.size(); ++i) {
    2641         [ -  + ]:      172476 :             CPubKey pubkey(data[i]);
    2642   [ +  -  +  + ]:      172476 :             if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
    2643         [ +  - ]:      170191 :                 providers.push_back(std::move(pubkey_provider));
    2644                 :             :             } else {
    2645                 :        2285 :                 ok = false;
    2646                 :        2285 :                 break;
    2647                 :      172476 :             }
    2648                 :             :         }
    2649   [ +  -  -  + ]:       33265 :         if (ok) return std::make_unique<MultisigDescriptor>((int)data[0][0], std::move(providers));
    2650                 :       35550 :     }
    2651         [ +  + ]:     1716334 :     if (txntype == TxoutType::SCRIPTHASH && ctx == ParseScriptContext::TOP) {
    2652         [ -  + ]:      158968 :         uint160 hash(data[0]);
    2653         [ +  - ]:      158968 :         CScriptID scriptid(hash);
    2654                 :      158968 :         CScript subscript;
    2655   [ +  -  +  + ]:      158968 :         if (provider.GetCScript(scriptid, subscript)) {
    2656         [ +  - ]:        8403 :             auto sub = InferScript(subscript, ParseScriptContext::P2SH, provider);
    2657   [ +  +  +  -  :        8403 :             if (sub) return std::make_unique<SHDescriptor>(std::move(sub));
                   -  + ]
    2658                 :        8403 :         }
    2659                 :      158968 :     }
    2660         [ +  + ]:     1707955 :     if (txntype == TxoutType::WITNESS_V0_SCRIPTHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH)) {
    2661   [ -  +  +  - ]:       96083 :         CScriptID scriptid{RIPEMD160(data[0])};
    2662                 :       96083 :         CScript subscript;
    2663   [ +  -  +  + ]:       96083 :         if (provider.GetCScript(scriptid, subscript)) {
    2664         [ +  - ]:       19462 :             auto sub = InferScript(subscript, ParseScriptContext::P2WSH, provider);
    2665   [ +  +  +  -  :       19462 :             if (sub) return std::make_unique<WSHDescriptor>(std::move(sub));
                   -  + ]
    2666                 :       19462 :         }
    2667                 :       96083 :     }
    2668         [ +  + ]:     1689377 :     if (txntype == TxoutType::WITNESS_V1_TAPROOT && ctx == ParseScriptContext::TOP) {
    2669                 :             :         // Extract x-only pubkey from output.
    2670                 :       46371 :         XOnlyPubKey pubkey;
    2671                 :       46371 :         std::copy(data[0].begin(), data[0].end(), pubkey.begin());
    2672                 :             :         // Request spending data.
    2673         [ +  - ]:       46371 :         TaprootSpendData tap;
    2674   [ +  -  +  + ]:       46371 :         if (provider.GetTaprootSpendData(pubkey, tap)) {
    2675                 :             :             // If found, convert it back to tree form.
    2676         [ +  - ]:       28724 :             auto tree = InferTaprootTree(tap, pubkey);
    2677         [ +  + ]:       28724 :             if (tree) {
    2678                 :             :                 // If that works, try to infer subdescriptors for all leaves.
    2679                 :       28712 :                 bool ok = true;
    2680                 :       28712 :                 std::vector<std::unique_ptr<DescriptorImpl>> subscripts; //!< list of script subexpressions
    2681                 :       28712 :                 std::vector<int> depths; //!< depth in the tree of each subexpression (same length subscripts)
    2682   [ +  -  +  + ]:       73467 :                 for (const auto& [depth, script, leaf_ver] : *tree) {
    2683                 :       44862 :                     std::unique_ptr<DescriptorImpl> subdesc;
    2684         [ +  - ]:       44862 :                     if (leaf_ver == TAPROOT_LEAF_TAPSCRIPT) {
    2685         [ +  - ]:       89724 :                         subdesc = InferScript(CScript(script.begin(), script.end()), ParseScriptContext::P2TR, provider);
    2686                 :             :                     }
    2687         [ +  + ]:       44862 :                     if (!subdesc) {
    2688                 :         107 :                         ok = false;
    2689                 :         107 :                         break;
    2690                 :             :                     } else {
    2691         [ +  - ]:       44755 :                         subscripts.push_back(std::move(subdesc));
    2692         [ +  - ]:       44755 :                         depths.push_back(depth);
    2693                 :             :                     }
    2694                 :       44862 :                 }
    2695                 :         107 :                 if (ok) {
    2696         [ +  - ]:       28605 :                     auto key = InferXOnlyPubkey(tap.internal_key, ParseScriptContext::P2TR, provider);
    2697   [ +  -  -  + ]:       28605 :                     return std::make_unique<TRDescriptor>(std::move(key), std::move(subscripts), std::move(depths));
    2698                 :       28605 :                 }
    2699                 :       28712 :             }
    2700                 :       28724 :         }
    2701                 :             :         // If the above doesn't work, construct a rawtr() descriptor with just the encoded x-only pubkey.
    2702   [ +  -  +  + ]:       17766 :         if (pubkey.IsFullyValid()) {
    2703         [ +  - ]:       10722 :             auto key = InferXOnlyPubkey(pubkey, ParseScriptContext::P2TR, provider);
    2704         [ +  - ]:       10722 :             if (key) {
    2705   [ +  -  -  + ]:       10722 :                 return std::make_unique<RawTRDescriptor>(std::move(key));
    2706                 :             :             }
    2707                 :       10722 :         }
    2708                 :       46371 :     }
    2709                 :             : 
    2710         [ +  + ]:     1650050 :     if (ctx == ParseScriptContext::P2WSH || ctx == ParseScriptContext::P2TR) {
    2711                 :       46035 :         const auto script_ctx{ctx == ParseScriptContext::P2WSH ? miniscript::MiniscriptContext::P2WSH : miniscript::MiniscriptContext::TAPSCRIPT};
    2712         [ +  - ]:       46035 :         KeyParser parser(/* out = */nullptr, /* in = */&provider, /* ctx = */script_ctx);
    2713         [ +  - ]:       46035 :         auto node = miniscript::FromScript(script, parser);
    2714   [ +  +  +  + ]:       46035 :         if (node && node->IsSane()) {
    2715                 :       45044 :             std::vector<std::unique_ptr<PubkeyProvider>> keys;
    2716   [ -  +  +  - ]:       45044 :             keys.reserve(parser.m_keys.size());
    2717         [ +  + ]:      125590 :             for (auto& key : parser.m_keys) {
    2718   [ +  -  +  - ]:       80546 :                 keys.emplace_back(std::move(key.at(0)));
    2719                 :             :             }
    2720   [ +  -  -  + ]:       45044 :             return std::make_unique<MiniscriptDescriptor>(std::move(keys), std::move(node));
    2721                 :       45044 :         }
    2722                 :       92070 :     }
    2723                 :             : 
    2724                 :             :     // The following descriptors are all top-level only descriptors.
    2725                 :             :     // So if we are not at the top level, return early.
    2726         [ +  + ]:     1605006 :     if (ctx != ParseScriptContext::TOP) return nullptr;
    2727                 :             : 
    2728                 :     1603991 :     CTxDestination dest;
    2729   [ +  -  +  + ]:     1603991 :     if (ExtractDestination(script, dest)) {
    2730   [ +  -  +  - ]:      364081 :         if (GetScriptForDestination(dest) == script) {
    2731   [ +  -  -  + ]:      364081 :             return std::make_unique<AddressDescriptor>(std::move(dest));
    2732                 :             :         }
    2733                 :             :     }
    2734                 :             : 
    2735   [ +  -  -  + ]:     1239910 :     return std::make_unique<RawDescriptor>(script);
    2736                 :     1785134 : }
    2737                 :             : 
    2738                 :             : 
    2739                 :             : } // namespace
    2740                 :             : 
    2741                 :             : /** Check a descriptor checksum, and update desc to be the checksum-less part. */
    2742                 :       50928 : bool CheckChecksum(std::span<const char>& sp, bool require_checksum, std::string& error, std::string* out_checksum = nullptr)
    2743                 :             : {
    2744                 :       50928 :     auto check_split = Split(sp, '#');
    2745   [ -  +  +  + ]:       50928 :     if (check_split.size() > 2) {
    2746         [ +  - ]:          44 :         error = "Multiple '#' symbols";
    2747                 :             :         return false;
    2748                 :             :     }
    2749   [ +  +  +  + ]:       50884 :     if (check_split.size() == 1 && require_checksum){
    2750         [ +  - ]:       50928 :         error = "Missing checksum";
    2751                 :             :         return false;
    2752                 :             :     }
    2753         [ +  + ]:       46380 :     if (check_split.size() == 2) {
    2754         [ +  + ]:         145 :         if (check_split[1].size() != 8) {
    2755         [ +  - ]:          37 :             error = strprintf("Expected 8 character checksum, not %u characters", check_split[1].size());
    2756                 :          37 :             return false;
    2757                 :             :         }
    2758                 :             :     }
    2759         [ +  - ]:       46343 :     auto checksum = DescriptorChecksum(check_split[0]);
    2760         [ +  + ]:       46343 :     if (checksum.empty()) {
    2761         [ +  - ]:       46343 :         error = "Invalid characters in payload";
    2762                 :             :         return false;
    2763                 :             :     }
    2764   [ -  +  +  + ]:       46070 :     if (check_split.size() == 2) {
    2765   [ -  +  +  + ]:         104 :         if (!std::equal(checksum.begin(), checksum.end(), check_split[1].begin())) {
    2766   [ +  -  +  - ]:          58 :             error = strprintf("Provided checksum '%s' does not match computed checksum '%s'", std::string(check_split[1].begin(), check_split[1].end()), checksum);
    2767                 :          29 :             return false;
    2768                 :             :         }
    2769                 :             :     }
    2770         [ +  + ]:       46041 :     if (out_checksum) *out_checksum = std::move(checksum);
    2771                 :       46041 :     sp = check_split[0];
    2772                 :       46041 :     return true;
    2773                 :       97271 : }
    2774                 :             : 
    2775                 :       49498 : std::vector<std::unique_ptr<Descriptor>> Parse(std::string_view descriptor, FlatSigningProvider& out, std::string& error, bool require_checksum)
    2776                 :             : {
    2777                 :       49498 :     std::span<const char> sp{descriptor};
    2778         [ +  + ]:       49498 :     if (!CheckChecksum(sp, require_checksum, error)) return {};
    2779                 :       44821 :     uint32_t key_exp_index = 0;
    2780                 :       44821 :     auto ret = ParseScript(key_exp_index, sp, ParseScriptContext::TOP, out, error);
    2781   [ +  +  +  + ]:       44821 :     if (sp.empty() && !ret.empty()) {
    2782                 :       34172 :         std::vector<std::unique_ptr<Descriptor>> descs;
    2783   [ -  +  +  - ]:       34172 :         descs.reserve(ret.size());
    2784         [ +  + ]:      121415 :         for (auto& r : ret) {
    2785         [ +  - ]:       87243 :             descs.emplace_back(std::unique_ptr<Descriptor>(std::move(r)));
    2786                 :             :         }
    2787                 :       34172 :         return descs;
    2788                 :       34172 :     }
    2789                 :       10649 :     return {};
    2790                 :       44821 : }
    2791                 :             : 
    2792                 :        1430 : std::string GetDescriptorChecksum(const std::string& descriptor)
    2793                 :             : {
    2794         [ -  + ]:        1430 :     std::string ret;
    2795                 :        1430 :     std::string error;
    2796         [ -  + ]:        1430 :     std::span<const char> sp{descriptor};
    2797   [ +  -  +  +  :        1430 :     if (!CheckChecksum(sp, false, error, &ret)) return "";
                   +  - ]
    2798                 :        1220 :     return ret;
    2799                 :        1430 : }
    2800                 :             : 
    2801                 :     1727069 : std::unique_ptr<Descriptor> InferDescriptor(const CScript& script, const SigningProvider& provider)
    2802                 :             : {
    2803                 :     1727069 :     return InferScript(script, ParseScriptContext::TOP, provider);
    2804                 :             : }
    2805                 :             : 
    2806                 :       24327 : uint256 DescriptorID(const Descriptor& desc)
    2807                 :             : {
    2808                 :       24327 :     std::string desc_str = desc.ToString(/*compat_format=*/true);
    2809                 :       24327 :     uint256 id;
    2810   [ +  -  +  -  :       48654 :     CSHA256().Write((unsigned char*)desc_str.data(), desc_str.size()).Finalize(id.begin());
                   +  - ]
    2811                 :       24327 :     return id;
    2812                 :       24327 : }
    2813                 :             : 
    2814                 :     3009612 : void DescriptorCache::CacheParentExtPubKey(uint32_t key_exp_pos, const CExtPubKey& xpub)
    2815                 :             : {
    2816                 :     3009612 :     m_parent_xpubs[key_exp_pos] = xpub;
    2817                 :     3009612 : }
    2818                 :             : 
    2819                 :      207565 : void DescriptorCache::CacheDerivedExtPubKey(uint32_t key_exp_pos, uint32_t der_index, const CExtPubKey& xpub)
    2820                 :             : {
    2821                 :      207565 :     auto& xpubs = m_derived_xpubs[key_exp_pos];
    2822                 :      207565 :     xpubs[der_index] = xpub;
    2823                 :      207565 : }
    2824                 :             : 
    2825                 :      498437 : void DescriptorCache::CacheLastHardenedExtPubKey(uint32_t key_exp_pos, const CExtPubKey& xpub)
    2826                 :             : {
    2827                 :      498437 :     m_last_hardened_xpubs[key_exp_pos] = xpub;
    2828                 :      498437 : }
    2829                 :             : 
    2830                 :     2991052 : bool DescriptorCache::GetCachedParentExtPubKey(uint32_t key_exp_pos, CExtPubKey& xpub) const
    2831                 :             : {
    2832                 :     2991052 :     const auto& it = m_parent_xpubs.find(key_exp_pos);
    2833         [ +  + ]:     2991052 :     if (it == m_parent_xpubs.end()) return false;
    2834                 :     2910533 :     xpub = it->second;
    2835                 :     2910533 :     return true;
    2836                 :             : }
    2837                 :             : 
    2838                 :     2733279 : bool DescriptorCache::GetCachedDerivedExtPubKey(uint32_t key_exp_pos, uint32_t der_index, CExtPubKey& xpub) const
    2839                 :             : {
    2840                 :     2733279 :     const auto& key_exp_it = m_derived_xpubs.find(key_exp_pos);
    2841         [ +  + ]:     2733279 :     if (key_exp_it == m_derived_xpubs.end()) return false;
    2842                 :      184172 :     const auto& der_it = key_exp_it->second.find(der_index);
    2843         [ +  + ]:      184172 :     if (der_it == key_exp_it->second.end()) return false;
    2844                 :      128541 :     xpub = der_it->second;
    2845                 :      128541 :     return true;
    2846                 :             : }
    2847                 :             : 
    2848                 :       22126 : bool DescriptorCache::GetCachedLastHardenedExtPubKey(uint32_t key_exp_pos, CExtPubKey& xpub) const
    2849                 :             : {
    2850                 :       22126 :     const auto& it = m_last_hardened_xpubs.find(key_exp_pos);
    2851         [ +  + ]:       22126 :     if (it == m_last_hardened_xpubs.end()) return false;
    2852                 :       18221 :     xpub = it->second;
    2853                 :       18221 :     return true;
    2854                 :             : }
    2855                 :             : 
    2856                 :      209118 : DescriptorCache DescriptorCache::MergeAndDiff(const DescriptorCache& other)
    2857                 :             : {
    2858                 :      209118 :     DescriptorCache diff;
    2859   [ +  -  +  +  :      523727 :     for (const auto& parent_xpub_pair : other.GetCachedParentExtPubKeys()) {
                   +  - ]
    2860         [ +  - ]:      314609 :         CExtPubKey xpub;
    2861   [ +  +  +  - ]:      314609 :         if (GetCachedParentExtPubKey(parent_xpub_pair.first, xpub)) {
    2862         [ -  + ]:      264109 :             if (xpub != parent_xpub_pair.second) {
    2863   [ #  #  #  # ]:           0 :                 throw std::runtime_error(std::string(__func__) + ": New cached parent xpub does not match already cached parent xpub");
    2864                 :             :             }
    2865                 :      264109 :             continue;
    2866                 :             :         }
    2867         [ +  - ]:       50500 :         CacheParentExtPubKey(parent_xpub_pair.first, parent_xpub_pair.second);
    2868         [ +  - ]:       50500 :         diff.CacheParentExtPubKey(parent_xpub_pair.first, parent_xpub_pair.second);
    2869                 :           0 :     }
    2870   [ +  -  +  + ]:      258906 :     for (const auto& derived_xpub_map_pair : other.GetCachedDerivedExtPubKeys()) {
    2871   [ +  +  +  - ]:       99576 :         for (const auto& derived_xpub_pair : derived_xpub_map_pair.second) {
    2872         [ +  - ]:       49788 :             CExtPubKey xpub;
    2873   [ -  +  +  - ]:       49788 :             if (GetCachedDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, xpub)) {
    2874         [ #  # ]:           0 :                 if (xpub != derived_xpub_pair.second) {
    2875   [ #  #  #  # ]:           0 :                     throw std::runtime_error(std::string(__func__) + ": New cached derived xpub does not match already cached derived xpub");
    2876                 :             :                 }
    2877                 :           0 :                 continue;
    2878                 :             :             }
    2879         [ +  - ]:       49788 :             CacheDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, derived_xpub_pair.second);
    2880         [ +  - ]:       49788 :             diff.CacheDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, derived_xpub_pair.second);
    2881                 :             :         }
    2882                 :             :     }
    2883   [ +  -  +  +  :      228348 :     for (const auto& lh_xpub_pair : other.GetCachedLastHardenedExtPubKeys()) {
                   +  - ]
    2884         [ +  - ]:       19230 :         CExtPubKey xpub;
    2885   [ +  +  +  - ]:       19230 :         if (GetCachedLastHardenedExtPubKey(lh_xpub_pair.first, xpub)) {
    2886         [ -  + ]:       15325 :             if (xpub != lh_xpub_pair.second) {
    2887   [ #  #  #  # ]:           0 :                 throw std::runtime_error(std::string(__func__) + ": New cached last hardened xpub does not match already cached last hardened xpub");
    2888                 :             :             }
    2889                 :       15325 :             continue;
    2890                 :             :         }
    2891         [ +  - ]:        3905 :         CacheLastHardenedExtPubKey(lh_xpub_pair.first, lh_xpub_pair.second);
    2892         [ +  - ]:        3905 :         diff.CacheLastHardenedExtPubKey(lh_xpub_pair.first, lh_xpub_pair.second);
    2893                 :           0 :     }
    2894                 :      209118 :     return diff;
    2895                 :           0 : }
    2896                 :             : 
    2897                 :      493780 : ExtPubKeyMap DescriptorCache::GetCachedParentExtPubKeys() const
    2898                 :             : {
    2899                 :      493780 :     return m_parent_xpubs;
    2900                 :             : }
    2901                 :             : 
    2902                 :      493780 : std::unordered_map<uint32_t, ExtPubKeyMap> DescriptorCache::GetCachedDerivedExtPubKeys() const
    2903                 :             : {
    2904                 :      493780 :     return m_derived_xpubs;
    2905                 :             : }
    2906                 :             : 
    2907                 :      418236 : ExtPubKeyMap DescriptorCache::GetCachedLastHardenedExtPubKeys() const
    2908                 :             : {
    2909                 :      418236 :     return m_last_hardened_xpubs;
    2910                 :             : }
        

Generated by: LCOV version 2.0-1