LCOV - code coverage report
Current view: top level - src/script - descriptor.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 92.4 % 1711 1581
Test Date: 2026-01-25 05:13:27 Functions: 86.3 % 226 195
Branches: 62.2 % 2941 1830

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

Generated by: LCOV version 2.0-1