LCOV - code coverage report
Current view: top level - src/script - descriptor.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 92.0 % 1654 1521
Test Date: 2025-10-22 05:06:52 Functions: 87.0 % 223 194
Branches: 61.9 % 2893 1792

             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                 :   349589579 : uint64_t PolyMod(uint64_t c, int val)
      95                 :             : {
      96                 :   349589579 :     uint8_t c0 = c >> 35;
      97                 :   349589579 :     c = ((c & 0x7ffffffff) << 5) ^ val;
      98         [ +  + ]:   349589579 :     if (c0 & 1) c ^= 0xf5dee51989;
      99         [ +  + ]:   349589579 :     if (c0 & 2) c ^= 0xa9fdca3312;
     100         [ +  + ]:   349589579 :     if (c0 & 4) c ^= 0x1bab10e32d;
     101         [ +  + ]:   349589579 :     if (c0 & 8) c ^= 0x3706b1677a;
     102         [ +  + ]:   349589579 :     if (c0 & 16) c ^= 0x644d626ffd;
     103                 :   349589579 :     return c;
     104                 :             : }
     105                 :             : 
     106                 :      286436 : 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                 :      286436 :     static const std::string INPUT_CHARSET =
     122                 :             :         "0123456789()[],'/*abcdefgh@:$%{}"
     123                 :             :         "IJKLMNOPQRSTUVWXYZ&+-.;<=>?!^_|~"
     124   [ +  +  +  -  :      286927 :         "ijklmnopqrstuvwxyzABCDEFGH`#\"\\ ";
                   +  - ]
     125                 :             : 
     126                 :             :     /** The character set for the checksum itself (same as bech32). */
     127   [ +  +  +  -  :      286927 :     static const std::string CHECKSUM_CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
                   +  - ]
     128                 :             : 
     129                 :      286436 :     uint64_t c = 1;
     130                 :      286436 :     int cls = 0;
     131                 :      286436 :     int clscount = 0;
     132         [ +  + ]:   260676358 :     for (auto ch : span) {
     133                 :   260389923 :         auto pos = INPUT_CHARSET.find(ch);
     134         [ +  + ]:   260389923 :         if (pos == std::string::npos) return "";
     135                 :   260389922 :         c = PolyMod(c, pos & 31); // Emit a symbol for the position inside the group, for every character.
     136                 :   260389922 :         cls = cls * 3 + (pos >> 5); // Accumulate the group numbers
     137         [ +  + ]:   260389922 :         if (++clscount == 3) {
     138                 :             :             // Emit an extra symbol representing the group numbers, for every 3 characters.
     139                 :    86679638 :             c = PolyMod(c, cls);
     140                 :    86679638 :             cls = 0;
     141                 :    86679638 :             clscount = 0;
     142                 :             :         }
     143                 :             :     }
     144         [ +  + ]:      286435 :     if (clscount > 0) c = PolyMod(c, cls);
     145         [ +  + ]:     2577915 :     for (int j = 0; j < 8; ++j) c = PolyMod(c, 0); // Shift further to determine the checksum.
     146                 :      286435 :     c ^= 1; // Prevent appending zeroes from not affecting the checksum.
     147                 :             : 
     148                 :      286435 :     std::string ret(8, ' ');
     149         [ +  + ]:     2577915 :     for (int j = 0; j < 8; ++j) ret[j] = CHECKSUM_CHARSET[(c >> (5 * (7 - j))) & 31];
     150                 :      286435 :     return ret;
     151                 :      286435 : }
     152                 :             : 
     153   [ -  +  +  -  :      551814 : 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                 :      926842 :     explicit PubkeyProvider(uint32_t exp_index) : m_expr_index(exp_index) {}
     171                 :             : 
     172                 :         278 :     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                 :        4229 :     bool operator<(PubkeyProvider& other) const {
     178                 :        4229 :         FlatSigningProvider dummy;
     179                 :             : 
     180         [ +  - ]:        4229 :         std::optional<CPubKey> a = GetPubKey(0, dummy, dummy);
     181         [ +  - ]:        4229 :         std::optional<CPubKey> b = other.GetPubKey(0, dummy, dummy);
     182                 :             : 
     183                 :        4229 :         return a < b;
     184                 :        4229 :     }
     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                 :      116019 :     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   [ +  +  +  +  :      116019 :         bool use_apostrophe = (!normalized && m_apostrophe) || type == StringType::COMPAT;
                   +  + ]
     240   [ +  -  +  - ]:      232038 :         return HexStr(m_origin.fingerprint) + FormatHDKeypath(m_origin.path, use_apostrophe);
     241                 :             :     }
     242                 :             : 
     243                 :             : public:
     244                 :      442896 :     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                 :       64106 :     std::optional<CPubKey> GetPubKey(int pos, const SigningProvider& arg, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
     246                 :             :     {
     247                 :       64106 :         std::optional<CPubKey> pub = m_provider->GetPubKey(pos, arg, out, read_cache, write_cache);
     248         [ +  + ]:       64106 :         if (!pub) return std::nullopt;
     249                 :       63970 :         Assert(out.pubkeys.contains(pub->GetID()));
     250                 :       63970 :         auto& [pubkey, suborigin] = out.origins[pub->GetID()];
     251                 :       63970 :         Assert(pubkey == *pub); // m_provider must have a valid origin by this point.
     252                 :       63970 :         std::copy(std::begin(m_origin.fingerprint), std::end(m_origin.fingerprint), suborigin.fingerprint);
     253                 :       63970 :         suborigin.path.insert(suborigin.path.begin(), m_origin.path.begin(), m_origin.path.end());
     254                 :       63970 :         return pub;
     255                 :             :     }
     256                 :       10286 :     bool IsRange() const override { return m_provider->IsRange(); }
     257                 :       60531 :     size_t GetSize() const override { return m_provider->GetSize(); }
     258                 :         126 :     bool IsBIP32() const override { return m_provider->IsBIP32(); }
     259   [ +  -  +  -  :      346860 :     std::string ToString(StringType type) const override { return "[" + OriginString(type) + "]" + m_provider->ToString(type); }
                   +  - ]
     260                 :         114 :     bool ToPrivateString(const SigningProvider& arg, std::string& ret) const override
     261                 :             :     {
     262         [ +  - ]:         114 :         std::string sub;
     263   [ +  -  +  + ]:         114 :         if (!m_provider->ToPrivateString(arg, sub)) return false;
     264   [ +  -  +  -  :         138 :         ret = "[" + OriginString(StringType::PUBLIC) + "]" + std::move(sub);
                   +  - ]
     265                 :          69 :         return true;
     266                 :         114 :     }
     267                 :         330 :     bool ToNormalizedString(const SigningProvider& arg, std::string& ret, const DescriptorCache* cache) const override
     268                 :             :     {
     269         [ +  - ]:         330 :         std::string sub;
     270   [ +  -  +  - ]:         330 :         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         [ +  + ]:         330 :         if (sub[0] == '[') {
     275         [ +  - ]:           4 :             sub = sub.substr(9);
     276   [ +  -  +  -  :           4 :             ret = "[" + OriginString(StringType::PUBLIC, /*normalized=*/true) + std::move(sub);
                   +  - ]
     277                 :             :         } else {
     278   [ +  -  +  -  :         652 :             ret = "[" + OriginString(StringType::PUBLIC, /*normalized=*/true) + "]" + std::move(sub);
                   +  - ]
     279                 :             :         }
     280                 :             :         return true;
     281                 :         330 :     }
     282                 :        1638 :     void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const override
     283                 :             :     {
     284                 :        1638 :         m_provider->GetPrivKey(pos, arg, out);
     285                 :        1638 :     }
     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                 :          86 :     std::unique_ptr<PubkeyProvider> Clone() const override
     295                 :             :     {
     296   [ +  -  -  + ]:          86 :         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                 :         278 : class ConstPubkeyProvider final : public PubkeyProvider
     302                 :             : {
     303                 :             :     CPubKey m_pubkey;
     304                 :             :     bool m_xonly;
     305                 :             : 
     306                 :       60110 :     std::optional<CKey> GetPrivKey(const SigningProvider& arg) const
     307                 :             :     {
     308                 :       60110 :         CKey key;
     309   [ +  +  +  -  :       66026 :         if (!(m_xonly ? arg.GetKeyByXOnly(XOnlyPubKey(m_pubkey), key) :
                   +  + ]
     310   [ +  -  +  - ]:       60253 :                         arg.GetKey(m_pubkey.GetID(), key))) return std::nullopt;
     311                 :        5773 :         return key;
     312                 :       60110 :     }
     313                 :             : 
     314                 :             : public:
     315                 :      475302 :     ConstPubkeyProvider(uint32_t exp_index, const CPubKey& pubkey, bool xonly) : PubkeyProvider(exp_index), m_pubkey(pubkey), m_xonly(xonly) {}
     316                 :     1011721 :     std::optional<CPubKey> GetPubKey(int pos, const SigningProvider&, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
     317                 :             :     {
     318         [ +  - ]:     1011721 :         KeyOriginInfo info;
     319         [ +  - ]:     1011721 :         CKeyID keyid = m_pubkey.GetID();
     320                 :     1011721 :         std::copy(keyid.begin(), keyid.begin() + sizeof(info.fingerprint), info.fingerprint);
     321   [ +  -  +  - ]:     1011721 :         out.origins.emplace(keyid, std::make_pair(m_pubkey, info));
     322         [ +  - ]:     1011721 :         out.pubkeys.emplace(keyid, m_pubkey);
     323                 :     1011721 :         return m_pubkey;
     324                 :     1011721 :     }
     325                 :       24370 :     bool IsRange() const override { return false; }
     326                 :       74941 :     size_t GetSize() const override { return m_pubkey.size(); }
     327                 :           8 :     bool IsBIP32() const override { return false; }
     328   [ +  +  +  - ]:      391932 :     std::string ToString(StringType type) const override { return m_xonly ? HexStr(m_pubkey).substr(2) : HexStr(m_pubkey); }
     329                 :         309 :     bool ToPrivateString(const SigningProvider& arg, std::string& ret) const override
     330                 :             :     {
     331                 :         309 :         std::optional<CKey> key = GetPrivKey(arg);
     332         [ +  + ]:         309 :         if (!key) return false;
     333         [ +  - ]:         206 :         ret = EncodeSecret(*key);
     334                 :         206 :         return true;
     335                 :         309 :     }
     336                 :       10039 :     bool ToNormalizedString(const SigningProvider& arg, std::string& ret, const DescriptorCache* cache) const override
     337                 :             :     {
     338                 :       10039 :         ret = ToString(StringType::PUBLIC);
     339                 :       10039 :         return true;
     340                 :             :     }
     341                 :       59801 :     void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const override
     342                 :             :     {
     343                 :       59801 :         std::optional<CKey> key = GetPrivKey(arg);
     344         [ +  + ]:       59801 :         if (!key) return;
     345   [ +  -  +  -  :        5567 :         out.keys.emplace(key->GetPubKey().GetID(), *key);
                   +  - ]
     346                 :       59801 :     }
     347                 :           9 :     std::optional<CPubKey> GetRootPubKey() const override
     348                 :             :     {
     349                 :           9 :         return m_pubkey;
     350                 :             :     }
     351                 :           9 :     std::optional<CExtPubKey> GetRootExtPubKey() const override
     352                 :             :     {
     353                 :           9 :         return std::nullopt;
     354                 :             :     }
     355                 :          15 :     std::unique_ptr<PubkeyProvider> Clone() const override
     356                 :             :     {
     357                 :          15 :         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                 :       36415 :     bool GetExtKey(const SigningProvider& arg, CExtKey& ret) const
     378                 :             :     {
     379                 :       36415 :         CKey key;
     380   [ +  -  +  -  :       36415 :         if (!arg.GetKey(m_root_extkey.pubkey.GetID(), key)) return false;
                   +  + ]
     381                 :       33334 :         ret.nDepth = m_root_extkey.nDepth;
     382                 :       33334 :         std::copy(m_root_extkey.vchFingerprint, m_root_extkey.vchFingerprint + sizeof(ret.vchFingerprint), ret.vchFingerprint);
     383                 :       33334 :         ret.nChild = m_root_extkey.nChild;
     384                 :       33334 :         ret.chaincode = m_root_extkey.chaincode;
     385         [ +  - ]:       33334 :         ret.key = key;
     386                 :             :         return true;
     387                 :       36415 :     }
     388                 :             : 
     389                 :             :     // Derives the last xprv
     390                 :       35420 :     bool GetDerivedExtKey(const SigningProvider& arg, CExtKey& xprv, CExtKey& last_hardened) const
     391                 :             :     {
     392         [ +  + ]:       35420 :         if (!GetExtKey(arg, xprv)) return false;
     393         [ +  + ]:      105421 :         for (auto entry : m_path) {
     394         [ +  - ]:       72865 :             if (!xprv.Derive(xprv, entry)) return false;
     395         [ +  + ]:       72865 :             if (entry >> 31) {
     396                 :       56824 :                 last_hardened = xprv;
     397                 :             :             }
     398                 :             :         }
     399                 :             :         return true;
     400                 :             :     }
     401                 :             : 
     402                 :       38014 :     bool IsHardened() const
     403                 :             :     {
     404         [ +  + ]:       38014 :         if (m_derive == DeriveType::HARDENED) return true;
     405         [ +  + ]:       39486 :         for (auto entry : m_path) {
     406         [ +  + ]:       26184 :             if (entry >> 31) return true;
     407                 :             :         }
     408                 :             :         return false;
     409                 :             :     }
     410                 :             : 
     411                 :             : public:
     412                 :        8435 :     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                 :      230311 :     bool IsRange() const override { return m_derive != DeriveType::NO; }
     414                 :         580 :     size_t GetSize() const override { return 33; }
     415                 :         287 :     bool IsBIP32() const override { return true; }
     416                 :      700176 :     std::optional<CPubKey> GetPubKey(int pos, const SigningProvider& arg, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
     417                 :             :     {
     418         [ +  - ]:      700176 :         KeyOriginInfo info;
     419         [ +  - ]:      700176 :         CKeyID keyid = m_root_extkey.pubkey.GetID();
     420                 :      700176 :         std::copy(keyid.begin(), keyid.begin() + sizeof(info.fingerprint), info.fingerprint);
     421         [ +  - ]:      700176 :         info.path = m_path;
     422   [ +  +  +  - ]:      700176 :         if (m_derive == DeriveType::UNHARDENED) info.path.push_back((uint32_t)pos);
     423   [ +  +  +  - ]:      700176 :         if (m_derive == DeriveType::HARDENED) info.path.push_back(((uint32_t)pos) | 0x80000000L);
     424                 :             : 
     425                 :             :         // Derive keys or fetch them from cache
     426                 :      700176 :         CExtPubKey final_extkey = m_root_extkey;
     427                 :      700176 :         CExtPubKey parent_extkey = m_root_extkey;
     428         [ +  + ]:      700176 :         CExtPubKey last_hardened_extkey;
     429                 :      700176 :         bool der = true;
     430         [ +  + ]:      700176 :         if (read_cache) {
     431   [ +  -  +  + ]:      662162 :             if (!read_cache->GetCachedDerivedExtPubKey(m_expr_index, pos, final_extkey)) {
     432         [ +  + ]:      657782 :                 if (m_derive == DeriveType::HARDENED) return std::nullopt;
     433                 :             :                 // Try to get the derivation parent
     434   [ +  -  +  + ]:      647662 :                 if (!read_cache->GetCachedParentExtPubKey(m_expr_index, parent_extkey)) return std::nullopt;
     435                 :      643706 :                 final_extkey = parent_extkey;
     436   [ +  +  +  - ]:      643706 :                 if (m_derive == DeriveType::UNHARDENED) der = parent_extkey.Derive(final_extkey, pos);
     437                 :             :             }
     438         [ +  + ]:       38014 :         } else if (IsHardened()) {
     439         [ +  - ]:       24712 :             CExtKey xprv;
     440                 :       24712 :             CExtKey lh_xprv;
     441   [ +  -  +  + ]:       24712 :             if (!GetDerivedExtKey(arg, xprv, lh_xprv)) return std::nullopt;
     442         [ +  - ]:       24593 :             parent_extkey = xprv.Neuter();
     443   [ +  +  +  - ]:       24593 :             if (m_derive == DeriveType::UNHARDENED) der = xprv.Derive(xprv, pos);
     444   [ +  +  +  - ]:       24593 :             if (m_derive == DeriveType::HARDENED) der = xprv.Derive(xprv, pos | 0x80000000UL);
     445         [ +  - ]:       24593 :             final_extkey = xprv.Neuter();
     446         [ +  + ]:       24593 :             if (lh_xprv.key.IsValid()) {
     447         [ +  - ]:       21562 :                 last_hardened_extkey = lh_xprv.Neuter();
     448                 :             :             }
     449                 :       24712 :         } else {
     450         [ +  + ]:       30939 :             for (auto entry : m_path) {
     451   [ +  -  -  + ]:       17637 :                 if (!parent_extkey.Derive(parent_extkey, entry)) return std::nullopt;
     452                 :             :             }
     453                 :       13302 :             final_extkey = parent_extkey;
     454   [ +  +  +  - ]:       13302 :             if (m_derive == DeriveType::UNHARDENED) der = parent_extkey.Derive(final_extkey, pos);
     455         [ -  + ]:       13302 :             assert(m_derive != DeriveType::HARDENED);
     456                 :             :         }
     457         [ -  + ]:      679736 :         if (!der) return std::nullopt;
     458                 :             : 
     459   [ +  -  +  -  :      685981 :         out.origins.emplace(final_extkey.pubkey.GetID(), std::make_pair(final_extkey.pubkey, info));
                   +  - ]
     460   [ +  -  +  - ]:      685981 :         out.pubkeys.emplace(final_extkey.pubkey.GetID(), final_extkey.pubkey);
     461                 :             : 
     462         [ +  + ]:      685981 :         if (write_cache) {
     463                 :             :             // Only cache parent if there is any unhardened derivation
     464         [ +  + ]:       15768 :             if (m_derive != DeriveType::HARDENED) {
     465         [ +  - ]:        5727 :                 write_cache->CacheParentExtPubKey(m_expr_index, parent_extkey);
     466                 :             :                 // Cache last hardened xpub if we have it
     467         [ +  + ]:        5727 :                 if (last_hardened_extkey.pubkey.IsValid()) {
     468         [ +  - ]:        3692 :                     write_cache->CacheLastHardenedExtPubKey(m_expr_index, last_hardened_extkey);
     469                 :             :                 }
     470   [ -  +  +  - ]:       10041 :             } else if (info.path.size() > 0) {
     471         [ +  - ]:       10041 :                 write_cache->CacheDerivedExtPubKey(m_expr_index, pos, final_extkey);
     472                 :             :             }
     473                 :             :         }
     474                 :             : 
     475                 :      685981 :         return final_extkey.pubkey;
     476                 :      700176 :     }
     477                 :      101215 :     std::string ToString(StringType type, bool normalized) const
     478                 :             :     {
     479                 :             :         // If StringType==COMPAT, always use the apostrophe to stay compatible with previous versions
     480   [ +  +  +  +  :      101215 :         const bool use_apostrophe = (!normalized && m_apostrophe) || type == StringType::COMPAT;
                   +  + ]
     481   [ +  -  +  - ]:      202430 :         std::string ret = EncodeExtPubKey(m_root_extkey) + FormatHDKeypath(m_path, /*apostrophe=*/use_apostrophe);
     482         [ +  + ]:      101215 :         if (IsRange()) {
     483         [ +  - ]:       98048 :             ret += "/*";
     484   [ +  +  +  + ]:       98048 :             if (m_derive == DeriveType::HARDENED) ret += use_apostrophe ? '\'' : 'h';
     485                 :             :         }
     486                 :      101215 :         return ret;
     487                 :           0 :     }
     488                 :      101164 :     std::string ToString(StringType type=StringType::PUBLIC) const override
     489                 :             :     {
     490                 :      100475 :         return ToString(type, /*normalized=*/false);
     491                 :             :     }
     492                 :         995 :     bool ToPrivateString(const SigningProvider& arg, std::string& out) const override
     493                 :             :     {
     494         [ +  - ]:         995 :         CExtKey key;
     495   [ +  -  +  + ]:         995 :         if (!GetExtKey(arg, key)) return false;
     496   [ +  -  +  -  :         778 :         out = EncodeExtKey(key) + FormatHDKeypath(m_path, /*apostrophe=*/m_apostrophe);
                   +  - ]
     497         [ +  + ]:         778 :         if (IsRange()) {
     498         [ +  - ]:         590 :             out += "/*";
     499   [ +  +  +  + ]:        1007 :             if (m_derive == DeriveType::HARDENED) out += m_apostrophe ? '\'' : 'h';
     500                 :             :         }
     501                 :             :         return true;
     502                 :         995 :     }
     503                 :       32358 :     bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache) const override
     504                 :             :     {
     505         [ +  + ]:       32358 :         if (m_derive == DeriveType::HARDENED) {
     506                 :          51 :             out = ToString(StringType::PUBLIC, /*normalized=*/true);
     507                 :             : 
     508                 :          51 :             return true;
     509                 :             :         }
     510                 :             :         // Step backwards to find the last hardened step in the path
     511         [ -  + ]:       32307 :         int i = (int)m_path.size() - 1;
     512         [ +  + ]:       64323 :         for (; i >= 0; --i) {
     513         [ +  + ]:       63634 :             if (m_path.at(i) >> 31) {
     514                 :             :                 break;
     515                 :             :             }
     516                 :             :         }
     517                 :             :         // Either no derivation or all unhardened derivation
     518         [ +  + ]:       32307 :         if (i == -1) {
     519                 :         689 :             out = ToString();
     520                 :         689 :             return true;
     521                 :             :         }
     522                 :             :         // Get the path to the last hardened stup
     523                 :       31618 :         KeyOriginInfo origin;
     524                 :       31618 :         int k = 0;
     525         [ +  + ]:      126444 :         for (; k <= i; ++k) {
     526                 :             :             // Add to the path
     527   [ +  -  +  - ]:       94826 :             origin.path.push_back(m_path.at(k));
     528                 :             :         }
     529                 :             :         // Build the remaining path
     530                 :       31618 :         KeyPath end_path;
     531   [ -  +  +  + ]:       63207 :         for (; k < (int)m_path.size(); ++k) {
     532   [ +  -  +  - ]:       31589 :             end_path.push_back(m_path.at(k));
     533                 :             :         }
     534                 :             :         // Get the fingerprint
     535         [ +  - ]:       31618 :         CKeyID id = m_root_extkey.pubkey.GetID();
     536                 :       31618 :         std::copy(id.begin(), id.begin() + 4, origin.fingerprint);
     537                 :             : 
     538         [ +  + ]:       31618 :         CExtPubKey xpub;
     539         [ +  + ]:       31618 :         CExtKey lh_xprv;
     540                 :             :         // If we have the cache, just get the parent xpub
     541         [ +  + ]:       31618 :         if (cache != nullptr) {
     542         [ +  - ]:       31600 :             cache->GetCachedLastHardenedExtPubKey(m_expr_index, xpub);
     543                 :             :         }
     544         [ +  + ]:       31618 :         if (!xpub.pubkey.IsValid()) {
     545                 :             :             // Cache miss, or nor cache, or need privkey
     546         [ +  - ]:          18 :             CExtKey xprv;
     547   [ +  -  -  + ]:          18 :             if (!GetDerivedExtKey(arg, xprv, lh_xprv)) return false;
     548         [ +  - ]:          18 :             xpub = lh_xprv.Neuter();
     549                 :          18 :         }
     550         [ -  + ]:       31618 :         assert(xpub.pubkey.IsValid());
     551                 :             : 
     552                 :             :         // Build the string
     553   [ +  -  +  -  :       63236 :         std::string origin_str = HexStr(origin.fingerprint) + FormatHDKeypath(origin.path);
                   +  - ]
     554   [ +  -  +  -  :       63236 :         out = "[" + origin_str + "]" + EncodeExtPubKey(xpub) + FormatHDKeypath(end_path);
          +  -  +  -  +  
                      - ]
     555         [ +  + ]:       31618 :         if (IsRange()) {
     556         [ +  - ]:       31570 :             out += "/*";
     557         [ -  + ]:       31570 :             assert(m_derive == DeriveType::UNHARDENED);
     558                 :             :         }
     559                 :       31618 :         return true;
     560                 :       63236 :     }
     561                 :       10690 :     void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const override
     562                 :             :     {
     563         [ +  - ]:       10690 :         CExtKey extkey;
     564                 :       10690 :         CExtKey dummy;
     565   [ +  -  +  + ]:       10690 :         if (!GetDerivedExtKey(arg, extkey, dummy)) return;
     566   [ +  +  +  -  :        7945 :         if (m_derive == DeriveType::UNHARDENED && !extkey.Derive(extkey, pos)) return;
                   +  - ]
     567   [ +  +  +  -  :        7945 :         if (m_derive == DeriveType::HARDENED && !extkey.Derive(extkey, pos | 0x80000000UL)) return;
                   +  - ]
     568   [ +  -  +  -  :        7945 :         out.keys.emplace(extkey.key.GetPubKey().GetID(), extkey.key);
                   +  - ]
     569                 :       10690 :     }
     570                 :         248 :     std::optional<CPubKey> GetRootPubKey() const override
     571                 :             :     {
     572                 :         248 :         return std::nullopt;
     573                 :             :     }
     574                 :         248 :     std::optional<CExtPubKey> GetRootExtPubKey() const override
     575                 :             :     {
     576                 :         248 :         return m_root_extkey;
     577                 :             :     }
     578                 :         260 :     std::unique_ptr<PubkeyProvider> Clone() const override
     579                 :             :     {
     580         [ -  + ]:         260 :         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                 :        1869 :     bool IsRangedDerivation() const { return m_derive != DeriveType::NO; }
     599                 :             : 
     600                 :             : public:
     601                 :         209 :     MuSigPubkeyProvider(
     602                 :             :         uint32_t exp_index,
     603                 :             :         std::vector<std::unique_ptr<PubkeyProvider>> providers,
     604                 :             :         KeyPath path,
     605                 :             :         DeriveType derive
     606                 :             :     )
     607                 :         209 :         : PubkeyProvider(exp_index),
     608                 :         209 :         m_participants(std::move(providers)),
     609         [ +  - ]:         209 :         m_path(std::move(path)),
     610         [ +  - ]:         209 :         m_derive(derive),
     611         [ +  - ]:         670 :         m_ranged_participants(std::any_of(m_participants.begin(), m_participants.end(), [](const auto& pubkey) { return pubkey->IsRange(); }))
     612                 :             :     {
     613   [ +  +  +  -  :         209 :         if (!Assume(!(m_ranged_participants && IsRangedDerivation()))) {
                   -  + ]
     614         [ #  # ]:           0 :             throw std::runtime_error("musig(): Cannot have both ranged participants and ranged derivation");
     615                 :             :         }
     616         [ -  + ]:         209 :         if (!Assume(m_derive != DeriveType::HARDENED)) {
     617         [ #  # ]:           0 :             throw std::runtime_error("musig(): Cannot have hardened derivation");
     618                 :             :         }
     619                 :         209 :     }
     620                 :             : 
     621                 :        1137 :     std::optional<CPubKey> GetPubKey(int pos, const SigningProvider& arg, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
     622                 :             :     {
     623                 :        1137 :         FlatSigningProvider dummy;
     624                 :             :         // If the participants are not ranged, we can compute and cache the aggregate pubkey by creating a PubkeyProvider for it
     625   [ +  +  +  + ]:        1137 :         if (!m_aggregate_provider && !m_ranged_participants) {
     626                 :             :             // Retrieve the pubkeys from the providers
     627                 :         118 :             std::vector<CPubKey> pubkeys;
     628         [ +  + ]:         432 :             for (const auto& prov : m_participants) {
     629         [ +  - ]:         314 :                 std::optional<CPubKey> pubkey = prov->GetPubKey(0, arg, dummy, read_cache, write_cache);
     630         [ -  + ]:         314 :                 if (!pubkey.has_value()) {
     631                 :           0 :                     return std::nullopt;
     632                 :             :                 }
     633         [ +  - ]:         314 :                 pubkeys.push_back(pubkey.value());
     634                 :             :             }
     635                 :         118 :             std::sort(pubkeys.begin(), pubkeys.end());
     636                 :             : 
     637                 :             :             // Aggregate the pubkey
     638         [ +  - ]:         118 :             m_aggregate_pubkey = MuSig2AggregatePubkeys(pubkeys);
     639         [ -  + ]:         118 :             if (!Assume(m_aggregate_pubkey.has_value())) return std::nullopt;
     640                 :             : 
     641                 :             :             // Make our pubkey provider
     642   [ +  +  +  + ]:         118 :             if (IsRangedDerivation() || !m_path.empty()) {
     643                 :             :                 // Make the synthetic xpub and construct the BIP32PubkeyProvider
     644         [ +  - ]:         114 :                 CExtPubKey extpub = CreateMuSig2SyntheticXpub(m_aggregate_pubkey.value());
     645   [ +  -  -  + ]:         114 :                 m_aggregate_provider = std::make_unique<BIP32PubkeyProvider>(m_expr_index, extpub, m_path, m_derive, /*apostrophe=*/false);
     646                 :             :             } else {
     647         [ +  - ]:           4 :                 m_aggregate_provider = std::make_unique<ConstPubkeyProvider>(m_expr_index, m_aggregate_pubkey.value(), /*xonly=*/false);
     648                 :             :             }
     649                 :         118 :         }
     650                 :             : 
     651                 :             :         // Retrieve all participant pubkeys
     652                 :        1137 :         std::vector<CPubKey> pubkeys;
     653         [ +  + ]:        3985 :         for (const auto& prov : m_participants) {
     654         [ +  - ]:        2936 :             std::optional<CPubKey> pub = prov->GetPubKey(pos, arg, out, read_cache, write_cache);
     655         [ +  + ]:        2936 :             if (!pub) return std::nullopt;
     656         [ +  - ]:        2848 :             pubkeys.emplace_back(*pub);
     657                 :             :         }
     658                 :        1049 :         std::sort(pubkeys.begin(), pubkeys.end());
     659                 :             : 
     660         [ +  + ]:        1049 :         CPubKey pubout;
     661         [ +  + ]:        1049 :         if (m_aggregate_provider) {
     662                 :             :             // When we have a cached aggregate key, we are either returning it or deriving from it
     663                 :             :             // Either way, we can passthrough to its GetPubKey
     664                 :             :             // Use a dummy signing provider as private keys do not exist for the aggregate pubkey
     665         [ +  - ]:         771 :             std::optional<CPubKey> pub = m_aggregate_provider->GetPubKey(pos, dummy, out, read_cache, write_cache);
     666         [ -  + ]:         771 :             if (!pub) return std::nullopt;
     667         [ +  - ]:         771 :             pubout = *pub;
     668   [ +  -  +  - ]:         771 :             out.aggregate_pubkeys.emplace(m_aggregate_pubkey.value(), pubkeys);
     669                 :             :         } else {
     670   [ +  -  +  - ]:         278 :             if (!Assume(m_ranged_participants) || !Assume(m_path.empty())) return std::nullopt;
     671                 :             :             // Compute aggregate key from derived participants
     672         [ +  - ]:         278 :             std::optional<CPubKey> aggregate_pubkey = MuSig2AggregatePubkeys(pubkeys);
     673         [ -  + ]:         278 :             if (!aggregate_pubkey) return std::nullopt;
     674         [ +  - ]:         278 :             pubout = *aggregate_pubkey;
     675                 :             : 
     676         [ +  - ]:         278 :             std::unique_ptr<ConstPubkeyProvider> this_agg_provider = std::make_unique<ConstPubkeyProvider>(m_expr_index, aggregate_pubkey.value(), /*xonly=*/false);
     677         [ +  - ]:         278 :             this_agg_provider->GetPubKey(0, dummy, out, read_cache, write_cache);
     678         [ +  - ]:         278 :             out.aggregate_pubkeys.emplace(pubout, pubkeys);
     679                 :         278 :         }
     680                 :             : 
     681         [ -  + ]:        1049 :         if (!Assume(pubout.IsValid())) return std::nullopt;
     682                 :        1049 :         return pubout;
     683                 :        1137 :     }
     684   [ +  +  +  + ]:         645 :     bool IsRange() const override { return IsRangedDerivation() || m_ranged_participants; }
     685                 :             :     // musig() expressions can only be used in tr() contexts which have 32 byte xonly pubkeys
     686                 :           0 :     size_t GetSize() const override { return 32; }
     687                 :             : 
     688                 :         878 :     std::string ToString(StringType type=StringType::PUBLIC) const override
     689                 :             :     {
     690                 :         878 :         std::string out = "musig(";
     691   [ -  +  +  + ]:        3302 :         for (size_t i = 0; i < m_participants.size(); ++i) {
     692         [ +  - ]:        2424 :             const auto& pubkey = m_participants.at(i);
     693   [ +  +  +  - ]:        2424 :             if (i) out += ",";
     694         [ +  - ]:        4848 :             out += pubkey->ToString(type);
     695                 :             :         }
     696         [ +  - ]:         878 :         out += ")";
     697         [ +  - ]:        1756 :         out += FormatHDKeypath(m_path);
     698         [ +  + ]:         878 :         if (IsRangedDerivation()) {
     699         [ +  - ]:         609 :             out += "/*";
     700                 :             :         }
     701                 :         878 :         return out;
     702                 :           0 :     }
     703                 :          66 :     bool ToPrivateString(const SigningProvider& arg, std::string& out) const override
     704                 :             :     {
     705                 :          66 :         bool any_privkeys = false;
     706                 :          66 :         out = "musig(";
     707   [ -  +  +  + ]:         242 :         for (size_t i = 0; i < m_participants.size(); ++i) {
     708                 :         176 :             const auto& pubkey = m_participants.at(i);
     709         [ +  + ]:         176 :             if (i) out += ",";
     710         [ +  - ]:         176 :             std::string tmp;
     711   [ +  -  +  + ]:         176 :             if (pubkey->ToPrivateString(arg, tmp)) {
     712                 :          72 :                 any_privkeys = true;
     713         [ -  + ]:         248 :                 out += tmp;
     714                 :             :             } else {
     715         [ +  - ]:         208 :                 out += pubkey->ToString();
     716                 :             :             }
     717                 :         176 :         }
     718                 :          66 :         out += ")";
     719         [ -  + ]:         132 :         out += FormatHDKeypath(m_path);
     720         [ +  + ]:          66 :         if (IsRangedDerivation()) {
     721                 :          34 :             out += "/*";
     722                 :             :         }
     723         [ +  + ]:          66 :         if (!any_privkeys) out.clear();
     724                 :          66 :         return any_privkeys;
     725                 :             :     }
     726                 :          99 :     bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache = nullptr) const override
     727                 :             :     {
     728                 :          99 :         out = "musig(";
     729   [ -  +  +  + ]:         369 :         for (size_t i = 0; i < m_participants.size(); ++i) {
     730                 :         270 :             const auto& pubkey = m_participants.at(i);
     731         [ +  + ]:         270 :             if (i) out += ",";
     732         [ +  - ]:         270 :             std::string tmp;
     733   [ +  -  -  + ]:         270 :             if (!pubkey->ToNormalizedString(arg, tmp, cache)) {
     734                 :           0 :                 return false;
     735                 :             :             }
     736         [ -  + ]:         540 :             out += tmp;
     737                 :         270 :         }
     738                 :          99 :         out += ")";
     739         [ -  + ]:         198 :         out += FormatHDKeypath(m_path);
     740         [ +  + ]:          99 :         if (IsRangedDerivation()) {
     741                 :          63 :             out += "/*";
     742                 :             :         }
     743                 :             :         return true;
     744                 :             :     }
     745                 :             : 
     746                 :         768 :     void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const override
     747                 :             :     {
     748                 :             :         // Get the private keys for any participants that we have
     749                 :             :         // If there is participant derivation, it will be done.
     750                 :             :         // If there is not, then the participant privkeys will be included directly
     751         [ +  + ]:        2881 :         for (const auto& prov : m_participants) {
     752                 :        2113 :             prov->GetPrivKey(pos, arg, out);
     753                 :             :         }
     754                 :         768 :     }
     755                 :             : 
     756                 :             :     // Get RootPubKey and GetRootExtPubKey are used to return the single pubkey underlying the pubkey provider
     757                 :             :     // to be presented to the user in gethdkeys. As this is a multisig construction, there is no single underlying
     758                 :             :     // pubkey hence nothing should be returned.
     759                 :             :     // While the aggregate pubkey could be returned as the root (ext)pubkey, it is not a pubkey that anyone should
     760                 :             :     // be using by itself in a descriptor as it is unspendable without knowing its participants.
     761                 :           0 :     std::optional<CPubKey> GetRootPubKey() const override
     762                 :             :     {
     763                 :           0 :         return std::nullopt;
     764                 :             :     }
     765                 :           0 :     std::optional<CExtPubKey> GetRootExtPubKey() const override
     766                 :             :     {
     767                 :           0 :         return std::nullopt;
     768                 :             :     }
     769                 :             : 
     770                 :          29 :     std::unique_ptr<PubkeyProvider> Clone() const override
     771                 :             :     {
     772                 :          29 :         std::vector<std::unique_ptr<PubkeyProvider>> providers;
     773   [ -  +  +  - ]:          29 :         providers.reserve(m_participants.size());
     774         [ +  + ]:         107 :         for (const std::unique_ptr<PubkeyProvider>& p : m_participants) {
     775   [ +  -  +  - ]:          78 :             providers.emplace_back(p->Clone());
     776                 :             :         }
     777   [ +  -  -  + ]:          58 :         return std::make_unique<MuSigPubkeyProvider>(m_expr_index, std::move(providers), m_path, m_derive);
     778                 :          29 :     }
     779                 :           0 :     bool IsBIP32() const override
     780                 :             :     {
     781                 :             :         // musig() can only be a BIP 32 key if all participants are bip32 too
     782                 :           0 :         return std::all_of(m_participants.begin(), m_participants.end(), [](const auto& pubkey) { return pubkey->IsBIP32(); });
     783                 :             :     }
     784                 :             : };
     785                 :             : 
     786                 :             : /** Base class for all Descriptor implementations. */
     787                 :             : class DescriptorImpl : public Descriptor
     788                 :             : {
     789                 :             : protected:
     790                 :             :     //! Public key arguments for this descriptor (size 1 for PK, PKH, WPKH; any size for WSH and Multisig).
     791                 :             :     const std::vector<std::unique_ptr<PubkeyProvider>> m_pubkey_args;
     792                 :             :     //! The string name of the descriptor function.
     793                 :             :     const std::string m_name;
     794                 :             : 
     795                 :             :     //! The sub-descriptor arguments (empty for everything but SH and WSH).
     796                 :             :     //! In doc/descriptors.m this is referred to as SCRIPT expressions sh(SCRIPT)
     797                 :             :     //! and wsh(SCRIPT), and distinct from KEY expressions and ADDR expressions.
     798                 :             :     //! Subdescriptors can only ever generate a single script.
     799                 :             :     const std::vector<std::unique_ptr<DescriptorImpl>> m_subdescriptor_args;
     800                 :             : 
     801                 :             :     //! Return a serialization of anything except pubkey and script arguments, to be prepended to those.
     802                 :      335716 :     virtual std::string ToStringExtra() const { return ""; }
     803                 :             : 
     804                 :             :     /** A helper function to construct the scripts for this descriptor.
     805                 :             :      *
     806                 :             :      *  This function is invoked once by ExpandHelper.
     807                 :             :      *
     808                 :             :      *  @param pubkeys The evaluations of the m_pubkey_args field.
     809                 :             :      *  @param scripts The evaluations of m_subdescriptor_args (one for each m_subdescriptor_args element).
     810                 :             :      *  @param out A FlatSigningProvider to put scripts or public keys in that are necessary to the solver.
     811                 :             :      *             The origin info of the provided pubkeys is automatically added.
     812                 :             :      *  @return A vector with scriptPubKeys for this descriptor.
     813                 :             :      */
     814                 :             :     virtual std::vector<CScript> MakeScripts(const std::vector<CPubKey>& pubkeys, std::span<const CScript> scripts, FlatSigningProvider& out) const = 0;
     815                 :             : 
     816                 :             : public:
     817         [ -  + ]:      716790 :     DescriptorImpl(std::vector<std::unique_ptr<PubkeyProvider>> pubkeys, const std::string& name) : m_pubkey_args(std::move(pubkeys)), m_name(name), m_subdescriptor_args() {}
     818   [ -  +  +  - ]:      113666 :     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))) {}
     819         [ -  + ]:       16518 :     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)) {}
     820                 :             : 
     821                 :             :     enum class StringType
     822                 :             :     {
     823                 :             :         PUBLIC,
     824                 :             :         PRIVATE,
     825                 :             :         NORMALIZED,
     826                 :             :         COMPAT, // string calculation that mustn't change over time to stay compatible with previous software versions
     827                 :             :     };
     828                 :             : 
     829                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     830                 :        3895 :     bool IsSolvable() const override
     831                 :             :     {
     832         [ +  + ]:        5612 :         for (const auto& arg : m_subdescriptor_args) {
     833         [ +  - ]:        1717 :             if (!arg->IsSolvable()) return false;
     834                 :             :         }
     835                 :             :         return true;
     836                 :             :     }
     837                 :             : 
     838                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     839                 :      123652 :     bool IsRange() const final
     840                 :             :     {
     841         [ +  + ]:      148278 :         for (const auto& pubkey : m_pubkey_args) {
     842         [ +  + ]:      121003 :             if (pubkey->IsRange()) return true;
     843                 :             :         }
     844         [ +  + ]:       28461 :         for (const auto& arg : m_subdescriptor_args) {
     845         [ +  + ]:       10827 :             if (arg->IsRange()) return true;
     846                 :             :         }
     847                 :             :         return false;
     848                 :             :     }
     849                 :             : 
     850                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     851                 :      335034 :     virtual bool ToStringSubScriptHelper(const SigningProvider* arg, std::string& ret, const StringType type, const DescriptorCache* cache = nullptr) const
     852                 :             :     {
     853                 :      335034 :         size_t pos = 0;
     854         [ +  + ]:      399005 :         for (const auto& scriptarg : m_subdescriptor_args) {
     855         [ -  + ]:       64082 :             if (pos++) ret += ",";
     856         [ +  - ]:       64082 :             std::string tmp;
     857   [ +  -  +  + ]:       64082 :             if (!scriptarg->ToStringHelper(arg, tmp, type, cache)) return false;
     858         [ -  + ]:      127942 :             ret += tmp;
     859                 :       64082 :         }
     860                 :             :         return true;
     861                 :             :     }
     862                 :             : 
     863                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     864                 :      343973 :     virtual bool ToStringHelper(const SigningProvider* arg, std::string& out, const StringType type, const DescriptorCache* cache = nullptr) const
     865                 :             :     {
     866                 :      343973 :         std::string extra = ToStringExtra();
     867   [ -  +  +  + ]:      343973 :         size_t pos = extra.size() > 0 ? 1 : 0;
     868   [ +  -  +  - ]:      343973 :         std::string ret = m_name + "(" + extra;
     869         [ +  + ]:      732303 :         for (const auto& pubkey : m_pubkey_args) {
     870   [ +  +  +  - ]:      388545 :             if (pos++) ret += ",";
     871   [ +  +  +  +  :      388545 :             std::string tmp;
                      - ]
     872   [ +  +  +  +  :      388545 :             switch (type) {
                      - ]
     873                 :       42226 :                 case StringType::NORMALIZED:
     874   [ +  -  +  - ]:       42226 :                     if (!pubkey->ToNormalizedString(*arg, tmp, cache)) return false;
     875                 :             :                     break;
     876                 :        1061 :                 case StringType::PRIVATE:
     877   [ +  -  +  + ]:        1061 :                     if (!pubkey->ToPrivateString(*arg, tmp)) return false;
     878                 :             :                     break;
     879                 :      328597 :                 case StringType::PUBLIC:
     880         [ +  - ]:      328597 :                     tmp = pubkey->ToString();
     881                 :      328597 :                     break;
     882                 :       16661 :                 case StringType::COMPAT:
     883         [ +  - ]:       16661 :                     tmp = pubkey->ToString(PubkeyProvider::StringType::COMPAT);
     884                 :       16661 :                     break;
     885                 :             :             }
     886         [ -  + ]:      776660 :             ret += tmp;
     887                 :      388545 :         }
     888         [ +  - ]:      687516 :         std::string subscript;
     889   [ +  -  +  + ]:      343758 :         if (!ToStringSubScriptHelper(arg, subscript, type, cache)) return false;
     890   [ +  +  +  +  :      623309 :         if (pos && subscript.size()) ret += ',';
                   +  - ]
     891         [ +  - ]:      687294 :         out = std::move(ret) + std::move(subscript) + ")";
     892                 :      343647 :         return true;
     893                 :      343973 :     }
     894                 :             : 
     895                 :      237088 :     std::string ToString(bool compat_format) const final
     896                 :             :     {
     897         [ +  + ]:      237088 :         std::string ret;
     898   [ +  +  +  - ]:      467135 :         ToStringHelper(nullptr, ret, compat_format ? StringType::COMPAT : StringType::PUBLIC);
     899         [ +  - ]:      237088 :         return AddChecksum(ret);
     900                 :      237088 :     }
     901                 :             : 
     902                 :         925 :     bool ToPrivateString(const SigningProvider& arg, std::string& out) const override
     903                 :             :     {
     904                 :         925 :         bool ret = ToStringHelper(&arg, out, StringType::PRIVATE);
     905                 :         925 :         out = AddChecksum(out);
     906                 :         925 :         return ret;
     907                 :             :     }
     908                 :             : 
     909                 :       37894 :     bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache) const override final
     910                 :             :     {
     911                 :       37894 :         bool ret = ToStringHelper(&arg, out, StringType::NORMALIZED, cache);
     912                 :       37894 :         out = AddChecksum(out);
     913                 :       37894 :         return ret;
     914                 :             :     }
     915                 :             : 
     916                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     917                 :      752133 :     bool ExpandHelper(int pos, const SigningProvider& arg, const DescriptorCache* read_cache, std::vector<CScript>& output_scripts, FlatSigningProvider& out, DescriptorCache* write_cache) const
     918                 :             :     {
     919                 :      752133 :         FlatSigningProvider subprovider;
     920                 :      752133 :         std::vector<CPubKey> pubkeys;
     921   [ -  +  +  - ]:      752133 :         pubkeys.reserve(m_pubkey_args.size());
     922                 :             : 
     923                 :             :         // Construct temporary data in `pubkeys`, `subscripts`, and `subprovider` to avoid producing output in case of failure.
     924         [ +  + ]:     2438221 :         for (const auto& p : m_pubkey_args) {
     925         [ +  - ]:     1700277 :             std::optional<CPubKey> pubkey = p->GetPubKey(pos, arg, subprovider, read_cache, write_cache);
     926         [ +  + ]:     1700277 :             if (!pubkey) return false;
     927         [ +  - ]:     1686088 :             pubkeys.push_back(pubkey.value());
     928                 :             :         }
     929                 :      737944 :         std::vector<CScript> subscripts;
     930         [ +  + ]:      904563 :         for (const auto& subarg : m_subdescriptor_args) {
     931                 :      167956 :             std::vector<CScript> outscripts;
     932   [ +  -  +  + ]:      167956 :             if (!subarg->ExpandHelper(pos, arg, read_cache, outscripts, subprovider, write_cache)) return false;
     933   [ -  +  -  + ]:      166619 :             assert(outscripts.size() == 1);
     934         [ +  - ]:      166619 :             subscripts.emplace_back(std::move(outscripts[0]));
     935                 :      167956 :         }
     936         [ +  - ]:      736607 :         out.Merge(std::move(subprovider));
     937                 :             : 
     938   [ -  +  +  - ]:      736607 :         output_scripts = MakeScripts(pubkeys, std::span{subscripts}, out);
     939                 :      736607 :         return true;
     940                 :     1490077 :     }
     941                 :             : 
     942                 :       37360 :     bool Expand(int pos, const SigningProvider& provider, std::vector<CScript>& output_scripts, FlatSigningProvider& out, DescriptorCache* write_cache = nullptr) const final
     943                 :             :     {
     944                 :       37360 :         return ExpandHelper(pos, provider, nullptr, output_scripts, out, write_cache);
     945                 :             :     }
     946                 :             : 
     947                 :      546817 :     bool ExpandFromCache(int pos, const DescriptorCache& read_cache, std::vector<CScript>& output_scripts, FlatSigningProvider& out) const final
     948                 :             :     {
     949                 :      546817 :         return ExpandHelper(pos, DUMMY_SIGNING_PROVIDER, &read_cache, output_scripts, out, nullptr);
     950                 :             :     }
     951                 :             : 
     952                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     953                 :       16364 :     void ExpandPrivate(int pos, const SigningProvider& provider, FlatSigningProvider& out) const final
     954                 :             :     {
     955         [ +  + ]:       85510 :         for (const auto& p : m_pubkey_args) {
     956                 :       69146 :             p->GetPrivKey(pos, provider, out);
     957                 :             :         }
     958         [ +  + ]:       19777 :         for (const auto& arg : m_subdescriptor_args) {
     959                 :        3413 :             arg->ExpandPrivate(pos, provider, out);
     960                 :             :         }
     961                 :       16364 :     }
     962                 :             : 
     963                 :         403 :     std::optional<OutputType> GetOutputType() const override { return std::nullopt; }
     964                 :             : 
     965                 :           0 :     std::optional<int64_t> ScriptSize() const override { return {}; }
     966                 :             : 
     967                 :             :     /** A helper for MaxSatisfactionWeight.
     968                 :             :      *
     969                 :             :      * @param use_max_sig Whether to assume ECDSA signatures will have a high-r.
     970                 :             :      * @return The maximum size of the satisfaction in raw bytes (with no witness meaning).
     971                 :             :      */
     972                 :           0 :     virtual std::optional<int64_t> MaxSatSize(bool use_max_sig) const { return {}; }
     973                 :             : 
     974                 :          18 :     std::optional<int64_t> MaxSatisfactionWeight(bool) const override { return {}; }
     975                 :             : 
     976                 :           4 :     std::optional<int64_t> MaxSatisfactionElems() const override { return {}; }
     977                 :             : 
     978                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     979                 :         313 :     void GetPubKeys(std::set<CPubKey>& pubkeys, std::set<CExtPubKey>& ext_pubs) const override
     980                 :             :     {
     981         [ +  + ]:         570 :         for (const auto& p : m_pubkey_args) {
     982                 :         257 :             std::optional<CPubKey> pub = p->GetRootPubKey();
     983         [ +  + ]:         257 :             if (pub) pubkeys.insert(*pub);
     984                 :         257 :             std::optional<CExtPubKey> ext_pub = p->GetRootExtPubKey();
     985         [ +  + ]:         257 :             if (ext_pub) ext_pubs.insert(*ext_pub);
     986                 :             :         }
     987         [ +  + ]:         371 :         for (const auto& arg : m_subdescriptor_args) {
     988                 :          58 :             arg->GetPubKeys(pubkeys, ext_pubs);
     989                 :             :         }
     990                 :         313 :     }
     991                 :             : 
     992                 :             :     virtual std::unique_ptr<DescriptorImpl> Clone() const = 0;
     993                 :             : };
     994                 :             : 
     995                 :             : /** A parsed addr(A) descriptor. */
     996                 :             : class AddressDescriptor final : public DescriptorImpl
     997                 :             : {
     998                 :             :     const CTxDestination m_destination;
     999                 :             : protected:
    1000                 :        4324 :     std::string ToStringExtra() const override { return EncodeDestination(m_destination); }
    1001         [ +  - ]:         240 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, std::span<const CScript>, FlatSigningProvider&) const override { return Vector(GetScriptForDestination(m_destination)); }
    1002                 :             : public:
    1003         [ +  - ]:        4323 :     AddressDescriptor(CTxDestination destination) : DescriptorImpl({}, "addr"), m_destination(std::move(destination)) {}
    1004                 :          14 :     bool IsSolvable() const final { return false; }
    1005                 :             : 
    1006                 :          33 :     std::optional<OutputType> GetOutputType() const override
    1007                 :             :     {
    1008                 :          33 :         return OutputTypeFromDestination(m_destination);
    1009                 :             :     }
    1010                 :           0 :     bool IsSingleType() const final { return true; }
    1011                 :          15 :     bool ToPrivateString(const SigningProvider& arg, std::string& out) const final { return false; }
    1012                 :             : 
    1013         [ #  # ]:           0 :     std::optional<int64_t> ScriptSize() const override { return GetScriptForDestination(m_destination).size(); }
    1014                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1015                 :             :     {
    1016         [ #  # ]:           0 :         return std::make_unique<AddressDescriptor>(m_destination);
    1017                 :             :     }
    1018                 :             : };
    1019                 :             : 
    1020                 :             : /** A parsed raw(H) descriptor. */
    1021                 :             : class RawDescriptor final : public DescriptorImpl
    1022                 :             : {
    1023                 :             :     const CScript m_script;
    1024                 :             : protected:
    1025         [ +  + ]:        4180 :     std::string ToStringExtra() const override { return HexStr(m_script); }
    1026                 :        1895 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, std::span<const CScript>, FlatSigningProvider&) const override { return Vector(m_script); }
    1027                 :             : public:
    1028         [ +  - ]:        3846 :     RawDescriptor(CScript script) : DescriptorImpl({}, "raw"), m_script(std::move(script)) {}
    1029                 :           0 :     bool IsSolvable() const final { return false; }
    1030                 :             : 
    1031                 :           5 :     std::optional<OutputType> GetOutputType() const override
    1032                 :             :     {
    1033                 :           5 :         CTxDestination dest;
    1034         [ +  - ]:           5 :         ExtractDestination(m_script, dest);
    1035         [ +  - ]:           5 :         return OutputTypeFromDestination(dest);
    1036                 :           5 :     }
    1037                 :           0 :     bool IsSingleType() const final { return true; }
    1038                 :           1 :     bool ToPrivateString(const SigningProvider& arg, std::string& out) const final { return false; }
    1039                 :             : 
    1040         [ #  # ]:           0 :     std::optional<int64_t> ScriptSize() const override { return m_script.size(); }
    1041                 :             : 
    1042                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1043                 :             :     {
    1044         [ #  # ]:           0 :         return std::make_unique<RawDescriptor>(m_script);
    1045                 :             :     }
    1046                 :             : };
    1047                 :             : 
    1048                 :             : /** A parsed pk(P) descriptor. */
    1049                 :             : class PKDescriptor final : public DescriptorImpl
    1050                 :             : {
    1051                 :             : private:
    1052                 :             :     const bool m_xonly;
    1053                 :             : protected:
    1054                 :       27856 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override
    1055                 :             :     {
    1056         [ +  + ]:       27856 :         if (m_xonly) {
    1057   [ +  -  +  - ]:       55096 :             CScript script = CScript() << ToByteVector(XOnlyPubKey(keys[0])) << OP_CHECKSIG;
    1058         [ +  - ]:       27548 :             return Vector(std::move(script));
    1059                 :       27548 :         } else {
    1060         [ +  - ]:         616 :             return Vector(GetScriptForRawPubKey(keys[0]));
    1061                 :             :         }
    1062                 :             :     }
    1063                 :             : public:
    1064   [ +  -  +  - ]:       22641 :     PKDescriptor(std::unique_ptr<PubkeyProvider> prov, bool xonly = false) : DescriptorImpl(Vector(std::move(prov)), "pk"), m_xonly(xonly) {}
    1065                 :           6 :     bool IsSingleType() const final { return true; }
    1066                 :             : 
    1067                 :          11 :     std::optional<int64_t> ScriptSize() const override {
    1068         [ +  - ]:          11 :         return 1 + (m_xonly ? 32 : m_pubkey_args[0]->GetSize()) + 1;
    1069                 :             :     }
    1070                 :             : 
    1071                 :          64 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
    1072         [ +  + ]:          59 :         const auto ecdsa_sig_size = use_max_sig ? 72 : 71;
    1073   [ +  -  +  - ]:          64 :         return 1 + (m_xonly ? 65 : ecdsa_sig_size);
    1074                 :             :     }
    1075                 :             : 
    1076                 :          58 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
    1077         [ +  + ]:          58 :         return *MaxSatSize(use_max_sig) * WITNESS_SCALE_FACTOR;
    1078                 :             :     }
    1079                 :             : 
    1080                 :          56 :     std::optional<int64_t> MaxSatisfactionElems() const override { return 1; }
    1081                 :             : 
    1082                 :          15 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1083                 :             :     {
    1084   [ +  -  -  + ]:          15 :         return std::make_unique<PKDescriptor>(m_pubkey_args.at(0)->Clone(), m_xonly);
    1085                 :             :     }
    1086                 :             : };
    1087                 :             : 
    1088                 :             : /** A parsed pkh(P) descriptor. */
    1089                 :             : class PKHDescriptor final : public DescriptorImpl
    1090                 :             : {
    1091                 :             : protected:
    1092                 :      131911 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override
    1093                 :             :     {
    1094                 :      131911 :         CKeyID id = keys[0].GetID();
    1095   [ +  -  +  - ]:      263822 :         return Vector(GetScriptForDestination(PKHash(id)));
    1096                 :             :     }
    1097                 :             : public:
    1098   [ +  -  +  - ]:       98377 :     PKHDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "pkh") {}
    1099                 :       76057 :     std::optional<OutputType> GetOutputType() const override { return OutputType::LEGACY; }
    1100                 :       17476 :     bool IsSingleType() const final { return true; }
    1101                 :             : 
    1102                 :          79 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 1 + 20 + 1 + 1; }
    1103                 :             : 
    1104                 :       55808 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
    1105         [ +  + ]:       55808 :         const auto sig_size = use_max_sig ? 72 : 71;
    1106                 :       55808 :         return 1 + sig_size + 1 + m_pubkey_args[0]->GetSize();
    1107                 :             :     }
    1108                 :             : 
    1109                 :       55741 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
    1110                 :       55741 :         return *MaxSatSize(use_max_sig) * WITNESS_SCALE_FACTOR;
    1111                 :             :     }
    1112                 :             : 
    1113                 :       55793 :     std::optional<int64_t> MaxSatisfactionElems() const override { return 2; }
    1114                 :             : 
    1115                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1116                 :             :     {
    1117   [ #  #  #  # ]:           0 :         return std::make_unique<PKHDescriptor>(m_pubkey_args.at(0)->Clone());
    1118                 :             :     }
    1119                 :             : };
    1120                 :             : 
    1121                 :             : /** A parsed wpkh(P) descriptor. */
    1122                 :             : class WPKHDescriptor final : public DescriptorImpl
    1123                 :             : {
    1124                 :             : protected:
    1125                 :      270127 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override
    1126                 :             :     {
    1127                 :      270127 :         CKeyID id = keys[0].GetID();
    1128   [ +  -  +  - ]:      540254 :         return Vector(GetScriptForDestination(WitnessV0KeyHash(id)));
    1129                 :             :     }
    1130                 :             : public:
    1131   [ +  -  +  - ]:      209504 :     WPKHDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "wpkh") {}
    1132                 :      190130 :     std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32; }
    1133                 :       28557 :     bool IsSingleType() const final { return true; }
    1134                 :             : 
    1135                 :       18396 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 20; }
    1136                 :             : 
    1137                 :      146082 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
    1138         [ +  + ]:      145953 :         const auto sig_size = use_max_sig ? 72 : 71;
    1139                 :      146082 :         return (1 + sig_size + 1 + 33);
    1140                 :             :     }
    1141                 :             : 
    1142                 :      127691 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
    1143         [ +  + ]:      127691 :         return MaxSatSize(use_max_sig);
    1144                 :             :     }
    1145                 :             : 
    1146                 :      146072 :     std::optional<int64_t> MaxSatisfactionElems() const override { return 2; }
    1147                 :             : 
    1148                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1149                 :             :     {
    1150   [ #  #  #  # ]:           0 :         return std::make_unique<WPKHDescriptor>(m_pubkey_args.at(0)->Clone());
    1151                 :             :     }
    1152                 :             : };
    1153                 :             : 
    1154                 :             : /** A parsed combo(P) descriptor. */
    1155                 :             : class ComboDescriptor final : public DescriptorImpl
    1156                 :             : {
    1157                 :             : protected:
    1158                 :       19238 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider& out) const override
    1159                 :             :     {
    1160                 :       19238 :         std::vector<CScript> ret;
    1161         [ +  - ]:       19238 :         CKeyID id = keys[0].GetID();
    1162   [ +  -  +  - ]:       19238 :         ret.emplace_back(GetScriptForRawPubKey(keys[0])); // P2PK
    1163   [ +  -  +  -  :       38476 :         ret.emplace_back(GetScriptForDestination(PKHash(id))); // P2PKH
                   +  - ]
    1164         [ +  + ]:       19238 :         if (keys[0].IsCompressed()) {
    1165         [ +  - ]:       19211 :             CScript p2wpkh = GetScriptForDestination(WitnessV0KeyHash(id));
    1166   [ +  -  +  - ]:       19211 :             out.scripts.emplace(CScriptID(p2wpkh), p2wpkh);
    1167         [ +  - ]:       19211 :             ret.emplace_back(p2wpkh);
    1168   [ +  -  +  -  :       38422 :             ret.emplace_back(GetScriptForDestination(ScriptHash(p2wpkh))); // P2SH-P2WPKH
                   +  - ]
    1169                 :       19211 :         }
    1170                 :       19238 :         return ret;
    1171                 :           0 :     }
    1172                 :             : public:
    1173   [ +  -  +  - ]:         541 :     ComboDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "combo") {}
    1174                 :           5 :     bool IsSingleType() const final { return false; }
    1175                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1176                 :             :     {
    1177   [ #  #  #  # ]:           0 :         return std::make_unique<ComboDescriptor>(m_pubkey_args.at(0)->Clone());
    1178                 :             :     }
    1179                 :             : };
    1180                 :             : 
    1181                 :             : /** A parsed multi(...) or sortedmulti(...) descriptor */
    1182                 :             : class MultisigDescriptor final : public DescriptorImpl
    1183                 :             : {
    1184                 :             :     const int m_threshold;
    1185                 :             :     const bool m_sorted;
    1186                 :             : protected:
    1187                 :        1045 :     std::string ToStringExtra() const override { return strprintf("%i", m_threshold); }
    1188                 :       18606 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override {
    1189         [ +  + ]:       18606 :         if (m_sorted) {
    1190                 :        2833 :             std::vector<CPubKey> sorted_keys(keys);
    1191                 :        2833 :             std::sort(sorted_keys.begin(), sorted_keys.end());
    1192   [ +  -  +  - ]:        5666 :             return Vector(GetScriptForMultisig(m_threshold, sorted_keys));
    1193                 :        2833 :         }
    1194         [ +  - ]:       31546 :         return Vector(GetScriptForMultisig(m_threshold, keys));
    1195                 :             :     }
    1196                 :             : public:
    1197   [ +  +  +  - ]:        1734 :     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) {}
    1198                 :           7 :     bool IsSingleType() const final { return true; }
    1199                 :             : 
    1200                 :         234 :     std::optional<int64_t> ScriptSize() const override {
    1201         [ -  + ]:         234 :         const auto n_keys = m_pubkey_args.size();
    1202                 :         731 :         auto op = [](int64_t acc, const std::unique_ptr<PubkeyProvider>& pk) { return acc + 1 + pk->GetSize();};
    1203                 :         234 :         const auto pubkeys_size{std::accumulate(m_pubkey_args.begin(), m_pubkey_args.end(), int64_t{0}, op)};
    1204   [ -  +  +  - ]:         468 :         return 1 + BuildScript(n_keys).size() + BuildScript(m_threshold).size() + pubkeys_size;
    1205                 :             :     }
    1206                 :             : 
    1207                 :         241 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
    1208         [ +  + ]:         234 :         const auto sig_size = use_max_sig ? 72 : 71;
    1209                 :         241 :         return (1 + (1 + sig_size) * m_threshold);
    1210                 :             :     }
    1211                 :             : 
    1212                 :          14 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
    1213         [ +  + ]:          14 :         return *MaxSatSize(use_max_sig) * WITNESS_SCALE_FACTOR;
    1214                 :             :     }
    1215                 :             : 
    1216                 :         219 :     std::optional<int64_t> MaxSatisfactionElems() const override { return 1 + m_threshold; }
    1217                 :             : 
    1218                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1219                 :             :     {
    1220                 :           0 :         std::vector<std::unique_ptr<PubkeyProvider>> providers;
    1221   [ #  #  #  # ]:           0 :         providers.reserve(m_pubkey_args.size());
    1222         [ #  # ]:           0 :         std::transform(m_pubkey_args.begin(), m_pubkey_args.end(), providers.begin(), [](const std::unique_ptr<PubkeyProvider>& p) { return p->Clone(); });
    1223   [ #  #  #  # ]:           0 :         return std::make_unique<MultisigDescriptor>(m_threshold, std::move(providers), m_sorted);
    1224                 :           0 :     }
    1225                 :             : };
    1226                 :             : 
    1227                 :             : /** A parsed (sorted)multi_a(...) descriptor. Always uses x-only pubkeys. */
    1228                 :             : class MultiADescriptor final : public DescriptorImpl
    1229                 :             : {
    1230                 :             :     const int m_threshold;
    1231                 :             :     const bool m_sorted;
    1232                 :             : protected:
    1233                 :         798 :     std::string ToStringExtra() const override { return strprintf("%i", m_threshold); }
    1234                 :        6950 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override {
    1235                 :        6950 :         CScript ret;
    1236                 :        6950 :         std::vector<XOnlyPubKey> xkeys;
    1237   [ -  +  +  - ]:        6950 :         xkeys.reserve(keys.size());
    1238   [ +  -  +  + ]:      999840 :         for (const auto& key : keys) xkeys.emplace_back(key);
    1239         [ +  + ]:        6950 :         if (m_sorted) std::sort(xkeys.begin(), xkeys.end());
    1240   [ +  -  +  - ]:       13900 :         ret << ToByteVector(xkeys[0]) << OP_CHECKSIG;
    1241   [ -  +  +  + ]:      992890 :         for (size_t i = 1; i < keys.size(); ++i) {
    1242   [ +  -  +  - ]:     2957820 :             ret << ToByteVector(xkeys[i]) << OP_CHECKSIGADD;
    1243                 :             :         }
    1244   [ +  -  +  - ]:        6950 :         ret << m_threshold << OP_NUMEQUAL;
    1245         [ +  - ]:        6950 :         return Vector(std::move(ret));
    1246                 :        6950 :     }
    1247                 :             : public:
    1248   [ +  +  +  - ]:        1770 :     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) {}
    1249                 :           0 :     bool IsSingleType() const final { return true; }
    1250                 :             : 
    1251                 :           0 :     std::optional<int64_t> ScriptSize() const override {
    1252         [ #  # ]:           0 :         const auto n_keys = m_pubkey_args.size();
    1253         [ #  # ]:           0 :         return (1 + 32 + 1) * n_keys + BuildScript(m_threshold).size() + 1;
    1254                 :             :     }
    1255                 :             : 
    1256                 :           0 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
    1257         [ #  # ]:           0 :         return (1 + 65) * m_threshold + (m_pubkey_args.size() - m_threshold);
    1258                 :             :     }
    1259                 :             : 
    1260         [ #  # ]:           0 :     std::optional<int64_t> MaxSatisfactionElems() const override { return m_pubkey_args.size(); }
    1261                 :             : 
    1262                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1263                 :             :     {
    1264                 :           0 :         std::vector<std::unique_ptr<PubkeyProvider>> providers;
    1265   [ #  #  #  # ]:           0 :         providers.reserve(m_pubkey_args.size());
    1266         [ #  # ]:           0 :         for (const auto& arg : m_pubkey_args) {
    1267         [ #  # ]:           0 :             providers.push_back(arg->Clone());
    1268                 :             :         }
    1269   [ #  #  #  # ]:           0 :         return std::make_unique<MultiADescriptor>(m_threshold, std::move(providers), m_sorted);
    1270                 :           0 :     }
    1271                 :             : };
    1272                 :             : 
    1273                 :             : /** A parsed sh(...) descriptor. */
    1274                 :             : class SHDescriptor final : public DescriptorImpl
    1275                 :             : {
    1276                 :             : protected:
    1277                 :      114597 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, std::span<const CScript> scripts, FlatSigningProvider& out) const override
    1278                 :             :     {
    1279   [ +  -  +  - ]:      229194 :         auto ret = Vector(GetScriptForDestination(ScriptHash(scripts[0])));
    1280   [ -  +  +  -  :      114597 :         if (ret.size()) out.scripts.emplace(CScriptID(scripts[0]), scripts[0]);
             +  -  +  - ]
    1281                 :      114597 :         return ret;
    1282                 :           0 :     }
    1283                 :             : 
    1284         [ +  + ]:       41897 :     bool IsSegwit() const { return m_subdescriptor_args[0]->GetOutputType() == OutputType::BECH32; }
    1285                 :             : 
    1286                 :             : public:
    1287         [ +  - ]:       55763 :     SHDescriptor(std::unique_ptr<DescriptorImpl> desc) : DescriptorImpl({}, std::move(desc), "sh") {}
    1288                 :             : 
    1289                 :       23375 :     std::optional<OutputType> GetOutputType() const override
    1290                 :             :     {
    1291   [ -  +  -  + ]:       23375 :         assert(m_subdescriptor_args.size() == 1);
    1292         [ +  + ]:       23375 :         if (IsSegwit()) return OutputType::P2SH_SEGWIT;
    1293                 :         124 :         return OutputType::LEGACY;
    1294                 :             :     }
    1295                 :        1573 :     bool IsSingleType() const final { return true; }
    1296                 :             : 
    1297                 :          24 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 20 + 1; }
    1298                 :             : 
    1299                 :       18522 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
    1300         [ +  - ]:       18522 :         if (const auto sat_size = m_subdescriptor_args[0]->MaxSatSize(use_max_sig)) {
    1301         [ +  - ]:       18522 :             if (const auto subscript_size = m_subdescriptor_args[0]->ScriptSize()) {
    1302                 :             :                 // The subscript is never witness data.
    1303                 :       18522 :                 const auto subscript_weight = (1 + *subscript_size) * WITNESS_SCALE_FACTOR;
    1304                 :             :                 // The weight depends on whether the inner descriptor is satisfied using the witness stack.
    1305         [ +  + ]:       18522 :                 if (IsSegwit()) return subscript_weight + *sat_size;
    1306                 :          60 :                 return subscript_weight + *sat_size * WITNESS_SCALE_FACTOR;
    1307                 :             :             }
    1308                 :             :         }
    1309                 :           0 :         return {};
    1310                 :             :     }
    1311                 :             : 
    1312                 :       18498 :     std::optional<int64_t> MaxSatisfactionElems() const override {
    1313         [ +  - ]:       18498 :         if (const auto sub_elems = m_subdescriptor_args[0]->MaxSatisfactionElems()) return 1 + *sub_elems;
    1314                 :           0 :         return {};
    1315                 :             :     }
    1316                 :             : 
    1317                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1318                 :             :     {
    1319   [ #  #  #  # ]:           0 :         return std::make_unique<SHDescriptor>(m_subdescriptor_args.at(0)->Clone());
    1320                 :             :     }
    1321                 :             : };
    1322                 :             : 
    1323                 :             : /** A parsed wsh(...) descriptor. */
    1324                 :             : class WSHDescriptor final : public DescriptorImpl
    1325                 :             : {
    1326                 :             : protected:
    1327                 :       17057 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, std::span<const CScript> scripts, FlatSigningProvider& out) const override
    1328                 :             :     {
    1329   [ +  -  +  - ]:       34114 :         auto ret = Vector(GetScriptForDestination(WitnessV0ScriptHash(scripts[0])));
    1330   [ -  +  +  -  :       17057 :         if (ret.size()) out.scripts.emplace(CScriptID(scripts[0]), scripts[0]);
             +  -  +  - ]
    1331                 :       17057 :         return ret;
    1332                 :           0 :     }
    1333                 :             : public:
    1334         [ +  - ]:        1070 :     WSHDescriptor(std::unique_ptr<DescriptorImpl> desc) : DescriptorImpl({}, std::move(desc), "wsh") {}
    1335                 :         875 :     std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32; }
    1336                 :         410 :     bool IsSingleType() const final { return true; }
    1337                 :             : 
    1338                 :          89 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
    1339                 :             : 
    1340                 :         390 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
    1341         [ +  - ]:         390 :         if (const auto sat_size = m_subdescriptor_args[0]->MaxSatSize(use_max_sig)) {
    1342         [ +  - ]:         390 :             if (const auto subscript_size = m_subdescriptor_args[0]->ScriptSize()) {
    1343         [ +  + ]:         445 :                 return GetSizeOfCompactSize(*subscript_size) + *subscript_size + *sat_size;
    1344                 :             :             }
    1345                 :             :         }
    1346                 :           0 :         return {};
    1347                 :             :     }
    1348                 :             : 
    1349                 :         319 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
    1350                 :         319 :         return MaxSatSize(use_max_sig);
    1351                 :             :     }
    1352                 :             : 
    1353                 :         364 :     std::optional<int64_t> MaxSatisfactionElems() const override {
    1354         [ +  - ]:         364 :         if (const auto sub_elems = m_subdescriptor_args[0]->MaxSatisfactionElems()) return 1 + *sub_elems;
    1355                 :           0 :         return {};
    1356                 :             :     }
    1357                 :             : 
    1358                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1359                 :             :     {
    1360   [ #  #  #  # ]:           0 :         return std::make_unique<WSHDescriptor>(m_subdescriptor_args.at(0)->Clone());
    1361                 :             :     }
    1362                 :             : };
    1363                 :             : 
    1364                 :             : /** A parsed tr(...) descriptor. */
    1365                 :             : class TRDescriptor final : public DescriptorImpl
    1366                 :             : {
    1367                 :             :     std::vector<int> m_depths;
    1368                 :             : protected:
    1369                 :      125473 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript> scripts, FlatSigningProvider& out) const override
    1370                 :             :     {
    1371         [ -  + ]:      125473 :         TaprootBuilder builder;
    1372   [ -  +  -  + ]:      125473 :         assert(m_depths.size() == scripts.size());
    1373   [ -  +  +  + ]:      160429 :         for (size_t pos = 0; pos < m_depths.size(); ++pos) {
    1374   [ +  +  +  - ]:       69912 :             builder.Add(m_depths[pos], scripts[pos], TAPROOT_LEAF_TAPSCRIPT);
    1375                 :             :         }
    1376         [ -  + ]:      125473 :         if (!builder.IsComplete()) return {};
    1377   [ -  +  -  + ]:      125473 :         assert(keys.size() == 1);
    1378                 :      125473 :         XOnlyPubKey xpk(keys[0]);
    1379   [ +  -  -  + ]:      125473 :         if (!xpk.IsFullyValid()) return {};
    1380         [ +  - ]:      125473 :         builder.Finalize(xpk);
    1381         [ +  - ]:      125473 :         WitnessV1Taproot output = builder.GetOutput();
    1382   [ +  -  +  - ]:      125473 :         out.tr_trees[output] = builder;
    1383   [ +  -  +  - ]:      250946 :         return Vector(GetScriptForDestination(output));
    1384                 :      125473 :     }
    1385                 :        8724 :     bool ToStringSubScriptHelper(const SigningProvider* arg, std::string& ret, const StringType type, const DescriptorCache* cache = nullptr) const override
    1386                 :             :     {
    1387         [ +  + ]:        8724 :         if (m_depths.empty()) return true;
    1388                 :        2040 :         std::vector<bool> path;
    1389   [ -  +  +  + ]:        6840 :         for (size_t pos = 0; pos < m_depths.size(); ++pos) {
    1390   [ +  +  +  - ]:        4800 :             if (pos) ret += ',';
    1391         [ +  + ]:        9600 :             while ((int)path.size() <= m_depths[pos]) {
    1392   [ +  +  +  - ]:        4800 :                 if (path.size()) ret += '{';
    1393         [ +  - ]:        4800 :                 path.push_back(false);
    1394                 :             :             }
    1395         [ +  - ]:        4800 :             std::string tmp;
    1396   [ +  -  -  + ]:        4800 :             if (!m_subdescriptor_args[pos]->ToStringHelper(arg, tmp, type, cache)) return false;
    1397         [ -  + ]:        4800 :             ret += tmp;
    1398   [ +  -  +  + ]:        7560 :             while (!path.empty() && path.back()) {
    1399   [ +  -  +  - ]:        2760 :                 if (path.size() > 1) ret += '}';
    1400   [ -  +  +  - ]:       10320 :                 path.pop_back();
    1401                 :             :             }
    1402         [ +  - ]:        4800 :             if (!path.empty()) path.back() = true;
    1403                 :        4800 :         }
    1404                 :             :         return true;
    1405                 :        2040 :     }
    1406                 :             : public:
    1407                 :        8259 :     TRDescriptor(std::unique_ptr<PubkeyProvider> internal_key, std::vector<std::unique_ptr<DescriptorImpl>> descs, std::vector<int> depths) :
    1408   [ +  -  +  -  :        8259 :         DescriptorImpl(Vector(std::move(internal_key)), std::move(descs), "tr"), m_depths(std::move(depths))
                   -  + ]
    1409                 :             :     {
    1410   [ -  +  -  +  :        8259 :         assert(m_subdescriptor_args.size() == m_depths.size());
                   -  + ]
    1411                 :        8259 :     }
    1412                 :       11004 :     std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32M; }
    1413                 :        1881 :     bool IsSingleType() const final { return true; }
    1414                 :             : 
    1415                 :          28 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
    1416                 :             : 
    1417                 :        5448 :     std::optional<int64_t> MaxSatisfactionWeight(bool) const override {
    1418                 :             :         // FIXME: We assume keypath spend, which can lead to very large underestimations.
    1419                 :        5448 :         return 1 + 65;
    1420                 :             :     }
    1421                 :             : 
    1422                 :        5420 :     std::optional<int64_t> MaxSatisfactionElems() const override {
    1423                 :             :         // FIXME: See above, we assume keypath spend.
    1424                 :        5420 :         return 1;
    1425                 :             :     }
    1426                 :             : 
    1427                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1428                 :             :     {
    1429                 :           0 :         std::vector<std::unique_ptr<DescriptorImpl>> subdescs;
    1430   [ #  #  #  # ]:           0 :         subdescs.reserve(m_subdescriptor_args.size());
    1431         [ #  # ]:           0 :         std::transform(m_subdescriptor_args.begin(), m_subdescriptor_args.end(), subdescs.begin(), [](const std::unique_ptr<DescriptorImpl>& d) { return d->Clone(); });
    1432   [ #  #  #  #  :           0 :         return std::make_unique<TRDescriptor>(m_pubkey_args.at(0)->Clone(), std::move(subdescs), m_depths);
             #  #  #  # ]
    1433                 :           0 :     }
    1434                 :             : };
    1435                 :             : 
    1436                 :             : /* We instantiate Miniscript here with a simple integer as key type.
    1437                 :             :  * The value of these key integers are an index in the
    1438                 :             :  * DescriptorImpl::m_pubkey_args vector.
    1439                 :             :  */
    1440                 :             : 
    1441                 :             : /**
    1442                 :             :  * The context for converting a Miniscript descriptor into a Script.
    1443                 :             :  */
    1444                 :             : class ScriptMaker {
    1445                 :             :     //! Keys contained in the Miniscript (the evaluation of DescriptorImpl::m_pubkey_args).
    1446                 :             :     const std::vector<CPubKey>& m_keys;
    1447                 :             :     //! The script context we're operating within (Tapscript or P2WSH).
    1448                 :             :     const miniscript::MiniscriptContext m_script_ctx;
    1449                 :             : 
    1450                 :             :     //! Get the ripemd160(sha256()) hash of this key.
    1451                 :             :     //! Any key that is valid in a descriptor serializes as 32 bytes within a Tapscript context. So we
    1452                 :             :     //! must not hash the sign-bit byte in this case.
    1453                 :         450 :     uint160 GetHash160(uint32_t key) const {
    1454         [ +  + ]:         450 :         if (miniscript::IsTapscript(m_script_ctx)) {
    1455                 :         179 :             return Hash160(XOnlyPubKey{m_keys[key]});
    1456                 :             :         }
    1457                 :         271 :         return m_keys[key].GetID();
    1458                 :             :     }
    1459                 :             : 
    1460                 :             : public:
    1461                 :        1291 :     ScriptMaker(const std::vector<CPubKey>& keys LIFETIMEBOUND, const miniscript::MiniscriptContext script_ctx) : m_keys(keys), m_script_ctx{script_ctx} {}
    1462                 :             : 
    1463                 :        2651 :     std::vector<unsigned char> ToPKBytes(uint32_t key) const {
    1464                 :             :         // In Tapscript keys always serialize as x-only, whether an x-only key was used in the descriptor or not.
    1465         [ +  + ]:        2651 :         if (!miniscript::IsTapscript(m_script_ctx)) {
    1466                 :        1898 :             return {m_keys[key].begin(), m_keys[key].end()};
    1467                 :             :         }
    1468                 :         753 :         const XOnlyPubKey xonly_pubkey{m_keys[key]};
    1469                 :         753 :         return {xonly_pubkey.begin(), xonly_pubkey.end()};
    1470                 :             :     }
    1471                 :             : 
    1472                 :         450 :     std::vector<unsigned char> ToPKHBytes(uint32_t key) const {
    1473                 :         450 :         auto id = GetHash160(key);
    1474                 :         450 :         return {id.begin(), id.end()};
    1475                 :             :     }
    1476                 :             : };
    1477                 :             : 
    1478                 :             : /**
    1479                 :             :  * The context for converting a Miniscript descriptor to its textual form.
    1480                 :             :  */
    1481                 :             : class StringMaker {
    1482                 :             :     //! To convert private keys for private descriptors.
    1483                 :             :     const SigningProvider* m_arg;
    1484                 :             :     //! Keys contained in the Miniscript (a reference to DescriptorImpl::m_pubkey_args).
    1485                 :             :     const std::vector<std::unique_ptr<PubkeyProvider>>& m_pubkeys;
    1486                 :             :     //! Whether to serialize keys as private or public.
    1487                 :             :     bool m_private;
    1488                 :             : 
    1489                 :             : public:
    1490                 :         816 :     StringMaker(const SigningProvider* arg LIFETIMEBOUND, const std::vector<std::unique_ptr<PubkeyProvider>>& pubkeys LIFETIMEBOUND, bool priv)
    1491                 :         816 :         : m_arg(arg), m_pubkeys(pubkeys), m_private(priv) {}
    1492                 :             : 
    1493                 :        4515 :     std::optional<std::string> ToString(uint32_t key) const
    1494                 :             :     {
    1495         [ +  + ]:        4515 :         std::string ret;
    1496         [ +  + ]:        4515 :         if (m_private) {
    1497   [ +  -  +  + ]:         133 :             if (!m_pubkeys[key]->ToPrivateString(*m_arg, ret)) return {};
    1498                 :             :         } else {
    1499         [ +  - ]:        4382 :             ret = m_pubkeys[key]->ToString();
    1500                 :             :         }
    1501                 :        4482 :         return ret;
    1502                 :        4515 :     }
    1503                 :             : };
    1504                 :             : 
    1505                 :             : class MiniscriptDescriptor final : public DescriptorImpl
    1506                 :             : {
    1507                 :             : private:
    1508                 :             :     miniscript::NodeRef<uint32_t> m_node;
    1509                 :             : 
    1510                 :             : protected:
    1511                 :        1291 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript> scripts,
    1512                 :             :                                      FlatSigningProvider& provider) const override
    1513                 :             :     {
    1514                 :        1291 :         const auto script_ctx{m_node->GetMsCtx()};
    1515         [ +  + ]:        4392 :         for (const auto& key : keys) {
    1516         [ +  + ]:        3101 :             if (miniscript::IsTapscript(script_ctx)) {
    1517                 :         932 :                 provider.pubkeys.emplace(Hash160(XOnlyPubKey{key}), key);
    1518                 :             :             } else {
    1519                 :        2169 :                 provider.pubkeys.emplace(key.GetID(), key);
    1520                 :             :             }
    1521                 :             :         }
    1522         [ +  - ]:        2582 :         return Vector(m_node->ToScript(ScriptMaker(keys, script_ctx)));
    1523                 :             :     }
    1524                 :             : 
    1525                 :             : public:
    1526                 :         672 :     MiniscriptDescriptor(std::vector<std::unique_ptr<PubkeyProvider>> providers, miniscript::NodeRef<uint32_t> node)
    1527         [ +  - ]:         672 :         : DescriptorImpl(std::move(providers), "?"), m_node(std::move(node)) {}
    1528                 :             : 
    1529                 :         816 :     bool ToStringHelper(const SigningProvider* arg, std::string& out, const StringType type,
    1530                 :             :                         const DescriptorCache* cache = nullptr) const override
    1531                 :             :     {
    1532         [ +  + ]:         816 :         if (const auto res = m_node->ToString(StringMaker(arg, m_pubkey_args, type == StringType::PRIVATE))) {
    1533         [ +  - ]:         783 :             out = *res;
    1534                 :         783 :             return true;
    1535                 :         783 :         }
    1536                 :          33 :         return false;
    1537                 :             :     }
    1538                 :             : 
    1539                 :         352 :     bool IsSolvable() const override { return true; }
    1540                 :           0 :     bool IsSingleType() const final { return true; }
    1541                 :             : 
    1542                 :         150 :     std::optional<int64_t> ScriptSize() const override { return m_node->ScriptSize(); }
    1543                 :             : 
    1544                 :         150 :     std::optional<int64_t> MaxSatSize(bool) const override {
    1545                 :             :         // For Miniscript we always assume high-R ECDSA signatures.
    1546   [ -  +  +  - ]:         300 :         return m_node->GetWitnessSize();
    1547                 :             :     }
    1548                 :             : 
    1549                 :         134 :     std::optional<int64_t> MaxSatisfactionElems() const override {
    1550         [ +  - ]:         134 :         return m_node->GetStackSize();
    1551                 :             :     }
    1552                 :             : 
    1553                 :           5 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1554                 :             :     {
    1555                 :           5 :         std::vector<std::unique_ptr<PubkeyProvider>> providers;
    1556   [ -  +  +  - ]:           5 :         providers.reserve(m_pubkey_args.size());
    1557         [ +  + ]:          10 :         for (const auto& arg : m_pubkey_args) {
    1558         [ +  - ]:          10 :             providers.push_back(arg->Clone());
    1559                 :             :         }
    1560   [ +  -  +  -  :          10 :         return std::make_unique<MiniscriptDescriptor>(std::move(providers), m_node->Clone());
                   -  + ]
    1561                 :           5 :     }
    1562                 :             : };
    1563                 :             : 
    1564                 :             : /** A parsed rawtr(...) descriptor. */
    1565                 :             : class RawTRDescriptor final : public DescriptorImpl
    1566                 :             : {
    1567                 :             : protected:
    1568                 :        1486 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript> scripts, FlatSigningProvider& out) const override
    1569                 :             :     {
    1570   [ -  +  -  + ]:        1486 :         assert(keys.size() == 1);
    1571                 :        1486 :         XOnlyPubKey xpk(keys[0]);
    1572         [ -  + ]:        1486 :         if (!xpk.IsFullyValid()) return {};
    1573         [ +  - ]:        1486 :         WitnessV1Taproot output{xpk};
    1574   [ +  -  +  - ]:        2972 :         return Vector(GetScriptForDestination(output));
    1575                 :             :     }
    1576                 :             : public:
    1577   [ +  -  +  - ]:       16706 :     RawTRDescriptor(std::unique_ptr<PubkeyProvider> output_key) : DescriptorImpl(Vector(std::move(output_key)), "rawtr") {}
    1578                 :         310 :     std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32M; }
    1579                 :         130 :     bool IsSingleType() const final { return true; }
    1580                 :             : 
    1581                 :          13 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
    1582                 :             : 
    1583                 :         169 :     std::optional<int64_t> MaxSatisfactionWeight(bool) const override {
    1584                 :             :         // We can't know whether there is a script path, so assume key path spend.
    1585                 :         169 :         return 1 + 65;
    1586                 :             :     }
    1587                 :             : 
    1588                 :         156 :     std::optional<int64_t> MaxSatisfactionElems() const override {
    1589                 :             :         // See above, we assume keypath spend.
    1590                 :         156 :         return 1;
    1591                 :             :     }
    1592                 :             : 
    1593                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1594                 :             :     {
    1595   [ #  #  #  # ]:           0 :         return std::make_unique<RawTRDescriptor>(m_pubkey_args.at(0)->Clone());
    1596                 :             :     }
    1597                 :             : };
    1598                 :             : 
    1599                 :             : ////////////////////////////////////////////////////////////////////////////
    1600                 :             : // Parser                                                                 //
    1601                 :             : ////////////////////////////////////////////////////////////////////////////
    1602                 :             : 
    1603                 :             : enum class ParseScriptContext {
    1604                 :             :     TOP,     //!< Top-level context (script goes directly in scriptPubKey)
    1605                 :             :     P2SH,    //!< Inside sh() (script becomes P2SH redeemScript)
    1606                 :             :     P2WPKH,  //!< Inside wpkh() (no script, pubkey only)
    1607                 :             :     P2WSH,   //!< Inside wsh() (script becomes v0 witness script)
    1608                 :             :     P2TR,    //!< Inside tr() (either internal key, or BIP342 script leaf)
    1609                 :             :     MUSIG,   //!< Inside musig() (implies P2TR, cannot have nested musig())
    1610                 :             : };
    1611                 :             : 
    1612                 :       27308 : std::optional<uint32_t> ParseKeyPathNum(std::span<const char> elem, bool& apostrophe, std::string& error, bool& has_hardened)
    1613                 :             : {
    1614                 :       27308 :     bool hardened = false;
    1615         [ +  + ]:       27308 :     if (elem.size() > 0) {
    1616         [ +  + ]:       27302 :         const char last = elem[elem.size() - 1];
    1617         [ +  + ]:       27302 :         if (last == '\'' || last == 'h') {
    1618                 :       19682 :             elem = elem.first(elem.size() - 1);
    1619                 :       19682 :             hardened = true;
    1620                 :       19682 :             apostrophe = last == '\'';
    1621                 :             :         }
    1622                 :             :     }
    1623                 :       27308 :     const auto p{ToIntegral<uint32_t>(std::string_view{elem.begin(), elem.end()})};
    1624         [ +  + ]:       27308 :     if (!p) {
    1625                 :          14 :         error = strprintf("Key path value '%s' is not a valid uint32", std::string_view{elem.begin(), elem.end()});
    1626                 :          14 :         return std::nullopt;
    1627         [ +  + ]:       27294 :     } else if (*p > 0x7FFFFFFFUL) {
    1628                 :           2 :         error = strprintf("Key path value %u is out of range", *p);
    1629                 :           2 :         return std::nullopt;
    1630                 :             :     }
    1631   [ +  +  +  + ]:       27292 :     has_hardened = has_hardened || hardened;
    1632                 :             : 
    1633                 :       27292 :     return std::make_optional<uint32_t>(*p | (((uint32_t)hardened) << 31));
    1634                 :             : }
    1635                 :             : 
    1636                 :             : /**
    1637                 :             :  * Parse a key path, being passed a split list of elements (the first element is ignored because it is always the key).
    1638                 :             :  *
    1639                 :             :  * @param[in] split BIP32 path string, using either ' or h for hardened derivation
    1640                 :             :  * @param[out] out Vector of parsed key paths
    1641                 :             :  * @param[out] apostrophe only updated if hardened derivation is found
    1642                 :             :  * @param[out] error parsing error message
    1643                 :             :  * @param[in] allow_multipath Allows the parsed path to use the multipath specifier
    1644                 :             :  * @param[out] has_hardened Records whether the path contains any hardened derivation
    1645                 :             :  * @returns false if parsing failed
    1646                 :             :  **/
    1647                 :       12785 : [[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)
    1648                 :             : {
    1649                 :       12785 :     KeyPath path;
    1650                 :         267 :     struct MultipathSubstitutes {
    1651                 :             :         size_t placeholder_index;
    1652                 :             :         std::vector<uint32_t> values;
    1653                 :             :     };
    1654                 :       12785 :     std::optional<MultipathSubstitutes> substitutes;
    1655                 :       12785 :     has_hardened = false;
    1656                 :             : 
    1657   [ -  +  +  + ]:       39693 :     for (size_t i = 1; i < split.size(); ++i) {
    1658         [ +  - ]:       26934 :         const std::span<const char>& elem = split[i];
    1659                 :             : 
    1660                 :             :         // Check if element contains multipath specifier
    1661   [ +  -  +  +  :       26934 :         if (!elem.empty() && elem.front() == '<' && elem.back() == '>') {
                   +  + ]
    1662         [ +  + ]:         275 :             if (!allow_multipath) {
    1663   [ +  -  +  - ]:           4 :                 error = strprintf("Key path value '%s' specifies multipath in a section where multipath is not allowed", std::string(elem.begin(), elem.end()));
    1664                 :           2 :                 return false;
    1665                 :             :             }
    1666         [ +  + ]:         273 :             if (substitutes) {
    1667         [ +  - ]:       12785 :                 error = "Multiple multipath key path specifiers found";
    1668                 :             :                 return false;
    1669                 :             :             }
    1670                 :             : 
    1671                 :             :             // Parse each possible value
    1672         [ +  - ]:         271 :             std::vector<std::span<const char>> nums = Split(std::span(elem.begin()+1, elem.end()-1), ";");
    1673   [ -  +  +  + ]:         271 :             if (nums.size() < 2) {
    1674         [ +  - ]:          12 :                 error = "Multipath key path specifiers must have at least two items";
    1675                 :             :                 return false;
    1676                 :             :             }
    1677                 :             : 
    1678                 :         267 :             substitutes.emplace();
    1679                 :         267 :             std::unordered_set<uint32_t> seen_substitutes;
    1680         [ +  + ]:         908 :             for (const auto& num : nums) {
    1681         [ +  - ]:         649 :                 const auto& op_num = ParseKeyPathNum(num, apostrophe, error, has_hardened);
    1682         [ +  + ]:         649 :                 if (!op_num) return false;
    1683   [ +  -  +  + ]:         643 :                 auto [_, inserted] = seen_substitutes.insert(*op_num);
    1684         [ +  + ]:         643 :                 if (!inserted) {
    1685         [ +  - ]:           2 :                     error = strprintf("Duplicated key path value %u in multipath specifier", *op_num);
    1686                 :           2 :                     return false;
    1687                 :             :                 }
    1688         [ +  - ]:         641 :                 substitutes->values.emplace_back(*op_num);
    1689                 :             :             }
    1690                 :             : 
    1691         [ +  - ]:         259 :             path.emplace_back(); // Placeholder for multipath segment
    1692         [ -  + ]:         259 :             substitutes->placeholder_index = path.size() - 1;
    1693                 :         279 :         } else {
    1694         [ +  - ]:       26659 :             const auto& op_num = ParseKeyPathNum(elem, apostrophe, error, has_hardened);
    1695         [ +  + ]:       26659 :             if (!op_num) return false;
    1696         [ +  - ]:       26649 :             path.emplace_back(*op_num);
    1697                 :             :         }
    1698                 :             :     }
    1699                 :             : 
    1700         [ +  + ]:       12759 :     if (!substitutes) {
    1701         [ +  - ]:       12502 :         out.emplace_back(std::move(path));
    1702                 :             :     } else {
    1703                 :             :         // Replace the multipath placeholder with each value while generating paths
    1704         [ +  + ]:         886 :         for (uint32_t substitute : substitutes->values) {
    1705         [ +  - ]:         629 :             KeyPath branch_path = path;
    1706         [ +  - ]:         629 :             branch_path[substitutes->placeholder_index] = substitute;
    1707         [ +  - ]:         629 :             out.emplace_back(std::move(branch_path));
    1708                 :         629 :         }
    1709                 :             :     }
    1710                 :             :     return true;
    1711                 :       12785 : }
    1712                 :             : 
    1713                 :       12712 : [[nodiscard]] bool ParseKeyPath(const std::vector<std::span<const char>>& split, std::vector<KeyPath>& out, bool& apostrophe, std::string& error, bool allow_multipath)
    1714                 :             : {
    1715                 :       12712 :     bool dummy;
    1716                 :       12712 :     return ParseKeyPath(split, out, apostrophe, error, allow_multipath, /*has_hardened=*/dummy);
    1717                 :             : }
    1718                 :             : 
    1719                 :        7834 : static DeriveType ParseDeriveType(std::vector<std::span<const char>>& split, bool& apostrophe)
    1720                 :             : {
    1721                 :        7834 :     DeriveType type = DeriveType::NO;
    1722         [ +  + ]:        7834 :     if (std::ranges::equal(split.back(), std::span{"*"}.first(1))) {
    1723                 :        7249 :         split.pop_back();
    1724                 :        7249 :         type = DeriveType::UNHARDENED;
    1725   [ +  +  +  + ]:         585 :     } else if (std::ranges::equal(split.back(), std::span{"*'"}.first(2)) || std::ranges::equal(split.back(), std::span{"*h"}.first(2))) {
    1726                 :         174 :         apostrophe = std::ranges::equal(split.back(), std::span{"*'"}.first(2));
    1727                 :         174 :         split.pop_back();
    1728                 :         174 :         type = DeriveType::HARDENED;
    1729                 :             :     }
    1730                 :        7834 :     return type;
    1731                 :             : }
    1732                 :             : 
    1733                 :             : /** Parse a public key that excludes origin information. */
    1734                 :       27724 : 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)
    1735                 :             : {
    1736                 :       27724 :     std::vector<std::unique_ptr<PubkeyProvider>> ret;
    1737                 :       27724 :     bool permit_uncompressed = ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH;
    1738         [ +  - ]:       27724 :     auto split = Split(sp, '/');
    1739   [ +  -  -  + ]:       55448 :     std::string str(split[0].begin(), split[0].end());
    1740   [ -  +  +  + ]:       27724 :     if (str.size() == 0) {
    1741         [ +  - ]:           2 :         error = "No key provided";
    1742                 :           2 :         return {};
    1743                 :             :     }
    1744   [ +  +  +  + ]:       27722 :     if (IsSpace(str.front()) || IsSpace(str.back())) {
    1745         [ +  - ]:          10 :         error = strprintf("Key '%s' is invalid due to whitespace", str);
    1746                 :          10 :         return {};
    1747                 :             :     }
    1748   [ -  +  +  + ]:       27712 :     if (split.size() == 1) {
    1749   [ +  -  +  + ]:       20201 :         if (IsHex(str)) {
    1750   [ -  +  +  - ]:       19503 :             std::vector<unsigned char> data = ParseHex(str);
    1751         [ -  + ]:       19503 :             CPubKey pubkey(data);
    1752   [ +  +  +  + ]:       19503 :             if (pubkey.IsValid() && !pubkey.IsValidNonHybrid()) {
    1753         [ +  - ]:           4 :                 error = "Hybrid public keys are not allowed";
    1754                 :           4 :                 return {};
    1755                 :             :             }
    1756   [ +  -  +  + ]:       19499 :             if (pubkey.IsFullyValid()) {
    1757   [ +  +  +  + ]:         943 :                 if (permit_uncompressed || pubkey.IsCompressed()) {
    1758   [ +  -  +  - ]:         939 :                     ret.emplace_back(std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, false));
    1759                 :         939 :                     return ret;
    1760                 :             :                 } else {
    1761         [ +  - ]:           4 :                     error = "Uncompressed keys are not allowed";
    1762                 :           4 :                     return {};
    1763                 :             :                 }
    1764   [ -  +  +  -  :       18556 :             } else if (data.size() == 32 && ctx == ParseScriptContext::P2TR) {
                   +  + ]
    1765                 :       18555 :                 unsigned char fullkey[33] = {0x02};
    1766                 :       18555 :                 std::copy(data.begin(), data.end(), fullkey + 1);
    1767                 :       18555 :                 pubkey.Set(std::begin(fullkey), std::end(fullkey));
    1768   [ +  -  +  - ]:       18555 :                 if (pubkey.IsFullyValid()) {
    1769   [ +  -  +  - ]:       18555 :                     ret.emplace_back(std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, true));
    1770                 :       18555 :                     return ret;
    1771                 :             :                 }
    1772                 :             :             }
    1773         [ +  - ]:           1 :             error = strprintf("Pubkey '%s' is invalid", str);
    1774                 :           1 :             return {};
    1775                 :       19503 :         }
    1776         [ +  - ]:         698 :         CKey key = DecodeSecret(str);
    1777         [ +  + ]:         698 :         if (key.IsValid()) {
    1778   [ +  +  +  + ]:         447 :             if (permit_uncompressed || key.IsCompressed()) {
    1779         [ +  - ]:         442 :                 CPubKey pubkey = key.GetPubKey();
    1780   [ +  -  +  - ]:         442 :                 out.keys.emplace(pubkey.GetID(), key);
    1781   [ +  -  +  - ]:         442 :                 ret.emplace_back(std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, ctx == ParseScriptContext::P2TR));
    1782                 :         442 :                 return ret;
    1783                 :             :             } else {
    1784         [ +  - ]:           5 :                 error = "Uncompressed keys are not allowed";
    1785                 :           5 :                 return {};
    1786                 :             :             }
    1787                 :             :         }
    1788                 :         698 :     }
    1789         [ +  - ]:        7762 :     CExtKey extkey = DecodeExtKey(str);
    1790         [ +  - ]:        7762 :     CExtPubKey extpubkey = DecodeExtPubKey(str);
    1791   [ +  +  +  + ]:        7762 :     if (!extkey.key.IsValid() && !extpubkey.pubkey.IsValid()) {
    1792         [ +  - ]:           3 :         error = strprintf("key '%s' is not valid", str);
    1793                 :           3 :         return {};
    1794                 :             :     }
    1795                 :        7759 :     std::vector<KeyPath> paths;
    1796                 :        7759 :     DeriveType type = ParseDeriveType(split, apostrophe);
    1797   [ +  -  +  + ]:        7759 :     if (!ParseKeyPath(split, paths, apostrophe, error, /*allow_multipath=*/true)) return {};
    1798         [ +  + ]:        7735 :     if (extkey.key.IsValid()) {
    1799         [ +  - ]:         793 :         extpubkey = extkey.Neuter();
    1800   [ +  -  +  - ]:         793 :         out.keys.emplace(extpubkey.pubkey.GetID(), extkey.key);
    1801                 :             :     }
    1802         [ +  + ]:       15796 :     for (auto& path : paths) {
    1803   [ +  -  +  - ]:       16122 :         ret.emplace_back(std::make_unique<BIP32PubkeyProvider>(key_exp_index, extpubkey, std::move(path), type, apostrophe));
    1804                 :             :     }
    1805                 :        7735 :     return ret;
    1806                 :       43245 : }
    1807                 :             : 
    1808                 :             : /** Parse a public key including origin information (if enabled). */
    1809                 :             : // NOLINTNEXTLINE(misc-no-recursion)
    1810                 :       27874 : 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)
    1811                 :             : {
    1812                 :       27874 :     std::vector<std::unique_ptr<PubkeyProvider>> ret;
    1813                 :             : 
    1814                 :       27874 :     using namespace script;
    1815                 :             : 
    1816                 :             :     // musig cannot be nested inside of an origin
    1817                 :       27874 :     std::span<const char> span = sp;
    1818   [ +  -  +  -  :       27874 :     if (Const("musig(", span, /*skip=*/false)) {
                   +  + ]
    1819         [ +  + ]:         134 :         if (ctx != ParseScriptContext::P2TR) {
    1820         [ +  - ]:          12 :             error = "musig() is only allowed in tr() and rawtr()";
    1821                 :          12 :             return {};
    1822                 :             :         }
    1823                 :             : 
    1824                 :             :         // Split the span on the end parentheses. The end parentheses must
    1825                 :             :         // be included in the resulting span so that Expr is happy.
    1826         [ +  - ]:         122 :         auto split = Split(sp, ')', /*include_sep=*/true);
    1827   [ -  +  +  + ]:         122 :         if (split.size() > 2) {
    1828         [ +  - ]:           2 :             error = "Too many ')' in musig() expression";
    1829                 :           2 :             return {};
    1830                 :             :         }
    1831   [ +  -  +  -  :         120 :         std::span<const char> expr(split.at(0).begin(), split.at(0).end());
                   +  - ]
    1832   [ +  -  +  -  :         120 :         if (!Func("musig", expr)) {
                   +  + ]
    1833         [ +  - ]:           2 :             error = "Invalid musig() expression";
    1834                 :           2 :             return {};
    1835                 :             :         }
    1836                 :             : 
    1837                 :             :         // Parse the participant pubkeys
    1838                 :         118 :         bool any_ranged = false;
    1839                 :         118 :         bool all_bip32 = true;
    1840                 :         118 :         std::vector<std::vector<std::unique_ptr<PubkeyProvider>>> providers;
    1841                 :         118 :         bool any_key_parsed = false;
    1842                 :         118 :         size_t max_multipath_len = 0;
    1843         [ +  + ]:         429 :         while (expr.size()) {
    1844   [ +  +  +  -  :         506 :             if (any_key_parsed && !Const(",", expr)) {
          +  -  -  +  -  
                +  -  - ]
    1845         [ #  # ]:           0 :                 error = strprintf("musig(): expected ',', got '%c'", expr[0]);
    1846                 :           0 :                 return {};
    1847                 :             :             }
    1848         [ +  - ]:         311 :             auto arg = Expr(expr);
    1849         [ +  - ]:         311 :             auto pk = ParsePubkey(key_exp_index, arg, ParseScriptContext::MUSIG, out, error);
    1850         [ -  + ]:         311 :             if (pk.empty()) {
    1851         [ #  # ]:           0 :                 error = strprintf("musig(): %s", error);
    1852                 :           0 :                 return {};
    1853                 :             :             }
    1854                 :         311 :             any_key_parsed = true;
    1855                 :             : 
    1856   [ +  +  +  -  :         562 :             any_ranged = any_ranged || pk.at(0)->IsRange();
                   +  + ]
    1857   [ +  +  +  -  :         606 :             all_bip32 = all_bip32 &&  pk.at(0)->IsBIP32();
                   +  + ]
    1858                 :             : 
    1859   [ -  +  +  + ]:         311 :             max_multipath_len = std::max(max_multipath_len, pk.size());
    1860                 :             : 
    1861         [ +  - ]:         311 :             providers.emplace_back(std::move(pk));
    1862                 :         311 :             key_exp_index++;
    1863                 :         311 :         }
    1864         [ +  + ]:         118 :         if (!any_key_parsed) {
    1865         [ +  - ]:           2 :             error = "musig(): Must contain key expressions";
    1866                 :           2 :             return {};
    1867                 :             :         }
    1868                 :             : 
    1869                 :             :         // Parse any derivation
    1870                 :         116 :         DeriveType deriv_type = DeriveType::NO;
    1871                 :         116 :         std::vector<KeyPath> derivation_multipaths;
    1872   [ -  +  +  -  :         348 :         if (split.size() == 2 && Const("/", split.at(1), /*skip=*/false)) {
          +  -  +  -  +  
                +  +  + ]
    1873         [ +  + ]:          83 :             if (!all_bip32) {
    1874         [ +  - ]:           4 :                 error = "musig(): derivation requires all participants to be xpubs or xprvs";
    1875                 :           4 :                 return {};
    1876                 :             :             }
    1877         [ +  + ]:          79 :             if (any_ranged) {
    1878         [ +  - ]:           4 :                 error = "musig(): Cannot have ranged participant keys if musig() also has derivation";
    1879                 :           4 :                 return {};
    1880                 :             :             }
    1881                 :          75 :             bool dummy = false;
    1882   [ +  -  +  - ]:          75 :             auto deriv_split = Split(split.at(1), '/');
    1883                 :          75 :             deriv_type = ParseDeriveType(deriv_split, dummy);
    1884         [ +  + ]:          75 :             if (deriv_type == DeriveType::HARDENED) {
    1885         [ +  - ]:           2 :                 error = "musig(): Cannot have hardened child derivation";
    1886                 :           2 :                 return {};
    1887                 :             :             }
    1888                 :          73 :             bool has_hardened = false;
    1889   [ +  -  -  + ]:          73 :             if (!ParseKeyPath(deriv_split, derivation_multipaths, dummy, error, /*allow_multipath=*/true, has_hardened)) {
    1890         [ #  # ]:           0 :                 error = "musig(): " + error;
    1891                 :           0 :                 return {};
    1892                 :             :             }
    1893         [ +  + ]:          73 :             if (has_hardened) {
    1894         [ +  - ]:           2 :                 error = "musig(): cannot have hardened derivation steps";
    1895                 :           2 :                 return {};
    1896                 :             :             }
    1897                 :          75 :         } else {
    1898         [ +  - ]:          33 :             derivation_multipaths.emplace_back();
    1899                 :             :         }
    1900                 :             : 
    1901                 :             :         // Makes sure that all providers vectors in providers are the given length, or exactly length 1
    1902                 :             :         // Length 1 vectors have the single provider cloned until it matches the given length.
    1903                 :         165 :         const auto& clone_providers = [&providers](size_t length) -> bool {
    1904         [ +  + ]:         238 :             for (auto& multipath_providers : providers) {
    1905   [ -  +  +  + ]:         177 :                 if (multipath_providers.size() == 1) {
    1906         [ +  + ]:         252 :                     for (size_t i = 1; i < length; ++i) {
    1907         [ +  - ]:         140 :                         multipath_providers.emplace_back(multipath_providers.at(0)->Clone());
    1908                 :             :                     }
    1909         [ +  - ]:          65 :                 } else if (multipath_providers.size() != length) {
    1910                 :             :                     return false;
    1911                 :             :                 }
    1912                 :             :             }
    1913                 :             :             return true;
    1914                 :         104 :         };
    1915                 :             : 
    1916                 :             :         // Emplace the final MuSigPubkeyProvider into ret with the pubkey providers from the specified provider vectors index
    1917                 :             :         // and the path from the specified path index
    1918                 :         284 :         const auto& emplace_final_provider = [&ret, &key_exp_index, &deriv_type, &derivation_multipaths, &providers](size_t vec_idx, size_t path_idx) -> void {
    1919                 :         180 :             KeyPath& path = derivation_multipaths.at(path_idx);
    1920                 :         180 :             std::vector<std::unique_ptr<PubkeyProvider>> pubs;
    1921   [ -  +  +  - ]:         180 :             pubs.reserve(providers.size());
    1922         [ +  + ]:         687 :             for (auto& vec : providers) {
    1923   [ +  -  +  - ]:         507 :                 pubs.emplace_back(std::move(vec.at(vec_idx)));
    1924                 :             :             }
    1925   [ +  -  +  - ]:         180 :             ret.emplace_back(std::make_unique<MuSigPubkeyProvider>(key_exp_index, std::move(pubs), path, deriv_type));
    1926                 :         180 :         };
    1927                 :             : 
    1928   [ +  +  +  + ]:         130 :         if (max_multipath_len > 1 && derivation_multipaths.size() > 1) {
    1929         [ +  - ]:           2 :             error = "musig(): Cannot have multipath participant keys if musig() is also multipath";
    1930                 :           2 :             return {};
    1931         [ +  + ]:         102 :         } else if (max_multipath_len > 1) {
    1932   [ +  -  -  + ]:          24 :             if (!clone_providers(max_multipath_len)) {
    1933         [ #  # ]:           0 :                 error = strprintf("musig(): Multipath derivation paths have mismatched lengths");
    1934                 :           0 :                 return {};
    1935                 :             :             }
    1936         [ +  + ]:          82 :             for (size_t i = 0; i < max_multipath_len; ++i) {
    1937                 :             :                 // Final MuSigPubkeyProvider uses participant pubkey providers at each multipath position, and the first (and only) path
    1938         [ +  - ]:          58 :                 emplace_final_provider(i, 0);
    1939                 :             :             }
    1940   [ -  +  +  + ]:          78 :         } else if (derivation_multipaths.size() > 1) {
    1941                 :             :             // All key provider vectors should be length 1. Clone them until they have the same length as paths
    1942   [ +  -  -  + ]:          37 :             if (!Assume(clone_providers(derivation_multipaths.size()))) {
    1943         [ #  # ]:           0 :                 error = "musig(): Multipath derivation path with multipath participants is disallowed"; // This error is unreachable due to earlier check
    1944                 :           0 :                 return {};
    1945                 :             :             }
    1946   [ -  +  +  + ]:         118 :             for (size_t i = 0; i < derivation_multipaths.size(); ++i) {
    1947                 :             :                 // Final MuSigPubkeyProvider uses cloned participant pubkey providers, and the multipath derivation paths
    1948         [ +  - ]:          81 :                 emplace_final_provider(i, i);
    1949                 :             :             }
    1950                 :             :         } else {
    1951                 :             :             // No multipath derivation, MuSigPubkeyProvider uses the first (and only) participant pubkey providers, and the first (and only) path
    1952         [ +  - ]:          41 :             emplace_final_provider(0, 0);
    1953                 :             :         }
    1954                 :         102 :         return ret;
    1955                 :         240 :     }
    1956                 :             : 
    1957         [ +  - ]:       27740 :     auto origin_split = Split(sp, ']');
    1958   [ -  +  +  + ]:       27740 :     if (origin_split.size() > 2) {
    1959         [ +  - ]:           4 :         error = "Multiple ']' characters found for a single pubkey";
    1960                 :           4 :         return {};
    1961                 :             :     }
    1962                 :             :     // This is set if either the origin or path suffix contains a hardened derivation.
    1963                 :       27736 :     bool apostrophe = false;
    1964         [ +  + ]:       27736 :     if (origin_split.size() == 1) {
    1965         [ +  - ]:       22773 :         return ParsePubkeyInner(key_exp_index, origin_split[0], ctx, out, apostrophe, error);
    1966                 :             :     }
    1967   [ +  -  +  + ]:        4963 :     if (origin_split[0].empty() || origin_split[0][0] != '[') {
    1968                 :           6 :         error = strprintf("Key origin start '[ character expected but not found, got '%c' instead",
    1969   [ +  -  +  - ]:           2 :                           origin_split[0].empty() ? /** empty, implies split char */ ']' : origin_split[0][0]);
    1970                 :           2 :         return {};
    1971                 :             :     }
    1972         [ +  - ]:        4961 :     auto slash_split = Split(origin_split[0].subspan(1), '/');
    1973         [ +  + ]:        4961 :     if (slash_split[0].size() != 8) {
    1974         [ +  - ]:           6 :         error = strprintf("Fingerprint is not 4 bytes (%u characters instead of 8 characters)", slash_split[0].size());
    1975                 :           6 :         return {};
    1976                 :             :     }
    1977   [ +  -  -  + ]:        9910 :     std::string fpr_hex = std::string(slash_split[0].begin(), slash_split[0].end());
    1978   [ -  +  +  -  :        4955 :     if (!IsHex(fpr_hex)) {
                   +  + ]
    1979         [ +  - ]:           2 :         error = strprintf("Fingerprint '%s' is not hex", fpr_hex);
    1980                 :           2 :         return {};
    1981                 :             :     }
    1982   [ -  +  +  - ]:        4953 :     auto fpr_bytes = ParseHex(fpr_hex);
    1983         [ -  + ]:        4953 :     KeyOriginInfo info;
    1984                 :        4953 :     static_assert(sizeof(info.fingerprint) == 4, "Fingerprint must be 4 bytes");
    1985   [ -  +  -  + ]:        4953 :     assert(fpr_bytes.size() == 4);
    1986                 :        4953 :     std::copy(fpr_bytes.begin(), fpr_bytes.end(), info.fingerprint);
    1987                 :        4953 :     std::vector<KeyPath> path;
    1988   [ +  -  +  + ]:        4953 :     if (!ParseKeyPath(slash_split, path, apostrophe, error, /*allow_multipath=*/false)) return {};
    1989   [ +  -  +  - ]:        4951 :     info.path = path.at(0);
    1990         [ +  - ]:        4951 :     auto providers = ParsePubkeyInner(key_exp_index, origin_split[1], ctx, out, apostrophe, error);
    1991         [ +  + ]:        4951 :     if (providers.empty()) return {};
    1992   [ -  +  +  - ]:        4949 :     ret.reserve(providers.size());
    1993         [ +  + ]:        9953 :     for (auto& prov : providers) {
    1994   [ +  -  +  - ]:       10008 :         ret.emplace_back(std::make_unique<OriginPubkeyProvider>(key_exp_index, info, std::move(prov), apostrophe));
    1995                 :             :     }
    1996                 :        4949 :     return ret;
    1997                 :       42743 : }
    1998                 :             : 
    1999                 :      325139 : std::unique_ptr<PubkeyProvider> InferPubkey(const CPubKey& pubkey, ParseScriptContext ctx, const SigningProvider& provider)
    2000                 :             : {
    2001                 :             :     // Key cannot be hybrid
    2002         [ +  + ]:      325139 :     if (!pubkey.IsValidNonHybrid()) {
    2003                 :           7 :         return nullptr;
    2004                 :             :     }
    2005                 :             :     // Uncompressed is only allowed in TOP and P2SH contexts
    2006   [ +  +  +  + ]:      325132 :     if (ctx != ParseScriptContext::TOP && ctx != ParseScriptContext::P2SH && !pubkey.IsCompressed()) {
    2007                 :           5 :         return nullptr;
    2008                 :             :     }
    2009                 :      325127 :     std::unique_ptr<PubkeyProvider> key_provider = std::make_unique<ConstPubkeyProvider>(0, pubkey, false);
    2010         [ +  - ]:      325127 :     KeyOriginInfo info;
    2011   [ +  -  +  -  :      325127 :     if (provider.GetKeyOrigin(pubkey.GetID(), info)) {
                   +  + ]
    2012   [ +  -  -  + ]:      324149 :         return std::make_unique<OriginPubkeyProvider>(0, std::move(info), std::move(key_provider), /*apostrophe=*/false);
    2013                 :             :     }
    2014                 :         978 :     return key_provider;
    2015                 :      325127 : }
    2016                 :             : 
    2017                 :      129942 : std::unique_ptr<PubkeyProvider> InferXOnlyPubkey(const XOnlyPubKey& xkey, ParseScriptContext ctx, const SigningProvider& provider)
    2018                 :             : {
    2019                 :      129942 :     CPubKey pubkey{xkey.GetEvenCorrespondingCPubKey()};
    2020                 :      129942 :     std::unique_ptr<PubkeyProvider> key_provider = std::make_unique<ConstPubkeyProvider>(0, pubkey, true);
    2021         [ +  - ]:      129942 :     KeyOriginInfo info;
    2022   [ +  -  +  + ]:      129942 :     if (provider.GetKeyOriginByXOnly(xkey, info)) {
    2023   [ +  -  -  + ]:      113657 :         return std::make_unique<OriginPubkeyProvider>(0, std::move(info), std::move(key_provider), /*apostrophe=*/false);
    2024                 :             :     }
    2025                 :       16285 :     return key_provider;
    2026                 :      129942 : }
    2027                 :             : 
    2028                 :             : /**
    2029                 :             :  * The context for parsing a Miniscript descriptor (either from Script or from its textual representation).
    2030                 :             :  */
    2031                 :        1039 : struct KeyParser {
    2032                 :             :     //! The Key type is an index in DescriptorImpl::m_pubkey_args
    2033                 :             :     using Key = uint32_t;
    2034                 :             :     //! Must not be nullptr if parsing from string.
    2035                 :             :     FlatSigningProvider* m_out;
    2036                 :             :     //! Must not be nullptr if parsing from Script.
    2037                 :             :     const SigningProvider* m_in;
    2038                 :             :     //! List of multipath expanded keys contained in the Miniscript.
    2039                 :             :     mutable std::vector<std::vector<std::unique_ptr<PubkeyProvider>>> m_keys;
    2040                 :             :     //! Used to detect key parsing errors within a Miniscript.
    2041                 :             :     mutable std::string m_key_parsing_error;
    2042                 :             :     //! The script context we're operating within (Tapscript or P2WSH).
    2043                 :             :     const miniscript::MiniscriptContext m_script_ctx;
    2044                 :             :     //! The number of keys that were parsed before starting to parse this Miniscript descriptor.
    2045                 :             :     uint32_t m_offset;
    2046                 :             : 
    2047                 :        1039 :     KeyParser(FlatSigningProvider* out LIFETIMEBOUND, const SigningProvider* in LIFETIMEBOUND,
    2048                 :             :               miniscript::MiniscriptContext ctx, uint32_t offset = 0)
    2049                 :        1039 :         : m_out(out), m_in(in), m_script_ctx(ctx), m_offset(offset) {}
    2050                 :             : 
    2051                 :        4229 :     bool KeyCompare(const Key& a, const Key& b) const {
    2052                 :        4229 :         return *m_keys.at(a).at(0) < *m_keys.at(b).at(0);
    2053                 :             :     }
    2054                 :             : 
    2055                 :        1785 :     ParseScriptContext ParseContext() const {
    2056      [ +  -  + ]:        1785 :         switch (m_script_ctx) {
    2057                 :             :             case miniscript::MiniscriptContext::P2WSH: return ParseScriptContext::P2WSH;
    2058                 :         460 :             case miniscript::MiniscriptContext::TAPSCRIPT: return ParseScriptContext::P2TR;
    2059                 :             :         }
    2060                 :           0 :         assert(false);
    2061                 :             :     }
    2062                 :             : 
    2063                 :         420 :     template<typename I> std::optional<Key> FromString(I begin, I end) const
    2064                 :             :     {
    2065         [ -  + ]:         420 :         assert(m_out);
    2066         [ -  + ]:         420 :         Key key = m_keys.size();
    2067                 :         420 :         uint32_t exp_index = m_offset + key;
    2068                 :         420 :         auto pk = ParsePubkey(exp_index, {&*begin, &*end}, ParseContext(), *m_out, m_key_parsing_error);
    2069         [ +  + ]:         420 :         if (pk.empty()) return {};
    2070         [ +  - ]:         416 :         m_keys.emplace_back(std::move(pk));
    2071                 :         416 :         return key;
    2072                 :         420 :     }
    2073                 :             : 
    2074                 :          30 :     std::optional<std::string> ToString(const Key& key) const
    2075                 :             :     {
    2076                 :          30 :         return m_keys.at(key).at(0)->ToString();
    2077                 :             :     }
    2078                 :             : 
    2079                 :        1095 :     template<typename I> std::optional<Key> FromPKBytes(I begin, I end) const
    2080                 :             :     {
    2081         [ -  + ]:        1095 :         assert(m_in);
    2082         [ -  + ]:        1095 :         Key key = m_keys.size();
    2083   [ +  +  +  - ]:        1095 :         if (miniscript::IsTapscript(m_script_ctx) && end - begin == 32) {
    2084                 :         222 :             XOnlyPubKey pubkey;
    2085                 :         222 :             std::copy(begin, end, pubkey.begin());
    2086         [ +  - ]:         222 :             if (auto pubkey_provider = InferXOnlyPubkey(pubkey, ParseContext(), *m_in)) {
    2087         [ +  - ]:         222 :                 m_keys.emplace_back();
    2088         [ +  - ]:         222 :                 m_keys.back().push_back(std::move(pubkey_provider));
    2089                 :         222 :                 return key;
    2090                 :             :             }
    2091         [ +  - ]:         873 :         } else if (!miniscript::IsTapscript(m_script_ctx)) {
    2092                 :         873 :             CPubKey pubkey(begin, end);
    2093         [ +  + ]:         873 :             if (auto pubkey_provider = InferPubkey(pubkey, ParseContext(), *m_in)) {
    2094         [ +  - ]:         871 :                 m_keys.emplace_back();
    2095         [ +  - ]:         871 :                 m_keys.back().push_back(std::move(pubkey_provider));
    2096                 :         871 :                 return key;
    2097                 :             :             }
    2098                 :             :         }
    2099                 :           2 :         return {};
    2100                 :             :     }
    2101                 :             : 
    2102         [ -  + ]:         270 :     template<typename I> std::optional<Key> FromPKHBytes(I begin, I end) const
    2103                 :             :     {
    2104         [ -  + ]:         270 :         assert(end - begin == 20);
    2105         [ -  + ]:         270 :         assert(m_in);
    2106                 :         270 :         uint160 hash;
    2107                 :         270 :         std::copy(begin, end, hash.begin());
    2108                 :         270 :         CKeyID keyid(hash);
    2109                 :         270 :         CPubKey pubkey;
    2110         [ +  - ]:         270 :         if (m_in->GetPubKey(keyid, pubkey)) {
    2111         [ +  + ]:         270 :             if (auto pubkey_provider = InferPubkey(pubkey, ParseContext(), *m_in)) {
    2112         [ -  + ]:         268 :                 Key key = m_keys.size();
    2113         [ +  - ]:         268 :                 m_keys.emplace_back();
    2114         [ +  - ]:         268 :                 m_keys.back().push_back(std::move(pubkey_provider));
    2115                 :         268 :                 return key;
    2116                 :             :             }
    2117                 :             :         }
    2118                 :           2 :         return {};
    2119                 :             :     }
    2120                 :             : 
    2121                 :      996602 :     miniscript::MiniscriptContext MsContext() const {
    2122   [ +  -  +  -  :      996602 :         return m_script_ctx;
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          -  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  -  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  -  
          +  -  +  -  -  
          -  -  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  +  +  
                -  +  - ]
    2123                 :             :     }
    2124                 :             : };
    2125                 :             : 
    2126                 :             : /** Parse a script in a particular context. */
    2127                 :             : // NOLINTNEXTLINE(misc-no-recursion)
    2128                 :       13079 : std::vector<std::unique_ptr<DescriptorImpl>> ParseScript(uint32_t& key_exp_index, std::span<const char>& sp, ParseScriptContext ctx, FlatSigningProvider& out, std::string& error)
    2129                 :             : {
    2130                 :       13079 :     using namespace script;
    2131                 :       13079 :     Assume(ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH || ctx == ParseScriptContext::P2TR);
    2132                 :       13079 :     std::vector<std::unique_ptr<DescriptorImpl>> ret;
    2133         [ +  - ]:       13079 :     auto expr = Expr(sp);
    2134   [ +  -  +  -  :       13079 :     if (Func("pk", expr)) {
                   +  + ]
    2135         [ +  - ]:         656 :         auto pubkeys = ParsePubkey(key_exp_index, expr, ctx, out, error);
    2136         [ +  + ]:         656 :         if (pubkeys.empty()) {
    2137         [ +  - ]:          12 :             error = strprintf("pk(): %s", error);
    2138                 :          12 :             return {};
    2139                 :             :         }
    2140                 :         644 :         ++key_exp_index;
    2141         [ +  + ]:        1406 :         for (auto& pubkey : pubkeys) {
    2142   [ +  -  +  - ]:        1524 :             ret.emplace_back(std::make_unique<PKDescriptor>(std::move(pubkey), ctx == ParseScriptContext::P2TR));
    2143                 :             :         }
    2144                 :         644 :         return ret;
    2145                 :         656 :     }
    2146   [ +  +  +  -  :       24645 :     if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH) && Func("pkh", expr)) {
          +  -  +  +  +  
                      + ]
    2147         [ +  - ]:        1631 :         auto pubkeys = ParsePubkey(key_exp_index, expr, ctx, out, error);
    2148         [ +  + ]:        1631 :         if (pubkeys.empty()) {
    2149         [ +  - ]:          19 :             error = strprintf("pkh(): %s", error);
    2150                 :          19 :             return {};
    2151                 :             :         }
    2152                 :        1612 :         ++key_exp_index;
    2153         [ +  + ]:        3244 :         for (auto& pubkey : pubkeys) {
    2154   [ +  -  +  - ]:        3264 :             ret.emplace_back(std::make_unique<PKHDescriptor>(std::move(pubkey)));
    2155                 :             :         }
    2156                 :        1612 :         return ret;
    2157                 :        1631 :     }
    2158   [ +  +  +  -  :       19385 :     if (ctx == ParseScriptContext::TOP && Func("combo", expr)) {
          +  -  +  +  +  
                      + ]
    2159         [ +  - ]:         546 :         auto pubkeys = ParsePubkey(key_exp_index, expr, ctx, out, error);
    2160         [ +  + ]:         546 :         if (pubkeys.empty()) {
    2161         [ +  - ]:           5 :             error = strprintf("combo(): %s", error);
    2162                 :           5 :             return {};
    2163                 :             :         }
    2164                 :         541 :         ++key_exp_index;
    2165         [ +  + ]:        1082 :         for (auto& pubkey : pubkeys) {
    2166   [ +  -  +  - ]:        1082 :             ret.emplace_back(std::make_unique<ComboDescriptor>(std::move(pubkey)));
    2167                 :             :         }
    2168                 :         541 :         return ret;
    2169   [ +  -  +  -  :       10792 :     } else if (Func("combo", expr)) {
                   +  + ]
    2170         [ +  - ]:           2 :         error = "Can only have combo() at top level";
    2171                 :           2 :         return {};
    2172                 :             :     }
    2173   [ +  -  +  - ]:       10244 :     const bool multi = Func("multi", expr);
    2174   [ +  +  +  -  :       20270 :     const bool sortedmulti = !multi && Func("sortedmulti", expr);
             +  -  +  + ]
    2175   [ +  +  +  -  :       20246 :     const bool multi_a = !(multi || sortedmulti) && Func("multi_a", expr);
             +  -  +  + ]
    2176   [ +  +  +  +  :       20156 :     const bool sortedmulti_a = !(multi || sortedmulti || multi_a) && Func("sortedmulti_a", expr);
          +  -  +  -  +  
                      + ]
    2177   [ +  +  +  +  :       10244 :     if (((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH) && (multi || sortedmulti)) ||
             +  +  +  + ]
    2178   [ +  +  +  + ]:         201 :         (ctx == ParseScriptContext::P2TR && (multi_a || sortedmulti_a))) {
    2179         [ +  - ]:         374 :         auto threshold = Expr(expr);
    2180                 :         374 :         uint32_t thres;
    2181                 :         374 :         std::vector<std::vector<std::unique_ptr<PubkeyProvider>>> providers; // List of multipath expanded pubkeys
    2182         [ +  + ]:         374 :         if (const auto maybe_thres{ToIntegral<uint32_t>(std::string_view{threshold.begin(), threshold.end()})}) {
    2183                 :         370 :             thres = *maybe_thres;
    2184                 :             :         } else {
    2185   [ +  -  +  - ]:           8 :             error = strprintf("Multi threshold '%s' is not valid", std::string(threshold.begin(), threshold.end()));
    2186                 :           4 :             return {};
    2187                 :             :         }
    2188                 :         370 :         size_t script_size = 0;
    2189                 :         370 :         size_t max_providers_len = 0;
    2190         [ +  + ]:       19341 :         while (expr.size()) {
    2191   [ +  -  +  -  :       18985 :             if (!Const(",", expr)) {
                   -  + ]
    2192         [ #  # ]:           0 :                 error = strprintf("Multi: expected ',', got '%c'", expr[0]);
    2193                 :           0 :                 return {};
    2194                 :             :             }
    2195         [ +  - ]:       18985 :             auto arg = Expr(expr);
    2196         [ +  - ]:       18985 :             auto pks = ParsePubkey(key_exp_index, arg, ctx, out, error);
    2197         [ +  + ]:       18985 :             if (pks.empty()) {
    2198         [ +  - ]:          14 :                 error = strprintf("Multi: %s", error);
    2199                 :          14 :                 return {};
    2200                 :             :             }
    2201   [ +  -  +  - ]:       18971 :             script_size += pks.at(0)->GetSize() + 1;
    2202   [ -  +  +  + ]:       18971 :             max_providers_len = std::max(max_providers_len, pks.size());
    2203         [ +  - ]:       18971 :             providers.emplace_back(std::move(pks));
    2204                 :       18971 :             key_exp_index++;
    2205                 :       18985 :         }
    2206   [ +  +  +  +  :         580 :         if ((multi || sortedmulti) && (providers.empty() || providers.size() > MAX_PUBKEYS_PER_MULTISIG)) {
             +  -  -  + ]
    2207   [ #  #  #  # ]:           0 :             error = strprintf("Cannot have %u keys in multisig; must have between 1 and %d keys, inclusive", providers.size(), MAX_PUBKEYS_PER_MULTISIG);
    2208                 :           0 :             return {};
    2209   [ +  +  +  +  :         488 :         } else if ((multi_a || sortedmulti_a) && (providers.empty() || providers.size() > MAX_PUBKEYS_PER_MULTI_A)) {
             +  -  -  + ]
    2210   [ #  #  #  # ]:           0 :             error = strprintf("Cannot have %u keys in multi_a; must have between 1 and %d keys, inclusive", providers.size(), MAX_PUBKEYS_PER_MULTI_A);
    2211                 :           0 :             return {};
    2212         [ +  + ]:         356 :         } else if (thres < 1) {
    2213         [ +  - ]:           2 :             error = strprintf("Multisig threshold cannot be %d, must be at least 1", thres);
    2214                 :           2 :             return {};
    2215   [ -  +  +  + ]:         354 :         } else if (thres > providers.size()) {
    2216         [ +  - ]:           2 :             error = strprintf("Multisig threshold cannot be larger than the number of keys; threshold is %d but only %u keys specified", thres, providers.size());
    2217                 :           2 :             return {};
    2218                 :             :         }
    2219         [ +  + ]:         352 :         if (ctx == ParseScriptContext::TOP) {
    2220         [ +  + ]:          24 :             if (providers.size() > 3) {
    2221         [ +  - ]:           2 :                 error = strprintf("Cannot have %u pubkeys in bare multisig; only at most 3 pubkeys", providers.size());
    2222                 :           2 :                 return {};
    2223                 :             :             }
    2224                 :             :         }
    2225         [ +  + ]:         350 :         if (ctx == ParseScriptContext::P2SH) {
    2226                 :             :             // This limits the maximum number of compressed pubkeys to 15.
    2227         [ +  + ]:          58 :             if (script_size + 3 > MAX_SCRIPT_ELEMENT_SIZE) {
    2228         [ +  - ]:           4 :                 error = strprintf("P2SH script is too large, %d bytes is larger than %d bytes", script_size + 3, MAX_SCRIPT_ELEMENT_SIZE);
    2229                 :           4 :                 return {};
    2230                 :             :             }
    2231                 :             :         }
    2232                 :             : 
    2233                 :             :         // Make sure all vecs are of the same length, or exactly length 1
    2234                 :             :         // For length 1 vectors, clone key providers until vector is the same length
    2235         [ +  + ]:       19232 :         for (auto& vec : providers) {
    2236   [ -  +  +  + ]:       18888 :             if (vec.size() == 1) {
    2237         [ +  + ]:       18874 :                 for (size_t i = 1; i < max_providers_len; ++i) {
    2238   [ +  -  +  -  :          18 :                     vec.emplace_back(vec.at(0)->Clone());
                   +  - ]
    2239                 :             :                 }
    2240         [ +  + ]:          32 :             } else if (vec.size() != max_providers_len) {
    2241         [ +  - ]:           2 :                 error = strprintf("multi(): Multipath derivation paths have mismatched lengths");
    2242                 :           2 :                 return {};
    2243                 :             :             }
    2244                 :             :         }
    2245                 :             : 
    2246                 :             :         // Build the final descriptors vector
    2247         [ +  + ]:         709 :         for (size_t i = 0; i < max_providers_len; ++i) {
    2248                 :             :             // Build final pubkeys vectors by retrieving the i'th subscript for each vector in subscripts
    2249                 :         365 :             std::vector<std::unique_ptr<PubkeyProvider>> pubs;
    2250   [ -  +  +  - ]:         365 :             pubs.reserve(providers.size());
    2251         [ +  + ]:       19303 :             for (auto& pub : providers) {
    2252   [ +  -  +  - ]:       18938 :                 pubs.emplace_back(std::move(pub.at(i)));
    2253                 :             :             }
    2254   [ +  +  +  + ]:         365 :             if (multi || sortedmulti) {
    2255   [ +  -  +  - ]:         466 :                 ret.emplace_back(std::make_unique<MultisigDescriptor>(thres, std::move(pubs), sortedmulti));
    2256                 :             :             } else {
    2257   [ +  -  +  - ]:         264 :                 ret.emplace_back(std::make_unique<MultiADescriptor>(thres, std::move(pubs), sortedmulti_a));
    2258                 :             :             }
    2259                 :         365 :         }
    2260                 :         344 :         return ret;
    2261   [ +  -  -  + ]:       10244 :     } else if (multi || sortedmulti) {
    2262         [ #  # ]:           0 :         error = "Can only have multi/sortedmulti at top level, in sh(), or in wsh()";
    2263                 :           0 :         return {};
    2264   [ +  -  -  + ]:        9870 :     } else if (multi_a || sortedmulti_a) {
    2265         [ #  # ]:           0 :         error = "Can only have multi_a/sortedmulti_a inside tr()";
    2266                 :           0 :         return {};
    2267                 :             :     }
    2268   [ +  +  +  -  :       19573 :     if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH) && Func("wpkh", expr)) {
          +  -  +  +  +  
                      + ]
    2269         [ +  - ]:        3377 :         auto pubkeys = ParsePubkey(key_exp_index, expr, ParseScriptContext::P2WPKH, out, error);
    2270         [ +  + ]:        3377 :         if (pubkeys.empty()) {
    2271         [ +  - ]:          27 :             error = strprintf("wpkh(): %s", error);
    2272                 :          27 :             return {};
    2273                 :             :         }
    2274                 :        3350 :         key_exp_index++;
    2275         [ +  + ]:        6717 :         for (auto& pubkey : pubkeys) {
    2276   [ +  -  +  - ]:        6734 :             ret.emplace_back(std::make_unique<WPKHDescriptor>(std::move(pubkey)));
    2277                 :             :         }
    2278                 :        3350 :         return ret;
    2279   [ +  -  +  -  :        9870 :     } else if (Func("wpkh", expr)) {
                   +  + ]
    2280         [ +  - ]:           3 :         error = "Can only have wpkh() at top level or inside sh()";
    2281                 :           3 :         return {};
    2282                 :             :     }
    2283   [ +  +  +  -  :       12739 :     if (ctx == ParseScriptContext::TOP && Func("sh", expr)) {
          +  -  +  +  +  
                      + ]
    2284         [ +  - ]:        1769 :         auto descs = ParseScript(key_exp_index, expr, ParseScriptContext::P2SH, out, error);
    2285   [ +  +  +  - ]:        1769 :         if (descs.empty() || expr.size()) return {};
    2286                 :        1743 :         std::vector<std::unique_ptr<DescriptorImpl>> ret;
    2287   [ -  +  +  - ]:        1743 :         ret.reserve(descs.size());
    2288         [ +  + ]:        3505 :         for (auto& desc : descs) {
    2289   [ +  -  +  -  :        1762 :             ret.push_back(std::make_unique<SHDescriptor>(std::move(desc)));
                   -  + ]
    2290                 :             :         }
    2291                 :        1743 :         return ret;
    2292   [ +  -  +  -  :        6490 :     } else if (Func("sh", expr)) {
                   +  + ]
    2293         [ +  - ]:           6 :         error = "Can only have sh() at top level";
    2294                 :           6 :         return {};
    2295                 :             :     }
    2296   [ +  +  +  -  :        9269 :     if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH) && Func("wsh", expr)) {
          +  -  +  +  +  
                      + ]
    2297         [ +  - ]:         281 :         auto descs = ParseScript(key_exp_index, expr, ParseScriptContext::P2WSH, out, error);
    2298   [ +  +  +  - ]:         281 :         if (descs.empty() || expr.size()) return {};
    2299         [ +  + ]:         473 :         for (auto& desc : descs) {
    2300   [ +  -  +  - ]:         480 :             ret.emplace_back(std::make_unique<WSHDescriptor>(std::move(desc)));
    2301                 :             :         }
    2302                 :         233 :         return ret;
    2303   [ +  -  +  -  :        4715 :     } else if (Func("wsh", expr)) {
                   +  + ]
    2304         [ +  - ]:           3 :         error = "Can only have wsh() at top level or inside sh()";
    2305                 :           3 :         return {};
    2306                 :             :     }
    2307   [ +  +  +  -  :        8697 :     if (ctx == ParseScriptContext::TOP && Func("addr", expr)) {
          +  -  +  +  +  
                      + ]
    2308   [ +  -  +  - ]:         182 :         CTxDestination dest = DecodeDestination(std::string(expr.begin(), expr.end()));
    2309   [ +  -  +  + ]:          91 :         if (!IsValidDestination(dest)) {
    2310         [ +  - ]:           3 :             error = "Address is not valid";
    2311                 :           3 :             return {};
    2312                 :             :         }
    2313   [ +  -  +  - ]:          88 :         ret.emplace_back(std::make_unique<AddressDescriptor>(std::move(dest)));
    2314                 :          88 :         return ret;
    2315   [ +  -  +  -  :        4431 :     } else if (Func("addr", expr)) {
                   -  + ]
    2316         [ #  # ]:           0 :         error = "Can only have addr() at top level";
    2317                 :           0 :         return {};
    2318                 :             :     }
    2319   [ +  +  +  -  :        8515 :     if (ctx == ParseScriptContext::TOP && Func("tr", expr)) {
          +  -  +  +  +  
                      + ]
    2320         [ +  - ]:        1883 :         auto arg = Expr(expr);
    2321         [ +  - ]:        1883 :         auto internal_keys = ParsePubkey(key_exp_index, arg, ParseScriptContext::P2TR, out, error);
    2322         [ +  + ]:        1883 :         if (internal_keys.empty()) {
    2323         [ +  - ]:          20 :             error = strprintf("tr(): %s", error);
    2324                 :          20 :             return {};
    2325                 :             :         }
    2326         [ -  + ]:        1863 :         size_t max_providers_len = internal_keys.size();
    2327                 :        1863 :         ++key_exp_index;
    2328                 :        1863 :         std::vector<std::vector<std::unique_ptr<DescriptorImpl>>> subscripts; //!< list of multipath expanded script subexpressions
    2329                 :        1863 :         std::vector<int> depths; //!< depth in the tree of each subexpression (same length subscripts)
    2330         [ +  + ]:        1863 :         if (expr.size()) {
    2331   [ +  -  +  -  :         342 :             if (!Const(",", expr)) {
                   -  + ]
    2332         [ #  # ]:           0 :                 error = strprintf("tr: expected ',', got '%c'", expr[0]);
    2333                 :           0 :                 return {};
    2334                 :             :             }
    2335                 :             :             /** The path from the top of the tree to what we're currently processing.
    2336                 :             :              * branches[i] == false: left branch in the i'th step from the top; true: right branch.
    2337                 :             :              */
    2338                 :         342 :             std::vector<bool> branches;
    2339                 :             :             // Loop over all provided scripts. In every iteration exactly one script will be processed.
    2340                 :             :             // Use a do-loop because inside this if-branch we expect at least one script.
    2341                 :             :             do {
    2342                 :             :                 // First process all open braces.
    2343   [ +  -  +  -  :        1266 :                 while (Const("{", expr)) {
                   +  + ]
    2344         [ +  - ]:         473 :                     branches.push_back(false); // new left branch
    2345         [ -  + ]:         473 :                     if (branches.size() > TAPROOT_CONTROL_MAX_NODE_COUNT) {
    2346         [ #  # ]:           0 :                         error = strprintf("tr() supports at most %i nesting levels", TAPROOT_CONTROL_MAX_NODE_COUNT);
    2347                 :           0 :                         return {};
    2348                 :             :                     }
    2349                 :             :                 }
    2350                 :             :                 // Process the actual script expression.
    2351         [ +  - ]:         793 :                 auto sarg = Expr(expr);
    2352   [ +  -  +  - ]:         793 :                 subscripts.emplace_back(ParseScript(key_exp_index, sarg, ParseScriptContext::P2TR, out, error));
    2353         [ +  + ]:         793 :                 if (subscripts.back().empty()) return {};
    2354   [ -  +  +  + ]:         791 :                 max_providers_len = std::max(max_providers_len, subscripts.back().size());
    2355         [ +  - ]:         791 :                 depths.push_back(branches.size());
    2356                 :             :                 // Process closing braces; one is expected for every right branch we were in.
    2357         [ +  + ]:         902 :                 while (branches.size() && branches.back()) {
    2358   [ +  -  -  +  :         451 :                     if (!Const("}", expr)) {
                   +  - ]
    2359         [ #  # ]:           0 :                         error = strprintf("tr(): expected '}' after script expression");
    2360                 :           0 :                         return {};
    2361                 :             :                     }
    2362   [ -  +  +  + ]:        1693 :                     branches.pop_back(); // move up one level after encountering '}'
    2363                 :             :                 }
    2364                 :             :                 // If after that, we're at the end of a left branch, expect a comma.
    2365   [ +  +  +  - ]:         791 :                 if (branches.size() && !branches.back()) {
    2366   [ +  -  +  -  :         451 :                     if (!Const(",", expr)) {
                   -  + ]
    2367         [ #  # ]:           0 :                         error = strprintf("tr(): expected ',' after script expression");
    2368                 :           0 :                         return {};
    2369                 :             :                     }
    2370                 :         451 :                     branches.back() = true; // And now we're in a right branch.
    2371                 :             :                 }
    2372         [ +  + ]:         791 :             } while (branches.size());
    2373                 :             :             // After we've explored a whole tree, we must be at the end of the expression.
    2374         [ -  + ]:         340 :             if (expr.size()) {
    2375         [ #  # ]:           0 :                 error = strprintf("tr(): expected ')' after script expression");
    2376                 :           0 :                 return {};
    2377                 :             :             }
    2378                 :         342 :         }
    2379   [ +  -  -  + ]:        1861 :         assert(TaprootBuilder::ValidDepths(depths));
    2380                 :             : 
    2381                 :             :         // Make sure all vecs are of the same length, or exactly length 1
    2382                 :             :         // For length 1 vectors, clone subdescs until vector is the same length
    2383         [ +  + ]:        2646 :         for (auto& vec : subscripts) {
    2384   [ -  +  +  + ]:         789 :             if (vec.size() == 1) {
    2385         [ +  + ]:         738 :                 for (size_t i = 1; i < max_providers_len; ++i) {
    2386   [ +  -  +  -  :          20 :                     vec.emplace_back(vec.at(0)->Clone());
                   +  - ]
    2387                 :             :                 }
    2388         [ +  + ]:          71 :             } else if (vec.size() != max_providers_len) {
    2389         [ +  - ]:           4 :                 error = strprintf("tr(): Multipath subscripts have mismatched lengths");
    2390                 :           4 :                 return {};
    2391                 :             :             }
    2392                 :             :         }
    2393                 :             : 
    2394   [ -  +  +  +  :        1857 :         if (internal_keys.size() > 1 && internal_keys.size() != max_providers_len) {
                   +  + ]
    2395         [ +  - ]:           2 :             error = strprintf("tr(): Multipath internal key mismatches multipath subscripts lengths");
    2396                 :           2 :             return {};
    2397                 :             :         }
    2398                 :             : 
    2399   [ -  +  +  + ]:        1903 :         while (internal_keys.size() < max_providers_len) {
    2400   [ +  -  +  -  :          48 :             internal_keys.emplace_back(internal_keys.at(0)->Clone());
                   +  - ]
    2401                 :             :         }
    2402                 :             : 
    2403                 :             :         // Build the final descriptors vector
    2404         [ +  + ]:        3796 :         for (size_t i = 0; i < max_providers_len; ++i) {
    2405                 :             :             // Build final subscripts vectors by retrieving the i'th subscript for each vector in subscripts
    2406                 :        1941 :             std::vector<std::unique_ptr<DescriptorImpl>> this_subs;
    2407   [ -  +  +  - ]:        1941 :             this_subs.reserve(subscripts.size());
    2408         [ +  + ]:        2836 :             for (auto& subs : subscripts) {
    2409   [ +  -  +  - ]:         895 :                 this_subs.emplace_back(std::move(subs.at(i)));
    2410                 :             :             }
    2411   [ +  -  +  -  :        1941 :             ret.emplace_back(std::make_unique<TRDescriptor>(std::move(internal_keys.at(i)), std::move(this_subs), depths));
                   +  - ]
    2412                 :        1941 :         }
    2413                 :        1855 :         return ret;
    2414                 :             : 
    2415                 :             : 
    2416   [ +  -  +  -  :        4340 :     } else if (Func("tr", expr)) {
                   -  + ]
    2417         [ #  # ]:           0 :         error = "Can only have tr at top level";
    2418                 :           0 :         return {};
    2419                 :             :     }
    2420   [ +  +  +  -  :        4749 :     if (ctx == ParseScriptContext::TOP && Func("rawtr", expr)) {
          +  -  +  +  +  
                      + ]
    2421         [ +  - ]:          66 :         auto arg = Expr(expr);
    2422         [ +  + ]:          66 :         if (expr.size()) {
    2423         [ +  - ]:           1 :             error = strprintf("rawtr(): only one key expected.");
    2424                 :           1 :             return {};
    2425                 :             :         }
    2426         [ +  - ]:          65 :         auto output_keys = ParsePubkey(key_exp_index, arg, ParseScriptContext::P2TR, out, error);
    2427         [ -  + ]:          65 :         if (output_keys.empty()) {
    2428         [ #  # ]:           0 :             error = strprintf("rawtr(): %s", error);
    2429                 :           0 :             return {};
    2430                 :             :         }
    2431                 :          65 :         ++key_exp_index;
    2432         [ +  + ]:         168 :         for (auto& pubkey : output_keys) {
    2433   [ +  -  +  - ]:         206 :             ret.emplace_back(std::make_unique<RawTRDescriptor>(std::move(pubkey)));
    2434                 :             :         }
    2435                 :          65 :         return ret;
    2436   [ +  -  +  -  :        2456 :     } else if (Func("rawtr", expr)) {
                   -  + ]
    2437         [ #  # ]:           0 :         error = "Can only have rawtr at top level";
    2438                 :           0 :         return {};
    2439                 :             :     }
    2440   [ +  +  +  -  :        4617 :     if (ctx == ParseScriptContext::TOP && Func("raw", expr)) {
          +  -  +  +  +  
                      + ]
    2441   [ +  -  -  + ]:        3776 :         std::string str(expr.begin(), expr.end());
    2442   [ -  +  +  -  :        1888 :         if (!IsHex(str)) {
                   +  + ]
    2443         [ +  - ]:           2 :             error = "Raw script is not hex";
    2444                 :           2 :             return {};
    2445                 :             :         }
    2446   [ -  +  +  - ]:        1886 :         auto bytes = ParseHex(str);
    2447   [ +  -  +  - ]:        3772 :         ret.emplace_back(std::make_unique<RawDescriptor>(CScript(bytes.begin(), bytes.end())));
    2448                 :        1886 :         return ret;
    2449   [ +  -  +  -  :        4277 :     } else if (Func("raw", expr)) {
                   -  + ]
    2450         [ #  # ]:           0 :         error = "Can only have raw() at top level";
    2451                 :           0 :         return {};
    2452                 :             :     }
    2453                 :             :     // Process miniscript expressions.
    2454                 :         503 :     {
    2455                 :         503 :         const auto script_ctx{ctx == ParseScriptContext::P2WSH ? miniscript::MiniscriptContext::P2WSH : miniscript::MiniscriptContext::TAPSCRIPT};
    2456         [ +  - ]:         503 :         KeyParser parser(/*out = */&out, /* in = */nullptr, /* ctx = */script_ctx, key_exp_index);
    2457   [ +  -  -  + ]:        1509 :         auto node = miniscript::FromString(std::string(expr.begin(), expr.end()), parser);
    2458         [ +  + ]:         503 :         if (parser.m_key_parsing_error != "") {
    2459                 :           4 :             error = std::move(parser.m_key_parsing_error);
    2460                 :           4 :             return {};
    2461                 :             :         }
    2462         [ +  + ]:         499 :         if (node) {
    2463         [ +  + ]:         153 :             if (ctx != ParseScriptContext::P2WSH && ctx != ParseScriptContext::P2TR) {
    2464         [ +  - ]:           3 :                 error = "Miniscript expressions can only be used in wsh or tr.";
    2465                 :           3 :                 return {};
    2466                 :             :             }
    2467   [ +  +  +  + ]:         150 :             if (!node->IsSane() || node->IsNotSatisfiable()) {
    2468                 :             :                 // Try to find the first insane sub for better error reporting.
    2469         [ +  - ]:          14 :                 auto insane_node = node.get();
    2470   [ +  -  +  + ]:          14 :                 if (const auto sub = node->FindInsaneSub()) insane_node = sub;
    2471   [ +  -  +  -  :          28 :                 if (const auto str = insane_node->ToString(parser)) error = *str;
                   +  - ]
    2472         [ +  + ]:          14 :                 if (!insane_node->IsValid()) {
    2473         [ +  - ]:           4 :                     error += " is invalid";
    2474         [ +  + ]:          10 :                 } else if (!node->IsSane()) {
    2475         [ +  - ]:           9 :                     error += " is not sane";
    2476         [ +  + ]:           9 :                     if (!insane_node->IsNonMalleable()) {
    2477         [ +  - ]:           2 :                         error += ": malleable witnesses exist";
    2478   [ +  +  +  + ]:           7 :                     } else if (insane_node == node.get() && !insane_node->NeedsSignature()) {
    2479         [ +  - ]:           3 :                         error += ": witnesses without signature exist";
    2480         [ +  + ]:           4 :                     } else if (!insane_node->CheckTimeLocksMix()) {
    2481         [ +  - ]:           2 :                         error += ": contains mixes of timelocks expressed in blocks and seconds";
    2482         [ +  - ]:           2 :                     } else if (!insane_node->CheckDuplicateKey()) {
    2483         [ +  - ]:           2 :                         error += ": contains duplicate public keys";
    2484         [ #  # ]:           0 :                     } else if (!insane_node->ValidSatisfactions()) {
    2485         [ #  # ]:           0 :                         error += ": needs witnesses that may exceed resource limits";
    2486                 :             :                     }
    2487                 :             :                 } else {
    2488         [ +  - ]:           1 :                     error += " is not satisfiable";
    2489                 :             :                 }
    2490                 :          14 :                 return {};
    2491                 :             :             }
    2492                 :             :             // A signature check is required for a miniscript to be sane. Therefore no sane miniscript
    2493                 :             :             // may have an empty list of public keys.
    2494         [ +  - ]:         136 :             CHECK_NONFATAL(!parser.m_keys.empty());
    2495         [ -  + ]:         136 :             key_exp_index += parser.m_keys.size();
    2496                 :             :             // Make sure all vecs are of the same length, or exactly length 1
    2497                 :             :             // For length 1 vectors, clone subdescs until vector is the same length
    2498         [ -  + ]:         136 :             size_t num_multipath = std::max_element(parser.m_keys.begin(), parser.m_keys.end(),
    2499                 :         242 :                     [](const std::vector<std::unique_ptr<PubkeyProvider>>& a, const std::vector<std::unique_ptr<PubkeyProvider>>& b) {
    2500   [ -  +  -  +  :         242 :                         return a.size() < b.size();
                   -  + ]
    2501         [ -  + ]:         136 :                     })->size();
    2502                 :             : 
    2503         [ +  + ]:         512 :             for (auto& vec : parser.m_keys) {
    2504   [ -  +  +  + ]:         378 :                 if (vec.size() == 1) {
    2505         [ -  + ]:         359 :                     for (size_t i = 1; i < num_multipath; ++i) {
    2506   [ #  #  #  #  :           0 :                         vec.emplace_back(vec.at(0)->Clone());
                   #  # ]
    2507                 :             :                     }
    2508         [ +  + ]:          19 :                 } else if (vec.size() != num_multipath) {
    2509         [ +  - ]:           2 :                     error = strprintf("Miniscript: Multipath derivation paths have mismatched lengths");
    2510                 :           2 :                     return {};
    2511                 :             :                 }
    2512                 :             :             }
    2513                 :             : 
    2514                 :             :             // Build the final descriptors vector
    2515         [ +  + ]:         278 :             for (size_t i = 0; i < num_multipath; ++i) {
    2516                 :             :                 // Build final pubkeys vectors by retrieving the i'th subscript for each vector in subscripts
    2517                 :         144 :                 std::vector<std::unique_ptr<PubkeyProvider>> pubs;
    2518   [ -  +  +  - ]:         144 :                 pubs.reserve(parser.m_keys.size());
    2519         [ +  + ]:         533 :                 for (auto& pub : parser.m_keys) {
    2520   [ +  -  +  - ]:         389 :                     pubs.emplace_back(std::move(pub.at(i)));
    2521                 :             :                 }
    2522   [ +  -  +  -  :         288 :                 ret.emplace_back(std::make_unique<MiniscriptDescriptor>(std::move(pubs), node->Clone()));
                   +  - ]
    2523                 :         144 :             }
    2524                 :         134 :             return ret;
    2525                 :             :         }
    2526                 :         660 :     }
    2527         [ +  + ]:         346 :     if (ctx == ParseScriptContext::P2SH) {
    2528         [ +  - ]:           4 :         error = "A function is needed within P2SH";
    2529                 :           4 :         return {};
    2530         [ +  + ]:         342 :     } else if (ctx == ParseScriptContext::P2WSH) {
    2531         [ +  - ]:           4 :         error = "A function is needed within P2WSH";
    2532                 :           4 :         return {};
    2533                 :             :     }
    2534   [ +  -  +  - ]:         676 :     error = strprintf("'%s' is not a valid descriptor function", std::string(expr.begin(), expr.end()));
    2535                 :         338 :     return {};
    2536                 :       13079 : }
    2537                 :             : 
    2538                 :         946 : std::unique_ptr<DescriptorImpl> InferMultiA(const CScript& script, ParseScriptContext ctx, const SigningProvider& provider)
    2539                 :             : {
    2540                 :         946 :     auto match = MatchMultiA(script);
    2541         [ +  + ]:         946 :     if (!match) return {};
    2542                 :         774 :     std::vector<std::unique_ptr<PubkeyProvider>> keys;
    2543   [ -  +  +  - ]:         774 :     keys.reserve(match->second.size());
    2544         [ +  + ]:      104222 :     for (const auto keyspan : match->second) {
    2545         [ -  + ]:      103448 :         if (keyspan.size() != 32) return {};
    2546         [ +  - ]:      103448 :         auto key = InferXOnlyPubkey(XOnlyPubKey{keyspan}, ctx, provider);
    2547         [ -  + ]:      103448 :         if (!key) return {};
    2548         [ +  - ]:      103448 :         keys.push_back(std::move(key));
    2549                 :      103448 :     }
    2550   [ +  -  -  + ]:         774 :     return std::make_unique<MultiADescriptor>(match->first, std::move(keys));
    2551                 :        1720 : }
    2552                 :             : 
    2553                 :             : // NOLINTNEXTLINE(misc-no-recursion)
    2554                 :      410661 : std::unique_ptr<DescriptorImpl> InferScript(const CScript& script, ParseScriptContext ctx, const SigningProvider& provider)
    2555                 :             : {
    2556   [ +  +  +  +  :      418169 :     if (ctx == ParseScriptContext::P2TR && script.size() == 34 && script[0] == 32 && script[33] == OP_CHECKSIG) {
          +  +  +  -  +  
             -  +  -  +  
                      - ]
    2557                 :        3351 :         XOnlyPubKey key{std::span{script}.subspan(1, 32)};
    2558   [ +  -  -  + ]:        3351 :         return std::make_unique<PKDescriptor>(InferXOnlyPubkey(key, ctx, provider), true);
    2559                 :             :     }
    2560                 :             : 
    2561         [ +  + ]:      407310 :     if (ctx == ParseScriptContext::P2TR) {
    2562                 :         946 :         auto ret = InferMultiA(script, ctx, provider);
    2563         [ +  + ]:         946 :         if (ret) return ret;
    2564                 :         946 :     }
    2565                 :             : 
    2566                 :      406536 :     std::vector<std::vector<unsigned char>> data;
    2567         [ +  - ]:      406536 :     TxoutType txntype = Solver(script, data);
    2568                 :             : 
    2569   [ +  +  +  - ]:      406536 :     if (txntype == TxoutType::PUBKEY && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
    2570         [ -  + ]:       18515 :         CPubKey pubkey(data[0]);
    2571   [ +  -  +  + ]:       18515 :         if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
    2572   [ +  -  -  + ]:       18513 :             return std::make_unique<PKDescriptor>(std::move(pubkey_provider));
    2573                 :       18515 :         }
    2574                 :             :     }
    2575   [ +  +  +  + ]:      388023 :     if (txntype == TxoutType::PUBKEYHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
    2576         [ -  + ]:       97167 :         uint160 hash(data[0]);
    2577         [ +  - ]:       97167 :         CKeyID keyid(hash);
    2578         [ +  - ]:       97167 :         CPubKey pubkey;
    2579   [ +  -  +  + ]:       97167 :         if (provider.GetPubKey(keyid, pubkey)) {
    2580   [ +  -  +  + ]:       96749 :             if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
    2581   [ +  -  -  + ]:       96745 :                 return std::make_unique<PKHDescriptor>(std::move(pubkey_provider));
    2582                 :       96749 :             }
    2583                 :             :         }
    2584                 :             :     }
    2585         [ +  + ]:      291278 :     if (txntype == TxoutType::WITNESS_V0_KEYHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH)) {
    2586         [ -  + ]:      207534 :         uint160 hash(data[0]);
    2587         [ +  - ]:      207534 :         CKeyID keyid(hash);
    2588         [ +  - ]:      207534 :         CPubKey pubkey;
    2589   [ +  -  +  + ]:      207534 :         if (provider.GetPubKey(keyid, pubkey)) {
    2590   [ +  -  +  + ]:      206139 :             if (auto pubkey_provider = InferPubkey(pubkey, ParseScriptContext::P2WPKH, provider)) {
    2591   [ +  -  -  + ]:      206137 :                 return std::make_unique<WPKHDescriptor>(std::move(pubkey_provider));
    2592                 :      206139 :             }
    2593                 :             :         }
    2594                 :             :     }
    2595   [ +  +  +  - ]:       85141 :     if (txntype == TxoutType::MULTISIG && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
    2596                 :         646 :         bool ok = true;
    2597                 :         646 :         std::vector<std::unique_ptr<PubkeyProvider>> providers;
    2598   [ -  +  +  + ]:        3239 :         for (size_t i = 1; i + 1 < data.size(); ++i) {
    2599         [ -  + ]:        2593 :             CPubKey pubkey(data[i]);
    2600   [ +  -  +  - ]:        2593 :             if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
    2601         [ +  - ]:        2593 :                 providers.push_back(std::move(pubkey_provider));
    2602                 :             :             } else {
    2603                 :           0 :                 ok = false;
    2604                 :           0 :                 break;
    2605                 :        2593 :             }
    2606                 :             :         }
    2607   [ +  -  -  + ]:         646 :         if (ok) return std::make_unique<MultisigDescriptor>((int)data[0][0], std::move(providers));
    2608                 :         646 :     }
    2609         [ +  + ]:       84495 :     if (txntype == TxoutType::SCRIPTHASH && ctx == ParseScriptContext::TOP) {
    2610         [ -  + ]:       54447 :         uint160 hash(data[0]);
    2611         [ +  - ]:       54447 :         CScriptID scriptid(hash);
    2612                 :       54447 :         CScript subscript;
    2613   [ +  -  +  + ]:       54447 :         if (provider.GetCScript(scriptid, subscript)) {
    2614         [ +  - ]:       54013 :             auto sub = InferScript(subscript, ParseScriptContext::P2SH, provider);
    2615   [ +  +  +  -  :       54013 :             if (sub) return std::make_unique<SHDescriptor>(std::move(sub));
                   -  + ]
    2616                 :       54013 :         }
    2617                 :       54447 :     }
    2618         [ +  + ]:       30494 :     if (txntype == TxoutType::WITNESS_V0_SCRIPTHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH)) {
    2619   [ -  +  +  - ]:        2764 :         CScriptID scriptid{RIPEMD160(data[0])};
    2620                 :        2764 :         CScript subscript;
    2621   [ +  -  +  + ]:        2764 :         if (provider.GetCScript(scriptid, subscript)) {
    2622         [ +  - ]:         843 :             auto sub = InferScript(subscript, ParseScriptContext::P2WSH, provider);
    2623   [ +  +  +  -  :         843 :             if (sub) return std::make_unique<WSHDescriptor>(std::move(sub));
                   -  + ]
    2624                 :         843 :         }
    2625                 :        2764 :     }
    2626         [ +  + ]:       29664 :     if (txntype == TxoutType::WITNESS_V1_TAPROOT && ctx == ParseScriptContext::TOP) {
    2627                 :             :         // Extract x-only pubkey from output.
    2628                 :       22921 :         XOnlyPubKey pubkey;
    2629                 :       22921 :         std::copy(data[0].begin(), data[0].end(), pubkey.begin());
    2630                 :             :         // Request spending data.
    2631         [ +  - ]:       22921 :         TaprootSpendData tap;
    2632   [ +  -  +  + ]:       22921 :         if (provider.GetTaprootSpendData(pubkey, tap)) {
    2633                 :             :             // If found, convert it back to tree form.
    2634         [ +  - ]:        6318 :             auto tree = InferTaprootTree(tap, pubkey);
    2635         [ +  - ]:        6318 :             if (tree) {
    2636                 :             :                 // If that works, try to infer subdescriptors for all leaves.
    2637                 :        6318 :                 bool ok = true;
    2638                 :        6318 :                 std::vector<std::unique_ptr<DescriptorImpl>> subscripts; //!< list of script subexpressions
    2639                 :        6318 :                 std::vector<int> depths; //!< depth in the tree of each subexpression (same length subscripts)
    2640   [ +  -  +  + ]:       10615 :                 for (const auto& [depth, script, leaf_ver] : *tree) {
    2641                 :        4297 :                     std::unique_ptr<DescriptorImpl> subdesc;
    2642         [ +  - ]:        4297 :                     if (leaf_ver == TAPROOT_LEAF_TAPSCRIPT) {
    2643         [ +  - ]:        8594 :                         subdesc = InferScript(CScript(script.begin(), script.end()), ParseScriptContext::P2TR, provider);
    2644                 :             :                     }
    2645         [ -  + ]:        4297 :                     if (!subdesc) {
    2646                 :           0 :                         ok = false;
    2647                 :           0 :                         break;
    2648                 :             :                     } else {
    2649         [ +  - ]:        4297 :                         subscripts.push_back(std::move(subdesc));
    2650         [ +  - ]:        4297 :                         depths.push_back(depth);
    2651                 :             :                     }
    2652                 :        4297 :                 }
    2653                 :           0 :                 if (ok) {
    2654         [ +  - ]:        6318 :                     auto key = InferXOnlyPubkey(tap.internal_key, ParseScriptContext::P2TR, provider);
    2655   [ +  -  -  + ]:        6318 :                     return std::make_unique<TRDescriptor>(std::move(key), std::move(subscripts), std::move(depths));
    2656                 :        6318 :                 }
    2657                 :        6318 :             }
    2658                 :        6318 :         }
    2659                 :             :         // If the above doesn't work, construct a rawtr() descriptor with just the encoded x-only pubkey.
    2660   [ +  -  +  - ]:       16603 :         if (pubkey.IsFullyValid()) {
    2661         [ +  - ]:       16603 :             auto key = InferXOnlyPubkey(pubkey, ParseScriptContext::P2TR, provider);
    2662         [ +  - ]:       16603 :             if (key) {
    2663   [ +  -  -  + ]:       16603 :                 return std::make_unique<RawTRDescriptor>(std::move(key));
    2664                 :             :             }
    2665                 :       16603 :         }
    2666                 :       22921 :     }
    2667                 :             : 
    2668         [ +  + ]:        6743 :     if (ctx == ParseScriptContext::P2WSH || ctx == ParseScriptContext::P2TR) {
    2669                 :         536 :         const auto script_ctx{ctx == ParseScriptContext::P2WSH ? miniscript::MiniscriptContext::P2WSH : miniscript::MiniscriptContext::TAPSCRIPT};
    2670         [ +  - ]:         536 :         KeyParser parser(/* out = */nullptr, /* in = */&provider, /* ctx = */script_ctx);
    2671         [ +  - ]:         536 :         auto node = miniscript::FromScript(script, parser);
    2672   [ +  +  -  + ]:         536 :         if (node && node->IsSane()) {
    2673                 :         523 :             std::vector<std::unique_ptr<PubkeyProvider>> keys;
    2674   [ -  +  +  - ]:         523 :             keys.reserve(parser.m_keys.size());
    2675         [ +  + ]:        1882 :             for (auto& key : parser.m_keys) {
    2676   [ +  -  +  - ]:        1359 :                 keys.emplace_back(std::move(key.at(0)));
    2677                 :             :             }
    2678   [ +  -  -  + ]:         523 :             return std::make_unique<MiniscriptDescriptor>(std::move(keys), std::move(node));
    2679                 :         523 :         }
    2680                 :        1072 :     }
    2681                 :             : 
    2682                 :             :     // The following descriptors are all top-level only descriptors.
    2683                 :             :     // So if we are not at the top level, return early.
    2684         [ +  + ]:        6220 :     if (ctx != ParseScriptContext::TOP) return nullptr;
    2685                 :             : 
    2686                 :        6195 :     CTxDestination dest;
    2687   [ +  -  +  + ]:        6195 :     if (ExtractDestination(script, dest)) {
    2688   [ +  -  +  - ]:        4235 :         if (GetScriptForDestination(dest) == script) {
    2689   [ +  -  -  + ]:        4235 :             return std::make_unique<AddressDescriptor>(std::move(dest));
    2690                 :             :         }
    2691                 :             :     }
    2692                 :             : 
    2693   [ +  -  -  + ]:        1960 :     return std::make_unique<RawDescriptor>(script);
    2694                 :      406536 : }
    2695                 :             : 
    2696                 :             : 
    2697                 :             : } // namespace
    2698                 :             : 
    2699                 :             : /** Check a descriptor checksum, and update desc to be the checksum-less part. */
    2700                 :       10544 : bool CheckChecksum(std::span<const char>& sp, bool require_checksum, std::string& error, std::string* out_checksum = nullptr)
    2701                 :             : {
    2702                 :       10544 :     auto check_split = Split(sp, '#');
    2703   [ -  +  +  + ]:       10544 :     if (check_split.size() > 2) {
    2704         [ +  - ]:           2 :         error = "Multiple '#' symbols";
    2705                 :             :         return false;
    2706                 :             :     }
    2707   [ +  +  +  + ]:       10542 :     if (check_split.size() == 1 && require_checksum){
    2708         [ +  - ]:       10544 :         error = "Missing checksum";
    2709                 :             :         return false;
    2710                 :             :     }
    2711         [ +  + ]:       10535 :     if (check_split.size() == 2) {
    2712         [ +  + ]:        5849 :         if (check_split[1].size() != 8) {
    2713         [ +  - ]:           6 :             error = strprintf("Expected 8 character checksum, not %u characters", check_split[1].size());
    2714                 :           6 :             return false;
    2715                 :             :         }
    2716                 :             :     }
    2717         [ +  - ]:       10529 :     auto checksum = DescriptorChecksum(check_split[0]);
    2718         [ +  + ]:       10529 :     if (checksum.empty()) {
    2719         [ +  - ]:       10529 :         error = "Invalid characters in payload";
    2720                 :             :         return false;
    2721                 :             :     }
    2722   [ -  +  +  + ]:       10528 :     if (check_split.size() == 2) {
    2723   [ -  +  +  + ]:        5842 :         if (!std::equal(checksum.begin(), checksum.end(), check_split[1].begin())) {
    2724   [ +  -  +  - ]:          22 :             error = strprintf("Provided checksum '%s' does not match computed checksum '%s'", std::string(check_split[1].begin(), check_split[1].end()), checksum);
    2725                 :          11 :             return false;
    2726                 :             :         }
    2727                 :             :     }
    2728         [ +  + ]:       10517 :     if (out_checksum) *out_checksum = std::move(checksum);
    2729                 :       10517 :     sp = check_split[0];
    2730                 :       10517 :     return true;
    2731                 :       21073 : }
    2732                 :             : 
    2733                 :       10259 : std::vector<std::unique_ptr<Descriptor>> Parse(const std::string& descriptor, FlatSigningProvider& out, std::string& error, bool require_checksum)
    2734                 :             : {
    2735         [ -  + ]:       10259 :     std::span<const char> sp{descriptor};
    2736         [ +  + ]:       10259 :     if (!CheckChecksum(sp, require_checksum, error)) return {};
    2737                 :       10236 :     uint32_t key_exp_index = 0;
    2738                 :       10236 :     auto ret = ParseScript(key_exp_index, sp, ParseScriptContext::TOP, out, error);
    2739   [ +  -  +  + ]:       10236 :     if (sp.size() == 0 && !ret.empty()) {
    2740                 :        9728 :         std::vector<std::unique_ptr<Descriptor>> descs;
    2741   [ -  +  +  - ]:        9728 :         descs.reserve(ret.size());
    2742         [ +  + ]:       19648 :         for (auto& r : ret) {
    2743         [ +  - ]:        9920 :             descs.emplace_back(std::unique_ptr<Descriptor>(std::move(r)));
    2744                 :             :         }
    2745                 :        9728 :         return descs;
    2746                 :        9728 :     }
    2747                 :         508 :     return {};
    2748                 :       10236 : }
    2749                 :             : 
    2750                 :         285 : std::string GetDescriptorChecksum(const std::string& descriptor)
    2751                 :             : {
    2752         [ -  + ]:         285 :     std::string ret;
    2753                 :         285 :     std::string error;
    2754         [ -  + ]:         285 :     std::span<const char> sp{descriptor};
    2755   [ +  -  +  +  :         285 :     if (!CheckChecksum(sp, false, error, &ret)) return "";
                   +  - ]
    2756                 :         281 :     return ret;
    2757                 :         285 : }
    2758                 :             : 
    2759                 :      351508 : std::unique_ptr<Descriptor> InferDescriptor(const CScript& script, const SigningProvider& provider)
    2760                 :             : {
    2761                 :      351508 :     return InferScript(script, ParseScriptContext::TOP, provider);
    2762                 :             : }
    2763                 :             : 
    2764                 :        7043 : uint256 DescriptorID(const Descriptor& desc)
    2765                 :             : {
    2766                 :        7043 :     std::string desc_str = desc.ToString(/*compat_format=*/true);
    2767                 :        7043 :     uint256 id;
    2768   [ +  -  +  -  :       14086 :     CSHA256().Write((unsigned char*)desc_str.data(), desc_str.size()).Finalize(id.begin());
                   +  - ]
    2769                 :        7043 :     return id;
    2770                 :        7043 : }
    2771                 :             : 
    2772                 :       17366 : void DescriptorCache::CacheParentExtPubKey(uint32_t key_exp_pos, const CExtPubKey& xpub)
    2773                 :             : {
    2774                 :       17366 :     m_parent_xpubs[key_exp_pos] = xpub;
    2775                 :       17366 : }
    2776                 :             : 
    2777                 :       30231 : void DescriptorCache::CacheDerivedExtPubKey(uint32_t key_exp_pos, uint32_t der_index, const CExtPubKey& xpub)
    2778                 :             : {
    2779                 :       30231 :     auto& xpubs = m_derived_xpubs[key_exp_pos];
    2780                 :       30231 :     xpubs[der_index] = xpub;
    2781                 :       30231 : }
    2782                 :             : 
    2783                 :       13150 : void DescriptorCache::CacheLastHardenedExtPubKey(uint32_t key_exp_pos, const CExtPubKey& xpub)
    2784                 :             : {
    2785                 :       13150 :     m_last_hardened_xpubs[key_exp_pos] = xpub;
    2786                 :       13150 : }
    2787                 :             : 
    2788                 :      652383 : bool DescriptorCache::GetCachedParentExtPubKey(uint32_t key_exp_pos, CExtPubKey& xpub) const
    2789                 :             : {
    2790                 :      652383 :     const auto& it = m_parent_xpubs.find(key_exp_pos);
    2791         [ +  + ]:      652383 :     if (it == m_parent_xpubs.end()) return false;
    2792                 :      643712 :     xpub = it->second;
    2793                 :      643712 :     return true;
    2794                 :             : }
    2795                 :             : 
    2796                 :      672167 : bool DescriptorCache::GetCachedDerivedExtPubKey(uint32_t key_exp_pos, uint32_t der_index, CExtPubKey& xpub) const
    2797                 :             : {
    2798                 :      672167 :     const auto& key_exp_it = m_derived_xpubs.find(key_exp_pos);
    2799         [ +  + ]:      672167 :     if (key_exp_it == m_derived_xpubs.end()) return false;
    2800                 :       24341 :     const auto& der_it = key_exp_it->second.find(der_index);
    2801         [ +  + ]:       24341 :     if (der_it == key_exp_it->second.end()) return false;
    2802                 :        4380 :     xpub = der_it->second;
    2803                 :        4380 :     return true;
    2804                 :             : }
    2805                 :             : 
    2806                 :       35238 : bool DescriptorCache::GetCachedLastHardenedExtPubKey(uint32_t key_exp_pos, CExtPubKey& xpub) const
    2807                 :             : {
    2808                 :       35238 :     const auto& it = m_last_hardened_xpubs.find(key_exp_pos);
    2809         [ +  + ]:       35238 :     if (it == m_last_hardened_xpubs.end()) return false;
    2810                 :       31600 :     xpub = it->second;
    2811                 :       31600 :     return true;
    2812                 :             : }
    2813                 :             : 
    2814                 :      424124 : DescriptorCache DescriptorCache::MergeAndDiff(const DescriptorCache& other)
    2815                 :             : {
    2816                 :      424124 :     DescriptorCache diff;
    2817   [ +  -  +  +  :      428845 :     for (const auto& parent_xpub_pair : other.GetCachedParentExtPubKeys()) {
                   +  - ]
    2818         [ +  - ]:        4721 :         CExtPubKey xpub;
    2819   [ +  +  +  - ]:        4721 :         if (GetCachedParentExtPubKey(parent_xpub_pair.first, xpub)) {
    2820         [ -  + ]:           6 :             if (xpub != parent_xpub_pair.second) {
    2821   [ #  #  #  # ]:           0 :                 throw std::runtime_error(std::string(__func__) + ": New cached parent xpub does not match already cached parent xpub");
    2822                 :             :             }
    2823                 :           6 :             continue;
    2824                 :             :         }
    2825         [ +  - ]:        4715 :         CacheParentExtPubKey(parent_xpub_pair.first, parent_xpub_pair.second);
    2826         [ +  - ]:        4715 :         diff.CacheParentExtPubKey(parent_xpub_pair.first, parent_xpub_pair.second);
    2827                 :           0 :     }
    2828   [ +  -  +  + ]:      434129 :     for (const auto& derived_xpub_map_pair : other.GetCachedDerivedExtPubKeys()) {
    2829   [ +  +  +  - ]:       20010 :         for (const auto& derived_xpub_pair : derived_xpub_map_pair.second) {
    2830         [ +  - ]:       10005 :             CExtPubKey xpub;
    2831   [ -  +  +  - ]:       10005 :             if (GetCachedDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, xpub)) {
    2832         [ #  # ]:           0 :                 if (xpub != derived_xpub_pair.second) {
    2833   [ #  #  #  # ]:           0 :                     throw std::runtime_error(std::string(__func__) + ": New cached derived xpub does not match already cached derived xpub");
    2834                 :             :                 }
    2835                 :           0 :                 continue;
    2836                 :             :             }
    2837         [ +  - ]:       10005 :             CacheDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, derived_xpub_pair.second);
    2838         [ +  - ]:       10005 :             diff.CacheDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, derived_xpub_pair.second);
    2839                 :             :         }
    2840                 :             :     }
    2841   [ +  -  +  +  :      427762 :     for (const auto& lh_xpub_pair : other.GetCachedLastHardenedExtPubKeys()) {
                   +  - ]
    2842         [ +  - ]:        3638 :         CExtPubKey xpub;
    2843   [ -  +  +  - ]:        3638 :         if (GetCachedLastHardenedExtPubKey(lh_xpub_pair.first, xpub)) {
    2844         [ #  # ]:           0 :             if (xpub != lh_xpub_pair.second) {
    2845   [ #  #  #  # ]:           0 :                 throw std::runtime_error(std::string(__func__) + ": New cached last hardened xpub does not match already cached last hardened xpub");
    2846                 :             :             }
    2847                 :           0 :             continue;
    2848                 :             :         }
    2849         [ +  - ]:        3638 :         CacheLastHardenedExtPubKey(lh_xpub_pair.first, lh_xpub_pair.second);
    2850         [ +  - ]:        3638 :         diff.CacheLastHardenedExtPubKey(lh_xpub_pair.first, lh_xpub_pair.second);
    2851                 :           0 :     }
    2852                 :      424124 :     return diff;
    2853                 :           0 : }
    2854                 :             : 
    2855                 :      848938 : ExtPubKeyMap DescriptorCache::GetCachedParentExtPubKeys() const
    2856                 :             : {
    2857                 :      848938 :     return m_parent_xpubs;
    2858                 :             : }
    2859                 :             : 
    2860                 :      848938 : std::unordered_map<uint32_t, ExtPubKeyMap> DescriptorCache::GetCachedDerivedExtPubKeys() const
    2861                 :             : {
    2862                 :      848938 :     return m_derived_xpubs;
    2863                 :             : }
    2864                 :             : 
    2865                 :      848292 : ExtPubKeyMap DescriptorCache::GetCachedLastHardenedExtPubKeys() const
    2866                 :             : {
    2867                 :      848292 :     return m_last_hardened_xpubs;
    2868                 :             : }
        

Generated by: LCOV version 2.0-1