LCOV - code coverage report
Current view: top level - src/script - descriptor.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 92.4 % 1734 1602
Test Date: 2026-02-25 05:45:00 Functions: 86.5 % 230 199
Branches: 62.4 % 2957 1846

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

Generated by: LCOV version 2.0-1