LCOV - code coverage report
Current view: top level - src/script - descriptor.cpp (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 82.0 % 1660 1361
Test Date: 2025-08-01 04:15:35 Functions: 80.7 % 223 180
Branches: 57.4 % 2730 1566

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

Generated by: LCOV version 2.0-1