LCOV - code coverage report
Current view: top level - src/script - descriptor.cpp (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 93.3 % 1446 1349
Test Date: 2025-05-07 04:08:43 Functions: 82.0 % 217 178
Branches: 65.4 % 2378 1556

             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 <script/miniscript.h>
      11                 :             : #include <script/parsing.h>
      12                 :             : #include <script/script.h>
      13                 :             : #include <script/signingprovider.h>
      14                 :             : #include <script/solver.h>
      15                 :             : #include <uint256.h>
      16                 :             : 
      17                 :             : #include <common/args.h>
      18                 :             : #include <span.h>
      19                 :             : #include <util/bip32.h>
      20                 :             : #include <util/check.h>
      21                 :             : #include <util/strencodings.h>
      22                 :             : #include <util/vector.h>
      23                 :             : 
      24                 :             : #include <algorithm>
      25                 :             : #include <memory>
      26                 :             : #include <numeric>
      27                 :             : #include <optional>
      28                 :             : #include <string>
      29                 :             : #include <vector>
      30                 :             : 
      31                 :             : using util::Split;
      32                 :             : 
      33                 :             : namespace {
      34                 :             : 
      35                 :             : ////////////////////////////////////////////////////////////////////////////
      36                 :             : // Checksum                                                               //
      37                 :             : ////////////////////////////////////////////////////////////////////////////
      38                 :             : 
      39                 :             : // This section implements a checksum algorithm for descriptors with the
      40                 :             : // following properties:
      41                 :             : // * Mistakes in a descriptor string are measured in "symbol errors". The higher
      42                 :             : //   the number of symbol errors, the harder it is to detect:
      43                 :             : //   * An error substituting a character from 0123456789()[],'/*abcdefgh@:$%{} for
      44                 :             : //     another in that set always counts as 1 symbol error.
      45                 :             : //     * Note that hex encoded keys are covered by these characters. Xprvs and
      46                 :             : //       xpubs use other characters too, but already have their own checksum
      47                 :             : //       mechanism.
      48                 :             : //     * Function names like "multi()" use other characters, but mistakes in
      49                 :             : //       these would generally result in an unparsable descriptor.
      50                 :             : //   * A case error always counts as 1 symbol error.
      51                 :             : //   * Any other 1 character substitution error counts as 1 or 2 symbol errors.
      52                 :             : // * Any 1 symbol error is always detected.
      53                 :             : // * Any 2 or 3 symbol error in a descriptor of up to 49154 characters is always detected.
      54                 :             : // * Any 4 symbol error in a descriptor of up to 507 characters is always detected.
      55                 :             : // * Any 5 symbol error in a descriptor of up to 77 characters is always detected.
      56                 :             : // * Is optimized to minimize the chance a 5 symbol error in a descriptor up to 387 characters is undetected
      57                 :             : // * Random errors have a chance of 1 in 2**40 of being undetected.
      58                 :             : //
      59                 :             : // These properties are achieved by expanding every group of 3 (non checksum) characters into
      60                 :             : // 4 GF(32) symbols, over which a cyclic code is defined.
      61                 :             : 
      62                 :             : /*
      63                 :             :  * Interprets c as 8 groups of 5 bits which are the coefficients of a degree 8 polynomial over GF(32),
      64                 :             :  * multiplies that polynomial by x, computes its remainder modulo a generator, and adds the constant term val.
      65                 :             :  *
      66                 :             :  * 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}.
      67                 :             :  * It is chosen to define an cyclic error detecting code which is selected by:
      68                 :             :  * - Starting from all BCH codes over GF(32) of degree 8 and below, which by construction guarantee detecting
      69                 :             :  *   3 errors in windows up to 19000 symbols.
      70                 :             :  * - Taking all those generators, and for degree 7 ones, extend them to degree 8 by adding all degree-1 factors.
      71                 :             :  * - Selecting just the set of generators that guarantee detecting 4 errors in a window of length 512.
      72                 :             :  * - Selecting one of those with best worst-case behavior for 5 errors in windows of length up to 512.
      73                 :             :  *
      74                 :             :  * The generator and the constants to implement it can be verified using this Sage code:
      75                 :             :  *   B = GF(2) # Binary field
      76                 :             :  *   BP.<b> = B[] # Polynomials over the binary field
      77                 :             :  *   F_mod = b**5 + b**3 + 1
      78                 :             :  *   F.<f> = GF(32, modulus=F_mod, repr='int') # GF(32) definition
      79                 :             :  *   FP.<x> = F[] # Polynomials over GF(32)
      80                 :             :  *   E_mod = x**3 + x + F.fetch_int(8)
      81                 :             :  *   E.<e> = F.extension(E_mod) # Extension field definition
      82                 :             :  *   alpha = e**2743 # Choice of an element in extension field
      83                 :             :  *   for p in divisors(E.order() - 1): # Verify alpha has order 32767.
      84                 :             :  *       assert((alpha**p == 1) == (p % 32767 == 0))
      85                 :             :  *   G = lcm([(alpha**i).minpoly() for i in [1056,1057,1058]] + [x + 1])
      86                 :             :  *   print(G) # Print out the generator
      87                 :             :  *   for i in [1,2,4,8,16]: # Print out {1,2,4,8,16}*(G mod x^8), packed in hex integers.
      88                 :             :  *       v = 0
      89                 :             :  *       for coef in reversed((F.fetch_int(i)*(G % x**8)).coefficients(sparse=True)):
      90                 :             :  *           v = v*32 + coef.integer_representation()
      91                 :             :  *       print("0x%x" % v)
      92                 :             :  */
      93                 :   596988925 : uint64_t PolyMod(uint64_t c, int val)
      94                 :             : {
      95                 :   596988925 :     uint8_t c0 = c >> 35;
      96                 :   596988925 :     c = ((c & 0x7ffffffff) << 5) ^ val;
      97         [ +  + ]:   596988925 :     if (c0 & 1) c ^= 0xf5dee51989;
      98         [ +  + ]:   596988925 :     if (c0 & 2) c ^= 0xa9fdca3312;
      99         [ +  + ]:   596988925 :     if (c0 & 4) c ^= 0x1bab10e32d;
     100         [ +  + ]:   596988925 :     if (c0 & 8) c ^= 0x3706b1677a;
     101         [ +  + ]:   596988925 :     if (c0 & 16) c ^= 0x644d626ffd;
     102                 :   596988925 :     return c;
     103                 :             : }
     104                 :             : 
     105                 :     2200478 : std::string DescriptorChecksum(const std::span<const char>& span)
     106                 :             : {
     107                 :             :     /** A character set designed such that:
     108                 :             :      *  - The most common 'unprotected' descriptor characters (hex, keypaths) are in the first group of 32.
     109                 :             :      *  - Case errors cause an offset that's a multiple of 32.
     110                 :             :      *  - As many alphabetic characters are in the same group (while following the above restrictions).
     111                 :             :      *
     112                 :             :      * If p(x) gives the position of a character c in this character set, every group of 3 characters
     113                 :             :      * (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).
     114                 :             :      * This means that changes that only affect the lower 5 bits of the position, or only the higher 2 bits, will just
     115                 :             :      * affect a single symbol.
     116                 :             :      *
     117                 :             :      * As a result, within-group-of-32 errors count as 1 symbol, as do cross-group errors that don't affect
     118                 :             :      * the position within the groups.
     119                 :             :      */
     120                 :     2200478 :     static const std::string INPUT_CHARSET =
     121                 :             :         "0123456789()[],'/*abcdefgh@:$%{}"
     122                 :             :         "IJKLMNOPQRSTUVWXYZ&+-.;<=>?!^_|~"
     123   [ +  +  +  -  :     2200488 :         "ijklmnopqrstuvwxyzABCDEFGH`#\"\\ ";
                   +  - ]
     124                 :             : 
     125                 :             :     /** The character set for the checksum itself (same as bech32). */
     126   [ +  +  +  -  :     2200488 :     static const std::string CHECKSUM_CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
                   +  - ]
     127                 :             : 
     128                 :     2200478 :     uint64_t c = 1;
     129                 :     2200478 :     int cls = 0;
     130                 :     2200478 :     int clscount = 0;
     131         [ +  + ]:   435898615 :     for (auto ch : span) {
     132                 :   433698324 :         auto pos = INPUT_CHARSET.find(ch);
     133         [ +  + ]:   433698324 :         if (pos == std::string::npos) return "";
     134                 :   433698137 :         c = PolyMod(c, pos & 31); // Emit a symbol for the position inside the group, for every character.
     135                 :   433698137 :         cls = cls * 3 + (pos >> 5); // Accumulate the group numbers
     136         [ +  + ]:   433698137 :         if (++clscount == 3) {
     137                 :             :             // Emit an extra symbol representing the group numbers, for every 3 characters.
     138                 :   143662117 :             c = PolyMod(c, cls);
     139                 :   143662117 :             cls = 0;
     140                 :   143662117 :             clscount = 0;
     141                 :             :         }
     142                 :             :     }
     143         [ +  + ]:     2200291 :     if (clscount > 0) c = PolyMod(c, cls);
     144         [ +  + ]:    19802619 :     for (int j = 0; j < 8; ++j) c = PolyMod(c, 0); // Shift further to determine the checksum.
     145                 :     2200291 :     c ^= 1; // Prevent appending zeroes from not affecting the checksum.
     146                 :             : 
     147                 :     2200291 :     std::string ret(8, ' ');
     148         [ +  + ]:    19802619 :     for (int j = 0; j < 8; ++j) ret[j] = CHECKSUM_CHARSET[(c >> (5 * (7 - j))) & 31];
     149                 :     2200291 :     return ret;
     150                 :     2200291 : }
     151                 :             : 
     152   [ +  -  +  - ]:     4324456 : std::string AddChecksum(const std::string& str) { return str + "#" + DescriptorChecksum(str); }
     153                 :             : 
     154                 :             : ////////////////////////////////////////////////////////////////////////////
     155                 :             : // Internal representation                                                //
     156                 :             : ////////////////////////////////////////////////////////////////////////////
     157                 :             : 
     158                 :             : typedef std::vector<uint32_t> KeyPath;
     159                 :             : 
     160                 :             : /** Interface for public key objects in descriptors. */
     161                 :             : struct PubkeyProvider
     162                 :             : {
     163                 :             : protected:
     164                 :             :     //! Index of this key expression in the descriptor
     165                 :             :     //! E.g. If this PubkeyProvider is key1 in multi(2, key1, key2, key3), then m_expr_index = 0
     166                 :             :     uint32_t m_expr_index;
     167                 :             : 
     168                 :             : public:
     169                 :     8562402 :     explicit PubkeyProvider(uint32_t exp_index) : m_expr_index(exp_index) {}
     170                 :             : 
     171                 :           0 :     virtual ~PubkeyProvider() = default;
     172                 :             : 
     173                 :             :     /** Compare two public keys represented by this provider.
     174                 :             :      * Used by the Miniscript descriptors to check for duplicate keys in the script.
     175                 :             :      */
     176                 :      142402 :     bool operator<(PubkeyProvider& other) const {
     177                 :      142402 :         FlatSigningProvider dummy;
     178                 :             : 
     179         [ +  - ]:      142402 :         std::optional<CPubKey> a = GetPubKey(0, dummy, dummy);
     180         [ +  - ]:      142402 :         std::optional<CPubKey> b = other.GetPubKey(0, dummy, dummy);
     181                 :             : 
     182                 :      142402 :         return a < b;
     183                 :      142402 :     }
     184                 :             : 
     185                 :             :     /** Derive a public key and put it into out.
     186                 :             :      *  read_cache is the cache to read keys from (if not nullptr)
     187                 :             :      *  write_cache is the cache to write keys to (if not nullptr)
     188                 :             :      *  Caches are not exclusive but this is not tested. Currently we use them exclusively
     189                 :             :      */
     190                 :             :     virtual std::optional<CPubKey> GetPubKey(int pos, const SigningProvider& arg, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const = 0;
     191                 :             : 
     192                 :             :     /** Whether this represent multiple public keys at different positions. */
     193                 :             :     virtual bool IsRange() const = 0;
     194                 :             : 
     195                 :             :     /** Get the size of the generated public key(s) in bytes (33 or 65). */
     196                 :             :     virtual size_t GetSize() const = 0;
     197                 :             : 
     198                 :             :     enum class StringType {
     199                 :             :         PUBLIC,
     200                 :             :         COMPAT // string calculation that mustn't change over time to stay compatible with previous software versions
     201                 :             :     };
     202                 :             : 
     203                 :             :     /** Get the descriptor string form. */
     204                 :             :     virtual std::string ToString(StringType type=StringType::PUBLIC) const = 0;
     205                 :             : 
     206                 :             :     /** Get the descriptor string form including private data (if available in arg). */
     207                 :             :     virtual bool ToPrivateString(const SigningProvider& arg, std::string& out) const = 0;
     208                 :             : 
     209                 :             :     /** Get the descriptor string form with the xpub at the last hardened derivation,
     210                 :             :      *  and always use h for hardened derivation.
     211                 :             :      */
     212                 :             :     virtual bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache = nullptr) const = 0;
     213                 :             : 
     214                 :             :     /** Derive a private key, if private data is available in arg and put it into out. */
     215                 :             :     virtual void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const = 0;
     216                 :             : 
     217                 :             :     /** Return the non-extended public key for this PubkeyProvider, if it has one. */
     218                 :             :     virtual std::optional<CPubKey> GetRootPubKey() const = 0;
     219                 :             :     /** Return the extended public key for this PubkeyProvider, if it has one. */
     220                 :             :     virtual std::optional<CExtPubKey> GetRootExtPubKey() const = 0;
     221                 :             : 
     222                 :             :     /** Make a deep copy of this PubkeyProvider */
     223                 :             :     virtual std::unique_ptr<PubkeyProvider> Clone() const = 0;
     224                 :             : };
     225                 :             : 
     226                 :             : class OriginPubkeyProvider final : public PubkeyProvider
     227                 :             : {
     228                 :             :     KeyOriginInfo m_origin;
     229                 :             :     std::unique_ptr<PubkeyProvider> m_provider;
     230                 :             :     bool m_apostrophe;
     231                 :             : 
     232                 :     1098246 :     std::string OriginString(StringType type, bool normalized=false) const
     233                 :             :     {
     234                 :             :         // If StringType==COMPAT, always use the apostrophe to stay compatible with previous versions
     235   [ +  +  +  +  :     1098246 :         bool use_apostrophe = (!normalized && m_apostrophe) || type == StringType::COMPAT;
                   +  + ]
     236   [ +  -  +  - ]:     2196492 :         return HexStr(m_origin.fingerprint) + FormatHDKeypath(m_origin.path, use_apostrophe);
     237                 :             :     }
     238                 :             : 
     239                 :             : public:
     240                 :     4025085 :     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) {}
     241                 :     1196128 :     std::optional<CPubKey> GetPubKey(int pos, const SigningProvider& arg, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
     242                 :             :     {
     243                 :     1196128 :         std::optional<CPubKey> pub = m_provider->GetPubKey(pos, arg, out, read_cache, write_cache);
     244         [ +  + ]:     1196128 :         if (!pub) return std::nullopt;
     245                 :     1169725 :         Assert(out.pubkeys.contains(pub->GetID()));
     246                 :     1169725 :         auto& [pubkey, suborigin] = out.origins[pub->GetID()];
     247                 :     1169725 :         Assert(pubkey == *pub); // m_provider must have a valid origin by this point.
     248                 :     1169725 :         std::copy(std::begin(m_origin.fingerprint), std::end(m_origin.fingerprint), suborigin.fingerprint);
     249                 :     1169725 :         suborigin.path.insert(suborigin.path.begin(), m_origin.path.begin(), m_origin.path.end());
     250                 :     1169725 :         return pub;
     251                 :             :     }
     252                 :     1071305 :     bool IsRange() const override { return m_provider->IsRange(); }
     253                 :     1032789 :     size_t GetSize() const override { return m_provider->GetSize(); }
     254   [ +  -  +  -  :     3204714 :     std::string ToString(StringType type) const override { return "[" + OriginString(type) + "]" + m_provider->ToString(type); }
                   +  - ]
     255                 :        2113 :     bool ToPrivateString(const SigningProvider& arg, std::string& ret) const override
     256                 :             :     {
     257         [ +  - ]:        2113 :         std::string sub;
     258   [ +  -  +  + ]:        2113 :         if (!m_provider->ToPrivateString(arg, sub)) return false;
     259   [ +  -  +  -  :        3954 :         ret = "[" + OriginString(StringType::PUBLIC) + "]" + std::move(sub);
                   +  - ]
     260                 :        1977 :         return true;
     261                 :        2113 :     }
     262                 :       28160 :     bool ToNormalizedString(const SigningProvider& arg, std::string& ret, const DescriptorCache* cache) const override
     263                 :             :     {
     264         [ +  - ]:       28160 :         std::string sub;
     265   [ +  -  +  + ]:       28160 :         if (!m_provider->ToNormalizedString(arg, sub, cache)) return false;
     266                 :             :         // If m_provider is a BIP32PubkeyProvider, we may get a string formatted like a OriginPubkeyProvider
     267                 :             :         // In that case, we need to strip out the leading square bracket and fingerprint from the substring,
     268                 :             :         // and append that to our own origin string.
     269         [ +  + ]:       28031 :         if (sub[0] == '[') {
     270         [ +  - ]:       10839 :             sub = sub.substr(9);
     271   [ +  -  +  -  :       10839 :             ret = "[" + OriginString(StringType::PUBLIC, /*normalized=*/true) + std::move(sub);
                   +  - ]
     272                 :             :         } else {
     273   [ +  -  +  -  :       34384 :             ret = "[" + OriginString(StringType::PUBLIC, /*normalized=*/true) + "]" + std::move(sub);
                   +  - ]
     274                 :             :         }
     275                 :             :         return true;
     276                 :       28160 :     }
     277                 :       74855 :     void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const override
     278                 :             :     {
     279                 :       74855 :         m_provider->GetPrivKey(pos, arg, out);
     280                 :       74855 :     }
     281                 :           0 :     std::optional<CPubKey> GetRootPubKey() const override
     282                 :             :     {
     283                 :           0 :         return m_provider->GetRootPubKey();
     284                 :             :     }
     285                 :           0 :     std::optional<CExtPubKey> GetRootExtPubKey() const override
     286                 :             :     {
     287                 :           0 :         return m_provider->GetRootExtPubKey();
     288                 :             :     }
     289                 :       12776 :     std::unique_ptr<PubkeyProvider> Clone() const override
     290                 :             :     {
     291   [ +  -  -  + ]:       12776 :         return std::make_unique<OriginPubkeyProvider>(m_expr_index, m_origin, m_provider->Clone(), m_apostrophe);
     292                 :             :     }
     293                 :             : };
     294                 :             : 
     295                 :             : /** An object representing a parsed constant public key in a descriptor. */
     296                 :           0 : class ConstPubkeyProvider final : public PubkeyProvider
     297                 :             : {
     298                 :             :     CPubKey m_pubkey;
     299                 :             :     bool m_xonly;
     300                 :             : 
     301                 :      110771 :     std::optional<CKey> GetPrivKey(const SigningProvider& arg) const
     302                 :             :     {
     303                 :      110771 :         CKey key;
     304   [ +  +  +  -  :      139405 :         if (!(m_xonly ? arg.GetKeyByXOnly(XOnlyPubKey(m_pubkey), key) :
                   +  + ]
     305   [ +  -  +  - ]:       67082 :                         arg.GetKey(m_pubkey.GetID(), key))) return std::nullopt;
     306                 :       72323 :         return key;
     307                 :      110771 :     }
     308                 :             : 
     309                 :             : public:
     310                 :     4254983 :     ConstPubkeyProvider(uint32_t exp_index, const CPubKey& pubkey, bool xonly) : PubkeyProvider(exp_index), m_pubkey(pubkey), m_xonly(xonly) {}
     311                 :      921183 :     std::optional<CPubKey> GetPubKey(int pos, const SigningProvider&, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
     312                 :             :     {
     313         [ +  - ]:      921183 :         KeyOriginInfo info;
     314         [ +  - ]:      921183 :         CKeyID keyid = m_pubkey.GetID();
     315                 :      921183 :         std::copy(keyid.begin(), keyid.begin() + sizeof(info.fingerprint), info.fingerprint);
     316   [ +  -  +  - ]:      921183 :         out.origins.emplace(keyid, std::make_pair(m_pubkey, info));
     317         [ +  - ]:      921183 :         out.pubkeys.emplace(keyid, m_pubkey);
     318                 :      921183 :         return m_pubkey;
     319                 :      921183 :     }
     320                 :      151870 :     bool IsRange() const override { return false; }
     321                 :     1088717 :     size_t GetSize() const override { return m_pubkey.size(); }
     322   [ +  +  +  - ]:     1442230 :     std::string ToString(StringType type) const override { return m_xonly ? HexStr(m_pubkey).substr(2) : HexStr(m_pubkey); }
     323                 :       13699 :     bool ToPrivateString(const SigningProvider& arg, std::string& ret) const override
     324                 :             :     {
     325                 :       13699 :         std::optional<CKey> key = GetPrivKey(arg);
     326         [ +  + ]:       13699 :         if (!key) return false;
     327         [ +  - ]:        9438 :         ret = EncodeSecret(*key);
     328                 :        9438 :         return true;
     329                 :       13699 :     }
     330                 :       96626 :     bool ToNormalizedString(const SigningProvider& arg, std::string& ret, const DescriptorCache* cache) const override
     331                 :             :     {
     332                 :       96626 :         ret = ToString(StringType::PUBLIC);
     333                 :       96626 :         return true;
     334                 :             :     }
     335                 :       97072 :     void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const override
     336                 :             :     {
     337                 :       97072 :         std::optional<CKey> key = GetPrivKey(arg);
     338         [ +  + ]:       97072 :         if (!key) return;
     339   [ +  -  +  -  :       62885 :         out.keys.emplace(key->GetPubKey().GetID(), *key);
                   +  - ]
     340                 :       97072 :     }
     341                 :           0 :     std::optional<CPubKey> GetRootPubKey() const override
     342                 :             :     {
     343                 :           0 :         return m_pubkey;
     344                 :             :     }
     345                 :           0 :     std::optional<CExtPubKey> GetRootExtPubKey() const override
     346                 :             :     {
     347                 :           0 :         return std::nullopt;
     348                 :             :     }
     349                 :       80944 :     std::unique_ptr<PubkeyProvider> Clone() const override
     350                 :             :     {
     351                 :       80944 :         return std::make_unique<ConstPubkeyProvider>(m_expr_index, m_pubkey, m_xonly);
     352                 :             :     }
     353                 :             : };
     354                 :             : 
     355                 :             : enum class DeriveType {
     356                 :             :     NO,
     357                 :             :     UNHARDENED,
     358                 :             :     HARDENED,
     359                 :             : };
     360                 :             : 
     361                 :             : /** An object representing a parsed extended public key in a descriptor. */
     362                 :             : class BIP32PubkeyProvider final : public PubkeyProvider
     363                 :             : {
     364                 :             :     // Root xpub, path, and final derivation step type being used, if any
     365                 :             :     CExtPubKey m_root_extkey;
     366                 :             :     KeyPath m_path;
     367                 :             :     DeriveType m_derive;
     368                 :             :     // Whether ' or h is used in harded derivation
     369                 :             :     bool m_apostrophe;
     370                 :             : 
     371                 :      377791 :     bool GetExtKey(const SigningProvider& arg, CExtKey& ret) const
     372                 :             :     {
     373                 :      377791 :         CKey key;
     374   [ +  -  +  -  :      377791 :         if (!arg.GetKey(m_root_extkey.pubkey.GetID(), key)) return false;
                   +  + ]
     375                 :      322214 :         ret.nDepth = m_root_extkey.nDepth;
     376                 :      322214 :         std::copy(m_root_extkey.vchFingerprint, m_root_extkey.vchFingerprint + sizeof(ret.vchFingerprint), ret.vchFingerprint);
     377                 :      322214 :         ret.nChild = m_root_extkey.nChild;
     378                 :      322214 :         ret.chaincode = m_root_extkey.chaincode;
     379         [ +  - ]:      322214 :         ret.key = key;
     380                 :             :         return true;
     381                 :      377791 :     }
     382                 :             : 
     383                 :             :     // Derives the last xprv
     384                 :      344572 :     bool GetDerivedExtKey(const SigningProvider& arg, CExtKey& xprv, CExtKey& last_hardened) const
     385                 :             :     {
     386         [ +  + ]:      344572 :         if (!GetExtKey(arg, xprv)) return false;
     387         [ +  + ]:      600984 :         for (auto entry : m_path) {
     388         [ +  - ]:      305996 :             if (!xprv.Derive(xprv, entry)) return false;
     389         [ +  + ]:      305996 :             if (entry >> 31) {
     390                 :       82772 :                 last_hardened = xprv;
     391                 :             :             }
     392                 :             :         }
     393                 :             :         return true;
     394                 :             :     }
     395                 :             : 
     396                 :      424599 :     bool IsHardened() const
     397                 :             :     {
     398         [ +  + ]:      424599 :         if (m_derive == DeriveType::HARDENED) return true;
     399         [ +  + ]:      662426 :         for (auto entry : m_path) {
     400         [ +  + ]:      297017 :             if (entry >> 31) return true;
     401                 :             :         }
     402                 :             :         return false;
     403                 :             :     }
     404                 :             : 
     405                 :             : public:
     406                 :      282334 :     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) {}
     407                 :     2986526 :     bool IsRange() const override { return m_derive != DeriveType::NO; }
     408                 :       93995 :     size_t GetSize() const override { return 33; }
     409                 :     1807412 :     std::optional<CPubKey> GetPubKey(int pos, const SigningProvider& arg, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
     410                 :             :     {
     411         [ +  - ]:     1807412 :         KeyOriginInfo info;
     412         [ +  - ]:     1807412 :         CKeyID keyid = m_root_extkey.pubkey.GetID();
     413                 :     1807412 :         std::copy(keyid.begin(), keyid.begin() + sizeof(info.fingerprint), info.fingerprint);
     414         [ +  - ]:     1807412 :         info.path = m_path;
     415   [ +  +  +  - ]:     1807412 :         if (m_derive == DeriveType::UNHARDENED) info.path.push_back((uint32_t)pos);
     416   [ +  +  +  - ]:     1807412 :         if (m_derive == DeriveType::HARDENED) info.path.push_back(((uint32_t)pos) | 0x80000000L);
     417                 :             : 
     418                 :             :         // Derive keys or fetch them from cache
     419                 :     1807412 :         CExtPubKey final_extkey = m_root_extkey;
     420                 :     1807412 :         CExtPubKey parent_extkey = m_root_extkey;
     421         [ +  + ]:     1807412 :         CExtPubKey last_hardened_extkey;
     422                 :     1807412 :         bool der = true;
     423         [ +  + ]:     1807412 :         if (read_cache) {
     424   [ +  -  +  + ]:     1382813 :             if (!read_cache->GetCachedDerivedExtPubKey(m_expr_index, pos, final_extkey)) {
     425         [ +  + ]:     1348932 :                 if (m_derive == DeriveType::HARDENED) return std::nullopt;
     426                 :             :                 // Try to get the derivation parent
     427   [ +  -  +  + ]:     1346091 :                 if (!read_cache->GetCachedParentExtPubKey(m_expr_index, parent_extkey)) return std::nullopt;
     428                 :     1319128 :                 final_extkey = parent_extkey;
     429   [ +  +  +  - ]:     1319128 :                 if (m_derive == DeriveType::UNHARDENED) der = parent_extkey.Derive(final_extkey, pos);
     430                 :             :             }
     431         [ +  + ]:      424599 :         } else if (IsHardened()) {
     432         [ +  - ]:       59190 :             CExtKey xprv;
     433                 :       59190 :             CExtKey lh_xprv;
     434   [ +  -  +  + ]:       59190 :             if (!GetDerivedExtKey(arg, xprv, lh_xprv)) return std::nullopt;
     435         [ +  - ]:       52534 :             parent_extkey = xprv.Neuter();
     436   [ +  +  +  - ]:       52534 :             if (m_derive == DeriveType::UNHARDENED) der = xprv.Derive(xprv, pos);
     437   [ +  +  +  - ]:       52534 :             if (m_derive == DeriveType::HARDENED) der = xprv.Derive(xprv, pos | 0x80000000UL);
     438         [ +  - ]:       52534 :             final_extkey = xprv.Neuter();
     439         [ +  + ]:       52534 :             if (lh_xprv.key.IsValid()) {
     440         [ +  - ]:       24228 :                 last_hardened_extkey = lh_xprv.Neuter();
     441                 :             :             }
     442                 :       59190 :         } else {
     443         [ +  + ]:      626135 :             for (auto entry : m_path) {
     444   [ +  -  -  + ]:      260726 :                 if (!parent_extkey.Derive(parent_extkey, entry)) return std::nullopt;
     445                 :             :             }
     446                 :      365409 :             final_extkey = parent_extkey;
     447   [ +  +  +  - ]:      365409 :             if (m_derive == DeriveType::UNHARDENED) der = parent_extkey.Derive(final_extkey, pos);
     448         [ -  + ]:      365409 :             assert(m_derive != DeriveType::HARDENED);
     449                 :             :         }
     450         [ -  + ]:     1423229 :         if (!der) return std::nullopt;
     451                 :             : 
     452   [ +  -  +  -  :     1770952 :         out.origins.emplace(final_extkey.pubkey.GetID(), std::make_pair(final_extkey.pubkey, info));
                   +  - ]
     453   [ +  -  +  - ]:     1770952 :         out.pubkeys.emplace(final_extkey.pubkey.GetID(), final_extkey.pubkey);
     454                 :             : 
     455         [ +  + ]:     1770952 :         if (write_cache) {
     456                 :             :             // Only cache parent if there is any unhardened derivation
     457         [ +  + ]:      340775 :             if (m_derive != DeriveType::HARDENED) {
     458         [ +  - ]:      312280 :                 write_cache->CacheParentExtPubKey(m_expr_index, parent_extkey);
     459                 :             :                 // Cache last hardened xpub if we have it
     460         [ +  + ]:      312280 :                 if (last_hardened_extkey.pubkey.IsValid()) {
     461         [ +  - ]:       24039 :                     write_cache->CacheLastHardenedExtPubKey(m_expr_index, last_hardened_extkey);
     462                 :             :                 }
     463         [ +  - ]:       28495 :             } else if (info.path.size() > 0) {
     464         [ +  - ]:       28495 :                 write_cache->CacheDerivedExtPubKey(m_expr_index, pos, final_extkey);
     465                 :             :             }
     466                 :             :         }
     467                 :             : 
     468                 :     1770952 :         return final_extkey.pubkey;
     469                 :     1807412 :     }
     470                 :     1708625 :     std::string ToString(StringType type, bool normalized) const
     471                 :             :     {
     472                 :             :         // If StringType==COMPAT, always use the apostrophe to stay compatible with previous versions
     473   [ +  +  +  +  :     1708625 :         const bool use_apostrophe = (!normalized && m_apostrophe) || type == StringType::COMPAT;
                   +  + ]
     474   [ +  -  +  - ]:     3417250 :         std::string ret = EncodeExtPubKey(m_root_extkey) + FormatHDKeypath(m_path, /*apostrophe=*/use_apostrophe);
     475         [ +  + ]:     1708625 :         if (IsRange()) {
     476         [ +  - ]:     1117884 :             ret += "/*";
     477   [ +  +  +  + ]:     1117884 :             if (m_derive == DeriveType::HARDENED) ret += use_apostrophe ? '\'' : 'h';
     478                 :             :         }
     479                 :     1708625 :         return ret;
     480                 :           0 :     }
     481                 :     1697388 :     std::string ToString(StringType type=StringType::PUBLIC) const override
     482                 :             :     {
     483                 :     1534292 :         return ToString(type, /*normalized=*/false);
     484                 :             :     }
     485                 :       33219 :     bool ToPrivateString(const SigningProvider& arg, std::string& out) const override
     486                 :             :     {
     487         [ +  - ]:       33219 :         CExtKey key;
     488   [ +  -  +  + ]:       33219 :         if (!GetExtKey(arg, key)) return false;
     489   [ +  -  +  -  :       27226 :         out = EncodeExtKey(key) + FormatHDKeypath(m_path, /*apostrophe=*/m_apostrophe);
                   +  - ]
     490         [ +  + ]:       27226 :         if (IsRange()) {
     491         [ +  - ]:        1846 :             out += "/*";
     492   [ +  +  +  + ]:       33906 :             if (m_derive == DeriveType::HARDENED) out += m_apostrophe ? '\'' : 'h';
     493                 :             :         }
     494                 :             :         return true;
     495                 :       33219 :     }
     496                 :      196759 :     bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache) const override
     497                 :             :     {
     498         [ +  + ]:      196759 :         if (m_derive == DeriveType::HARDENED) {
     499                 :       11237 :             out = ToString(StringType::PUBLIC, /*normalized=*/true);
     500                 :             : 
     501                 :       11237 :             return true;
     502                 :             :         }
     503                 :             :         // Step backwards to find the last hardened step in the path
     504                 :      185522 :         int i = (int)m_path.size() - 1;
     505         [ +  + ]:      336621 :         for (; i >= 0; --i) {
     506         [ +  + ]:      173525 :             if (m_path.at(i) >> 31) {
     507                 :             :                 break;
     508                 :             :             }
     509                 :             :         }
     510                 :             :         // Either no derivation or all unhardened derivation
     511         [ +  + ]:      185522 :         if (i == -1) {
     512                 :      163096 :             out = ToString();
     513                 :      163096 :             return true;
     514                 :             :         }
     515                 :             :         // Get the path to the last hardened stup
     516                 :       22426 :         KeyOriginInfo origin;
     517                 :       22426 :         int k = 0;
     518         [ +  + ]:       55496 :         for (; k <= i; ++k) {
     519                 :             :             // Add to the path
     520   [ +  -  +  - ]:       33070 :             origin.path.push_back(m_path.at(k));
     521                 :             :         }
     522                 :             :         // Build the remaining path
     523                 :       22426 :         KeyPath end_path;
     524         [ +  + ]:       24406 :         for (; k < (int)m_path.size(); ++k) {
     525   [ +  -  +  - ]:        1980 :             end_path.push_back(m_path.at(k));
     526                 :             :         }
     527                 :             :         // Get the fingerprint
     528         [ +  - ]:       22426 :         CKeyID id = m_root_extkey.pubkey.GetID();
     529                 :       22426 :         std::copy(id.begin(), id.begin() + 4, origin.fingerprint);
     530                 :             : 
     531         [ +  + ]:       22426 :         CExtPubKey xpub;
     532         [ +  + ]:       22426 :         CExtKey lh_xprv;
     533                 :             :         // If we have the cache, just get the parent xpub
     534         [ +  + ]:       22426 :         if (cache != nullptr) {
     535         [ +  - ]:         311 :             cache->GetCachedLastHardenedExtPubKey(m_expr_index, xpub);
     536                 :             :         }
     537         [ +  + ]:       22426 :         if (!xpub.pubkey.IsValid()) {
     538                 :             :             // Cache miss, or nor cache, or need privkey
     539         [ +  - ]:       22115 :             CExtKey xprv;
     540   [ +  -  +  + ]:       22115 :             if (!GetDerivedExtKey(arg, xprv, lh_xprv)) return false;
     541         [ +  - ]:       21658 :             xpub = lh_xprv.Neuter();
     542                 :       22115 :         }
     543         [ -  + ]:       21969 :         assert(xpub.pubkey.IsValid());
     544                 :             : 
     545                 :             :         // Build the string
     546   [ +  -  +  -  :       43938 :         std::string origin_str = HexStr(origin.fingerprint) + FormatHDKeypath(origin.path);
                   +  - ]
     547   [ +  -  +  -  :       43938 :         out = "[" + origin_str + "]" + EncodeExtPubKey(xpub) + FormatHDKeypath(end_path);
          +  -  +  -  +  
                      - ]
     548         [ +  + ]:       21969 :         if (IsRange()) {
     549         [ +  - ]:         154 :             out += "/*";
     550         [ -  + ]:         154 :             assert(m_derive == DeriveType::UNHARDENED);
     551                 :             :         }
     552                 :       21969 :         return true;
     553                 :       44395 :     }
     554                 :      263267 :     void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const override
     555                 :             :     {
     556         [ +  - ]:      263267 :         CExtKey extkey;
     557                 :      263267 :         CExtKey dummy;
     558   [ +  -  +  + ]:      263267 :         if (!GetDerivedExtKey(arg, extkey, dummy)) return;
     559   [ +  +  +  -  :      220796 :         if (m_derive == DeriveType::UNHARDENED && !extkey.Derive(extkey, pos)) return;
                   +  - ]
     560   [ +  +  +  -  :      220796 :         if (m_derive == DeriveType::HARDENED && !extkey.Derive(extkey, pos | 0x80000000UL)) return;
                   +  - ]
     561   [ +  -  +  -  :      220796 :         out.keys.emplace(extkey.key.GetPubKey().GetID(), extkey.key);
                   +  - ]
     562                 :      263267 :     }
     563                 :           0 :     std::optional<CPubKey> GetRootPubKey() const override
     564                 :             :     {
     565                 :           0 :         return std::nullopt;
     566                 :             :     }
     567                 :           0 :     std::optional<CExtPubKey> GetRootExtPubKey() const override
     568                 :             :     {
     569                 :           0 :         return m_root_extkey;
     570                 :             :     }
     571                 :      153027 :     std::unique_ptr<PubkeyProvider> Clone() const override
     572                 :             :     {
     573         [ -  + ]:      153027 :         return std::make_unique<BIP32PubkeyProvider>(m_expr_index, m_root_extkey, m_path, m_derive, m_apostrophe);
     574                 :             :     }
     575                 :             : };
     576                 :             : 
     577                 :             : /** Base class for all Descriptor implementations. */
     578                 :             : class DescriptorImpl : public Descriptor
     579                 :             : {
     580                 :             : protected:
     581                 :             :     //! Public key arguments for this descriptor (size 1 for PK, PKH, WPKH; any size for WSH and Multisig).
     582                 :             :     const std::vector<std::unique_ptr<PubkeyProvider>> m_pubkey_args;
     583                 :             :     //! The string name of the descriptor function.
     584                 :             :     const std::string m_name;
     585                 :             : 
     586                 :             :     //! The sub-descriptor arguments (empty for everything but SH and WSH).
     587                 :             :     //! In doc/descriptors.m this is referred to as SCRIPT expressions sh(SCRIPT)
     588                 :             :     //! and wsh(SCRIPT), and distinct from KEY expressions and ADDR expressions.
     589                 :             :     //! Subdescriptors can only ever generate a single script.
     590                 :             :     const std::vector<std::unique_ptr<DescriptorImpl>> m_subdescriptor_args;
     591                 :             : 
     592                 :             :     //! Return a serialization of anything except pubkey and script arguments, to be prepended to those.
     593                 :     1617087 :     virtual std::string ToStringExtra() const { return ""; }
     594                 :             : 
     595                 :             :     /** A helper function to construct the scripts for this descriptor.
     596                 :             :      *
     597                 :             :      *  This function is invoked once by ExpandHelper.
     598                 :             :      *
     599                 :             :      *  @param pubkeys The evaluations of the m_pubkey_args field.
     600                 :             :      *  @param scripts The evaluations of m_subdescriptor_args (one for each m_subdescriptor_args element).
     601                 :             :      *  @param out A FlatSigningProvider to put scripts or public keys in that are necessary to the solver.
     602                 :             :      *             The origin info of the provided pubkeys is automatically added.
     603                 :             :      *  @return A vector with scriptPubKeys for this descriptor.
     604                 :             :      */
     605                 :             :     virtual std::vector<CScript> MakeScripts(const std::vector<CPubKey>& pubkeys, std::span<const CScript> scripts, FlatSigningProvider& out) const = 0;
     606                 :             : 
     607                 :             : public:
     608         [ +  - ]:     4434267 :     DescriptorImpl(std::vector<std::unique_ptr<PubkeyProvider>> pubkeys, const std::string& name) : m_pubkey_args(std::move(pubkeys)), m_name(name), m_subdescriptor_args() {}
     609   [ +  -  +  - ]:     2181883 :     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))) {}
     610         [ +  - ]:      413403 :     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)) {}
     611                 :             : 
     612                 :             :     enum class StringType
     613                 :             :     {
     614                 :             :         PUBLIC,
     615                 :             :         PRIVATE,
     616                 :             :         NORMALIZED,
     617                 :             :         COMPAT, // string calculation that mustn't change over time to stay compatible with previous software versions
     618                 :             :     };
     619                 :             : 
     620                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     621                 :       21062 :     bool IsSolvable() const override
     622                 :             :     {
     623         [ +  + ]:       42992 :         for (const auto& arg : m_subdescriptor_args) {
     624         [ +  - ]:       21930 :             if (!arg->IsSolvable()) return false;
     625                 :             :         }
     626                 :             :         return true;
     627                 :             :     }
     628                 :             : 
     629                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     630                 :     1615606 :     bool IsRange() const final
     631                 :             :     {
     632         [ +  + ]:     1948599 :         for (const auto& pubkey : m_pubkey_args) {
     633         [ +  + ]:     1380576 :             if (pubkey->IsRange()) return true;
     634                 :             :         }
     635         [ +  + ]:      612676 :         for (const auto& arg : m_subdescriptor_args) {
     636         [ +  + ]:      535629 :             if (arg->IsRange()) return true;
     637                 :             :         }
     638                 :             :         return false;
     639                 :             :     }
     640                 :             : 
     641                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     642                 :     2376648 :     virtual bool ToStringSubScriptHelper(const SigningProvider* arg, std::string& ret, const StringType type, const DescriptorCache* cache = nullptr) const
     643                 :             :     {
     644                 :     2376648 :         size_t pos = 0;
     645         [ +  + ]:     2879811 :         for (const auto& scriptarg : m_subdescriptor_args) {
     646         [ -  + ]:      508589 :             if (pos++) ret += ",";
     647         [ +  - ]:      508589 :             std::string tmp;
     648   [ +  -  +  + ]:      508589 :             if (!scriptarg->ToStringHelper(arg, tmp, type, cache)) return false;
     649         [ +  - ]:     1006326 :             ret += tmp;
     650                 :      508589 :         }
     651                 :             :         return true;
     652                 :             :     }
     653                 :             : 
     654                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     655                 :     2668418 :     virtual bool ToStringHelper(const SigningProvider* arg, std::string& out, const StringType type, const DescriptorCache* cache = nullptr) const
     656                 :             :     {
     657                 :     2668418 :         std::string extra = ToStringExtra();
     658         [ +  + ]:     2668418 :         size_t pos = extra.size() > 0 ? 1 : 0;
     659   [ +  -  +  - ]:     2668418 :         std::string ret = m_name + "(" + extra;
     660         [ +  + ]:     5122231 :         for (const auto& pubkey : m_pubkey_args) {
     661   [ +  +  +  - ]:     2460396 :             if (pos++) ret += ",";
     662   [ +  +  +  +  :     2460396 :             std::string tmp;
                      - ]
     663   [ +  +  +  +  :     2460396 :             switch (type) {
                      - ]
     664                 :      293385 :                 case StringType::NORMALIZED:
     665   [ +  -  +  + ]:      293385 :                     if (!pubkey->ToNormalizedString(*arg, tmp, cache)) return false;
     666                 :             :                     break;
     667                 :       35208 :                 case StringType::PRIVATE:
     668   [ +  -  +  + ]:       35208 :                     if (!pubkey->ToPrivateString(*arg, tmp)) return false;
     669                 :             :                     break;
     670                 :     2058504 :                 case StringType::PUBLIC:
     671         [ +  - ]:     2058504 :                     tmp = pubkey->ToString();
     672                 :     2058504 :                     break;
     673                 :       73299 :                 case StringType::COMPAT:
     674         [ +  - ]:       73299 :                     tmp = pubkey->ToString(PubkeyProvider::StringType::COMPAT);
     675                 :       73299 :                     break;
     676                 :             :             }
     677         [ +  - ]:     4907626 :             ret += tmp;
     678                 :     2460396 :         }
     679         [ +  - ]:     5323670 :         std::string subscript;
     680   [ +  -  +  + ]:     2661835 :         if (!ToStringSubScriptHelper(arg, subscript, type, cache)) return false;
     681   [ +  +  +  +  :     2653800 :         if (pos && subscript.size()) ret += ',';
                   +  - ]
     682         [ +  - ]:     5307600 :         out = std::move(ret) + std::move(subscript) + ")";
     683                 :     2653800 :         return true;
     684                 :     2668418 :     }
     685                 :             : 
     686                 :     2132006 :     std::string ToString(bool compat_format) const final
     687                 :             :     {
     688         [ +  + ]:     2132006 :         std::string ret;
     689   [ +  +  +  - ]:     4235094 :         ToStringHelper(nullptr, ret, compat_format ? StringType::COMPAT : StringType::PUBLIC);
     690         [ +  - ]:     2132006 :         return AddChecksum(ret);
     691                 :     2132006 :     }
     692                 :             : 
     693                 :       14141 :     bool ToPrivateString(const SigningProvider& arg, std::string& out) const override
     694                 :             :     {
     695                 :       14141 :         bool ret = ToStringHelper(&arg, out, StringType::PRIVATE);
     696                 :       14141 :         out = AddChecksum(out);
     697                 :       14141 :         return ret;
     698                 :             :     }
     699                 :             : 
     700                 :       16081 :     bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache) const override final
     701                 :             :     {
     702                 :       16081 :         bool ret = ToStringHelper(&arg, out, StringType::NORMALIZED, cache);
     703                 :       16081 :         out = AddChecksum(out);
     704                 :       16081 :         return ret;
     705                 :             :     }
     706                 :             : 
     707                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     708                 :     1618555 :     bool ExpandHelper(int pos, const SigningProvider& arg, const DescriptorCache* read_cache, std::vector<CScript>& output_scripts, FlatSigningProvider& out, DescriptorCache* write_cache) const
     709                 :             :     {
     710                 :     1618555 :         FlatSigningProvider subprovider;
     711                 :     1618555 :         std::vector<CPubKey> pubkeys;
     712         [ +  - ]:     1618555 :         pubkeys.reserve(m_pubkey_args.size());
     713                 :             : 
     714                 :             :         // Construct temporary data in `pubkeys`, `subscripts`, and `subprovider` to avoid producing output in case of failure.
     715         [ +  + ]:     4030813 :         for (const auto& p : m_pubkey_args) {
     716         [ +  - ]:     2443791 :             std::optional<CPubKey> pubkey = p->GetPubKey(pos, arg, subprovider, read_cache, write_cache);
     717         [ +  + ]:     2443791 :             if (!pubkey) return false;
     718         [ +  - ]:     2412258 :             pubkeys.push_back(pubkey.value());
     719                 :             :         }
     720                 :     1587022 :         std::vector<CScript> subscripts;
     721         [ +  + ]:     2109514 :         for (const auto& subarg : m_subdescriptor_args) {
     722                 :      531723 :             std::vector<CScript> outscripts;
     723   [ +  -  +  + ]:      531723 :             if (!subarg->ExpandHelper(pos, arg, read_cache, outscripts, subprovider, write_cache)) return false;
     724         [ -  + ]:      522492 :             assert(outscripts.size() == 1);
     725         [ +  - ]:      522492 :             subscripts.emplace_back(std::move(outscripts[0]));
     726                 :      531723 :         }
     727         [ +  - ]:     1577791 :         out.Merge(std::move(subprovider));
     728                 :             : 
     729         [ +  - ]:     1577791 :         output_scripts = MakeScripts(pubkeys, std::span{subscripts}, out);
     730                 :     1577791 :         return true;
     731                 :     3205577 :     }
     732                 :             : 
     733                 :       44166 :     bool Expand(int pos, const SigningProvider& provider, std::vector<CScript>& output_scripts, FlatSigningProvider& out, DescriptorCache* write_cache = nullptr) const final
     734                 :             :     {
     735                 :       44166 :         return ExpandHelper(pos, provider, nullptr, output_scripts, out, write_cache);
     736                 :             :     }
     737                 :             : 
     738                 :     1042666 :     bool ExpandFromCache(int pos, const DescriptorCache& read_cache, std::vector<CScript>& output_scripts, FlatSigningProvider& out) const final
     739                 :             :     {
     740                 :     1042666 :         return ExpandHelper(pos, DUMMY_SIGNING_PROVIDER, &read_cache, output_scripts, out, nullptr);
     741                 :             :     }
     742                 :             : 
     743                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     744                 :       91246 :     void ExpandPrivate(int pos, const SigningProvider& provider, FlatSigningProvider& out) const final
     745                 :             :     {
     746         [ +  + ]:      451585 :         for (const auto& p : m_pubkey_args) {
     747                 :      360339 :             p->GetPrivKey(pos, provider, out);
     748                 :             :         }
     749         [ +  + ]:      117016 :         for (const auto& arg : m_subdescriptor_args) {
     750                 :       25770 :             arg->ExpandPrivate(pos, provider, out);
     751                 :             :         }
     752                 :       91246 :     }
     753                 :             : 
     754                 :        6501 :     std::optional<OutputType> GetOutputType() const override { return std::nullopt; }
     755                 :             : 
     756                 :           0 :     std::optional<int64_t> ScriptSize() const override { return {}; }
     757                 :             : 
     758                 :             :     /** A helper for MaxSatisfactionWeight.
     759                 :             :      *
     760                 :             :      * @param use_max_sig Whether to assume ECDSA signatures will have a high-r.
     761                 :             :      * @return The maximum size of the satisfaction in raw bytes (with no witness meaning).
     762                 :             :      */
     763                 :           0 :     virtual std::optional<int64_t> MaxSatSize(bool use_max_sig) const { return {}; }
     764                 :             : 
     765                 :        1564 :     std::optional<int64_t> MaxSatisfactionWeight(bool) const override { return {}; }
     766                 :             : 
     767                 :         782 :     std::optional<int64_t> MaxSatisfactionElems() const override { return {}; }
     768                 :             : 
     769                 :             :     // NOLINTNEXTLINE(misc-no-recursion)
     770                 :           0 :     void GetPubKeys(std::set<CPubKey>& pubkeys, std::set<CExtPubKey>& ext_pubs) const override
     771                 :             :     {
     772         [ #  # ]:           0 :         for (const auto& p : m_pubkey_args) {
     773                 :           0 :             std::optional<CPubKey> pub = p->GetRootPubKey();
     774         [ #  # ]:           0 :             if (pub) pubkeys.insert(*pub);
     775                 :           0 :             std::optional<CExtPubKey> ext_pub = p->GetRootExtPubKey();
     776         [ #  # ]:           0 :             if (ext_pub) ext_pubs.insert(*ext_pub);
     777                 :             :         }
     778         [ #  # ]:           0 :         for (const auto& arg : m_subdescriptor_args) {
     779                 :           0 :             arg->GetPubKeys(pubkeys, ext_pubs);
     780                 :             :         }
     781                 :           0 :     }
     782                 :             : 
     783                 :             :     virtual std::unique_ptr<DescriptorImpl> Clone() const = 0;
     784                 :             : };
     785                 :             : 
     786                 :             : /** A parsed addr(A) descriptor. */
     787                 :             : class AddressDescriptor final : public DescriptorImpl
     788                 :             : {
     789                 :             :     const CTxDestination m_destination;
     790                 :             : protected:
     791                 :      268297 :     std::string ToStringExtra() const override { return EncodeDestination(m_destination); }
     792         [ +  - ]:          66 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, std::span<const CScript>, FlatSigningProvider&) const override { return Vector(GetScriptForDestination(m_destination)); }
     793                 :             : public:
     794         [ +  - ]:      268333 :     AddressDescriptor(CTxDestination destination) : DescriptorImpl({}, "addr"), m_destination(std::move(destination)) {}
     795                 :           0 :     bool IsSolvable() const final { return false; }
     796                 :             : 
     797                 :          64 :     std::optional<OutputType> GetOutputType() const override
     798                 :             :     {
     799                 :          64 :         return OutputTypeFromDestination(m_destination);
     800                 :             :     }
     801                 :         128 :     bool IsSingleType() const final { return true; }
     802                 :           0 :     bool IsSingleKey() const final { return false; }
     803                 :           2 :     bool ToPrivateString(const SigningProvider& arg, std::string& out) const final { return false; }
     804                 :             : 
     805         [ #  # ]:           0 :     std::optional<int64_t> ScriptSize() const override { return GetScriptForDestination(m_destination).size(); }
     806                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
     807                 :             :     {
     808         [ #  # ]:           0 :         return std::make_unique<AddressDescriptor>(m_destination);
     809                 :             :     }
     810                 :             : };
     811                 :             : 
     812                 :             : /** A parsed raw(H) descriptor. */
     813                 :             : class RawDescriptor final : public DescriptorImpl
     814                 :             : {
     815                 :             :     const CScript m_script;
     816                 :             : protected:
     817         [ +  + ]:     1499478 :     std::string ToStringExtra() const override { return HexStr(m_script); }
     818                 :        1596 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, std::span<const CScript>, FlatSigningProvider&) const override { return Vector(m_script); }
     819                 :             : public:
     820         [ +  - ]:      749142 :     RawDescriptor(CScript script) : DescriptorImpl({}, "raw"), m_script(std::move(script)) {}
     821                 :         225 :     bool IsSolvable() const final { return false; }
     822                 :             : 
     823                 :        1734 :     std::optional<OutputType> GetOutputType() const override
     824                 :             :     {
     825                 :        1734 :         CTxDestination dest;
     826         [ +  - ]:        1734 :         ExtractDestination(m_script, dest);
     827         [ +  - ]:        1734 :         return OutputTypeFromDestination(dest);
     828                 :        1734 :     }
     829                 :        2136 :     bool IsSingleType() const final { return true; }
     830                 :           0 :     bool IsSingleKey() const final { return false; }
     831                 :         342 :     bool ToPrivateString(const SigningProvider& arg, std::string& out) const final { return false; }
     832                 :             : 
     833         [ +  + ]:         224 :     std::optional<int64_t> ScriptSize() const override { return m_script.size(); }
     834                 :             : 
     835                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
     836                 :             :     {
     837         [ #  # ]:           0 :         return std::make_unique<RawDescriptor>(m_script);
     838                 :             :     }
     839                 :             : };
     840                 :             : 
     841                 :             : /** A parsed pk(P) descriptor. */
     842                 :             : class PKDescriptor final : public DescriptorImpl
     843                 :             : {
     844                 :             : private:
     845                 :             :     const bool m_xonly;
     846                 :             : protected:
     847                 :        8118 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override
     848                 :             :     {
     849         [ +  + ]:        8118 :         if (m_xonly) {
     850   [ +  -  +  - ]:        5961 :             CScript script = CScript() << ToByteVector(XOnlyPubKey(keys[0])) << OP_CHECKSIG;
     851         [ +  - ]:        5961 :             return Vector(std::move(script));
     852                 :        5961 :         } else {
     853         [ +  - ]:        4314 :             return Vector(GetScriptForRawPubKey(keys[0]));
     854                 :             :         }
     855                 :             :     }
     856                 :             : public:
     857   [ +  -  +  - ]:       31244 :     PKDescriptor(std::unique_ptr<PubkeyProvider> prov, bool xonly = false) : DescriptorImpl(Vector(std::move(prov)), "pk"), m_xonly(xonly) {}
     858                 :         466 :     bool IsSingleType() const final { return true; }
     859                 :           0 :     bool IsSingleKey() const final { return true; }
     860                 :             : 
     861                 :         769 :     std::optional<int64_t> ScriptSize() const override {
     862         [ +  - ]:         769 :         return 1 + (m_xonly ? 32 : m_pubkey_args[0]->GetSize()) + 1;
     863                 :             :     }
     864                 :             : 
     865                 :         970 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
     866         [ -  + ]:         578 :         const auto ecdsa_sig_size = use_max_sig ? 72 : 71;
     867   [ +  -  +  - ]:         970 :         return 1 + (m_xonly ? 65 : ecdsa_sig_size);
     868                 :             :     }
     869                 :             : 
     870                 :         392 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
     871         [ -  + ]:         392 :         return *MaxSatSize(use_max_sig) * WITNESS_SCALE_FACTOR;
     872                 :             :     }
     873                 :             : 
     874                 :         485 :     std::optional<int64_t> MaxSatisfactionElems() const override { return 1; }
     875                 :             : 
     876                 :        1134 :     std::unique_ptr<DescriptorImpl> Clone() const override
     877                 :             :     {
     878   [ +  -  -  + ]:        1134 :         return std::make_unique<PKDescriptor>(m_pubkey_args.at(0)->Clone(), m_xonly);
     879                 :             :     }
     880                 :             : };
     881                 :             : 
     882                 :             : /** A parsed pkh(P) descriptor. */
     883                 :             : class PKHDescriptor final : public DescriptorImpl
     884                 :             : {
     885                 :             : protected:
     886                 :      230816 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override
     887                 :             :     {
     888                 :      230816 :         CKeyID id = keys[0].GetID();
     889   [ +  -  +  - ]:      461632 :         return Vector(GetScriptForDestination(PKHash(id)));
     890                 :             :     }
     891                 :             : public:
     892   [ +  -  +  - ]:     1056297 :     PKHDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "pkh") {}
     893                 :     1140275 :     std::optional<OutputType> GetOutputType() const override { return OutputType::LEGACY; }
     894                 :      174639 :     bool IsSingleType() const final { return true; }
     895                 :           0 :     bool IsSingleKey() const final { return true; }
     896                 :             : 
     897                 :         667 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 1 + 20 + 1 + 1; }
     898                 :             : 
     899                 :     1012004 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
     900         [ +  + ]:     1012004 :         const auto sig_size = use_max_sig ? 72 : 71;
     901                 :     1012004 :         return 1 + sig_size + 1 + m_pubkey_args[0]->GetSize();
     902                 :             :     }
     903                 :             : 
     904                 :     1011502 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
     905                 :     1011502 :         return *MaxSatSize(use_max_sig) * WITNESS_SCALE_FACTOR;
     906                 :             :     }
     907                 :             : 
     908                 :     1011584 :     std::optional<int64_t> MaxSatisfactionElems() const override { return 2; }
     909                 :             : 
     910                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
     911                 :             :     {
     912   [ #  #  #  # ]:           0 :         return std::make_unique<PKHDescriptor>(m_pubkey_args.at(0)->Clone());
     913                 :             :     }
     914                 :             : };
     915                 :             : 
     916                 :             : /** A parsed wpkh(P) descriptor. */
     917                 :             : class WPKHDescriptor final : public DescriptorImpl
     918                 :             : {
     919                 :             : protected:
     920                 :      494765 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override
     921                 :             :     {
     922                 :      494765 :         CKeyID id = keys[0].GetID();
     923   [ +  -  +  - ]:      989530 :         return Vector(GetScriptForDestination(WitnessV0KeyHash(id)));
     924                 :             :     }
     925                 :             : public:
     926   [ +  -  +  - ]:     2259525 :     WPKHDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "wpkh") {}
     927                 :     4577608 :     std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32; }
     928                 :       21549 :     bool IsSingleType() const final { return true; }
     929                 :           0 :     bool IsSingleKey() const final { return true; }
     930                 :             : 
     931                 :     2136761 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 20; }
     932                 :             : 
     933                 :     2221671 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
     934         [ +  + ]:     2136428 :         const auto sig_size = use_max_sig ? 72 : 71;
     935                 :     2221671 :         return (1 + sig_size + 1 + 33);
     936                 :             :     }
     937                 :             : 
     938                 :       85243 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
     939         [ +  + ]:       85243 :         return MaxSatSize(use_max_sig);
     940                 :             :     }
     941                 :             : 
     942                 :     2221227 :     std::optional<int64_t> MaxSatisfactionElems() const override { return 2; }
     943                 :             : 
     944                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
     945                 :             :     {
     946   [ #  #  #  # ]:           0 :         return std::make_unique<WPKHDescriptor>(m_pubkey_args.at(0)->Clone());
     947                 :             :     }
     948                 :             : };
     949                 :             : 
     950                 :             : /** A parsed combo(P) descriptor. */
     951                 :             : class ComboDescriptor final : public DescriptorImpl
     952                 :             : {
     953                 :             : protected:
     954                 :        2146 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider& out) const override
     955                 :             :     {
     956                 :        2146 :         std::vector<CScript> ret;
     957         [ +  - ]:        2146 :         CKeyID id = keys[0].GetID();
     958   [ +  -  +  - ]:        2146 :         ret.emplace_back(GetScriptForRawPubKey(keys[0])); // P2PK
     959   [ +  -  +  -  :        4292 :         ret.emplace_back(GetScriptForDestination(PKHash(id))); // P2PKH
                   +  - ]
     960         [ +  + ]:        2146 :         if (keys[0].IsCompressed()) {
     961         [ +  - ]:        2130 :             CScript p2wpkh = GetScriptForDestination(WitnessV0KeyHash(id));
     962   [ +  -  +  - ]:        2130 :             out.scripts.emplace(CScriptID(p2wpkh), p2wpkh);
     963         [ +  - ]:        2130 :             ret.emplace_back(p2wpkh);
     964   [ +  -  +  -  :        4260 :             ret.emplace_back(GetScriptForDestination(ScriptHash(p2wpkh))); // P2SH-P2WPKH
                   +  - ]
     965                 :        2130 :         }
     966                 :        2146 :         return ret;
     967                 :           0 :     }
     968                 :             : public:
     969   [ +  -  +  - ]:         926 :     ComboDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "combo") {}
     970                 :        1305 :     bool IsSingleType() const final { return false; }
     971                 :           0 :     bool IsSingleKey() const final { return true; }
     972                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
     973                 :             :     {
     974   [ #  #  #  # ]:           0 :         return std::make_unique<ComboDescriptor>(m_pubkey_args.at(0)->Clone());
     975                 :             :     }
     976                 :             : };
     977                 :             : 
     978                 :             : /** A parsed multi(...) or sortedmulti(...) descriptor */
     979                 :             : class MultisigDescriptor final : public DescriptorImpl
     980                 :             : {
     981                 :             :     const int m_threshold;
     982                 :             :     const bool m_sorted;
     983                 :             : protected:
     984                 :       27067 :     std::string ToStringExtra() const override { return strprintf("%i", m_threshold); }
     985                 :        5055 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override {
     986         [ +  + ]:        5055 :         if (m_sorted) {
     987                 :        2703 :             std::vector<CPubKey> sorted_keys(keys);
     988                 :        2703 :             std::sort(sorted_keys.begin(), sorted_keys.end());
     989   [ +  -  +  - ]:        5406 :             return Vector(GetScriptForMultisig(m_threshold, sorted_keys));
     990                 :        2703 :         }
     991         [ +  - ]:        4704 :         return Vector(GetScriptForMultisig(m_threshold, keys));
     992                 :             :     }
     993                 :             : public:
     994   [ +  +  +  - ]:       47699 :     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) {}
     995                 :         399 :     bool IsSingleType() const final { return true; }
     996                 :           0 :     bool IsSingleKey() const final { return false; }
     997                 :             : 
     998                 :        3483 :     std::optional<int64_t> ScriptSize() const override {
     999                 :        3483 :         const auto n_keys = m_pubkey_args.size();
    1000                 :       47497 :         auto op = [](int64_t acc, const std::unique_ptr<PubkeyProvider>& pk) { return acc + 1 + pk->GetSize();};
    1001                 :        3483 :         const auto pubkeys_size{std::accumulate(m_pubkey_args.begin(), m_pubkey_args.end(), int64_t{0}, op)};
    1002   [ -  +  +  - ]:        6966 :         return 1 + BuildScript(n_keys).size() + BuildScript(m_threshold).size() + pubkeys_size;
    1003                 :             :     }
    1004                 :             : 
    1005                 :        3630 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
    1006         [ -  + ]:        3348 :         const auto sig_size = use_max_sig ? 72 : 71;
    1007                 :        3630 :         return (1 + (1 + sig_size) * m_threshold);
    1008                 :             :     }
    1009                 :             : 
    1010                 :         282 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
    1011         [ -  + ]:         282 :         return *MaxSatSize(use_max_sig) * WITNESS_SCALE_FACTOR;
    1012                 :             :     }
    1013                 :             : 
    1014                 :        1815 :     std::optional<int64_t> MaxSatisfactionElems() const override { return 1 + m_threshold; }
    1015                 :             : 
    1016                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1017                 :             :     {
    1018                 :           0 :         std::vector<std::unique_ptr<PubkeyProvider>> providers;
    1019         [ #  # ]:           0 :         providers.reserve(m_pubkey_args.size());
    1020         [ #  # ]:           0 :         std::transform(m_pubkey_args.begin(), m_pubkey_args.end(), providers.begin(), [](const std::unique_ptr<PubkeyProvider>& p) { return p->Clone(); });
    1021   [ #  #  #  # ]:           0 :         return std::make_unique<MultisigDescriptor>(m_threshold, std::move(providers), m_sorted);
    1022                 :           0 :     }
    1023                 :             : };
    1024                 :             : 
    1025                 :             : /** A parsed (sorted)multi_a(...) descriptor. Always uses x-only pubkeys. */
    1026                 :             : class MultiADescriptor final : public DescriptorImpl
    1027                 :             : {
    1028                 :             :     const int m_threshold;
    1029                 :             :     const bool m_sorted;
    1030                 :             : protected:
    1031                 :        6228 :     std::string ToStringExtra() const override { return strprintf("%i", m_threshold); }
    1032                 :        4918 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override {
    1033                 :        4918 :         CScript ret;
    1034                 :        4918 :         std::vector<XOnlyPubKey> xkeys;
    1035         [ +  - ]:        4918 :         xkeys.reserve(keys.size());
    1036   [ +  -  +  + ]:     1187405 :         for (const auto& key : keys) xkeys.emplace_back(key);
    1037         [ +  + ]:        4918 :         if (m_sorted) std::sort(xkeys.begin(), xkeys.end());
    1038   [ +  -  +  - ]:        4918 :         ret << ToByteVector(xkeys[0]) << OP_CHECKSIG;
    1039         [ +  + ]:     1182487 :         for (size_t i = 1; i < keys.size(); ++i) {
    1040   [ +  -  +  - ]:     2355138 :             ret << ToByteVector(xkeys[i]) << OP_CHECKSIGADD;
    1041                 :             :         }
    1042   [ +  -  +  - ]:        4918 :         ret << m_threshold << OP_NUMEQUAL;
    1043         [ +  - ]:        4918 :         return Vector(std::move(ret));
    1044                 :        4918 :     }
    1045                 :             : public:
    1046   [ +  +  +  - ]:        6468 :     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) {}
    1047                 :           0 :     bool IsSingleType() const final { return true; }
    1048                 :           0 :     bool IsSingleKey() const final { return false; }
    1049                 :             : 
    1050                 :           0 :     std::optional<int64_t> ScriptSize() const override {
    1051                 :           0 :         const auto n_keys = m_pubkey_args.size();
    1052         [ #  # ]:           0 :         return (1 + 32 + 1) * n_keys + BuildScript(m_threshold).size() + 1;
    1053                 :             :     }
    1054                 :             : 
    1055                 :           0 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
    1056                 :           0 :         return (1 + 65) * m_threshold + (m_pubkey_args.size() - m_threshold);
    1057                 :             :     }
    1058                 :             : 
    1059                 :           0 :     std::optional<int64_t> MaxSatisfactionElems() const override { return m_pubkey_args.size(); }
    1060                 :             : 
    1061                 :         146 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1062                 :             :     {
    1063                 :         146 :         std::vector<std::unique_ptr<PubkeyProvider>> providers;
    1064         [ +  - ]:         146 :         providers.reserve(m_pubkey_args.size());
    1065         [ +  + ]:         437 :         for (const auto& arg : m_pubkey_args) {
    1066         [ +  - ]:         582 :             providers.push_back(arg->Clone());
    1067                 :             :         }
    1068   [ +  -  -  + ]:         292 :         return std::make_unique<MultiADescriptor>(m_threshold, std::move(providers), m_sorted);
    1069                 :         146 :     }
    1070                 :             : };
    1071                 :             : 
    1072                 :             : /** A parsed sh(...) descriptor. */
    1073                 :             : class SHDescriptor final : public DescriptorImpl
    1074                 :             : {
    1075                 :             : protected:
    1076                 :      474758 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, std::span<const CScript> scripts, FlatSigningProvider& out) const override
    1077                 :             :     {
    1078   [ +  -  +  - ]:      949516 :         auto ret = Vector(GetScriptForDestination(ScriptHash(scripts[0])));
    1079   [ +  -  +  -  :      474758 :         if (ret.size()) out.scripts.emplace(CScriptID(scripts[0]), scripts[0]);
                   +  - ]
    1080                 :      474758 :         return ret;
    1081                 :           0 :     }
    1082                 :             : 
    1083         [ +  + ]:     4486462 :     bool IsSegwit() const { return m_subdescriptor_args[0]->GetOutputType() == OutputType::BECH32; }
    1084                 :             : 
    1085                 :             : public:
    1086         [ +  - ]:     2170985 :     SHDescriptor(std::unique_ptr<DescriptorImpl> desc) : DescriptorImpl({}, std::move(desc), "sh") {}
    1087                 :             : 
    1088                 :     2346452 :     std::optional<OutputType> GetOutputType() const override
    1089                 :             :     {
    1090         [ -  + ]:     2346452 :         assert(m_subdescriptor_args.size() == 1);
    1091         [ +  + ]:     2346452 :         if (IsSegwit()) return OutputType::P2SH_SEGWIT;
    1092                 :        3085 :         return OutputType::LEGACY;
    1093                 :             :     }
    1094                 :      361585 :     bool IsSingleType() const final { return true; }
    1095                 :           0 :     bool IsSingleKey() const final { return m_subdescriptor_args[0]->IsSingleKey(); }
    1096                 :             : 
    1097                 :        1819 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 20 + 1; }
    1098                 :             : 
    1099                 :     2140010 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
    1100         [ +  - ]:     2140010 :         if (const auto sat_size = m_subdescriptor_args[0]->MaxSatSize(use_max_sig)) {
    1101         [ +  - ]:     2140010 :             if (const auto subscript_size = m_subdescriptor_args[0]->ScriptSize()) {
    1102                 :             :                 // The subscript is never witness data.
    1103                 :     2140010 :                 const auto subscript_weight = (1 + *subscript_size) * WITNESS_SCALE_FACTOR;
    1104                 :             :                 // The weight depends on whether the inner descriptor is satisfied using the witness stack.
    1105         [ +  + ]:     2140010 :                 if (IsSegwit()) return subscript_weight + *sat_size;
    1106                 :        1802 :                 return subscript_weight + *sat_size * WITNESS_SCALE_FACTOR;
    1107                 :             :             }
    1108                 :             :         }
    1109                 :           0 :         return {};
    1110                 :             :     }
    1111                 :             : 
    1112                 :     2138135 :     std::optional<int64_t> MaxSatisfactionElems() const override {
    1113         [ +  - ]:     2138135 :         if (const auto sub_elems = m_subdescriptor_args[0]->MaxSatisfactionElems()) return 1 + *sub_elems;
    1114                 :           0 :         return {};
    1115                 :             :     }
    1116                 :             : 
    1117                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1118                 :             :     {
    1119   [ #  #  #  # ]:           0 :         return std::make_unique<SHDescriptor>(m_subdescriptor_args.at(0)->Clone());
    1120                 :             :     }
    1121                 :             : };
    1122                 :             : 
    1123                 :             : /** A parsed wsh(...) descriptor. */
    1124                 :             : class WSHDescriptor final : public DescriptorImpl
    1125                 :             : {
    1126                 :             : protected:
    1127                 :       12726 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, std::span<const CScript> scripts, FlatSigningProvider& out) const override
    1128                 :             :     {
    1129   [ +  -  +  - ]:       25452 :         auto ret = Vector(GetScriptForDestination(WitnessV0ScriptHash(scripts[0])));
    1130   [ +  -  +  -  :       12726 :         if (ret.size()) out.scripts.emplace(CScriptID(scripts[0]), scripts[0]);
                   +  - ]
    1131                 :       12726 :         return ret;
    1132                 :           0 :     }
    1133                 :             : public:
    1134         [ +  - ]:       10898 :     WSHDescriptor(std::unique_ptr<DescriptorImpl> desc) : DescriptorImpl({}, std::move(desc), "wsh") {}
    1135                 :       13719 :     std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32; }
    1136                 :       10596 :     bool IsSingleType() const final { return true; }
    1137                 :           0 :     bool IsSingleKey() const final { return m_subdescriptor_args[0]->IsSingleKey(); }
    1138                 :             : 
    1139                 :        5788 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
    1140                 :             : 
    1141                 :       10162 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
    1142         [ +  - ]:       10162 :         if (const auto sat_size = m_subdescriptor_args[0]->MaxSatSize(use_max_sig)) {
    1143         [ +  - ]:       10162 :             if (const auto subscript_size = m_subdescriptor_args[0]->ScriptSize()) {
    1144         [ +  + ]:       13480 :                 return GetSizeOfCompactSize(*subscript_size) + *subscript_size + *sat_size;
    1145                 :             :             }
    1146                 :             :         }
    1147                 :           0 :         return {};
    1148                 :             :     }
    1149                 :             : 
    1150                 :        8382 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
    1151                 :        8382 :         return MaxSatSize(use_max_sig);
    1152                 :             :     }
    1153                 :             : 
    1154                 :        5081 :     std::optional<int64_t> MaxSatisfactionElems() const override {
    1155         [ +  - ]:        5081 :         if (const auto sub_elems = m_subdescriptor_args[0]->MaxSatisfactionElems()) return 1 + *sub_elems;
    1156                 :           0 :         return {};
    1157                 :             :     }
    1158                 :             : 
    1159                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1160                 :             :     {
    1161   [ #  #  #  # ]:           0 :         return std::make_unique<WSHDescriptor>(m_subdescriptor_args.at(0)->Clone());
    1162                 :             :     }
    1163                 :             : };
    1164                 :             : 
    1165                 :             : /** A parsed tr(...) descriptor. */
    1166                 :             : class TRDescriptor final : public DescriptorImpl
    1167                 :             : {
    1168                 :             :     std::vector<int> m_depths;
    1169                 :             : protected:
    1170                 :      308108 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript> scripts, FlatSigningProvider& out) const override
    1171                 :             :     {
    1172         [ -  + ]:      308108 :         TaprootBuilder builder;
    1173         [ -  + ]:      308108 :         assert(m_depths.size() == scripts.size());
    1174         [ +  + ]:      342436 :         for (size_t pos = 0; pos < m_depths.size(); ++pos) {
    1175   [ +  +  +  - ]:       68656 :             builder.Add(m_depths[pos], scripts[pos], TAPROOT_LEAF_TAPSCRIPT);
    1176                 :             :         }
    1177         [ -  + ]:      308108 :         if (!builder.IsComplete()) return {};
    1178         [ -  + ]:      308108 :         assert(keys.size() == 1);
    1179                 :      308108 :         XOnlyPubKey xpk(keys[0]);
    1180   [ +  -  -  + ]:      308108 :         if (!xpk.IsFullyValid()) return {};
    1181         [ +  - ]:      308108 :         builder.Finalize(xpk);
    1182         [ +  - ]:      308108 :         WitnessV1Taproot output = builder.GetOutput();
    1183   [ +  -  +  - ]:      308108 :         out.tr_trees[output] = builder;
    1184   [ +  -  +  - ]:      616216 :         return Vector(GetScriptForDestination(output));
    1185                 :      308108 :     }
    1186                 :      285187 :     bool ToStringSubScriptHelper(const SigningProvider* arg, std::string& ret, const StringType type, const DescriptorCache* cache = nullptr) const override
    1187                 :             :     {
    1188         [ +  + ]:      285187 :         if (m_depths.empty()) return true;
    1189                 :       16810 :         std::vector<bool> path;
    1190         [ +  + ]:       52310 :         for (size_t pos = 0; pos < m_depths.size(); ++pos) {
    1191   [ +  +  +  - ]:       38109 :             if (pos) ret += ',';
    1192         [ +  + ]:       77644 :             while ((int)path.size() <= m_depths[pos]) {
    1193   [ +  +  +  - ]:       39535 :                 if (path.size()) ret += '{';
    1194         [ +  - ]:       39535 :                 path.push_back(false);
    1195                 :             :             }
    1196         [ +  - ]:       38109 :             std::string tmp;
    1197   [ +  -  +  + ]:       38109 :             if (!m_subdescriptor_args[pos]->ToStringHelper(arg, tmp, type, cache)) return false;
    1198         [ +  - ]:       35500 :             ret += tmp;
    1199   [ +  -  +  + ]:       56618 :             while (!path.empty() && path.back()) {
    1200   [ +  -  +  - ]:       21118 :                 if (path.size() > 1) ret += '}';
    1201                 :       21118 :                 path.pop_back();
    1202                 :             :             }
    1203         [ +  - ]:       35500 :             if (!path.empty()) path.back() = true;
    1204                 :       38109 :         }
    1205                 :             :         return true;
    1206                 :       16810 :     }
    1207                 :             : public:
    1208                 :      413403 :     TRDescriptor(std::unique_ptr<PubkeyProvider> internal_key, std::vector<std::unique_ptr<DescriptorImpl>> descs, std::vector<int> depths) :
    1209   [ +  -  +  -  :      413403 :         DescriptorImpl(Vector(std::move(internal_key)), std::move(descs), "tr"), m_depths(std::move(depths))
                   -  + ]
    1210                 :             :     {
    1211         [ -  + ]:      413403 :         assert(m_subdescriptor_args.size() == m_depths.size());
    1212                 :      413403 :     }
    1213                 :      523914 :     std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32M; }
    1214                 :      238310 :     bool IsSingleType() const final { return true; }
    1215                 :           0 :     bool IsSingleKey() const final { return false; }
    1216                 :             : 
    1217                 :        5715 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
    1218                 :             : 
    1219                 :      399681 :     std::optional<int64_t> MaxSatisfactionWeight(bool) const override {
    1220                 :             :         // FIXME: We assume keypath spend, which can lead to very large underestimations.
    1221                 :      399681 :         return 1 + 65;
    1222                 :             :     }
    1223                 :             : 
    1224                 :      393584 :     std::optional<int64_t> MaxSatisfactionElems() const override {
    1225                 :             :         // FIXME: See above, we assume keypath spend.
    1226                 :      393584 :         return 1;
    1227                 :             :     }
    1228                 :             : 
    1229                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1230                 :             :     {
    1231                 :           0 :         std::vector<std::unique_ptr<DescriptorImpl>> subdescs;
    1232         [ #  # ]:           0 :         subdescs.reserve(m_subdescriptor_args.size());
    1233         [ #  # ]:           0 :         std::transform(m_subdescriptor_args.begin(), m_subdescriptor_args.end(), subdescs.begin(), [](const std::unique_ptr<DescriptorImpl>& d) { return d->Clone(); });
    1234   [ #  #  #  #  :           0 :         return std::make_unique<TRDescriptor>(m_pubkey_args.at(0)->Clone(), std::move(subdescs), m_depths);
             #  #  #  # ]
    1235                 :           0 :     }
    1236                 :             : };
    1237                 :             : 
    1238                 :             : /* We instantiate Miniscript here with a simple integer as key type.
    1239                 :             :  * The value of these key integers are an index in the
    1240                 :             :  * DescriptorImpl::m_pubkey_args vector.
    1241                 :             :  */
    1242                 :             : 
    1243                 :             : /**
    1244                 :             :  * The context for converting a Miniscript descriptor into a Script.
    1245                 :             :  */
    1246                 :             : class ScriptMaker {
    1247                 :             :     //! Keys contained in the Miniscript (the evaluation of DescriptorImpl::m_pubkey_args).
    1248                 :             :     const std::vector<CPubKey>& m_keys;
    1249                 :             :     //! The script context we're operating within (Tapscript or P2WSH).
    1250                 :             :     const miniscript::MiniscriptContext m_script_ctx;
    1251                 :             : 
    1252                 :             :     //! Get the ripemd160(sha256()) hash of this key.
    1253                 :             :     //! Any key that is valid in a descriptor serializes as 32 bytes within a Tapscript context. So we
    1254                 :             :     //! must not hash the sign-bit byte in this case.
    1255                 :        4611 :     uint160 GetHash160(uint32_t key) const {
    1256         [ +  + ]:        4611 :         if (miniscript::IsTapscript(m_script_ctx)) {
    1257                 :        3837 :             return Hash160(XOnlyPubKey{m_keys[key]});
    1258                 :             :         }
    1259                 :         774 :         return m_keys[key].GetID();
    1260                 :             :     }
    1261                 :             : 
    1262                 :             : public:
    1263                 :       34227 :     ScriptMaker(const std::vector<CPubKey>& keys LIFETIMEBOUND, const miniscript::MiniscriptContext script_ctx) : m_keys(keys), m_script_ctx{script_ctx} {}
    1264                 :             : 
    1265                 :       56953 :     std::vector<unsigned char> ToPKBytes(uint32_t key) const {
    1266                 :             :         // In Tapscript keys always serialize as x-only, whether an x-only key was used in the descriptor or not.
    1267         [ +  + ]:       56953 :         if (!miniscript::IsTapscript(m_script_ctx)) {
    1268                 :       29976 :             return {m_keys[key].begin(), m_keys[key].end()};
    1269                 :             :         }
    1270                 :       26977 :         const XOnlyPubKey xonly_pubkey{m_keys[key]};
    1271                 :       26977 :         return {xonly_pubkey.begin(), xonly_pubkey.end()};
    1272                 :             :     }
    1273                 :             : 
    1274                 :        4611 :     std::vector<unsigned char> ToPKHBytes(uint32_t key) const {
    1275                 :        4611 :         auto id = GetHash160(key);
    1276                 :        4611 :         return {id.begin(), id.end()};
    1277                 :             :     }
    1278                 :             : };
    1279                 :             : 
    1280                 :             : /**
    1281                 :             :  * The context for converting a Miniscript descriptor to its textual form.
    1282                 :             :  */
    1283                 :             : class StringMaker {
    1284                 :             :     //! To convert private keys for private descriptors.
    1285                 :             :     const SigningProvider* m_arg;
    1286                 :             :     //! Keys contained in the Miniscript (a reference to DescriptorImpl::m_pubkey_args).
    1287                 :             :     const std::vector<std::unique_ptr<PubkeyProvider>>& m_pubkeys;
    1288                 :             :     //! Whether to serialize keys as private or public.
    1289                 :             :     bool m_private;
    1290                 :             : 
    1291                 :             : public:
    1292                 :       40508 :     StringMaker(const SigningProvider* arg LIFETIMEBOUND, const std::vector<std::unique_ptr<PubkeyProvider>>& pubkeys LIFETIMEBOUND, bool priv)
    1293                 :       40508 :         : m_arg(arg), m_pubkeys(pubkeys), m_private(priv) {}
    1294                 :             : 
    1295                 :      105691 :     std::optional<std::string> ToString(uint32_t key) const
    1296                 :             :     {
    1297         [ +  + ]:      105691 :         std::string ret;
    1298         [ +  + ]:      105691 :         if (m_private) {
    1299   [ +  -  +  + ]:       11710 :             if (!m_pubkeys[key]->ToPrivateString(*m_arg, ret)) return {};
    1300                 :             :         } else {
    1301         [ +  - ]:       93981 :             ret = m_pubkeys[key]->ToString();
    1302                 :             :         }
    1303                 :      101563 :         return ret;
    1304                 :      105691 :     }
    1305                 :             : };
    1306                 :             : 
    1307                 :             : class MiniscriptDescriptor final : public DescriptorImpl
    1308                 :             : {
    1309                 :             : private:
    1310                 :             :     miniscript::NodeRef<uint32_t> m_node;
    1311                 :             : 
    1312                 :             : protected:
    1313                 :       34227 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript> scripts,
    1314                 :             :                                      FlatSigningProvider& provider) const override
    1315                 :             :     {
    1316                 :       34227 :         const auto script_ctx{m_node->GetMsCtx()};
    1317         [ +  + ]:       95791 :         for (const auto& key : keys) {
    1318         [ +  + ]:       61564 :             if (miniscript::IsTapscript(script_ctx)) {
    1319                 :       30814 :                 provider.pubkeys.emplace(Hash160(XOnlyPubKey{key}), key);
    1320                 :             :             } else {
    1321                 :       30750 :                 provider.pubkeys.emplace(key.GetID(), key);
    1322                 :             :             }
    1323                 :             :         }
    1324         [ +  - ]:       68454 :         return Vector(m_node->ToScript(ScriptMaker(keys, script_ctx)));
    1325                 :             :     }
    1326                 :             : 
    1327                 :             : public:
    1328                 :       32839 :     MiniscriptDescriptor(std::vector<std::unique_ptr<PubkeyProvider>> providers, miniscript::NodeRef<uint32_t> node)
    1329         [ +  - ]:       32839 :         : DescriptorImpl(std::move(providers), "?"), m_node(std::move(node)) {}
    1330                 :             : 
    1331                 :       40508 :     bool ToStringHelper(const SigningProvider* arg, std::string& out, const StringType type,
    1332                 :             :                         const DescriptorCache* cache = nullptr) const override
    1333                 :             :     {
    1334         [ +  + ]:       40508 :         if (const auto res = m_node->ToString(StringMaker(arg, m_pubkey_args, type == StringType::PRIVATE))) {
    1335         [ +  - ]:       36380 :             out = *res;
    1336                 :       36380 :             return true;
    1337                 :       36380 :         }
    1338                 :        4128 :         return false;
    1339                 :             :     }
    1340                 :             : 
    1341                 :       14639 :     bool IsSolvable() const override { return true; }
    1342                 :           0 :     bool IsSingleType() const final { return true; }
    1343                 :           0 :     bool IsSingleKey() const final { return false; }
    1344                 :             : 
    1345                 :        7536 :     std::optional<int64_t> ScriptSize() const override { return m_node->ScriptSize(); }
    1346                 :             : 
    1347                 :        7536 :     std::optional<int64_t> MaxSatSize(bool) const override {
    1348                 :             :         // For Miniscript we always assume high-R ECDSA signatures.
    1349         [ +  - ]:        7536 :         return m_node->GetWitnessSize();
    1350                 :             :     }
    1351                 :             : 
    1352                 :        3768 :     std::optional<int64_t> MaxSatisfactionElems() const override {
    1353         [ +  - ]:        3768 :         return m_node->GetStackSize();
    1354                 :             :     }
    1355                 :             : 
    1356                 :        7455 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1357                 :             :     {
    1358                 :        7455 :         std::vector<std::unique_ptr<PubkeyProvider>> providers;
    1359         [ +  - ]:        7455 :         providers.reserve(m_pubkey_args.size());
    1360         [ +  + ]:       15031 :         for (const auto& arg : m_pubkey_args) {
    1361         [ +  - ]:       15152 :             providers.push_back(arg->Clone());
    1362                 :             :         }
    1363   [ +  -  +  -  :       14910 :         return std::make_unique<MiniscriptDescriptor>(std::move(providers), m_node->Clone());
                   -  + ]
    1364                 :        7455 :     }
    1365                 :             : };
    1366                 :             : 
    1367                 :             : /** A parsed rawtr(...) descriptor. */
    1368                 :             : class RawTRDescriptor final : public DescriptorImpl
    1369                 :             : {
    1370                 :             : protected:
    1371                 :         525 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript> scripts, FlatSigningProvider& out) const override
    1372                 :             :     {
    1373         [ -  + ]:         525 :         assert(keys.size() == 1);
    1374                 :         525 :         XOnlyPubKey xpk(keys[0]);
    1375         [ -  + ]:         525 :         if (!xpk.IsFullyValid()) return {};
    1376         [ +  - ]:         525 :         WitnessV1Taproot output{xpk};
    1377   [ +  -  +  - ]:        1050 :         return Vector(GetScriptForDestination(output));
    1378                 :             :     }
    1379                 :             : public:
    1380   [ +  -  +  - ]:        7436 :     RawTRDescriptor(std::unique_ptr<PubkeyProvider> output_key) : DescriptorImpl(Vector(std::move(output_key)), "rawtr") {}
    1381                 :         486 :     std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32M; }
    1382                 :         589 :     bool IsSingleType() const final { return true; }
    1383                 :           0 :     bool IsSingleKey() const final { return false; }
    1384                 :             : 
    1385                 :         148 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
    1386                 :             : 
    1387                 :         316 :     std::optional<int64_t> MaxSatisfactionWeight(bool) const override {
    1388                 :             :         // We can't know whether there is a script path, so assume key path spend.
    1389                 :         316 :         return 1 + 65;
    1390                 :             :     }
    1391                 :             : 
    1392                 :         158 :     std::optional<int64_t> MaxSatisfactionElems() const override {
    1393                 :             :         // See above, we assume keypath spend.
    1394                 :         158 :         return 1;
    1395                 :             :     }
    1396                 :             : 
    1397                 :           0 :     std::unique_ptr<DescriptorImpl> Clone() const override
    1398                 :             :     {
    1399   [ #  #  #  # ]:           0 :         return std::make_unique<RawTRDescriptor>(m_pubkey_args.at(0)->Clone());
    1400                 :             :     }
    1401                 :             : };
    1402                 :             : 
    1403                 :             : ////////////////////////////////////////////////////////////////////////////
    1404                 :             : // Parser                                                                 //
    1405                 :             : ////////////////////////////////////////////////////////////////////////////
    1406                 :             : 
    1407                 :             : enum class ParseScriptContext {
    1408                 :             :     TOP,     //!< Top-level context (script goes directly in scriptPubKey)
    1409                 :             :     P2SH,    //!< Inside sh() (script becomes P2SH redeemScript)
    1410                 :             :     P2WPKH,  //!< Inside wpkh() (no script, pubkey only)
    1411                 :             :     P2WSH,   //!< Inside wsh() (script becomes v0 witness script)
    1412                 :             :     P2TR,    //!< Inside tr() (either internal key, or BIP342 script leaf)
    1413                 :             : };
    1414                 :             : 
    1415                 :      211292 : std::optional<uint32_t> ParseKeyPathNum(std::span<const char> elem, bool& apostrophe, std::string& error)
    1416                 :             : {
    1417                 :      211292 :     bool hardened = false;
    1418         [ +  + ]:      211292 :     if (elem.size() > 0) {
    1419         [ +  + ]:      211286 :         const char last = elem[elem.size() - 1];
    1420         [ +  + ]:      211286 :         if (last == '\'' || last == 'h') {
    1421                 :       86493 :             elem = elem.first(elem.size() - 1);
    1422                 :       86493 :             hardened = true;
    1423                 :       86493 :             apostrophe = last == '\'';
    1424                 :             :         }
    1425                 :             :     }
    1426                 :      211292 :     const auto p{ToIntegral<uint32_t>(std::string_view{elem.begin(), elem.end()})};
    1427         [ +  + ]:      211292 :     if (!p) {
    1428                 :         463 :         error = strprintf("Key path value '%s' is not a valid uint32", std::string_view{elem.begin(), elem.end()});
    1429                 :         463 :         return std::nullopt;
    1430         [ +  + ]:      210829 :     } else if (*p > 0x7FFFFFFFUL) {
    1431                 :           6 :         error = strprintf("Key path value %u is out of range", *p);
    1432                 :           6 :         return std::nullopt;
    1433                 :             :     }
    1434                 :             : 
    1435                 :      210823 :     return std::make_optional<uint32_t>(*p | (((uint32_t)hardened) << 31));
    1436                 :             : }
    1437                 :             : 
    1438                 :             : /**
    1439                 :             :  * Parse a key path, being passed a split list of elements (the first element is ignored because it is always the key).
    1440                 :             :  *
    1441                 :             :  * @param[in] split BIP32 path string, using either ' or h for hardened derivation
    1442                 :             :  * @param[out] out Vector of parsed key paths
    1443                 :             :  * @param[out] apostrophe only updated if hardened derivation is found
    1444                 :             :  * @param[out] error parsing error message
    1445                 :             :  * @param[in] allow_multipath Allows the parsed path to use the multipath specifier
    1446                 :             :  * @returns false if parsing failed
    1447                 :             :  **/
    1448                 :      159737 : [[nodiscard]] bool ParseKeyPath(const std::vector<std::span<const char>>& split, std::vector<KeyPath>& out, bool& apostrophe, std::string& error, bool allow_multipath)
    1449                 :             : {
    1450                 :      159737 :     KeyPath path;
    1451                 :        2234 :     struct MultipathSubstitutes {
    1452                 :             :         size_t placeholder_index;
    1453                 :             :         std::vector<uint32_t> values;
    1454                 :             :     };
    1455                 :      159737 :     std::optional<MultipathSubstitutes> substitutes;
    1456                 :             : 
    1457         [ +  + ]:      351016 :     for (size_t i = 1; i < split.size(); ++i) {
    1458         [ +  + ]:      191796 :         const std::span<const char>& elem = split[i];
    1459                 :             : 
    1460                 :             :         // Check if element contains multipath specifier
    1461   [ +  +  +  +  :      191796 :         if (!elem.empty() && elem.front() == '<' && elem.back() == '>') {
                   +  + ]
    1462         [ +  + ]:        2277 :             if (!allow_multipath) {
    1463   [ +  -  +  - ]:          74 :                 error = strprintf("Key path value '%s' specifies multipath in a section where multipath is not allowed", std::string(elem.begin(), elem.end()));
    1464                 :          37 :                 return false;
    1465                 :             :             }
    1466         [ +  + ]:        2240 :             if (substitutes) {
    1467         [ +  - ]:      159737 :                 error = "Multiple multipath key path specifiers found";
    1468                 :             :                 return false;
    1469                 :             :             }
    1470                 :             : 
    1471                 :             :             // Parse each possible value
    1472         [ +  - ]:        2238 :             std::vector<std::span<const char>> nums = Split(std::span(elem.begin()+1, elem.end()-1), ";");
    1473         [ +  + ]:        2238 :             if (nums.size() < 2) {
    1474         [ +  - ]:         287 :                 error = "Multipath key path specifiers must have at least two items";
    1475                 :             :                 return false;
    1476                 :             :             }
    1477                 :             : 
    1478                 :        2234 :             substitutes.emplace();
    1479                 :        2234 :             std::unordered_set<uint32_t> seen_substitutes;
    1480         [ +  + ]:       23724 :             for (const auto& num : nums) {
    1481         [ +  - ]:       21773 :                 const auto& op_num = ParseKeyPathNum(num, apostrophe, error);
    1482         [ +  + ]:       21773 :                 if (!op_num) return false;
    1483   [ +  -  +  + ]:       21495 :                 auto [_, inserted] = seen_substitutes.insert(*op_num);
    1484         [ +  + ]:       21495 :                 if (!inserted) {
    1485         [ +  - ]:           5 :                     error = strprintf("Duplicated key path value %u in multipath specifier", *op_num);
    1486                 :           5 :                     return false;
    1487                 :             :                 }
    1488         [ +  - ]:       21490 :                 substitutes->values.emplace_back(*op_num);
    1489                 :             :             }
    1490                 :             : 
    1491         [ +  - ]:        1951 :             path.emplace_back(); // Placeholder for multipath segment
    1492                 :        1951 :             substitutes->placeholder_index = path.size() - 1;
    1493                 :        2521 :         } else {
    1494         [ +  - ]:      189519 :             const auto& op_num = ParseKeyPathNum(elem, apostrophe, error);
    1495         [ +  + ]:      189519 :             if (!op_num) return false;
    1496         [ +  - ]:      189328 :             path.emplace_back(*op_num);
    1497                 :             :         }
    1498                 :             :     }
    1499                 :             : 
    1500         [ +  + ]:      159220 :     if (!substitutes) {
    1501         [ +  - ]:      157271 :         out.emplace_back(std::move(path));
    1502                 :             :     } else {
    1503                 :             :         // Replace the multipath placeholder with each value while generating paths
    1504         [ +  + ]:       22346 :         for (uint32_t substitute : substitutes->values) {
    1505         [ +  - ]:       20397 :             KeyPath branch_path = path;
    1506         [ +  - ]:       20397 :             branch_path[substitutes->placeholder_index] = substitute;
    1507         [ +  - ]:       20397 :             out.emplace_back(std::move(branch_path));
    1508                 :       20397 :         }
    1509                 :             :     }
    1510                 :             :     return true;
    1511                 :      159737 : }
    1512                 :             : 
    1513                 :             : /** Parse a public key that excludes origin information. */
    1514                 :      190084 : 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)
    1515                 :             : {
    1516                 :      190084 :     std::vector<std::unique_ptr<PubkeyProvider>> ret;
    1517                 :      190084 :     bool permit_uncompressed = ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH;
    1518         [ +  - ]:      190084 :     auto split = Split(sp, '/');
    1519   [ +  -  +  + ]:      380168 :     std::string str(split[0].begin(), split[0].end());
    1520         [ +  + ]:      190084 :     if (str.size() == 0) {
    1521         [ +  - ]:          39 :         error = "No key provided";
    1522                 :          39 :         return {};
    1523                 :             :     }
    1524   [ +  +  +  + ]:      190045 :     if (IsSpace(str.front()) || IsSpace(str.back())) {
    1525         [ +  - ]:          11 :         error = strprintf("Key '%s' is invalid due to whitespace", str);
    1526                 :          11 :         return {};
    1527                 :             :     }
    1528         [ +  + ]:      190034 :     if (split.size() == 1) {
    1529   [ +  -  +  + ]:      105909 :         if (IsHex(str)) {
    1530         [ +  - ]:       35122 :             std::vector<unsigned char> data = ParseHex(str);
    1531                 :       35122 :             CPubKey pubkey(data);
    1532   [ +  +  +  + ]:       35122 :             if (pubkey.IsValid() && !pubkey.IsValidNonHybrid()) {
    1533         [ +  - ]:          10 :                 error = "Hybrid public keys are not allowed";
    1534                 :          10 :                 return {};
    1535                 :             :             }
    1536   [ +  -  +  + ]:       35112 :             if (pubkey.IsFullyValid()) {
    1537   [ +  +  +  + ]:       19617 :                 if (permit_uncompressed || pubkey.IsCompressed()) {
    1538   [ +  -  +  - ]:       19614 :                     ret.emplace_back(std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, false));
    1539                 :       19614 :                     return ret;
    1540                 :             :                 } else {
    1541         [ +  - ]:           3 :                     error = "Uncompressed keys are not allowed";
    1542                 :           3 :                     return {};
    1543                 :             :                 }
    1544   [ +  +  +  + ]:       15495 :             } else if (data.size() == 32 && ctx == ParseScriptContext::P2TR) {
    1545                 :       15430 :                 unsigned char fullkey[33] = {0x02};
    1546                 :       15430 :                 std::copy(data.begin(), data.end(), fullkey + 1);
    1547                 :       15430 :                 pubkey.Set(std::begin(fullkey), std::end(fullkey));
    1548   [ +  -  +  + ]:       15430 :                 if (pubkey.IsFullyValid()) {
    1549   [ +  -  +  - ]:       15420 :                     ret.emplace_back(std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, true));
    1550                 :       15420 :                     return ret;
    1551                 :             :                 }
    1552                 :             :             }
    1553         [ +  - ]:          75 :             error = strprintf("Pubkey '%s' is invalid", str);
    1554                 :          75 :             return {};
    1555                 :       35122 :         }
    1556         [ +  - ]:       70787 :         CKey key = DecodeSecret(str);
    1557         [ +  + ]:       70787 :         if (key.IsValid()) {
    1558   [ +  +  -  + ]:       43416 :             if (permit_uncompressed || key.IsCompressed()) {
    1559         [ +  - ]:       43416 :                 CPubKey pubkey = key.GetPubKey();
    1560   [ +  -  +  - ]:       43416 :                 out.keys.emplace(pubkey.GetID(), key);
    1561   [ +  -  +  - ]:       43416 :                 ret.emplace_back(std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, ctx == ParseScriptContext::P2TR));
    1562                 :       43416 :                 return ret;
    1563                 :             :             } else {
    1564         [ #  # ]:           0 :                 error = "Uncompressed keys are not allowed";
    1565                 :           0 :                 return {};
    1566                 :             :             }
    1567                 :             :         }
    1568                 :       70787 :     }
    1569         [ +  - ]:      111496 :     CExtKey extkey = DecodeExtKey(str);
    1570         [ +  - ]:      111496 :     CExtPubKey extpubkey = DecodeExtPubKey(str);
    1571   [ +  +  +  + ]:      111496 :     if (!extkey.key.IsValid() && !extpubkey.pubkey.IsValid()) {
    1572         [ +  - ]:         209 :         error = strprintf("key '%s' is not valid", str);
    1573                 :         209 :         return {};
    1574                 :             :     }
    1575                 :      111287 :     std::vector<KeyPath> paths;
    1576                 :      111287 :     DeriveType type = DeriveType::NO;
    1577         [ +  + ]:      111287 :     if (std::ranges::equal(split.back(), std::span{"*"}.first(1))) {
    1578                 :       26924 :         split.pop_back();
    1579                 :       26924 :         type = DeriveType::UNHARDENED;
    1580   [ +  +  +  + ]:       84363 :     } else if (std::ranges::equal(split.back(), std::span{"*'"}.first(2)) || std::ranges::equal(split.back(), std::span{"*h"}.first(2))) {
    1581                 :        5895 :         apostrophe = std::ranges::equal(split.back(), std::span{"*'"}.first(2));
    1582                 :        5895 :         split.pop_back();
    1583                 :        5895 :         type = DeriveType::HARDENED;
    1584                 :             :     }
    1585   [ +  -  +  + ]:      111287 :     if (!ParseKeyPath(split, paths, apostrophe, error, /*allow_multipath=*/true)) return {};
    1586         [ +  + ]:      110859 :     if (extkey.key.IsValid()) {
    1587         [ +  - ]:       99645 :         extpubkey = extkey.Neuter();
    1588   [ +  -  +  - ]:       99645 :         out.keys.emplace(extpubkey.pubkey.GetID(), extkey.key);
    1589                 :             :     }
    1590         [ +  + ]:      240166 :     for (auto& path : paths) {
    1591   [ +  -  +  - ]:      258614 :         ret.emplace_back(std::make_unique<BIP32PubkeyProvider>(key_exp_index, extpubkey, std::move(path), type, apostrophe));
    1592                 :             :     }
    1593                 :      110859 :     return ret;
    1594                 :      412867 : }
    1595                 :             : 
    1596                 :             : /** Parse a public key including origin information (if enabled). */
    1597                 :      190207 : 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)
    1598                 :             : {
    1599                 :      190207 :     std::vector<std::unique_ptr<PubkeyProvider>> ret;
    1600         [ +  - ]:      190207 :     auto origin_split = Split(sp, ']');
    1601         [ +  + ]:      190207 :     if (origin_split.size() > 2) {
    1602         [ +  - ]:           8 :         error = "Multiple ']' characters found for a single pubkey";
    1603                 :           8 :         return {};
    1604                 :             :     }
    1605                 :             :     // This is set if either the origin or path suffix contains a hardened derivation.
    1606                 :      190199 :     bool apostrophe = false;
    1607         [ +  + ]:      190199 :     if (origin_split.size() == 1) {
    1608         [ +  - ]:      141723 :         return ParsePubkeyInner(key_exp_index, origin_split[0], ctx, out, apostrophe, error);
    1609                 :             :     }
    1610   [ +  +  +  + ]:       48476 :     if (origin_split[0].empty() || origin_split[0][0] != '[') {
    1611                 :          36 :         error = strprintf("Key origin start '[ character expected but not found, got '%c' instead",
    1612   [ +  +  +  - ]:          12 :                           origin_split[0].empty() ? /** empty, implies split char */ ']' : origin_split[0][0]);
    1613                 :          12 :         return {};
    1614                 :             :     }
    1615         [ +  - ]:       48464 :     auto slash_split = Split(origin_split[0].subspan(1), '/');
    1616         [ +  + ]:       48464 :     if (slash_split[0].size() != 8) {
    1617         [ +  - ]:           8 :         error = strprintf("Fingerprint is not 4 bytes (%u characters instead of 8 characters)", slash_split[0].size());
    1618                 :           8 :         return {};
    1619                 :             :     }
    1620   [ +  -  +  - ]:       96912 :     std::string fpr_hex = std::string(slash_split[0].begin(), slash_split[0].end());
    1621   [ +  -  +  + ]:       48456 :     if (!IsHex(fpr_hex)) {
    1622         [ +  - ]:           6 :         error = strprintf("Fingerprint '%s' is not hex", fpr_hex);
    1623                 :           6 :         return {};
    1624                 :             :     }
    1625         [ +  - ]:       48450 :     auto fpr_bytes = ParseHex(fpr_hex);
    1626         [ -  + ]:       48450 :     KeyOriginInfo info;
    1627                 :       48450 :     static_assert(sizeof(info.fingerprint) == 4, "Fingerprint must be 4 bytes");
    1628         [ -  + ]:       48450 :     assert(fpr_bytes.size() == 4);
    1629                 :       48450 :     std::copy(fpr_bytes.begin(), fpr_bytes.end(), info.fingerprint);
    1630                 :       48450 :     std::vector<KeyPath> path;
    1631   [ +  -  +  + ]:       48450 :     if (!ParseKeyPath(slash_split, path, apostrophe, error, /*allow_multipath=*/false)) return {};
    1632   [ +  -  +  - ]:       48361 :     info.path = path.at(0);
    1633         [ +  - ]:       48361 :     auto providers = ParsePubkeyInner(key_exp_index, origin_split[1], ctx, out, apostrophe, error);
    1634         [ +  + ]:       48361 :     if (providers.empty()) return {};
    1635         [ +  - ]:       48316 :     ret.reserve(providers.size());
    1636         [ +  + ]:       96764 :     for (auto& prov : providers) {
    1637   [ +  -  +  - ]:       96896 :         ret.emplace_back(std::make_unique<OriginPubkeyProvider>(key_exp_index, info, std::move(prov), apostrophe));
    1638                 :             :     }
    1639                 :       48316 :     return ret;
    1640                 :      335577 : }
    1641                 :             : 
    1642                 :     3456670 : std::unique_ptr<PubkeyProvider> InferPubkey(const CPubKey& pubkey, ParseScriptContext ctx, const SigningProvider& provider)
    1643                 :             : {
    1644                 :             :     // Key cannot be hybrid
    1645         [ +  + ]:     3456670 :     if (!pubkey.IsValidNonHybrid()) {
    1646                 :        3464 :         return nullptr;
    1647                 :             :     }
    1648                 :             :     // Uncompressed is only allowed in TOP and P2SH contexts
    1649   [ +  +  -  + ]:     3453206 :     if (ctx != ParseScriptContext::TOP && ctx != ParseScriptContext::P2SH && !pubkey.IsCompressed()) {
    1650                 :           0 :         return nullptr;
    1651                 :             :     }
    1652                 :     3453206 :     std::unique_ptr<PubkeyProvider> key_provider = std::make_unique<ConstPubkeyProvider>(0, pubkey, false);
    1653         [ +  - ]:     3453206 :     KeyOriginInfo info;
    1654   [ +  -  +  -  :     3453206 :     if (provider.GetKeyOrigin(pubkey.GetID(), info)) {
                   +  + ]
    1655   [ +  -  -  + ]:     3328471 :         return std::make_unique<OriginPubkeyProvider>(0, std::move(info), std::move(key_provider), /*apostrophe=*/false);
    1656                 :             :     }
    1657                 :      124735 :     return key_provider;
    1658                 :     3453206 : }
    1659                 :             : 
    1660                 :      642383 : std::unique_ptr<PubkeyProvider> InferXOnlyPubkey(const XOnlyPubKey& xkey, ParseScriptContext ctx, const SigningProvider& provider)
    1661                 :             : {
    1662                 :      642383 :     CPubKey pubkey{xkey.GetEvenCorrespondingCPubKey()};
    1663                 :      642383 :     std::unique_ptr<PubkeyProvider> key_provider = std::make_unique<ConstPubkeyProvider>(0, pubkey, true);
    1664         [ +  - ]:      642383 :     KeyOriginInfo info;
    1665   [ +  -  +  + ]:      642383 :     if (provider.GetKeyOriginByXOnly(xkey, info)) {
    1666   [ +  -  -  + ]:      635390 :         return std::make_unique<OriginPubkeyProvider>(0, std::move(info), std::move(key_provider), /*apostrophe=*/false);
    1667                 :             :     }
    1668                 :        6993 :     return key_provider;
    1669                 :      642383 : }
    1670                 :             : 
    1671                 :             : /**
    1672                 :             :  * The context for parsing a Miniscript descriptor (either from Script or from its textual representation).
    1673                 :             :  */
    1674                 :       23506 : struct KeyParser {
    1675                 :             :     //! The Key type is an index in DescriptorImpl::m_pubkey_args
    1676                 :             :     using Key = uint32_t;
    1677                 :             :     //! Must not be nullptr if parsing from string.
    1678                 :             :     FlatSigningProvider* m_out;
    1679                 :             :     //! Must not be nullptr if parsing from Script.
    1680                 :             :     const SigningProvider* m_in;
    1681                 :             :     //! List of multipath expanded keys contained in the Miniscript.
    1682                 :             :     mutable std::vector<std::vector<std::unique_ptr<PubkeyProvider>>> m_keys;
    1683                 :             :     //! Used to detect key parsing errors within a Miniscript.
    1684                 :             :     mutable std::string m_key_parsing_error;
    1685                 :             :     //! The script context we're operating within (Tapscript or P2WSH).
    1686                 :             :     const miniscript::MiniscriptContext m_script_ctx;
    1687                 :             :     //! The number of keys that were parsed before starting to parse this Miniscript descriptor.
    1688                 :             :     uint32_t m_offset;
    1689                 :             : 
    1690                 :       23506 :     KeyParser(FlatSigningProvider* out LIFETIMEBOUND, const SigningProvider* in LIFETIMEBOUND,
    1691                 :             :               miniscript::MiniscriptContext ctx, uint32_t offset = 0)
    1692                 :       23506 :         : m_out(out), m_in(in), m_script_ctx(ctx), m_offset(offset) {}
    1693                 :             : 
    1694                 :      142402 :     bool KeyCompare(const Key& a, const Key& b) const {
    1695                 :      142402 :         return *m_keys.at(a).at(0) < *m_keys.at(b).at(0);
    1696                 :             :     }
    1697                 :             : 
    1698                 :       59367 :     ParseScriptContext ParseContext() const {
    1699      [ +  -  + ]:       59367 :         switch (m_script_ctx) {
    1700                 :             :             case miniscript::MiniscriptContext::P2WSH: return ParseScriptContext::P2WSH;
    1701                 :       32349 :             case miniscript::MiniscriptContext::TAPSCRIPT: return ParseScriptContext::P2TR;
    1702                 :             :         }
    1703                 :           0 :         assert(false);
    1704                 :             :     }
    1705                 :             : 
    1706                 :       34807 :     template<typename I> std::optional<Key> FromString(I begin, I end) const
    1707                 :             :     {
    1708         [ -  + ]:       34807 :         assert(m_out);
    1709                 :       34807 :         Key key = m_keys.size();
    1710                 :       34807 :         auto pk = ParsePubkey(m_offset + key, {&*begin, &*end}, ParseContext(), *m_out, m_key_parsing_error);
    1711         [ +  + ]:       34807 :         if (pk.empty()) return {};
    1712         [ +  - ]:       34514 :         m_keys.emplace_back(std::move(pk));
    1713                 :       34514 :         return key;
    1714                 :       34807 :     }
    1715                 :             : 
    1716                 :       10654 :     std::optional<std::string> ToString(const Key& key) const
    1717                 :             :     {
    1718                 :       10654 :         return m_keys.at(key).at(0)->ToString();
    1719                 :             :     }
    1720                 :             : 
    1721                 :       23380 :     template<typename I> std::optional<Key> FromPKBytes(I begin, I end) const
    1722                 :             :     {
    1723         [ -  + ]:       23380 :         assert(m_in);
    1724                 :       23380 :         Key key = m_keys.size();
    1725   [ +  +  +  - ]:       23380 :         if (miniscript::IsTapscript(m_script_ctx) && end - begin == 32) {
    1726                 :       12415 :             XOnlyPubKey pubkey;
    1727                 :       12415 :             std::copy(begin, end, pubkey.begin());
    1728         [ +  - ]:       12415 :             if (auto pubkey_provider = InferXOnlyPubkey(pubkey, ParseContext(), *m_in)) {
    1729         [ +  - ]:       12415 :                 m_keys.emplace_back();
    1730         [ +  - ]:       12415 :                 m_keys.back().push_back(std::move(pubkey_provider));
    1731                 :       12415 :                 return key;
    1732                 :             :             }
    1733         [ +  - ]:       10965 :         } else if (!miniscript::IsTapscript(m_script_ctx)) {
    1734                 :       10965 :             CPubKey pubkey(begin, end);
    1735         [ +  + ]:       10965 :             if (auto pubkey_provider = InferPubkey(pubkey, ParseContext(), *m_in)) {
    1736         [ +  - ]:       10957 :                 m_keys.emplace_back();
    1737         [ +  - ]:       10957 :                 m_keys.back().push_back(std::move(pubkey_provider));
    1738                 :       10957 :                 return key;
    1739                 :             :             }
    1740                 :             :         }
    1741                 :           8 :         return {};
    1742                 :             :     }
    1743                 :             : 
    1744         [ -  + ]:        1181 :     template<typename I> std::optional<Key> FromPKHBytes(I begin, I end) const
    1745                 :             :     {
    1746         [ -  + ]:        1181 :         assert(end - begin == 20);
    1747         [ -  + ]:        1181 :         assert(m_in);
    1748                 :        1181 :         uint160 hash;
    1749                 :        1181 :         std::copy(begin, end, hash.begin());
    1750                 :        1181 :         CKeyID keyid(hash);
    1751                 :        1181 :         CPubKey pubkey;
    1752         [ +  + ]:        1181 :         if (m_in->GetPubKey(keyid, pubkey)) {
    1753         [ +  - ]:        1180 :             if (auto pubkey_provider = InferPubkey(pubkey, ParseContext(), *m_in)) {
    1754         [ +  - ]:        1180 :                 Key key = m_keys.size();
    1755         [ +  - ]:        1180 :                 m_keys.emplace_back();
    1756         [ +  - ]:        1180 :                 m_keys.back().push_back(std::move(pubkey_provider));
    1757                 :        1180 :                 return key;
    1758                 :             :             }
    1759                 :             :         }
    1760                 :           1 :         return {};
    1761                 :             :     }
    1762                 :             : 
    1763                 :     3777293 :     miniscript::MiniscriptContext MsContext() const {
    1764   [ +  -  +  -  :     3777293 :         return m_script_ctx;
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  +  +  
                -  +  - ]
    1765                 :             :     }
    1766                 :             : };
    1767                 :             : 
    1768                 :             : /** Parse a script in a particular context. */
    1769                 :             : // NOLINTNEXTLINE(misc-no-recursion)
    1770                 :       55554 : std::vector<std::unique_ptr<DescriptorImpl>> ParseScript(uint32_t& key_exp_index, std::span<const char>& sp, ParseScriptContext ctx, FlatSigningProvider& out, std::string& error)
    1771                 :             : {
    1772                 :       55554 :     using namespace script;
    1773      [ +  +  - ]:      111108 :     Assume(ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH || ctx == ParseScriptContext::P2TR);
    1774                 :       55554 :     std::vector<std::unique_ptr<DescriptorImpl>> ret;
    1775         [ +  - ]:       55554 :     auto expr = Expr(sp);
    1776   [ +  -  +  -  :       55554 :     if (Func("pk", expr)) {
                   +  + ]
    1777         [ +  - ]:        5227 :         auto pubkeys = ParsePubkey(key_exp_index, expr, ctx, out, error);
    1778         [ +  + ]:        5227 :         if (pubkeys.empty()) {
    1779         [ +  - ]:         162 :             error = strprintf("pk(): %s", error);
    1780                 :         162 :             return {};
    1781                 :             :         }
    1782                 :        5065 :         ++key_exp_index;
    1783         [ +  + ]:       10837 :         for (auto& pubkey : pubkeys) {
    1784   [ +  -  +  - ]:       11544 :             ret.emplace_back(std::make_unique<PKDescriptor>(std::move(pubkey), ctx == ParseScriptContext::P2TR));
    1785                 :             :         }
    1786                 :        5065 :         return ret;
    1787                 :        5227 :     }
    1788   [ +  +  +  -  :       95327 :     if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH) && Func("pkh", expr)) {
          +  -  +  +  +  
                      + ]
    1789         [ +  - ]:        6484 :         auto pubkeys = ParsePubkey(key_exp_index, expr, ctx, out, error);
    1790         [ +  + ]:        6484 :         if (pubkeys.empty()) {
    1791         [ +  - ]:          22 :             error = strprintf("pkh(): %s", error);
    1792                 :          22 :             return {};
    1793                 :             :         }
    1794                 :        6462 :         ++key_exp_index;
    1795         [ +  + ]:       13342 :         for (auto& pubkey : pubkeys) {
    1796   [ +  -  +  - ]:       13760 :             ret.emplace_back(std::make_unique<PKHDescriptor>(std::move(pubkey)));
    1797                 :             :         }
    1798                 :        6462 :         return ret;
    1799                 :        6484 :     }
    1800   [ +  +  +  -  :       72524 :     if (ctx == ParseScriptContext::TOP && Func("combo", expr)) {
          +  -  +  +  +  
                      + ]
    1801         [ +  - ]:         384 :         auto pubkeys = ParsePubkey(key_exp_index, expr, ctx, out, error);
    1802         [ +  + ]:         384 :         if (pubkeys.empty()) {
    1803         [ +  - ]:          19 :             error = strprintf("combo(): %s", error);
    1804                 :          19 :             return {};
    1805                 :             :         }
    1806                 :         365 :         ++key_exp_index;
    1807         [ +  + ]:        1291 :         for (auto& pubkey : pubkeys) {
    1808   [ +  -  +  - ]:        1852 :             ret.emplace_back(std::make_unique<ComboDescriptor>(std::move(pubkey)));
    1809                 :             :         }
    1810                 :         365 :         return ret;
    1811   [ +  -  +  -  :       43843 :     } else if (Func("combo", expr)) {
                   +  + ]
    1812         [ +  - ]:           5 :         error = "Can only have combo() at top level";
    1813                 :           5 :         return {};
    1814                 :             :     }
    1815   [ +  -  +  - ]:       43454 :     const bool multi = Func("multi", expr);
    1816   [ +  +  +  -  :       86247 :     const bool sortedmulti = !multi && Func("sortedmulti", expr);
             +  -  +  + ]
    1817   [ +  +  +  -  :       85820 :     const bool multi_a = !(multi || sortedmulti) && Func("multi_a", expr);
             +  -  +  + ]
    1818   [ +  +  +  +  :       84973 :     const bool sortedmulti_a = !(multi || sortedmulti || multi_a) && Func("sortedmulti_a", expr);
          +  -  +  -  +  
                      + ]
    1819   [ +  +  +  +  :       43454 :     if (((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH) && (multi || sortedmulti)) ||
             +  +  +  + ]
    1820   [ +  +  +  + ]:        5327 :         (ctx == ParseScriptContext::P2TR && (multi_a || sortedmulti_a))) {
    1821         [ +  - ]:        2374 :         auto threshold = Expr(expr);
    1822                 :        2374 :         uint32_t thres;
    1823                 :        2374 :         std::vector<std::vector<std::unique_ptr<PubkeyProvider>>> providers; // List of multipath expanded pubkeys
    1824         [ +  + ]:        2374 :         if (const auto maybe_thres{ToIntegral<uint32_t>(std::string_view{threshold.begin(), threshold.end()})}) {
    1825                 :        2280 :             thres = *maybe_thres;
    1826                 :             :         } else {
    1827   [ +  -  +  - ]:         188 :             error = strprintf("Multi threshold '%s' is not valid", std::string(threshold.begin(), threshold.end()));
    1828                 :          94 :             return {};
    1829                 :             :         }
    1830                 :        2280 :         size_t script_size = 0;
    1831                 :        2280 :         size_t max_providers_len = 0;
    1832         [ +  + ]:      124722 :         while (expr.size()) {
    1833   [ +  -  +  -  :      122696 :             if (!Const(",", expr)) {
                   +  + ]
    1834         [ +  - ]:           4 :                 error = strprintf("Multi: expected ',', got '%c'", expr[0]);
    1835                 :           4 :                 return {};
    1836                 :             :             }
    1837         [ +  - ]:      122692 :             auto arg = Expr(expr);
    1838         [ +  - ]:      122692 :             auto pks = ParsePubkey(key_exp_index, arg, ctx, out, error);
    1839         [ +  + ]:      122692 :             if (pks.empty()) {
    1840         [ +  - ]:         250 :                 error = strprintf("Multi: %s", error);
    1841                 :         250 :                 return {};
    1842                 :             :             }
    1843   [ +  -  +  - ]:      122442 :             script_size += pks.at(0)->GetSize() + 1;
    1844         [ +  + ]:      122442 :             max_providers_len = std::max(max_providers_len, pks.size());
    1845         [ +  - ]:      122442 :             providers.emplace_back(std::move(pks));
    1846                 :      122442 :             key_exp_index++;
    1847                 :      122692 :         }
    1848   [ +  +  +  +  :        2026 :         if ((multi || sortedmulti) && (providers.empty() || providers.size() > MAX_PUBKEYS_PER_MULTISIG)) {
             +  +  +  + ]
    1849         [ +  - ]:          18 :             error = strprintf("Cannot have %u keys in multisig; must have between 1 and %d keys, inclusive", providers.size(), MAX_PUBKEYS_PER_MULTISIG);
    1850                 :          18 :             return {};
    1851   [ +  +  +  +  :        2008 :         } else if ((multi_a || sortedmulti_a) && (providers.empty() || providers.size() > MAX_PUBKEYS_PER_MULTI_A)) {
             +  +  +  + ]
    1852         [ +  - ]:           7 :             error = strprintf("Cannot have %u keys in multi_a; must have between 1 and %d keys, inclusive", providers.size(), MAX_PUBKEYS_PER_MULTI_A);
    1853                 :           7 :             return {};
    1854         [ +  + ]:        2001 :         } else if (thres < 1) {
    1855         [ +  - ]:           5 :             error = strprintf("Multisig threshold cannot be %d, must be at least 1", thres);
    1856                 :           5 :             return {};
    1857         [ +  + ]:        1996 :         } else if (thres > providers.size()) {
    1858         [ +  - ]:          11 :             error = strprintf("Multisig threshold cannot be larger than the number of keys; threshold is %d but only %u keys specified", thres, providers.size());
    1859                 :          11 :             return {};
    1860                 :             :         }
    1861         [ +  + ]:        1985 :         if (ctx == ParseScriptContext::TOP) {
    1862         [ +  + ]:         173 :             if (providers.size() > 3) {
    1863         [ +  - ]:           9 :                 error = strprintf("Cannot have %u pubkeys in bare multisig; only at most 3 pubkeys", providers.size());
    1864                 :           9 :                 return {};
    1865                 :             :             }
    1866                 :             :         }
    1867         [ +  + ]:        1976 :         if (ctx == ParseScriptContext::P2SH) {
    1868                 :             :             // This limits the maximum number of compressed pubkeys to 15.
    1869         [ +  + ]:         309 :             if (script_size + 3 > MAX_SCRIPT_ELEMENT_SIZE) {
    1870         [ +  - ]:           7 :                 error = strprintf("P2SH script is too large, %d bytes is larger than %d bytes", script_size + 3, MAX_SCRIPT_ELEMENT_SIZE);
    1871                 :           7 :                 return {};
    1872                 :             :             }
    1873                 :             :         }
    1874                 :             : 
    1875                 :             :         // Make sure all vecs are of the same length, or exactly length 1
    1876                 :             :         // For length 1 vectors, clone key providers until vector is the same length
    1877         [ +  + ]:      110179 :         for (auto& vec : providers) {
    1878         [ +  + ]:      108214 :             if (vec.size() == 1) {
    1879         [ +  + ]:      322439 :                 for (size_t i = 1; i < max_providers_len; ++i) {
    1880   [ +  -  +  -  :      214480 :                     vec.emplace_back(vec.at(0)->Clone());
                   +  - ]
    1881                 :             :                 }
    1882         [ +  + ]:         255 :             } else if (vec.size() != max_providers_len) {
    1883         [ +  - ]:           4 :                 error = strprintf("multi(): Multipath derivation paths have mismatched lengths");
    1884                 :           4 :                 return {};
    1885                 :             :             }
    1886                 :             :         }
    1887                 :             : 
    1888                 :             :         // Build the final descriptors vector
    1889         [ +  + ]:        6488 :         for (size_t i = 0; i < max_providers_len; ++i) {
    1890                 :             :             // Build final pubkeys vectors by retrieving the i'th subscript for each vector in subscripts
    1891                 :        4523 :             std::vector<std::unique_ptr<PubkeyProvider>> pubs;
    1892         [ +  - ]:        4523 :             pubs.reserve(providers.size());
    1893         [ +  + ]:      330487 :             for (auto& pub : providers) {
    1894   [ +  -  +  - ]:      325964 :                 pubs.emplace_back(std::move(pub.at(i)));
    1895                 :             :             }
    1896   [ +  +  +  + ]:        4523 :             if (multi || sortedmulti) {
    1897   [ +  -  +  - ]:        4564 :                 ret.emplace_back(std::make_unique<MultisigDescriptor>(thres, std::move(pubs), sortedmulti));
    1898                 :             :             } else {
    1899   [ +  -  +  - ]:        4482 :                 ret.emplace_back(std::make_unique<MultiADescriptor>(thres, std::move(pubs), sortedmulti_a));
    1900                 :             :             }
    1901                 :        4523 :         }
    1902                 :        1965 :         return ret;
    1903   [ +  +  +  + ]:       43454 :     } else if (multi || sortedmulti) {
    1904         [ +  - ]:          10 :         error = "Can only have multi/sortedmulti at top level, in sh(), or in wsh()";
    1905                 :          10 :         return {};
    1906   [ +  +  +  + ]:       41070 :     } else if (multi_a || sortedmulti_a) {
    1907         [ +  - ]:          10 :         error = "Can only have multi_a/sortedmulti_a inside tr()";
    1908                 :          10 :         return {};
    1909                 :             :     }
    1910   [ +  +  +  -  :       75391 :     if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH) && Func("wpkh", expr)) {
          +  -  +  +  +  
                      + ]
    1911         [ +  - ]:       12166 :         auto pubkeys = ParsePubkey(key_exp_index, expr, ParseScriptContext::P2WPKH, out, error);
    1912         [ +  + ]:       12166 :         if (pubkeys.empty()) {
    1913         [ +  - ]:          21 :             error = strprintf("wpkh(): %s", error);
    1914                 :          21 :             return {};
    1915                 :             :         }
    1916                 :       12145 :         key_exp_index++;
    1917         [ +  + ]:       24757 :         for (auto& pubkey : pubkeys) {
    1918   [ +  -  +  - ]:       25224 :             ret.emplace_back(std::make_unique<WPKHDescriptor>(std::move(pubkey)));
    1919                 :             :         }
    1920                 :       12145 :         return ret;
    1921   [ +  -  +  -  :       41060 :     } else if (Func("wpkh", expr)) {
                   +  + ]
    1922         [ +  - ]:           5 :         error = "Can only have wpkh() at top level or inside sh()";
    1923                 :           5 :         return {};
    1924                 :             :     }
    1925   [ +  +  +  -  :       50737 :     if (ctx == ParseScriptContext::TOP && Func("sh", expr)) {
          +  -  +  +  +  
                      + ]
    1926         [ +  - ]:        6827 :         auto descs = ParseScript(key_exp_index, expr, ParseScriptContext::P2SH, out, error);
    1927   [ +  +  +  + ]:        6827 :         if (descs.empty() || expr.size()) return {};
    1928                 :        6643 :         std::vector<std::unique_ptr<DescriptorImpl>> ret;
    1929         [ +  - ]:        6643 :         ret.reserve(descs.size());
    1930         [ +  + ]:       14865 :         for (auto& desc : descs) {
    1931   [ +  -  +  -  :        8222 :             ret.push_back(std::make_unique<SHDescriptor>(std::move(desc)));
                   -  + ]
    1932                 :             :         }
    1933                 :        6643 :         return ret;
    1934   [ +  -  +  -  :       28889 :     } else if (Func("sh", expr)) {
                   +  + ]
    1935         [ +  - ]:           5 :         error = "Can only have sh() at top level";
    1936                 :           5 :         return {};
    1937                 :             :     }
    1938   [ +  +  +  -  :       37390 :     if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH) && Func("wsh", expr)) {
          +  -  +  +  +  
                      + ]
    1939         [ +  - ]:        3160 :         auto descs = ParseScript(key_exp_index, expr, ParseScriptContext::P2WSH, out, error);
    1940   [ +  +  +  + ]:        3160 :         if (descs.empty() || expr.size()) return {};
    1941         [ +  + ]:        7348 :         for (auto& desc : descs) {
    1942   [ +  -  +  - ]:       11714 :             ret.emplace_back(std::make_unique<WSHDescriptor>(std::move(desc)));
    1943                 :             :         }
    1944                 :        1491 :         return ret;
    1945   [ +  -  +  -  :       22057 :     } else if (Func("wsh", expr)) {
                   +  + ]
    1946         [ +  - ]:           5 :         error = "Can only have wsh() at top level or inside sh()";
    1947                 :           5 :         return {};
    1948                 :             :     }
    1949   [ +  +  +  -  :       31019 :     if (ctx == ParseScriptContext::TOP && Func("addr", expr)) {
          +  -  +  +  +  
                      + ]
    1950   [ +  -  +  - ]:        1050 :         CTxDestination dest = DecodeDestination(std::string(expr.begin(), expr.end()));
    1951   [ +  -  +  + ]:         525 :         if (!IsValidDestination(dest)) {
    1952         [ +  - ]:         502 :             error = "Address is not valid";
    1953                 :         502 :             return {};
    1954                 :             :         }
    1955   [ +  -  +  - ]:          23 :         ret.emplace_back(std::make_unique<AddressDescriptor>(std::move(dest)));
    1956                 :          23 :         return ret;
    1957   [ +  -  +  -  :       18892 :     } else if (Func("addr", expr)) {
                   +  + ]
    1958         [ +  - ]:           5 :         error = "Can only have addr() at top level";
    1959                 :           5 :         return {};
    1960                 :             :     }
    1961   [ +  +  +  -  :       29964 :     if (ctx == ParseScriptContext::TOP && Func("tr", expr)) {
          +  -  +  +  +  
                      + ]
    1962         [ +  - ]:        8378 :         auto arg = Expr(expr);
    1963         [ +  - ]:        8378 :         auto internal_keys = ParsePubkey(key_exp_index, arg, ParseScriptContext::P2TR, out, error);
    1964         [ +  + ]:        8378 :         if (internal_keys.empty()) {
    1965         [ +  - ]:         120 :             error = strprintf("tr(): %s", error);
    1966                 :         120 :             return {};
    1967                 :             :         }
    1968         [ +  + ]:        8258 :         size_t max_providers_len = internal_keys.size();
    1969                 :        8258 :         ++key_exp_index;
    1970                 :        8258 :         std::vector<std::vector<std::unique_ptr<DescriptorImpl>>> subscripts; //!< list of multipath expanded script subexpressions
    1971                 :        8258 :         std::vector<int> depths; //!< depth in the tree of each subexpression (same length subscripts)
    1972         [ +  + ]:        8258 :         if (expr.size()) {
    1973   [ +  -  +  -  :        1814 :             if (!Const(",", expr)) {
                   +  + ]
    1974         [ +  - ]:           9 :                 error = strprintf("tr: expected ',', got '%c'", expr[0]);
    1975                 :           9 :                 return {};
    1976                 :             :             }
    1977                 :             :             /** The path from the top of the tree to what we're currently processing.
    1978                 :             :              * branches[i] == false: left branch in the i'th step from the top; true: right branch.
    1979                 :             :              */
    1980                 :        1805 :             std::vector<bool> branches;
    1981                 :             :             // Loop over all provided scripts. In every iteration exactly one script will be processed.
    1982                 :             :             // Use a do-loop because inside this if-branch we expect at least one script.
    1983                 :             :             do {
    1984                 :             :                 // First process all open braces.
    1985   [ +  -  +  -  :       18774 :                 while (Const("{", expr)) {
                   +  + ]
    1986         [ +  - ]:       10703 :                     branches.push_back(false); // new left branch
    1987         [ +  + ]:       10703 :                     if (branches.size() > TAPROOT_CONTROL_MAX_NODE_COUNT) {
    1988         [ +  - ]:          12 :                         error = strprintf("tr() supports at most %i nesting levels", TAPROOT_CONTROL_MAX_NODE_COUNT);
    1989                 :          12 :                         return {};
    1990                 :             :                     }
    1991                 :             :                 }
    1992                 :             :                 // Process the actual script expression.
    1993         [ +  - ]:        8071 :                 auto sarg = Expr(expr);
    1994   [ +  -  +  - ]:        8071 :                 subscripts.emplace_back(ParseScript(key_exp_index, sarg, ParseScriptContext::P2TR, out, error));
    1995         [ +  + ]:        8071 :                 if (subscripts.back().empty()) return {};
    1996         [ +  + ]:        7557 :                 max_providers_len = std::max(max_providers_len, subscripts.back().size());
    1997         [ +  - ]:        7557 :                 depths.push_back(branches.size());
    1998                 :             :                 // Process closing braces; one is expected for every right branch we were in.
    1999   [ +  +  +  + ]:       10555 :                 while (branches.size() && branches.back()) {
    2000   [ +  -  +  +  :        3011 :                     if (!Const("}", expr)) {
                   +  - ]
    2001         [ +  - ]:          13 :                         error = strprintf("tr(): expected '}' after script expression");
    2002                 :          13 :                         return {};
    2003                 :             :                     }
    2004                 :        2998 :                     branches.pop_back(); // move up one level after encountering '}'
    2005                 :             :                 }
    2006                 :             :                 // If after that, we're at the end of a left branch, expect a comma.
    2007   [ +  +  +  - ]:        7544 :                 if (branches.size() && !branches.back()) {
    2008   [ +  -  +  -  :        6296 :                     if (!Const(",", expr)) {
                   +  + ]
    2009         [ +  - ]:          18 :                         error = strprintf("tr(): expected ',' after script expression");
    2010                 :          18 :                         return {};
    2011                 :             :                     }
    2012                 :        6278 :                     branches.back() = true; // And now we're in a right branch.
    2013                 :             :                 }
    2014         [ +  + ]:        7526 :             } while (branches.size());
    2015                 :             :             // After we've explored a whole tree, we must be at the end of the expression.
    2016         [ +  + ]:        1248 :             if (expr.size()) {
    2017         [ +  - ]:           6 :                 error = strprintf("tr(): expected ')' after script expression");
    2018                 :           6 :                 return {};
    2019                 :             :             }
    2020                 :        1805 :         }
    2021   [ +  -  -  + ]:        7686 :         assert(TaprootBuilder::ValidDepths(depths));
    2022                 :             : 
    2023                 :             :         // Make sure all vecs are of the same length, or exactly length 1
    2024                 :             :         // For length 1 vectors, clone subdescs until vector is the same length
    2025         [ +  + ]:       11525 :         for (auto& vec : subscripts) {
    2026         [ +  + ]:        3842 :             if (vec.size() == 1) {
    2027         [ +  + ]:       12348 :                 for (size_t i = 1; i < max_providers_len; ++i) {
    2028   [ +  -  +  -  :        8735 :                     vec.emplace_back(vec.at(0)->Clone());
                   +  - ]
    2029                 :             :                 }
    2030         [ +  + ]:         229 :             } else if (vec.size() != max_providers_len) {
    2031         [ +  - ]:           3 :                 error = strprintf("tr(): Multipath subscripts have mismatched lengths");
    2032                 :           3 :                 return {};
    2033                 :             :             }
    2034                 :             :         }
    2035                 :             : 
    2036   [ +  +  +  + ]:        7683 :         if (internal_keys.size() > 1 && internal_keys.size() != max_providers_len) {
    2037         [ +  - ]:           1 :             error = strprintf("tr(): Multipath internal key mismatches multipath subscripts lengths");
    2038                 :           1 :             return {};
    2039                 :             :         }
    2040                 :             : 
    2041         [ +  + ]:       11536 :         while (internal_keys.size() < max_providers_len) {
    2042   [ +  -  +  -  :        3854 :             internal_keys.emplace_back(internal_keys.at(0)->Clone());
                   +  - ]
    2043                 :             :         }
    2044                 :             : 
    2045                 :             :         // Build the final descriptors vector
    2046         [ +  + ]:       20608 :         for (size_t i = 0; i < max_providers_len; ++i) {
    2047                 :             :             // Build final subscripts vectors by retrieving the i'th subscript for each vector in subscripts
    2048                 :       12926 :             std::vector<std::unique_ptr<DescriptorImpl>> this_subs;
    2049         [ +  - ]:       12926 :             this_subs.reserve(subscripts.size());
    2050         [ +  + ]:       29299 :             for (auto& subs : subscripts) {
    2051   [ +  -  +  - ]:       16373 :                 this_subs.emplace_back(std::move(subs.at(i)));
    2052                 :             :             }
    2053   [ +  -  +  -  :       12926 :             ret.emplace_back(std::make_unique<TRDescriptor>(std::move(internal_keys.at(i)), std::move(this_subs), depths));
                   +  - ]
    2054                 :       12926 :         }
    2055                 :        7682 :         return ret;
    2056                 :             : 
    2057                 :             : 
    2058   [ +  -  +  -  :       18362 :     } else if (Func("tr", expr)) {
                   +  + ]
    2059         [ +  - ]:           5 :         error = "Can only have tr at top level";
    2060                 :           5 :         return {};
    2061                 :             :     }
    2062   [ +  +  +  -  :       13203 :     if (ctx == ParseScriptContext::TOP && Func("rawtr", expr)) {
          +  -  +  +  +  
                      + ]
    2063         [ +  - ]:          74 :         auto arg = Expr(expr);
    2064         [ +  + ]:          74 :         if (expr.size()) {
    2065         [ +  - ]:           5 :             error = strprintf("rawtr(): only one key expected.");
    2066                 :           5 :             return {};
    2067                 :             :         }
    2068         [ +  - ]:          69 :         auto output_keys = ParsePubkey(key_exp_index, arg, ParseScriptContext::P2TR, out, error);
    2069         [ +  + ]:          69 :         if (output_keys.empty()) {
    2070         [ +  - ]:          11 :             error = strprintf("rawtr(): %s", error);
    2071                 :          11 :             return {};
    2072                 :             :         }
    2073                 :          58 :         ++key_exp_index;
    2074         [ +  + ]:         352 :         for (auto& pubkey : output_keys) {
    2075   [ +  -  +  - ]:         588 :             ret.emplace_back(std::make_unique<RawTRDescriptor>(std::move(pubkey)));
    2076                 :             :         }
    2077                 :          58 :         return ret;
    2078   [ +  -  +  -  :        9974 :     } else if (Func("rawtr", expr)) {
                   +  + ]
    2079         [ +  - ]:           5 :         error = "Can only have rawtr at top level";
    2080                 :           5 :         return {};
    2081                 :             :     }
    2082   [ +  +  +  -  :       13050 :     if (ctx == ParseScriptContext::TOP && Func("raw", expr)) {
          +  -  +  +  +  
                      + ]
    2083   [ +  -  +  - ]:        2724 :         std::string str(expr.begin(), expr.end());
    2084   [ +  -  +  + ]:        1362 :         if (!IsHex(str)) {
    2085         [ +  - ]:           7 :             error = "Raw script is not hex";
    2086                 :           7 :             return {};
    2087                 :             :         }
    2088         [ +  - ]:        1355 :         auto bytes = ParseHex(str);
    2089   [ +  -  +  - ]:        2710 :         ret.emplace_back(std::make_unique<RawDescriptor>(CScript(bytes.begin(), bytes.end())));
    2090                 :        1355 :         return ret;
    2091   [ +  -  +  -  :       11255 :     } else if (Func("raw", expr)) {
                   +  + ]
    2092         [ +  - ]:           5 :         error = "Can only have raw() at top level";
    2093                 :           5 :         return {};
    2094                 :             :     }
    2095                 :             :     // Process miniscript expressions.
    2096                 :        8533 :     {
    2097                 :        8533 :         const auto script_ctx{ctx == ParseScriptContext::P2WSH ? miniscript::MiniscriptContext::P2WSH : miniscript::MiniscriptContext::TAPSCRIPT};
    2098         [ +  - ]:        8533 :         KeyParser parser(/*out = */&out, /* in = */nullptr, /* ctx = */script_ctx, key_exp_index);
    2099   [ +  -  +  - ]:       17066 :         auto node = miniscript::FromString(std::string(expr.begin(), expr.end()), parser);
    2100         [ +  + ]:        8533 :         if (parser.m_key_parsing_error != "") {
    2101                 :         293 :             error = std::move(parser.m_key_parsing_error);
    2102                 :         293 :             return {};
    2103                 :             :         }
    2104         [ +  + ]:        8240 :         if (node) {
    2105         [ +  + ]:        6677 :             if (ctx != ParseScriptContext::P2WSH && ctx != ParseScriptContext::P2TR) {
    2106         [ +  - ]:         484 :                 error = "Miniscript expressions can only be used in wsh or tr.";
    2107                 :         484 :                 return {};
    2108                 :             :             }
    2109   [ +  +  +  + ]:        6193 :             if (!node->IsSane() || node->IsNotSatisfiable()) {
    2110                 :             :                 // Try to find the first insane sub for better error reporting.
    2111         [ +  - ]:        1403 :                 auto insane_node = node.get();
    2112   [ +  -  +  + ]:        1403 :                 if (const auto sub = node->FindInsaneSub()) insane_node = sub;
    2113   [ +  -  +  -  :        2806 :                 if (const auto str = insane_node->ToString(parser)) error = *str;
                   +  - ]
    2114         [ +  + ]:        1403 :                 if (!insane_node->IsValid()) {
    2115         [ +  - ]:         828 :                     error += " is invalid";
    2116         [ +  + ]:         575 :                 } else if (!node->IsSane()) {
    2117         [ +  - ]:         467 :                     error += " is not sane";
    2118         [ +  + ]:         467 :                     if (!insane_node->IsNonMalleable()) {
    2119         [ +  - ]:          90 :                         error += ": malleable witnesses exist";
    2120   [ +  +  +  + ]:         377 :                     } else if (insane_node == node.get() && !insane_node->NeedsSignature()) {
    2121         [ +  - ]:          79 :                         error += ": witnesses without signature exist";
    2122         [ +  + ]:         298 :                     } else if (!insane_node->CheckTimeLocksMix()) {
    2123         [ +  - ]:          32 :                         error += ": contains mixes of timelocks expressed in blocks and seconds";
    2124         [ +  - ]:         266 :                     } else if (!insane_node->CheckDuplicateKey()) {
    2125         [ +  - ]:         206 :                         error += ": contains duplicate public keys";
    2126         [ +  + ]:          60 :                     } else if (!insane_node->ValidSatisfactions()) {
    2127         [ +  - ]:          30 :                         error += ": needs witnesses that may exceed resource limits";
    2128                 :             :                     }
    2129                 :             :                 } else {
    2130         [ +  - ]:         108 :                     error += " is not satisfiable";
    2131                 :             :                 }
    2132                 :        1403 :                 return {};
    2133                 :             :             }
    2134                 :             :             // A signature check is required for a miniscript to be sane. Therefore no sane miniscript
    2135                 :             :             // may have an empty list of public keys.
    2136         [ +  - ]:        4790 :             CHECK_NONFATAL(!parser.m_keys.empty());
    2137                 :        4790 :             key_exp_index += parser.m_keys.size();
    2138                 :             :             // Make sure all vecs are of the same length, or exactly length 1
    2139                 :             :             // For length 1 vectors, clone subdescs until vector is the same length
    2140                 :        4790 :             size_t num_multipath = std::max_element(parser.m_keys.begin(), parser.m_keys.end(),
    2141                 :        4237 :                     [](const std::vector<std::unique_ptr<PubkeyProvider>>& a, const std::vector<std::unique_ptr<PubkeyProvider>>& b) {
    2142         [ +  + ]:        4237 :                         return a.size() < b.size();
    2143                 :        4790 :                     })->size();
    2144                 :             : 
    2145         [ +  + ]:       13797 :             for (auto& vec : parser.m_keys) {
    2146         [ +  + ]:        9012 :                 if (vec.size() == 1) {
    2147         [ +  + ]:       15235 :                     for (size_t i = 1; i < num_multipath; ++i) {
    2148   [ +  -  +  -  :        6636 :                         vec.emplace_back(vec.at(0)->Clone());
                   +  - ]
    2149                 :             :                     }
    2150         [ +  + ]:         413 :                 } else if (vec.size() != num_multipath) {
    2151         [ +  - ]:           5 :                     error = strprintf("Miniscript: Multipath derivation paths have mismatched lengths");
    2152                 :           5 :                     return {};
    2153                 :             :                 }
    2154                 :             :             }
    2155                 :             : 
    2156                 :             :             // Build the final descriptors vector
    2157         [ +  + ]:       15638 :             for (size_t i = 0; i < num_multipath; ++i) {
    2158                 :             :                 // Build final pubkeys vectors by retrieving the i'th subscript for each vector in subscripts
    2159                 :       10853 :                 std::vector<std::unique_ptr<PubkeyProvider>> pubs;
    2160         [ +  - ]:       10853 :                 pubs.reserve(parser.m_keys.size());
    2161         [ +  + ]:       32558 :                 for (auto& pub : parser.m_keys) {
    2162   [ +  -  +  - ]:       21705 :                     pubs.emplace_back(std::move(pub.at(i)));
    2163                 :             :                 }
    2164   [ +  -  +  -  :       21706 :                 ret.emplace_back(std::make_unique<MiniscriptDescriptor>(std::move(pubs), node->Clone()));
                   +  - ]
    2165                 :       10853 :             }
    2166                 :        4785 :             return ret;
    2167                 :             :         }
    2168                 :       15503 :     }
    2169         [ +  + ]:        1563 :     if (ctx == ParseScriptContext::P2SH) {
    2170         [ +  - ]:          21 :         error = "A function is needed within P2SH";
    2171                 :          21 :         return {};
    2172         [ +  + ]:        1542 :     } else if (ctx == ParseScriptContext::P2WSH) {
    2173         [ +  - ]:         198 :         error = "A function is needed within P2WSH";
    2174                 :         198 :         return {};
    2175                 :             :     }
    2176   [ +  -  +  - ]:        2688 :     error = strprintf("'%s' is not a valid descriptor function", std::string(expr.begin(), expr.end()));
    2177                 :        1344 :     return {};
    2178                 :       55554 : }
    2179                 :             : 
    2180                 :       12189 : std::unique_ptr<DescriptorImpl> InferMultiA(const CScript& script, ParseScriptContext ctx, const SigningProvider& provider)
    2181                 :             : {
    2182                 :       12189 :     auto match = MatchMultiA(script);
    2183         [ +  + ]:       12189 :     if (!match) return {};
    2184                 :        1512 :     std::vector<std::unique_ptr<PubkeyProvider>> keys;
    2185         [ +  - ]:        1512 :     keys.reserve(match->second.size());
    2186         [ +  + ]:      221694 :     for (const auto keyspan : match->second) {
    2187         [ -  + ]:      220182 :         if (keyspan.size() != 32) return {};
    2188         [ +  - ]:      220182 :         auto key = InferXOnlyPubkey(XOnlyPubKey{keyspan}, ctx, provider);
    2189         [ -  + ]:      220182 :         if (!key) return {};
    2190         [ +  - ]:      220182 :         keys.push_back(std::move(key));
    2191                 :      220182 :     }
    2192   [ +  -  -  + ]:        1512 :     return std::make_unique<MultiADescriptor>(match->first, std::move(keys));
    2193                 :       13701 : }
    2194                 :             : 
    2195                 :             : // NOLINTNEXTLINE(misc-no-recursion)
    2196                 :     6951017 : std::unique_ptr<DescriptorImpl> InferScript(const CScript& script, ParseScriptContext ctx, const SigningProvider& provider)
    2197                 :             : {
    2198   [ +  +  +  +  :     6951017 :     if (ctx == ParseScriptContext::P2TR && script.size() == 34 && script[0] == 32 && script[33] == OP_CHECKSIG) {
          +  +  +  +  -  
                      + ]
    2199                 :        2167 :         XOnlyPubKey key{std::span{script}.subspan(1, 32)};
    2200   [ +  -  -  + ]:        2167 :         return std::make_unique<PKDescriptor>(InferXOnlyPubkey(key, ctx, provider), true);
    2201                 :             :     }
    2202                 :             : 
    2203         [ +  + ]:     6948850 :     if (ctx == ParseScriptContext::P2TR) {
    2204                 :       12189 :         auto ret = InferMultiA(script, ctx, provider);
    2205         [ +  + ]:       12189 :         if (ret) return ret;
    2206                 :       12189 :     }
    2207                 :             : 
    2208                 :     6947338 :     std::vector<std::vector<unsigned char>> data;
    2209         [ +  - ]:     6947338 :     TxoutType txntype = Solver(script, data);
    2210                 :             : 
    2211   [ +  +  +  - ]:     6947338 :     if (txntype == TxoutType::PUBKEY && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
    2212                 :       24003 :         CPubKey pubkey(data[0]);
    2213   [ +  -  +  + ]:       24003 :         if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
    2214   [ +  -  -  + ]:       22171 :             return std::make_unique<PKDescriptor>(std::move(pubkey_provider));
    2215                 :       24003 :         }
    2216                 :             :     }
    2217   [ +  +  +  + ]:     6925167 :     if (txntype == TxoutType::PUBKEYHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
    2218                 :     1069500 :         uint160 hash(data[0]);
    2219         [ +  - ]:     1069500 :         CKeyID keyid(hash);
    2220         [ +  - ]:     1069500 :         CPubKey pubkey;
    2221   [ +  -  +  + ]:     1069500 :         if (provider.GetPubKey(keyid, pubkey)) {
    2222   [ +  -  +  - ]:     1049417 :             if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
    2223   [ +  -  -  + ]:     1049417 :                 return std::make_unique<PKHDescriptor>(std::move(pubkey_provider));
    2224                 :     1049417 :             }
    2225                 :             :         }
    2226                 :             :     }
    2227         [ +  + ]:     5875750 :     if (txntype == TxoutType::WITNESS_V0_KEYHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH)) {
    2228                 :     2298908 :         uint160 hash(data[0]);
    2229         [ +  - ]:     2298908 :         CKeyID keyid(hash);
    2230         [ +  - ]:     2298908 :         CPubKey pubkey;
    2231   [ +  -  +  + ]:     2298908 :         if (provider.GetPubKey(keyid, pubkey)) {
    2232   [ +  -  +  - ]:     2246913 :             if (auto pubkey_provider = InferPubkey(pubkey, ParseScriptContext::P2WPKH, provider)) {
    2233   [ +  -  -  + ]:     2246913 :                 return std::make_unique<WPKHDescriptor>(std::move(pubkey_provider));
    2234                 :     2246913 :             }
    2235                 :             :         }
    2236                 :             :     }
    2237   [ +  +  +  - ]:     3628837 :     if (txntype == TxoutType::MULTISIG && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
    2238                 :       23968 :         bool ok = true;
    2239                 :       23968 :         std::vector<std::unique_ptr<PubkeyProvider>> providers;
    2240         [ +  + ]:      146536 :         for (size_t i = 1; i + 1 < data.size(); ++i) {
    2241                 :      124192 :             CPubKey pubkey(data[i]);
    2242   [ +  -  +  + ]:      124192 :             if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
    2243         [ +  - ]:      122568 :                 providers.push_back(std::move(pubkey_provider));
    2244                 :             :             } else {
    2245                 :        1624 :                 ok = false;
    2246                 :        1624 :                 break;
    2247                 :      124192 :             }
    2248                 :             :         }
    2249   [ +  -  -  + ]:       22344 :         if (ok) return std::make_unique<MultisigDescriptor>((int)data[0][0], std::move(providers));
    2250                 :       23968 :     }
    2251         [ +  + ]:     3606493 :     if (txntype == TxoutType::SCRIPTHASH && ctx == ParseScriptContext::TOP) {
    2252                 :     2277657 :         uint160 hash(data[0]);
    2253         [ +  - ]:     2277657 :         CScriptID scriptid(hash);
    2254                 :     2277657 :         CScript subscript;
    2255   [ +  -  +  + ]:     2277657 :         if (provider.GetCScript(scriptid, subscript)) {
    2256         [ +  - ]:     2162763 :             auto sub = InferScript(subscript, ParseScriptContext::P2SH, provider);
    2257   [ +  -  +  -  :     2162763 :             if (sub) return std::make_unique<SHDescriptor>(std::move(sub));
                   -  + ]
    2258                 :     2162763 :         }
    2259                 :     2277657 :     }
    2260         [ +  + ]:     1443730 :     if (txntype == TxoutType::WITNESS_V0_SCRIPTHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH)) {
    2261         [ +  - ]:       63955 :         CScriptID scriptid{RIPEMD160(data[0])};
    2262                 :       63955 :         CScript subscript;
    2263   [ +  -  +  + ]:       63955 :         if (provider.GetCScript(scriptid, subscript)) {
    2264         [ +  - ]:        5476 :             auto sub = InferScript(subscript, ParseScriptContext::P2WSH, provider);
    2265   [ +  +  +  -  :        5476 :             if (sub) return std::make_unique<WSHDescriptor>(std::move(sub));
                   -  + ]
    2266                 :        5476 :         }
    2267                 :       63955 :     }
    2268         [ +  + ]:     1438689 :     if (txntype == TxoutType::WITNESS_V1_TAPROOT && ctx == ParseScriptContext::TOP) {
    2269                 :             :         // Extract x-only pubkey from output.
    2270                 :      410964 :         XOnlyPubKey pubkey;
    2271                 :      410964 :         std::copy(data[0].begin(), data[0].end(), pubkey.begin());
    2272                 :             :         // Request spending data.
    2273         [ +  - ]:      410964 :         TaprootSpendData tap;
    2274   [ +  -  +  + ]:      410964 :         if (provider.GetTaprootSpendData(pubkey, tap)) {
    2275                 :             :             // If found, convert it back to tree form.
    2276         [ +  - ]:      400496 :             auto tree = InferTaprootTree(tap, pubkey);
    2277         [ +  + ]:      400496 :             if (tree) {
    2278                 :             :                 // If that works, try to infer subdescriptors for all leaves.
    2279                 :      400484 :                 bool ok = true;
    2280                 :      400484 :                 std::vector<std::unique_ptr<DescriptorImpl>> subscripts; //!< list of script subexpressions
    2281                 :      400484 :                 std::vector<int> depths; //!< depth in the tree of each subexpression (same length subscripts)
    2282   [ +  -  +  + ]:      414833 :                 for (const auto& [depth, script, leaf_ver] : *tree) {
    2283                 :       14356 :                     std::unique_ptr<DescriptorImpl> subdesc;
    2284         [ +  - ]:       14356 :                     if (leaf_ver == TAPROOT_LEAF_TAPSCRIPT) {
    2285         [ +  - ]:       28712 :                         subdesc = InferScript(CScript(script.begin(), script.end()), ParseScriptContext::P2TR, provider);
    2286                 :             :                     }
    2287         [ +  + ]:       14356 :                     if (!subdesc) {
    2288                 :           7 :                         ok = false;
    2289                 :           7 :                         break;
    2290                 :             :                     } else {
    2291         [ +  - ]:       14349 :                         subscripts.push_back(std::move(subdesc));
    2292         [ +  - ]:       14349 :                         depths.push_back(depth);
    2293                 :             :                     }
    2294                 :       14356 :                 }
    2295                 :           7 :                 if (ok) {
    2296         [ +  - ]:      400477 :                     auto key = InferXOnlyPubkey(tap.internal_key, ParseScriptContext::P2TR, provider);
    2297   [ +  -  -  + ]:      400477 :                     return std::make_unique<TRDescriptor>(std::move(key), std::move(subscripts), std::move(depths));
    2298                 :      400477 :                 }
    2299                 :      400484 :             }
    2300                 :      400496 :         }
    2301                 :             :         // If the above doesn't work, construct a rawtr() descriptor with just the encoded x-only pubkey.
    2302   [ +  -  +  + ]:       10487 :         if (pubkey.IsFullyValid()) {
    2303         [ +  - ]:        7142 :             auto key = InferXOnlyPubkey(pubkey, ParseScriptContext::P2TR, provider);
    2304         [ +  - ]:        7142 :             if (key) {
    2305   [ +  -  -  + ]:        7142 :                 return std::make_unique<RawTRDescriptor>(std::move(key));
    2306                 :             :             }
    2307                 :        7142 :         }
    2308                 :      410964 :     }
    2309                 :             : 
    2310         [ +  + ]:     1031070 :     if (ctx == ParseScriptContext::P2WSH || ctx == ParseScriptContext::P2TR) {
    2311                 :       14973 :         const auto script_ctx{ctx == ParseScriptContext::P2WSH ? miniscript::MiniscriptContext::P2WSH : miniscript::MiniscriptContext::TAPSCRIPT};
    2312         [ +  - ]:       14973 :         KeyParser parser(/* out = */nullptr, /* in = */&provider, /* ctx = */script_ctx);
    2313         [ +  - ]:       14973 :         auto node = miniscript::FromScript(script, parser);
    2314   [ +  +  +  + ]:       14973 :         if (node && node->IsSane()) {
    2315                 :       14531 :             std::vector<std::unique_ptr<PubkeyProvider>> keys;
    2316         [ +  - ]:       14531 :             keys.reserve(parser.m_keys.size());
    2317         [ +  + ]:       37943 :             for (auto& key : parser.m_keys) {
    2318   [ +  -  +  - ]:       23412 :                 keys.emplace_back(std::move(key.at(0)));
    2319                 :             :             }
    2320   [ +  -  -  + ]:       14531 :             return std::make_unique<MiniscriptDescriptor>(std::move(keys), std::move(node));
    2321                 :       14531 :         }
    2322                 :       29946 :     }
    2323                 :             : 
    2324                 :             :     // The following descriptors are all top-level only descriptors.
    2325                 :             :     // So if we are not at the top level, return early.
    2326         [ +  + ]:     1016539 :     if (ctx != ParseScriptContext::TOP) return nullptr;
    2327                 :             : 
    2328                 :     1016097 :     CTxDestination dest;
    2329   [ +  -  +  + ]:     1016097 :     if (ExtractDestination(script, dest)) {
    2330   [ +  -  +  - ]:      268310 :         if (GetScriptForDestination(dest) == script) {
    2331   [ +  -  -  + ]:      268310 :             return std::make_unique<AddressDescriptor>(std::move(dest));
    2332                 :             :         }
    2333                 :             :     }
    2334                 :             : 
    2335   [ +  -  -  + ]:      747787 :     return std::make_unique<RawDescriptor>(script);
    2336                 :     6947338 : }
    2337                 :             : 
    2338                 :             : 
    2339                 :             : } // namespace
    2340                 :             : 
    2341                 :             : /** Check a descriptor checksum, and update desc to be the checksum-less part. */
    2342                 :       40493 : bool CheckChecksum(std::span<const char>& sp, bool require_checksum, std::string& error, std::string* out_checksum = nullptr)
    2343                 :             : {
    2344                 :       40493 :     auto check_split = Split(sp, '#');
    2345         [ +  + ]:       40493 :     if (check_split.size() > 2) {
    2346         [ +  - ]:          32 :         error = "Multiple '#' symbols";
    2347                 :             :         return false;
    2348                 :             :     }
    2349   [ +  +  +  + ]:       40461 :     if (check_split.size() == 1 && require_checksum){
    2350         [ +  - ]:       40493 :         error = "Missing checksum";
    2351                 :             :         return false;
    2352                 :             :     }
    2353         [ +  + ]:       38271 :     if (check_split.size() == 2) {
    2354         [ +  + ]:          75 :         if (check_split[1].size() != 8) {
    2355         [ +  - ]:          21 :             error = strprintf("Expected 8 character checksum, not %u characters", check_split[1].size());
    2356                 :          21 :             return false;
    2357                 :             :         }
    2358                 :             :     }
    2359         [ +  - ]:       38250 :     auto checksum = DescriptorChecksum(check_split[0]);
    2360         [ +  + ]:       38250 :     if (checksum.empty()) {
    2361         [ +  - ]:       38250 :         error = "Invalid characters in payload";
    2362                 :             :         return false;
    2363                 :             :     }
    2364         [ +  + ]:       38063 :     if (check_split.size() == 2) {
    2365         [ +  + ]:          50 :         if (!std::equal(checksum.begin(), checksum.end(), check_split[1].begin())) {
    2366   [ +  -  +  - ]:          22 :             error = strprintf("Provided checksum '%s' does not match computed checksum '%s'", std::string(check_split[1].begin(), check_split[1].end()), checksum);
    2367                 :          11 :             return false;
    2368                 :             :         }
    2369                 :             :     }
    2370         [ +  + ]:       38052 :     if (out_checksum) *out_checksum = std::move(checksum);
    2371                 :       38052 :     sp = check_split[0];
    2372                 :       38052 :     return true;
    2373                 :       78743 : }
    2374                 :             : 
    2375                 :       39833 : std::vector<std::unique_ptr<Descriptor>> Parse(const std::string& descriptor, FlatSigningProvider& out, std::string& error, bool require_checksum)
    2376                 :             : {
    2377                 :       39833 :     std::span<const char> sp{descriptor};
    2378         [ +  + ]:       39833 :     if (!CheckChecksum(sp, require_checksum, error)) return {};
    2379                 :       37496 :     uint32_t key_exp_index = 0;
    2380                 :       37496 :     auto ret = ParseScript(key_exp_index, sp, ParseScriptContext::TOP, out, error);
    2381   [ +  +  +  + ]:       37496 :     if (sp.size() == 0 && !ret.empty()) {
    2382                 :       32268 :         std::vector<std::unique_ptr<Descriptor>> descs;
    2383         [ +  - ]:       32268 :         descs.reserve(ret.size());
    2384         [ +  + ]:       76484 :         for (auto& r : ret) {
    2385         [ +  - ]:       44216 :             descs.emplace_back(std::unique_ptr<Descriptor>(std::move(r)));
    2386                 :             :         }
    2387                 :       32268 :         return descs;
    2388                 :       32268 :     }
    2389                 :        5228 :     return {};
    2390                 :       37496 : }
    2391                 :             : 
    2392                 :         660 : std::string GetDescriptorChecksum(const std::string& descriptor)
    2393                 :             : {
    2394         [ +  - ]:         660 :     std::string ret;
    2395                 :         660 :     std::string error;
    2396         [ +  - ]:         660 :     std::span<const char> sp{descriptor};
    2397   [ +  -  +  +  :         660 :     if (!CheckChecksum(sp, false, error, &ret)) return "";
                   +  - ]
    2398                 :         556 :     return ret;
    2399                 :         660 : }
    2400                 :             : 
    2401                 :     4768422 : std::unique_ptr<Descriptor> InferDescriptor(const CScript& script, const SigningProvider& provider)
    2402                 :             : {
    2403                 :     4768422 :     return InferScript(script, ParseScriptContext::TOP, provider);
    2404                 :             : }
    2405                 :             : 
    2406                 :       28918 : uint256 DescriptorID(const Descriptor& desc)
    2407                 :             : {
    2408                 :       28918 :     std::string desc_str = desc.ToString(/*compat_format=*/true);
    2409                 :       28918 :     uint256 id;
    2410   [ +  -  +  -  :       28918 :     CSHA256().Write((unsigned char*)desc_str.data(), desc_str.size()).Finalize(id.begin());
                   +  - ]
    2411                 :       28918 :     return id;
    2412                 :       28918 : }
    2413                 :             : 
    2414                 :      429649 : void DescriptorCache::CacheParentExtPubKey(uint32_t key_exp_pos, const CExtPubKey& xpub)
    2415                 :             : {
    2416                 :      429649 :     m_parent_xpubs[key_exp_pos] = xpub;
    2417                 :      429649 : }
    2418                 :             : 
    2419                 :       68440 : void DescriptorCache::CacheDerivedExtPubKey(uint32_t key_exp_pos, uint32_t der_index, const CExtPubKey& xpub)
    2420                 :             : {
    2421                 :       68440 :     auto& xpubs = m_derived_xpubs[key_exp_pos];
    2422                 :       68440 :     xpubs[der_index] = xpub;
    2423                 :       68440 : }
    2424                 :             : 
    2425                 :       25325 : void DescriptorCache::CacheLastHardenedExtPubKey(uint32_t key_exp_pos, const CExtPubKey& xpub)
    2426                 :             : {
    2427                 :       25325 :     m_last_hardened_xpubs[key_exp_pos] = xpub;
    2428                 :       25325 : }
    2429                 :             : 
    2430                 :     1551288 : bool DescriptorCache::GetCachedParentExtPubKey(uint32_t key_exp_pos, CExtPubKey& xpub) const
    2431                 :             : {
    2432                 :     1551288 :     const auto& it = m_parent_xpubs.find(key_exp_pos);
    2433         [ +  + ]:     1551288 :     if (it == m_parent_xpubs.end()) return false;
    2434                 :     1480440 :     xpub = it->second;
    2435                 :     1480440 :     return true;
    2436                 :             : }
    2437                 :             : 
    2438                 :     1407989 : bool DescriptorCache::GetCachedDerivedExtPubKey(uint32_t key_exp_pos, uint32_t der_index, CExtPubKey& xpub) const
    2439                 :             : {
    2440                 :     1407989 :     const auto& key_exp_it = m_derived_xpubs.find(key_exp_pos);
    2441         [ +  + ]:     1407989 :     if (key_exp_it == m_derived_xpubs.end()) return false;
    2442                 :       58713 :     const auto& der_it = key_exp_it->second.find(der_index);
    2443         [ +  + ]:       58713 :     if (der_it == key_exp_it->second.end()) return false;
    2444                 :       39542 :     xpub = der_it->second;
    2445                 :       39542 :     return true;
    2446                 :             : }
    2447                 :             : 
    2448                 :        2384 : bool DescriptorCache::GetCachedLastHardenedExtPubKey(uint32_t key_exp_pos, CExtPubKey& xpub) const
    2449                 :             : {
    2450                 :        2384 :     const auto& it = m_last_hardened_xpubs.find(key_exp_pos);
    2451         [ +  + ]:        2384 :     if (it == m_last_hardened_xpubs.end()) return false;
    2452                 :        1741 :     xpub = it->second;
    2453                 :        1741 :     return true;
    2454                 :             : }
    2455                 :             : 
    2456                 :      393148 : DescriptorCache DescriptorCache::MergeAndDiff(const DescriptorCache& other)
    2457                 :             : {
    2458                 :      393148 :     DescriptorCache diff;
    2459   [ +  -  +  +  :      514995 :     for (const auto& parent_xpub_pair : other.GetCachedParentExtPubKeys()) {
                   +  - ]
    2460         [ +  - ]:      121847 :         CExtPubKey xpub;
    2461   [ +  +  +  - ]:      121847 :         if (GetCachedParentExtPubKey(parent_xpub_pair.first, xpub)) {
    2462         [ -  + ]:       84000 :             if (xpub != parent_xpub_pair.second) {
    2463   [ #  #  #  # ]:           0 :                 throw std::runtime_error(std::string(__func__) + ": New cached parent xpub does not match already cached parent xpub");
    2464                 :             :             }
    2465                 :       84000 :             continue;
    2466                 :             :         }
    2467         [ +  - ]:       37847 :         CacheParentExtPubKey(parent_xpub_pair.first, parent_xpub_pair.second);
    2468         [ +  - ]:       37847 :         diff.CacheParentExtPubKey(parent_xpub_pair.first, parent_xpub_pair.second);
    2469                 :           0 :     }
    2470   [ +  -  +  + ]:      411386 :     for (const auto& derived_xpub_map_pair : other.GetCachedDerivedExtPubKeys()) {
    2471   [ +  +  +  - ]:       36476 :         for (const auto& derived_xpub_pair : derived_xpub_map_pair.second) {
    2472         [ +  - ]:       18238 :             CExtPubKey xpub;
    2473   [ -  +  +  - ]:       18238 :             if (GetCachedDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, xpub)) {
    2474         [ #  # ]:           0 :                 if (xpub != derived_xpub_pair.second) {
    2475   [ #  #  #  # ]:           0 :                     throw std::runtime_error(std::string(__func__) + ": New cached derived xpub does not match already cached derived xpub");
    2476                 :             :                 }
    2477                 :           0 :                 continue;
    2478                 :             :             }
    2479         [ +  - ]:       18238 :             CacheDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, derived_xpub_pair.second);
    2480         [ +  - ]:       18238 :             diff.CacheDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, derived_xpub_pair.second);
    2481                 :             :         }
    2482                 :           0 :     }
    2483   [ +  -  +  +  :      395221 :     for (const auto& lh_xpub_pair : other.GetCachedLastHardenedExtPubKeys()) {
                   +  - ]
    2484         [ +  - ]:        2073 :         CExtPubKey xpub;
    2485   [ +  +  +  - ]:        2073 :         if (GetCachedLastHardenedExtPubKey(lh_xpub_pair.first, xpub)) {
    2486         [ -  + ]:        1430 :             if (xpub != lh_xpub_pair.second) {
    2487   [ #  #  #  # ]:           0 :                 throw std::runtime_error(std::string(__func__) + ": New cached last hardened xpub does not match already cached last hardened xpub");
    2488                 :             :             }
    2489                 :        1430 :             continue;
    2490                 :             :         }
    2491         [ +  - ]:         643 :         CacheLastHardenedExtPubKey(lh_xpub_pair.first, lh_xpub_pair.second);
    2492         [ +  - ]:         643 :         diff.CacheLastHardenedExtPubKey(lh_xpub_pair.first, lh_xpub_pair.second);
    2493                 :           0 :     }
    2494                 :      393148 :     return diff;
    2495                 :           0 : }
    2496                 :             : 
    2497                 :      831474 : ExtPubKeyMap DescriptorCache::GetCachedParentExtPubKeys() const
    2498                 :             : {
    2499                 :      831474 :     return m_parent_xpubs;
    2500                 :             : }
    2501                 :             : 
    2502                 :      831474 : std::unordered_map<uint32_t, ExtPubKeyMap> DescriptorCache::GetCachedDerivedExtPubKeys() const
    2503                 :             : {
    2504                 :      831474 :     return m_derived_xpubs;
    2505                 :             : }
    2506                 :             : 
    2507                 :      786296 : ExtPubKeyMap DescriptorCache::GetCachedLastHardenedExtPubKeys() const
    2508                 :             : {
    2509                 :      786296 :     return m_last_hardened_xpubs;
    2510                 :             : }
        

Generated by: LCOV version 2.0-1