LCOV - code coverage report
Current view: top level - src/script - descriptor.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 94.7 % 1803 1708
Test Date: 2026-11-19 06:09:33 Functions: 87.7 % 244 214
Branches: 63.8 % 3041 1941

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

Generated by: LCOV version 2.0-1