LCOV - code coverage report
Current view: top level - src/script - descriptor.cpp (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 93.6 % 1711 1601
Test Date: 2026-01-28 04:17:28 Functions: 86.3 % 226 195
Branches: 64.0 % 2951 1889

             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                 :   677740095 : uint64_t PolyMod(uint64_t c, int val)
      95                 :             : {
      96                 :   677740095 :     uint8_t c0 = c >> 35;
      97                 :   677740095 :     c = ((c & 0x7ffffffff) << 5) ^ val;
      98         [ +  + ]:   677740095 :     if (c0 & 1) c ^= 0xf5dee51989;
      99         [ +  + ]:   677740095 :     if (c0 & 2) c ^= 0xa9fdca3312;
     100         [ +  + ]:   677740095 :     if (c0 & 4) c ^= 0x1bab10e32d;
     101         [ +  + ]:   677740095 :     if (c0 & 8) c ^= 0x3706b1677a;
     102         [ +  + ]:   677740095 :     if (c0 & 16) c ^= 0x644d626ffd;
     103                 :   677740095 :     return c;
     104                 :             : }
     105                 :             : 
     106                 :     2215300 : 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                 :     2215300 :     static const std::string INPUT_CHARSET =
     122                 :             :         "0123456789()[],'/*abcdefgh@:$%{}"
     123                 :             :         "IJKLMNOPQRSTUVWXYZ&+-.;<=>?!^_|~"
     124   [ +  +  +  -  :     2215309 :         "ijklmnopqrstuvwxyzABCDEFGH`#\"\\ ";
                   +  - ]
     125                 :             : 
     126                 :             :     /** The character set for the checksum itself (same as bech32). */
     127   [ +  +  +  -  :     2215309 :     static const std::string CHECKSUM_CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
                   +  - ]
     128                 :             : 
     129                 :     2215300 :     uint64_t c = 1;
     130                 :     2215300 :     int cls = 0;
     131                 :     2215300 :     int clscount = 0;
     132         [ +  + ]:   496439410 :     for (auto ch : span) {
     133                 :   494224377 :         auto pos = INPUT_CHARSET.find(ch);
     134         [ +  + ]:   494224377 :         if (pos == std::string::npos) return "";
     135                 :   494224110 :         c = PolyMod(c, pos & 31); // Emit a symbol for the position inside the group, for every character.
     136                 :   494224110 :         cls = cls * 3 + (pos >> 5); // Accumulate the group numbers
     137         [ +  + ]:   494224110 :         if (++clscount == 3) {
     138                 :             :             // Emit an extra symbol representing the group numbers, for every 3 characters.
     139                 :   163816611 :             c = PolyMod(c, cls);
     140                 :   163816611 :             cls = 0;
     141                 :   163816611 :             clscount = 0;
     142                 :             :         }
     143                 :             :     }
     144         [ +  + ]:     2215033 :     if (clscount > 0) c = PolyMod(c, cls);
     145         [ +  + ]:    19935297 :     for (int j = 0; j < 8; ++j) c = PolyMod(c, 0); // Shift further to determine the checksum.
     146                 :     2215033 :     c ^= 1; // Prevent appending zeroes from not affecting the checksum.
     147                 :             : 
     148                 :     2215033 :     std::string ret(8, ' ');
     149         [ +  + ]:    19935297 :     for (int j = 0; j < 8; ++j) ret[j] = CHECKSUM_CHARSET[(c >> (5 * (7 - j))) & 31];
     150                 :     2215033 :     return ret;
     151                 :     2215033 : }
     152                 :             : 
     153   [ -  +  +  -  :     4342344 : std::string AddChecksum(const std::string& str) { return str + "#" + DescriptorChecksum(str); }
                   +  - ]
     154                 :             : 
     155                 :             : ////////////////////////////////////////////////////////////////////////////
     156                 :             : // Internal representation                                                //
     157                 :             : ////////////////////////////////////////////////////////////////////////////
     158                 :             : 
     159                 :             : typedef std::vector<uint32_t> KeyPath;
     160                 :             : 
     161                 :             : /** Interface for public key objects in descriptors. */
     162                 :             : struct PubkeyProvider
     163                 :             : {
     164                 :             : protected:
     165                 :             :     //! Index of this key expression in the descriptor
     166                 :             :     //! E.g. If this PubkeyProvider is key1 in multi(2, key1, key2, key3), then m_expr_index = 0
     167                 :             :     uint32_t m_expr_index;
     168                 :             : 
     169                 :             : public:
     170                 :     1276758 :     explicit PubkeyProvider(uint32_t exp_index) : m_expr_index(exp_index) {}
     171                 :             : 
     172                 :        6174 :     virtual ~PubkeyProvider() = default;
     173                 :             : 
     174                 :             :     /** Compare two public keys represented by this provider.
     175                 :             :      * Used by the Miniscript descriptors to check for duplicate keys in the script.
     176                 :             :      */
     177                 :      278992 :     bool operator<(PubkeyProvider& other) const {
     178                 :      278992 :         FlatSigningProvider dummy;
     179                 :             : 
     180         [ +  - ]:      278992 :         std::optional<CPubKey> a = GetPubKey(0, dummy, dummy);
     181         [ +  - ]:      278992 :         std::optional<CPubKey> b = other.GetPubKey(0, dummy, dummy);
     182                 :             : 
     183                 :      278992 :         return a < b;
     184                 :      278992 :     }
     185                 :             : 
     186                 :             :     /** Derive a public key and put it into out.
     187                 :             :      *  read_cache is the cache to read keys from (if not nullptr)
     188                 :             :      *  write_cache is the cache to write keys to (if not nullptr)
     189                 :             :      *  Caches are not exclusive but this is not tested. Currently we use them exclusively
     190                 :             :      */
     191                 :             :     virtual std::optional<CPubKey> GetPubKey(int pos, const SigningProvider& arg, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const = 0;
     192                 :             : 
     193                 :             :     /** Whether this represent multiple public keys at different positions. */
     194                 :             :     virtual bool IsRange() const = 0;
     195                 :             : 
     196                 :             :     /** Get the size of the generated public key(s) in bytes (33 or 65). */
     197                 :             :     virtual size_t GetSize() const = 0;
     198                 :             : 
     199                 :             :     enum class StringType {
     200                 :             :         PUBLIC,
     201                 :             :         COMPAT // string calculation that mustn't change over time to stay compatible with previous software versions
     202                 :             :     };
     203                 :             : 
     204                 :             :     /** Get the descriptor string form. */
     205                 :             :     virtual std::string ToString(StringType type=StringType::PUBLIC) const = 0;
     206                 :             : 
     207                 :             :     /** Get the descriptor string form including private data (if available in arg).
     208                 :             :      *  If the private data is not available, the output string in the "out" parameter
     209                 :             :      *  will not contain any private key information,
     210                 :             :      *  and this function will return "false".
     211                 :             :      */
     212                 :             :     virtual bool ToPrivateString(const SigningProvider& arg, std::string& out) const = 0;
     213                 :             : 
     214                 :             :     /** Get the descriptor string form with the xpub at the last hardened derivation,
     215                 :             :      *  and always use h for hardened derivation.
     216                 :             :      */
     217                 :             :     virtual bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache = nullptr) const = 0;
     218                 :             : 
     219                 :             :     /** Derive a private key, if private data is available in arg and put it into out. */
     220                 :             :     virtual void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const = 0;
     221                 :             : 
     222                 :             :     /** Return the non-extended public key for this PubkeyProvider, if it has one. */
     223                 :             :     virtual std::optional<CPubKey> GetRootPubKey() const = 0;
     224                 :             :     /** Return the extended public key for this PubkeyProvider, if it has one. */
     225                 :             :     virtual std::optional<CExtPubKey> GetRootExtPubKey() const = 0;
     226                 :             : 
     227                 :             :     /** Make a deep copy of this PubkeyProvider */
     228                 :             :     virtual std::unique_ptr<PubkeyProvider> Clone() const = 0;
     229                 :             : 
     230                 :             :     /** Whether this PubkeyProvider is a BIP 32 extended key that can be derived from */
     231                 :             :     virtual bool IsBIP32() const = 0;
     232                 :             : };
     233                 :             : 
     234                 :             : class OriginPubkeyProvider final : public PubkeyProvider
     235                 :             : {
     236                 :             :     KeyOriginInfo m_origin;
     237                 :             :     std::unique_ptr<PubkeyProvider> m_provider;
     238                 :             :     bool m_apostrophe;
     239                 :             : 
     240                 :      448515 :     std::string OriginString(StringType type, bool normalized=false) const
     241                 :             :     {
     242                 :             :         // If StringType==COMPAT, always use the apostrophe to stay compatible with previous versions
     243   [ +  +  +  +  :      448515 :         bool use_apostrophe = (!normalized && m_apostrophe) || type == StringType::COMPAT;
                   +  + ]
     244   [ +  -  +  - ]:      897030 :         return HexStr(m_origin.fingerprint) + FormatHDKeypath(m_origin.path, use_apostrophe);
     245                 :             :     }
     246                 :             : 
     247                 :             : public:
     248                 :      277757 :     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) {}
     249                 :      592878 :     std::optional<CPubKey> GetPubKey(int pos, const SigningProvider& arg, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
     250                 :             :     {
     251                 :      592878 :         std::optional<CPubKey> pub = m_provider->GetPubKey(pos, arg, out, read_cache, write_cache);
     252         [ +  + ]:      592878 :         if (!pub) return std::nullopt;
     253         [ -  + ]:      576756 :         Assert(out.pubkeys.contains(pub->GetID()));
     254         [ -  + ]:      576756 :         auto& [pubkey, suborigin] = out.origins[pub->GetID()];
     255         [ -  + ]:      576756 :         Assert(pubkey == *pub); // m_provider must have a valid origin by this point.
     256                 :      576756 :         std::copy(std::begin(m_origin.fingerprint), std::end(m_origin.fingerprint), suborigin.fingerprint);
     257                 :      576756 :         suborigin.path.insert(suborigin.path.begin(), m_origin.path.begin(), m_origin.path.end());
     258                 :      576756 :         return pub;
     259                 :             :     }
     260                 :      417557 :     bool IsRange() const override { return m_provider->IsRange(); }
     261                 :        9116 :     size_t GetSize() const override { return m_provider->GetSize(); }
     262                 :         316 :     bool IsBIP32() const override { return m_provider->IsBIP32(); }
     263   [ +  -  +  -  :     1242870 :     std::string ToString(StringType type) const override { return "[" + OriginString(type) + "]" + m_provider->ToString(type); }
                   +  - ]
     264                 :       18182 :     bool ToPrivateString(const SigningProvider& arg, std::string& ret) const override
     265                 :             :     {
     266         [ +  - ]:       18182 :         std::string sub;
     267         [ +  - ]:       18182 :         bool has_priv_key{m_provider->ToPrivateString(arg, sub)};
     268   [ +  -  +  -  :       36364 :         ret = "[" + OriginString(StringType::PUBLIC) + "]" + std::move(sub);
                   +  - ]
     269                 :       18182 :         return has_priv_key;
     270                 :       18182 :     }
     271                 :       16166 :     bool ToNormalizedString(const SigningProvider& arg, std::string& ret, const DescriptorCache* cache) const override
     272                 :             :     {
     273         [ +  - ]:       16166 :         std::string sub;
     274   [ +  -  +  + ]:       16166 :         if (!m_provider->ToNormalizedString(arg, sub, cache)) return false;
     275                 :             :         // If m_provider is a BIP32PubkeyProvider, we may get a string formatted like a OriginPubkeyProvider
     276                 :             :         // In that case, we need to strip out the leading square bracket and fingerprint from the substring,
     277                 :             :         // and append that to our own origin string.
     278         [ +  + ]:       16043 :         if (sub[0] == '[') {
     279         [ +  - ]:        7677 :             sub = sub.substr(9);
     280   [ +  -  +  -  :        7677 :             ret = "[" + OriginString(StringType::PUBLIC, /*normalized=*/true) + std::move(sub);
                   +  - ]
     281                 :             :         } else {
     282   [ +  -  +  -  :       16732 :             ret = "[" + OriginString(StringType::PUBLIC, /*normalized=*/true) + "]" + std::move(sub);
                   +  - ]
     283                 :             :         }
     284                 :             :         return true;
     285                 :       16166 :     }
     286                 :       18998 :     void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const override
     287                 :             :     {
     288                 :       18998 :         m_provider->GetPrivKey(pos, arg, out);
     289                 :       18998 :     }
     290                 :           0 :     std::optional<CPubKey> GetRootPubKey() const override
     291                 :             :     {
     292                 :           0 :         return m_provider->GetRootPubKey();
     293                 :             :     }
     294                 :           0 :     std::optional<CExtPubKey> GetRootExtPubKey() const override
     295                 :             :     {
     296                 :           0 :         return m_provider->GetRootExtPubKey();
     297                 :             :     }
     298                 :       11177 :     std::unique_ptr<PubkeyProvider> Clone() const override
     299                 :             :     {
     300   [ +  -  -  + ]:       11177 :         return std::make_unique<OriginPubkeyProvider>(m_expr_index, m_origin, m_provider->Clone(), m_apostrophe);
     301                 :             :     }
     302                 :             : };
     303                 :             : 
     304                 :             : /** An object representing a parsed constant public key in a descriptor. */
     305                 :        6174 : class ConstPubkeyProvider final : public PubkeyProvider
     306                 :             : {
     307                 :             :     CPubKey m_pubkey;
     308                 :             :     bool m_xonly;
     309                 :             : 
     310                 :      208276 :     std::optional<CKey> GetPrivKey(const SigningProvider& arg) const
     311                 :             :     {
     312                 :      208276 :         CKey key;
     313   [ +  +  +  -  :      287097 :         if (!(m_xonly ? arg.GetKeyByXOnly(XOnlyPubKey(m_pubkey), key) :
                   +  + ]
     314   [ +  -  +  - ]:      170250 :                         arg.GetKey(m_pubkey.GetID(), key))) return std::nullopt;
     315                 :      116847 :         return key;
     316                 :      208276 :     }
     317                 :             : 
     318                 :             : public:
     319                 :      660264 :     ConstPubkeyProvider(uint32_t exp_index, const CPubKey& pubkey, bool xonly) : PubkeyProvider(exp_index), m_pubkey(pubkey), m_xonly(xonly) {}
     320                 :     2150002 :     std::optional<CPubKey> GetPubKey(int pos, const SigningProvider&, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
     321                 :             :     {
     322         [ +  - ]:     2150002 :         KeyOriginInfo info;
     323         [ +  - ]:     2150002 :         CKeyID keyid = m_pubkey.GetID();
     324                 :     2150002 :         std::copy(keyid.begin(), keyid.begin() + sizeof(info.fingerprint), info.fingerprint);
     325   [ +  -  +  - ]:     2150002 :         out.origins.emplace(keyid, std::make_pair(m_pubkey, info));
     326         [ +  - ]:     2150002 :         out.pubkeys.emplace(keyid, m_pubkey);
     327                 :     2150002 :         return m_pubkey;
     328                 :     2150002 :     }
     329                 :      462042 :     bool IsRange() const override { return false; }
     330                 :       93954 :     size_t GetSize() const override { return m_pubkey.size(); }
     331                 :        4914 :     bool IsBIP32() const override { return false; }
     332   [ +  +  +  - ]:     2908676 :     std::string ToString(StringType type) const override { return m_xonly ? HexStr(m_pubkey).substr(2) : HexStr(m_pubkey); }
     333                 :      116823 :     bool ToPrivateString(const SigningProvider& arg, std::string& ret) const override
     334                 :             :     {
     335                 :      116823 :         std::optional<CKey> key = GetPrivKey(arg);
     336         [ +  + ]:      116823 :         if (!key) {
     337         [ +  - ]:       48095 :             ret = ToString(StringType::PUBLIC);
     338                 :       48095 :             return false;
     339                 :             :         }
     340         [ +  - ]:       68728 :         ret = EncodeSecret(*key);
     341                 :       68728 :         return true;
     342                 :      116823 :     }
     343                 :      131601 :     bool ToNormalizedString(const SigningProvider& arg, std::string& ret, const DescriptorCache* cache) const override
     344                 :             :     {
     345                 :      131601 :         ret = ToString(StringType::PUBLIC);
     346                 :      131601 :         return true;
     347                 :             :     }
     348                 :       91453 :     void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const override
     349                 :             :     {
     350                 :       91453 :         std::optional<CKey> key = GetPrivKey(arg);
     351         [ +  + ]:       91453 :         if (!key) return;
     352   [ +  -  +  -  :       48119 :         out.keys.emplace(key->GetPubKey().GetID(), *key);
                   +  - ]
     353                 :       91453 :     }
     354                 :           0 :     std::optional<CPubKey> GetRootPubKey() const override
     355                 :             :     {
     356                 :           0 :         return m_pubkey;
     357                 :             :     }
     358                 :           0 :     std::optional<CExtPubKey> GetRootExtPubKey() const override
     359                 :             :     {
     360                 :           0 :         return std::nullopt;
     361                 :             :     }
     362                 :       67879 :     std::unique_ptr<PubkeyProvider> Clone() const override
     363                 :             :     {
     364                 :       67879 :         return std::make_unique<ConstPubkeyProvider>(m_expr_index, m_pubkey, m_xonly);
     365                 :             :     }
     366                 :             : };
     367                 :             : 
     368                 :             : enum class DeriveType {
     369                 :             :     NO,
     370                 :             :     UNHARDENED,
     371                 :             :     HARDENED,
     372                 :             : };
     373                 :             : 
     374                 :             : /** An object representing a parsed extended public key in a descriptor. */
     375                 :             : class BIP32PubkeyProvider final : public PubkeyProvider
     376                 :             : {
     377                 :             :     // Root xpub, path, and final derivation step type being used, if any
     378                 :             :     CExtPubKey m_root_extkey;
     379                 :             :     KeyPath m_path;
     380                 :             :     DeriveType m_derive;
     381                 :             :     // Whether ' or h is used in harded derivation
     382                 :             :     bool m_apostrophe;
     383                 :             : 
     384                 :      582931 :     bool GetExtKey(const SigningProvider& arg, CExtKey& ret) const
     385                 :             :     {
     386                 :      582931 :         CKey key;
     387   [ +  -  +  -  :      582931 :         if (!arg.GetKey(m_root_extkey.pubkey.GetID(), key)) return false;
                   +  + ]
     388                 :      472220 :         ret.nDepth = m_root_extkey.nDepth;
     389                 :      472220 :         std::copy(m_root_extkey.vchFingerprint, m_root_extkey.vchFingerprint + sizeof(ret.vchFingerprint), ret.vchFingerprint);
     390                 :      472220 :         ret.nChild = m_root_extkey.nChild;
     391                 :      472220 :         ret.chaincode = m_root_extkey.chaincode;
     392         [ +  - ]:      472220 :         ret.key = key;
     393                 :             :         return true;
     394                 :      582931 :     }
     395                 :             : 
     396                 :             :     // Derives the last xprv
     397                 :      356017 :     bool GetDerivedExtKey(const SigningProvider& arg, CExtKey& xprv, CExtKey& last_hardened) const
     398                 :             :     {
     399         [ +  + ]:      356017 :         if (!GetExtKey(arg, xprv)) return false;
     400         [ +  + ]:      556279 :         for (auto entry : m_path) {
     401         [ +  - ]:      260849 :             if (!xprv.Derive(xprv, entry)) return false;
     402         [ +  + ]:      260849 :             if (entry >> 31) {
     403                 :       95609 :                 last_hardened = xprv;
     404                 :             :             }
     405                 :             :         }
     406                 :             :         return true;
     407                 :             :     }
     408                 :             : 
     409                 :      756274 :     bool IsHardened() const
     410                 :             :     {
     411         [ +  + ]:      756274 :         if (m_derive == DeriveType::HARDENED) return true;
     412         [ +  + ]:     1023106 :         for (auto entry : m_path) {
     413         [ +  + ]:      382894 :             if (entry >> 31) return true;
     414                 :             :         }
     415                 :             :         return false;
     416                 :             :     }
     417                 :             : 
     418                 :             : public:
     419                 :      329520 :     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) {}
     420                 :     2598067 :     bool IsRange() const override { return m_derive != DeriveType::NO; }
     421                 :       91509 :     size_t GetSize() const override { return 33; }
     422                 :        4761 :     bool IsBIP32() const override { return true; }
     423                 :     1876274 :     std::optional<CPubKey> GetPubKey(int pos, const SigningProvider& arg, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
     424                 :             :     {
     425         [ +  - ]:     1876274 :         KeyOriginInfo info;
     426         [ +  - ]:     1876274 :         CKeyID keyid = m_root_extkey.pubkey.GetID();
     427                 :     1876274 :         std::copy(keyid.begin(), keyid.begin() + sizeof(info.fingerprint), info.fingerprint);
     428         [ +  - ]:     1876274 :         info.path = m_path;
     429   [ +  +  +  - ]:     1876274 :         if (m_derive == DeriveType::UNHARDENED) info.path.push_back((uint32_t)pos);
     430   [ +  +  +  - ]:     1876274 :         if (m_derive == DeriveType::HARDENED) info.path.push_back(((uint32_t)pos) | 0x80000000L);
     431                 :             : 
     432                 :             :         // Derive keys or fetch them from cache
     433                 :     1876274 :         CExtPubKey final_extkey = m_root_extkey;
     434                 :     1876274 :         CExtPubKey parent_extkey = m_root_extkey;
     435         [ +  + ]:     1876274 :         CExtPubKey last_hardened_extkey;
     436                 :     1876274 :         bool der = true;
     437         [ +  + ]:     1876274 :         if (read_cache) {
     438   [ +  -  +  + ]:     1120000 :             if (!read_cache->GetCachedDerivedExtPubKey(m_expr_index, pos, final_extkey)) {
     439         [ +  + ]:     1043716 :                 if (m_derive == DeriveType::HARDENED) return std::nullopt;
     440                 :             :                 // Try to get the derivation parent
     441   [ +  -  +  + ]:     1033517 :                 if (!read_cache->GetCachedParentExtPubKey(m_expr_index, parent_extkey)) return std::nullopt;
     442                 :     1016799 :                 final_extkey = parent_extkey;
     443   [ +  +  +  - ]:     1016799 :                 if (m_derive == DeriveType::UNHARDENED) der = parent_extkey.Derive(final_extkey, pos);
     444                 :             :             }
     445         [ +  + ]:      756274 :         } else if (IsHardened()) {
     446         [ +  - ]:      116062 :             CExtKey xprv;
     447                 :      116062 :             CExtKey lh_xprv;
     448   [ +  -  +  + ]:      116062 :             if (!GetDerivedExtKey(arg, xprv, lh_xprv)) return std::nullopt;
     449         [ +  - ]:      102730 :             parent_extkey = xprv.Neuter();
     450   [ +  +  +  - ]:      102730 :             if (m_derive == DeriveType::UNHARDENED) der = xprv.Derive(xprv, pos);
     451   [ +  +  +  - ]:      102730 :             if (m_derive == DeriveType::HARDENED) der = xprv.Derive(xprv, pos | 0x80000000UL);
     452         [ +  - ]:      102730 :             final_extkey = xprv.Neuter();
     453         [ +  + ]:      102730 :             if (lh_xprv.key.IsValid()) {
     454         [ +  - ]:       42890 :                 last_hardened_extkey = lh_xprv.Neuter();
     455                 :             :             }
     456                 :      116062 :         } else {
     457         [ +  + ]:      966085 :             for (auto entry : m_path) {
     458   [ +  -  -  + ]:      325873 :                 if (!parent_extkey.Derive(parent_extkey, entry)) return std::nullopt;
     459                 :             :             }
     460                 :      640212 :             final_extkey = parent_extkey;
     461   [ +  +  +  - ]:      640212 :             if (m_derive == DeriveType::UNHARDENED) der = parent_extkey.Derive(final_extkey, pos);
     462         [ -  + ]:      640212 :             assert(m_derive != DeriveType::HARDENED);
     463                 :             :         }
     464         [ -  + ]:     1127180 :         if (!der) return std::nullopt;
     465                 :             : 
     466   [ +  -  +  -  :     1836025 :         out.origins.emplace(final_extkey.pubkey.GetID(), std::make_pair(final_extkey.pubkey, info));
                   +  - ]
     467   [ +  -  +  - ]:     1836025 :         out.pubkeys.emplace(final_extkey.pubkey.GetID(), final_extkey.pubkey);
     468                 :             : 
     469         [ +  + ]:     1836025 :         if (write_cache) {
     470                 :             :             // Only cache parent if there is any unhardened derivation
     471         [ +  + ]:      570388 :             if (m_derive != DeriveType::HARDENED) {
     472         [ +  - ]:      509942 :                 write_cache->CacheParentExtPubKey(m_expr_index, parent_extkey);
     473                 :             :                 // Cache last hardened xpub if we have it
     474         [ +  + ]:      509942 :                 if (last_hardened_extkey.pubkey.IsValid()) {
     475         [ +  - ]:       42284 :                     write_cache->CacheLastHardenedExtPubKey(m_expr_index, last_hardened_extkey);
     476                 :             :                 }
     477   [ -  +  +  - ]:       60446 :             } else if (info.path.size() > 0) {
     478         [ +  - ]:       60446 :                 write_cache->CacheDerivedExtPubKey(m_expr_index, pos, final_extkey);
     479                 :             :             }
     480                 :             :         }
     481                 :             : 
     482                 :     1836025 :         return final_extkey.pubkey;
     483                 :     1876274 :     }
     484                 :     1618695 :     std::string ToString(StringType type, bool normalized) const
     485                 :             :     {
     486                 :             :         // If StringType==COMPAT, always use the apostrophe to stay compatible with previous versions
     487   [ +  +  +  +  :     1618695 :         const bool use_apostrophe = (!normalized && m_apostrophe) || type == StringType::COMPAT;
                   +  + ]
     488   [ +  -  +  - ]:     3237390 :         std::string ret = EncodeExtPubKey(m_root_extkey) + FormatHDKeypath(m_path, /*apostrophe=*/use_apostrophe);
     489         [ +  + ]:     1618695 :         if (IsRange()) {
     490         [ +  - ]:      559645 :             ret += "/*";
     491   [ +  +  +  + ]:      559645 :             if (m_derive == DeriveType::HARDENED) ret += use_apostrophe ? '\'' : 'h';
     492                 :             :         }
     493                 :     1618695 :         return ret;
     494                 :           0 :     }
     495                 :     1605343 :     std::string ToString(StringType type=StringType::PUBLIC) const override
     496                 :             :     {
     497                 :     1366354 :         return ToString(type, /*normalized=*/false);
     498                 :             :     }
     499                 :      226914 :     bool ToPrivateString(const SigningProvider& arg, std::string& out) const override
     500                 :             :     {
     501         [ +  - ]:      226914 :         CExtKey key;
     502   [ +  -  +  + ]:      226914 :         if (!GetExtKey(arg, key)) {
     503         [ +  - ]:       50124 :             out = ToString(StringType::PUBLIC);
     504                 :       50124 :             return false;
     505                 :             :         }
     506   [ +  -  +  -  :      176790 :         out = EncodeExtKey(key) + FormatHDKeypath(m_path, /*apostrophe=*/m_apostrophe);
                   +  - ]
     507         [ +  + ]:      176790 :         if (IsRange()) {
     508         [ +  - ]:       16870 :             out += "/*";
     509   [ +  +  +  + ]:      239160 :             if (m_derive == DeriveType::HARDENED) out += m_apostrophe ? '\'' : 'h';
     510                 :             :         }
     511                 :             :         return true;
     512                 :      226914 :     }
     513                 :      226268 :     bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache) const override
     514                 :             :     {
     515         [ +  + ]:      226268 :         if (m_derive == DeriveType::HARDENED) {
     516                 :       13352 :             out = ToString(StringType::PUBLIC, /*normalized=*/true);
     517                 :             : 
     518                 :       13352 :             return true;
     519                 :             :         }
     520                 :             :         // Step backwards to find the last hardened step in the path
     521         [ -  + ]:      212916 :         int i = (int)m_path.size() - 1;
     522         [ +  + ]:      366868 :         for (; i >= 0; --i) {
     523         [ +  + ]:      178003 :             if (m_path.at(i) >> 31) {
     524                 :             :                 break;
     525                 :             :             }
     526                 :             :         }
     527                 :             :         // Either no derivation or all unhardened derivation
     528         [ +  + ]:      212916 :         if (i == -1) {
     529                 :      188865 :             out = ToString();
     530                 :      188865 :             return true;
     531                 :             :         }
     532                 :             :         // Get the path to the last hardened stup
     533                 :       24051 :         KeyOriginInfo origin;
     534                 :       24051 :         int k = 0;
     535         [ +  + ]:       53971 :         for (; k <= i; ++k) {
     536                 :             :             // Add to the path
     537   [ +  -  +  - ]:       29920 :             origin.path.push_back(m_path.at(k));
     538                 :             :         }
     539                 :             :         // Build the remaining path
     540                 :       24051 :         KeyPath end_path;
     541   [ -  +  +  + ]:       27110 :         for (; k < (int)m_path.size(); ++k) {
     542   [ +  -  +  - ]:        3059 :             end_path.push_back(m_path.at(k));
     543                 :             :         }
     544                 :             :         // Get the fingerprint
     545         [ +  - ]:       24051 :         CKeyID id = m_root_extkey.pubkey.GetID();
     546                 :       24051 :         std::copy(id.begin(), id.begin() + 4, origin.fingerprint);
     547                 :             : 
     548         [ +  + ]:       24051 :         CExtPubKey xpub;
     549         [ +  + ]:       24051 :         CExtKey lh_xprv;
     550                 :             :         // If we have the cache, just get the parent xpub
     551         [ +  + ]:       24051 :         if (cache != nullptr) {
     552         [ +  - ]:        2896 :             cache->GetCachedLastHardenedExtPubKey(m_expr_index, xpub);
     553                 :             :         }
     554         [ +  + ]:       24051 :         if (!xpub.pubkey.IsValid()) {
     555                 :             :             // Cache miss, or nor cache, or need privkey
     556         [ +  - ]:       21155 :             CExtKey xprv;
     557   [ +  -  +  + ]:       21155 :             if (!GetDerivedExtKey(arg, xprv, lh_xprv)) return false;
     558         [ +  - ]:       20649 :             xpub = lh_xprv.Neuter();
     559                 :       21155 :         }
     560         [ -  + ]:       23545 :         assert(xpub.pubkey.IsValid());
     561                 :             : 
     562                 :             :         // Build the string
     563   [ +  -  +  -  :       47090 :         std::string origin_str = HexStr(origin.fingerprint) + FormatHDKeypath(origin.path);
                   +  - ]
     564   [ +  -  +  -  :       47090 :         out = "[" + origin_str + "]" + EncodeExtPubKey(xpub) + FormatHDKeypath(end_path);
          +  -  +  -  +  
                      - ]
     565         [ +  + ]:       23545 :         if (IsRange()) {
     566         [ +  - ]:         379 :             out += "/*";
     567         [ -  + ]:         379 :             assert(m_derive == DeriveType::UNHARDENED);
     568                 :             :         }
     569                 :       23545 :         return true;
     570                 :       47596 :     }
     571                 :      218800 :     void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const override
     572                 :             :     {
     573         [ +  - ]:      218800 :         CExtKey extkey;
     574                 :      218800 :         CExtKey dummy;
     575   [ +  -  +  + ]:      218800 :         if (!GetDerivedExtKey(arg, extkey, dummy)) return;
     576   [ +  +  +  -  :      172051 :         if (m_derive == DeriveType::UNHARDENED && !extkey.Derive(extkey, pos)) return;
                   +  - ]
     577   [ +  +  +  -  :      172051 :         if (m_derive == DeriveType::HARDENED && !extkey.Derive(extkey, pos | 0x80000000UL)) return;
                   +  - ]
     578   [ +  -  +  -  :      172051 :         out.keys.emplace(extkey.key.GetPubKey().GetID(), extkey.key);
                   +  - ]
     579                 :      218800 :     }
     580                 :           0 :     std::optional<CPubKey> GetRootPubKey() const override
     581                 :             :     {
     582                 :           0 :         return std::nullopt;
     583                 :             :     }
     584                 :           0 :     std::optional<CExtPubKey> GetRootExtPubKey() const override
     585                 :             :     {
     586                 :           0 :         return m_root_extkey;
     587                 :             :     }
     588                 :      154576 :     std::unique_ptr<PubkeyProvider> Clone() const override
     589                 :             :     {
     590         [ -  + ]:      154576 :         return std::make_unique<BIP32PubkeyProvider>(m_expr_index, m_root_extkey, m_path, m_derive, m_apostrophe);
     591                 :             :     }
     592                 :             : };
     593                 :             : 
     594                 :             : /** PubkeyProvider for a musig() expression */
     595                 :             : class MuSigPubkeyProvider final : public PubkeyProvider
     596                 :             : {
     597                 :             : private:
     598                 :             :     //! PubkeyProvider for the participants
     599                 :             :     const std::vector<std::unique_ptr<PubkeyProvider>> m_participants;
     600                 :             :     //! Derivation path
     601                 :             :     const KeyPath m_path;
     602                 :             :     //! PubkeyProvider for the aggregate pubkey if it can be cached (i.e. participants are not ranged)
     603                 :             :     mutable std::unique_ptr<PubkeyProvider> m_aggregate_provider;
     604                 :             :     mutable std::optional<CPubKey> m_aggregate_pubkey;
     605                 :             :     const DeriveType m_derive;
     606                 :             :     const bool m_ranged_participants;
     607                 :             : 
     608                 :       52671 :     bool IsRangedDerivation() const { return m_derive != DeriveType::NO; }
     609                 :             : 
     610                 :             : public:
     611                 :        9217 :     MuSigPubkeyProvider(
     612                 :             :         uint32_t exp_index,
     613                 :             :         std::vector<std::unique_ptr<PubkeyProvider>> providers,
     614                 :             :         KeyPath path,
     615                 :             :         DeriveType derive
     616                 :             :     )
     617                 :        9217 :         : PubkeyProvider(exp_index),
     618                 :        9217 :         m_participants(std::move(providers)),
     619         [ +  - ]:        9217 :         m_path(std::move(path)),
     620         [ +  - ]:        9217 :         m_derive(derive),
     621         [ +  - ]:       73730 :         m_ranged_participants(std::any_of(m_participants.begin(), m_participants.end(), [](const auto& pubkey) { return pubkey->IsRange(); }))
     622                 :             :     {
     623   [ +  +  +  -  :       10201 :         if (!Assume(!(m_ranged_participants && IsRangedDerivation()))) {
                   +  - ]
     624         [ #  # ]:           0 :             throw std::runtime_error("musig(): Cannot have both ranged participants and ranged derivation");
     625                 :             :         }
     626         [ +  - ]:        9217 :         if (!Assume(m_derive != DeriveType::HARDENED)) {
     627         [ #  # ]:           0 :             throw std::runtime_error("musig(): Cannot have hardened derivation");
     628                 :             :         }
     629                 :        9217 :     }
     630                 :             : 
     631                 :       26273 :     std::optional<CPubKey> GetPubKey(int pos, const SigningProvider& arg, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
     632                 :             :     {
     633                 :       26273 :         FlatSigningProvider dummy;
     634                 :             :         // If the participants are not ranged, we can compute and cache the aggregate pubkey by creating a PubkeyProvider for it
     635   [ +  +  +  + ]:       26273 :         if (!m_aggregate_provider && !m_ranged_participants) {
     636                 :             :             // Retrieve the pubkeys from the providers
     637                 :        6821 :             std::vector<CPubKey> pubkeys;
     638         [ +  + ]:       59103 :             for (const auto& prov : m_participants) {
     639         [ +  - ]:       52633 :                 std::optional<CPubKey> pubkey = prov->GetPubKey(0, arg, dummy, read_cache, write_cache);
     640         [ +  + ]:       52633 :                 if (!pubkey.has_value()) {
     641                 :         351 :                     return std::nullopt;
     642                 :             :                 }
     643         [ +  - ]:       52282 :                 pubkeys.push_back(pubkey.value());
     644                 :             :             }
     645                 :        6470 :             std::sort(pubkeys.begin(), pubkeys.end());
     646                 :             : 
     647                 :             :             // Aggregate the pubkey
     648         [ +  - ]:        6470 :             m_aggregate_pubkey = MuSig2AggregatePubkeys(pubkeys);
     649         [ +  - ]:        6470 :             if (!Assume(m_aggregate_pubkey.has_value())) return std::nullopt;
     650                 :             : 
     651                 :             :             // Make our pubkey provider
     652   [ +  +  +  + ]:        6470 :             if (IsRangedDerivation() || !m_path.empty()) {
     653                 :             :                 // Make the synthetic xpub and construct the BIP32PubkeyProvider
     654         [ +  - ]:         781 :                 CExtPubKey extpub = CreateMuSig2SyntheticXpub(m_aggregate_pubkey.value());
     655   [ +  -  -  + ]:         781 :                 m_aggregate_provider = std::make_unique<BIP32PubkeyProvider>(m_expr_index, extpub, m_path, m_derive, /*apostrophe=*/false);
     656                 :             :             } else {
     657         [ +  - ]:        5689 :                 m_aggregate_provider = std::make_unique<ConstPubkeyProvider>(m_expr_index, m_aggregate_pubkey.value(), /*xonly=*/false);
     658                 :             :             }
     659                 :        6821 :         }
     660                 :             : 
     661                 :             :         // Retrieve all participant pubkeys
     662                 :       25922 :         std::vector<CPubKey> pubkeys;
     663         [ +  + ]:      580766 :         for (const auto& prov : m_participants) {
     664         [ +  - ]:      557124 :             std::optional<CPubKey> pub = prov->GetPubKey(pos, arg, out, read_cache, write_cache);
     665         [ +  + ]:      557124 :             if (!pub) return std::nullopt;
     666         [ +  - ]:      554844 :             pubkeys.emplace_back(*pub);
     667                 :             :         }
     668                 :       23642 :         std::sort(pubkeys.begin(), pubkeys.end());
     669                 :             : 
     670         [ +  + ]:       23642 :         CPubKey pubout;
     671         [ +  + ]:       23642 :         if (m_aggregate_provider) {
     672                 :             :             // When we have a cached aggregate key, we are either returning it or deriving from it
     673                 :             :             // Either way, we can passthrough to its GetPubKey
     674                 :             :             // Use a dummy signing provider as private keys do not exist for the aggregate pubkey
     675         [ +  - ]:       17468 :             std::optional<CPubKey> pub = m_aggregate_provider->GetPubKey(pos, dummy, out, read_cache, write_cache);
     676         [ -  + ]:       17468 :             if (!pub) return std::nullopt;
     677         [ +  - ]:       17468 :             pubout = *pub;
     678   [ +  -  +  - ]:       17468 :             out.aggregate_pubkeys.emplace(m_aggregate_pubkey.value(), pubkeys);
     679                 :             :         } else {
     680   [ -  +  +  -  :        6174 :             if (!Assume(m_ranged_participants) || !Assume(m_path.empty())) return std::nullopt;
                   +  - ]
     681                 :             :             // Compute aggregate key from derived participants
     682         [ +  - ]:        6174 :             std::optional<CPubKey> aggregate_pubkey = MuSig2AggregatePubkeys(pubkeys);
     683         [ -  + ]:        6174 :             if (!aggregate_pubkey) return std::nullopt;
     684         [ +  - ]:        6174 :             pubout = *aggregate_pubkey;
     685                 :             : 
     686         [ +  - ]:        6174 :             std::unique_ptr<ConstPubkeyProvider> this_agg_provider = std::make_unique<ConstPubkeyProvider>(m_expr_index, aggregate_pubkey.value(), /*xonly=*/false);
     687         [ +  - ]:        6174 :             this_agg_provider->GetPubKey(0, dummy, out, read_cache, write_cache);
     688         [ +  - ]:        6174 :             out.aggregate_pubkeys.emplace(pubout, pubkeys);
     689                 :        6174 :         }
     690                 :             : 
     691         [ +  - ]:       23642 :         if (!Assume(pubout.IsValid())) return std::nullopt;
     692                 :       23642 :         return pubout;
     693                 :       26273 :     }
     694   [ +  +  +  + ]:       21131 :     bool IsRange() const override { return IsRangedDerivation() || m_ranged_participants; }
     695                 :             :     // musig() expressions can only be used in tr() contexts which have 32 byte xonly pubkeys
     696                 :        4145 :     size_t GetSize() const override { return 32; }
     697                 :             : 
     698                 :       15276 :     std::string ToString(StringType type=StringType::PUBLIC) const override
     699                 :             :     {
     700                 :       15276 :         std::string out = "musig(";
     701   [ -  +  +  + ]:      403576 :         for (size_t i = 0; i < m_participants.size(); ++i) {
     702         [ +  - ]:      388300 :             const auto& pubkey = m_participants.at(i);
     703   [ +  +  +  - ]:      388300 :             if (i) out += ",";
     704         [ +  - ]:      776600 :             out += pubkey->ToString(type);
     705                 :             :         }
     706         [ +  - ]:       15276 :         out += ")";
     707         [ +  - ]:       30552 :         out += FormatHDKeypath(m_path);
     708         [ +  + ]:       15276 :         if (IsRangedDerivation()) {
     709         [ +  - ]:         630 :             out += "/*";
     710                 :             :         }
     711                 :       15276 :         return out;
     712                 :           0 :     }
     713                 :        4428 :     bool ToPrivateString(const SigningProvider& arg, std::string& out) const override
     714                 :             :     {
     715                 :        4428 :         bool any_privkeys = false;
     716                 :        4428 :         out = "musig(";
     717   [ -  +  +  + ]:       58223 :         for (size_t i = 0; i < m_participants.size(); ++i) {
     718                 :       53795 :             const auto& pubkey = m_participants.at(i);
     719         [ +  + ]:       53795 :             if (i) out += ",";
     720         [ +  - ]:       53795 :             std::string tmp;
     721   [ +  -  +  + ]:       53795 :             if (pubkey->ToPrivateString(arg, tmp)) {
     722                 :       30416 :                 any_privkeys = true;
     723                 :             :             }
     724         [ -  + ]:      107590 :             out += tmp;
     725                 :       53795 :         }
     726                 :        4428 :         out += ")";
     727         [ -  + ]:        8856 :         out += FormatHDKeypath(m_path);
     728         [ +  + ]:        4428 :         if (IsRangedDerivation()) {
     729                 :         339 :             out += "/*";
     730                 :             :         }
     731                 :        4428 :         return any_privkeys;
     732                 :             :     }
     733                 :        4545 :     bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache = nullptr) const override
     734                 :             :     {
     735                 :        4545 :         out = "musig(";
     736   [ -  +  +  + ]:       59803 :         for (size_t i = 0; i < m_participants.size(); ++i) {
     737                 :       55421 :             const auto& pubkey = m_participants.at(i);
     738         [ +  + ]:       55421 :             if (i) out += ",";
     739         [ +  - ]:       55421 :             std::string tmp;
     740   [ +  -  +  + ]:       55421 :             if (!pubkey->ToNormalizedString(arg, tmp, cache)) {
     741                 :         163 :                 return false;
     742                 :             :             }
     743         [ -  + ]:      110516 :             out += tmp;
     744                 :       55421 :         }
     745                 :        4382 :         out += ")";
     746         [ -  + ]:        8764 :         out += FormatHDKeypath(m_path);
     747         [ +  + ]:        4382 :         if (IsRangedDerivation()) {
     748                 :         330 :             out += "/*";
     749                 :             :         }
     750                 :             :         return true;
     751                 :             :     }
     752                 :             : 
     753                 :        4290 :     void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const override
     754                 :             :     {
     755                 :             :         // Get the private keys for any participants that we have
     756                 :             :         // If there is participant derivation, it will be done.
     757                 :             :         // If there is not, then the participant privkeys will be included directly
     758         [ +  + ]:       51663 :         for (const auto& prov : m_participants) {
     759                 :       47373 :             prov->GetPrivKey(pos, arg, out);
     760                 :             :         }
     761                 :        4290 :     }
     762                 :             : 
     763                 :             :     // Get RootPubKey and GetRootExtPubKey are used to return the single pubkey underlying the pubkey provider
     764                 :             :     // to be presented to the user in gethdkeys. As this is a multisig construction, there is no single underlying
     765                 :             :     // pubkey hence nothing should be returned.
     766                 :             :     // While the aggregate pubkey could be returned as the root (ext)pubkey, it is not a pubkey that anyone should
     767                 :             :     // be using by itself in a descriptor as it is unspendable without knowing its participants.
     768                 :           0 :     std::optional<CPubKey> GetRootPubKey() const override
     769                 :             :     {
     770                 :           0 :         return std::nullopt;
     771                 :             :     }
     772                 :           0 :     std::optional<CExtPubKey> GetRootExtPubKey() const override
     773                 :             :     {
     774                 :           0 :         return std::nullopt;
     775                 :             :     }
     776                 :             : 
     777                 :        1729 :     std::unique_ptr<PubkeyProvider> Clone() const override
     778                 :             :     {
     779                 :        1729 :         std::vector<std::unique_ptr<PubkeyProvider>> providers;
     780   [ -  +  +  - ]:        1729 :         providers.reserve(m_participants.size());
     781         [ +  + ]:        6533 :         for (const std::unique_ptr<PubkeyProvider>& p : m_participants) {
     782   [ +  -  +  - ]:        4804 :             providers.emplace_back(p->Clone());
     783                 :             :         }
     784   [ +  -  -  + ]:        3458 :         return std::make_unique<MuSigPubkeyProvider>(m_expr_index, std::move(providers), m_path, m_derive);
     785                 :        1729 :     }
     786                 :           0 :     bool IsBIP32() const override
     787                 :             :     {
     788                 :             :         // musig() can only be a BIP 32 key if all participants are bip32 too
     789                 :           0 :         return std::all_of(m_participants.begin(), m_participants.end(), [](const auto& pubkey) { return pubkey->IsBIP32(); });
     790                 :             :     }
     791                 :             : };
     792                 :             : 
     793                 :             : /** Base class for all Descriptor implementations. */
     794                 :             : class DescriptorImpl : public Descriptor
     795                 :             : {
     796                 :             : protected:
     797                 :             :     //! Public key arguments for this descriptor (size 1 for PK, PKH, WPKH; any size for WSH and Multisig).
     798                 :             :     const std::vector<std::unique_ptr<PubkeyProvider>> m_pubkey_args;
     799                 :             :     //! The string name of the descriptor function.
     800                 :             :     const std::string m_name;
     801                 :             :     //! Warnings (not including subdescriptors).
     802                 :             :     std::vector<std::string> m_warnings;
     803                 :             : 
     804                 :             :     //! The sub-descriptor arguments (empty for everything but SH and WSH).
     805                 :             :     //! In doc/descriptors.m this is referred to as SCRIPT expressions sh(SCRIPT)
     806                 :             :     //! and wsh(SCRIPT), and distinct from KEY expressions and ADDR expressions.
     807                 :             :     //! Subdescriptors can only ever generate a single script.
     808                 :             :     const std::vector<std::unique_ptr<DescriptorImpl>> m_subdescriptor_args;
     809                 :             : 
     810                 :             :     //! Return a serialization of anything except pubkey and script arguments, to be prepended to those.
     811                 :      690902 :     virtual std::string ToStringExtra() const { return ""; }
     812                 :             : 
     813                 :             :     /** A helper function to construct the scripts for this descriptor.
     814                 :             :      *
     815                 :             :      *  This function is invoked once by ExpandHelper.
     816                 :             :      *
     817                 :             :      *  @param pubkeys The evaluations of the m_pubkey_args field.
     818                 :             :      *  @param scripts The evaluations of m_subdescriptor_args (one for each m_subdescriptor_args element).
     819                 :             :      *  @param out A FlatSigningProvider to put scripts or public keys in that are necessary to the solver.
     820                 :             :      *             The origin info of the provided pubkeys is automatically added.
     821                 :             :      *  @return A vector with scriptPubKeys for this descriptor.
     822                 :             :      */
     823                 :             :     virtual std::vector<CScript> MakeScripts(const std::vector<CPubKey>& pubkeys, std::span<const CScript> scripts, FlatSigningProvider& out) const = 0;
     824                 :             : 
     825                 :             : public:
     826         [ -  + ]:     3495488 :     DescriptorImpl(std::vector<std::unique_ptr<PubkeyProvider>> pubkeys, const std::string& name) : m_pubkey_args(std::move(pubkeys)), m_name(name), m_subdescriptor_args() {}
     827   [ -  +  +  - ]:       36230 :     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))) {}
     828         [ -  + ]:       39148 :     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)) {}
     829                 :             : 
     830                 :             :     enum class StringType
     831                 :             :     {
     832                 :             :         PUBLIC,
     833                 :             :         PRIVATE,
     834                 :             :         NORMALIZED,
     835                 :             :         COMPAT, // string calculation that mustn't change over time to stay compatible with previous software versions
     836                 :             :     };
     837                 :             : 
     838                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     839                 :       20568 :     bool IsSolvable() const override
     840                 :             :     {
     841         [ +  + ]:       38012 :         for (const auto& arg : m_subdescriptor_args) {
     842         [ +  - ]:       17444 :             if (!arg->IsSolvable()) return false;
     843                 :             :         }
     844                 :             :         return true;
     845                 :             :     }
     846                 :             : 
     847                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     848                 :           0 :     bool HavePrivateKeys(const SigningProvider& arg) const override
     849                 :             :     {
     850   [ #  #  #  # ]:           0 :         if (m_pubkey_args.empty() && m_subdescriptor_args.empty()) return false;
     851                 :             : 
     852         [ #  # ]:           0 :         for (const auto& sub: m_subdescriptor_args) {
     853         [ #  # ]:           0 :             if (!sub->HavePrivateKeys(arg)) return false;
     854                 :             :         }
     855                 :             : 
     856                 :           0 :         FlatSigningProvider tmp_provider;
     857         [ #  # ]:           0 :         for (const auto& pubkey : m_pubkey_args) {
     858                 :           0 :             tmp_provider.keys.clear();
     859         [ #  # ]:           0 :             pubkey->GetPrivKey(0, arg, tmp_provider);
     860         [ #  # ]:           0 :             if (tmp_provider.keys.empty()) return false;
     861                 :             :         }
     862                 :             : 
     863                 :             :         return true;
     864                 :           0 :     }
     865                 :             : 
     866                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     867                 :      707068 :     bool IsRange() const final
     868                 :             :     {
     869         [ +  + ]:     1428313 :         for (const auto& pubkey : m_pubkey_args) {
     870         [ +  + ]:     1159809 :             if (pubkey->IsRange()) return true;
     871                 :             :         }
     872         [ +  + ]:      315763 :         for (const auto& arg : m_subdescriptor_args) {
     873         [ +  + ]:      221305 :             if (arg->IsRange()) return true;
     874                 :             :         }
     875                 :             :         return false;
     876                 :             :     }
     877                 :             : 
     878                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     879                 :     2196204 :     virtual bool ToStringSubScriptHelper(const SigningProvider* arg, std::string& ret, const StringType type, const DescriptorCache* cache = nullptr) const
     880                 :             :     {
     881                 :     2196204 :         size_t pos = 0;
     882                 :     2196204 :         bool is_private{type == StringType::PRIVATE};
     883                 :             :         // For private string output, track if at least one key has a private key available.
     884                 :             :         // Initialize to true for non-private types.
     885                 :     2196204 :         bool any_success{!is_private};
     886         [ +  + ]:     2370611 :         for (const auto& scriptarg : m_subdescriptor_args) {
     887         [ -  + ]:      174606 :             if (pos++) ret += ",";
     888         [ +  - ]:      174606 :             std::string tmp;
     889         [ +  - ]:      174606 :             bool subscript_res{scriptarg->ToStringHelper(arg, tmp, type, cache)};
     890         [ +  + ]:      174606 :             if (!is_private && !subscript_res) return false;
     891                 :      174407 :             any_success = any_success || subscript_res;
     892         [ -  + ]:      348814 :             ret += tmp;
     893                 :      174606 :         }
     894                 :             :         return any_success;
     895                 :             :     }
     896                 :             : 
     897                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     898                 :     2356146 :     virtual bool ToStringHelper(const SigningProvider* arg, std::string& out, const StringType type, const DescriptorCache* cache = nullptr) const
     899                 :             :     {
     900                 :     2356146 :         std::string extra = ToStringExtra();
     901   [ -  +  +  + ]:     2356146 :         size_t pos = extra.size() > 0 ? 1 : 0;
     902   [ +  -  +  - ]:     2356146 :         std::string ret = m_name + "(" + extra;
     903                 :     2356146 :         bool is_private{type == StringType::PRIVATE};
     904                 :             :         // For private string output, track if at least one key has a private key available.
     905                 :             :         // Initialize to true for non-private types.
     906                 :     2356146 :         bool any_success{!is_private};
     907                 :             : 
     908         [ +  + ]:     5305286 :         for (const auto& pubkey : m_pubkey_args) {
     909   [ +  +  +  - ]:     2949577 :             if (pos++) ret += ",";
     910   [ +  +  +  +  :     2949577 :             std::string tmp;
                      - ]
     911   [ +  +  +  +  :     2949577 :             switch (type) {
                      - ]
     912                 :      275246 :                 case StringType::NORMALIZED:
     913   [ +  -  +  + ]:      275246 :                     if (!pubkey->ToNormalizedString(*arg, tmp, cache)) return false;
     914                 :             :                     break;
     915                 :      263841 :                 case StringType::PRIVATE:
     916   [ +  -  +  +  :      263841 :                     any_success = pubkey->ToPrivateString(*arg, tmp) || any_success;
                   +  + ]
     917                 :             :                     break;
     918                 :     2300684 :                 case StringType::PUBLIC:
     919         [ +  - ]:     2300684 :                     tmp = pubkey->ToString();
     920                 :     2300684 :                     break;
     921                 :      109806 :                 case StringType::COMPAT:
     922         [ +  - ]:      109806 :                     tmp = pubkey->ToString(PubkeyProvider::StringType::COMPAT);
     923                 :      109806 :                     break;
     924                 :             :             }
     925         [ -  + ]:     5898280 :             ret += tmp;
     926                 :     2949577 :         }
     927         [ +  - ]:     4711418 :         std::string subscript;
     928         [ +  - ]:     2355709 :         bool subscript_res{ToStringSubScriptHelper(arg, subscript, type, cache)};
     929         [ +  + ]:     2355709 :         if (!is_private && !subscript_res) return false;
     930                 :     2355404 :         any_success = any_success || subscript_res;
     931   [ +  +  +  +  :     4253798 :         if (pos && subscript.size()) ret += ',';
                   +  - ]
     932         [ +  - ]:     4710808 :         out = std::move(ret) + std::move(subscript) + ")";
     933                 :     2355404 :         return any_success;
     934                 :     2356146 :     }
     935                 :             : 
     936                 :     2134893 :     std::string ToString(bool compat_format) const final
     937                 :             :     {
     938         [ +  + ]:     2134893 :         std::string ret;
     939   [ +  +  +  - ]:     4245595 :         ToStringHelper(nullptr, ret, compat_format ? StringType::COMPAT : StringType::PUBLIC);
     940         [ +  - ]:     2134893 :         return AddChecksum(ret);
     941                 :     2134893 :     }
     942                 :             : 
     943                 :       14707 :     bool ToPrivateString(const SigningProvider& arg, std::string& out) const override
     944                 :             :     {
     945                 :       14707 :         bool has_priv_key{ToStringHelper(&arg, out, StringType::PRIVATE)};
     946                 :       14707 :         out = AddChecksum(out);
     947                 :       14707 :         return has_priv_key;
     948                 :             :     }
     949                 :             : 
     950                 :       21572 :     bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache) const override final
     951                 :             :     {
     952                 :       21572 :         bool ret = ToStringHelper(&arg, out, StringType::NORMALIZED, cache);
     953                 :       21572 :         out = AddChecksum(out);
     954                 :       21572 :         return ret;
     955                 :             :     }
     956                 :             : 
     957                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     958                 :      690858 :     bool ExpandHelper(int pos, const SigningProvider& arg, const DescriptorCache* read_cache, std::vector<CScript>& output_scripts, FlatSigningProvider& out, DescriptorCache* write_cache) const
     959                 :             :     {
     960                 :      690858 :         FlatSigningProvider subprovider;
     961                 :      690858 :         std::vector<CPubKey> pubkeys;
     962   [ -  +  +  - ]:      690858 :         pubkeys.reserve(m_pubkey_args.size());
     963                 :             : 
     964                 :             :         // Construct temporary data in `pubkeys`, `subscripts`, and `subprovider` to avoid producing output in case of failure.
     965         [ +  + ]:     3524437 :         for (const auto& p : m_pubkey_args) {
     966         [ +  - ]:     2861166 :             std::optional<CPubKey> pubkey = p->GetPubKey(pos, arg, subprovider, read_cache, write_cache);
     967         [ +  + ]:     2861166 :             if (!pubkey) return false;
     968         [ +  - ]:     2833579 :             pubkeys.push_back(pubkey.value());
     969                 :             :         }
     970                 :      663271 :         std::vector<CScript> subscripts;
     971         [ +  + ]:      874331 :         for (const auto& subarg : m_subdescriptor_args) {
     972                 :      222077 :             std::vector<CScript> outscripts;
     973   [ +  -  +  + ]:      222077 :             if (!subarg->ExpandHelper(pos, arg, read_cache, outscripts, subprovider, write_cache)) return false;
     974   [ -  +  -  + ]:      211060 :             assert(outscripts.size() == 1);
     975         [ +  - ]:      211060 :             subscripts.emplace_back(std::move(outscripts[0]));
     976                 :      222077 :         }
     977         [ +  - ]:      652254 :         out.Merge(std::move(subprovider));
     978                 :             : 
     979   [ -  +  +  - ]:      652254 :         output_scripts = MakeScripts(pubkeys, std::span{subscripts}, out);
     980                 :      652254 :         return true;
     981                 :     1354129 :     }
     982                 :             : 
     983                 :       44425 :     bool Expand(int pos, const SigningProvider& provider, std::vector<CScript>& output_scripts, FlatSigningProvider& out, DescriptorCache* write_cache = nullptr) const final
     984                 :             :     {
     985                 :       44425 :         return ExpandHelper(pos, provider, nullptr, output_scripts, out, write_cache);
     986                 :             :     }
     987                 :             : 
     988                 :      424356 :     bool ExpandFromCache(int pos, const DescriptorCache& read_cache, std::vector<CScript>& output_scripts, FlatSigningProvider& out) const final
     989                 :             :     {
     990                 :      424356 :         return ExpandHelper(pos, DUMMY_SIGNING_PROVIDER, &read_cache, output_scripts, out, nullptr);
     991                 :             :     }
     992                 :             : 
     993                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     994                 :       40938 :     void ExpandPrivate(int pos, const SigningProvider& provider, FlatSigningProvider& out) const final
     995                 :             :     {
     996         [ +  + ]:      308108 :         for (const auto& p : m_pubkey_args) {
     997                 :      267170 :             p->GetPrivKey(pos, provider, out);
     998                 :             :         }
     999         [ +  + ]:       58815 :         for (const auto& arg : m_subdescriptor_args) {
    1000                 :       17877 :             arg->ExpandPrivate(pos, provider, out);
    1001                 :             :         }
    1002                 :       40938 :     }
    1003                 :             : 
    1004                 :        8830 :     std::optional<OutputType> GetOutputType() const override { return std::nullopt; }
    1005                 :             : 
    1006                 :           0 :     std::optional<int64_t> ScriptSize() const override { return {}; }
    1007                 :             : 
    1008                 :             :     /** A helper for MaxSatisfactionWeight.
    1009                 :             :      *
    1010                 :             :      * @param use_max_sig Whether to assume ECDSA signatures will have a high-r.
    1011                 :             :      * @return The maximum size of the satisfaction in raw bytes (with no witness meaning).
    1012                 :             :      */
    1013                 :           0 :     virtual std::optional<int64_t> MaxSatSize(bool use_max_sig) const { return {}; }
    1014                 :             : 
    1015                 :        1410 :     std::optional<int64_t> MaxSatisfactionWeight(bool) const override { return {}; }
    1016                 :             : 
    1017                 :         705 :     std::optional<int64_t> MaxSatisfactionElems() const override { return {}; }
    1018                 :             : 
    1019                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
    1020                 :           0 :     void GetPubKeys(std::set<CPubKey>& pubkeys, std::set<CExtPubKey>& ext_pubs) const override
    1021                 :             :     {
    1022         [ #  # ]:           0 :         for (const auto& p : m_pubkey_args) {
    1023                 :           0 :             std::optional<CPubKey> pub = p->GetRootPubKey();
    1024         [ #  # ]:           0 :             if (pub) pubkeys.insert(*pub);
    1025                 :           0 :             std::optional<CExtPubKey> ext_pub = p->GetRootExtPubKey();
    1026         [ #  # ]:           0 :             if (ext_pub) ext_pubs.insert(*ext_pub);
    1027                 :             :         }
    1028         [ #  # ]:           0 :         for (const auto& arg : m_subdescriptor_args) {
    1029                 :           0 :             arg->GetPubKeys(pubkeys, ext_pubs);
    1030                 :             :         }
    1031                 :           0 :     }
    1032                 :             : 
    1033                 :             :     virtual std::unique_ptr<DescriptorImpl> Clone() const = 0;
    1034                 :             : 
    1035                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
    1036                 :           0 :     std::vector<std::string> Warnings() const override {
    1037                 :           0 :         std::vector<std::string> all = m_warnings;
    1038         [ #  # ]:           0 :         for (const auto& sub : m_subdescriptor_args) {
    1039         [ #  # ]:           0 :             auto sub_w = sub->Warnings();
    1040         [ #  # ]:           0 :             all.insert(all.end(), sub_w.begin(), sub_w.end());
    1041                 :           0 :         }
    1042                 :           0 :         return all;
    1043                 :           0 :     }
    1044                 :             : };
    1045                 :             : 
    1046                 :             : /** A parsed addr(A) descriptor. */
    1047                 :             : class AddressDescriptor final : public DescriptorImpl
    1048                 :             : {
    1049                 :             :     const CTxDestination m_destination;
    1050                 :             : protected:
    1051                 :      363947 :     std::string ToStringExtra() const override { return EncodeDestination(m_destination); }
    1052         [ +  - ]:         128 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, std::span<const CScript>, FlatSigningProvider&) const override { return Vector(GetScriptForDestination(m_destination)); }
    1053                 :             : public:
    1054         [ +  - ]:      364050 :     AddressDescriptor(CTxDestination destination) : DescriptorImpl({}, "addr"), m_destination(std::move(destination)) {}
    1055                 :           0 :     bool IsSolvable() const final { return false; }
    1056                 :             : 
    1057                 :         105 :     std::optional<OutputType> GetOutputType() const override
    1058                 :             :     {
    1059                 :         105 :         return OutputTypeFromDestination(m_destination);
    1060                 :             :     }
    1061                 :         210 :     bool IsSingleType() const final { return true; }
    1062                 :           5 :     bool ToPrivateString(const SigningProvider& arg, std::string& out) const final { return false; }
    1063                 :             : 
    1064         [ #  # ]:           0 :     std::optional<int64_t> ScriptSize() const override { return GetScriptForDestination(m_destination).size(); }
    1065                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1066                 :             :     {
    1067         [ #  # ]:           0 :         return std::make_unique<AddressDescriptor>(m_destination);
    1068                 :             :     }
    1069                 :             : };
    1070                 :             : 
    1071                 :             : /** A parsed raw(H) descriptor. */
    1072                 :             : class RawDescriptor final : public DescriptorImpl
    1073                 :             : {
    1074                 :             :     const CScript m_script;
    1075                 :             : protected:
    1076         [ +  + ]:     2501044 :     std::string ToStringExtra() const override { return HexStr(m_script); }
    1077                 :        6021 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, std::span<const CScript>, FlatSigningProvider&) const override { return Vector(m_script); }
    1078                 :             : public:
    1079         [ +  - ]:     1245275 :     RawDescriptor(CScript script) : DescriptorImpl({}, "raw"), m_script(std::move(script)) {}
    1080                 :         326 :     bool IsSolvable() const final { return false; }
    1081                 :             : 
    1082                 :        5134 :     std::optional<OutputType> GetOutputType() const override
    1083                 :             :     {
    1084                 :        5134 :         CTxDestination dest;
    1085         [ +  - ]:        5134 :         ExtractDestination(m_script, dest);
    1086         [ +  - ]:        5134 :         return OutputTypeFromDestination(dest);
    1087                 :        5134 :     }
    1088                 :        6025 :     bool IsSingleType() const final { return true; }
    1089                 :         744 :     bool ToPrivateString(const SigningProvider& arg, std::string& out) const final { return false; }
    1090                 :             : 
    1091         [ +  + ]:         324 :     std::optional<int64_t> ScriptSize() const override { return m_script.size(); }
    1092                 :             : 
    1093                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1094                 :             :     {
    1095         [ #  # ]:           0 :         return std::make_unique<RawDescriptor>(m_script);
    1096                 :             :     }
    1097                 :             : };
    1098                 :             : 
    1099                 :             : /** A parsed pk(P) descriptor. */
    1100                 :             : class PKDescriptor final : public DescriptorImpl
    1101                 :             : {
    1102                 :             : private:
    1103                 :             :     const bool m_xonly;
    1104                 :             : protected:
    1105                 :       19907 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override
    1106                 :             :     {
    1107         [ +  + ]:       19907 :         if (m_xonly) {
    1108   [ +  -  +  - ]:       30384 :             CScript script = CScript() << ToByteVector(XOnlyPubKey(keys[0])) << OP_CHECKSIG;
    1109         [ +  - ]:       15192 :             return Vector(std::move(script));
    1110                 :       15192 :         } else {
    1111         [ +  - ]:        9430 :             return Vector(GetScriptForRawPubKey(keys[0]));
    1112                 :             :         }
    1113                 :             :     }
    1114                 :             : public:
    1115   [ +  -  +  - ]:       44256 :     PKDescriptor(std::unique_ptr<PubkeyProvider> prov, bool xonly = false) : DescriptorImpl(Vector(std::move(prov)), "pk"), m_xonly(xonly) {}
    1116                 :         806 :     bool IsSingleType() const final { return true; }
    1117                 :             : 
    1118                 :         926 :     std::optional<int64_t> ScriptSize() const override {
    1119         [ +  - ]:         926 :         return 1 + (m_xonly ? 32 : m_pubkey_args[0]->GetSize()) + 1;
    1120                 :             :     }
    1121                 :             : 
    1122                 :        1178 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
    1123         [ -  + ]:         696 :         const auto ecdsa_sig_size = use_max_sig ? 72 : 71;
    1124   [ +  -  +  - ]:        1178 :         return 1 + (m_xonly ? 65 : ecdsa_sig_size);
    1125                 :             :     }
    1126                 :             : 
    1127                 :         482 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
    1128         [ -  + ]:         482 :         return *MaxSatSize(use_max_sig) * WITNESS_SCALE_FACTOR;
    1129                 :             :     }
    1130                 :             : 
    1131                 :         589 :     std::optional<int64_t> MaxSatisfactionElems() const override { return 1; }
    1132                 :             : 
    1133                 :         354 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1134                 :             :     {
    1135   [ +  -  -  + ]:         354 :         return std::make_unique<PKDescriptor>(m_pubkey_args.at(0)->Clone(), m_xonly);
    1136                 :             :     }
    1137                 :             : };
    1138                 :             : 
    1139                 :             : /** A parsed pkh(P) descriptor. */
    1140                 :             : class PKHDescriptor final : public DescriptorImpl
    1141                 :             : {
    1142                 :             : protected:
    1143                 :      107317 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override
    1144                 :             :     {
    1145                 :      107317 :         CKeyID id = keys[0].GetID();
    1146   [ +  -  +  - ]:      214634 :         return Vector(GetScriptForDestination(PKHash(id)));
    1147                 :             :     }
    1148                 :             : public:
    1149   [ +  -  +  - ]:        6015 :     PKHDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "pkh") {}
    1150                 :       56058 :     std::optional<OutputType> GetOutputType() const override { return OutputType::LEGACY; }
    1151                 :      105742 :     bool IsSingleType() const final { return true; }
    1152                 :             : 
    1153                 :         848 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 1 + 20 + 1 + 1; }
    1154                 :             : 
    1155                 :        1210 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
    1156         [ +  + ]:        1210 :         const auto sig_size = use_max_sig ? 72 : 71;
    1157                 :        1210 :         return 1 + sig_size + 1 + m_pubkey_args[0]->GetSize();
    1158                 :             :     }
    1159                 :             : 
    1160                 :         576 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
    1161                 :         576 :         return *MaxSatSize(use_max_sig) * WITNESS_SCALE_FACTOR;
    1162                 :             :     }
    1163                 :             : 
    1164                 :         676 :     std::optional<int64_t> MaxSatisfactionElems() const override { return 2; }
    1165                 :             : 
    1166                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1167                 :             :     {
    1168   [ #  #  #  # ]:           0 :         return std::make_unique<PKHDescriptor>(m_pubkey_args.at(0)->Clone());
    1169                 :             :     }
    1170                 :             : };
    1171                 :             : 
    1172                 :             : /** A parsed wpkh(P) descriptor. */
    1173                 :             : class WPKHDescriptor final : public DescriptorImpl
    1174                 :             : {
    1175                 :             : protected:
    1176                 :      151225 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override
    1177                 :             :     {
    1178                 :      151225 :         CKeyID id = keys[0].GetID();
    1179   [ +  -  +  - ]:      302450 :         return Vector(GetScriptForDestination(WitnessV0KeyHash(id)));
    1180                 :             :     }
    1181                 :             : public:
    1182   [ +  -  +  - ]:        7383 :     WPKHDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "wpkh") {}
    1183                 :       80609 :     std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32; }
    1184                 :       16179 :     bool IsSingleType() const final { return true; }
    1185                 :             : 
    1186                 :         624 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 20; }
    1187                 :             : 
    1188                 :         821 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
    1189         [ +  + ]:         557 :         const auto sig_size = use_max_sig ? 72 : 71;
    1190                 :         821 :         return (1 + sig_size + 1 + 33);
    1191                 :             :     }
    1192                 :             : 
    1193                 :         326 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
    1194         [ +  + ]:         326 :         return MaxSatSize(use_max_sig);
    1195                 :             :     }
    1196                 :             : 
    1197                 :         546 :     std::optional<int64_t> MaxSatisfactionElems() const override { return 2; }
    1198                 :             : 
    1199                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1200                 :             :     {
    1201   [ #  #  #  # ]:           0 :         return std::make_unique<WPKHDescriptor>(m_pubkey_args.at(0)->Clone());
    1202                 :             :     }
    1203                 :             : };
    1204                 :             : 
    1205                 :             : /** A parsed combo(P) descriptor. */
    1206                 :             : class ComboDescriptor final : public DescriptorImpl
    1207                 :             : {
    1208                 :             : protected:
    1209                 :        2697 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider& out) const override
    1210                 :             :     {
    1211                 :        2697 :         std::vector<CScript> ret;
    1212         [ +  - ]:        2697 :         CKeyID id = keys[0].GetID();
    1213   [ +  -  +  - ]:        2697 :         ret.emplace_back(GetScriptForRawPubKey(keys[0])); // P2PK
    1214   [ +  -  +  -  :        5394 :         ret.emplace_back(GetScriptForDestination(PKHash(id))); // P2PKH
                   +  - ]
    1215         [ +  + ]:        2697 :         if (keys[0].IsCompressed()) {
    1216         [ +  - ]:        2673 :             CScript p2wpkh = GetScriptForDestination(WitnessV0KeyHash(id));
    1217   [ +  -  +  - ]:        2673 :             out.scripts.emplace(CScriptID(p2wpkh), p2wpkh);
    1218         [ +  - ]:        2673 :             ret.emplace_back(p2wpkh);
    1219   [ +  -  +  -  :        5346 :             ret.emplace_back(GetScriptForDestination(ScriptHash(p2wpkh))); // P2SH-P2WPKH
                   +  - ]
    1220                 :        2673 :         }
    1221                 :        2697 :         return ret;
    1222                 :           0 :     }
    1223                 :             : public:
    1224   [ +  -  +  - ]:        1138 :     ComboDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "combo") {}
    1225                 :        1030 :     bool IsSingleType() const final { return false; }
    1226                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1227                 :             :     {
    1228   [ #  #  #  # ]:           0 :         return std::make_unique<ComboDescriptor>(m_pubkey_args.at(0)->Clone());
    1229                 :             :     }
    1230                 :             : };
    1231                 :             : 
    1232                 :             : /** A parsed multi(...) or sortedmulti(...) descriptor */
    1233                 :             : class MultisigDescriptor final : public DescriptorImpl
    1234                 :             : {
    1235                 :             :     const int m_threshold;
    1236                 :             :     const bool m_sorted;
    1237                 :             : protected:
    1238                 :       37312 :     std::string ToStringExtra() const override { return strprintf("%i", m_threshold); }
    1239                 :        8224 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override {
    1240         [ +  + ]:        8224 :         if (m_sorted) {
    1241                 :        3584 :             std::vector<CPubKey> sorted_keys(keys);
    1242                 :        3584 :             std::sort(sorted_keys.begin(), sorted_keys.end());
    1243   [ +  -  +  - ]:        7168 :             return Vector(GetScriptForMultisig(m_threshold, sorted_keys));
    1244                 :        3584 :         }
    1245         [ +  - ]:        9280 :         return Vector(GetScriptForMultisig(m_threshold, keys));
    1246                 :             :     }
    1247                 :             : public:
    1248   [ +  +  +  - ]:       62867 :     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) {}
    1249                 :         751 :     bool IsSingleType() const final { return true; }
    1250                 :             : 
    1251                 :        2625 :     std::optional<int64_t> ScriptSize() const override {
    1252         [ -  + ]:        2625 :         const auto n_keys = m_pubkey_args.size();
    1253                 :       18237 :         auto op = [](int64_t acc, const std::unique_ptr<PubkeyProvider>& pk) { return acc + 1 + pk->GetSize();};
    1254                 :        2625 :         const auto pubkeys_size{std::accumulate(m_pubkey_args.begin(), m_pubkey_args.end(), int64_t{0}, op)};
    1255   [ -  +  +  - ]:        5250 :         return 1 + BuildScript(n_keys).size() + BuildScript(m_threshold).size() + pubkeys_size;
    1256                 :             :     }
    1257                 :             : 
    1258                 :        2878 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
    1259         [ -  + ]:        2382 :         const auto sig_size = use_max_sig ? 72 : 71;
    1260                 :        2878 :         return (1 + (1 + sig_size) * m_threshold);
    1261                 :             :     }
    1262                 :             : 
    1263                 :         496 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
    1264         [ -  + ]:         496 :         return *MaxSatSize(use_max_sig) * WITNESS_SCALE_FACTOR;
    1265                 :             :     }
    1266                 :             : 
    1267                 :        1439 :     std::optional<int64_t> MaxSatisfactionElems() const override { return 1 + m_threshold; }
    1268                 :             : 
    1269                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1270                 :             :     {
    1271                 :           0 :         std::vector<std::unique_ptr<PubkeyProvider>> providers;
    1272   [ #  #  #  # ]:           0 :         providers.reserve(m_pubkey_args.size());
    1273         [ #  # ]:           0 :         std::transform(m_pubkey_args.begin(), m_pubkey_args.end(), providers.begin(), [](const std::unique_ptr<PubkeyProvider>& p) { return p->Clone(); });
    1274   [ #  #  #  # ]:           0 :         return std::make_unique<MultisigDescriptor>(m_threshold, std::move(providers), m_sorted);
    1275                 :           0 :     }
    1276                 :             : };
    1277                 :             : 
    1278                 :             : /** A parsed (sorted)multi_a(...) descriptor. Always uses x-only pubkeys. */
    1279                 :             : class MultiADescriptor final : public DescriptorImpl
    1280                 :             : {
    1281                 :             :     const int m_threshold;
    1282                 :             :     const bool m_sorted;
    1283                 :             : protected:
    1284                 :       13463 :     std::string ToStringExtra() const override { return strprintf("%i", m_threshold); }
    1285                 :       11973 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override {
    1286                 :       11973 :         CScript ret;
    1287                 :       11973 :         std::vector<XOnlyPubKey> xkeys;
    1288   [ -  +  +  - ]:       11973 :         xkeys.reserve(keys.size());
    1289   [ +  -  +  + ]:     2108991 :         for (const auto& key : keys) xkeys.emplace_back(key);
    1290         [ +  + ]:       11973 :         if (m_sorted) std::sort(xkeys.begin(), xkeys.end());
    1291   [ +  -  +  - ]:       23946 :         ret << ToByteVector(xkeys[0]) << OP_CHECKSIG;
    1292   [ -  +  +  + ]:     2097018 :         for (size_t i = 1; i < keys.size(); ++i) {
    1293   [ +  -  +  - ]:     6255135 :             ret << ToByteVector(xkeys[i]) << OP_CHECKSIGADD;
    1294                 :             :         }
    1295   [ +  -  +  - ]:       11973 :         ret << m_threshold << OP_NUMEQUAL;
    1296         [ +  - ]:       11973 :         return Vector(std::move(ret));
    1297                 :       11973 :     }
    1298                 :             : public:
    1299   [ +  +  +  - ]:        8824 :     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) {}
    1300                 :           0 :     bool IsSingleType() const final { return true; }
    1301                 :             : 
    1302                 :           0 :     std::optional<int64_t> ScriptSize() const override {
    1303         [ #  # ]:           0 :         const auto n_keys = m_pubkey_args.size();
    1304         [ #  # ]:           0 :         return (1 + 32 + 1) * n_keys + BuildScript(m_threshold).size() + 1;
    1305                 :             :     }
    1306                 :             : 
    1307                 :           0 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
    1308         [ #  # ]:           0 :         return (1 + 65) * m_threshold + (m_pubkey_args.size() - m_threshold);
    1309                 :             :     }
    1310                 :             : 
    1311         [ #  # ]:           0 :     std::optional<int64_t> MaxSatisfactionElems() const override { return m_pubkey_args.size(); }
    1312                 :             : 
    1313                 :         185 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1314                 :             :     {
    1315                 :         185 :         std::vector<std::unique_ptr<PubkeyProvider>> providers;
    1316   [ -  +  +  - ]:         185 :         providers.reserve(m_pubkey_args.size());
    1317         [ +  + ]:         995 :         for (const auto& arg : m_pubkey_args) {
    1318         [ +  - ]:        1620 :             providers.push_back(arg->Clone());
    1319                 :             :         }
    1320   [ +  -  -  + ]:         370 :         return std::make_unique<MultiADescriptor>(m_threshold, std::move(providers), m_sorted);
    1321                 :         185 :     }
    1322                 :             : };
    1323                 :             : 
    1324                 :             : /** A parsed sh(...) descriptor. */
    1325                 :             : class SHDescriptor final : public DescriptorImpl
    1326                 :             : {
    1327                 :             : protected:
    1328                 :      145059 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, std::span<const CScript> scripts, FlatSigningProvider& out) const override
    1329                 :             :     {
    1330   [ +  -  +  - ]:      290118 :         auto ret = Vector(GetScriptForDestination(ScriptHash(scripts[0])));
    1331   [ -  +  +  -  :      145059 :         if (ret.size()) out.scripts.emplace(CScriptID(scripts[0]), scripts[0]);
             +  -  +  - ]
    1332                 :      145059 :         return ret;
    1333                 :           0 :     }
    1334                 :             : 
    1335         [ +  + ]:       81501 :     bool IsSegwit() const { return m_subdescriptor_args[0]->GetOutputType() == OutputType::BECH32; }
    1336                 :             : 
    1337                 :             : public:
    1338         [ +  - ]:        7621 :     SHDescriptor(std::unique_ptr<DescriptorImpl> desc) : DescriptorImpl({}, std::move(desc), "sh") {}
    1339                 :             : 
    1340                 :       77810 :     std::optional<OutputType> GetOutputType() const override
    1341                 :             :     {
    1342   [ -  +  -  + ]:       77810 :         assert(m_subdescriptor_args.size() == 1);
    1343         [ +  + ]:       77810 :         if (IsSegwit()) return OutputType::P2SH_SEGWIT;
    1344                 :        5388 :         return OutputType::LEGACY;
    1345                 :             :     }
    1346                 :      146510 :     bool IsSingleType() const final { return true; }
    1347                 :             : 
    1348                 :        1697 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 20 + 1; }
    1349                 :             : 
    1350                 :        3691 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
    1351         [ +  - ]:        3691 :         if (const auto sat_size = m_subdescriptor_args[0]->MaxSatSize(use_max_sig)) {
    1352         [ +  - ]:        3691 :             if (const auto subscript_size = m_subdescriptor_args[0]->ScriptSize()) {
    1353                 :             :                 // The subscript is never witness data.
    1354                 :        3691 :                 const auto subscript_weight = (1 + *subscript_size) * WITNESS_SCALE_FACTOR;
    1355                 :             :                 // The weight depends on whether the inner descriptor is satisfied using the witness stack.
    1356         [ +  + ]:        3691 :                 if (IsSegwit()) return subscript_weight + *sat_size;
    1357                 :        1906 :                 return subscript_weight + *sat_size * WITNESS_SCALE_FACTOR;
    1358                 :             :             }
    1359                 :             :         }
    1360                 :           0 :         return {};
    1361                 :             :     }
    1362                 :             : 
    1363                 :        1950 :     std::optional<int64_t> MaxSatisfactionElems() const override {
    1364         [ +  - ]:        1950 :         if (const auto sub_elems = m_subdescriptor_args[0]->MaxSatisfactionElems()) return 1 + *sub_elems;
    1365                 :           0 :         return {};
    1366                 :             :     }
    1367                 :             : 
    1368                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1369                 :             :     {
    1370   [ #  #  #  # ]:           0 :         return std::make_unique<SHDescriptor>(m_subdescriptor_args.at(0)->Clone());
    1371                 :             :     }
    1372                 :             : };
    1373                 :             : 
    1374                 :             : /** A parsed wsh(...) descriptor. */
    1375                 :             : class WSHDescriptor final : public DescriptorImpl
    1376                 :             : {
    1377                 :             : protected:
    1378                 :       15376 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, std::span<const CScript> scripts, FlatSigningProvider& out) const override
    1379                 :             :     {
    1380   [ +  -  +  - ]:       30752 :         auto ret = Vector(GetScriptForDestination(WitnessV0ScriptHash(scripts[0])));
    1381   [ -  +  +  -  :       15376 :         if (ret.size()) out.scripts.emplace(CScriptID(scripts[0]), scripts[0]);
             +  -  +  - ]
    1382                 :       15376 :         return ret;
    1383                 :           0 :     }
    1384                 :             : public:
    1385         [ +  - ]:       10494 :     WSHDescriptor(std::unique_ptr<DescriptorImpl> desc) : DescriptorImpl({}, std::move(desc), "wsh") {}
    1386                 :       14729 :     std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32; }
    1387                 :       12998 :     bool IsSingleType() const final { return true; }
    1388                 :             : 
    1389                 :        5049 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
    1390                 :             : 
    1391                 :        9094 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
    1392         [ +  - ]:        9094 :         if (const auto sat_size = m_subdescriptor_args[0]->MaxSatSize(use_max_sig)) {
    1393         [ +  - ]:        9094 :             if (const auto subscript_size = m_subdescriptor_args[0]->ScriptSize()) {
    1394         [ +  + ]:       10642 :                 return GetSizeOfCompactSize(*subscript_size) + *subscript_size + *sat_size;
    1395                 :             :             }
    1396                 :             :         }
    1397                 :           0 :         return {};
    1398                 :             :     }
    1399                 :             : 
    1400                 :        7804 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
    1401                 :        7804 :         return MaxSatSize(use_max_sig);
    1402                 :             :     }
    1403                 :             : 
    1404                 :        4547 :     std::optional<int64_t> MaxSatisfactionElems() const override {
    1405         [ +  - ]:        4547 :         if (const auto sub_elems = m_subdescriptor_args[0]->MaxSatisfactionElems()) return 1 + *sub_elems;
    1406                 :           0 :         return {};
    1407                 :             :     }
    1408                 :             : 
    1409                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1410                 :             :     {
    1411   [ #  #  #  # ]:           0 :         return std::make_unique<WSHDescriptor>(m_subdescriptor_args.at(0)->Clone());
    1412                 :             :     }
    1413                 :             : };
    1414                 :             : 
    1415                 :             : /** A parsed tr(...) descriptor. */
    1416                 :             : class TRDescriptor final : public DescriptorImpl
    1417                 :             : {
    1418                 :             :     std::vector<int> m_depths;
    1419                 :             : protected:
    1420                 :      146925 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript> scripts, FlatSigningProvider& out) const override
    1421                 :             :     {
    1422         [ -  + ]:      146925 :         TaprootBuilder builder;
    1423   [ -  +  -  + ]:      146925 :         assert(m_depths.size() == scripts.size());
    1424   [ -  +  +  + ]:      194552 :         for (size_t pos = 0; pos < m_depths.size(); ++pos) {
    1425   [ +  +  +  - ]:       95254 :             builder.Add(m_depths[pos], scripts[pos], TAPROOT_LEAF_TAPSCRIPT);
    1426                 :             :         }
    1427         [ -  + ]:      146925 :         if (!builder.IsComplete()) return {};
    1428   [ -  +  -  + ]:      146925 :         assert(keys.size() == 1);
    1429                 :      146925 :         XOnlyPubKey xpk(keys[0]);
    1430   [ +  -  -  + ]:      146925 :         if (!xpk.IsFullyValid()) return {};
    1431         [ +  - ]:      146925 :         builder.Finalize(xpk);
    1432         [ +  - ]:      146925 :         WitnessV1Taproot output = builder.GetOutput();
    1433   [ +  -  +  - ]:      146925 :         out.tr_trees[output] = builder;
    1434   [ +  -  +  - ]:      293850 :         return Vector(GetScriptForDestination(output));
    1435                 :      146925 :     }
    1436                 :      159505 :     bool ToStringSubScriptHelper(const SigningProvider* arg, std::string& ret, const StringType type, const DescriptorCache* cache = nullptr) const override
    1437                 :             :     {
    1438         [ +  + ]:      159505 :         if (m_depths.empty()) {
    1439                 :             :             // If there are no sub-descriptors and a PRIVATE string
    1440                 :             :             // is requested, return `false` to indicate that the presence
    1441                 :             :             // of a private key depends solely on the internal key (which is checked
    1442                 :             :             // in the caller), not on any sub-descriptor. This ensures correct behavior for
    1443                 :             :             // descriptors like tr(internal_key) when checking for private keys.
    1444                 :      132778 :             return type != StringType::PRIVATE;
    1445                 :             :         }
    1446                 :       26727 :         std::vector<bool> path;
    1447                 :       26727 :         bool is_private{type == StringType::PRIVATE};
    1448                 :             :         // For private string output, track if at least one key has a private key available.
    1449                 :             :         // Initialize to true for non-private types.
    1450                 :       26727 :         bool any_success{!is_private};
    1451                 :             : 
    1452   [ -  +  +  + ]:       82206 :         for (size_t pos = 0; pos < m_depths.size(); ++pos) {
    1453   [ +  +  +  - ]:       55585 :             if (pos) ret += ',';
    1454         [ +  + ]:      111172 :             while ((int)path.size() <= m_depths[pos]) {
    1455   [ +  +  +  - ]:       55587 :                 if (path.size()) ret += '{';
    1456         [ +  - ]:       55587 :                 path.push_back(false);
    1457                 :             :             }
    1458         [ +  - ]:       55585 :             std::string tmp;
    1459         [ +  - ]:       55585 :             bool subscript_res{m_subdescriptor_args[pos]->ToStringHelper(arg, tmp, type, cache)};
    1460         [ +  + ]:       55585 :             if (!is_private && !subscript_res) return false;
    1461                 :       55479 :             any_success = any_success || subscript_res;
    1462         [ -  + ]:       55479 :             ret += tmp;
    1463   [ +  -  +  + ]:       84335 :             while (!path.empty() && path.back()) {
    1464   [ +  -  +  - ]:       28856 :                 if (path.size() > 1) ret += '}';
    1465   [ -  +  +  - ]:      113191 :                 path.pop_back();
    1466                 :             :             }
    1467         [ +  - ]:       55479 :             if (!path.empty()) path.back() = true;
    1468                 :       55585 :         }
    1469                 :             :         return any_success;
    1470                 :       26727 :     }
    1471                 :             : public:
    1472                 :       19574 :     TRDescriptor(std::unique_ptr<PubkeyProvider> internal_key, std::vector<std::unique_ptr<DescriptorImpl>> descs, std::vector<int> depths) :
    1473   [ +  -  +  -  :       19574 :         DescriptorImpl(Vector(std::move(internal_key)), std::move(descs), "tr"), m_depths(std::move(depths))
                   -  + ]
    1474                 :             :     {
    1475   [ -  +  -  +  :       19574 :         assert(m_subdescriptor_args.size() == m_depths.size());
                   -  + ]
    1476                 :       19574 :     }
    1477                 :       85906 :     std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32M; }
    1478                 :      147581 :     bool IsSingleType() const final { return true; }
    1479                 :             : 
    1480                 :        5836 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
    1481                 :             : 
    1482                 :       12901 :     std::optional<int64_t> MaxSatisfactionWeight(bool) const override {
    1483                 :             :         // FIXME: We assume keypath spend, which can lead to very large underestimations.
    1484                 :       12901 :         return 1 + 65;
    1485                 :             :     }
    1486                 :             : 
    1487                 :        6704 :     std::optional<int64_t> MaxSatisfactionElems() const override {
    1488                 :             :         // FIXME: See above, we assume keypath spend.
    1489                 :        6704 :         return 1;
    1490                 :             :     }
    1491                 :             : 
    1492                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1493                 :             :     {
    1494                 :           0 :         std::vector<std::unique_ptr<DescriptorImpl>> subdescs;
    1495   [ #  #  #  # ]:           0 :         subdescs.reserve(m_subdescriptor_args.size());
    1496         [ #  # ]:           0 :         std::transform(m_subdescriptor_args.begin(), m_subdescriptor_args.end(), subdescs.begin(), [](const std::unique_ptr<DescriptorImpl>& d) { return d->Clone(); });
    1497   [ #  #  #  #  :           0 :         return std::make_unique<TRDescriptor>(m_pubkey_args.at(0)->Clone(), std::move(subdescs), m_depths);
             #  #  #  # ]
    1498                 :           0 :     }
    1499                 :             : };
    1500                 :             : 
    1501                 :             : /* We instantiate Miniscript here with a simple integer as key type.
    1502                 :             :  * The value of these key integers are an index in the
    1503                 :             :  * DescriptorImpl::m_pubkey_args vector.
    1504                 :             :  */
    1505                 :             : 
    1506                 :             : /**
    1507                 :             :  * The context for converting a Miniscript descriptor into a Script.
    1508                 :             :  */
    1509                 :             : class ScriptMaker {
    1510                 :             :     //! Keys contained in the Miniscript (the evaluation of DescriptorImpl::m_pubkey_args).
    1511                 :             :     const std::vector<CPubKey>& m_keys;
    1512                 :             :     //! The script context we're operating within (Tapscript or P2WSH).
    1513                 :             :     const miniscript::MiniscriptContext m_script_ctx;
    1514                 :             : 
    1515                 :             :     //! Get the ripemd160(sha256()) hash of this key.
    1516                 :             :     //! Any key that is valid in a descriptor serializes as 32 bytes within a Tapscript context. So we
    1517                 :             :     //! must not hash the sign-bit byte in this case.
    1518                 :       12560 :     uint160 GetHash160(uint32_t key) const {
    1519         [ +  + ]:       12560 :         if (miniscript::IsTapscript(m_script_ctx)) {
    1520                 :       10113 :             return Hash160(XOnlyPubKey{m_keys[key]});
    1521                 :             :         }
    1522                 :        2447 :         return m_keys[key].GetID();
    1523                 :             :     }
    1524                 :             : 
    1525                 :             : public:
    1526                 :       35985 :     ScriptMaker(const std::vector<CPubKey>& keys LIFETIMEBOUND, const miniscript::MiniscriptContext script_ctx) : m_keys(keys), m_script_ctx{script_ctx} {}
    1527                 :             : 
    1528                 :       63610 :     std::vector<unsigned char> ToPKBytes(uint32_t key) const {
    1529                 :             :         // In Tapscript keys always serialize as x-only, whether an x-only key was used in the descriptor or not.
    1530         [ +  + ]:       63610 :         if (!miniscript::IsTapscript(m_script_ctx)) {
    1531                 :       33791 :             return {m_keys[key].begin(), m_keys[key].end()};
    1532                 :             :         }
    1533                 :       29819 :         const XOnlyPubKey xonly_pubkey{m_keys[key]};
    1534                 :       29819 :         return {xonly_pubkey.begin(), xonly_pubkey.end()};
    1535                 :             :     }
    1536                 :             : 
    1537                 :       12560 :     std::vector<unsigned char> ToPKHBytes(uint32_t key) const {
    1538                 :       12560 :         auto id = GetHash160(key);
    1539                 :       12560 :         return {id.begin(), id.end()};
    1540                 :             :     }
    1541                 :             : };
    1542                 :             : 
    1543                 :             : /**
    1544                 :             :  * The context for converting a Miniscript descriptor to its textual form.
    1545                 :             :  */
    1546                 :             : class StringMaker {
    1547                 :             :     //! To convert private keys for private descriptors.
    1548                 :             :     const SigningProvider* m_arg;
    1549                 :             :     //! Keys contained in the Miniscript (a reference to DescriptorImpl::m_pubkey_args).
    1550                 :             :     const std::vector<std::unique_ptr<PubkeyProvider>>& m_pubkeys;
    1551                 :             :     //! StringType to serialize keys
    1552                 :             :     const DescriptorImpl::StringType m_type;
    1553                 :             :     const DescriptorCache* m_cache;
    1554                 :             : 
    1555                 :             : public:
    1556                 :       45217 :     StringMaker(const SigningProvider* arg LIFETIMEBOUND,
    1557                 :             :                 const std::vector<std::unique_ptr<PubkeyProvider>>& pubkeys LIFETIMEBOUND,
    1558                 :             :                 DescriptorImpl::StringType type,
    1559                 :             :                 const DescriptorCache* cache LIFETIMEBOUND)
    1560                 :       45217 :         : m_arg(arg), m_pubkeys(pubkeys), m_type(type), m_cache(cache) {}
    1561                 :             : 
    1562                 :      134656 :     std::optional<std::string> ToString(uint32_t key, bool& has_priv_key) const
    1563                 :             :     {
    1564   [ +  +  +  +  :      134656 :         std::string ret;
                      - ]
    1565                 :      134656 :         has_priv_key = false;
    1566   [ +  +  +  +  :      134656 :         switch (m_type) {
                      - ]
    1567                 :       68470 :         case DescriptorImpl::StringType::PUBLIC:
    1568         [ +  - ]:       68470 :             ret = m_pubkeys[key]->ToString();
    1569                 :       68470 :             break;
    1570                 :       30529 :         case DescriptorImpl::StringType::PRIVATE:
    1571         [ +  - ]:       30529 :             has_priv_key = m_pubkeys[key]->ToPrivateString(*m_arg, ret);
    1572                 :       30529 :             break;
    1573                 :       31747 :         case DescriptorImpl::StringType::NORMALIZED:
    1574   [ +  -  +  + ]:       31747 :             if (!m_pubkeys[key]->ToNormalizedString(*m_arg, ret, m_cache)) return {};
    1575                 :             :             break;
    1576                 :        3910 :         case DescriptorImpl::StringType::COMPAT:
    1577         [ +  - ]:        3910 :             ret = m_pubkeys[key]->ToString(PubkeyProvider::StringType::COMPAT);
    1578                 :        3910 :             break;
    1579                 :             :         }
    1580                 :      134587 :         return ret;
    1581                 :      134656 :     }
    1582                 :             : };
    1583                 :             : 
    1584                 :             : class MiniscriptDescriptor final : public DescriptorImpl
    1585                 :             : {
    1586                 :             : private:
    1587                 :             :     miniscript::NodeRef<uint32_t> m_node;
    1588                 :             : 
    1589                 :             : protected:
    1590                 :       35985 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript> scripts,
    1591                 :             :                                      FlatSigningProvider& provider) const override
    1592                 :             :     {
    1593                 :       35985 :         const auto script_ctx{m_node->GetMsCtx()};
    1594         [ +  + ]:      112155 :         for (const auto& key : keys) {
    1595         [ +  + ]:       76170 :             if (miniscript::IsTapscript(script_ctx)) {
    1596                 :       39932 :                 provider.pubkeys.emplace(Hash160(XOnlyPubKey{key}), key);
    1597                 :             :             } else {
    1598                 :       36238 :                 provider.pubkeys.emplace(key.GetID(), key);
    1599                 :             :             }
    1600                 :             :         }
    1601         [ +  - ]:       71970 :         return Vector(m_node->ToScript(ScriptMaker(keys, script_ctx)));
    1602                 :             :     }
    1603                 :             : 
    1604                 :             : public:
    1605                 :       31335 :     MiniscriptDescriptor(std::vector<std::unique_ptr<PubkeyProvider>> providers, miniscript::NodeRef<uint32_t> node)
    1606   [ +  -  +  - ]:       31335 :         : DescriptorImpl(std::move(providers), "?"), m_node(std::move(node))
    1607                 :             :     {
    1608                 :             :         // Traverse miniscript tree for unsafe use of older()
    1609         [ +  - ]:       31335 :         miniscript::ForEachNode(*m_node, [&](const miniscript::Node<uint32_t>& node) {
    1610         [ +  + ]:     1471738 :             if (node.fragment == miniscript::Fragment::OLDER) {
    1611                 :        1245 :                 const uint32_t raw = node.k;
    1612                 :        1245 :                 const uint32_t value_part = raw & ~CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG;
    1613         [ +  + ]:        1245 :                 if (value_part > CTxIn::SEQUENCE_LOCKTIME_MASK) {
    1614                 :         603 :                     const bool is_time_based = (raw & CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) != 0;
    1615         [ +  + ]:         603 :                     if (is_time_based) {
    1616         [ +  - ]:         472 :                         m_warnings.push_back(strprintf("time-based relative locktime: older(%u) > (65535 * 512) seconds is unsafe", raw));
    1617                 :             :                     } else {
    1618         [ +  - ]:         131 :                         m_warnings.push_back(strprintf("height-based relative locktime: older(%u) > 65535 blocks is unsafe", raw));
    1619                 :             :                     }
    1620                 :             :                 }
    1621                 :             :             }
    1622                 :     1471738 :         });
    1623                 :       31335 :     }
    1624                 :             : 
    1625                 :       45217 :     bool ToStringHelper(const SigningProvider* arg, std::string& out, const StringType type,
    1626                 :             :                         const DescriptorCache* cache = nullptr) const override
    1627                 :             :     {
    1628                 :       45217 :         bool has_priv_key{false};
    1629                 :       45217 :         auto res = m_node->ToString(StringMaker(arg, m_pubkey_args, type, cache), has_priv_key);
    1630   [ +  +  +  - ]:       45217 :         if (res) out = *res;
    1631         [ +  + ]:       45217 :         if (type == StringType::PRIVATE) {
    1632         [ -  + ]:       10483 :             Assume(res.has_value());
    1633                 :       10483 :             return has_priv_key;
    1634                 :             :         } else {
    1635                 :       34734 :             return res.has_value();
    1636                 :             :         }
    1637                 :       45217 :     }
    1638                 :             : 
    1639                 :       10310 :     bool IsSolvable() const override { return true; }
    1640                 :           0 :     bool IsSingleType() const final { return true; }
    1641                 :             : 
    1642                 :        7288 :     std::optional<int64_t> ScriptSize() const override { return m_node->ScriptSize(); }
    1643                 :             : 
    1644                 :        7288 :     std::optional<int64_t> MaxSatSize(bool) const override {
    1645                 :             :         // For Miniscript we always assume high-R ECDSA signatures.
    1646   [ -  +  +  - ]:       14576 :         return m_node->GetWitnessSize();
    1647                 :             :     }
    1648                 :             : 
    1649                 :        3644 :     std::optional<int64_t> MaxSatisfactionElems() const override {
    1650         [ +  - ]:        3644 :         return m_node->GetStackSize();
    1651                 :             :     }
    1652                 :             : 
    1653                 :        2857 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1654                 :             :     {
    1655                 :        2857 :         std::vector<std::unique_ptr<PubkeyProvider>> providers;
    1656   [ -  +  +  - ]:        2857 :         providers.reserve(m_pubkey_args.size());
    1657         [ +  + ]:        5858 :         for (const auto& arg : m_pubkey_args) {
    1658         [ +  - ]:        6002 :             providers.push_back(arg->Clone());
    1659                 :             :         }
    1660   [ +  -  +  -  :        5714 :         return std::make_unique<MiniscriptDescriptor>(std::move(providers), m_node->Clone());
                   -  + ]
    1661                 :        2857 :     }
    1662                 :             : };
    1663                 :             : 
    1664                 :             : /** A parsed rawtr(...) descriptor. */
    1665                 :             : class RawTRDescriptor final : public DescriptorImpl
    1666                 :             : {
    1667                 :             : protected:
    1668                 :        1481 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript> scripts, FlatSigningProvider& out) const override
    1669                 :             :     {
    1670   [ -  +  -  + ]:        1481 :         assert(keys.size() == 1);
    1671                 :        1481 :         XOnlyPubKey xpk(keys[0]);
    1672         [ -  + ]:        1481 :         if (!xpk.IsFullyValid()) return {};
    1673         [ +  - ]:        1481 :         WitnessV1Taproot output{xpk};
    1674   [ +  -  +  - ]:        2962 :         return Vector(GetScriptForDestination(output));
    1675                 :             :     }
    1676                 :             : public:
    1677   [ +  -  +  - ]:       10907 :     RawTRDescriptor(std::unique_ptr<PubkeyProvider> output_key) : DescriptorImpl(Vector(std::move(output_key)), "rawtr") {}
    1678                 :        1247 :     std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32M; }
    1679                 :        1573 :     bool IsSingleType() const final { return true; }
    1680                 :             : 
    1681                 :         339 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
    1682                 :             : 
    1683                 :         684 :     std::optional<int64_t> MaxSatisfactionWeight(bool) const override {
    1684                 :             :         // We can't know whether there is a script path, so assume key path spend.
    1685                 :         684 :         return 1 + 65;
    1686                 :             :     }
    1687                 :             : 
    1688                 :         342 :     std::optional<int64_t> MaxSatisfactionElems() const override {
    1689                 :             :         // See above, we assume keypath spend.
    1690                 :         342 :         return 1;
    1691                 :             :     }
    1692                 :             : 
    1693                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1694                 :             :     {
    1695   [ #  #  #  # ]:           0 :         return std::make_unique<RawTRDescriptor>(m_pubkey_args.at(0)->Clone());
    1696                 :             :     }
    1697                 :             : };
    1698                 :             : 
    1699                 :             : ////////////////////////////////////////////////////////////////////////////
    1700                 :             : // Parser                                                                 //
    1701                 :             : ////////////////////////////////////////////////////////////////////////////
    1702                 :             : 
    1703                 :             : enum class ParseScriptContext {
    1704                 :             :     TOP,     //!< Top-level context (script goes directly in scriptPubKey)
    1705                 :             :     P2SH,    //!< Inside sh() (script becomes P2SH redeemScript)
    1706                 :             :     P2WPKH,  //!< Inside wpkh() (no script, pubkey only)
    1707                 :             :     P2WSH,   //!< Inside wsh() (script becomes v0 witness script)
    1708                 :             :     P2TR,    //!< Inside tr() (either internal key, or BIP342 script leaf)
    1709                 :             :     MUSIG,   //!< Inside musig() (implies P2TR, cannot have nested musig())
    1710                 :             : };
    1711                 :             : 
    1712                 :      229839 : std::optional<uint32_t> ParseKeyPathNum(std::span<const char> elem, bool& apostrophe, std::string& error, bool& has_hardened)
    1713                 :             : {
    1714                 :      229839 :     bool hardened = false;
    1715         [ +  + ]:      229839 :     if (elem.size() > 0) {
    1716         [ +  + ]:      229823 :         const char last = elem[elem.size() - 1];
    1717         [ +  + ]:      229823 :         if (last == '\'' || last == 'h') {
    1718                 :       54014 :             elem = elem.first(elem.size() - 1);
    1719                 :       54014 :             hardened = true;
    1720                 :       54014 :             apostrophe = last == '\'';
    1721                 :             :         }
    1722                 :             :     }
    1723                 :      229839 :     const auto p{ToIntegral<uint32_t>(std::string_view{elem.begin(), elem.end()})};
    1724         [ +  + ]:      229839 :     if (!p) {
    1725                 :         188 :         error = strprintf("Key path value '%s' is not a valid uint32", std::string_view{elem.begin(), elem.end()});
    1726                 :         188 :         return std::nullopt;
    1727         [ +  + ]:      229651 :     } else if (*p > 0x7FFFFFFFUL) {
    1728                 :          22 :         error = strprintf("Key path value %u is out of range", *p);
    1729                 :          22 :         return std::nullopt;
    1730                 :             :     }
    1731   [ +  +  +  + ]:      229629 :     has_hardened = has_hardened || hardened;
    1732                 :             : 
    1733                 :      229629 :     return std::make_optional<uint32_t>(*p | (((uint32_t)hardened) << 31));
    1734                 :             : }
    1735                 :             : 
    1736                 :             : /**
    1737                 :             :  * Parse a key path, being passed a split list of elements (the first element is ignored because it is always the key).
    1738                 :             :  *
    1739                 :             :  * @param[in] split BIP32 path string, using either ' or h for hardened derivation
    1740                 :             :  * @param[out] out Vector of parsed key paths
    1741                 :             :  * @param[out] apostrophe only updated if hardened derivation is found
    1742                 :             :  * @param[out] error parsing error message
    1743                 :             :  * @param[in] allow_multipath Allows the parsed path to use the multipath specifier
    1744                 :             :  * @param[out] has_hardened Records whether the path contains any hardened derivation
    1745                 :             :  * @returns false if parsing failed
    1746                 :             :  **/
    1747                 :      176630 : [[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)
    1748                 :             : {
    1749                 :      176630 :     KeyPath path;
    1750                 :        8119 :     struct MultipathSubstitutes {
    1751                 :             :         size_t placeholder_index;
    1752                 :             :         std::vector<uint32_t> values;
    1753                 :             :     };
    1754                 :      176630 :     std::optional<MultipathSubstitutes> substitutes;
    1755                 :      176630 :     has_hardened = false;
    1756                 :             : 
    1757   [ -  +  +  + ]:      371935 :     for (size_t i = 1; i < split.size(); ++i) {
    1758         [ +  + ]:      195638 :         const std::span<const char>& elem = split[i];
    1759                 :             : 
    1760                 :             :         // Check if element contains multipath specifier
    1761   [ +  +  +  +  :      195638 :         if (!elem.empty() && elem.front() == '<' && elem.back() == '>') {
                   +  + ]
    1762         [ +  + ]:        8223 :             if (!allow_multipath) {
    1763   [ +  -  +  - ]:         186 :                 error = strprintf("Key path value '%s' specifies multipath in a section where multipath is not allowed", std::string(elem.begin(), elem.end()));
    1764                 :          93 :                 return false;
    1765                 :             :             }
    1766         [ +  + ]:        8130 :             if (substitutes) {
    1767         [ +  - ]:      176630 :                 error = "Multiple multipath key path specifiers found";
    1768                 :             :                 return false;
    1769                 :             :             }
    1770                 :             : 
    1771                 :             :             // Parse each possible value
    1772         [ +  - ]:        8125 :             std::vector<std::span<const char>> nums = Split(std::span(elem.begin()+1, elem.end()-1), ";");
    1773   [ -  +  +  + ]:        8125 :             if (nums.size() < 2) {
    1774         [ +  - ]:          54 :                 error = "Multipath key path specifiers must have at least two items";
    1775                 :             :                 return false;
    1776                 :             :             }
    1777                 :             : 
    1778                 :        8119 :             substitutes.emplace();
    1779                 :        8119 :             std::unordered_set<uint32_t> seen_substitutes;
    1780         [ +  + ]:       50495 :             for (const auto& num : nums) {
    1781         [ +  - ]:       42424 :                 const auto& op_num = ParseKeyPathNum(num, apostrophe, error, has_hardened);
    1782         [ +  + ]:       42424 :                 if (!op_num) return false;
    1783   [ +  -  +  + ]:       42395 :                 auto [_, inserted] = seen_substitutes.insert(*op_num);
    1784         [ +  + ]:       42395 :                 if (!inserted) {
    1785         [ +  - ]:          19 :                     error = strprintf("Duplicated key path value %u in multipath specifier", *op_num);
    1786                 :          19 :                     return false;
    1787                 :             :                 }
    1788         [ +  - ]:       42376 :                 substitutes->values.emplace_back(*op_num);
    1789                 :             :             }
    1790                 :             : 
    1791         [ +  - ]:        8071 :             path.emplace_back(); // Placeholder for multipath segment
    1792         [ -  + ]:        8071 :             substitutes->placeholder_index = path.size() - 1;
    1793                 :        8173 :         } else {
    1794         [ +  - ]:      187415 :             const auto& op_num = ParseKeyPathNum(elem, apostrophe, error, has_hardened);
    1795         [ +  + ]:      187415 :             if (!op_num) return false;
    1796         [ +  - ]:      187234 :             path.emplace_back(*op_num);
    1797                 :             :         }
    1798                 :             :     }
    1799                 :             : 
    1800         [ +  + ]:      176297 :     if (!substitutes) {
    1801         [ +  - ]:      168232 :         out.emplace_back(std::move(path));
    1802                 :             :     } else {
    1803                 :             :         // Replace the multipath placeholder with each value while generating paths
    1804         [ +  + ]:       50279 :         for (uint32_t substitute : substitutes->values) {
    1805         [ +  - ]:       42214 :             KeyPath branch_path = path;
    1806         [ +  - ]:       42214 :             branch_path[substitutes->placeholder_index] = substitute;
    1807         [ +  - ]:       42214 :             out.emplace_back(std::move(branch_path));
    1808                 :       42214 :         }
    1809                 :             :     }
    1810                 :             :     return true;
    1811                 :      176630 : }
    1812                 :             : 
    1813                 :      176299 : [[nodiscard]] bool ParseKeyPath(const std::vector<std::span<const char>>& split, std::vector<KeyPath>& out, bool& apostrophe, std::string& error, bool allow_multipath)
    1814                 :             : {
    1815                 :      176299 :     bool dummy;
    1816                 :      176299 :     return ParseKeyPath(split, out, apostrophe, error, allow_multipath, /*has_hardened=*/dummy);
    1817                 :             : }
    1818                 :             : 
    1819                 :      140810 : static DeriveType ParseDeriveType(std::vector<std::span<const char>>& split, bool& apostrophe)
    1820                 :             : {
    1821                 :      140810 :     DeriveType type = DeriveType::NO;
    1822         [ +  + ]:      140810 :     if (std::ranges::equal(split.back(), std::span{"*"}.first(1))) {
    1823                 :       16755 :         split.pop_back();
    1824                 :       16755 :         type = DeriveType::UNHARDENED;
    1825   [ +  +  +  + ]:      124055 :     } else if (std::ranges::equal(split.back(), std::span{"*'"}.first(2)) || std::ranges::equal(split.back(), std::span{"*h"}.first(2))) {
    1826                 :       10191 :         apostrophe = std::ranges::equal(split.back(), std::span{"*'"}.first(2));
    1827                 :       10191 :         split.pop_back();
    1828                 :       10191 :         type = DeriveType::HARDENED;
    1829                 :             :     }
    1830                 :      140810 :     return type;
    1831                 :             : }
    1832                 :             : 
    1833                 :             : /** Parse a public key that excludes origin information. */
    1834                 :      324101 : 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)
    1835                 :             : {
    1836                 :      324101 :     std::vector<std::unique_ptr<PubkeyProvider>> ret;
    1837                 :      324101 :     bool permit_uncompressed = ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH;
    1838         [ +  - ]:      324101 :     auto split = Split(sp, '/');
    1839   [ +  -  -  + ]:      648202 :     std::string str(split[0].begin(), split[0].end());
    1840   [ -  +  +  + ]:      324101 :     if (str.size() == 0) {
    1841         [ +  - ]:          88 :         error = "No key provided";
    1842                 :          88 :         return {};
    1843                 :             :     }
    1844   [ +  +  +  + ]:      324013 :     if (IsSpace(str.front()) || IsSpace(str.back())) {
    1845         [ +  - ]:          23 :         error = strprintf("Key '%s' is invalid due to whitespace", str);
    1846                 :          23 :         return {};
    1847                 :             :     }
    1848   [ -  +  +  + ]:      323990 :     if (split.size() == 1) {
    1849   [ +  -  +  + ]:      239796 :         if (IsHex(str)) {
    1850   [ -  +  +  - ]:       93257 :             std::vector<unsigned char> data = ParseHex(str);
    1851         [ -  + ]:       93257 :             CPubKey pubkey(data);
    1852   [ +  +  +  + ]:       93257 :             if (pubkey.IsValid() && !pubkey.IsValidNonHybrid()) {
    1853         [ +  - ]:          14 :                 error = "Hybrid public keys are not allowed";
    1854                 :          14 :                 return {};
    1855                 :             :             }
    1856   [ +  -  +  + ]:       93243 :             if (pubkey.IsFullyValid()) {
    1857   [ +  +  +  + ]:       57339 :                 if (permit_uncompressed || pubkey.IsCompressed()) {
    1858   [ +  -  +  - ]:       57334 :                     ret.emplace_back(std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, false));
    1859                 :       57334 :                     return ret;
    1860                 :             :                 } else {
    1861         [ +  - ]:           5 :                     error = "Uncompressed keys are not allowed";
    1862                 :           5 :                     return {};
    1863                 :             :                 }
    1864   [ -  +  +  +  :       35904 :             } else if (data.size() == 32 && ctx == ParseScriptContext::P2TR) {
                   +  + ]
    1865                 :       35732 :                 unsigned char fullkey[33] = {0x02};
    1866                 :       35732 :                 std::copy(data.begin(), data.end(), fullkey + 1);
    1867                 :       35732 :                 pubkey.Set(std::begin(fullkey), std::end(fullkey));
    1868   [ +  -  +  + ]:       35732 :                 if (pubkey.IsFullyValid()) {
    1869   [ +  -  +  - ]:       35710 :                     ret.emplace_back(std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, true));
    1870                 :       35710 :                     return ret;
    1871                 :             :                 }
    1872                 :             :             }
    1873         [ +  - ]:         194 :             error = strprintf("Pubkey '%s' is invalid", str);
    1874                 :         194 :             return {};
    1875                 :       93257 :         }
    1876         [ +  - ]:      146539 :         CKey key = DecodeSecret(str);
    1877         [ +  + ]:      146539 :         if (key.IsValid()) {
    1878   [ +  +  -  + ]:       89800 :             if (permit_uncompressed || key.IsCompressed()) {
    1879         [ +  - ]:       89800 :                 CPubKey pubkey = key.GetPubKey();
    1880   [ +  -  +  - ]:       89800 :                 out.keys.emplace(pubkey.GetID(), key);
    1881   [ +  -  +  - ]:       89800 :                 ret.emplace_back(std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, ctx == ParseScriptContext::P2TR));
    1882                 :       89800 :                 return ret;
    1883                 :             :             } else {
    1884         [ #  # ]:           0 :                 error = "Uncompressed keys are not allowed";
    1885                 :           0 :                 return {};
    1886                 :             :             }
    1887                 :             :         }
    1888                 :      146539 :     }
    1889         [ +  - ]:      140933 :     CExtKey extkey = DecodeExtKey(str);
    1890         [ +  - ]:      140933 :     CExtPubKey extpubkey = DecodeExtPubKey(str);
    1891   [ +  +  +  + ]:      140933 :     if (!extkey.key.IsValid() && !extpubkey.pubkey.IsValid()) {
    1892         [ +  - ]:         458 :         error = strprintf("key '%s' is not valid", str);
    1893                 :         458 :         return {};
    1894                 :             :     }
    1895                 :      140475 :     std::vector<KeyPath> paths;
    1896                 :      140475 :     DeriveType type = ParseDeriveType(split, apostrophe);
    1897   [ +  -  +  + ]:      140475 :     if (!ParseKeyPath(split, paths, apostrophe, error, /*allow_multipath=*/true)) return {};
    1898         [ +  + ]:      140349 :     if (extkey.key.IsValid()) {
    1899         [ +  - ]:      119199 :         extpubkey = extkey.Neuter();
    1900   [ +  -  +  - ]:      119199 :         out.keys.emplace(extpubkey.pubkey.GetID(), extkey.key);
    1901                 :             :     }
    1902         [ +  + ]:      314512 :     for (auto& path : paths) {
    1903   [ +  -  +  - ]:      348326 :         ret.emplace_back(std::make_unique<BIP32PubkeyProvider>(key_exp_index, extpubkey, std::move(path), type, apostrophe));
    1904                 :             :     }
    1905                 :      140349 :     return ret;
    1906                 :      605509 : }
    1907                 :             : 
    1908                 :             : /** Parse a public key including origin information (if enabled). */
    1909                 :             : // NOLINTNEXTLINE(misc-no-recursion)
    1910                 :      330280 : 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)
    1911                 :             : {
    1912                 :      330280 :     std::vector<std::unique_ptr<PubkeyProvider>> ret;
    1913                 :             : 
    1914                 :      330280 :     using namespace script;
    1915                 :             : 
    1916                 :             :     // musig cannot be nested inside of an origin
    1917                 :      330280 :     std::span<const char> span = sp;
    1918   [ +  -  +  -  :      330280 :     if (Const("musig(", span, /*skip=*/false)) {
                   +  + ]
    1919         [ +  + ]:        5915 :         if (ctx != ParseScriptContext::P2TR) {
    1920         [ +  - ]:          10 :             error = "musig() is only allowed in tr() and rawtr()";
    1921                 :          10 :             return {};
    1922                 :             :         }
    1923                 :             : 
    1924                 :             :         // Split the span on the end parentheses. The end parentheses must
    1925                 :             :         // be included in the resulting span so that Expr is happy.
    1926         [ +  - ]:        5905 :         auto split = Split(sp, ')', /*include_sep=*/true);
    1927   [ -  +  +  + ]:        5905 :         if (split.size() > 2) {
    1928         [ +  - ]:         130 :             error = "Too many ')' in musig() expression";
    1929                 :         130 :             return {};
    1930                 :             :         }
    1931   [ +  -  +  -  :        5775 :         std::span<const char> expr(split.at(0).begin(), split.at(0).end());
                   +  - ]
    1932   [ +  -  +  -  :        5775 :         if (!Func("musig", expr)) {
                   +  + ]
    1933         [ +  - ]:          10 :             error = "Invalid musig() expression";
    1934                 :          10 :             return {};
    1935                 :             :         }
    1936                 :             : 
    1937                 :             :         // Parse the participant pubkeys
    1938                 :        5765 :         bool any_ranged = false;
    1939                 :        5765 :         bool all_bip32 = true;
    1940                 :        5765 :         std::vector<std::vector<std::unique_ptr<PubkeyProvider>>> providers;
    1941                 :        5765 :         bool any_key_parsed = false;
    1942                 :        5765 :         size_t max_multipath_len = 0;
    1943         [ +  + ]:       56627 :         while (expr.size()) {
    1944   [ +  +  +  -  :       96159 :             if (any_key_parsed && !Const(",", expr)) {
          +  -  +  +  +  
                +  -  - ]
    1945         [ +  - ]:          11 :                 error = strprintf("musig(): expected ',', got '%c'", expr[0]);
    1946                 :          11 :                 return {};
    1947                 :             :             }
    1948         [ +  - ]:       50948 :             auto arg = Expr(expr);
    1949         [ +  - ]:       50948 :             auto pk = ParsePubkey(key_exp_index, arg, ParseScriptContext::MUSIG, out, error);
    1950         [ +  + ]:       50948 :             if (pk.empty()) {
    1951         [ +  - ]:          86 :                 error = strprintf("musig(): %s", error);
    1952                 :          86 :                 return {};
    1953                 :             :             }
    1954                 :       50862 :             any_key_parsed = true;
    1955                 :             : 
    1956   [ +  +  +  -  :       88750 :             any_ranged = any_ranged || pk.at(0)->IsRange();
                   +  + ]
    1957   [ +  +  +  -  :       60537 :             all_bip32 = all_bip32 &&  pk.at(0)->IsBIP32();
                   +  + ]
    1958                 :             : 
    1959   [ -  +  +  + ]:       50862 :             max_multipath_len = std::max(max_multipath_len, pk.size());
    1960                 :             : 
    1961         [ +  - ]:       50862 :             providers.emplace_back(std::move(pk));
    1962                 :       50862 :             key_exp_index++;
    1963                 :       50948 :         }
    1964         [ +  + ]:        5668 :         if (!any_key_parsed) {
    1965         [ +  - ]:           6 :             error = "musig(): Must contain key expressions";
    1966                 :           6 :             return {};
    1967                 :             :         }
    1968                 :             : 
    1969                 :             :         // Parse any derivation
    1970                 :        5662 :         DeriveType deriv_type = DeriveType::NO;
    1971                 :        5662 :         std::vector<KeyPath> derivation_multipaths;
    1972   [ -  +  +  -  :       16986 :         if (split.size() == 2 && Const("/", split.at(1), /*skip=*/false)) {
          +  -  +  -  +  
                +  +  + ]
    1973         [ +  + ]:         352 :             if (!all_bip32) {
    1974         [ +  - ]:          12 :                 error = "musig(): derivation requires all participants to be xpubs or xprvs";
    1975                 :          12 :                 return {};
    1976                 :             :             }
    1977         [ +  + ]:         340 :             if (any_ranged) {
    1978         [ +  - ]:           5 :                 error = "musig(): Cannot have ranged participant keys if musig() also has derivation";
    1979                 :           5 :                 return {};
    1980                 :             :             }
    1981                 :         335 :             bool dummy = false;
    1982   [ +  -  +  - ]:         335 :             auto deriv_split = Split(split.at(1), '/');
    1983                 :         335 :             deriv_type = ParseDeriveType(deriv_split, dummy);
    1984         [ +  + ]:         335 :             if (deriv_type == DeriveType::HARDENED) {
    1985         [ +  - ]:           4 :                 error = "musig(): Cannot have hardened child derivation";
    1986                 :           4 :                 return {};
    1987                 :             :             }
    1988                 :         331 :             bool has_hardened = false;
    1989   [ +  -  +  + ]:         331 :             if (!ParseKeyPath(deriv_split, derivation_multipaths, dummy, error, /*allow_multipath=*/true, has_hardened)) {
    1990         [ +  - ]:           5 :                 error = "musig(): " + error;
    1991                 :           5 :                 return {};
    1992                 :             :             }
    1993         [ +  + ]:         326 :             if (has_hardened) {
    1994         [ +  - ]:           7 :                 error = "musig(): cannot have hardened derivation steps";
    1995                 :           7 :                 return {};
    1996                 :             :             }
    1997                 :         335 :         } else {
    1998         [ +  - ]:        5310 :             derivation_multipaths.emplace_back();
    1999                 :             :         }
    2000                 :             : 
    2001                 :             :         // Makes sure that all providers vectors in providers are the given length, or exactly length 1
    2002                 :             :         // Length 1 vectors have the single provider cloned until it matches the given length.
    2003                 :        6141 :         const auto& clone_providers = [&providers](size_t length) -> bool {
    2004         [ +  + ]:        7205 :             for (auto& multipath_providers : providers) {
    2005   [ -  +  +  + ]:        6698 :                 if (multipath_providers.size() == 1) {
    2006         [ +  + ]:       35525 :                     for (size_t i = 1; i < length; ++i) {
    2007         [ +  - ]:       29487 :                         multipath_providers.emplace_back(multipath_providers.at(0)->Clone());
    2008                 :             :                     }
    2009         [ +  + ]:         660 :                 } else if (multipath_providers.size() != length) {
    2010                 :             :                     return false;
    2011                 :             :                 }
    2012                 :             :             }
    2013                 :             :             return true;
    2014                 :        5629 :         };
    2015                 :             : 
    2016                 :             :         // Emplace the final MuSigPubkeyProvider into ret with the pubkey providers from the specified provider vectors index
    2017                 :             :         // and the path from the specified path index
    2018                 :       13117 :         const auto& emplace_final_provider = [&ret, &key_exp_index, &deriv_type, &derivation_multipaths, &providers](size_t vec_idx, size_t path_idx) -> void {
    2019                 :        7488 :             KeyPath& path = derivation_multipaths.at(path_idx);
    2020                 :        7488 :             std::vector<std::unique_ptr<PubkeyProvider>> pubs;
    2021   [ -  +  +  - ]:        7488 :             pubs.reserve(providers.size());
    2022         [ +  + ]:       87683 :             for (auto& vec : providers) {
    2023   [ +  -  +  - ]:       80195 :                 pubs.emplace_back(std::move(vec.at(vec_idx)));
    2024                 :             :             }
    2025   [ +  -  +  - ]:        7488 :             ret.emplace_back(std::make_unique<MuSigPubkeyProvider>(key_exp_index, std::move(pubs), path, deriv_type));
    2026                 :        7488 :         };
    2027                 :             : 
    2028   [ +  +  +  + ]:        6086 :         if (max_multipath_len > 1 && derivation_multipaths.size() > 1) {
    2029         [ +  - ]:           4 :             error = "musig(): Cannot have multipath participant keys if musig() is also multipath";
    2030                 :           4 :             return {};
    2031         [ +  + ]:        5625 :         } else if (max_multipath_len > 1) {
    2032   [ +  -  +  + ]:         453 :             if (!clone_providers(max_multipath_len)) {
    2033         [ +  - ]:           5 :                 error = strprintf("musig(): Multipath derivation paths have mismatched lengths");
    2034                 :           5 :                 return {};
    2035                 :             :             }
    2036         [ +  + ]:        2489 :             for (size_t i = 0; i < max_multipath_len; ++i) {
    2037                 :             :                 // Final MuSigPubkeyProvider uses participant pubkey providers at each multipath position, and the first (and only) path
    2038         [ +  - ]:        2041 :                 emplace_final_provider(i, 0);
    2039                 :             :             }
    2040   [ -  +  +  + ]:        5172 :         } else if (derivation_multipaths.size() > 1) {
    2041                 :             :             // All key provider vectors should be length 1. Clone them until they have the same length as paths
    2042   [ +  -  -  +  :          59 :             if (!Assume(clone_providers(derivation_multipaths.size()))) {
                   -  + ]
    2043         [ #  # ]:           0 :                 error = "musig(): Multipath derivation path with multipath participants is disallowed"; // This error is unreachable due to earlier check
    2044                 :           0 :                 return {};
    2045                 :             :             }
    2046   [ -  +  +  + ]:         393 :             for (size_t i = 0; i < derivation_multipaths.size(); ++i) {
    2047                 :             :                 // Final MuSigPubkeyProvider uses cloned participant pubkey providers, and the multipath derivation paths
    2048         [ +  - ]:         334 :                 emplace_final_provider(i, i);
    2049                 :             :             }
    2050                 :             :         } else {
    2051                 :             :             // No multipath derivation, MuSigPubkeyProvider uses the first (and only) participant pubkey providers, and the first (and only) path
    2052         [ +  - ]:        5113 :             emplace_final_provider(0, 0);
    2053                 :             :         }
    2054                 :        5620 :         return ret;
    2055                 :       11670 :     }
    2056                 :             : 
    2057         [ +  - ]:      324365 :     auto origin_split = Split(sp, ']');
    2058   [ -  +  +  + ]:      324365 :     if (origin_split.size() > 2) {
    2059         [ +  - ]:          10 :         error = "Multiple ']' characters found for a single pubkey";
    2060                 :          10 :         return {};
    2061                 :             :     }
    2062                 :             :     // This is set if either the origin or path suffix contains a hardened derivation.
    2063                 :      324355 :     bool apostrophe = false;
    2064         [ +  + ]:      324355 :     if (origin_split.size() == 1) {
    2065         [ +  - ]:      288479 :         return ParsePubkeyInner(key_exp_index, origin_split[0], ctx, out, apostrophe, error);
    2066                 :             :     }
    2067   [ +  +  +  + ]:       35876 :     if (origin_split[0].empty() || origin_split[0][0] != '[') {
    2068                 :          78 :         error = strprintf("Key origin start '[ character expected but not found, got '%c' instead",
    2069   [ +  +  +  - ]:          26 :                           origin_split[0].empty() ? /** empty, implies split char */ ']' : origin_split[0][0]);
    2070                 :          26 :         return {};
    2071                 :             :     }
    2072         [ +  - ]:       35850 :     auto slash_split = Split(origin_split[0].subspan(1), '/');
    2073         [ +  + ]:       35850 :     if (slash_split[0].size() != 8) {
    2074         [ +  - ]:          13 :         error = strprintf("Fingerprint is not 4 bytes (%u characters instead of 8 characters)", slash_split[0].size());
    2075                 :          13 :         return {};
    2076                 :             :     }
    2077   [ +  -  -  + ]:       71674 :     std::string fpr_hex = std::string(slash_split[0].begin(), slash_split[0].end());
    2078   [ -  +  +  -  :       35837 :     if (!IsHex(fpr_hex)) {
                   +  + ]
    2079         [ +  - ]:          13 :         error = strprintf("Fingerprint '%s' is not hex", fpr_hex);
    2080                 :          13 :         return {};
    2081                 :             :     }
    2082   [ -  +  +  - ]:       35824 :     auto fpr_bytes = ParseHex(fpr_hex);
    2083         [ -  + ]:       35824 :     KeyOriginInfo info;
    2084                 :       35824 :     static_assert(sizeof(info.fingerprint) == 4, "Fingerprint must be 4 bytes");
    2085   [ -  +  -  + ]:       35824 :     assert(fpr_bytes.size() == 4);
    2086                 :       35824 :     std::copy(fpr_bytes.begin(), fpr_bytes.end(), info.fingerprint);
    2087                 :       35824 :     std::vector<KeyPath> path;
    2088   [ +  -  +  + ]:       35824 :     if (!ParseKeyPath(slash_split, path, apostrophe, error, /*allow_multipath=*/false)) return {};
    2089   [ +  -  +  - ]:       35622 :     info.path = path.at(0);
    2090         [ +  - ]:       35622 :     auto providers = ParsePubkeyInner(key_exp_index, origin_split[1], ctx, out, apostrophe, error);
    2091         [ +  + ]:       35622 :     if (providers.empty()) return {};
    2092   [ -  +  +  - ]:       35548 :     ret.reserve(providers.size());
    2093         [ +  + ]:       73057 :     for (auto& prov : providers) {
    2094   [ +  -  +  - ]:       75018 :         ret.emplace_back(std::make_unique<OriginPubkeyProvider>(key_exp_index, info, std::move(prov), apostrophe));
    2095                 :             :     }
    2096                 :       35548 :     return ret;
    2097                 :      437791 : }
    2098                 :             : 
    2099                 :      184540 : std::unique_ptr<PubkeyProvider> InferPubkey(const CPubKey& pubkey, ParseScriptContext ctx, const SigningProvider& provider)
    2100                 :             : {
    2101                 :             :     // Key cannot be hybrid
    2102         [ +  + ]:      184540 :     if (!pubkey.IsValidNonHybrid()) {
    2103                 :        5181 :         return nullptr;
    2104                 :             :     }
    2105                 :             :     // Uncompressed is only allowed in TOP and P2SH contexts
    2106   [ +  +  -  + ]:      179359 :     if (ctx != ParseScriptContext::TOP && ctx != ParseScriptContext::P2SH && !pubkey.IsCompressed()) {
    2107                 :           0 :         return nullptr;
    2108                 :             :     }
    2109                 :      179359 :     std::unique_ptr<PubkeyProvider> key_provider = std::make_unique<ConstPubkeyProvider>(0, pubkey, false);
    2110         [ +  - ]:      179359 :     KeyOriginInfo info;
    2111   [ +  -  +  -  :      179359 :     if (provider.GetKeyOrigin(pubkey.GetID(), info)) {
                   +  + ]
    2112   [ +  -  -  + ]:       20732 :         return std::make_unique<OriginPubkeyProvider>(0, std::move(info), std::move(key_provider), /*apostrophe=*/false);
    2113                 :             :     }
    2114                 :      158627 :     return key_provider;
    2115                 :      179359 : }
    2116                 :             : 
    2117                 :      218319 : std::unique_ptr<PubkeyProvider> InferXOnlyPubkey(const XOnlyPubKey& xkey, ParseScriptContext ctx, const SigningProvider& provider)
    2118                 :             : {
    2119                 :      218319 :     CPubKey pubkey{xkey.GetEvenCorrespondingCPubKey()};
    2120                 :      218319 :     std::unique_ptr<PubkeyProvider> key_provider = std::make_unique<ConstPubkeyProvider>(0, pubkey, true);
    2121         [ +  - ]:      218319 :     KeyOriginInfo info;
    2122   [ +  -  +  + ]:      218319 :     if (provider.GetKeyOriginByXOnly(xkey, info)) {
    2123   [ +  -  -  + ]:      208339 :         return std::make_unique<OriginPubkeyProvider>(0, std::move(info), std::move(key_provider), /*apostrophe=*/false);
    2124                 :             :     }
    2125                 :        9980 :     return key_provider;
    2126                 :      218319 : }
    2127                 :             : 
    2128                 :             : /**
    2129                 :             :  * The context for parsing a Miniscript descriptor (either from Script or from its textual representation).
    2130                 :             :  */
    2131                 :       31161 : struct KeyParser {
    2132                 :             :     //! The Key type is an index in DescriptorImpl::m_pubkey_args
    2133                 :             :     using Key = uint32_t;
    2134                 :             :     //! Must not be nullptr if parsing from string.
    2135                 :             :     FlatSigningProvider* m_out;
    2136                 :             :     //! Must not be nullptr if parsing from Script.
    2137                 :             :     const SigningProvider* m_in;
    2138                 :             :     //! List of multipath expanded keys contained in the Miniscript.
    2139                 :             :     mutable std::vector<std::vector<std::unique_ptr<PubkeyProvider>>> m_keys;
    2140                 :             :     //! Used to detect key parsing errors within a Miniscript.
    2141                 :             :     mutable std::string m_key_parsing_error;
    2142                 :             :     //! The script context we're operating within (Tapscript or P2WSH).
    2143                 :             :     const miniscript::MiniscriptContext m_script_ctx;
    2144                 :             :     //! The number of keys that were parsed before starting to parse this Miniscript descriptor.
    2145                 :             :     uint32_t m_offset;
    2146                 :             : 
    2147                 :       31161 :     KeyParser(FlatSigningProvider* out LIFETIMEBOUND, const SigningProvider* in LIFETIMEBOUND,
    2148                 :             :               miniscript::MiniscriptContext ctx, uint32_t offset = 0)
    2149                 :       31161 :         : m_out(out), m_in(in), m_script_ctx(ctx), m_offset(offset) {}
    2150                 :             : 
    2151                 :      278992 :     bool KeyCompare(const Key& a, const Key& b) const {
    2152                 :      278992 :         return *m_keys.at(a).at(0) < *m_keys.at(b).at(0);
    2153                 :             :     }
    2154                 :             : 
    2155                 :      102123 :     ParseScriptContext ParseContext() const {
    2156      [ +  -  + ]:      102123 :         switch (m_script_ctx) {
    2157                 :             :             case miniscript::MiniscriptContext::P2WSH: return ParseScriptContext::P2WSH;
    2158                 :       63913 :             case miniscript::MiniscriptContext::TAPSCRIPT: return ParseScriptContext::P2TR;
    2159                 :             :         }
    2160                 :           0 :         assert(false);
    2161                 :             :     }
    2162                 :             : 
    2163                 :       77954 :     template<typename I> std::optional<Key> FromString(I begin, I end) const
    2164                 :             :     {
    2165         [ -  + ]:       77954 :         assert(m_out);
    2166         [ -  + ]:       77954 :         Key key = m_keys.size();
    2167                 :       77954 :         uint32_t exp_index = m_offset + key;
    2168                 :       77954 :         auto pk = ParsePubkey(exp_index, {&*begin, &*end}, ParseContext(), *m_out, m_key_parsing_error);
    2169         [ +  + ]:       77954 :         if (pk.empty()) return {};
    2170         [ +  - ]:       77626 :         m_keys.emplace_back(std::move(pk));
    2171                 :       77626 :         return key;
    2172                 :       77954 :     }
    2173                 :             : 
    2174                 :       26576 :     std::optional<std::string> ToString(const Key& key, bool&) const
    2175                 :             :     {
    2176                 :       26576 :         return m_keys.at(key).at(0)->ToString();
    2177                 :             :     }
    2178                 :             : 
    2179                 :       21867 :     template<typename I> std::optional<Key> FromPKBytes(I begin, I end) const
    2180                 :             :     {
    2181         [ -  + ]:       21867 :         assert(m_in);
    2182         [ -  + ]:       21867 :         Key key = m_keys.size();
    2183   [ +  +  +  - ]:       21867 :         if (miniscript::IsTapscript(m_script_ctx) && end - begin == 32) {
    2184                 :       10377 :             XOnlyPubKey pubkey;
    2185                 :       10377 :             std::copy(begin, end, pubkey.begin());
    2186         [ +  - ]:       10377 :             if (auto pubkey_provider = InferXOnlyPubkey(pubkey, ParseContext(), *m_in)) {
    2187         [ +  - ]:       10377 :                 m_keys.emplace_back();
    2188         [ +  - ]:       10377 :                 m_keys.back().push_back(std::move(pubkey_provider));
    2189                 :       10377 :                 return key;
    2190                 :             :             }
    2191         [ +  - ]:       11490 :         } else if (!miniscript::IsTapscript(m_script_ctx)) {
    2192                 :       11490 :             CPubKey pubkey(begin, end);
    2193         [ +  + ]:       11490 :             if (auto pubkey_provider = InferPubkey(pubkey, ParseContext(), *m_in)) {
    2194         [ +  - ]:       11477 :                 m_keys.emplace_back();
    2195         [ +  - ]:       11477 :                 m_keys.back().push_back(std::move(pubkey_provider));
    2196                 :       11477 :                 return key;
    2197                 :             :             }
    2198                 :             :         }
    2199                 :          13 :         return {};
    2200                 :             :     }
    2201                 :             : 
    2202         [ -  + ]:        2303 :     template<typename I> std::optional<Key> FromPKHBytes(I begin, I end) const
    2203                 :             :     {
    2204         [ -  + ]:        2303 :         assert(end - begin == 20);
    2205         [ -  + ]:        2303 :         assert(m_in);
    2206                 :        2303 :         uint160 hash;
    2207                 :        2303 :         std::copy(begin, end, hash.begin());
    2208                 :        2303 :         CKeyID keyid(hash);
    2209                 :        2303 :         CPubKey pubkey;
    2210         [ +  + ]:        2303 :         if (m_in->GetPubKey(keyid, pubkey)) {
    2211         [ +  - ]:        2302 :             if (auto pubkey_provider = InferPubkey(pubkey, ParseContext(), *m_in)) {
    2212         [ -  + ]:        2302 :                 Key key = m_keys.size();
    2213         [ +  - ]:        2302 :                 m_keys.emplace_back();
    2214         [ +  - ]:        2302 :                 m_keys.back().push_back(std::move(pubkey_provider));
    2215                 :        2302 :                 return key;
    2216                 :             :             }
    2217                 :             :         }
    2218                 :           1 :         return {};
    2219                 :             :     }
    2220                 :             : 
    2221                 :     7797351 :     miniscript::MiniscriptContext MsContext() const {
    2222   [ +  -  +  -  :     7797351 :         return m_script_ctx;
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  +  +  
                -  +  - ]
    2223                 :             :     }
    2224                 :             : };
    2225                 :             : 
    2226                 :             : /** Parse a script in a particular context. */
    2227                 :             : // NOLINTNEXTLINE(misc-no-recursion)
    2228                 :       71686 : std::vector<std::unique_ptr<DescriptorImpl>> ParseScript(uint32_t& key_exp_index, std::span<const char>& sp, ParseScriptContext ctx, FlatSigningProvider& out, std::string& error)
    2229                 :             : {
    2230                 :       71686 :     using namespace script;
    2231   [ +  +  -  +  :       71686 :     Assume(ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH || ctx == ParseScriptContext::P2TR);
                   -  + ]
    2232                 :       71686 :     std::vector<std::unique_ptr<DescriptorImpl>> ret;
    2233         [ +  - ]:       71686 :     auto expr = Expr(sp);
    2234   [ +  -  +  -  :       71686 :     if (Func("pk", expr)) {
                   +  + ]
    2235         [ +  - ]:       10745 :         auto pubkeys = ParsePubkey(key_exp_index, expr, ctx, out, error);
    2236         [ +  + ]:       10745 :         if (pubkeys.empty()) {
    2237         [ +  - ]:         313 :             error = strprintf("pk(): %s", error);
    2238                 :         313 :             return {};
    2239                 :             :         }
    2240                 :       10432 :         ++key_exp_index;
    2241         [ +  + ]:       21772 :         for (auto& pubkey : pubkeys) {
    2242   [ +  -  +  - ]:       22680 :             ret.emplace_back(std::make_unique<PKDescriptor>(std::move(pubkey), ctx == ParseScriptContext::P2TR));
    2243                 :             :         }
    2244                 :       10432 :         return ret;
    2245                 :       10745 :     }
    2246   [ +  +  +  -  :      108479 :     if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH) && Func("pkh", expr)) {
          +  -  +  +  +  
                      + ]
    2247         [ +  - ]:        4726 :         auto pubkeys = ParsePubkey(key_exp_index, expr, ctx, out, error);
    2248         [ +  + ]:        4726 :         if (pubkeys.empty()) {
    2249         [ +  - ]:          23 :             error = strprintf("pkh(): %s", error);
    2250                 :          23 :             return {};
    2251                 :             :         }
    2252                 :        4703 :         ++key_exp_index;
    2253         [ +  + ]:       10035 :         for (auto& pubkey : pubkeys) {
    2254   [ +  -  +  - ]:       10664 :             ret.emplace_back(std::make_unique<PKHDescriptor>(std::move(pubkey)));
    2255                 :             :         }
    2256                 :        4703 :         return ret;
    2257                 :        4726 :     }
    2258   [ +  +  +  -  :       89660 :     if (ctx == ParseScriptContext::TOP && Func("combo", expr)) {
          +  -  +  +  +  
                      + ]
    2259         [ +  - ]:         642 :         auto pubkeys = ParsePubkey(key_exp_index, expr, ctx, out, error);
    2260         [ +  + ]:         642 :         if (pubkeys.empty()) {
    2261         [ +  - ]:          26 :             error = strprintf("combo(): %s", error);
    2262                 :          26 :             return {};
    2263                 :             :         }
    2264                 :         616 :         ++key_exp_index;
    2265         [ +  + ]:        1754 :         for (auto& pubkey : pubkeys) {
    2266   [ +  -  +  - ]:        2276 :             ret.emplace_back(std::make_unique<ComboDescriptor>(std::move(pubkey)));
    2267                 :             :         }
    2268                 :         616 :         return ret;
    2269   [ +  -  +  -  :       56215 :     } else if (Func("combo", expr)) {
                   +  + ]
    2270         [ +  - ]:           6 :         error = "Can only have combo() at top level";
    2271                 :           6 :         return {};
    2272                 :             :     }
    2273   [ +  -  +  - ]:       55567 :     const bool multi = Func("multi", expr);
    2274   [ +  +  +  -  :      110046 :     const bool sortedmulti = !multi && Func("sortedmulti", expr);
             +  -  +  + ]
    2275   [ +  +  +  -  :      109431 :     const bool multi_a = !(multi || sortedmulti) && Func("multi_a", expr);
             +  -  +  + ]
    2276   [ +  +  +  +  :      108180 :     const bool sortedmulti_a = !(multi || sortedmulti || multi_a) && Func("sortedmulti_a", expr);
          +  -  +  -  +  
                      + ]
    2277   [ +  +  +  +  :       55567 :     if (((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH) && (multi || sortedmulti)) ||
             +  +  +  + ]
    2278   [ +  +  +  + ]:       13403 :         (ctx == ParseScriptContext::P2TR && (multi_a || sortedmulti_a))) {
    2279         [ +  - ]:        3983 :         auto threshold = Expr(expr);
    2280                 :        3983 :         uint32_t thres;
    2281                 :        3983 :         std::vector<std::vector<std::unique_ptr<PubkeyProvider>>> providers; // List of multipath expanded pubkeys
    2282         [ +  + ]:        3983 :         if (const auto maybe_thres{ToIntegral<uint32_t>(std::string_view{threshold.begin(), threshold.end()})}) {
    2283                 :        3818 :             thres = *maybe_thres;
    2284                 :             :         } else {
    2285   [ +  -  +  - ]:         330 :             error = strprintf("Multi threshold '%s' is not valid", std::string(threshold.begin(), threshold.end()));
    2286                 :         165 :             return {};
    2287                 :             :         }
    2288                 :        3818 :         size_t script_size = 0;
    2289                 :        3818 :         size_t max_providers_len = 0;
    2290         [ +  + ]:      173053 :         while (expr.size()) {
    2291   [ +  -  +  -  :      169506 :             if (!Const(",", expr)) {
                   +  + ]
    2292         [ +  - ]:           9 :                 error = strprintf("Multi: expected ',', got '%c'", expr[0]);
    2293                 :           9 :                 return {};
    2294                 :             :             }
    2295         [ +  - ]:      169497 :             auto arg = Expr(expr);
    2296         [ +  - ]:      169497 :             auto pks = ParsePubkey(key_exp_index, arg, ctx, out, error);
    2297         [ +  + ]:      169497 :             if (pks.empty()) {
    2298         [ +  - ]:         262 :                 error = strprintf("Multi: %s", error);
    2299                 :         262 :                 return {};
    2300                 :             :             }
    2301   [ +  -  +  - ]:      169235 :             script_size += pks.at(0)->GetSize() + 1;
    2302   [ -  +  +  + ]:      169235 :             max_providers_len = std::max(max_providers_len, pks.size());
    2303         [ +  - ]:      169235 :             providers.emplace_back(std::move(pks));
    2304                 :      169235 :             key_exp_index++;
    2305                 :      169497 :         }
    2306   [ +  +  +  +  :        4845 :         if ((multi || sortedmulti) && (providers.empty() || providers.size() > MAX_PUBKEYS_PER_MULTISIG)) {
             +  +  +  + ]
    2307   [ -  +  +  - ]:          34 :             error = strprintf("Cannot have %u keys in multisig; must have between 1 and %d keys, inclusive", providers.size(), MAX_PUBKEYS_PER_MULTISIG);
    2308                 :          34 :             return {};
    2309   [ +  +  +  +  :        5727 :         } else if ((multi_a || sortedmulti_a) && (providers.empty() || providers.size() > MAX_PUBKEYS_PER_MULTI_A)) {
             +  +  -  + ]
    2310   [ -  +  +  - ]:          19 :             error = strprintf("Cannot have %u keys in multi_a; must have between 1 and %d keys, inclusive", providers.size(), MAX_PUBKEYS_PER_MULTI_A);
    2311                 :          19 :             return {};
    2312         [ +  + ]:        3494 :         } else if (thres < 1) {
    2313         [ +  - ]:          12 :             error = strprintf("Multisig threshold cannot be %d, must be at least 1", thres);
    2314                 :          12 :             return {};
    2315   [ -  +  +  + ]:        3482 :         } else if (thres > providers.size()) {
    2316         [ +  - ]:          19 :             error = strprintf("Multisig threshold cannot be larger than the number of keys; threshold is %d but only %u keys specified", thres, providers.size());
    2317                 :          19 :             return {};
    2318                 :             :         }
    2319         [ +  + ]:        3463 :         if (ctx == ParseScriptContext::TOP) {
    2320         [ +  + ]:         461 :             if (providers.size() > 3) {
    2321         [ +  - ]:          21 :                 error = strprintf("Cannot have %u pubkeys in bare multisig; only at most 3 pubkeys", providers.size());
    2322                 :          21 :                 return {};
    2323                 :             :             }
    2324                 :             :         }
    2325         [ +  + ]:        3442 :         if (ctx == ParseScriptContext::P2SH) {
    2326                 :             :             // This limits the maximum number of compressed pubkeys to 15.
    2327         [ +  + ]:         490 :             if (script_size + 3 > MAX_SCRIPT_ELEMENT_SIZE) {
    2328         [ +  - ]:          10 :                 error = strprintf("P2SH script is too large, %d bytes is larger than %d bytes", script_size + 3, MAX_SCRIPT_ELEMENT_SIZE);
    2329                 :          10 :                 return {};
    2330                 :             :             }
    2331                 :             :         }
    2332                 :             : 
    2333                 :             :         // Make sure all vecs are of the same length, or exactly length 1
    2334                 :             :         // For length 1 vectors, clone key providers until vector is the same length
    2335         [ +  + ]:      155613 :         for (auto& vec : providers) {
    2336   [ -  +  +  + ]:      152189 :             if (vec.size() == 1) {
    2337         [ +  + ]:      326332 :                 for (size_t i = 1; i < max_providers_len; ++i) {
    2338   [ +  -  +  -  :      174977 :                     vec.emplace_back(vec.at(0)->Clone());
                   +  - ]
    2339                 :             :                 }
    2340         [ +  + ]:         834 :             } else if (vec.size() != max_providers_len) {
    2341         [ +  - ]:           8 :                 error = strprintf("multi(): Multipath derivation paths have mismatched lengths");
    2342                 :           8 :                 return {};
    2343                 :             :             }
    2344                 :             :         }
    2345                 :             : 
    2346                 :             :         // Build the final descriptors vector
    2347         [ +  + ]:        9364 :         for (size_t i = 0; i < max_providers_len; ++i) {
    2348                 :             :             // Build final pubkeys vectors by retrieving the i'th subscript for each vector in subscripts
    2349                 :        5940 :             std::vector<std::unique_ptr<PubkeyProvider>> pubs;
    2350   [ -  +  +  - ]:        5940 :             pubs.reserve(providers.size());
    2351         [ +  + ]:      336848 :             for (auto& pub : providers) {
    2352   [ +  -  +  - ]:      330908 :                 pubs.emplace_back(std::move(pub.at(i)));
    2353                 :             :             }
    2354   [ +  +  +  + ]:        5940 :             if (multi || sortedmulti) {
    2355   [ +  -  +  - ]:        5020 :                 ret.emplace_back(std::make_unique<MultisigDescriptor>(thres, std::move(pubs), sortedmulti));
    2356                 :             :             } else {
    2357   [ +  -  +  - ]:        6860 :                 ret.emplace_back(std::make_unique<MultiADescriptor>(thres, std::move(pubs), sortedmulti_a));
    2358                 :             :             }
    2359                 :        5940 :         }
    2360                 :        3424 :         return ret;
    2361   [ +  +  +  + ]:       55567 :     } else if (multi || sortedmulti) {
    2362         [ +  - ]:          13 :         error = "Can only have multi/sortedmulti at top level, in sh(), or in wsh()";
    2363                 :          13 :         return {};
    2364   [ +  +  +  + ]:       51571 :     } else if (multi_a || sortedmulti_a) {
    2365         [ +  - ]:          11 :         error = "Can only have multi_a/sortedmulti_a inside tr()";
    2366                 :          11 :         return {};
    2367                 :             :     }
    2368   [ +  +  +  -  :       87013 :     if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH) && Func("wpkh", expr)) {
          +  -  +  +  +  
                      + ]
    2369         [ +  - ]:        6056 :         auto pubkeys = ParsePubkey(key_exp_index, expr, ParseScriptContext::P2WPKH, out, error);
    2370         [ +  + ]:        6056 :         if (pubkeys.empty()) {
    2371         [ +  - ]:          18 :             error = strprintf("wpkh(): %s", error);
    2372                 :          18 :             return {};
    2373                 :             :         }
    2374                 :        6038 :         key_exp_index++;
    2375         [ +  + ]:       12488 :         for (auto& pubkey : pubkeys) {
    2376   [ +  -  +  - ]:       12900 :             ret.emplace_back(std::make_unique<WPKHDescriptor>(std::move(pubkey)));
    2377                 :             :         }
    2378                 :        6038 :         return ret;
    2379   [ +  -  +  -  :       51560 :     } else if (Func("wpkh", expr)) {
                   +  + ]
    2380         [ +  - ]:           5 :         error = "Can only have wpkh() at top level or inside sh()";
    2381                 :           5 :         return {};
    2382                 :             :     }
    2383   [ +  +  +  -  :       74426 :     if (ctx == ParseScriptContext::TOP && Func("sh", expr)) {
          +  -  +  +  +  
                      + ]
    2384         [ +  - ]:        4172 :         auto descs = ParseScript(key_exp_index, expr, ParseScriptContext::P2SH, out, error);
    2385   [ +  +  +  + ]:        4172 :         if (descs.empty() || expr.size()) return {};
    2386                 :        3899 :         std::vector<std::unique_ptr<DescriptorImpl>> ret;
    2387   [ -  +  +  - ]:        3899 :         ret.reserve(descs.size());
    2388         [ +  + ]:        9196 :         for (auto& desc : descs) {
    2389   [ +  -  +  -  :        5297 :             ret.push_back(std::make_unique<SHDescriptor>(std::move(desc)));
                   -  + ]
    2390                 :             :         }
    2391                 :        3899 :         return ret;
    2392   [ +  -  +  -  :       45499 :     } else if (Func("sh", expr)) {
                   +  + ]
    2393         [ +  - ]:           6 :         error = "Can only have sh() at top level";
    2394                 :           6 :         return {};
    2395                 :             :     }
    2396   [ +  +  +  -  :       66540 :     if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH) && Func("wsh", expr)) {
          +  -  +  +  +  
                      + ]
    2397         [ +  - ]:        5455 :         auto descs = ParseScript(key_exp_index, expr, ParseScriptContext::P2WSH, out, error);
    2398   [ +  +  +  + ]:        5455 :         if (descs.empty() || expr.size()) return {};
    2399         [ +  + ]:        8209 :         for (auto& desc : descs) {
    2400   [ +  -  +  - ]:       11646 :             ret.emplace_back(std::make_unique<WSHDescriptor>(std::move(desc)));
    2401                 :             :         }
    2402                 :        2386 :         return ret;
    2403   [ +  -  +  -  :       41321 :     } else if (Func("wsh", expr)) {
                   +  + ]
    2404         [ +  - ]:           6 :         error = "Can only have wsh() at top level or inside sh()";
    2405                 :           6 :         return {};
    2406                 :             :     }
    2407   [ +  +  +  -  :       55547 :     if (ctx == ParseScriptContext::TOP && Func("addr", expr)) {
          +  -  +  +  +  
                      + ]
    2408   [ +  -  +  - ]:        1842 :         CTxDestination dest = DecodeDestination(std::string(expr.begin(), expr.end()));
    2409   [ +  -  +  + ]:         921 :         if (!IsValidDestination(dest)) {
    2410         [ +  - ]:         871 :             error = "Address is not valid";
    2411                 :         871 :             return {};
    2412                 :             :         }
    2413   [ +  -  +  - ]:          50 :         ret.emplace_back(std::make_unique<AddressDescriptor>(std::move(dest)));
    2414                 :          50 :         return ret;
    2415   [ +  -  +  -  :       35860 :     } else if (Func("addr", expr)) {
                   +  + ]
    2416         [ +  - ]:           7 :         error = "Can only have addr() at top level";
    2417                 :           7 :         return {};
    2418                 :             :     }
    2419   [ +  +  +  -  :       53698 :     if (ctx == ParseScriptContext::TOP && Func("tr", expr)) {
          +  -  +  +  +  
                      + ]
    2420         [ +  - ]:        9490 :         auto arg = Expr(expr);
    2421         [ +  - ]:        9490 :         auto internal_keys = ParsePubkey(key_exp_index, arg, ParseScriptContext::P2TR, out, error);
    2422         [ +  + ]:        9490 :         if (internal_keys.empty()) {
    2423         [ +  - ]:         375 :             error = strprintf("tr(): %s", error);
    2424                 :         375 :             return {};
    2425                 :             :         }
    2426         [ -  + ]:        9115 :         size_t max_providers_len = internal_keys.size();
    2427                 :        9115 :         ++key_exp_index;
    2428                 :        9115 :         std::vector<std::vector<std::unique_ptr<DescriptorImpl>>> subscripts; //!< list of multipath expanded script subexpressions
    2429                 :        9115 :         std::vector<int> depths; //!< depth in the tree of each subexpression (same length subscripts)
    2430         [ +  + ]:        9115 :         if (expr.size()) {
    2431   [ +  -  +  -  :        4429 :             if (!Const(",", expr)) {
                   +  + ]
    2432         [ +  - ]:          13 :                 error = strprintf("tr: expected ',', got '%c'", expr[0]);
    2433                 :          13 :                 return {};
    2434                 :             :             }
    2435                 :             :             /** The path from the top of the tree to what we're currently processing.
    2436                 :             :              * branches[i] == false: left branch in the i'th step from the top; true: right branch.
    2437                 :             :              */
    2438                 :        4416 :             std::vector<bool> branches;
    2439                 :             :             // Loop over all provided scripts. In every iteration exactly one script will be processed.
    2440                 :             :             // Use a do-loop because inside this if-branch we expect at least one script.
    2441                 :             :             do {
    2442                 :             :                 // First process all open braces.
    2443   [ +  -  +  -  :       44562 :                 while (Const("{", expr)) {
                   +  + ]
    2444         [ +  - ]:       25115 :                     branches.push_back(false); // new left branch
    2445         [ +  + ]:       25115 :                     if (branches.size() > TAPROOT_CONTROL_MAX_NODE_COUNT) {
    2446         [ +  - ]:          26 :                         error = strprintf("tr() supports at most %i nesting levels", TAPROOT_CONTROL_MAX_NODE_COUNT);
    2447                 :          26 :                         return {};
    2448                 :             :                     }
    2449                 :             :                 }
    2450                 :             :                 // Process the actual script expression.
    2451         [ +  - ]:       19447 :                 auto sarg = Expr(expr);
    2452   [ +  -  +  - ]:       19447 :                 subscripts.emplace_back(ParseScript(key_exp_index, sarg, ParseScriptContext::P2TR, out, error));
    2453         [ +  + ]:       19447 :                 if (subscripts.back().empty()) return {};
    2454   [ -  +  +  + ]:       18482 :                 max_providers_len = std::max(max_providers_len, subscripts.back().size());
    2455         [ +  - ]:       18482 :                 depths.push_back(branches.size());
    2456                 :             :                 // Process closing braces; one is expected for every right branch we were in.
    2457         [ +  + ]:       22252 :                 while (branches.size() && branches.back()) {
    2458   [ +  -  +  +  :        7154 :                     if (!Const("}", expr)) {
                   +  - ]
    2459         [ +  - ]:          32 :                         error = strprintf("tr(): expected '}' after script expression");
    2460                 :          32 :                         return {};
    2461                 :             :                     }
    2462   [ -  +  +  + ]:       32726 :                     branches.pop_back(); // move up one level after encountering '}'
    2463                 :             :                 }
    2464                 :             :                 // If after that, we're at the end of a left branch, expect a comma.
    2465   [ +  +  +  - ]:       18450 :                 if (branches.size() && !branches.back()) {
    2466   [ +  -  +  -  :       15098 :                     if (!Const(",", expr)) {
                   +  + ]
    2467         [ +  - ]:          41 :                         error = strprintf("tr(): expected ',' after script expression");
    2468                 :          41 :                         return {};
    2469                 :             :                     }
    2470                 :       15057 :                     branches.back() = true; // And now we're in a right branch.
    2471                 :             :                 }
    2472         [ +  + ]:       18409 :             } while (branches.size());
    2473                 :             :             // After we've explored a whole tree, we must be at the end of the expression.
    2474         [ +  + ]:        3352 :             if (expr.size()) {
    2475         [ +  - ]:          28 :                 error = strprintf("tr(): expected ')' after script expression");
    2476                 :          28 :                 return {};
    2477                 :             :             }
    2478                 :        4416 :         }
    2479   [ +  -  -  + ]:        8010 :         assert(TaprootBuilder::ValidDepths(depths));
    2480                 :             : 
    2481                 :             :         // Make sure all vecs are of the same length, or exactly length 1
    2482                 :             :         // For length 1 vectors, clone subdescs until vector is the same length
    2483         [ +  + ]:       17191 :         for (auto& vec : subscripts) {
    2484   [ -  +  +  + ]:        9184 :             if (vec.size() == 1) {
    2485         [ +  + ]:       12087 :                 for (size_t i = 1; i < max_providers_len; ++i) {
    2486   [ +  -  +  -  :        3396 :                     vec.emplace_back(vec.at(0)->Clone());
                   +  - ]
    2487                 :             :                 }
    2488         [ +  + ]:         493 :             } else if (vec.size() != max_providers_len) {
    2489         [ +  - ]:           3 :                 error = strprintf("tr(): Multipath subscripts have mismatched lengths");
    2490                 :           3 :                 return {};
    2491                 :             :             }
    2492                 :             :         }
    2493                 :             : 
    2494   [ -  +  +  +  :        8007 :         if (internal_keys.size() > 1 && internal_keys.size() != max_providers_len) {
                   +  + ]
    2495         [ +  - ]:           4 :             error = strprintf("tr(): Multipath internal key mismatches multipath subscripts lengths");
    2496                 :           4 :             return {};
    2497                 :             :         }
    2498                 :             : 
    2499   [ -  +  +  + ]:       10711 :         while (internal_keys.size() < max_providers_len) {
    2500   [ +  -  +  -  :        2708 :             internal_keys.emplace_back(internal_keys.at(0)->Clone());
                   +  - ]
    2501                 :             :         }
    2502                 :             : 
    2503                 :             :         // Build the final descriptors vector
    2504         [ +  + ]:       21051 :         for (size_t i = 0; i < max_providers_len; ++i) {
    2505                 :             :             // Build final subscripts vectors by retrieving the i'th subscript for each vector in subscripts
    2506                 :       13048 :             std::vector<std::unique_ptr<DescriptorImpl>> this_subs;
    2507   [ -  +  +  - ]:       13048 :             this_subs.reserve(subscripts.size());
    2508         [ +  + ]:       28366 :             for (auto& subs : subscripts) {
    2509   [ +  -  +  - ]:       15318 :                 this_subs.emplace_back(std::move(subs.at(i)));
    2510                 :             :             }
    2511   [ +  -  +  -  :       13048 :             ret.emplace_back(std::make_unique<TRDescriptor>(std::move(internal_keys.at(i)), std::move(this_subs), depths));
                   +  - ]
    2512                 :       13048 :         }
    2513                 :        8003 :         return ret;
    2514                 :             : 
    2515                 :             : 
    2516   [ +  -  +  -  :       34932 :     } else if (Func("tr", expr)) {
                   +  + ]
    2517         [ +  - ]:           8 :         error = "Can only have tr at top level";
    2518                 :           8 :         return {};
    2519                 :             :     }
    2520   [ +  +  +  -  :       34710 :     if (ctx == ParseScriptContext::TOP && Func("rawtr", expr)) {
          +  -  +  +  +  
                      + ]
    2521         [ +  - ]:         228 :         auto arg = Expr(expr);
    2522         [ +  + ]:         228 :         if (expr.size()) {
    2523         [ +  - ]:           6 :             error = strprintf("rawtr(): only one key expected.");
    2524                 :           6 :             return {};
    2525                 :             :         }
    2526         [ +  - ]:         222 :         auto output_keys = ParsePubkey(key_exp_index, arg, ParseScriptContext::P2TR, out, error);
    2527         [ +  + ]:         222 :         if (output_keys.empty()) {
    2528         [ +  - ]:          36 :             error = strprintf("rawtr(): %s", error);
    2529                 :          36 :             return {};
    2530                 :             :         }
    2531                 :         186 :         ++key_exp_index;
    2532         [ +  + ]:         767 :         for (auto& pubkey : output_keys) {
    2533   [ +  -  +  - ]:        1162 :             ret.emplace_back(std::make_unique<RawTRDescriptor>(std::move(pubkey)));
    2534                 :             :         }
    2535                 :         186 :         return ret;
    2536   [ +  -  +  -  :       25428 :     } else if (Func("rawtr", expr)) {
                   +  + ]
    2537         [ +  - ]:           8 :         error = "Can only have rawtr at top level";
    2538                 :           8 :         return {};
    2539                 :             :     }
    2540   [ +  +  +  -  :       34246 :     if (ctx == ParseScriptContext::TOP && Func("raw", expr)) {
          +  -  +  +  +  
                      + ]
    2541   [ +  -  -  + ]:       10962 :         std::string str(expr.begin(), expr.end());
    2542   [ -  +  +  -  :        5481 :         if (!IsHex(str)) {
                   +  + ]
    2543         [ +  - ]:          24 :             error = "Raw script is not hex";
    2544                 :          24 :             return {};
    2545                 :             :         }
    2546   [ -  +  +  - ]:        5457 :         auto bytes = ParseHex(str);
    2547   [ +  -  +  - ]:       10914 :         ret.emplace_back(std::make_unique<RawDescriptor>(CScript(bytes.begin(), bytes.end())));
    2548                 :        5457 :         return ret;
    2549   [ +  -  +  -  :       30655 :     } else if (Func("raw", expr)) {
                   +  + ]
    2550         [ +  - ]:           6 :         error = "Can only have raw() at top level";
    2551                 :           6 :         return {};
    2552                 :             :     }
    2553                 :             :     // Process miniscript expressions.
    2554                 :       19711 :     {
    2555                 :       19711 :         const auto script_ctx{ctx == ParseScriptContext::P2WSH ? miniscript::MiniscriptContext::P2WSH : miniscript::MiniscriptContext::TAPSCRIPT};
    2556         [ +  - ]:       19711 :         KeyParser parser(/*out = */&out, /* in = */nullptr, /* ctx = */script_ctx, key_exp_index);
    2557   [ +  -  -  + ]:       59133 :         auto node = miniscript::FromString(std::string(expr.begin(), expr.end()), parser);
    2558         [ +  + ]:       19711 :         if (parser.m_key_parsing_error != "") {
    2559                 :         328 :             error = std::move(parser.m_key_parsing_error);
    2560                 :         328 :             return {};
    2561                 :             :         }
    2562         [ +  + ]:       19383 :         if (node) {
    2563         [ +  + ]:       16213 :             if (ctx != ParseScriptContext::P2WSH && ctx != ParseScriptContext::P2TR) {
    2564         [ +  - ]:         843 :                 error = "Miniscript expressions can only be used in wsh or tr.";
    2565                 :         843 :                 return {};
    2566                 :             :             }
    2567   [ +  +  +  + ]:       15370 :             if (!node->IsSane() || node->IsNotSatisfiable()) {
    2568                 :             :                 // Try to find the first insane sub for better error reporting.
    2569         [ +  - ]:        3033 :                 auto insane_node = node.get();
    2570   [ +  -  +  + ]:        3033 :                 if (const auto sub = node->FindInsaneSub()) insane_node = sub;
    2571         [ +  - ]:        3033 :                 error = *insane_node->ToString(parser);
    2572         [ +  + ]:        3033 :                 if (!insane_node->IsValid()) {
    2573         [ +  - ]:        1805 :                     error += " is invalid";
    2574         [ +  + ]:        1228 :                 } else if (!node->IsSane()) {
    2575         [ +  - ]:         995 :                     error += " is not sane";
    2576         [ +  + ]:         995 :                     if (!insane_node->IsNonMalleable()) {
    2577         [ +  - ]:         252 :                         error += ": malleable witnesses exist";
    2578   [ +  +  +  + ]:         743 :                     } else if (insane_node == node.get() && !insane_node->NeedsSignature()) {
    2579         [ +  - ]:         139 :                         error += ": witnesses without signature exist";
    2580         [ +  + ]:         604 :                     } else if (!insane_node->CheckTimeLocksMix()) {
    2581         [ +  - ]:          84 :                         error += ": contains mixes of timelocks expressed in blocks and seconds";
    2582         [ +  - ]:         520 :                     } else if (!insane_node->CheckDuplicateKey()) {
    2583         [ +  - ]:         369 :                         error += ": contains duplicate public keys";
    2584         [ +  + ]:         151 :                     } else if (!insane_node->ValidSatisfactions()) {
    2585         [ +  - ]:          69 :                         error += ": needs witnesses that may exceed resource limits";
    2586                 :             :                     }
    2587                 :             :                 } else {
    2588         [ +  - ]:         233 :                     error += " is not satisfiable";
    2589                 :             :                 }
    2590                 :        3033 :                 return {};
    2591                 :             :             }
    2592                 :             :             // A signature check is required for a miniscript to be sane. Therefore no sane miniscript
    2593                 :             :             // may have an empty list of public keys.
    2594         [ +  - ]:       12337 :             CHECK_NONFATAL(!parser.m_keys.empty());
    2595         [ -  + ]:       12337 :             key_exp_index += parser.m_keys.size();
    2596                 :             :             // Make sure all vecs are of the same length, or exactly length 1
    2597                 :             :             // For length 1 vectors, clone subdescs until vector is the same length
    2598         [ -  + ]:       12337 :             size_t num_multipath = std::max_element(parser.m_keys.begin(), parser.m_keys.end(),
    2599                 :        7240 :                     [](const std::vector<std::unique_ptr<PubkeyProvider>>& a, const std::vector<std::unique_ptr<PubkeyProvider>>& b) {
    2600   [ -  +  -  +  :        7240 :                         return a.size() < b.size();
                   +  + ]
    2601         [ -  + ]:       12337 :                     })->size();
    2602                 :             : 
    2603         [ +  + ]:       31868 :             for (auto& vec : parser.m_keys) {
    2604   [ -  +  +  + ]:       19544 :                 if (vec.size() == 1) {
    2605         [ +  + ]:       26159 :                     for (size_t i = 1; i < num_multipath; ++i) {
    2606   [ +  -  +  -  :        8043 :                         vec.emplace_back(vec.at(0)->Clone());
                   +  - ]
    2607                 :             :                     }
    2608         [ +  + ]:        1428 :                 } else if (vec.size() != num_multipath) {
    2609         [ +  - ]:          13 :                     error = strprintf("Miniscript: Multipath derivation paths have mismatched lengths");
    2610                 :          13 :                     return {};
    2611                 :             :                 }
    2612                 :             :             }
    2613                 :             : 
    2614                 :             :             // Build the final descriptors vector
    2615         [ +  + ]:       30262 :             for (size_t i = 0; i < num_multipath; ++i) {
    2616                 :             :                 // Build final pubkeys vectors by retrieving the i'th subscript for each vector in subscripts
    2617                 :       17938 :                 std::vector<std::unique_ptr<PubkeyProvider>> pubs;
    2618   [ -  +  +  - ]:       17938 :                 pubs.reserve(parser.m_keys.size());
    2619         [ +  + ]:       51343 :                 for (auto& pub : parser.m_keys) {
    2620   [ +  -  +  - ]:       33405 :                     pubs.emplace_back(std::move(pub.at(i)));
    2621                 :             :                 }
    2622   [ +  -  +  -  :       35876 :                 ret.emplace_back(std::make_unique<MiniscriptDescriptor>(std::move(pubs), node->Clone()));
                   +  - ]
    2623                 :       17938 :             }
    2624                 :       12324 :             return ret;
    2625                 :             :         }
    2626                 :       36252 :     }
    2627         [ +  + ]:        3170 :     if (ctx == ParseScriptContext::P2SH) {
    2628         [ +  - ]:          34 :         error = "A function is needed within P2SH";
    2629                 :          34 :         return {};
    2630         [ +  + ]:        3136 :     } else if (ctx == ParseScriptContext::P2WSH) {
    2631         [ +  - ]:         374 :         error = "A function is needed within P2WSH";
    2632                 :         374 :         return {};
    2633                 :             :     }
    2634   [ +  -  +  - ]:        5524 :     error = strprintf("'%s' is not a valid descriptor function", std::string(expr.begin(), expr.end()));
    2635                 :        2762 :     return {};
    2636                 :       71686 : }
    2637                 :             : 
    2638                 :        8602 : std::unique_ptr<DescriptorImpl> InferMultiA(const CScript& script, ParseScriptContext ctx, const SigningProvider& provider)
    2639                 :             : {
    2640                 :        8602 :     auto match = MatchMultiA(script);
    2641         [ +  + ]:        8602 :     if (!match) return {};
    2642                 :        1798 :     std::vector<std::unique_ptr<PubkeyProvider>> keys;
    2643   [ -  +  +  - ]:        1798 :     keys.reserve(match->second.size());
    2644         [ +  + ]:      190419 :     for (const auto keyspan : match->second) {
    2645         [ -  + ]:      188621 :         if (keyspan.size() != 32) return {};
    2646         [ +  - ]:      188621 :         auto key = InferXOnlyPubkey(XOnlyPubKey{keyspan}, ctx, provider);
    2647         [ -  + ]:      188621 :         if (!key) return {};
    2648         [ +  - ]:      188621 :         keys.push_back(std::move(key));
    2649                 :      188621 :     }
    2650   [ +  -  -  + ]:        1798 :     return std::make_unique<MultiADescriptor>(match->first, std::move(keys));
    2651                 :       10400 : }
    2652                 :             : 
    2653                 :             : // NOLINTNEXTLINE(misc-no-recursion)
    2654                 :     1704577 : std::unique_ptr<DescriptorImpl> InferScript(const CScript& script, ParseScriptContext ctx, const SigningProvider& provider)
    2655                 :             : {
    2656   [ +  +  +  +  :     1715015 :     if (ctx == ParseScriptContext::P2TR && script.size() == 34 && script[0] == 32 && script[33] == OP_CHECKSIG) {
          +  +  +  -  +  
             +  +  -  +  
                      - ]
    2657                 :        2469 :         XOnlyPubKey key{std::span{script}.subspan(1, 32)};
    2658   [ +  -  -  + ]:        2469 :         return std::make_unique<PKDescriptor>(InferXOnlyPubkey(key, ctx, provider), true);
    2659                 :             :     }
    2660                 :             : 
    2661         [ +  + ]:     1702108 :     if (ctx == ParseScriptContext::P2TR) {
    2662                 :        8602 :         auto ret = InferMultiA(script, ctx, provider);
    2663         [ +  + ]:        8602 :         if (ret) return ret;
    2664                 :        8602 :     }
    2665                 :             : 
    2666                 :     1700310 :     std::vector<std::vector<unsigned char>> data;
    2667         [ +  - ]:     1700310 :     TxoutType txntype = Solver(script, data);
    2668                 :             : 
    2669   [ +  +  +  - ]:     1700310 :     if (txntype == TxoutType::PUBKEY && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
    2670         [ -  + ]:       32976 :         CPubKey pubkey(data[0]);
    2671   [ +  -  +  + ]:       32976 :         if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
    2672   [ +  -  -  + ]:       30093 :             return std::make_unique<PKDescriptor>(std::move(pubkey_provider));
    2673                 :       32976 :         }
    2674                 :             :     }
    2675   [ +  +  +  + ]:     1670217 :     if (txntype == TxoutType::PUBKEYHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
    2676         [ -  + ]:       26829 :         uint160 hash(data[0]);
    2677         [ +  - ]:       26829 :         CKeyID keyid(hash);
    2678         [ +  - ]:       26829 :         CPubKey pubkey;
    2679   [ +  -  +  + ]:       26829 :         if (provider.GetPubKey(keyid, pubkey)) {
    2680   [ +  -  +  - ]:         683 :             if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
    2681   [ +  -  -  + ]:         683 :                 return std::make_unique<PKHDescriptor>(std::move(pubkey_provider));
    2682                 :         683 :             }
    2683                 :             :         }
    2684                 :             :     }
    2685         [ +  + ]:     1669534 :     if (txntype == TxoutType::WITNESS_V0_KEYHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH)) {
    2686         [ -  + ]:       72051 :         uint160 hash(data[0]);
    2687         [ +  - ]:       72051 :         CKeyID keyid(hash);
    2688         [ +  - ]:       72051 :         CPubKey pubkey;
    2689   [ +  -  +  + ]:       72051 :         if (provider.GetPubKey(keyid, pubkey)) {
    2690   [ +  -  +  - ]:         933 :             if (auto pubkey_provider = InferPubkey(pubkey, ParseScriptContext::P2WPKH, provider)) {
    2691   [ +  -  -  + ]:         933 :                 return std::make_unique<WPKHDescriptor>(std::move(pubkey_provider));
    2692                 :         933 :             }
    2693                 :             :         }
    2694                 :             :     }
    2695   [ +  +  +  - ]:     1668601 :     if (txntype == TxoutType::MULTISIG && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
    2696                 :       31747 :         bool ok = true;
    2697                 :       31747 :         std::vector<std::unique_ptr<PubkeyProvider>> providers;
    2698   [ -  +  +  + ]:      165618 :         for (size_t i = 1; i + 1 < data.size(); ++i) {
    2699         [ -  + ]:      136156 :             CPubKey pubkey(data[i]);
    2700   [ +  -  +  + ]:      136156 :             if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
    2701         [ +  - ]:      133871 :                 providers.push_back(std::move(pubkey_provider));
    2702                 :             :             } else {
    2703                 :        2285 :                 ok = false;
    2704                 :        2285 :                 break;
    2705                 :      136156 :             }
    2706                 :             :         }
    2707   [ +  -  -  + ]:       29462 :         if (ok) return std::make_unique<MultisigDescriptor>((int)data[0][0], std::move(providers));
    2708                 :       31747 :     }
    2709         [ +  + ]:     1639139 :     if (txntype == TxoutType::SCRIPTHASH && ctx == ParseScriptContext::TOP) {
    2710         [ -  + ]:      152913 :         uint160 hash(data[0]);
    2711         [ +  - ]:      152913 :         CScriptID scriptid(hash);
    2712                 :      152913 :         CScript subscript;
    2713   [ +  -  +  + ]:      152913 :         if (provider.GetCScript(scriptid, subscript)) {
    2714         [ +  - ]:        2348 :             auto sub = InferScript(subscript, ParseScriptContext::P2SH, provider);
    2715   [ +  +  +  -  :        2348 :             if (sub) return std::make_unique<SHDescriptor>(std::move(sub));
                   -  + ]
    2716                 :        2348 :         }
    2717                 :      152913 :     }
    2718         [ +  + ]:     1636815 :     if (txntype == TxoutType::WITNESS_V0_SCRIPTHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH)) {
    2719   [ -  +  +  - ]:       82095 :         CScriptID scriptid{RIPEMD160(data[0])};
    2720                 :       82095 :         CScript subscript;
    2721   [ +  -  +  + ]:       82095 :         if (provider.GetCScript(scriptid, subscript)) {
    2722         [ +  - ]:        5474 :             auto sub = InferScript(subscript, ParseScriptContext::P2WSH, provider);
    2723   [ +  +  +  -  :        5474 :             if (sub) return std::make_unique<WSHDescriptor>(std::move(sub));
                   -  + ]
    2724                 :        5474 :         }
    2725                 :       82095 :     }
    2726         [ +  + ]:     1632144 :     if (txntype == TxoutType::WITNESS_V1_TAPROOT && ctx == ParseScriptContext::TOP) {
    2727                 :             :         // Extract x-only pubkey from output.
    2728                 :       23896 :         XOnlyPubKey pubkey;
    2729                 :       23896 :         std::copy(data[0].begin(), data[0].end(), pubkey.begin());
    2730                 :             :         // Request spending data.
    2731         [ +  - ]:       23896 :         TaprootSpendData tap;
    2732   [ +  -  +  + ]:       23896 :         if (provider.GetTaprootSpendData(pubkey, tap)) {
    2733                 :             :             // If found, convert it back to tree form.
    2734         [ +  - ]:        6645 :             auto tree = InferTaprootTree(tap, pubkey);
    2735         [ +  + ]:        6645 :             if (tree) {
    2736                 :             :                 // If that works, try to infer subdescriptors for all leaves.
    2737                 :        6633 :                 bool ok = true;
    2738                 :        6633 :                 std::vector<std::unique_ptr<DescriptorImpl>> subscripts; //!< list of script subexpressions
    2739                 :        6633 :                 std::vector<int> depths; //!< depth in the tree of each subexpression (same length subscripts)
    2740   [ +  -  +  + ]:       17597 :                 for (const auto& [depth, script, leaf_ver] : *tree) {
    2741                 :       11071 :                     std::unique_ptr<DescriptorImpl> subdesc;
    2742         [ +  - ]:       11071 :                     if (leaf_ver == TAPROOT_LEAF_TAPSCRIPT) {
    2743         [ +  - ]:       22142 :                         subdesc = InferScript(CScript(script.begin(), script.end()), ParseScriptContext::P2TR, provider);
    2744                 :             :                     }
    2745         [ +  + ]:       11071 :                     if (!subdesc) {
    2746                 :         107 :                         ok = false;
    2747                 :         107 :                         break;
    2748                 :             :                     } else {
    2749         [ +  - ]:       10964 :                         subscripts.push_back(std::move(subdesc));
    2750         [ +  - ]:       10964 :                         depths.push_back(depth);
    2751                 :             :                     }
    2752                 :       11071 :                 }
    2753                 :         107 :                 if (ok) {
    2754         [ +  - ]:        6526 :                     auto key = InferXOnlyPubkey(tap.internal_key, ParseScriptContext::P2TR, provider);
    2755   [ +  -  -  + ]:        6526 :                     return std::make_unique<TRDescriptor>(std::move(key), std::move(subscripts), std::move(depths));
    2756                 :        6526 :                 }
    2757                 :        6633 :             }
    2758                 :        6645 :         }
    2759                 :             :         // If the above doesn't work, construct a rawtr() descriptor with just the encoded x-only pubkey.
    2760   [ +  -  +  + ]:       17370 :         if (pubkey.IsFullyValid()) {
    2761         [ +  - ]:       10326 :             auto key = InferXOnlyPubkey(pubkey, ParseScriptContext::P2TR, provider);
    2762         [ +  - ]:       10326 :             if (key) {
    2763   [ +  -  -  + ]:       10326 :                 return std::make_unique<RawTRDescriptor>(std::move(key));
    2764                 :             :             }
    2765                 :       10326 :         }
    2766                 :       23896 :     }
    2767                 :             : 
    2768         [ +  + ]:     1615292 :     if (ctx == ParseScriptContext::P2WSH || ctx == ParseScriptContext::P2TR) {
    2769                 :       11450 :         const auto script_ctx{ctx == ParseScriptContext::P2WSH ? miniscript::MiniscriptContext::P2WSH : miniscript::MiniscriptContext::TAPSCRIPT};
    2770         [ +  - ]:       11450 :         KeyParser parser(/* out = */nullptr, /* in = */&provider, /* ctx = */script_ctx);
    2771         [ +  - ]:       11450 :         auto node = miniscript::FromScript(script, parser);
    2772   [ +  +  +  + ]:       11450 :         if (node && node->IsSane()) {
    2773                 :       10540 :             std::vector<std::unique_ptr<PubkeyProvider>> keys;
    2774   [ -  +  +  - ]:       10540 :             keys.reserve(parser.m_keys.size());
    2775         [ +  + ]:       31971 :             for (auto& key : parser.m_keys) {
    2776   [ +  -  +  - ]:       21431 :                 keys.emplace_back(std::move(key.at(0)));
    2777                 :             :             }
    2778   [ +  -  -  + ]:       10540 :             return std::make_unique<MiniscriptDescriptor>(std::move(keys), std::move(node));
    2779                 :       10540 :         }
    2780                 :       22900 :     }
    2781                 :             : 
    2782                 :             :     // The following descriptors are all top-level only descriptors.
    2783                 :             :     // So if we are not at the top level, return early.
    2784         [ +  + ]:     1604752 :     if (ctx != ParseScriptContext::TOP) return nullptr;
    2785                 :             : 
    2786                 :     1603818 :     CTxDestination dest;
    2787   [ +  -  +  + ]:     1603818 :     if (ExtractDestination(script, dest)) {
    2788   [ +  -  +  - ]:      364000 :         if (GetScriptForDestination(dest) == script) {
    2789   [ +  -  -  + ]:      364000 :             return std::make_unique<AddressDescriptor>(std::move(dest));
    2790                 :             :         }
    2791                 :             :     }
    2792                 :             : 
    2793   [ +  -  -  + ]:     1239818 :     return std::make_unique<RawDescriptor>(script);
    2794                 :     1700310 : }
    2795                 :             : 
    2796                 :             : 
    2797                 :             : } // namespace
    2798                 :             : 
    2799                 :             : /** Check a descriptor checksum, and update desc to be the checksum-less part. */
    2800                 :       47935 : bool CheckChecksum(std::span<const char>& sp, bool require_checksum, std::string& error, std::string* out_checksum = nullptr)
    2801                 :             : {
    2802                 :       47935 :     auto check_split = Split(sp, '#');
    2803   [ -  +  +  + ]:       47935 :     if (check_split.size() > 2) {
    2804         [ +  - ]:          42 :         error = "Multiple '#' symbols";
    2805                 :             :         return false;
    2806                 :             :     }
    2807   [ +  +  +  + ]:       47893 :     if (check_split.size() == 1 && require_checksum){
    2808         [ +  - ]:       47935 :         error = "Missing checksum";
    2809                 :             :         return false;
    2810                 :             :     }
    2811         [ +  + ]:       44165 :     if (check_split.size() == 2) {
    2812         [ +  + ]:         143 :         if (check_split[1].size() != 8) {
    2813         [ +  - ]:          37 :             error = strprintf("Expected 8 character checksum, not %u characters", check_split[1].size());
    2814                 :          37 :             return false;
    2815                 :             :         }
    2816                 :             :     }
    2817         [ +  - ]:       44128 :     auto checksum = DescriptorChecksum(check_split[0]);
    2818         [ +  + ]:       44128 :     if (checksum.empty()) {
    2819         [ +  - ]:       44128 :         error = "Invalid characters in payload";
    2820                 :             :         return false;
    2821                 :             :     }
    2822   [ -  +  +  + ]:       43861 :     if (check_split.size() == 2) {
    2823   [ -  +  +  + ]:         102 :         if (!std::equal(checksum.begin(), checksum.end(), check_split[1].begin())) {
    2824   [ +  -  +  - ]:          58 :             error = strprintf("Provided checksum '%s' does not match computed checksum '%s'", std::string(check_split[1].begin(), check_split[1].end()), checksum);
    2825                 :          29 :             return false;
    2826                 :             :         }
    2827                 :             :     }
    2828         [ +  + ]:       43832 :     if (out_checksum) *out_checksum = std::move(checksum);
    2829                 :       43832 :     sp = check_split[0];
    2830                 :       43832 :     return true;
    2831                 :       92063 : }
    2832                 :             : 
    2833                 :       46505 : std::vector<std::unique_ptr<Descriptor>> Parse(std::string_view descriptor, FlatSigningProvider& out, std::string& error, bool require_checksum)
    2834                 :             : {
    2835                 :       46505 :     std::span<const char> sp{descriptor};
    2836         [ +  + ]:       46505 :     if (!CheckChecksum(sp, require_checksum, error)) return {};
    2837                 :       42612 :     uint32_t key_exp_index = 0;
    2838                 :       42612 :     auto ret = ParseScript(key_exp_index, sp, ParseScriptContext::TOP, out, error);
    2839   [ +  +  +  + ]:       42612 :     if (sp.empty() && !ret.empty()) {
    2840                 :       32531 :         std::vector<std::unique_ptr<Descriptor>> descs;
    2841   [ -  +  +  - ]:       32531 :         descs.reserve(ret.size());
    2842         [ +  + ]:       75933 :         for (auto& r : ret) {
    2843         [ +  - ]:       43402 :             descs.emplace_back(std::unique_ptr<Descriptor>(std::move(r)));
    2844                 :             :         }
    2845                 :       32531 :         return descs;
    2846                 :       32531 :     }
    2847                 :       10081 :     return {};
    2848                 :       42612 : }
    2849                 :             : 
    2850                 :        1430 : std::string GetDescriptorChecksum(const std::string& descriptor)
    2851                 :             : {
    2852         [ -  + ]:        1430 :     std::string ret;
    2853                 :        1430 :     std::string error;
    2854         [ -  + ]:        1430 :     std::span<const char> sp{descriptor};
    2855   [ +  -  +  +  :        1430 :     if (!CheckChecksum(sp, false, error, &ret)) return "";
                   +  - ]
    2856                 :        1220 :     return ret;
    2857                 :        1430 : }
    2858                 :             : 
    2859                 :     1685684 : std::unique_ptr<Descriptor> InferDescriptor(const CScript& script, const SigningProvider& provider)
    2860                 :             : {
    2861                 :     1685684 :     return InferScript(script, ParseScriptContext::TOP, provider);
    2862                 :             : }
    2863                 :             : 
    2864                 :       24191 : uint256 DescriptorID(const Descriptor& desc)
    2865                 :             : {
    2866                 :       24191 :     std::string desc_str = desc.ToString(/*compat_format=*/true);
    2867                 :       24191 :     uint256 id;
    2868   [ +  -  +  -  :       48382 :     CSHA256().Write((unsigned char*)desc_str.data(), desc_str.size()).Finalize(id.begin());
                   +  - ]
    2869                 :       24191 :     return id;
    2870                 :       24191 : }
    2871                 :             : 
    2872                 :      676715 : void DescriptorCache::CacheParentExtPubKey(uint32_t key_exp_pos, const CExtPubKey& xpub)
    2873                 :             : {
    2874                 :      676715 :     m_parent_xpubs[key_exp_pos] = xpub;
    2875                 :      676715 : }
    2876                 :             : 
    2877                 :      167860 : void DescriptorCache::CacheDerivedExtPubKey(uint32_t key_exp_pos, uint32_t der_index, const CExtPubKey& xpub)
    2878                 :             : {
    2879                 :      167860 :     auto& xpubs = m_derived_xpubs[key_exp_pos];
    2880                 :      167860 :     xpubs[der_index] = xpub;
    2881                 :      167860 : }
    2882                 :             : 
    2883                 :       50094 : void DescriptorCache::CacheLastHardenedExtPubKey(uint32_t key_exp_pos, const CExtPubKey& xpub)
    2884                 :             : {
    2885                 :       50094 :     m_last_hardened_xpubs[key_exp_pos] = xpub;
    2886                 :       50094 : }
    2887                 :             : 
    2888                 :     1473988 : bool DescriptorCache::GetCachedParentExtPubKey(uint32_t key_exp_pos, CExtPubKey& xpub) const
    2889                 :             : {
    2890                 :     1473988 :     const auto& it = m_parent_xpubs.find(key_exp_pos);
    2891         [ +  + ]:     1473988 :     if (it == m_parent_xpubs.end()) return false;
    2892                 :     1396406 :     xpub = it->second;
    2893                 :     1396406 :     return true;
    2894                 :             : }
    2895                 :             : 
    2896                 :     1185551 : bool DescriptorCache::GetCachedDerivedExtPubKey(uint32_t key_exp_pos, uint32_t der_index, CExtPubKey& xpub) const
    2897                 :             : {
    2898                 :     1185551 :     const auto& key_exp_it = m_derived_xpubs.find(key_exp_pos);
    2899         [ +  + ]:     1185551 :     if (key_exp_it == m_derived_xpubs.end()) return false;
    2900                 :      144476 :     const auto& der_it = key_exp_it->second.find(der_index);
    2901         [ +  + ]:      144476 :     if (der_it == key_exp_it->second.end()) return false;
    2902                 :       88895 :     xpub = der_it->second;
    2903                 :       88895 :     return true;
    2904                 :             : }
    2905                 :             : 
    2906                 :       22126 : bool DescriptorCache::GetCachedLastHardenedExtPubKey(uint32_t key_exp_pos, CExtPubKey& xpub) const
    2907                 :             : {
    2908                 :       22126 :     const auto& it = m_last_hardened_xpubs.find(key_exp_pos);
    2909         [ +  + ]:       22126 :     if (it == m_last_hardened_xpubs.end()) return false;
    2910                 :       18221 :     xpub = it->second;
    2911                 :       18221 :     return true;
    2912                 :             : }
    2913                 :             : 
    2914                 :      208648 : DescriptorCache DescriptorCache::MergeAndDiff(const DescriptorCache& other)
    2915                 :             : {
    2916                 :      208648 :     DescriptorCache diff;
    2917   [ +  -  +  +  :      513973 :     for (const auto& parent_xpub_pair : other.GetCachedParentExtPubKeys()) {
                   +  - ]
    2918         [ +  - ]:      305325 :         CExtPubKey xpub;
    2919   [ +  +  +  - ]:      305325 :         if (GetCachedParentExtPubKey(parent_xpub_pair.first, xpub)) {
    2920         [ -  + ]:      255725 :             if (xpub != parent_xpub_pair.second) {
    2921   [ #  #  #  # ]:           0 :                 throw std::runtime_error(std::string(__func__) + ": New cached parent xpub does not match already cached parent xpub");
    2922                 :             :             }
    2923                 :      255725 :             continue;
    2924                 :             :         }
    2925         [ +  - ]:       49600 :         CacheParentExtPubKey(parent_xpub_pair.first, parent_xpub_pair.second);
    2926         [ +  - ]:       49600 :         diff.CacheParentExtPubKey(parent_xpub_pair.first, parent_xpub_pair.second);
    2927                 :           0 :     }
    2928   [ +  -  +  + ]:      258407 :     for (const auto& derived_xpub_map_pair : other.GetCachedDerivedExtPubKeys()) {
    2929   [ +  +  +  - ]:       99518 :         for (const auto& derived_xpub_pair : derived_xpub_map_pair.second) {
    2930         [ +  - ]:       49759 :             CExtPubKey xpub;
    2931   [ -  +  +  - ]:       49759 :             if (GetCachedDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, xpub)) {
    2932         [ #  # ]:           0 :                 if (xpub != derived_xpub_pair.second) {
    2933   [ #  #  #  # ]:           0 :                     throw std::runtime_error(std::string(__func__) + ": New cached derived xpub does not match already cached derived xpub");
    2934                 :             :                 }
    2935                 :           0 :                 continue;
    2936                 :             :             }
    2937         [ +  - ]:       49759 :             CacheDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, derived_xpub_pair.second);
    2938         [ +  - ]:       49759 :             diff.CacheDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, derived_xpub_pair.second);
    2939                 :             :         }
    2940                 :             :     }
    2941   [ +  -  +  +  :      227878 :     for (const auto& lh_xpub_pair : other.GetCachedLastHardenedExtPubKeys()) {
                   +  - ]
    2942         [ +  - ]:       19230 :         CExtPubKey xpub;
    2943   [ +  +  +  - ]:       19230 :         if (GetCachedLastHardenedExtPubKey(lh_xpub_pair.first, xpub)) {
    2944         [ -  + ]:       15325 :             if (xpub != lh_xpub_pair.second) {
    2945   [ #  #  #  # ]:           0 :                 throw std::runtime_error(std::string(__func__) + ": New cached last hardened xpub does not match already cached last hardened xpub");
    2946                 :             :             }
    2947                 :       15325 :             continue;
    2948                 :             :         }
    2949         [ +  - ]:        3905 :         CacheLastHardenedExtPubKey(lh_xpub_pair.first, lh_xpub_pair.second);
    2950         [ +  - ]:        3905 :         diff.CacheLastHardenedExtPubKey(lh_xpub_pair.first, lh_xpub_pair.second);
    2951                 :           0 :     }
    2952                 :      208648 :     return diff;
    2953                 :           0 : }
    2954                 :             : 
    2955                 :      492840 : ExtPubKeyMap DescriptorCache::GetCachedParentExtPubKeys() const
    2956                 :             : {
    2957                 :      492840 :     return m_parent_xpubs;
    2958                 :             : }
    2959                 :             : 
    2960                 :      492840 : std::unordered_map<uint32_t, ExtPubKeyMap> DescriptorCache::GetCachedDerivedExtPubKeys() const
    2961                 :             : {
    2962                 :      492840 :     return m_derived_xpubs;
    2963                 :             : }
    2964                 :             : 
    2965                 :      417296 : ExtPubKeyMap DescriptorCache::GetCachedLastHardenedExtPubKeys() const
    2966                 :             : {
    2967                 :      417296 :     return m_last_hardened_xpubs;
    2968                 :             : }
        

Generated by: LCOV version 2.0-1