LCOV - code coverage report
Current view: top level - src/script - descriptor.cpp (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 94.2 % 1803 1698
Test Date: 2026-11-21 05:38:30 Functions: 86.1 % 244 210
Branches: 64.6 % 3081 1989

             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                 :          27 : util::Expected<void, std::string> CheckDescriptorRangeBounds(int64_t low, int64_t high)
      54                 :             : {
      55         [ +  + ]:          27 :     if (low < 0) {
      56                 :          10 :         return util::Unexpected<std::string>("Range should be greater or equal than 0");
      57                 :             :     }
      58         [ +  + ]:          22 :     if ((high >> 31) != 0) {
      59                 :          20 :         return util::Unexpected<std::string>("End of range is too high");
      60                 :             :     }
      61         [ +  + ]:          12 :     if (low > high) {
      62                 :           4 :         return util::Unexpected<std::string>("Range specified as [begin,end] must not have begin after end");
      63                 :             :     }
      64         [ +  + ]:          10 :     if (high - low >= 1000000) {
      65                 :           6 :         return util::Unexpected<std::string>("Range is too large");
      66                 :             :     }
      67                 :           7 :     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                 :  1107413382 : uint64_t PolyMod(uint64_t c, int val)
     131                 :             : {
     132                 :  1107413382 :     uint8_t c0 = c >> 35;
     133                 :  1107413382 :     c = ((c & 0x7ffffffff) << 5) ^ val;
     134         [ +  + ]:  1107413382 :     if (c0 & 1) c ^= 0xf5dee51989;
     135         [ +  + ]:  1107413382 :     if (c0 & 2) c ^= 0xa9fdca3312;
     136         [ +  + ]:  1107413382 :     if (c0 & 4) c ^= 0x1bab10e32d;
     137         [ +  + ]:  1107413382 :     if (c0 & 8) c ^= 0x3706b1677a;
     138         [ +  + ]:  1107413382 :     if (c0 & 16) c ^= 0x644d626ffd;
     139                 :  1107413382 :     return c;
     140                 :             : }
     141                 :             : 
     142                 :     1706980 : 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                 :     1706980 :     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                 :     1706980 :     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                 :     1706980 :     static constexpr std::string_view CHECKSUM_CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
     174                 :             : 
     175                 :     1706980 :     uint64_t c = 1;
     176                 :     1706980 :     int cls = 0;
     177                 :     1706980 :     int clscount = 0;
     178         [ +  + ]:   821425565 :     for (auto ch : span) {
     179         [ +  + ]:   819718629 :         auto pos = INPUT_CHARSET_POS[static_cast<uint8_t>(ch)];
     180         [ +  + ]:   819718629 :         if (pos == -1) return "";
     181                 :   819718585 :         c = PolyMod(c, pos & 31); // Emit a symbol for the position inside the group, for every character.
     182                 :   819718585 :         cls = cls * 3 + (pos >> 5); // Accumulate the group numbers
     183         [ +  + ]:   819718585 :         if (++clscount == 3) {
     184                 :             :             // Emit an extra symbol representing the group numbers, for every 3 characters.
     185                 :   272536131 :             c = PolyMod(c, cls);
     186                 :   272536131 :             cls = 0;
     187                 :   272536131 :             clscount = 0;
     188                 :             :         }
     189                 :             :     }
     190         [ +  + ]:     1706936 :     if (clscount > 0) c = PolyMod(c, cls);
     191         [ +  + ]:    15362424 :     for (int j = 0; j < 8; ++j) c = PolyMod(c, 0); // Shift further to determine the checksum.
     192                 :     1706936 :     c ^= 1; // Prevent appending zeroes from not affecting the checksum.
     193                 :             : 
     194                 :     1706936 :     std::string ret(8, ' ');
     195         [ +  + ]:    15362424 :     for (int j = 0; j < 8; ++j) ret[j] = CHECKSUM_CHARSET[(c >> (5 * (7 - j))) & 31];
     196                 :     1706936 :     return ret;
     197                 :     1706936 : }
     198                 :             : 
     199   [ -  +  +  -  :     3315730 : 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                 :     4693077 :     explicit PubkeyProvider(uint32_t exp_index) : m_expr_index(exp_index) {}
     216                 :             : 
     217                 :       16726 :     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                 :       39738 :     virtual bool HavePrivateKeys(const SigningProvider& arg) const
     258                 :             :     {
     259                 :       39738 :         FlatSigningProvider tmp_provider;
     260         [ +  - ]:       39738 :         GetPrivKey(/*pos=*/0, arg, tmp_provider);
     261                 :       39738 :         return !tmp_provider.keys.empty();
     262                 :       39738 :     }
     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                 :      491229 :     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                 :     4145518 :     static bool DetermineApostropheUse(StringType type, bool normalized, bool public_apostrophe)
     283                 :             :     {
     284                 :     4145518 :         bool use_apostrophe{false};
     285                 :     4145518 :         switch (type) {
     286                 :       41700 :         case StringType::COMPAT:
     287                 :             :             // COMPAT always uses apostrophe to stay compatible with previous versions
     288                 :       41700 :             use_apostrophe = true;
     289                 :       41700 :             break;
     290                 :             :         case StringType::CANONICAL:
     291                 :             :             // CANONICAL always uses h
     292                 :             :             use_apostrophe = false;
     293                 :             :             break;
     294                 :     4101341 :         case StringType::PUBLIC:
     295                 :     4101341 :             use_apostrophe = !normalized && public_apostrophe;
     296                 :     4101341 :             break;
     297                 :             :         } // no default case, so the compiler can warn about missing cases
     298                 :     4145518 :         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                 :     1464539 :     std::string OriginString(StringType type, bool normalized=false) const
     309                 :             :     {
     310      [ +  +  + ]:     1464539 :         bool use_apostrophe{DetermineApostropheUse(type, normalized, m_apostrophe)};
     311   [ +  -  +  - ]:     2929078 :         return HexStr(m_origin.fingerprint) + FormatHDKeypath(m_origin.path, use_apostrophe);
     312                 :             :     }
     313                 :             : 
     314                 :             : public:
     315                 :     1441953 :     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                 :     1638953 :     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                 :     1638953 :         FlatSigningProvider subprovider;
     321         [ +  - ]:     1638953 :         std::optional<CPubKey> pub = m_provider->GetPubKey(pos, arg, subprovider, read_cache, write_cache);
     322         [ +  + ]:     1638953 :         if (!pub) return std::nullopt;
     323         [ +  - ]:     1637646 :         const CKeyID keyid{pub->GetID()};
     324         [ +  - ]:     1637646 :         Assert(subprovider.pubkeys.contains(keyid));
     325   [ +  -  +  - ]:     1637646 :         auto& [pubkey, suborigin] = subprovider.origins[keyid];
     326         [ +  - ]:     1637646 :         Assert(pubkey == *pub); // m_provider must have a valid origin by this point.
     327                 :     1637646 :         suborigin.fingerprint = m_origin.fingerprint;
     328         [ +  - ]:     1637646 :         suborigin.path.insert(suborigin.path.begin(), m_origin.path.begin(), m_origin.path.end());
     329                 :     1637646 :         auto origin{subprovider.origins.extract(keyid)};
     330         [ +  - ]:     1637646 :         out.Merge(std::move(subprovider));
     331                 :             :         // An explicit origin takes precedence over an implicit one for the same key.
     332         [ +  - ]:     1637646 :         out.origins.insert_or_assign(keyid, std::move(origin.mapped()));
     333         [ +  - ]:     1637646 :         return pub;
     334                 :     1638953 :     }
     335                 :      471027 :     bool IsRange() const override { return m_provider->IsRange(); }
     336                 :       22656 :     size_t GetSize() const override { return m_provider->GetSize(); }
     337                 :       23613 :     bool IsBIP32() const override { return m_provider->IsBIP32(); }
     338   [ +  -  +  -  :     1493874 :     std::string ToString(StringType type) const override { return "[" + OriginString(type) + "]" + m_provider->ToString(type); }
                   +  - ]
     339                 :      483569 :     bool ToPrivateString(const SigningProvider& arg, std::string& ret) const override
     340                 :             :     {
     341         [ +  - ]:      483569 :         std::string sub;
     342         [ +  - ]:      483569 :         bool has_priv_key{m_provider->ToPrivateString(arg, sub)};
     343   [ +  -  +  -  :      967138 :         ret = "[" + OriginString(StringType::PUBLIC) + "]" + std::move(sub);
                   +  - ]
     344                 :      483569 :         return has_priv_key;
     345                 :      483569 :     }
     346                 :      483164 :     bool ToNormalizedString(const SigningProvider& arg, std::string& ret, const DescriptorCache* cache) const override
     347                 :             :     {
     348         [ +  - ]:      483164 :         std::string sub;
     349   [ +  -  +  + ]:      483164 :         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         [ +  + ]:      483012 :         if (sub[0] == '[') {
     354         [ +  - ]:      421524 :             sub = sub.substr(9);
     355   [ +  -  +  -  :      421524 :             ret = "[" + OriginString(StringType::PUBLIC, /*normalized=*/true) + std::move(sub);
                   +  - ]
     356                 :             :         } else {
     357   [ +  -  +  -  :      122976 :             ret = "[" + OriginString(StringType::PUBLIC, /*normalized=*/true) + "]" + std::move(sub);
                   +  - ]
     358                 :             :         }
     359                 :             :         return true;
     360                 :      483164 :     }
     361                 :      588250 :     void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const override
     362                 :             :     {
     363                 :      588250 :         m_provider->GetPrivKey(pos, arg, out);
     364                 :      588250 :     }
     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                 :      436374 :     std::unique_ptr<PubkeyProvider> Clone() const override
     374                 :             :     {
     375   [ +  -  -  + ]:      436374 :         return std::make_unique<OriginPubkeyProvider>(m_expr_index, m_origin, m_provider->Clone(), m_apostrophe);
     376                 :             :     }
     377                 :          68 :     bool CanSelfExpand() const override { return m_provider->CanSelfExpand(); }
     378                 :             : };
     379                 :             : 
     380                 :             : /** An object representing a parsed constant public key in a descriptor. */
     381                 :       16726 : class ConstPubkeyProvider final : public PubkeyProvider
     382                 :             : {
     383                 :             :     CPubKey m_pubkey;
     384                 :             :     bool m_xonly;
     385                 :             : 
     386                 :      726812 :     std::optional<CKey> GetPrivKey(const SigningProvider& arg) const
     387                 :             :     {
     388                 :      726812 :         CKey key;
     389   [ +  +  +  -  :     1239530 :         if (!(m_xonly ? arg.GetKeyByXOnly(XOnlyPubKey(m_pubkey), key) :
                   +  + ]
     390   [ +  -  +  - ]:      911498 :                         arg.GetKey(m_pubkey.GetID(), key))) return std::nullopt;
     391                 :      328032 :         return key;
     392                 :      726812 :     }
     393                 :             : 
     394                 :             : public:
     395                 :     1895253 :     ConstPubkeyProvider(uint32_t exp_index, const CPubKey& pubkey, bool xonly) : PubkeyProvider(exp_index), m_pubkey(pubkey), m_xonly(xonly) {}
     396                 :     2933345 :     std::optional<CPubKey> GetPubKey(int pos, const SigningProvider&, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
     397                 :             :     {
     398         [ +  - ]:     2933345 :         KeyOriginInfo info;
     399         [ +  - ]:     2933345 :         CKeyID keyid = m_pubkey.GetID();
     400                 :     2933345 :         info.fingerprint = keyid.fingerprint();
     401   [ +  -  +  - ]:     2933345 :         out.origins.emplace(keyid, std::make_pair(m_pubkey, info));
     402         [ +  - ]:     2933345 :         out.pubkeys.emplace(keyid, m_pubkey);
     403                 :     2933345 :         return m_pubkey;
     404                 :     2933345 :     }
     405                 :     1330310 :     bool IsRange() const override { return false; }
     406                 :      202982 :     size_t GetSize() const override { return m_pubkey.size(); }
     407                 :       16060 :     bool IsBIP32() const override { return false; }
     408   [ +  +  +  - ]:     3361041 :     std::string ToString(StringType type) const override { return m_xonly ? HexStr(m_pubkey).substr(2) : HexStr(m_pubkey); }
     409                 :      359348 :     bool ToPrivateString(const SigningProvider& arg, std::string& ret) const override
     410                 :             :     {
     411                 :      359348 :         std::optional<CKey> key = GetPrivKey(arg);
     412         [ +  + ]:      359348 :         if (!key) {
     413         [ +  - ]:      206898 :             ret = ToString(StringType::PUBLIC);
     414                 :      206898 :             return false;
     415                 :             :         }
     416         [ +  - ]:      152450 :         ret = EncodeSecret(*key);
     417                 :      152450 :         return true;
     418                 :      359348 :     }
     419                 :      370688 :     bool ToNormalizedString(const SigningProvider& arg, std::string& ret, const DescriptorCache* cache) const override
     420                 :             :     {
     421                 :      370688 :         ret = ToString(StringType::PUBLIC);
     422                 :      370688 :         return true;
     423                 :             :     }
     424                 :      367464 :     void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const override
     425                 :             :     {
     426                 :      367464 :         std::optional<CKey> key = GetPrivKey(arg);
     427         [ +  + ]:      367464 :         if (!key) return;
     428   [ +  -  +  -  :      175582 :         out.keys.emplace(key->GetPubKey().GetID(), *key);
                   +  - ]
     429                 :      367464 :     }
     430                 :           0 :     std::optional<CPubKey> GetRootPubKey() const override
     431                 :             :     {
     432                 :           0 :         return m_pubkey;
     433                 :             :     }
     434                 :           0 :     std::optional<CExtPubKey> GetRootExtPubKey() const override
     435                 :             :     {
     436                 :           0 :         return std::nullopt;
     437                 :             :     }
     438                 :      319009 :     std::unique_ptr<PubkeyProvider> Clone() const override
     439                 :             :     {
     440                 :      319009 :         return std::make_unique<ConstPubkeyProvider>(m_expr_index, m_pubkey, m_xonly);
     441                 :             :     }
     442                 :         957 :     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                 :     3743346 :     bool GetExtKey(const SigningProvider& arg, CExtKey& ret) const
     462                 :             :     {
     463                 :     3743346 :         CKey key;
     464   [ +  -  +  -  :     3743346 :         if (!arg.GetKey(m_root_extkey.pubkey.GetID(), key)) return false;
                   +  + ]
     465                 :     3357046 :         ret.nDepth = m_root_extkey.nDepth;
     466                 :     3357046 :         ret.fingerprint = m_root_extkey.fingerprint;
     467                 :     3357046 :         ret.nChild = m_root_extkey.nChild;
     468                 :     3357046 :         ret.chaincode = m_root_extkey.chaincode;
     469         [ +  - ]:     3357046 :         ret.key = key;
     470                 :             :         return true;
     471                 :     3743346 :     }
     472                 :             : 
     473                 :             :     // Derives the last xprv
     474                 :     2625589 :     bool GetDerivedExtKey(const SigningProvider& arg, CExtKey& xprv, CExtKey& last_hardened) const
     475                 :             :     {
     476         [ +  + ]:     2625589 :         if (!GetExtKey(arg, xprv)) return false;
     477         [ +  + ]:     5826930 :         for (auto entry : m_path) {
     478         [ +  - ]:     3399314 :             if (!xprv.Derive(xprv, entry)) return false;
     479         [ +  + ]:     3399314 :             if (entry >> 31) {
     480                 :     1804373 :                 last_hardened = xprv;
     481                 :             :             }
     482                 :             :         }
     483                 :             :         return true;
     484                 :             :     }
     485                 :             : 
     486                 :     2262305 :     bool IsHardened() const
     487                 :             :     {
     488         [ +  + ]:     2262305 :         if (m_derive == DeriveType::HARDENED_RANGED) return true;
     489         [ -  + ]:     2165924 :         return HasHardenedDerivation(m_path);
     490                 :             :     }
     491                 :             : 
     492                 :             : public:
     493                 :     1273372 :     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                 :     5573246 :     bool IsRange() const override { return m_derive != DeriveType::NON_RANGED; }
     495                 :       92198 :     size_t GetSize() const override { return 33; }
     496                 :       45927 :     bool IsBIP32() const override { return true; }
     497                 :     3925334 :     std::optional<CPubKey> GetPubKey(int pos, const SigningProvider& arg, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
     498                 :             :     {
     499         [ +  - ]:     3925334 :         KeyOriginInfo info;
     500         [ +  - ]:     3925334 :         info.fingerprint = m_root_extkey.id_key_fingerprint();
     501         [ +  - ]:     3925334 :         info.path = m_path;
     502   [ +  +  +  - ]:     3925334 :         if (m_derive == DeriveType::UNHARDENED_RANGED) info.path.push_back((uint32_t)pos);
     503   [ +  +  +  - ]:     3925334 :         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                 :     3925334 :         CExtPubKey final_extkey = m_root_extkey;
     507                 :     3925334 :         CExtPubKey parent_extkey = m_root_extkey;
     508         [ +  + ]:     3925334 :         CExtPubKey last_hardened_extkey;
     509                 :     3925334 :         bool der = true;
     510         [ +  + ]:     3925334 :         if (read_cache) {
     511   [ +  -  +  + ]:     1665524 :             if (!read_cache->GetCachedDerivedExtPubKey(m_expr_index, pos, final_extkey)) {
     512         [ +  + ]:     1563089 :                 if (m_derive == DeriveType::HARDENED_RANGED) return std::nullopt;
     513                 :             :                 // Try to get the derivation parent
     514   [ +  -  +  + ]:     1553369 :                 if (!read_cache->GetCachedParentExtPubKey(m_expr_index, parent_extkey)) return std::nullopt;
     515                 :     1548419 :                 final_extkey = parent_extkey;
     516   [ +  +  +  - ]:     1548419 :                 if (m_derive == DeriveType::UNHARDENED_RANGED) der = parent_extkey.Derive(final_extkey, pos);
     517                 :             :             }
     518   [ +  -  +  + ]:     2259810 :         } else if (IsHardened()) {
     519         [ +  - ]:      939745 :             CExtKey xprv;
     520                 :      939745 :             CExtKey lh_xprv;
     521   [ +  -  +  + ]:      939745 :             if (!GetDerivedExtKey(arg, xprv, lh_xprv)) return std::nullopt;
     522         [ +  - ]:      923380 :             parent_extkey = xprv.Neuter();
     523   [ +  +  +  - ]:      923380 :             if (m_derive == DeriveType::UNHARDENED_RANGED) der = xprv.Derive(xprv, pos);
     524   [ +  +  +  - ]:      923380 :             if (m_derive == DeriveType::HARDENED_RANGED) der = xprv.Derive(xprv, pos | BIP32_HARDENED_FLAG);
     525         [ +  - ]:      923380 :             final_extkey = xprv.Neuter();
     526         [ +  + ]:      923380 :             if (lh_xprv.key.IsValid()) {
     527         [ +  - ]:      828004 :                 last_hardened_extkey = lh_xprv.Neuter();
     528                 :             :             }
     529                 :      939745 :         } else {
     530         [ +  + ]:     2400857 :             for (auto entry : m_path) {
     531   [ +  -  -  + ]:     1080792 :                 if (!parent_extkey.Derive(parent_extkey, entry)) return std::nullopt;
     532                 :             :             }
     533                 :     1320065 :             final_extkey = parent_extkey;
     534   [ +  +  +  - ]:     1320065 :             if (m_derive == DeriveType::UNHARDENED_RANGED) der = parent_extkey.Derive(final_extkey, pos);
     535         [ -  + ]:     1320065 :             assert(m_derive != DeriveType::HARDENED_RANGED);
     536                 :             :         }
     537         [ -  + ]:     2285042 :         if (!der) return std::nullopt;
     538                 :             : 
     539   [ +  -  +  -  :     3894299 :         out.origins.emplace(final_extkey.pubkey.GetID(), std::make_pair(final_extkey.pubkey, info));
                   +  - ]
     540   [ +  -  +  - ]:     3894299 :         out.pubkeys.emplace(final_extkey.pubkey.GetID(), final_extkey.pubkey);
     541                 :             : 
     542         [ +  + ]:     3894299 :         if (write_cache) {
     543                 :             :             // Only cache parent if there is any unhardened derivation
     544         [ +  + ]:     2024127 :             if (m_derive != DeriveType::HARDENED_RANGED) {
     545         [ +  - ]:     1934647 :                 write_cache->CacheParentExtPubKey(m_expr_index, parent_extkey);
     546                 :             :                 // Cache last hardened xpub if we have it
     547         [ +  + ]:     1934647 :                 if (last_hardened_extkey.pubkey.IsValid()) {
     548         [ +  - ]:      817523 :                     write_cache->CacheLastHardenedExtPubKey(m_expr_index, last_hardened_extkey);
     549                 :             :                 }
     550   [ -  +  +  - ]:       89480 :             } else if (info.path.size() > 0) {
     551         [ +  - ]:       89480 :                 write_cache->CacheDerivedExtPubKey(m_expr_index, pos, final_extkey);
     552                 :             :             }
     553                 :             :         }
     554                 :             : 
     555                 :     3894299 :         return final_extkey.pubkey;
     556                 :     3925334 :     }
     557                 :     2680979 :     std::string ToString(StringType type, bool normalized) const
     558                 :             :     {
     559      [ +  +  + ]:     2680979 :         bool use_apostrophe{DetermineApostropheUse(type, normalized, m_apostrophe)};
     560   [ +  -  +  - ]:     5361958 :         std::string ret = EncodeExtPubKey(m_root_extkey) + FormatHDKeypath(m_path, /*apostrophe=*/use_apostrophe);
     561         [ +  + ]:     2680979 :         if (IsRange()) {
     562         [ +  - ]:      230340 :             ret += "/*";
     563   [ +  +  +  + ]:      230340 :             if (m_derive == DeriveType::HARDENED_RANGED) ret += use_apostrophe ? '\'' : 'h';
     564                 :             :         }
     565                 :     2680979 :         return ret;
     566                 :           0 :     }
     567                 :     2642444 :     std::string ToString(StringType type) const override
     568                 :             :     {
     569                 :     1867165 :         return ToString(type, /*normalized=*/false);
     570                 :             :     }
     571                 :     1117757 :     bool ToPrivateString(const SigningProvider& arg, std::string& out) const override
     572                 :             :     {
     573         [ +  - ]:     1117757 :         CExtKey key;
     574   [ +  -  +  + ]:     1117757 :         if (!GetExtKey(arg, key)) {
     575         [ +  - ]:      188327 :             out = ToString(StringType::PUBLIC);
     576                 :      188327 :             return false;
     577                 :             :         }
     578   [ +  -  +  -  :      929430 :         out = EncodeExtKey(key) + FormatHDKeypath(m_path, /*apostrophe=*/m_apostrophe);
                   +  - ]
     579         [ +  + ]:      929430 :         if (IsRange()) {
     580         [ +  - ]:       43969 :             out += "/*";
     581   [ +  +  +  + ]:       43969 :             if (m_derive == DeriveType::HARDENED_RANGED) out += m_apostrophe ? '\'' : 'h';
     582                 :             :         }
     583                 :             :         return true;
     584                 :     1117757 :     }
     585                 :     1111539 :     bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache) const override
     586                 :             :     {
     587         [ +  + ]:     1111539 :         if (m_derive == DeriveType::HARDENED_RANGED) {
     588                 :       38535 :             out = ToString(StringType::PUBLIC, /*normalized=*/true);
     589                 :             : 
     590                 :       38535 :             return true;
     591                 :             :         }
     592                 :             :         // Step backwards to find the last hardened step in the path
     593         [ -  + ]:     1073004 :         int i = (int)m_path.size() - 1;
     594         [ +  + ]:     1661363 :         for (; i >= 0; --i) {
     595         [ +  + ]:     1074411 :             if (m_path.at(i) >> 31) {
     596                 :             :                 break;
     597                 :             :             }
     598                 :             :         }
     599                 :             :         // Either no derivation or all unhardened derivation
     600         [ +  + ]:     1073004 :         if (i == -1) {
     601                 :      586952 :             out = ToString(StringType::PUBLIC);
     602                 :      586952 :             return true;
     603                 :             :         }
     604                 :             :         // Get the path to the last hardened stup
     605                 :      486052 :         KeyOriginInfo origin;
     606                 :      486052 :         int k = 0;
     607         [ +  + ]:     1241784 :         for (; k <= i; ++k) {
     608                 :             :             // Add to the path
     609   [ +  -  +  - ]:      755732 :             origin.path.push_back(m_path.at(k));
     610                 :             :         }
     611                 :             :         // Build the remaining path
     612                 :      486052 :         KeyPath end_path;
     613   [ -  +  +  + ]:      492180 :         for (; k < (int)m_path.size(); ++k) {
     614   [ +  -  +  - ]:        6128 :             end_path.push_back(m_path.at(k));
     615                 :             :         }
     616         [ +  - ]:      486052 :         origin.fingerprint = m_root_extkey.id_key_fingerprint();
     617                 :             : 
     618         [ +  + ]:      486052 :         CExtPubKey xpub;
     619         [ +  + ]:      486052 :         CExtKey lh_xprv;
     620                 :             :         // If we have the cache, just get the parent xpub
     621         [ +  + ]:      486052 :         if (cache != nullptr) {
     622         [ +  - ]:        3527 :             cache->GetCachedLastHardenedExtPubKey(m_expr_index, xpub);
     623                 :             :         }
     624         [ +  + ]:      486052 :         if (!xpub.pubkey.IsValid()) {
     625                 :             :             // Cache miss, or nor cache, or need privkey
     626         [ +  - ]:      482525 :             CExtKey xprv;
     627   [ +  -  +  + ]:      482525 :             if (!GetDerivedExtKey(arg, xprv, lh_xprv)) return false;
     628         [ +  - ]:      481368 :             xpub = lh_xprv.Neuter();
     629                 :      482525 :         }
     630         [ -  + ]:      484895 :         assert(xpub.pubkey.IsValid());
     631                 :             : 
     632                 :             :         // Build the string
     633   [ +  -  +  -  :      969790 :         std::string origin_str = HexStr(origin.fingerprint) + FormatHDKeypath(origin.path);
                   +  - ]
     634   [ +  -  +  -  :      969790 :         out = "[" + origin_str + "]" + EncodeExtPubKey(xpub) + FormatHDKeypath(end_path);
          +  -  +  -  +  
                      - ]
     635         [ +  + ]:      484895 :         if (IsRange()) {
     636         [ +  - ]:         820 :             out += "/*";
     637         [ -  + ]:         820 :             assert(m_derive == DeriveType::UNHARDENED_RANGED);
     638                 :             :         }
     639                 :      484895 :         return true;
     640                 :      486052 :     }
     641                 :     1203319 :     void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const override
     642                 :             :     {
     643         [ +  - ]:     1203319 :         CExtKey extkey;
     644                 :     1203319 :         CExtKey dummy;
     645   [ +  -  +  + ]:     1203319 :         if (!GetDerivedExtKey(arg, extkey, dummy)) return;
     646   [ +  +  +  -  :     1022868 :         if (m_derive == DeriveType::UNHARDENED_RANGED && !extkey.Derive(extkey, pos)) return;
                   +  - ]
     647   [ +  +  +  -  :     1022868 :         if (m_derive == DeriveType::HARDENED_RANGED && !extkey.Derive(extkey, pos | BIP32_HARDENED_FLAG)) return;
                   +  - ]
     648   [ +  -  +  -  :     1022868 :         out.keys.emplace(extkey.key.GetPubKey().GetID(), extkey.key);
                   +  - ]
     649                 :     1203319 :     }
     650                 :           0 :     std::optional<CPubKey> GetRootPubKey() const override
     651                 :             :     {
     652                 :           0 :         return std::nullopt;
     653                 :             :     }
     654                 :           0 :     std::optional<CExtPubKey> GetRootExtPubKey() const override
     655                 :             :     {
     656                 :           0 :         return m_root_extkey;
     657                 :             :     }
     658                 :      998109 :     std::unique_ptr<PubkeyProvider> Clone() const override
     659                 :             :     {
     660         [ -  + ]:      998109 :         return std::make_unique<BIP32PubkeyProvider>(m_expr_index, m_root_extkey, m_path, m_derive, m_apostrophe);
     661                 :             :     }
     662                 :        2495 :     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                 :      418701 :     bool IsRangedDerivation() const { return m_derive != DeriveType::NON_RANGED; }
     680                 :             : 
     681                 :             : public:
     682                 :       82499 :     MuSigPubkeyProvider(
     683                 :             :         uint32_t exp_index,
     684                 :             :         std::vector<std::unique_ptr<PubkeyProvider>> providers,
     685                 :             :         KeyPath path,
     686                 :             :         DeriveType derive
     687                 :             :     )
     688                 :       82499 :         : PubkeyProvider(exp_index),
     689                 :       82499 :         m_participants(std::move(providers)),
     690         [ +  - ]:       82499 :         m_path(std::move(path)),
     691         [ +  - ]:       82499 :         m_derive(derive),
     692         [ +  - ]:     1006907 :         m_ranged_participants(std::any_of(m_participants.begin(), m_participants.end(), [](const auto& pubkey) { return pubkey->IsRange(); }))
     693                 :             :     {
     694   [ +  +  +  -  :       86575 :         if (!Assume(!(m_ranged_participants && IsRangedDerivation()))) {
             +  -  -  + ]
     695         [ #  # ]:           0 :             throw std::runtime_error("musig(): Cannot have both ranged participants and ranged derivation");
     696                 :             :         }
     697   [ +  -  -  + ]:       82499 :         if (!Assume(m_derive != DeriveType::HARDENED_RANGED)) {
     698         [ #  # ]:           0 :             throw std::runtime_error("musig(): Cannot have hardened derivation");
     699                 :             :         }
     700                 :       82499 :     }
     701                 :             : 
     702                 :      151610 :     std::optional<CPubKey> GetPubKey(int pos, const SigningProvider& arg, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
     703                 :             :     {
     704                 :      151610 :         FlatSigningProvider dummy;
     705                 :             :         // If the participants are not ranged, we can compute and cache the aggregate pubkey by creating a PubkeyProvider for it
     706   [ +  +  +  + ]:      151610 :         if (!m_aggregate_provider && !m_ranged_participants) {
     707                 :             :             // Retrieve the pubkeys from the providers
     708                 :       57223 :             std::vector<CPubKey> pubkeys;
     709         [ +  + ]:      848543 :             for (const auto& prov : m_participants) {
     710         [ +  - ]:      791968 :                 std::optional<CPubKey> pubkey = prov->GetPubKey(0, arg, dummy, read_cache, write_cache);
     711         [ +  + ]:      791968 :                 if (!pubkey.has_value()) {
     712                 :         648 :                     return std::nullopt;
     713                 :             :                 }
     714         [ +  - ]:      791320 :                 pubkeys.push_back(pubkey.value());
     715                 :             :             }
     716                 :       56575 :             std::sort(pubkeys.begin(), pubkeys.end());
     717                 :             : 
     718                 :             :             // Aggregate the pubkey
     719         [ +  - ]:       56575 :             m_aggregate_pubkey = MuSig2AggregatePubkeys(pubkeys);
     720   [ +  -  -  + ]:       56575 :             if (!Assume(m_aggregate_pubkey.has_value())) return std::nullopt;
     721                 :             : 
     722                 :             :             // Make our pubkey provider
     723   [ +  +  +  + ]:       56575 :             if (IsRangedDerivation() || !m_path.empty()) {
     724                 :             :                 // Make the synthetic xpub and construct the BIP32PubkeyProvider
     725   [ +  -  +  - ]:        5218 :                 CExtPubKey extpub = CreateMuSig2SyntheticXpub(m_aggregate_pubkey.value());
     726   [ +  -  -  + ]:        5218 :                 m_aggregate_provider = std::make_unique<BIP32PubkeyProvider>(m_expr_index, extpub, m_path, m_derive, /*apostrophe=*/false);
     727                 :        5218 :             } else {
     728   [ +  -  +  - ]:       51357 :                 m_aggregate_provider = std::make_unique<ConstPubkeyProvider>(m_expr_index, m_aggregate_pubkey.value(), /*xonly=*/false);
     729                 :             :             }
     730                 :       57223 :         }
     731                 :             : 
     732                 :             :         // Retrieve all participant pubkeys
     733                 :      150962 :         std::vector<CPubKey> pubkeys;
     734         [ +  + ]:     2952660 :         for (const auto& prov : m_participants) {
     735         [ +  - ]:     2805713 :             std::optional<CPubKey> pub = prov->GetPubKey(pos, arg, out, read_cache, write_cache);
     736         [ +  + ]:     2805713 :             if (!pub) return std::nullopt;
     737         [ +  - ]:     2801698 :             pubkeys.emplace_back(*pub);
     738                 :             :         }
     739                 :      146947 :         std::sort(pubkeys.begin(), pubkeys.end());
     740                 :             : 
     741         [ +  + ]:      146947 :         CPubKey pubout;
     742         [ +  + ]:      146947 :         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         [ +  - ]:      130221 :             std::optional<CPubKey> pub = m_aggregate_provider->GetPubKey(pos, dummy, out, read_cache, write_cache);
     747         [ -  + ]:      130221 :             if (!pub) return std::nullopt;
     748         [ +  - ]:      130221 :             pubout = *pub;
     749   [ +  -  +  - ]:      130221 :             out.aggregate_pubkeys.emplace(m_aggregate_pubkey.value(), pubkeys);
     750                 :             :         } else {
     751   [ +  -  +  -  :       16726 :             if (!Assume(m_ranged_participants) || !Assume(m_path.empty())) return std::nullopt;
             +  -  +  - ]
     752                 :             :             // Compute aggregate key from derived participants
     753         [ +  - ]:       16726 :             std::optional<CPubKey> aggregate_pubkey = MuSig2AggregatePubkeys(pubkeys);
     754         [ -  + ]:       16726 :             if (!aggregate_pubkey) return std::nullopt;
     755         [ +  - ]:       16726 :             pubout = *aggregate_pubkey;
     756                 :             : 
     757         [ +  - ]:       16726 :             std::unique_ptr<ConstPubkeyProvider> this_agg_provider = std::make_unique<ConstPubkeyProvider>(m_expr_index, aggregate_pubkey.value(), /*xonly=*/false);
     758         [ +  - ]:       16726 :             this_agg_provider->GetPubKey(0, dummy, out, read_cache, write_cache);
     759         [ +  - ]:       16726 :             out.aggregate_pubkeys.emplace(pubout, pubkeys);
     760                 :       16726 :         }
     761                 :             : 
     762   [ +  -  -  + ]:      146947 :         if (!Assume(pubout.IsValid())) return std::nullopt;
     763                 :      146947 :         return pubout;
     764                 :      151610 :     }
     765   [ +  +  +  + ]:      163567 :     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                 :       18085 :     size_t GetSize() const override { return 32; }
     768                 :             : 
     769                 :       83247 :     std::string ToString(StringType type) const override
     770                 :             :     {
     771                 :       83247 :         std::string out = "musig(";
     772   [ -  +  +  + ]:     1701178 :         for (size_t i = 0; i < m_participants.size(); ++i) {
     773         [ +  - ]:     1617931 :             const auto& pubkey = m_participants.at(i);
     774   [ +  +  +  - ]:     1617931 :             if (i) out += ',';
     775         [ +  - ]:     3235862 :             out += pubkey->ToString(type);
     776                 :             :         }
     777         [ +  - ]:       83247 :         out += ')';
     778         [ +  - ]:      166494 :         out += FormatHDKeypath(m_path);
     779         [ +  + ]:       83247 :         if (IsRangedDerivation()) {
     780         [ +  - ]:        7254 :             out += "/*";
     781                 :             :         }
     782                 :       83247 :         return out;
     783                 :           0 :     }
     784                 :       56236 :     bool ToPrivateString(const SigningProvider& arg, std::string& out) const override
     785                 :             :     {
     786                 :       56236 :         bool any_privkeys = false;
     787                 :       56236 :         out = "musig(";
     788   [ -  +  +  + ]:     1002236 :         for (size_t i = 0; i < m_participants.size(); ++i) {
     789                 :      946000 :             const auto& pubkey = m_participants.at(i);
     790         [ +  + ]:      946000 :             if (i) out += ',';
     791         [ +  - ]:      946000 :             std::string tmp;
     792   [ +  -  +  + ]:      946000 :             if (pubkey->ToPrivateString(arg, tmp)) {
     793                 :      687417 :                 any_privkeys = true;
     794                 :             :             }
     795         [ -  + ]:     1892000 :             out += tmp;
     796                 :      946000 :         }
     797                 :       56236 :         out += ')';
     798         [ -  + ]:      112472 :         out += FormatHDKeypath(m_path);
     799         [ +  + ]:       56236 :         if (IsRangedDerivation()) {
     800                 :        1978 :             out += "/*";
     801                 :             :         }
     802                 :       56236 :         return any_privkeys;
     803                 :             :     }
     804                 :       55379 :     bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache = nullptr) const override
     805                 :             :     {
     806                 :       55379 :         out = "musig(";
     807   [ -  +  +  + ]:      989371 :         for (size_t i = 0; i < m_participants.size(); ++i) {
     808                 :      934371 :             const auto& pubkey = m_participants.at(i);
     809         [ +  + ]:      934371 :             if (i) out += ',';
     810         [ +  - ]:      934371 :             std::string tmp;
     811   [ +  -  +  + ]:      934371 :             if (!pubkey->ToNormalizedString(arg, tmp, cache)) {
     812                 :         379 :                 return false;
     813                 :             :             }
     814         [ -  + ]:     1867984 :             out += tmp;
     815                 :      934371 :         }
     816                 :       55000 :         out += ')';
     817         [ -  + ]:      110000 :         out += FormatHDKeypath(m_path);
     818         [ +  + ]:       55000 :         if (IsRangedDerivation()) {
     819                 :        1881 :             out += "/*";
     820                 :             :         }
     821                 :             :         return true;
     822                 :             :     }
     823                 :             : 
     824                 :       54612 :     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         [ +  + ]:      985317 :         for (const auto& prov : m_participants) {
     830                 :      930705 :             prov->GetPrivKey(pos, arg, out);
     831                 :             :         }
     832                 :       54612 :     }
     833                 :             : 
     834                 :           0 :     bool HavePrivateKeys(const SigningProvider& arg) const override
     835                 :             :     {
     836                 :           0 :         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                 :       30548 :     std::unique_ptr<PubkeyProvider> Clone() const override
     854                 :             :     {
     855                 :       30548 :         std::vector<std::unique_ptr<PubkeyProvider>> providers;
     856   [ -  +  +  - ]:       30548 :         providers.reserve(m_participants.size());
     857         [ +  + ]:       94457 :         for (const std::unique_ptr<PubkeyProvider>& p : m_participants) {
     858   [ +  -  +  - ]:       63909 :             providers.emplace_back(p->Clone());
     859                 :             :         }
     860   [ +  -  -  + ]:       61096 :         return std::make_unique<MuSigPubkeyProvider>(m_expr_index, std::move(providers), m_path, m_derive);
     861                 :       30548 :     }
     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                 :       54612 :     size_t GetKeyCount() const override
     868                 :             :     {
     869         [ -  + ]:       54612 :         return 1 + m_participants.size();
     870                 :             :     }
     871                 :         301 :     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         [ +  + ]:        1353 :         for (const auto& key : m_participants) {
     876         [ +  - ]:        1052 :             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                 :      264760 :     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         [ -  + ]:     3456286 :     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   [ -  +  +  - ]:      302778 :     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         [ -  + ]:      607534 :     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                 :       64197 :     bool IsSolvable() const override
     930                 :             :     {
     931         [ +  + ]:      112897 :         for (const auto& arg : m_subdescriptor_args) {
     932         [ +  - ]:       48700 :             if (!arg->IsSolvable()) return false;
     933                 :             :         }
     934                 :             :         return true;
     935                 :             :     }
     936                 :             : 
     937                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     938                 :       12469 :     bool HavePrivateKeys(const SigningProvider& arg) const override
     939                 :             :     {
     940   [ +  +  +  + ]:       12469 :         if (m_pubkey_args.empty() && m_subdescriptor_args.empty()) return false;
     941                 :             : 
     942         [ +  + ]:       16317 :         for (const auto& sub: m_subdescriptor_args) {
     943         [ +  - ]:        5439 :             if (!sub->HavePrivateKeys(arg)) return false;
     944                 :             :         }
     945                 :             : 
     946         [ +  + ]:       50616 :         for (const auto& pubkey : m_pubkey_args) {
     947         [ +  - ]:       39738 :             if (!pubkey->HavePrivateKeys(arg)) return false;
     948                 :             :         }
     949                 :             : 
     950                 :             :         return true;
     951                 :             :     }
     952                 :             : 
     953                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     954                 :      529837 :     bool IsRange() const final
     955                 :             :     {
     956         [ +  + ]:     2310437 :         for (const auto& pubkey : m_pubkey_args) {
     957         [ +  + ]:     1921972 :             if (pubkey->IsRange()) return true;
     958                 :             :         }
     959         [ +  + ]:      530649 :         for (const auto& arg : m_subdescriptor_args) {
     960         [ +  + ]:      218233 :             if (arg->IsRange()) return true;
     961                 :             :         }
     962                 :             :         return false;
     963                 :             :     }
     964                 :             : 
     965                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     966                 :     1672407 :     virtual bool ToStringSubScriptHelper(const SigningProvider* arg, std::string& ret, const StringType type, const DescriptorCache* cache = nullptr) const
     967                 :             :     {
     968                 :     1672407 :         size_t pos = 0;
     969                 :     1672407 :         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                 :     1672407 :         bool any_success{!is_private};
     973         [ +  + ]:     1748683 :         for (const auto& scriptarg : m_subdescriptor_args) {
     974         [ -  + ]:       76652 :             if (pos++) ret += ',';
     975         [ +  - ]:       76652 :             std::string tmp;
     976         [ +  - ]:       76652 :             bool subscript_res{scriptarg->ToStringHelper(arg, tmp, type, cache)};
     977         [ +  + ]:       76652 :             if (!is_private && !subscript_res) return false;
     978                 :       76276 :             any_success = any_success || subscript_res;
     979         [ -  + ]:      152552 :             ret += tmp;
     980                 :       76652 :         }
     981                 :             :         return any_success;
     982                 :             :     }
     983                 :             : 
     984                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     985                 :     1757463 :     virtual bool ToStringHelper(const SigningProvider* arg, std::string& out, const StringType type, const DescriptorCache* cache = nullptr) const
     986                 :             :     {
     987                 :     1757463 :         std::string extra = ToStringExtra();
     988   [ -  +  +  + ]:     1757463 :         size_t pos = extra.size() > 0 ? 1 : 0;
     989   [ +  -  +  - ]:     1757463 :         std::string ret = m_name + "(" + extra;
     990                 :     1757463 :         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                 :     1757463 :         bool any_success{!is_private};
     994                 :             : 
     995         [ +  + ]:     4833151 :         for (const auto& pubkey : m_pubkey_args) {
     996   [ +  +  +  - ]:     3076388 :             if (pos++) ret += ',';
     997   [ +  +  +  +  :     3076388 :             std::string tmp;
                   +  - ]
     998   [ +  +  +  +  :     3076388 :             switch (type) {
                   +  - ]
     999                 :      532685 :                 case StringType::NORMALIZED:
    1000   [ +  -  +  + ]:      532685 :                     if (!pubkey->ToNormalizedString(*arg, tmp, cache)) return false;
    1001                 :             :                     break;
    1002                 :      515999 :                 case StringType::PRIVATE:
    1003   [ +  -  +  +  :      515999 :                     any_success = pubkey->ToPrivateString(*arg, tmp) || any_success;
                   +  + ]
    1004                 :             :                     break;
    1005                 :     1909853 :                 case StringType::PUBLIC:
    1006         [ +  - ]:     1909853 :                     tmp = pubkey->ToString(PubkeyProvider::StringType::PUBLIC);
    1007                 :     1909853 :                     break;
    1008                 :      113093 :                 case StringType::COMPAT:
    1009         [ +  - ]:      113093 :                     tmp = pubkey->ToString(PubkeyProvider::StringType::COMPAT);
    1010                 :      113093 :                     break;
    1011                 :        4758 :                 case StringType::CANONICAL:
    1012         [ +  - ]:        4758 :                     tmp = pubkey->ToString(PubkeyProvider::StringType::CANONICAL);
    1013                 :        4758 :                     break;
    1014                 :             :             }
    1015         [ -  + ]:     6151376 :             ret += tmp;
    1016                 :     3076388 :         }
    1017         [ +  - ]:     3513526 :         std::string subscript;
    1018         [ +  - ]:     1756763 :         bool subscript_res{ToStringSubScriptHelper(arg, subscript, type, cache)};
    1019         [ +  + ]:     1756763 :         if (!is_private && !subscript_res) return false;
    1020                 :     1755908 :         any_success = any_success || subscript_res;
    1021   [ +  +  +  +  :     3209825 :         if (pos && subscript.size()) ret += ',';
                   +  - ]
    1022         [ +  - ]:     3511816 :         out = std::move(ret) + std::move(subscript) + ")";
    1023                 :     1755908 :         return any_success;
    1024                 :     1757463 :     }
    1025                 :             : 
    1026                 :     1584445 :     std::string ToString(bool compat_format) const final
    1027                 :             :     {
    1028         [ +  + ]:     1584445 :         std::string ret;
    1029   [ +  +  +  - ]:     3145833 :         ToStringHelper(nullptr, ret, compat_format ? StringType::COMPAT : StringType::PUBLIC);
    1030         [ +  - ]:     1584445 :         return AddChecksum(ret);
    1031                 :     1584445 :     }
    1032                 :             : 
    1033                 :        3530 :     std::string ToCanonicalString() const final
    1034                 :             :     {
    1035         [ +  - ]:        3530 :         std::string ret;
    1036         [ +  - ]:        3530 :         ToStringHelper(nullptr, ret, StringType::CANONICAL);
    1037         [ +  - ]:        3530 :         return AddChecksum(ret);
    1038                 :        3530 :     }
    1039                 :             : 
    1040                 :       31816 :     bool ToPrivateString(const SigningProvider& arg, std::string& out) const override
    1041                 :             :     {
    1042                 :       31816 :         bool has_priv_key{ToStringHelper(&arg, out, StringType::PRIVATE)};
    1043                 :       31816 :         out = AddChecksum(out);
    1044                 :       31816 :         return has_priv_key;
    1045                 :             :     }
    1046                 :             : 
    1047                 :       38074 :     bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache) const override final
    1048                 :             :     {
    1049                 :       38074 :         bool ret = ToStringHelper(&arg, out, StringType::NORMALIZED, cache);
    1050                 :       38074 :         out = AddChecksum(out);
    1051                 :       38074 :         return ret;
    1052                 :             :     }
    1053                 :             : 
    1054                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
    1055                 :      290636 :     bool ExpandHelper(int pos, const SigningProvider& arg, const DescriptorCache* read_cache, std::vector<CScript>& output_scripts, FlatSigningProvider& out, DescriptorCache* write_cache) const
    1056                 :             :     {
    1057                 :      290636 :         FlatSigningProvider subprovider;
    1058                 :      290636 :         std::vector<CPubKey> pubkeys;
    1059   [ -  +  +  - ]:      290636 :         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         [ +  + ]:     2876961 :         for (const auto& p : m_pubkey_args) {
    1063         [ +  - ]:     2602343 :             std::optional<CPubKey> pubkey = p->GetPubKey(pos, arg, subprovider, read_cache, write_cache);
    1064         [ +  + ]:     2602343 :             if (!pubkey) return false;
    1065         [ +  - ]:     2586325 :             pubkeys.push_back(pubkey.value());
    1066                 :             :         }
    1067                 :      274618 :         std::vector<CScript> subscripts;
    1068         [ +  + ]:      401932 :         for (const auto& subarg : m_subdescriptor_args) {
    1069                 :      135573 :             std::vector<CScript> outscripts;
    1070   [ +  -  +  + ]:      135573 :             if (!subarg->ExpandHelper(pos, arg, read_cache, outscripts, subprovider, write_cache)) return false;
    1071   [ -  +  -  + ]:      127314 :             assert(outscripts.size() == 1);
    1072         [ +  - ]:      127314 :             subscripts.emplace_back(std::move(outscripts[0]));
    1073                 :      135573 :         }
    1074         [ +  - ]:      266359 :         out.Merge(std::move(subprovider));
    1075                 :             : 
    1076   [ -  +  +  - ]:      266359 :         output_scripts = MakeScripts(pubkeys, std::span{subscripts}, out);
    1077                 :      266359 :         return true;
    1078                 :      565254 :     }
    1079                 :             : 
    1080                 :       64359 :     bool Expand(int pos, const SigningProvider& provider, std::vector<CScript>& output_scripts, FlatSigningProvider& out, DescriptorCache* write_cache = nullptr) const final
    1081                 :             :     {
    1082                 :       64359 :         return ExpandHelper(pos, provider, nullptr, output_scripts, out, write_cache);
    1083                 :             :     }
    1084                 :             : 
    1085                 :       90704 :     bool ExpandFromCache(int pos, const DescriptorCache& read_cache, std::vector<CScript>& output_scripts, FlatSigningProvider& out) const final
    1086                 :             :     {
    1087                 :       90704 :         return ExpandHelper(pos, DUMMY_SIGNING_PROVIDER, &read_cache, output_scripts, out, nullptr);
    1088                 :             :     }
    1089                 :             : 
    1090                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
    1091                 :      214706 :     void ExpandPrivate(int pos, const SigningProvider& provider, FlatSigningProvider& out) const final
    1092                 :             :     {
    1093         [ +  + ]:      869658 :         for (const auto& p : m_pubkey_args) {
    1094                 :      654952 :             p->GetPrivKey(pos, provider, out);
    1095                 :             :         }
    1096         [ +  + ]:      289073 :         for (const auto& arg : m_subdescriptor_args) {
    1097                 :       74367 :             arg->ExpandPrivate(pos, provider, out);
    1098                 :             :         }
    1099                 :      214706 :     }
    1100                 :             : 
    1101                 :        9563 :     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                 :        2158 :     std::optional<int64_t> MaxSatisfactionWeight(bool) const override { return {}; }
    1113                 :             : 
    1114                 :        1079 :     std::optional<int64_t> MaxSatisfactionElems() const override { return {}; }
    1115                 :             : 
    1116                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
    1117                 :           0 :     void GetPubKeys(std::set<CPubKey>& pubkeys, std::set<CExtPubKey>& ext_pubs) const override
    1118                 :             :     {
    1119         [ #  # ]:           0 :         for (const auto& p : m_pubkey_args) {
    1120                 :           0 :             std::optional<CPubKey> pub = p->GetRootPubKey();
    1121         [ #  # ]:           0 :             if (pub) pubkeys.insert(*pub);
    1122                 :           0 :             std::optional<CExtPubKey> ext_pub = p->GetRootExtPubKey();
    1123   [ #  #  #  # ]:           0 :             if (ext_pub) ext_pubs.insert(*ext_pub);
    1124                 :           0 :         }
    1125         [ #  # ]:           0 :         for (const auto& arg : m_subdescriptor_args) {
    1126                 :           0 :             arg->GetPubKeys(pubkeys, ext_pubs);
    1127                 :             :         }
    1128                 :           0 :     }
    1129                 :             : 
    1130                 :             :     virtual std::unique_ptr<DescriptorImpl> Clone() const = 0;
    1131                 :             : 
    1132                 :        6114 :     bool HasScripts() const override { return true; }
    1133                 :             : 
    1134                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
    1135                 :           0 :     std::vector<std::string> Warnings() const override {
    1136                 :           0 :         std::vector<std::string> all = m_warnings;
    1137         [ #  # ]:           0 :         for (const auto& sub : m_subdescriptor_args) {
    1138         [ #  # ]:           0 :             auto sub_w = sub->Warnings();
    1139         [ #  # ]:           0 :             all.insert(all.end(), sub_w.begin(), sub_w.end());
    1140                 :           0 :         }
    1141                 :           0 :         return all;
    1142                 :           0 :     }
    1143                 :             : 
    1144                 :       31224 :     uint32_t GetMaxKeyExpr() const final
    1145                 :             :     {
    1146                 :       31224 :         uint32_t max_key_expr{0};
    1147                 :       31224 :         std::vector<const DescriptorImpl*> todo = {this};
    1148         [ +  + ]:      101525 :         while (!todo.empty()) {
    1149                 :       70301 :             const DescriptorImpl* desc = todo.back();
    1150                 :       70301 :             todo.pop_back();
    1151         [ +  + ]:      616142 :             for (const auto& p : desc->m_pubkey_args) {
    1152         [ +  + ]:      586994 :                 max_key_expr = std::max(max_key_expr, p->m_expr_index);
    1153                 :             :             }
    1154         [ +  + ]:      109378 :             for (const auto& s : desc->m_subdescriptor_args) {
    1155         [ +  - ]:       39077 :                 todo.push_back(s.get());
    1156                 :             :             }
    1157                 :             :         }
    1158                 :       31224 :         return max_key_expr;
    1159                 :       31224 :     }
    1160                 :             : 
    1161                 :       31224 :     size_t GetKeyCount() const final
    1162                 :             :     {
    1163                 :       31224 :         size_t count{0};
    1164                 :       31224 :         std::vector<const DescriptorImpl*> todo = {this};
    1165         [ +  + ]:      101525 :         while (!todo.empty()) {
    1166                 :       70301 :             const DescriptorImpl* desc = todo.back();
    1167                 :       70301 :             todo.pop_back();
    1168         [ +  + ]:      616142 :             for (const auto& p : desc->m_pubkey_args) {
    1169         [ +  - ]:      545841 :                 count += p->GetKeyCount();
    1170                 :             :             }
    1171         [ +  + ]:      109378 :             for (const auto& s : desc->m_subdescriptor_args) {
    1172         [ +  - ]:       39077 :                 todo.push_back(s.get());
    1173                 :             :             }
    1174                 :             :         }
    1175                 :       31224 :         return count;
    1176                 :       31224 :     }
    1177                 :             : 
    1178                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
    1179                 :        2545 :     bool CanSelfExpand() const override
    1180                 :             :     {
    1181         [ +  + ]:        5246 :         for (const auto& key : m_pubkey_args) {
    1182         [ +  - ]:        2701 :             if (!key->CanSelfExpand()) return false;
    1183                 :             :         }
    1184         [ +  + ]:        3726 :         for (const auto& sub : m_subdescriptor_args) {
    1185         [ +  - ]:        1181 :             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                 :      316024 :     std::string ToStringExtra() const override { return EncodeDestination(m_destination); }
    1197         [ +  - ]:        6364 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, std::span<const CScript>, FlatSigningProvider&) const override { return Vector(GetScriptForDestination(m_destination)); }
    1198                 :             : public:
    1199         [ +  - ]:      321175 :     AddressDescriptor(CTxDestination destination) : DescriptorImpl({}, "addr"), m_destination(std::move(destination)) {}
    1200                 :        4881 :     bool IsSolvable() const final { return false; }
    1201                 :             : 
    1202                 :           0 :     std::optional<OutputType> GetOutputType() const override
    1203                 :             :     {
    1204                 :           0 :         return OutputTypeFromDestination(m_destination);
    1205                 :             :     }
    1206                 :           0 :     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         [ +  + ]:     2166834 :     std::string ToStringExtra() const override { return HexStr(m_script); }
    1222                 :        5116 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, std::span<const CScript>, FlatSigningProvider&) const override { return Vector(m_script); }
    1223                 :             : public:
    1224         [ +  - ]:     1077575 :     RawDescriptor(CScript script) : DescriptorImpl({}, "raw"), m_script(std::move(script)) {}
    1225                 :         269 :     bool IsSolvable() const final { return false; }
    1226                 :             : 
    1227                 :        2556 :     std::optional<OutputType> GetOutputType() const override
    1228                 :             :     {
    1229                 :        2556 :         CTxDestination dest;
    1230         [ +  - ]:        2556 :         ExtractDestination(m_script, dest);
    1231         [ +  - ]:        2556 :         return OutputTypeFromDestination(dest);
    1232                 :        2556 :     }
    1233                 :        8635 :     bool IsSingleType() const final { return true; }
    1234                 :         452 :     bool ToPrivateString(const SigningProvider& arg, std::string& out) const final { return false; }
    1235                 :             : 
    1236         [ +  + ]:         266 :     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                 :       28363 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override
    1251                 :             :     {
    1252         [ +  + ]:       28363 :         if (m_xonly) {
    1253   [ +  -  +  - ]:       40714 :             CScript script = CScript() << ToByteVector(XOnlyPubKey(keys[0])) << OP_CHECKSIG;
    1254         [ +  - ]:       20357 :             return Vector(std::move(script));
    1255                 :       20357 :         } else {
    1256         [ +  - ]:       16012 :             return Vector(GetScriptForRawPubKey(keys[0]));
    1257                 :             :         }
    1258                 :             :     }
    1259                 :             : public:
    1260   [ +  -  +  - ]:       40297 :     PKDescriptor(std::unique_ptr<PubkeyProvider> prov, bool xonly = false) : DescriptorImpl(Vector(std::move(prov)), "pk"), m_xonly(xonly) {}
    1261                 :        5048 :     bool IsSingleType() const final { return true; }
    1262                 :             : 
    1263                 :        1559 :     std::optional<int64_t> ScriptSize() const override {
    1264         [ +  - ]:        1559 :         return 1 + (m_xonly ? 32 : m_pubkey_args[0]->GetSize()) + 1;
    1265                 :             :     }
    1266                 :             : 
    1267                 :        1798 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
    1268         [ +  + ]:        1574 :         const auto ecdsa_sig_size = use_max_sig ? 72 : 71;
    1269   [ +  -  +  - ]:        1798 :         return 1 + (m_xonly ? 65 : ecdsa_sig_size);
    1270                 :             :     }
    1271                 :             : 
    1272                 :         448 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
    1273         [ +  + ]:         448 :         return *MaxSatSize(use_max_sig) * WITNESS_SCALE_FACTOR;
    1274                 :             :     }
    1275                 :             : 
    1276                 :         899 :     std::optional<int64_t> MaxSatisfactionElems() const override { return 1; }
    1277                 :             : 
    1278                 :        1287 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1279                 :             :     {
    1280   [ +  -  -  + ]:        1287 :         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                 :        7927 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override
    1289                 :             :     {
    1290                 :        7927 :         CKeyID id = keys[0].GetID();
    1291   [ +  -  +  - ]:       15854 :         return Vector(GetScriptForDestination(PKHash(id)));
    1292                 :             :     }
    1293                 :             : public:
    1294   [ +  -  +  - ]:       17397 :     PKHDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "pkh") {}
    1295                 :       16360 :     std::optional<OutputType> GetOutputType() const override { return OutputType::LEGACY; }
    1296                 :        9394 :     bool IsSingleType() const final { return true; }
    1297                 :             : 
    1298                 :        1264 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 1 + 20 + 1 + 1; }
    1299                 :             : 
    1300                 :       13631 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
    1301         [ +  + ]:       13631 :         const auto sig_size = use_max_sig ? 72 : 71;
    1302                 :       13631 :         return 1 + sig_size + 1 + m_pubkey_args[0]->GetSize();
    1303                 :             :     }
    1304                 :             : 
    1305                 :       12601 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
    1306                 :       12601 :         return *MaxSatSize(use_max_sig) * WITNESS_SCALE_FACTOR;
    1307                 :             :     }
    1308                 :             : 
    1309                 :       12880 :     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                 :        2094 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override
    1322                 :             :     {
    1323                 :        2094 :         CKeyID id = keys[0].GetID();
    1324   [ +  -  +  - ]:        4188 :         return Vector(GetScriptForDestination(WitnessV0KeyHash(id)));
    1325                 :             :     }
    1326                 :             : public:
    1327   [ +  -  +  - ]:      121876 :     WPKHDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "wpkh") {}
    1328                 :      221657 :     std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32; }
    1329                 :        2534 :     bool IsSingleType() const final { return true; }
    1330                 :             : 
    1331                 :      100152 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 20; }
    1332                 :             : 
    1333                 :      120390 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
    1334         [ +  + ]:      120191 :         const auto sig_size = use_max_sig ? 72 : 71;
    1335                 :      120390 :         return (1 + sig_size + 1 + 33);
    1336                 :             :     }
    1337                 :             : 
    1338                 :       20435 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
    1339         [ +  + ]:       20435 :         return MaxSatSize(use_max_sig);
    1340                 :             :     }
    1341                 :             : 
    1342                 :      120023 :     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                 :       10750 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider& out) const override
    1355                 :             :     {
    1356                 :       10750 :         std::vector<CScript> ret;
    1357         [ +  - ]:       10750 :         CKeyID id = keys[0].GetID();
    1358   [ +  -  +  - ]:       10750 :         ret.emplace_back(GetScriptForRawPubKey(keys[0])); // P2PK
    1359   [ +  -  +  -  :       21500 :         ret.emplace_back(GetScriptForDestination(PKHash(id))); // P2PKH
                   +  - ]
    1360         [ +  + ]:       10750 :         if (keys[0].IsCompressed()) {
    1361         [ +  - ]:       10057 :             CScript p2wpkh = GetScriptForDestination(WitnessV0KeyHash(id));
    1362   [ +  -  +  - ]:       10057 :             out.scripts.emplace(CScriptID(p2wpkh), p2wpkh);
    1363         [ +  - ]:       10057 :             ret.emplace_back(p2wpkh);
    1364   [ +  -  +  -  :       20114 :             ret.emplace_back(GetScriptForDestination(ScriptHash(p2wpkh))); // P2SH-P2WPKH
                   +  - ]
    1365                 :       10057 :         }
    1366                 :       10750 :         return ret;
    1367                 :           0 :     }
    1368                 :             : public:
    1369   [ +  -  +  - ]:       10681 :     ComboDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "combo") {}
    1370                 :       22381 :     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                 :       67200 :     std::string ToStringExtra() const override { return strprintf("%i", m_threshold); }
    1384                 :       18428 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override {
    1385         [ +  + ]:       18428 :         if (m_sorted) {
    1386                 :        3200 :             std::vector<CPubKey> sorted_keys(keys);
    1387                 :        3200 :             std::sort(sorted_keys.begin(), sorted_keys.end());
    1388   [ +  -  +  - ]:        6400 :             return Vector(GetScriptForMultisig(m_threshold, sorted_keys));
    1389                 :        3200 :         }
    1390         [ +  - ]:       30456 :         return Vector(GetScriptForMultisig(m_threshold, keys));
    1391                 :             :     }
    1392                 :             : public:
    1393   [ +  +  +  - ]:      112685 :     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                 :        1548 :     bool IsSingleType() const final { return true; }
    1395                 :             : 
    1396                 :        3175 :     std::optional<int64_t> ScriptSize() const override {
    1397         [ -  + ]:        3175 :         const auto n_keys = m_pubkey_args.size();
    1398                 :       25151 :         auto op = [](int64_t acc, const std::unique_ptr<PubkeyProvider>& pk) { return acc + 1 + pk->GetSize();};
    1399                 :        3175 :         const auto pubkeys_size{std::accumulate(m_pubkey_args.begin(), m_pubkey_args.end(), int64_t{0}, op)};
    1400   [ -  +  +  - ]:        6350 :         return 1 + BuildScript(n_keys).size() + BuildScript(m_threshold).size() + pubkeys_size;
    1401                 :             :     }
    1402                 :             : 
    1403                 :        3338 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
    1404         [ +  + ]:        3178 :         const auto sig_size = use_max_sig ? 72 : 71;
    1405                 :        3338 :         return (1 + (1 + sig_size) * m_threshold);
    1406                 :             :     }
    1407                 :             : 
    1408                 :         320 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
    1409         [ +  + ]:         320 :         return *MaxSatSize(use_max_sig) * WITNESS_SCALE_FACTOR;
    1410                 :             :     }
    1411                 :             : 
    1412                 :        1669 :     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                 :       26062 :     std::string ToStringExtra() const override { return strprintf("%i", m_threshold); }
    1430                 :       20191 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override {
    1431                 :       20191 :         CScript ret;
    1432                 :       20191 :         std::vector<XOnlyPubKey> xkeys;
    1433   [ -  +  +  - ]:       20191 :         xkeys.reserve(keys.size());
    1434   [ +  -  +  + ]:     2093784 :         for (const auto& key : keys) xkeys.emplace_back(key);
    1435         [ +  + ]:       20191 :         if (m_sorted) std::sort(xkeys.begin(), xkeys.end());
    1436   [ +  -  +  - ]:       40382 :         ret << ToByteVector(xkeys[0]) << OP_CHECKSIG;
    1437   [ -  +  +  + ]:     2073593 :         for (size_t i = 1; i < keys.size(); ++i) {
    1438   [ +  -  +  - ]:     6160206 :             ret << ToByteVector(xkeys[i]) << OP_CHECKSIGADD;
    1439                 :             :         }
    1440   [ +  -  +  - ]:       20191 :         ret << m_threshold << OP_NUMEQUAL;
    1441         [ +  - ]:       20191 :         return Vector(std::move(ret));
    1442                 :       20191 :     }
    1443                 :             : public:
    1444   [ +  +  +  - ]:       22382 :     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                 :         633 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1459                 :             :     {
    1460                 :         633 :         std::vector<std::unique_ptr<PubkeyProvider>> providers;
    1461   [ -  +  +  - ]:         633 :         providers.reserve(m_pubkey_args.size());
    1462         [ +  + ]:        2880 :         for (const auto& arg : m_pubkey_args) {
    1463         [ +  - ]:        4494 :             providers.push_back(arg->Clone());
    1464                 :             :         }
    1465   [ +  -  -  + ]:        1266 :         return std::make_unique<MultiADescriptor>(m_threshold, std::move(providers), m_sorted);
    1466                 :         633 :     }
    1467                 :             : };
    1468                 :             : 
    1469                 :             : /** A parsed sh(...) descriptor. */
    1470                 :             : class SHDescriptor final : public DescriptorImpl
    1471                 :             : {
    1472                 :             : protected:
    1473                 :       22028 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, std::span<const CScript> scripts, FlatSigningProvider& out) const override
    1474                 :             :     {
    1475   [ +  -  +  - ]:       44056 :         auto ret = Vector(GetScriptForDestination(ScriptHash(scripts[0])));
    1476   [ -  +  +  -  :       22028 :         if (ret.size()) out.scripts.emplace(CScriptID(scripts[0]), scripts[0]);
             +  -  +  - ]
    1477                 :       22028 :         return ret;
    1478                 :           0 :     }
    1479                 :             : 
    1480         [ +  + ]:      214054 :     bool IsSegwit() const { return m_subdescriptor_args[0]->GetOutputType() == OutputType::BECH32; }
    1481                 :             : 
    1482                 :             : public:
    1483         [ +  - ]:      123654 :     SHDescriptor(std::unique_ptr<DescriptorImpl> desc) : DescriptorImpl({}, std::move(desc), "sh") {}
    1484                 :             : 
    1485                 :      109201 :     std::optional<OutputType> GetOutputType() const override
    1486                 :             :     {
    1487   [ -  +  -  + ]:      109201 :         assert(m_subdescriptor_args.size() == 1);
    1488         [ +  + ]:      109201 :         if (IsSegwit()) return OutputType::P2SH_SEGWIT;
    1489                 :        5277 :         return OutputType::LEGACY;
    1490                 :             :     }
    1491                 :       31355 :     bool IsSingleType() const final { return true; }
    1492                 :             : 
    1493                 :        2537 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 20 + 1; }
    1494                 :             : 
    1495                 :      104853 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
    1496         [ +  - ]:      104853 :         if (const auto sat_size = m_subdescriptor_args[0]->MaxSatSize(use_max_sig)) {
    1497         [ +  - ]:      104853 :             if (const auto subscript_size = m_subdescriptor_args[0]->ScriptSize()) {
    1498                 :             :                 // The subscript is never witness data.
    1499                 :      104853 :                 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         [ +  + ]:      104853 :                 if (IsSegwit()) return subscript_weight + *sat_size;
    1502                 :        2364 :                 return subscript_weight + *sat_size * WITNESS_SCALE_FACTOR;
    1503                 :             :             }
    1504                 :             :         }
    1505                 :           0 :         return {};
    1506                 :             :     }
    1507                 :             : 
    1508                 :      102236 :     std::optional<int64_t> MaxSatisfactionElems() const override {
    1509         [ +  - ]:      102236 :         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                 :       20163 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, std::span<const CScript> scripts, FlatSigningProvider& out) const override
    1524                 :             :     {
    1525   [ +  -  +  - ]:       40326 :         auto ret = Vector(GetScriptForDestination(WitnessV0ScriptHash(scripts[0])));
    1526   [ -  +  +  -  :       20163 :         if (ret.size()) out.scripts.emplace(CScriptID(scripts[0]), scripts[0]);
             +  -  +  - ]
    1527                 :       20163 :         return ret;
    1528                 :           0 :     }
    1529                 :             : public:
    1530         [ +  - ]:       27735 :     WSHDescriptor(std::unique_ptr<DescriptorImpl> desc) : DescriptorImpl({}, std::move(desc), "wsh") {}
    1531                 :       20616 :     std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32; }
    1532                 :       23962 :     bool IsSingleType() const final { return true; }
    1533                 :             : 
    1534                 :        8144 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
    1535                 :             : 
    1536                 :       14246 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
    1537         [ +  - ]:       14246 :         if (const auto sat_size = m_subdescriptor_args[0]->MaxSatSize(use_max_sig)) {
    1538         [ +  - ]:       14246 :             if (const auto subscript_size = m_subdescriptor_args[0]->ScriptSize()) {
    1539         [ +  + ]:       16856 :                 return GetSizeOfCompactSize(*subscript_size) + *subscript_size + *sat_size;
    1540                 :             :             }
    1541                 :             :         }
    1542                 :           0 :         return {};
    1543                 :             :     }
    1544                 :             : 
    1545                 :       11712 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
    1546                 :       11712 :         return MaxSatSize(use_max_sig);
    1547                 :             :     }
    1548                 :             : 
    1549                 :        7123 :     std::optional<int64_t> MaxSatisfactionElems() const override {
    1550         [ +  - ]:        7123 :         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                 :       65452 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript> scripts, FlatSigningProvider& out) const override
    1566                 :             :     {
    1567         [ -  + ]:       65452 :         TaprootBuilder builder;
    1568   [ -  +  -  + ]:       65452 :         assert(m_depths.size() == scripts.size());
    1569   [ -  +  +  + ]:      144355 :         for (size_t pos = 0; pos < m_depths.size(); ++pos) {
    1570   [ +  +  +  - ]:      157806 :             builder.Add(m_depths[pos], scripts[pos], TAPROOT_LEAF_TAPSCRIPT);
    1571                 :             :         }
    1572         [ -  + ]:       65452 :         if (!builder.IsComplete()) return {};
    1573   [ -  +  -  + ]:       65452 :         assert(keys.size() == 1);
    1574                 :       65452 :         XOnlyPubKey xpk(keys[0]);
    1575   [ +  -  -  + ]:       65452 :         if (!xpk.IsFullyValid()) return {};
    1576         [ +  - ]:       65452 :         builder.Finalize(xpk);
    1577         [ +  - ]:       65452 :         WitnessV1Taproot output = builder.GetOutput();
    1578   [ +  -  +  - ]:       65452 :         out.tr_trees[output] = builder;
    1579   [ +  -  +  - ]:      130904 :         return Vector(GetScriptForDestination(output));
    1580                 :       65452 :     }
    1581                 :       84356 :     bool ToStringSubScriptHelper(const SigningProvider* arg, std::string& ret, const StringType type, const DescriptorCache* cache = nullptr) const override
    1582                 :             :     {
    1583         [ +  + ]:       84356 :         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                 :       39194 :             return type != StringType::PRIVATE;
    1590                 :             :         }
    1591                 :       45162 :         std::vector<bool> path;
    1592                 :       45162 :         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                 :       45162 :         bool any_success{!is_private};
    1596                 :             : 
    1597   [ -  +  +  + ]:      153415 :         for (size_t pos = 0; pos < m_depths.size(); ++pos) {
    1598   [ +  +  +  - ]:      108732 :             if (pos) ret += ',';
    1599         [ +  + ]:      217495 :             while ((int)path.size() <= m_depths[pos]) {
    1600   [ +  +  +  - ]:      108763 :                 if (path.size()) ret += '{';
    1601         [ +  - ]:      108763 :                 path.push_back(false);
    1602                 :             :             }
    1603         [ +  - ]:      108732 :             std::string tmp;
    1604         [ +  - ]:      108732 :             bool subscript_res{m_subdescriptor_args[pos]->ToStringHelper(arg, tmp, type, cache)};
    1605         [ +  + ]:      108732 :             if (!is_private && !subscript_res) return false;
    1606                 :      108253 :             any_success = any_success || subscript_res;
    1607         [ -  + ]:      108253 :             ret += tmp;
    1608   [ +  -  +  + ]:      170290 :             while (!path.empty() && path.back()) {
    1609   [ +  -  +  - ]:       62037 :                 if (path.size() > 1) ret += '}';
    1610   [ -  +  +  - ]:      232327 :                 path.pop_back();
    1611                 :             :             }
    1612         [ +  - ]:      108253 :             if (!path.empty()) path.back() = true;
    1613                 :      108732 :         }
    1614                 :             :         return any_success;
    1615                 :       45162 :     }
    1616                 :             : public:
    1617                 :      303767 :     TRDescriptor(std::unique_ptr<PubkeyProvider> internal_key, std::vector<std::unique_ptr<DescriptorImpl>> descs, std::vector<int> depths) :
    1618   [ +  -  +  -  :      303767 :         DescriptorImpl(Vector(std::move(internal_key)), std::move(descs), "tr"), m_depths(std::move(depths))
                   -  + ]
    1619                 :             :     {
    1620   [ -  +  -  +  :      303767 :         assert(m_subdescriptor_args.size() == m_depths.size());
                   -  + ]
    1621                 :      303767 :     }
    1622                 :      317609 :     std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32M; }
    1623                 :      102304 :     bool IsSingleType() const final { return true; }
    1624                 :             : 
    1625                 :       19505 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
    1626                 :             : 
    1627                 :      300499 :     std::optional<int64_t> MaxSatisfactionWeight(bool) const override {
    1628                 :             :         // FIXME: We assume keypath spend, which can lead to very large underestimations.
    1629                 :      300499 :         return 1 + 65;
    1630                 :             :     }
    1631                 :             : 
    1632                 :      280074 :     std::optional<int64_t> MaxSatisfactionElems() const override {
    1633                 :             :         // FIXME: See above, we assume keypath spend.
    1634                 :      280074 :         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                 :       12293 :     uint160 GetHash160(uint32_t key) const {
    1664         [ +  + ]:       12293 :         if (miniscript::IsTapscript(m_script_ctx)) {
    1665                 :        9583 :             return Hash160(XOnlyPubKey{m_keys[key]});
    1666                 :             :         }
    1667                 :        2710 :         return m_keys[key].GetID();
    1668                 :             :     }
    1669                 :             : 
    1670                 :             : public:
    1671                 :       60569 :     ScriptMaker(const std::vector<CPubKey>& keys LIFETIMEBOUND, const miniscript::MiniscriptContext script_ctx) : m_keys(keys), m_script_ctx{script_ctx} {}
    1672                 :             : 
    1673                 :      111117 :     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         [ +  + ]:      111117 :         if (!miniscript::IsTapscript(m_script_ctx)) {
    1676                 :       46058 :             return {m_keys[key].begin(), m_keys[key].end()};
    1677                 :             :         }
    1678                 :       65059 :         const XOnlyPubKey xonly_pubkey{m_keys[key]};
    1679                 :       65059 :         return {xonly_pubkey.begin(), xonly_pubkey.end()};
    1680                 :             :     }
    1681                 :             : 
    1682                 :       12293 :     std::vector<unsigned char> ToPKHBytes(uint32_t key) const {
    1683                 :       12293 :         auto id = GetHash160(key);
    1684                 :       12293 :         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                 :       85786 :     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                 :       85786 :         : m_arg(arg), m_pubkeys(pubkeys), m_type(type), m_cache(cache) {}
    1706                 :             : 
    1707                 :      246508 :     std::optional<std::string> ToString(uint32_t key, bool& has_priv_key) const
    1708                 :             :     {
    1709   [ +  +  +  +  :      246508 :         std::string ret;
                   +  - ]
    1710                 :      246508 :         has_priv_key = false;
    1711   [ +  +  +  +  :      246508 :         switch (m_type) {
                   +  - ]
    1712                 :      101083 :         case DescriptorImpl::StringType::PUBLIC:
    1713         [ +  - ]:      101083 :             ret = m_pubkeys[key]->ToString(PubkeyProvider::StringType::PUBLIC);
    1714                 :      101083 :             break;
    1715                 :       71342 :         case DescriptorImpl::StringType::PRIVATE:
    1716         [ +  - ]:       71342 :             has_priv_key = m_pubkeys[key]->ToPrivateString(*m_arg, ret);
    1717                 :       71342 :             break;
    1718                 :       70550 :         case DescriptorImpl::StringType::NORMALIZED:
    1719   [ +  -  +  + ]:       70550 :             if (!m_pubkeys[key]->ToNormalizedString(*m_arg, ret, m_cache)) return {};
    1720                 :             :             break;
    1721                 :        2675 :         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         [ +  - ]:        2675 :             ret = m_pubkeys[key]->ToString(PubkeyProvider::StringType::PUBLIC);
    1727                 :        2675 :             break;
    1728                 :         858 :         case DescriptorImpl::StringType::CANONICAL:
    1729         [ +  - ]:         858 :             ret = m_pubkeys[key]->ToString(PubkeyProvider::StringType::CANONICAL);
    1730                 :         858 :             break;
    1731                 :             :         }
    1732                 :      246051 :         return ret;
    1733                 :      246508 :     }
    1734                 :             : };
    1735                 :             : 
    1736                 :             : class MiniscriptDescriptor final : public DescriptorImpl
    1737                 :             : {
    1738                 :             : private:
    1739                 :             :     miniscript::Node<uint32_t> m_node;
    1740                 :             : 
    1741                 :             : protected:
    1742                 :       60569 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript> scripts,
    1743                 :             :                                      FlatSigningProvider& provider) const override
    1744                 :             :     {
    1745                 :       60569 :         const auto script_ctx{m_node.GetMsCtx()};
    1746         [ +  + ]:      183979 :         for (const auto& key : keys) {
    1747         [ +  + ]:      123410 :             if (miniscript::IsTapscript(script_ctx)) {
    1748                 :       74642 :                 provider.pubkeys.emplace(Hash160(XOnlyPubKey{key}), key);
    1749                 :             :             } else {
    1750                 :       48768 :                 provider.pubkeys.emplace(key.GetID(), key);
    1751                 :             :             }
    1752                 :             :         }
    1753         [ +  - ]:      121138 :         return Vector(m_node.ToScript(ScriptMaker(keys, script_ctx)));
    1754                 :             :     }
    1755                 :             : 
    1756                 :             : public:
    1757                 :       58686 :     MiniscriptDescriptor(std::vector<std::unique_ptr<PubkeyProvider>> providers, miniscript::Node<uint32_t>&& node)
    1758         [ +  - ]:       58686 :         : DescriptorImpl(std::move(providers), "?"), m_node(std::move(node))
    1759                 :             :     {
    1760                 :             :         // Traverse miniscript tree for unsafe use of older()
    1761         [ +  - ]:       58686 :         miniscript::ForEachNode(m_node, [&](const miniscript::Node<uint32_t>& node) {
    1762         [ +  + ]:     2156799 :             if (node.Fragment() == miniscript::Fragment::OLDER) {
    1763         [ +  + ]:        2916 :                 const uint32_t raw = node.K();
    1764                 :        2916 :                 const uint32_t value_part = raw & ~CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG;
    1765         [ +  + ]:        2916 :                 if (value_part > CTxIn::SEQUENCE_LOCKTIME_MASK) {
    1766                 :        1926 :                     const bool is_time_based = (raw & CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) != 0;
    1767         [ +  + ]:        1926 :                     if (is_time_based) {
    1768         [ +  - ]:         938 :                         m_warnings.push_back(strprintf("time-based relative locktime: older(%u) > (65535 * 512) seconds is unsafe", raw));
    1769                 :             :                     } else {
    1770         [ +  - ]:         988 :                         m_warnings.push_back(strprintf("height-based relative locktime: older(%u) > 65535 blocks is unsafe", raw));
    1771                 :             :                     }
    1772                 :             :                 }
    1773                 :             :             }
    1774                 :     2156799 :         });
    1775                 :       58686 :     }
    1776                 :             : 
    1777                 :       85786 :     bool ToStringHelper(const SigningProvider* arg, std::string& out, const StringType type,
    1778                 :             :                         const DescriptorCache* cache = nullptr) const override
    1779                 :             :     {
    1780                 :       85786 :         bool has_priv_key{false};
    1781                 :       85786 :         auto res = m_node.ToString(StringMaker(arg, m_pubkey_args, type, cache), has_priv_key);
    1782   [ +  +  +  - ]:       85786 :         if (res) out = *res;
    1783         [ +  + ]:       85786 :         if (type == StringType::PRIVATE) {
    1784         [ +  - ]:       25190 :             Assume(res.has_value());
    1785                 :       25190 :             return has_priv_key;
    1786                 :             :         } else {
    1787                 :       60596 :             return res.has_value();
    1788                 :             :         }
    1789                 :       85786 :     }
    1790                 :             : 
    1791                 :       25086 :     bool IsSolvable() const override { return true; }
    1792                 :           0 :     bool IsSingleType() const final { return true; }
    1793                 :             : 
    1794                 :       11212 :     std::optional<int64_t> ScriptSize() const override { return m_node.ScriptSize(); }
    1795                 :             : 
    1796                 :       11212 :     std::optional<int64_t> MaxSatSize(bool) const override
    1797                 :             :     {
    1798                 :             :         // For Miniscript we always assume high-R ECDSA signatures.
    1799   [ -  +  +  - ]:       22424 :         return m_node.GetWitnessSize();
    1800                 :             :     }
    1801                 :             : 
    1802                 :        5606 :     std::optional<int64_t> MaxSatisfactionElems() const override
    1803                 :             :     {
    1804         [ +  - ]:        5606 :         return m_node.GetStackSize();
    1805                 :             :     }
    1806                 :             : 
    1807                 :       12653 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1808                 :             :     {
    1809                 :       12653 :         std::vector<std::unique_ptr<PubkeyProvider>> providers;
    1810   [ -  +  +  - ]:       12653 :         providers.reserve(m_pubkey_args.size());
    1811         [ +  + ]:       26218 :         for (const auto& arg : m_pubkey_args) {
    1812         [ +  - ]:       27130 :             providers.push_back(arg->Clone());
    1813                 :             :         }
    1814   [ +  -  +  -  :       25306 :         return std::make_unique<MiniscriptDescriptor>(std::move(providers), m_node.Clone());
                   -  + ]
    1815                 :       12653 :     }
    1816                 :             : };
    1817                 :             : 
    1818                 :             : /** A parsed rawtr(...) descriptor. */
    1819                 :             : class RawTRDescriptor final : public DescriptorImpl
    1820                 :             : {
    1821                 :             : protected:
    1822                 :        1737 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript> scripts, FlatSigningProvider& out) const override
    1823                 :             :     {
    1824   [ -  +  -  + ]:        1737 :         assert(keys.size() == 1);
    1825                 :        1737 :         XOnlyPubKey xpk(keys[0]);
    1826         [ -  + ]:        1737 :         if (!xpk.IsFullyValid()) return {};
    1827         [ +  - ]:        1737 :         WitnessV1Taproot output{xpk};
    1828   [ +  -  +  - ]:        3474 :         return Vector(GetScriptForDestination(output));
    1829                 :             :     }
    1830                 :             : public:
    1831   [ +  -  +  - ]:        9164 :     RawTRDescriptor(std::unique_ptr<PubkeyProvider> output_key) : DescriptorImpl(Vector(std::move(output_key)), "rawtr") {}
    1832                 :        1297 :     std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32M; }
    1833                 :        2614 :     bool IsSingleType() const final { return true; }
    1834                 :             : 
    1835                 :         426 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
    1836                 :             : 
    1837                 :         856 :     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                 :         856 :         return 1 + 65;
    1840                 :             :     }
    1841                 :             : 
    1842                 :         428 :     std::optional<int64_t> MaxSatisfactionElems() const override {
    1843                 :             :         // See above, we assume keypath spend.
    1844                 :         428 :         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                 :         359 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript> scripts, FlatSigningProvider& out) const override { return {}; }
    1858                 :             : public:
    1859   [ +  -  +  - ]:         275 :     UnusedDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "unused") {}
    1860                 :         268 :     bool IsSingleType() const final { return true; }
    1861                 :          34 :     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                 :      248855 : [[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                 :      583869 :     auto parse_elem = [&](std::span<const char> elem) -> std::optional<uint32_t> {
    1897                 :      335014 :         const auto parsed{ParseKeyPathElement(elem)};
    1898         [ +  + ]:      335014 :         if (!parsed) {
    1899         [ +  - ]:         147 :             error = parsed.error();
    1900                 :         147 :             return std::nullopt;
    1901                 :             :         }
    1902         [ +  + ]:      334867 :         if (parsed->is_hardened) {
    1903                 :       56419 :             has_hardened = true;
    1904                 :       56419 :             apostrophe = elem.back() == '\'';
    1905                 :             :         }
    1906         [ +  + ]:      613315 :         return parsed->ChildNumber();
    1907                 :      335014 :     };
    1908                 :             : 
    1909                 :      248855 :     KeyPath path;
    1910                 :       11974 :     struct MultipathSubstitutes {
    1911                 :             :         size_t placeholder_index;
    1912                 :             :         std::vector<uint32_t> values;
    1913                 :             :     };
    1914                 :      248855 :     std::optional<MultipathSubstitutes> substitutes;
    1915                 :      248855 :     has_hardened = false;
    1916                 :             : 
    1917   [ -  +  +  + ]:      490875 :     for (size_t i = 1; i < split.size(); ++i) {
    1918         [ +  + ]:      242249 :         const std::span<const char>& elem = split[i];
    1919                 :             : 
    1920                 :             :         // Check if element contains multipath specifier
    1921   [ +  +  +  +  :      242249 :         if (!elem.empty() && elem.front() == '<' && elem.back() == '>') {
                   +  + ]
    1922         [ +  + ]:       12041 :             if (!allow_multipath) {
    1923   [ +  -  +  - ]:         112 :                 error = strprintf("Key path value '%s' specifies multipath in a section where multipath is not allowed", std::string(elem.begin(), elem.end()));
    1924                 :          56 :                 return false;
    1925                 :             :             }
    1926         [ +  + ]:       11985 :             if (substitutes) {
    1927         [ +  - ]:      248855 :                 error = "Multiple multipath key path specifiers found";
    1928                 :             :                 return false;
    1929                 :             :             }
    1930                 :             : 
    1931                 :             :             // Parse each possible value
    1932         [ +  - ]:       11981 :             std::vector<std::span<const char>> nums = Split(std::span(elem.begin()+1, elem.end()-1), ";");
    1933   [ -  +  +  + ]:       11981 :             if (nums.size() < 2) {
    1934         [ +  - ]:          44 :                 error = "Multipath key path specifiers must have at least two items";
    1935                 :             :                 return false;
    1936                 :             :             }
    1937                 :             : 
    1938                 :       11974 :             substitutes.emplace();
    1939                 :       11974 :             std::unordered_set<uint32_t> seen_substitutes;
    1940         [ +  + ]:      116743 :             for (const auto& num : nums) {
    1941         [ +  - ]:      104806 :                 const auto& op_num = parse_elem(num);
    1942         [ +  + ]:      104806 :                 if (!op_num) return false;
    1943   [ +  -  +  + ]:      104784 :                 auto [_, inserted] = seen_substitutes.insert(*op_num);
    1944         [ +  + ]:      104784 :                 if (!inserted) {
    1945         [ +  - ]:          15 :                     error = strprintf("Duplicated key path value %u in multipath specifier", *op_num);
    1946                 :          15 :                     return false;
    1947                 :             :                 }
    1948         [ +  - ]:      104769 :                 substitutes->values.emplace_back(*op_num);
    1949                 :             :             }
    1950                 :             : 
    1951         [ +  - ]:       11937 :             path.emplace_back(); // Placeholder for multipath segment
    1952         [ -  + ]:       11937 :             substitutes->placeholder_index = path.size() - 1;
    1953                 :       12018 :         } else {
    1954         [ +  - ]:      230208 :             const auto& op_num = parse_elem(elem);
    1955         [ +  + ]:      230208 :             if (!op_num) return false;
    1956         [ +  - ]:      230083 :             path.emplace_back(*op_num);
    1957                 :             :         }
    1958                 :             :     }
    1959                 :             : 
    1960         [ +  + ]:      248626 :     if (!substitutes) {
    1961         [ +  - ]:      236693 :         out.emplace_back(std::move(path));
    1962                 :             :     } else {
    1963                 :             :         // Replace the multipath placeholder with each value while generating paths
    1964         [ +  + ]:      116536 :         for (uint32_t substitute : substitutes->values) {
    1965         [ +  - ]:      104603 :             KeyPath branch_path = path;
    1966         [ +  - ]:      104603 :             branch_path[substitutes->placeholder_index] = substitute;
    1967         [ +  - ]:      104603 :             out.emplace_back(std::move(branch_path));
    1968                 :      104603 :         }
    1969                 :             :     }
    1970                 :             :     return true;
    1971                 :      248855 : }
    1972                 :             : 
    1973                 :      246766 : [[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                 :      246766 :     bool dummy;
    1976                 :      246766 :     return ParseKeyPath(split, out, apostrophe, error, allow_multipath, /*has_hardened=*/dummy);
    1977                 :             : }
    1978                 :             : 
    1979                 :      183570 : static DeriveType ParseDeriveType(std::vector<std::span<const char>>& split, bool& apostrophe)
    1980                 :             : {
    1981                 :      183570 :     DeriveType type = DeriveType::NON_RANGED;
    1982         [ +  + ]:      183570 :     if (std::ranges::equal(split.back(), std::span{"*"}.first(1))) {
    1983                 :        5876 :         split.pop_back();
    1984                 :        5876 :         type = DeriveType::UNHARDENED_RANGED;
    1985   [ +  +  +  + ]:      177694 :     } else if (std::ranges::equal(split.back(), std::span{"*'"}.first(2)) || std::ranges::equal(split.back(), std::span{"*h"}.first(2))) {
    1986                 :       11656 :         apostrophe = std::ranges::equal(split.back(), std::span{"*'"}.first(2));
    1987                 :       11656 :         split.pop_back();
    1988                 :       11656 :         type = DeriveType::HARDENED_RANGED;
    1989                 :             :     }
    1990                 :      183570 :     return type;
    1991                 :             : }
    1992                 :             : 
    1993                 :             : /** Parse a public key that excludes origin information. */
    1994                 :      501707 : 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                 :      501707 :     std::vector<std::unique_ptr<PubkeyProvider>> ret;
    1997                 :      501707 :     bool permit_uncompressed = ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH;
    1998         [ +  - ]:      501707 :     auto split = Split(sp, '/');
    1999         [ +  + ]:      501707 :     std::string_view str(split[0].data(), split[0].size());
    2000         [ +  + ]:      501707 :     if (str.size() == 0) {
    2001         [ +  - ]:          70 :         error = "No key provided";
    2002                 :          70 :         return {};
    2003                 :             :     }
    2004   [ +  +  +  + ]:      501637 :     if (IsSpace(str.front()) || IsSpace(str.back())) {
    2005         [ +  - ]:          15 :         error = strprintf("Key '%s' is invalid due to whitespace", str);
    2006                 :          15 :         return {};
    2007                 :             :     }
    2008   [ -  +  +  + ]:      501622 :     if (split.size() == 1) {
    2009   [ +  -  +  + ]:      374152 :         if (IsHex(str)) {
    2010         [ +  - ]:      245534 :             std::vector<unsigned char> data = ParseHex(str);
    2011         [ -  + ]:      245534 :             CPubKey pubkey(data);
    2012   [ +  +  +  + ]:      245534 :             if (pubkey.IsValid() && !pubkey.IsValidNonHybrid()) {
    2013         [ +  - ]:           9 :                 error = "Hybrid public keys are not allowed";
    2014                 :           9 :                 return {};
    2015                 :             :             }
    2016   [ +  -  +  + ]:      245525 :             if (pubkey.IsFullyValid()) {
    2017   [ +  +  +  + ]:      211899 :                 if (permit_uncompressed || pubkey.IsCompressed()) {
    2018   [ +  -  +  - ]:      211895 :                     ret.emplace_back(std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, false));
    2019                 :      211895 :                     ++key_exp_index;
    2020                 :      211895 :                     return ret;
    2021                 :             :                 } else {
    2022         [ +  - ]:           4 :                     error = "Uncompressed keys are not allowed";
    2023                 :           4 :                     return {};
    2024                 :             :                 }
    2025   [ -  +  +  +  :       33626 :             } else if (data.size() == 32 && ctx == ParseScriptContext::P2TR) {
                   +  + ]
    2026                 :       33477 :                 unsigned char fullkey[33] = {0x02};
    2027                 :       33477 :                 std::copy(data.begin(), data.end(), fullkey + 1);
    2028                 :       33477 :                 pubkey.Set(std::begin(fullkey), std::end(fullkey));
    2029   [ +  -  +  + ]:       33477 :                 if (pubkey.IsFullyValid()) {
    2030   [ +  -  +  - ]:       33465 :                     ret.emplace_back(std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, true));
    2031                 :       33465 :                     ++key_exp_index;
    2032                 :       33465 :                     return ret;
    2033                 :             :                 }
    2034                 :             :             }
    2035         [ +  - ]:         161 :             error = strprintf("Pubkey '%s' is invalid", str);
    2036                 :         161 :             return {};
    2037                 :      245534 :         }
    2038         [ +  - ]:      128618 :         CKey key = DecodeSecret(str);
    2039         [ +  + ]:      128618 :         if (key.IsValid()) {
    2040   [ +  +  -  + ]:       74299 :             if (permit_uncompressed || key.IsCompressed()) {
    2041         [ +  - ]:       74299 :                 CPubKey pubkey = key.GetPubKey();
    2042   [ +  -  +  - ]:       74299 :                 out.keys.emplace(pubkey.GetID(), key);
    2043   [ +  -  +  - ]:       74299 :                 ret.emplace_back(std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, ctx == ParseScriptContext::P2TR));
    2044                 :       74299 :                 ++key_exp_index;
    2045                 :       74299 :                 return ret;
    2046                 :             :             } else {
    2047         [ #  # ]:           0 :                 error = "Uncompressed keys are not allowed";
    2048                 :           0 :                 return {};
    2049                 :             :             }
    2050                 :             :         }
    2051                 :      128618 :     }
    2052   [ +  -  +  + ]:      181789 :     auto [extkey, extpubkey] = DecodeExtKeyOrPubKey(str);
    2053   [ +  +  +  + ]:      181789 :     if (!extkey.key.IsValid() && !extpubkey.pubkey.IsValid()) {
    2054         [ +  - ]:         313 :         error = strprintf("key '%s' is not valid", str);
    2055                 :         313 :         return {};
    2056                 :             :     }
    2057                 :      181476 :     std::vector<KeyPath> paths;
    2058                 :      181476 :     DeriveType type = ParseDeriveType(split, apostrophe);
    2059   [ +  -  +  + ]:      181476 :     if (!ParseKeyPath(split, paths, apostrophe, error, /*allow_multipath=*/true)) return {};
    2060         [ +  + ]:      181383 :     if (extkey.key.IsValid()) {
    2061         [ +  - ]:      140034 :         extpubkey = extkey.Neuter();
    2062   [ +  -  +  - ]:      140034 :         out.keys.emplace(extpubkey.pubkey.GetID(), extkey.key);
    2063                 :             :     }
    2064         [ +  + ]:      451428 :     for (auto& path : paths) {
    2065   [ +  -  +  - ]:      540090 :         ret.emplace_back(std::make_unique<BIP32PubkeyProvider>(key_exp_index, extpubkey, std::move(path), type, apostrophe));
    2066                 :             :     }
    2067                 :      181383 :     ++key_exp_index;
    2068                 :      181383 :     return ret;
    2069                 :      683496 : }
    2070                 :             : 
    2071                 :             : /** Parse a public key including origin information (if enabled). */
    2072                 :             : // NOLINTNEXTLINE(misc-no-recursion)
    2073                 :      522796 : 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                 :      522796 :     std::vector<std::unique_ptr<PubkeyProvider>> ret;
    2076                 :             : 
    2077                 :      522796 :     using namespace script;
    2078                 :             : 
    2079                 :             :     // musig cannot be nested inside of an origin
    2080                 :      522796 :     std::span<const char> span = sp;
    2081   [ +  -  +  -  :      522796 :     if (Const("musig(", span, /*skip=*/false)) {
                   +  + ]
    2082         [ +  + ]:       20918 :         if (ctx != ParseScriptContext::P2TR) {
    2083         [ +  - ]:           6 :             error = "musig() is only allowed in tr() and rawtr()";
    2084                 :           6 :             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         [ +  - ]:       20912 :         auto split = Split(sp, ')', /*include_sep=*/true);
    2090   [ -  +  +  + ]:       20912 :         if (split.size() > 2) {
    2091         [ +  - ]:          70 :             error = "Too many ')' in musig() expression";
    2092                 :          70 :             return {};
    2093                 :             :         }
    2094   [ +  -  +  -  :       20842 :         std::span<const char> expr(split.at(0).begin(), split.at(0).end());
                   +  - ]
    2095   [ +  -  +  -  :       20842 :         if (!Func("musig", expr)) {
                   +  + ]
    2096         [ +  - ]:          10 :             error = "Invalid musig() expression";
    2097                 :          10 :             return {};
    2098                 :             :         }
    2099                 :             : 
    2100                 :             :         // Parse the participant pubkeys
    2101                 :       20832 :         bool any_ranged = false;
    2102                 :       20832 :         bool all_bip32 = true;
    2103                 :       20832 :         std::vector<std::vector<std::unique_ptr<PubkeyProvider>>> providers;
    2104                 :       20832 :         bool any_key_parsed = false;
    2105                 :       20832 :         size_t max_multipath_len = 0;
    2106         [ +  + ]:      170957 :         while (expr.size()) {
    2107                 :      279565 :             if (any_key_parsed && !Const(",", expr)) {
           [ +  +  +  -  
          +  -  +  +  +  
                +  -  - ]
    2108         [ +  - ]:           8 :                 error = strprintf("musig(): expected ',', got '%c'", expr[0]);
    2109                 :           8 :                 return {};
    2110                 :             :             }
    2111         [ +  - ]:      150188 :             auto arg = Expr(expr);
    2112         [ +  - ]:      150188 :             auto pk = ParsePubkey(key_exp_index, arg, ParseScriptContext::MUSIG, out, error);
    2113         [ +  + ]:      150188 :             if (pk.empty()) {
    2114         [ +  - ]:          63 :                 error = strprintf("musig(): %s", error);
    2115                 :          63 :                 return {};
    2116                 :             :             }
    2117                 :      150125 :             any_key_parsed = true;
    2118                 :             : 
    2119   [ +  +  +  -  :      275285 :             any_ranged = any_ranged || pk.at(0)->IsRange();
                   +  + ]
    2120   [ +  +  +  -  :      212112 :             all_bip32 = all_bip32 &&  pk.at(0)->IsBIP32();
                   +  + ]
    2121                 :             : 
    2122   [ -  +  +  + ]:      150125 :             max_multipath_len = std::max(max_multipath_len, pk.size());
    2123                 :             : 
    2124         [ +  - ]:      150125 :             providers.emplace_back(std::move(pk));
    2125                 :      150188 :         }
    2126         [ +  + ]:       20761 :         if (!any_key_parsed) {
    2127         [ +  - ]:           5 :             error = "musig(): Must contain key expressions";
    2128                 :           5 :             return {};
    2129                 :             :         }
    2130                 :             : 
    2131                 :             :         // Parse any derivation
    2132                 :       20756 :         DeriveType deriv_type = DeriveType::NON_RANGED;
    2133                 :       20756 :         std::vector<KeyPath> derivation_multipaths;
    2134                 :       62268 :         if (split.size() == 2 && Const("/", split.at(1), /*skip=*/false)) {
           [ -  +  +  -  
          +  -  +  -  +  
                +  +  + ]
    2135         [ +  + ]:        2107 :             if (!all_bip32) {
    2136         [ +  - ]:           9 :                 error = "musig(): derivation requires all participants to be xpubs or xprvs";
    2137                 :           9 :                 return {};
    2138                 :             :             }
    2139         [ +  + ]:        2098 :             if (any_ranged) {
    2140         [ +  - ]:           4 :                 error = "musig(): Cannot have ranged participant keys if musig() also has derivation";
    2141                 :           4 :                 return {};
    2142                 :             :             }
    2143                 :        2094 :             bool dummy = false;
    2144   [ +  -  +  - ]:        2094 :             auto deriv_split = Split(split.at(1), '/');
    2145                 :        2094 :             deriv_type = ParseDeriveType(deriv_split, dummy);
    2146         [ +  + ]:        2094 :             if (deriv_type == DeriveType::HARDENED_RANGED) {
    2147         [ +  - ]:           5 :                 error = "musig(): Cannot have hardened child derivation";
    2148                 :           5 :                 return {};
    2149                 :             :             }
    2150                 :        2089 :             bool has_hardened = false;
    2151   [ +  -  +  + ]:        2089 :             if (!ParseKeyPath(deriv_split, derivation_multipaths, dummy, error, /*allow_multipath=*/true, has_hardened)) {
    2152         [ +  - ]:          12 :                 error = "musig(): " + error;
    2153                 :          12 :                 return {};
    2154                 :             :             }
    2155         [ +  + ]:        2077 :             if (has_hardened) {
    2156         [ +  - ]:           4 :                 error = "musig(): cannot have hardened derivation steps";
    2157                 :           4 :                 return {};
    2158                 :             :             }
    2159                 :        2094 :         } else {
    2160         [ +  - ]:       18649 :             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                 :       24488 :         const auto& clone_providers = [&providers](size_t length) -> bool {
    2166         [ +  + ]:       72683 :             for (auto& multipath_providers : providers) {
    2167   [ -  +  +  + ]:       68927 :                 if (multipath_providers.size() == 1) {
    2168         [ +  + ]:      901860 :                     for (size_t i = 1; i < length; ++i) {
    2169         [ +  - ]:      836953 :                         multipath_providers.emplace_back(multipath_providers.at(0)->Clone());
    2170                 :             :                     }
    2171         [ +  + ]:        4020 :                 } else if (multipath_providers.size() != length) {
    2172                 :             :                     return false;
    2173                 :             :                 }
    2174                 :             :             }
    2175                 :             :             return true;
    2176                 :       20722 :         };
    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                 :       72673 :         const auto& emplace_final_provider = [&ret, &key_exp_index, &deriv_type, &derivation_multipaths, &providers](size_t vec_idx, size_t path_idx) -> void {
    2181                 :       51951 :             KeyPath& path = derivation_multipaths.at(path_idx);
    2182                 :       51951 :             std::vector<std::unique_ptr<PubkeyProvider>> pubs;
    2183   [ -  +  +  - ]:       51951 :             pubs.reserve(providers.size());
    2184         [ +  + ]:     1071959 :             for (auto& vec : providers) {
    2185   [ +  -  +  - ]:     1020008 :                 pubs.emplace_back(std::move(vec.at(vec_idx)));
    2186                 :             :             }
    2187   [ +  -  +  - ]:       51951 :             ret.emplace_back(std::make_unique<MuSigPubkeyProvider>(key_exp_index, std::move(pubs), path, deriv_type));
    2188                 :       51951 :         };
    2189                 :             : 
    2190   [ +  +  +  + ]:       24020 :         if (max_multipath_len > 1 && derivation_multipaths.size() > 1) {
    2191         [ +  - ]:           5 :             error = "musig(): Cannot have multipath participant keys if musig() is also multipath";
    2192                 :           5 :             return {};
    2193         [ +  + ]:       20717 :         } else if (max_multipath_len > 1) {
    2194   [ +  -  +  + ]:        3293 :             if (!clone_providers(max_multipath_len)) {
    2195         [ +  - ]:          10 :                 error = strprintf("musig(): Multipath derivation paths have mismatched lengths");
    2196                 :          10 :                 return {};
    2197                 :             :             }
    2198         [ +  + ]:       33873 :             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         [ +  - ]:       30590 :                 emplace_final_provider(i, 0);
    2201                 :             :             }
    2202   [ -  +  +  + ]:       17424 :         } 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   [ +  -  +  -  :         473 :             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   [ -  +  +  + ]:        4883 :             for (size_t i = 0; i < derivation_multipaths.size(); ++i) {
    2209                 :             :                 // Final MuSigPubkeyProvider uses cloned participant pubkey providers, and the multipath derivation paths
    2210         [ +  - ]:        4410 :                 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         [ +  - ]:       16951 :             emplace_final_provider(0, 0);
    2215                 :             :         }
    2216                 :       20707 :         ++key_exp_index; // Increment key expression index for the MuSigPubkeyProvider too
    2217                 :       20707 :         return ret;
    2218                 :       41744 :     }
    2219                 :             : 
    2220         [ +  - ]:      501878 :     auto origin_split = Split(sp, ']');
    2221   [ -  +  +  + ]:      501878 :     if (origin_split.size() > 2) {
    2222         [ +  - ]:          11 :         error = "Multiple ']' characters found for a single pubkey";
    2223                 :          11 :         return {};
    2224                 :             :     }
    2225                 :             :     // This is set if either the origin or path suffix contains a hardened derivation.
    2226                 :      501867 :     bool apostrophe = false;
    2227         [ +  + ]:      501867 :     if (origin_split.size() == 1) {
    2228         [ +  - ]:      436541 :         return ParsePubkeyInner(key_exp_index, origin_split[0], ctx, out, apostrophe, error);
    2229                 :             :     }
    2230   [ +  +  +  + ]:       65326 :     if (origin_split[0].empty() || origin_split[0][0] != '[') {
    2231                 :          60 :         error = strprintf("Key origin start '[ character expected but not found, got '%c' instead",
    2232   [ +  +  +  - ]:          20 :                           origin_split[0].empty() ? /** empty, implies split char */ ']' : origin_split[0][0]);
    2233                 :          20 :         return {};
    2234                 :             :     }
    2235         [ +  - ]:       65306 :     auto slash_split = Split(origin_split[0].subspan(1), '/');
    2236         [ +  + ]:       65306 :     if (slash_split[0].size() != 8) {
    2237         [ +  - ]:          10 :         error = strprintf("Fingerprint is not 4 bytes (%u characters instead of 8 characters)", slash_split[0].size());
    2238                 :          10 :         return {};
    2239                 :             :     }
    2240   [ +  -  -  + ]:      130592 :     std::string fpr_hex = std::string(slash_split[0].begin(), slash_split[0].end());
    2241   [ -  +  +  -  :       65296 :     if (!IsHex(fpr_hex)) {
                   +  + ]
    2242         [ +  - ]:           6 :         error = strprintf("Fingerprint '%s' is not hex", fpr_hex);
    2243                 :           6 :         return {};
    2244                 :             :     }
    2245   [ -  +  +  - ]:       65290 :     auto fpr_bytes = ParseHex(fpr_hex);
    2246         [ -  + ]:       65290 :     KeyOriginInfo info;
    2247                 :       65290 :     static_assert(sizeof(info.fingerprint) == 4, "Fingerprint must be 4 bytes");
    2248   [ -  +  -  + ]:       65290 :     assert(fpr_bytes.size() == 4);
    2249                 :       65290 :     std::copy_n(fpr_bytes.begin(), info.fingerprint.size(), info.fingerprint.begin());
    2250                 :       65290 :     std::vector<KeyPath> path;
    2251   [ +  -  +  + ]:       65290 :     if (!ParseKeyPath(slash_split, path, apostrophe, error, /*allow_multipath=*/false)) return {};
    2252   [ +  -  +  - ]:       65166 :     info.path = path.at(0);
    2253         [ +  - ]:       65166 :     auto providers = ParsePubkeyInner(key_exp_index, origin_split[1], ctx, out, apostrophe, error);
    2254         [ +  + ]:       65166 :     if (providers.empty()) return {};
    2255   [ -  +  +  - ]:       65109 :     ret.reserve(providers.size());
    2256         [ +  + ]:      155542 :     for (auto& prov : providers) {
    2257   [ +  -  +  - ]:      180866 :         ret.emplace_back(std::make_unique<OriginPubkeyProvider>(prov->m_expr_index, info, std::move(prov), apostrophe));
    2258                 :             :     }
    2259                 :       65109 :     return ret;
    2260                 :      718688 : }
    2261                 :             : 
    2262                 :      436376 : std::unique_ptr<PubkeyProvider> InferPubkey(const CPubKey& pubkey, ParseScriptContext ctx, const SigningProvider& provider)
    2263                 :             : {
    2264                 :             :     // Key cannot be hybrid
    2265         [ +  + ]:      436376 :     if (!pubkey.IsValidNonHybrid()) {
    2266                 :        4676 :         return nullptr;
    2267                 :             :     }
    2268                 :             :     // Uncompressed is only allowed in TOP and P2SH contexts
    2269   [ +  +  +  + ]:      431700 :     if (ctx != ParseScriptContext::TOP && ctx != ParseScriptContext::P2SH && !pubkey.IsCompressed()) {
    2270                 :        1296 :         return nullptr;
    2271                 :             :     }
    2272                 :      430404 :     std::unique_ptr<PubkeyProvider> key_provider = std::make_unique<ConstPubkeyProvider>(0, pubkey, false);
    2273         [ +  - ]:      430404 :     KeyOriginInfo info;
    2274   [ +  -  +  -  :      430404 :     if (provider.GetKeyOrigin(pubkey.GetID(), info)) {
                   +  + ]
    2275   [ +  -  -  + ]:      165055 :         return std::make_unique<OriginPubkeyProvider>(0, std::move(info), std::move(key_provider), /*apostrophe=*/false);
    2276                 :             :     }
    2277                 :      265349 :     return key_provider;
    2278                 :      430404 : }
    2279                 :             : 
    2280                 :      758098 : std::unique_ptr<PubkeyProvider> InferXOnlyPubkey(const XOnlyPubKey& xkey, ParseScriptContext ctx, const SigningProvider& provider)
    2281                 :             : {
    2282                 :      758098 :     CPubKey pubkey{xkey.GetEvenCorrespondingCPubKey()};
    2283                 :      758098 :     std::unique_ptr<PubkeyProvider> key_provider = std::make_unique<ConstPubkeyProvider>(0, pubkey, true);
    2284         [ +  - ]:      758098 :     KeyOriginInfo info;
    2285   [ +  -  +  + ]:      758098 :     if (provider.GetKeyOriginByXOnly(xkey, info)) {
    2286   [ +  -  -  + ]:      750091 :         return std::make_unique<OriginPubkeyProvider>(0, std::move(info), std::move(key_provider), /*apostrophe=*/false);
    2287                 :             :     }
    2288                 :        8007 :     return key_provider;
    2289                 :      758098 : }
    2290                 :             : 
    2291                 :             : /**
    2292                 :             :  * The context for parsing a Miniscript descriptor (either from Script or from its textual representation).
    2293                 :             :  */
    2294                 :       40218 : 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                 :       40218 :     KeyParser(FlatSigningProvider* out LIFETIMEBOUND, const SigningProvider* in LIFETIMEBOUND,
    2311                 :             :               miniscript::MiniscriptContext ctx, uint32_t& key_exp_index LIFETIMEBOUND)
    2312                 :       40218 :         : m_out(out), m_in(in), m_script_ctx(ctx), m_expr_index(key_exp_index) {}
    2313                 :             : 
    2314                 :      331659 :     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   [ +  +  -  + ]:      331659 :         const SigningProvider& provider{m_out ? *m_out : (m_in ? *m_in : DUMMY_SIGNING_PROVIDER)};
    2318                 :      331659 :         const PubkeyProvider& key_a{*m_keys.at(a).at(0)};
    2319                 :      331659 :         const PubkeyProvider& key_b{*m_keys.at(b).at(0)};
    2320                 :      331659 :         FlatSigningProvider out_a, out_b;
    2321         [ +  - ]:      331659 :         const std::optional<CPubKey> pub_a{key_a.GetPubKey(0, provider, out_a)};
    2322         [ +  - ]:      331659 :         const std::optional<CPubKey> pub_b{key_b.GetPubKey(0, provider, out_b)};
    2323   [ +  +  +  + ]:      331659 :         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         [ +  + ]:       10113 :         if (pub_a.has_value() != pub_b.has_value()) return !pub_a.has_value();
    2327   [ +  -  +  - ]:        4904 :         return key_a.ToString(PubkeyProvider::StringType::PUBLIC) < key_b.ToString(PubkeyProvider::StringType::PUBLIC);
    2328                 :      331659 :     }
    2329                 :             : 
    2330                 :      122108 :     ParseScriptContext ParseContext() const {
    2331      [ +  -  + ]:      122108 :         switch (m_script_ctx) {
    2332                 :             :             case miniscript::MiniscriptContext::P2WSH: return ParseScriptContext::P2WSH;
    2333                 :       85372 :             case miniscript::MiniscriptContext::TAPSCRIPT: return ParseScriptContext::P2TR;
    2334                 :             :         }
    2335                 :           0 :         AssertUnreachable();
    2336                 :             :     }
    2337                 :             : 
    2338                 :       72522 :     std::optional<Key> FromString(std::span<const char>& in) const
    2339                 :             :     {
    2340         [ -  + ]:       72522 :         assert(m_out);
    2341         [ -  + ]:       72522 :         Key key = m_keys.size();
    2342                 :       72522 :         auto pk = ParsePubkey(m_expr_index, in, ParseContext(), *m_out, m_key_parsing_error);
    2343         [ +  + ]:       72522 :         if (pk.empty()) return {};
    2344         [ +  - ]:       72298 :         m_keys.emplace_back(std::move(pk));
    2345                 :       72298 :         return key;
    2346                 :       72522 :     }
    2347                 :             : 
    2348                 :       21874 :     std::optional<std::string> ToString(const Key& key, bool&) const
    2349                 :             :     {
    2350                 :       21874 :         return m_keys.at(key).at(0)->ToString(PubkeyProvider::StringType::PUBLIC);
    2351                 :             :     }
    2352                 :             : 
    2353                 :       46436 :     template<typename I> std::optional<Key> FromPKBytes(I begin, I end) const
    2354                 :             :     {
    2355         [ -  + ]:       46436 :         assert(m_in);
    2356         [ -  + ]:       46436 :         Key key = m_keys.size();
    2357   [ +  +  +  - ]:       46436 :         if (miniscript::IsTapscript(m_script_ctx) && end - begin == 32) {
    2358                 :       27509 :             XOnlyPubKey pubkey;
    2359                 :       27509 :             std::copy(begin, end, pubkey.begin());
    2360         [ +  - ]:       27509 :             if (auto pubkey_provider = InferXOnlyPubkey(pubkey, ParseContext(), *m_in)) {
    2361         [ +  - ]:       27509 :                 m_keys.emplace_back();
    2362         [ +  - ]:       27509 :                 m_keys.back().push_back(std::move(pubkey_provider));
    2363                 :       27509 :                 return key;
    2364                 :             :             }
    2365         [ +  - ]:       18927 :         } else if (!miniscript::IsTapscript(m_script_ctx)) {
    2366                 :       18927 :             CPubKey pubkey(begin, end);
    2367         [ +  + ]:       18927 :             if (auto pubkey_provider = InferPubkey(pubkey, ParseContext(), *m_in)) {
    2368         [ +  - ]:       18914 :                 m_keys.emplace_back();
    2369         [ +  - ]:       18914 :                 m_keys.back().push_back(std::move(pubkey_provider));
    2370                 :       18914 :                 return key;
    2371                 :             :             }
    2372                 :             :         }
    2373                 :          13 :         return {};
    2374                 :             :     }
    2375                 :             : 
    2376         [ -  + ]:        3151 :     template<typename I> std::optional<Key> FromPKHBytes(I begin, I end) const
    2377                 :             :     {
    2378         [ -  + ]:        3151 :         assert(end - begin == 20);
    2379         [ -  + ]:        3151 :         assert(m_in);
    2380                 :        3151 :         uint160 hash;
    2381                 :        3151 :         std::copy(begin, end, hash.begin());
    2382                 :        3151 :         CKeyID keyid(hash);
    2383                 :        3151 :         CPubKey pubkey;
    2384         [ +  + ]:        3151 :         if (m_in->GetPubKey(keyid, pubkey)) {
    2385         [ +  + ]:        3150 :             if (auto pubkey_provider = InferPubkey(pubkey, ParseContext(), *m_in)) {
    2386         [ -  + ]:        3113 :                 Key key = m_keys.size();
    2387         [ +  - ]:        3113 :                 m_keys.emplace_back();
    2388         [ +  - ]:        3113 :                 m_keys.back().push_back(std::move(pubkey_provider));
    2389                 :        3113 :                 return key;
    2390                 :             :             }
    2391                 :             :         }
    2392                 :          38 :         return {};
    2393                 :             :     }
    2394                 :             : 
    2395                 :     6540307 :     miniscript::MiniscriptContext MsContext() const {
    2396                 :     6540307 :         return m_script_ctx;
           [ +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
             +  +  -  +  
                      - ]
    2397                 :             :     }
    2398                 :             : };
    2399                 :             : 
    2400                 :             : /** Parse a script in a particular context. */
    2401                 :             : // NOLINTNEXTLINE(misc-no-recursion)
    2402                 :       86029 : 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                 :       86029 :     using namespace script;
    2405   [ +  +  -  + ]:       86029 :     Assume(ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH || ctx == ParseScriptContext::P2TR);
    2406                 :       86029 :     std::vector<std::unique_ptr<DescriptorImpl>> ret;
    2407         [ +  - ]:       86029 :     auto expr = Expr(sp);
    2408   [ +  -  +  -  :       86029 :     if (Func("pk", expr)) {
                   +  + ]
    2409         [ +  - ]:        8434 :         auto pubkeys = ParsePubkey(key_exp_index, expr, ctx, out, error);
    2410         [ +  + ]:        8434 :         if (pubkeys.empty()) {
    2411         [ +  - ]:         263 :             error = strprintf("pk(): %s", error);
    2412                 :         263 :             return {};
    2413                 :             :         }
    2414         [ +  + ]:       18667 :         for (auto& pubkey : pubkeys) {
    2415   [ +  -  +  - ]:       20992 :             ret.emplace_back(std::make_unique<PKDescriptor>(std::move(pubkey), ctx == ParseScriptContext::P2TR));
    2416                 :             :         }
    2417                 :        8171 :         return ret;
    2418                 :        8434 :     }
    2419   [ +  +  +  -  :      143156 :     if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH) && Func("pkh", expr)) {
          +  -  +  +  +  
                      + ]
    2420         [ +  - ]:        1972 :         auto pubkeys = ParsePubkey(key_exp_index, expr, ctx, out, error);
    2421         [ +  + ]:        1972 :         if (pubkeys.empty()) {
    2422         [ +  - ]:          17 :             error = strprintf("pkh(): %s", error);
    2423                 :          17 :             return {};
    2424                 :             :         }
    2425         [ +  + ]:        4698 :         for (auto& pubkey : pubkeys) {
    2426   [ +  -  +  - ]:        5486 :             ret.emplace_back(std::make_unique<PKHDescriptor>(std::move(pubkey)));
    2427                 :             :         }
    2428                 :        1955 :         return ret;
    2429                 :        1972 :     }
    2430   [ +  +  +  -  :      119891 :     if (ctx == ParseScriptContext::TOP && Func("combo", expr)) {
          +  -  +  +  +  
                      + ]
    2431         [ +  - ]:        9984 :         auto pubkeys = ParsePubkey(key_exp_index, expr, ctx, out, error);
    2432         [ +  + ]:        9984 :         if (pubkeys.empty()) {
    2433         [ +  - ]:          17 :             error = strprintf("combo(): %s", error);
    2434                 :          17 :             return {};
    2435                 :             :         }
    2436         [ +  + ]:       20648 :         for (auto& pubkey : pubkeys) {
    2437   [ +  -  +  - ]:       21362 :             ret.emplace_back(std::make_unique<ComboDescriptor>(std::move(pubkey)));
    2438                 :             :         }
    2439                 :        9967 :         return ret;
    2440   [ +  -  +  -  :       75623 :     } else if (Func("combo", expr)) {
                   +  + ]
    2441         [ +  - ]:           5 :         error = "Can only have combo() at top level";
    2442                 :           5 :         return {};
    2443                 :             :     }
    2444   [ +  -  +  - ]:       65634 :     const bool multi = Func("multi", expr);
    2445   [ +  +  +  -  :      116055 :     const bool sortedmulti = !multi && Func("sortedmulti", expr);
             +  -  +  + ]
    2446   [ +  +  +  -  :      115617 :     const bool multi_a = !(multi || sortedmulti) && Func("multi_a", expr);
             +  -  +  + ]
    2447   [ +  +  +  +  :      114430 :     const bool sortedmulti_a = !(multi || sortedmulti || multi_a) && Func("sortedmulti_a", expr);
          +  -  +  -  +  
                      + ]
    2448   [ +  +  +  +  :       65634 :     if (((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH) && (multi || sortedmulti)) ||
             +  +  +  + ]
    2449   [ +  +  +  + ]:       12034 :         (ctx == ParseScriptContext::P2TR && (multi_a || sortedmulti_a))) {
    2450         [ +  - ]:       18023 :         auto threshold = Expr(expr);
    2451                 :       18023 :         uint32_t thres;
    2452                 :       18023 :         std::vector<std::vector<std::unique_ptr<PubkeyProvider>>> providers; // List of multipath expanded pubkeys
    2453         [ +  + ]:       18023 :         if (const auto maybe_thres{ToIntegral<uint32_t>(std::string_view{threshold.begin(), threshold.end()})}) {
    2454                 :       17891 :             thres = *maybe_thres;
    2455                 :             :         } else {
    2456   [ +  -  +  - ]:         264 :             error = strprintf("Multi threshold '%s' is not valid", std::string(threshold.begin(), threshold.end()));
    2457                 :         132 :             return {};
    2458                 :             :         }
    2459                 :       17891 :         size_t script_size = 0;
    2460                 :       17891 :         size_t max_providers_len = 0;
    2461         [ +  + ]:      290815 :         while (expr.size()) {
    2462   [ +  -  +  -  :      273122 :             if (!Const(",", expr)) {
                   +  + ]
    2463         [ +  - ]:           7 :                 error = strprintf("Multi: expected ',', got '%c'", expr[0]);
    2464                 :           7 :                 return {};
    2465                 :             :             }
    2466         [ +  - ]:      273115 :             auto arg = Expr(expr);
    2467         [ +  - ]:      273115 :             auto pks = ParsePubkey(key_exp_index, arg, ctx, out, error);
    2468         [ +  + ]:      273115 :             if (pks.empty()) {
    2469         [ +  - ]:         191 :                 error = strprintf("Multi: %s", error);
    2470                 :         191 :                 return {};
    2471                 :             :             }
    2472   [ +  -  +  - ]:      272924 :             script_size += pks.at(0)->GetSize() + 1;
    2473   [ -  +  +  + ]:      272924 :             max_providers_len = std::max(max_providers_len, pks.size());
    2474         [ +  - ]:      272924 :             providers.emplace_back(std::move(pks));
    2475                 :      273115 :         }
    2476   [ +  +  +  +  :       33061 :         if ((multi || sortedmulti) && (providers.empty() || providers.size() > MAX_PUBKEYS_PER_MULTISIG)) {
             +  +  +  + ]
    2477   [ -  +  +  - ]:          26 :             error = strprintf("Cannot have %u keys in multisig; must have between 1 and %d keys, inclusive", providers.size(), MAX_PUBKEYS_PER_MULTISIG);
    2478                 :          26 :             return {};
    2479   [ +  +  +  +  :       19962 :         } else if ((multi_a || sortedmulti_a) && (providers.empty() || providers.size() > MAX_PUBKEYS_PER_MULTI_A)) {
             +  +  -  + ]
    2480   [ -  +  +  - ]:          15 :             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                 :          15 :             return {};
    2482         [ +  + ]:       17652 :         } else if (thres < 1) {
    2483         [ +  - ]:           8 :             error = strprintf("Multisig threshold cannot be %d, must be at least 1", thres);
    2484                 :           8 :             return {};
    2485   [ -  +  +  + ]:       17644 :         } else if (thres > providers.size()) {
    2486         [ +  - ]:          13 :             error = strprintf("Multisig threshold cannot be larger than the number of keys; threshold is %d but only %u keys specified", thres, providers.size());
    2487                 :          13 :             return {};
    2488                 :             :         }
    2489         [ +  + ]:       17631 :         if (ctx == ParseScriptContext::TOP) {
    2490         [ +  + ]:         251 :             if (providers.size() > 3) {
    2491         [ +  - ]:          14 :                 error = strprintf("Cannot have %u pubkeys in bare multisig; only at most 3 pubkeys", providers.size());
    2492                 :          14 :                 return {};
    2493                 :             :             }
    2494                 :             :         }
    2495         [ +  + ]:       17617 :         if (ctx == ParseScriptContext::P2SH) {
    2496                 :             :             // This limits the maximum number of compressed pubkeys to 15.
    2497         [ +  + ]:        8740 :             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         [ +  + ]:      274341 :         for (auto& vec : providers) {
    2506   [ -  +  +  + ]:      256734 :             if (vec.size() == 1) {
    2507         [ +  + ]:      655821 :                 for (size_t i = 1; i < max_providers_len; ++i) {
    2508   [ +  -  +  -  :      401523 :                     vec.emplace_back(vec.at(0)->Clone());
                   +  - ]
    2509                 :             :                 }
    2510         [ +  + ]:        2436 :             } else if (vec.size() != max_providers_len) {
    2511         [ +  - ]:           6 :                 error = strprintf("multi(): Multipath derivation paths have mismatched lengths");
    2512                 :           6 :                 return {};
    2513                 :             :             }
    2514                 :             :         }
    2515                 :             : 
    2516                 :             :         // Build the final descriptors vector
    2517         [ +  + ]:       41928 :         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                 :       24321 :             std::vector<std::unique_ptr<PubkeyProvider>> pubs;
    2520   [ -  +  +  - ]:       24321 :             pubs.reserve(providers.size());
    2521         [ +  + ]:      691587 :             for (auto& pub : providers) {
    2522   [ +  -  +  - ]:      667266 :                 pubs.emplace_back(std::move(pub.at(i)));
    2523                 :             :             }
    2524   [ +  +  +  + ]:       24321 :             if (multi || sortedmulti) {
    2525   [ +  -  +  - ]:       33696 :                 ret.emplace_back(std::make_unique<MultisigDescriptor>(thres, std::move(pubs), sortedmulti));
    2526                 :             :             } else {
    2527   [ +  -  +  - ]:       14946 :                 ret.emplace_back(std::make_unique<MultiADescriptor>(thres, std::move(pubs), sortedmulti_a));
    2528                 :             :             }
    2529                 :       24321 :         }
    2530                 :       17607 :         return ret;
    2531   [ +  +  +  + ]:       65634 :     } else if (multi || sortedmulti) {
    2532         [ +  - ]:           8 :         error = "Can only have multi/sortedmulti at top level, in sh(), or in wsh()";
    2533                 :           8 :         return {};
    2534   [ +  +  +  + ]:       47603 :     } else if (multi_a || sortedmulti_a) {
    2535         [ +  - ]:          11 :         error = "Can only have multi_a/sortedmulti_a inside tr()";
    2536                 :          11 :         return {};
    2537                 :             :     }
    2538   [ +  +  +  -  :       81783 :     if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH) && Func("wpkh", expr)) {
          +  -  +  +  +  
                      + ]
    2539         [ +  - ]:         150 :         auto pubkeys = ParsePubkey(key_exp_index, expr, ParseScriptContext::P2WPKH, out, error);
    2540         [ +  + ]:         150 :         if (pubkeys.empty()) {
    2541         [ +  - ]:          16 :             error = strprintf("wpkh(): %s", error);
    2542                 :          16 :             return {};
    2543                 :             :         }
    2544         [ +  + ]:         774 :         for (auto& pubkey : pubkeys) {
    2545   [ +  -  +  - ]:        1280 :             ret.emplace_back(std::make_unique<WPKHDescriptor>(std::move(pubkey)));
    2546                 :             :         }
    2547                 :         134 :         return ret;
    2548   [ +  -  +  -  :       47592 :     } else if (Func("wpkh", expr)) {
                   +  + ]
    2549         [ +  - ]:           6 :         error = "Can only have wpkh() at top level or inside sh()";
    2550                 :           6 :         return {};
    2551                 :             :     }
    2552   [ +  +  +  -  :       81111 :     if (ctx == ParseScriptContext::TOP && Func("sh", expr)) {
          +  -  +  +  +  
                      + ]
    2553         [ +  - ]:        9632 :         auto descs = ParseScript(key_exp_index, expr, ParseScriptContext::P2SH, out, error);
    2554   [ +  +  +  + ]:        9632 :         if (descs.empty() || expr.size()) return {};
    2555                 :        9435 :         std::vector<std::unique_ptr<DescriptorImpl>> ret;
    2556   [ -  +  +  - ]:        9435 :         ret.reserve(descs.size());
    2557         [ +  + ]:       21169 :         for (auto& desc : descs) {
    2558   [ +  -  +  -  :       11734 :             ret.push_back(std::make_unique<SHDescriptor>(std::move(desc)));
                   -  + ]
    2559                 :             :         }
    2560                 :        9435 :         return ret;
    2561   [ +  -  +  -  :       47436 :     } else if (Func("sh", expr)) {
                   +  + ]
    2562         [ +  - ]:           5 :         error = "Can only have sh() at top level";
    2563                 :           5 :         return {};
    2564                 :             :     }
    2565   [ +  +  +  -  :       62204 :     if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH) && Func("wsh", expr)) {
          +  -  +  +  +  
                      + ]
    2566         [ +  - ]:       10480 :         auto descs = ParseScript(key_exp_index, expr, ParseScriptContext::P2WSH, out, error);
    2567   [ +  +  +  + ]:       10480 :         if (descs.empty() || expr.size()) return {};
    2568         [ +  + ]:       22975 :         for (auto& desc : descs) {
    2569   [ +  -  +  - ]:       29068 :             ret.emplace_back(std::make_unique<WSHDescriptor>(std::move(desc)));
    2570                 :             :         }
    2571                 :        8441 :         return ret;
    2572   [ +  -  +  -  :       37799 :     } else if (Func("wsh", expr)) {
                   +  + ]
    2573         [ +  - ]:           6 :         error = "Can only have wsh() at top level or inside sh()";
    2574                 :           6 :         return {};
    2575                 :             :     }
    2576   [ +  +  +  -  :       41185 :     if (ctx == ParseScriptContext::TOP && Func("addr", expr)) {
          +  -  +  +  +  
                      + ]
    2577   [ +  -  +  - ]:        4690 :         CTxDestination dest = DecodeDestination(std::string(expr.begin(), expr.end()));
    2578   [ +  -  +  + ]:        2345 :         if (!IsValidDestination(dest)) {
    2579         [ +  - ]:         754 :             error = "Address is not valid";
    2580                 :         754 :             return {};
    2581                 :             :         }
    2582   [ +  -  +  - ]:        1591 :         ret.emplace_back(std::make_unique<AddressDescriptor>(std::move(dest)));
    2583                 :        1591 :         return ret;
    2584   [ +  -  +  -  :       27313 :     } else if (Func("addr", expr)) {
                   +  + ]
    2585         [ +  - ]:           5 :         error = "Can only have addr() at top level";
    2586                 :           5 :         return {};
    2587                 :             :     }
    2588   [ +  +  +  -  :       36490 :     if (ctx == ParseScriptContext::TOP && Func("tr", expr)) {
          +  -  +  +  +  
                      + ]
    2589         [ +  - ]:        6068 :         auto arg = Expr(expr);
    2590         [ +  - ]:        6068 :         auto internal_keys = ParsePubkey(key_exp_index, arg, ParseScriptContext::P2TR, out, error);
    2591         [ +  + ]:        6068 :         if (internal_keys.empty()) {
    2592         [ +  - ]:         229 :             error = strprintf("tr(): %s", error);
    2593                 :         229 :             return {};
    2594                 :             :         }
    2595         [ -  + ]:        5839 :         size_t max_providers_len = internal_keys.size();
    2596                 :        5839 :         std::vector<std::vector<std::unique_ptr<DescriptorImpl>>> subscripts; //!< list of multipath expanded script subexpressions
    2597                 :        5839 :         std::vector<int> depths; //!< depth in the tree of each subexpression (same length subscripts)
    2598         [ +  + ]:        5839 :         if (expr.size()) {
    2599   [ +  -  +  -  :        3817 :             if (!Const(",", expr)) {
                   +  + ]
    2600         [ +  - ]:           8 :                 error = strprintf("tr: expected ',', got '%c'", expr[0]);
    2601                 :           8 :                 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                 :        3809 :             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   [ +  -  +  -  :       36717 :                 while (Const("{", expr)) {
                   +  + ]
    2612         [ +  - ]:       19852 :                     branches.push_back(false); // new left branch
    2613         [ +  + ]:       19852 :                     if (branches.size() > TAPROOT_CONTROL_MAX_NODE_COUNT) {
    2614         [ +  - ]:          13 :                         error = strprintf("tr() supports at most %i nesting levels", TAPROOT_CONTROL_MAX_NODE_COUNT);
    2615                 :          13 :                         return {};
    2616                 :             :                     }
    2617                 :             :                 }
    2618                 :             :                 // Process the actual script expression.
    2619         [ +  - ]:       16865 :                 auto sarg = Expr(expr);
    2620   [ +  -  +  - ]:       16865 :                 subscripts.emplace_back(ParseScript(key_exp_index, sarg, ParseScriptContext::P2TR, out, error));
    2621         [ +  + ]:       16865 :                 if (subscripts.back().empty()) return {};
    2622   [ -  +  +  + ]:       16028 :                 max_providers_len = std::max(max_providers_len, subscripts.back().size());
    2623         [ +  - ]:       16028 :                 depths.push_back(branches.size());
    2624                 :             :                 // Process closing braces; one is expected for every right branch we were in.
    2625         [ +  + ]:       19831 :                 while (branches.size() && branches.back()) {
    2626   [ +  -  +  +  :        6713 :                     if (!Const("}", expr)) {
                   +  - ]
    2627         [ +  - ]:          24 :                         error = strprintf("tr(): expected '}' after script expression");
    2628                 :          24 :                         return {};
    2629                 :             :                     }
    2630   [ -  +  +  + ]:       29406 :                     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   [ +  +  +  - ]:       16004 :                 if (branches.size() && !branches.back()) {
    2634   [ +  -  +  -  :       13118 :                     if (!Const(",", expr)) {
                   +  + ]
    2635         [ +  - ]:          49 :                         error = strprintf("tr(): expected ',' after script expression");
    2636                 :          49 :                         return {};
    2637                 :             :                     }
    2638                 :       13069 :                     branches.back() = true; // And now we're in a right branch.
    2639                 :             :                 }
    2640         [ +  + ]:       15955 :             } while (branches.size());
    2641                 :             :             // After we've explored a whole tree, we must be at the end of the expression.
    2642         [ +  + ]:        2886 :             if (expr.size()) {
    2643         [ +  - ]:          19 :                 error = strprintf("tr(): expected ')' after script expression");
    2644                 :          19 :                 return {};
    2645                 :             :             }
    2646                 :        3809 :         }
    2647   [ +  -  -  + ]:        4889 :         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         [ +  + ]:       13690 :         for (auto& vec : subscripts) {
    2652   [ -  +  +  + ]:        8807 :             if (vec.size() == 1) {
    2653         [ +  + ]:       22409 :                 for (size_t i = 1; i < max_providers_len; ++i) {
    2654   [ +  -  +  -  :       14573 :                     vec.emplace_back(vec.at(0)->Clone());
                   +  - ]
    2655                 :             :                 }
    2656         [ +  + ]:         971 :             } else if (vec.size() != max_providers_len) {
    2657         [ +  - ]:           6 :                 error = strprintf("tr(): Multipath subscripts have mismatched lengths");
    2658                 :           6 :                 return {};
    2659                 :             :             }
    2660                 :             :         }
    2661                 :             : 
    2662   [ -  +  +  +  :        4883 :         if (internal_keys.size() > 1 && internal_keys.size() != max_providers_len) {
                   +  + ]
    2663         [ +  - ]:           4 :             error = strprintf("tr(): Multipath internal key mismatches multipath subscripts lengths");
    2664                 :           4 :             return {};
    2665                 :             :         }
    2666                 :             : 
    2667   [ -  +  +  + ]:       13736 :         while (internal_keys.size() < max_providers_len) {
    2668   [ +  -  +  -  :        8857 :             internal_keys.emplace_back(internal_keys.at(0)->Clone());
                   +  - ]
    2669                 :             :         }
    2670                 :             : 
    2671                 :             :         // Build the final descriptors vector
    2672         [ +  + ]:       28740 :         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                 :       23861 :             std::vector<std::unique_ptr<DescriptorImpl>> this_subs;
    2675   [ -  +  +  - ]:       23861 :             this_subs.reserve(subscripts.size());
    2676         [ +  + ]:       56765 :             for (auto& subs : subscripts) {
    2677   [ +  -  +  - ]:       32904 :                 this_subs.emplace_back(std::move(subs.at(i)));
    2678                 :             :             }
    2679   [ +  -  +  -  :       23861 :             ret.emplace_back(std::make_unique<TRDescriptor>(std::move(internal_keys.at(i)), std::move(this_subs), depths));
                   +  - ]
    2680                 :       23861 :         }
    2681                 :        4879 :         return ret;
    2682                 :             : 
    2683                 :             : 
    2684   [ +  -  +  -  :       24963 :     } else if (Func("tr", expr)) {
                   +  + ]
    2685         [ +  - ]:           5 :         error = "Can only have tr at top level";
    2686                 :           5 :         return {};
    2687                 :             :     }
    2688   [ +  +  +  -  :       24349 :     if (ctx == ParseScriptContext::TOP && Func("rawtr", expr)) {
          +  -  +  +  +  
                      + ]
    2689         [ +  - ]:         290 :         auto arg = Expr(expr);
    2690         [ +  + ]:         290 :         if (expr.size()) {
    2691         [ +  - ]:           5 :             error = strprintf("rawtr(): only one key expected.");
    2692                 :           5 :             return {};
    2693                 :             :         }
    2694         [ +  - ]:         285 :         auto output_keys = ParsePubkey(key_exp_index, arg, ParseScriptContext::P2TR, out, error);
    2695         [ +  + ]:         285 :         if (output_keys.empty()) {
    2696         [ +  - ]:          19 :             error = strprintf("rawtr(): %s", error);
    2697                 :          19 :             return {};
    2698                 :             :         }
    2699         [ +  + ]:         997 :         for (auto& pubkey : output_keys) {
    2700   [ +  -  +  - ]:        1462 :             ret.emplace_back(std::make_unique<RawTRDescriptor>(std::move(pubkey)));
    2701                 :             :         }
    2702                 :         266 :         return ret;
    2703   [ +  -  +  -  :       18885 :     } else if (Func("rawtr", expr)) {
                   +  + ]
    2704         [ +  - ]:           4 :         error = "Can only have rawtr at top level";
    2705                 :           4 :         return {};
    2706                 :             :     }
    2707   [ +  +  +  -  :       23765 :     if (ctx == ParseScriptContext::TOP && Func("unused", expr)) {
          +  -  +  +  +  
                      + ]
    2708                 :             :         // Check for only one expression, should not find commas, brackets, or parentheses
    2709         [ +  - ]:          84 :         auto arg = Expr(expr);
    2710         [ +  + ]:          84 :         if (expr.size()) {
    2711         [ +  - ]:           6 :             error = strprintf("unused(): only one key expected");
    2712                 :           6 :             return {};
    2713                 :             :         }
    2714         [ +  - ]:          78 :         auto keys = ParsePubkey(key_exp_index, arg, ctx, out, error);
    2715         [ +  + ]:          78 :         if (keys.empty()) return {};
    2716         [ +  + ]:         345 :         for (auto& pubkey : keys) {
    2717   [ +  -  +  + ]:         279 :             if (pubkey->IsRange()) {
    2718         [ +  - ]:           4 :                 error = "unused(): key cannot be ranged";
    2719                 :           4 :                 return {};
    2720                 :             :             }
    2721   [ +  -  +  - ]:         550 :             ret.emplace_back(std::make_unique<UnusedDescriptor>(std::move(pubkey)));
    2722                 :             :         }
    2723                 :          66 :         return ret;
    2724   [ +  -  +  -  :       18590 :     } else if (Func("unused", expr)) {
                   +  + ]
    2725         [ +  - ]:           6 :         error = "Can only have unused at top level";
    2726                 :           6 :         return {};
    2727                 :             :     }
    2728   [ +  +  +  -  :       23591 :     if (ctx == ParseScriptContext::TOP && Func("raw", expr)) {
          +  -  +  +  +  
                      + ]
    2729   [ +  -  -  + ]:        5152 :         std::string str(expr.begin(), expr.end());
    2730   [ -  +  +  -  :        2576 :         if (!IsHex(str)) {
                   +  + ]
    2731         [ +  - ]:           7 :             error = "Raw script is not hex";
    2732                 :           7 :             return {};
    2733                 :             :         }
    2734   [ -  +  +  - ]:        2569 :         auto bytes = ParseHex(str);
    2735   [ +  -  +  - ]:        5138 :         ret.emplace_back(std::make_unique<RawDescriptor>(CScript(bytes.begin(), bytes.end())));
    2736                 :        2569 :         return ret;
    2737   [ +  -  +  -  :       21075 :     } else if (Func("raw", expr)) {
                   +  + ]
    2738         [ +  - ]:           4 :         error = "Can only have raw() at top level";
    2739                 :           4 :         return {};
    2740                 :             :     }
    2741                 :             :     // Process miniscript expressions.
    2742                 :       15926 :     {
    2743                 :       15926 :         const auto script_ctx{ctx == ParseScriptContext::P2WSH ? miniscript::MiniscriptContext::P2WSH : miniscript::MiniscriptContext::TAPSCRIPT};
    2744         [ +  - ]:       15926 :         KeyParser parser(/*out = */&out, /* in = */nullptr, /* ctx = */script_ctx, key_exp_index);
    2745   [ +  -  -  + ]:       47778 :         auto node = miniscript::FromString(std::string(expr.begin(), expr.end()), parser);
    2746         [ +  + ]:       15926 :         if (parser.m_key_parsing_error != "") {
    2747                 :         224 :             error = std::move(parser.m_key_parsing_error);
    2748                 :         224 :             return {};
    2749                 :             :         }
    2750         [ +  + ]:       15702 :         if (node) {
    2751         [ +  + ]:       13551 :             if (ctx != ParseScriptContext::P2WSH && ctx != ParseScriptContext::P2TR) {
    2752         [ +  - ]:         710 :                 error = "Miniscript expressions can only be used in wsh or tr.";
    2753                 :         710 :                 return {};
    2754                 :             :             }
    2755   [ +  -  +  +  :       12841 :             if (!node->IsSane() || node->IsNotSatisfiable()) {
                   +  + ]
    2756                 :             :                 // Try to find the first insane sub for better error reporting.
    2757         [ +  - ]:        2115 :                 const auto* insane_node = &node.value();
    2758   [ +  -  +  + ]:        2115 :                 if (const auto sub = node->FindInsaneSub()) insane_node = sub;
    2759         [ +  - ]:        2115 :                 error = *insane_node->ToString(parser);
    2760   [ +  -  +  + ]:        2115 :                 if (!insane_node->IsValid()) {
    2761         [ +  - ]:        1239 :                     error += " is invalid";
    2762   [ +  -  +  + ]:         876 :                 } else if (!node->IsSane()) {
    2763         [ +  - ]:         715 :                     error += " is not sane";
    2764         [ +  + ]:         715 :                     if (!insane_node->IsNonMalleable()) {
    2765         [ +  - ]:         184 :                         error += ": malleable witnesses exist";
    2766   [ +  -  +  +  :         531 :                     } else if (insane_node == &node.value() && !insane_node->NeedsSignature()) {
                   +  + ]
    2767         [ +  - ]:         101 :                         error += ": witnesses without signature exist";
    2768         [ +  + ]:         430 :                     } else if (!insane_node->CheckTimeLocksMix()) {
    2769         [ +  - ]:          47 :                         error += ": contains mixes of timelocks expressed in blocks and seconds";
    2770         [ +  - ]:         383 :                     } else if (!insane_node->CheckDuplicateKey()) {
    2771         [ +  - ]:         260 :                         error += ": contains duplicate public keys";
    2772   [ +  -  +  + ]:         123 :                     } else if (!insane_node->ValidSatisfactions()) {
    2773         [ +  - ]:          36 :                         error += ": needs witnesses that may exceed resource limits";
    2774                 :             :                     }
    2775                 :             :                 } else {
    2776         [ +  - ]:         161 :                     error += " is not satisfiable";
    2777                 :             :                 }
    2778                 :        2115 :                 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         [ +  - ]:       10726 :             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         [ -  + ]:       10726 :             size_t num_multipath = std::max_element(parser.m_keys.begin(), parser.m_keys.end(),
    2786                 :        6691 :                     [](const std::vector<std::unique_ptr<PubkeyProvider>>& a, const std::vector<std::unique_ptr<PubkeyProvider>>& b) {
    2787   [ -  +  -  +  :        6691 :                         return a.size() < b.size();
                   +  + ]
    2788         [ -  + ]:       10726 :                     })->size();
    2789                 :             : 
    2790         [ +  + ]:       28110 :             for (auto& vec : parser.m_keys) {
    2791   [ -  +  +  + ]:       17394 :                 if (vec.size() == 1) {
    2792         [ +  + ]:       34981 :                     for (size_t i = 1; i < num_multipath; ++i) {
    2793   [ +  -  +  -  :       19325 :                         vec.emplace_back(vec.at(0)->Clone());
                   +  - ]
    2794                 :             :                     }
    2795         [ +  + ]:        1738 :                 } else if (vec.size() != num_multipath) {
    2796         [ +  - ]:          10 :                     error = strprintf("Miniscript: Multipath derivation paths have mismatched lengths");
    2797                 :          10 :                     return {};
    2798                 :             :                 }
    2799                 :             :             }
    2800                 :             : 
    2801                 :             :             // Build the final descriptors vector
    2802         [ +  + ]:       34446 :             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                 :       23730 :                 std::vector<std::unique_ptr<PubkeyProvider>> pubs;
    2805   [ -  +  +  - ]:       23730 :                 pubs.reserve(parser.m_keys.size());
    2806         [ +  + ]:       73760 :                 for (auto& pub : parser.m_keys) {
    2807   [ +  -  +  - ]:       50030 :                     pubs.emplace_back(std::move(pub.at(i)));
    2808                 :             :                 }
    2809   [ +  -  +  -  :       47460 :                 ret.emplace_back(std::make_unique<MiniscriptDescriptor>(std::move(pubs), node->Clone()));
                   +  - ]
    2810                 :       23730 :             }
    2811                 :       10716 :             return ret;
    2812                 :             :         }
    2813                 :       29701 :     }
    2814         [ +  + ]:        2151 :     if (ctx == ParseScriptContext::P2SH) {
    2815         [ +  - ]:          22 :         error = "A function is needed within P2SH";
    2816                 :          22 :         return {};
    2817         [ +  + ]:        2129 :     } else if (ctx == ParseScriptContext::P2WSH) {
    2818         [ +  - ]:         274 :         error = "A function is needed within P2WSH";
    2819                 :         274 :         return {};
    2820                 :             :     }
    2821   [ +  -  +  - ]:        3710 :     error = strprintf("'%s' is not a valid descriptor function", std::string(expr.begin(), expr.end()));
    2822                 :        1855 :     return {};
    2823                 :       86029 : }
    2824                 :             : 
    2825                 :       22917 : std::unique_ptr<DescriptorImpl> InferMultiA(const CScript& script, ParseScriptContext ctx, const SigningProvider& provider)
    2826                 :             : {
    2827                 :       22917 :     auto match = MatchMultiA(script);
    2828         [ +  + ]:       22917 :     if (!match) return {};
    2829                 :        5979 :     std::vector<std::unique_ptr<PubkeyProvider>> keys;
    2830   [ -  +  +  - ]:        5979 :     keys.reserve(match->second.size());
    2831         [ +  + ]:      444847 :     for (const auto keyspan : match->second) {
    2832         [ -  + ]:      438868 :         if (keyspan.size() != 32) return {};
    2833         [ +  - ]:      438868 :         auto key = InferXOnlyPubkey(XOnlyPubKey{keyspan}, ctx, provider);
    2834         [ -  + ]:      438868 :         if (!key) return {};
    2835         [ +  - ]:      438868 :         keys.push_back(std::move(key));
    2836                 :      438868 :     }
    2837   [ +  -  -  + ]:        5979 :     return std::make_unique<MultiADescriptor>(match->first, std::move(keys));
    2838                 :       28896 : }
    2839                 :             : 
    2840                 :             : // NOLINTNEXTLINE(misc-no-recursion)
    2841                 :     2046495 : std::unique_ptr<DescriptorImpl> InferScript(const CScript& script, ParseScriptContext ctx, const SigningProvider& provider)
    2842                 :             : {
    2843                 :     2072158 :     if (ctx == ParseScriptContext::P2TR && script.size() == 34 && script[0] == 32 && script[33] == OP_CHECKSIG) {
           [ +  +  +  +  
          +  +  +  -  +  
             +  +  -  +  
                      - ]
    2844                 :        3382 :         XOnlyPubKey key{std::span{script}.subspan(1, 32)};
    2845   [ +  -  -  + ]:        3382 :         return std::make_unique<PKDescriptor>(InferXOnlyPubkey(key, ctx, provider), true);
    2846                 :             :     }
    2847                 :             : 
    2848         [ +  + ]:     2043113 :     if (ctx == ParseScriptContext::P2TR) {
    2849                 :       22917 :         auto ret = InferMultiA(script, ctx, provider);
    2850         [ +  + ]:       22917 :         if (ret) return ret;
    2851                 :       22917 :     }
    2852                 :             : 
    2853                 :     2037134 :     std::vector<std::vector<unsigned char>> data;
    2854         [ +  - ]:     2037134 :     TxoutType txntype = Solver(script, data);
    2855                 :             : 
    2856   [ +  +  +  - ]:     2037134 :     if (txntype == TxoutType::PUBKEY && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
    2857         [ -  + ]:       27453 :         CPubKey pubkey(data[0]);
    2858   [ +  -  +  + ]:       27453 :         if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
    2859   [ +  -  -  + ]:       25132 :             return std::make_unique<PKDescriptor>(std::move(pubkey_provider));
    2860                 :       27453 :         }
    2861                 :             :     }
    2862   [ +  +  +  + ]:     2012002 :     if (txntype == TxoutType::PUBKEYHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
    2863         [ -  + ]:       37951 :         uint160 hash(data[0]);
    2864         [ +  - ]:       37951 :         CKeyID keyid(hash);
    2865         [ +  - ]:       37951 :         CPubKey pubkey;
    2866   [ +  -  +  + ]:       37951 :         if (provider.GetPubKey(keyid, pubkey)) {
    2867   [ +  -  +  + ]:       14691 :             if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
    2868   [ +  -  -  + ]:       14654 :                 return std::make_unique<PKHDescriptor>(std::move(pubkey_provider));
    2869                 :       14691 :             }
    2870                 :             :         }
    2871                 :             :     }
    2872         [ +  + ]:     1997348 :     if (txntype == TxoutType::WITNESS_V0_KEYHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH)) {
    2873         [ -  + ]:      187134 :         uint160 hash(data[0]);
    2874         [ +  - ]:      187134 :         CKeyID keyid(hash);
    2875         [ +  - ]:      187134 :         CPubKey pubkey;
    2876   [ +  -  +  + ]:      187134 :         if (provider.GetPubKey(keyid, pubkey)) {
    2877   [ +  -  +  + ]:      121257 :             if (auto pubkey_provider = InferPubkey(pubkey, ParseScriptContext::P2WPKH, provider)) {
    2878   [ +  -  -  + ]:      121236 :                 return std::make_unique<WPKHDescriptor>(std::move(pubkey_provider));
    2879                 :      121257 :             }
    2880                 :             :         }
    2881                 :             :     }
    2882   [ +  +  +  - ]:     1876112 :     if (txntype == TxoutType::MULTISIG && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
    2883                 :       43627 :         bool ok = true;
    2884                 :       43627 :         std::vector<std::unique_ptr<PubkeyProvider>> providers;
    2885   [ -  +  +  + ]:      290982 :         for (size_t i = 1; i + 1 < data.size(); ++i) {
    2886         [ -  + ]:      250898 :             CPubKey pubkey(data[i]);
    2887   [ +  -  +  + ]:      250898 :             if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
    2888         [ +  - ]:      247355 :                 providers.push_back(std::move(pubkey_provider));
    2889                 :             :             } else {
    2890                 :        3543 :                 ok = false;
    2891                 :        3543 :                 break;
    2892                 :      250898 :             }
    2893                 :             :         }
    2894   [ +  -  -  + ]:       40084 :         if (ok) return std::make_unique<MultisigDescriptor>((int)data[0][0], std::move(providers));
    2895                 :       43627 :     }
    2896         [ +  + ]:     1836028 :     if (txntype == TxoutType::SCRIPTHASH && ctx == ParseScriptContext::TOP) {
    2897         [ -  + ]:      244072 :         uint160 hash(data[0]);
    2898         [ +  - ]:      244072 :         CScriptID scriptid(hash);
    2899                 :      244072 :         CScript subscript;
    2900   [ +  -  +  + ]:      244072 :         if (provider.GetCScript(scriptid, subscript)) {
    2901         [ +  - ]:      115606 :             auto sub = InferScript(subscript, ParseScriptContext::P2SH, provider);
    2902   [ +  +  +  -  :      115606 :             if (sub) return std::make_unique<SHDescriptor>(std::move(sub));
                   -  + ]
    2903                 :      115606 :         }
    2904                 :      244072 :     }
    2905         [ +  + ]:     1724108 :     if (txntype == TxoutType::WITNESS_V0_SCRIPTHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH)) {
    2906   [ -  +  +  - ]:       78171 :         CScriptID scriptid{RIPEMD160(data[0])};
    2907                 :       78171 :         CScript subscript;
    2908   [ +  -  +  + ]:       78171 :         if (provider.GetCScript(scriptid, subscript)) {
    2909         [ +  - ]:       15136 :             auto sub = InferScript(subscript, ParseScriptContext::P2WSH, provider);
    2910   [ +  +  +  -  :       15136 :             if (sub) return std::make_unique<WSHDescriptor>(std::move(sub));
                   -  + ]
    2911                 :       15136 :         }
    2912                 :       78171 :     }
    2913         [ +  + ]:     1710907 :     if (txntype == TxoutType::WITNESS_V1_TAPROOT && ctx == ParseScriptContext::TOP) {
    2914                 :             :         // Extract x-only pubkey from output.
    2915                 :      293425 :         XOnlyPubKey pubkey;
    2916                 :      293425 :         std::copy(data[0].begin(), data[0].end(), pubkey.begin());
    2917                 :             :         // Request spending data.
    2918         [ +  - ]:      293425 :         TaprootSpendData tap;
    2919   [ +  -  +  + ]:      293425 :         if (provider.GetTaprootSpendData(pubkey, tap)) {
    2920                 :             :             // If found, convert it back to tree form.
    2921         [ +  - ]:      280009 :             auto tree = InferTaprootTree(tap, pubkey);
    2922         [ +  + ]:      280009 :             if (tree) {
    2923                 :             :                 // If that works, try to infer subdescriptors for all leaves.
    2924                 :      279960 :                 bool ok = true;
    2925                 :      279960 :                 std::vector<std::unique_ptr<DescriptorImpl>> subscripts; //!< list of script subexpressions
    2926                 :      279960 :                 std::vector<int> depths; //!< depth in the tree of each subexpression (same length subscripts)
    2927   [ +  -  +  + ]:      306205 :                 for (const auto& [depth, script, leaf_ver] : *tree) {
    2928                 :       26299 :                     std::unique_ptr<DescriptorImpl> subdesc;
    2929         [ +  - ]:       26299 :                     if (leaf_ver == TAPROOT_LEAF_TAPSCRIPT) {
    2930         [ +  - ]:       52598 :                         subdesc = InferScript(CScript(script.begin(), script.end()), ParseScriptContext::P2TR, provider);
    2931                 :             :                     }
    2932         [ +  + ]:       26299 :                     if (!subdesc) {
    2933                 :          54 :                         ok = false;
    2934                 :          54 :                         break;
    2935                 :             :                     } else {
    2936         [ +  - ]:       26245 :                         subscripts.push_back(std::move(subdesc));
    2937         [ +  - ]:       26245 :                         depths.push_back(depth);
    2938                 :             :                     }
    2939                 :       26299 :                 }
    2940                 :          54 :                 if (ok) {
    2941         [ +  - ]:      279906 :                     auto key = InferXOnlyPubkey(tap.internal_key, ParseScriptContext::P2TR, provider);
    2942   [ +  -  -  + ]:      279906 :                     return std::make_unique<TRDescriptor>(std::move(key), std::move(subscripts), std::move(depths));
    2943                 :      279906 :                 }
    2944                 :      279960 :             }
    2945                 :      280009 :         }
    2946                 :             :         // If the above doesn't work, construct a rawtr() descriptor with just the encoded x-only pubkey.
    2947   [ +  -  +  + ]:       13519 :         if (pubkey.IsFullyValid()) {
    2948         [ +  - ]:        8433 :             auto key = InferXOnlyPubkey(pubkey, ParseScriptContext::P2TR, provider);
    2949         [ +  - ]:        8433 :             if (key) {
    2950   [ +  -  -  + ]:        8433 :                 return std::make_unique<RawTRDescriptor>(std::move(key));
    2951                 :             :             }
    2952                 :        8433 :         }
    2953                 :      293425 :     }
    2954                 :             : 
    2955         [ +  + ]:     1422568 :     if (ctx == ParseScriptContext::P2WSH || ctx == ParseScriptContext::P2TR) {
    2956                 :       24292 :         const auto script_ctx{ctx == ParseScriptContext::P2WSH ? miniscript::MiniscriptContext::P2WSH : miniscript::MiniscriptContext::TAPSCRIPT};
    2957                 :       24292 :         uint32_t key_exp_index = 0;
    2958         [ +  - ]:       24292 :         KeyParser parser(/* out = */nullptr, /* in = */&provider, /* ctx = */script_ctx, key_exp_index);
    2959         [ +  - ]:       24292 :         auto node = miniscript::FromScript(script, parser);
    2960   [ +  +  +  -  :       24292 :         if (node && node->IsSane()) {
                   +  + ]
    2961                 :       22303 :             std::vector<std::unique_ptr<PubkeyProvider>> keys;
    2962   [ -  +  +  - ]:       22303 :             keys.reserve(parser.m_keys.size());
    2963         [ +  + ]:       66398 :             for (auto& key : parser.m_keys) {
    2964   [ +  -  +  - ]:       44095 :                 keys.emplace_back(std::move(key.at(0)));
    2965                 :             :             }
    2966   [ +  -  -  + ]:       22303 :             return std::make_unique<MiniscriptDescriptor>(std::move(keys), std::move(*node));
    2967                 :       22303 :         }
    2968                 :       48584 :     }
    2969                 :             : 
    2970                 :             :     // The following descriptors are all top-level only descriptors.
    2971                 :             :     // So if we are not at the top level, return early.
    2972         [ +  + ]:     1400265 :     if (ctx != ParseScriptContext::TOP) return nullptr;
    2973                 :             : 
    2974                 :     1394590 :     CTxDestination dest;
    2975   [ +  -  +  + ]:     1394590 :     if (ExtractDestination(script, dest)) {
    2976   [ +  -  +  - ]:      319584 :         if (GetScriptForDestination(dest) == script) {
    2977   [ +  -  -  + ]:      319584 :             return std::make_unique<AddressDescriptor>(std::move(dest));
    2978                 :             :         }
    2979                 :             :     }
    2980                 :             : 
    2981   [ +  -  -  + ]:     1075006 :     return std::make_unique<RawDescriptor>(script);
    2982                 :     2037134 : }
    2983                 :             : 
    2984                 :             : 
    2985                 :             : } // namespace
    2986                 :             : 
    2987                 :             : /** Check a descriptor checksum, and update desc to be the checksum-less part. */
    2988                 :       52797 : bool CheckChecksum(std::span<const char>& sp, bool require_checksum, std::string& error, std::string* out_checksum = nullptr)
    2989                 :             : {
    2990                 :       52797 :     auto check_split = Split(sp, '#');
    2991   [ -  +  +  + ]:       52797 :     if (check_split.size() > 2) {
    2992         [ +  - ]:          12 :         error = "Multiple '#' symbols";
    2993                 :             :         return false;
    2994                 :             :     }
    2995   [ +  +  +  + ]:       52785 :     if (check_split.size() == 1 && require_checksum){
    2996         [ +  - ]:       52797 :         error = "Missing checksum";
    2997                 :             :         return false;
    2998                 :             :     }
    2999         [ +  + ]:       49133 :     if (check_split.size() == 2) {
    3000         [ +  + ]:       16762 :         if (check_split[1].size() != 8) {
    3001         [ +  - ]:          18 :             error = strprintf("Expected 8 character checksum, not %u characters", check_split[1].size());
    3002                 :          18 :             return false;
    3003                 :             :         }
    3004                 :             :     }
    3005         [ +  - ]:       49115 :     auto checksum = DescriptorChecksum(check_split[0]);
    3006         [ +  + ]:       49115 :     if (checksum.empty()) {
    3007         [ +  - ]:       49115 :         error = "Invalid characters in payload";
    3008                 :             :         return false;
    3009                 :             :     }
    3010   [ -  +  +  + ]:       49071 :     if (check_split.size() == 2) {
    3011   [ -  +  +  + ]:       16740 :         if (!std::equal(checksum.begin(), checksum.end(), check_split[1].begin())) {
    3012   [ +  -  +  - ]:          28 :             error = strprintf("Provided checksum '%s' does not match computed checksum '%s'", std::string(check_split[1].begin(), check_split[1].end()), checksum);
    3013                 :          14 :             return false;
    3014                 :             :         }
    3015                 :             :     }
    3016         [ +  + ]:       49057 :     if (out_checksum) *out_checksum = std::move(checksum);
    3017                 :       49057 :     sp = check_split[0];
    3018                 :       49057 :     return true;
    3019                 :      101912 : }
    3020                 :             : 
    3021                 :       52792 : std::vector<std::unique_ptr<Descriptor>> Parse(std::string_view descriptor, FlatSigningProvider& out, std::string& error, bool require_checksum)
    3022                 :             : {
    3023                 :       52792 :     std::span<const char> sp{descriptor};
    3024         [ +  + ]:       52792 :     if (!CheckChecksum(sp, require_checksum, error)) return {};
    3025                 :       49052 :     uint32_t key_exp_index = 0;
    3026                 :       49052 :     auto ret = ParseScript(key_exp_index, sp, ParseScriptContext::TOP, out, error);
    3027   [ +  +  +  + ]:       49052 :     if (sp.empty() && !ret.empty()) {
    3028                 :       41737 :         std::vector<std::unique_ptr<Descriptor>> descs;
    3029   [ -  +  +  - ]:       41737 :         descs.reserve(ret.size());
    3030         [ +  + ]:      111896 :         for (auto& r : ret) {
    3031         [ +  - ]:       70159 :             descs.emplace_back(std::unique_ptr<Descriptor>(std::move(r)));
    3032                 :             :         }
    3033                 :       41737 :         return descs;
    3034                 :       41737 :     }
    3035                 :        7315 :     return {};
    3036                 :       49052 : }
    3037                 :             : 
    3038                 :           5 : std::string GetDescriptorChecksum(const std::string& descriptor)
    3039                 :             : {
    3040         [ -  + ]:           5 :     std::string ret;
    3041                 :           5 :     std::string error;
    3042         [ -  + ]:           5 :     std::span<const char> sp{descriptor};
    3043   [ +  -  -  +  :           5 :     if (!CheckChecksum(sp, false, error, &ret)) return "";
                   -  - ]
    3044                 :           5 :     return ret;
    3045                 :           5 : }
    3046                 :             : 
    3047                 :     1889454 : std::unique_ptr<Descriptor> InferDescriptor(const CScript& script, const SigningProvider& provider)
    3048                 :             : {
    3049                 :     1889454 :     return InferScript(script, ParseScriptContext::TOP, provider);
    3050                 :             : }
    3051                 :             : 
    3052                 :       23057 : uint256 CompatDescriptorHash(const Descriptor& desc)
    3053                 :             : {
    3054                 :       23057 :     std::string desc_str = desc.ToString(/*compat_format=*/true);
    3055                 :       23057 :     uint256 id;
    3056   [ +  -  +  -  :       46114 :     CSHA256().Write((unsigned char*)desc_str.data(), desc_str.size()).Finalize(id.begin());
                   +  - ]
    3057                 :       23057 :     return id;
    3058                 :       23057 : }
    3059                 :             : 
    3060                 :     2063020 : void DescriptorCache::CacheParentExtPubKey(uint32_t key_exp_pos, const CExtPubKey& xpub)
    3061                 :             : {
    3062                 :     2063020 :     m_parent_xpubs[key_exp_pos] = xpub;
    3063                 :     2063020 : }
    3064                 :             : 
    3065                 :      195262 : void DescriptorCache::CacheDerivedExtPubKey(uint32_t key_exp_pos, uint32_t der_index, const CExtPubKey& xpub)
    3066                 :             : {
    3067                 :      195262 :     auto& xpubs = m_derived_xpubs[key_exp_pos];
    3068                 :      195262 :     xpubs[der_index] = xpub;
    3069                 :      195262 : }
    3070                 :             : 
    3071                 :      825105 : void DescriptorCache::CacheLastHardenedExtPubKey(uint32_t key_exp_pos, const CExtPubKey& xpub)
    3072                 :             : {
    3073                 :      825105 :     m_last_hardened_xpubs[key_exp_pos] = xpub;
    3074                 :      825105 : }
    3075                 :             : 
    3076                 :     1951228 : bool DescriptorCache::GetCachedParentExtPubKey(uint32_t key_exp_pos, CExtPubKey& xpub) const
    3077                 :             : {
    3078                 :     1951228 :     const auto& it = m_parent_xpubs.find(key_exp_pos);
    3079         [ +  + ]:     1951228 :     if (it == m_parent_xpubs.end()) return false;
    3080                 :     1896857 :     xpub = it->second;
    3081                 :     1896857 :     return true;
    3082                 :             : }
    3083                 :             : 
    3084                 :     1727424 : bool DescriptorCache::GetCachedDerivedExtPubKey(uint32_t key_exp_pos, uint32_t der_index, CExtPubKey& xpub) const
    3085                 :             : {
    3086                 :     1727424 :     const auto& key_exp_it = m_derived_xpubs.find(key_exp_pos);
    3087         [ +  + ]:     1727424 :     if (key_exp_it == m_derived_xpubs.end()) return false;
    3088                 :      167629 :     const auto& der_it = key_exp_it->second.find(der_index);
    3089         [ +  + ]:      167629 :     if (der_it == key_exp_it->second.end()) return false;
    3090                 :      111878 :     xpub = der_it->second;
    3091                 :      111878 :     return true;
    3092                 :             : }
    3093                 :             : 
    3094                 :       20835 : bool DescriptorCache::GetCachedLastHardenedExtPubKey(uint32_t key_exp_pos, CExtPubKey& xpub) const
    3095                 :             : {
    3096                 :       20835 :     const auto& it = m_last_hardened_xpubs.find(key_exp_pos);
    3097         [ +  + ]:       20835 :     if (it == m_last_hardened_xpubs.end()) return false;
    3098                 :       17044 :     xpub = it->second;
    3099                 :       17044 :     return true;
    3100                 :             : }
    3101                 :             : 
    3102                 :       35974 : DescriptorCache DescriptorCache::MergeAndDiff(const DescriptorCache& other)
    3103                 :             : {
    3104                 :       35974 :     DescriptorCache diff;
    3105   [ +  -  +  +  :      328183 :     for (const auto& parent_xpub_pair : other.GetCachedParentExtPubKeys()) {
                   +  - ]
    3106         [ +  - ]:      292209 :         CExtPubKey xpub;
    3107   [ +  +  +  - ]:      292209 :         if (GetCachedParentExtPubKey(parent_xpub_pair.first, xpub)) {
    3108         [ -  + ]:      254435 :             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                 :      254435 :             continue;
    3112                 :             :         }
    3113         [ +  - ]:       37774 :         CacheParentExtPubKey(parent_xpub_pair.first, parent_xpub_pair.second);
    3114         [ +  - ]:       37774 :         diff.CacheParentExtPubKey(parent_xpub_pair.first, parent_xpub_pair.second);
    3115                 :      292209 :     }
    3116   [ +  -  +  + ]:       85862 :     for (const auto& derived_xpub_map_pair : other.GetCachedDerivedExtPubKeys()) {
    3117   [ +  +  +  - ]:       99776 :         for (const auto& derived_xpub_pair : derived_xpub_map_pair.second) {
    3118         [ +  - ]:       49888 :             CExtPubKey xpub;
    3119   [ -  +  +  - ]:       49888 :             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         [ +  - ]:       49888 :             CacheDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, derived_xpub_pair.second);
    3126         [ +  - ]:       49888 :             diff.CacheDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, derived_xpub_pair.second);
    3127                 :       49888 :         }
    3128                 :             :     }
    3129   [ +  -  +  +  :       53282 :     for (const auto& lh_xpub_pair : other.GetCachedLastHardenedExtPubKeys()) {
                   +  - ]
    3130         [ +  - ]:       17308 :         CExtPubKey xpub;
    3131   [ +  +  +  - ]:       17308 :         if (GetCachedLastHardenedExtPubKey(lh_xpub_pair.first, xpub)) {
    3132         [ -  + ]:       13517 :             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                 :       13517 :             continue;
    3136                 :             :         }
    3137         [ +  - ]:        3791 :         CacheLastHardenedExtPubKey(lh_xpub_pair.first, lh_xpub_pair.second);
    3138         [ +  - ]:        3791 :         diff.CacheLastHardenedExtPubKey(lh_xpub_pair.first, lh_xpub_pair.second);
    3139                 :       17308 :     }
    3140                 :       35974 :     return diff;
    3141                 :           0 : }
    3142                 :             : 
    3143                 :      138937 : ExtPubKeyMap DescriptorCache::GetCachedParentExtPubKeys() const
    3144                 :             : {
    3145                 :      138937 :     return m_parent_xpubs;
    3146                 :             : }
    3147                 :             : 
    3148                 :      138937 : std::unordered_map<uint32_t, ExtPubKeyMap> DescriptorCache::GetCachedDerivedExtPubKeys() const
    3149                 :             : {
    3150                 :      138937 :     return m_derived_xpubs;
    3151                 :             : }
    3152                 :             : 
    3153                 :       80039 : ExtPubKeyMap DescriptorCache::GetCachedLastHardenedExtPubKeys() const
    3154                 :             : {
    3155                 :       80039 :     return m_last_hardened_xpubs;
    3156                 :             : }
        

Generated by: LCOV version 2.5.0-full