LCOV - code coverage report
Current view: top level - src/script - descriptor.cpp (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 93.6 % 1767 1654
Test Date: 2026-08-19 06:38:57 Functions: 84.8 % 243 206
Branches: 64.5 % 3019 1947

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

Generated by: LCOV version 2.5.0-full