LCOV - code coverage report
Current view: top level - src/script - descriptor.cpp (source / functions) Hit Total Coverage
Test: fuzz_coverage.info Lines: 552 1323 41.7 %
Date: 2023-11-10 23:46:46 Functions: 108 230 47.0 %
Branches: 535 2175 24.6 %

           Branch data     Line data    Source code
       1                 :            : // Copyright (c) 2018-2022 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/script.h>
      12                 :            : #include <script/signingprovider.h>
      13                 :            : #include <script/solver.h>
      14                 :            : #include <uint256.h>
      15                 :            : 
      16                 :            : #include <common/args.h>
      17                 :            : #include <span.h>
      18                 :            : #include <util/bip32.h>
      19                 :            : #include <util/check.h>
      20                 :            : #include <util/spanparsing.h>
      21                 :            : #include <util/strencodings.h>
      22                 :            : #include <util/vector.h>
      23                 :            : 
      24                 :            : #include <memory>
      25                 :            : #include <numeric>
      26                 :            : #include <optional>
      27                 :            : #include <string>
      28                 :            : #include <vector>
      29                 :            : 
      30                 :            : namespace {
      31                 :            : 
      32                 :            : ////////////////////////////////////////////////////////////////////////////
      33                 :            : // Checksum                                                               //
      34                 :            : ////////////////////////////////////////////////////////////////////////////
      35                 :            : 
      36                 :            : // This section implements a checksum algorithm for descriptors with the
      37                 :            : // following properties:
      38                 :            : // * Mistakes in a descriptor string are measured in "symbol errors". The higher
      39                 :            : //   the number of symbol errors, the harder it is to detect:
      40                 :            : //   * An error substituting a character from 0123456789()[],'/*abcdefgh@:$%{} for
      41                 :            : //     another in that set always counts as 1 symbol error.
      42                 :            : //     * Note that hex encoded keys are covered by these characters. Xprvs and
      43                 :            : //       xpubs use other characters too, but already have their own checksum
      44                 :            : //       mechanism.
      45                 :            : //     * Function names like "multi()" use other characters, but mistakes in
      46                 :            : //       these would generally result in an unparsable descriptor.
      47                 :            : //   * A case error always counts as 1 symbol error.
      48                 :            : //   * Any other 1 character substitution error counts as 1 or 2 symbol errors.
      49                 :            : // * Any 1 symbol error is always detected.
      50                 :            : // * Any 2 or 3 symbol error in a descriptor of up to 49154 characters is always detected.
      51                 :            : // * Any 4 symbol error in a descriptor of up to 507 characters is always detected.
      52                 :            : // * Any 5 symbol error in a descriptor of up to 77 characters is always detected.
      53                 :            : // * Is optimized to minimize the chance a 5 symbol error in a descriptor up to 387 characters is undetected
      54                 :            : // * Random errors have a chance of 1 in 2**40 of being undetected.
      55                 :            : //
      56                 :            : // These properties are achieved by expanding every group of 3 (non checksum) characters into
      57                 :            : // 4 GF(32) symbols, over which a cyclic code is defined.
      58                 :            : 
      59                 :            : /*
      60                 :            :  * Interprets c as 8 groups of 5 bits which are the coefficients of a degree 8 polynomial over GF(32),
      61                 :            :  * multiplies that polynomial by x, computes its remainder modulo a generator, and adds the constant term val.
      62                 :            :  *
      63                 :            :  * 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}.
      64                 :            :  * It is chosen to define an cyclic error detecting code which is selected by:
      65                 :            :  * - Starting from all BCH codes over GF(32) of degree 8 and below, which by construction guarantee detecting
      66                 :            :  *   3 errors in windows up to 19000 symbols.
      67                 :            :  * - Taking all those generators, and for degree 7 ones, extend them to degree 8 by adding all degree-1 factors.
      68                 :            :  * - Selecting just the set of generators that guarantee detecting 4 errors in a window of length 512.
      69                 :            :  * - Selecting one of those with best worst-case behavior for 5 errors in windows of length up to 512.
      70                 :            :  *
      71                 :            :  * The generator and the constants to implement it can be verified using this Sage code:
      72                 :            :  *   B = GF(2) # Binary field
      73                 :            :  *   BP.<b> = B[] # Polynomials over the binary field
      74                 :            :  *   F_mod = b**5 + b**3 + 1
      75                 :            :  *   F.<f> = GF(32, modulus=F_mod, repr='int') # GF(32) definition
      76                 :            :  *   FP.<x> = F[] # Polynomials over GF(32)
      77                 :            :  *   E_mod = x**3 + x + F.fetch_int(8)
      78                 :            :  *   E.<e> = F.extension(E_mod) # Extension field definition
      79                 :            :  *   alpha = e**2743 # Choice of an element in extension field
      80                 :            :  *   for p in divisors(E.order() - 1): # Verify alpha has order 32767.
      81                 :            :  *       assert((alpha**p == 1) == (p % 32767 == 0))
      82                 :            :  *   G = lcm([(alpha**i).minpoly() for i in [1056,1057,1058]] + [x + 1])
      83                 :            :  *   print(G) # Print out the generator
      84                 :            :  *   for i in [1,2,4,8,16]: # Print out {1,2,4,8,16}*(G mod x^8), packed in hex integers.
      85                 :            :  *       v = 0
      86                 :            :  *       for coef in reversed((F.fetch_int(i)*(G % x**8)).coefficients(sparse=True)):
      87                 :            :  *           v = v*32 + coef.integer_representation()
      88                 :            :  *       print("0x%x" % v)
      89                 :            :  */
      90                 :    6087912 : uint64_t PolyMod(uint64_t c, int val)
      91                 :            : {
      92                 :    6087912 :     uint8_t c0 = c >> 35;
      93                 :    6087912 :     c = ((c & 0x7ffffffff) << 5) ^ val;
      94         [ +  + ]:    6087912 :     if (c0 & 1) c ^= 0xf5dee51989;
      95         [ +  + ]:    6087912 :     if (c0 & 2) c ^= 0xa9fdca3312;
      96         [ +  + ]:    6087912 :     if (c0 & 4) c ^= 0x1bab10e32d;
      97         [ +  + ]:    6087912 :     if (c0 & 8) c ^= 0x3706b1677a;
      98         [ +  + ]:    6087912 :     if (c0 & 16) c ^= 0x644d626ffd;
      99                 :    6087912 :     return c;
     100                 :            : }
     101                 :            : 
     102                 :      33846 : std::string DescriptorChecksum(const Span<const char>& span)
     103                 :            : {
     104                 :            :     /** A character set designed such that:
     105                 :            :      *  - The most common 'unprotected' descriptor characters (hex, keypaths) are in the first group of 32.
     106                 :            :      *  - Case errors cause an offset that's a multiple of 32.
     107                 :            :      *  - As many alphabetic characters are in the same group (while following the above restrictions).
     108                 :            :      *
     109                 :            :      * If p(x) gives the position of a character c in this character set, every group of 3 characters
     110                 :            :      * (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).
     111                 :            :      * This means that changes that only affect the lower 5 bits of the position, or only the higher 2 bits, will just
     112                 :            :      * affect a single symbol.
     113                 :            :      *
     114                 :            :      * As a result, within-group-of-32 errors count as 1 symbol, as do cross-group errors that don't affect
     115                 :            :      * the position within the groups.
     116                 :            :      */
     117 [ +  + ][ -  + ]:      33847 :     static std::string INPUT_CHARSET =
     118         [ +  - ]:          1 :         "0123456789()[],'/*abcdefgh@:$%{}"
     119                 :            :         "IJKLMNOPQRSTUVWXYZ&+-.;<=>?!^_|~"
     120                 :            :         "ijklmnopqrstuvwxyzABCDEFGH`#\"\\ ";
     121                 :            : 
     122                 :            :     /** The character set for the checksum itself (same as bech32). */
     123 [ +  + ][ -  + ]:      33846 :     static std::string CHECKSUM_CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
                 [ -  + ]
     124                 :            : 
     125                 :      33846 :     uint64_t c = 1;
     126                 :      33846 :     int cls = 0;
     127                 :      33846 :     int clscount = 0;
     128         [ +  + ]:    4394493 :     for (auto ch : span) {
     129                 :    4360647 :         auto pos = INPUT_CHARSET.find(ch);
     130 [ +  - ][ #  # ]:    4360647 :         if (pos == std::string::npos) return "";
     131                 :    4360647 :         c = PolyMod(c, pos & 31); // Emit a symbol for the position inside the group, for every character.
     132                 :    4360647 :         cls = cls * 3 + (pos >> 5); // Accumulate the group numbers
     133         [ +  + ]:    4360647 :         if (++clscount == 3) {
     134                 :            :             // Emit an extra symbol representing the group numbers, for every 3 characters.
     135                 :    1450283 :             c = PolyMod(c, cls);
     136                 :    1450283 :             cls = 0;
     137                 :    1450283 :             clscount = 0;
     138                 :    1450283 :         }
     139                 :            :     }
     140         [ +  + ]:      33846 :     if (clscount > 0) c = PolyMod(c, cls);
     141         [ +  + ]:     304614 :     for (int j = 0; j < 8; ++j) c = PolyMod(c, 0); // Shift further to determine the checksum.
     142                 :      33846 :     c ^= 1; // Prevent appending zeroes from not affecting the checksum.
     143                 :            : 
     144         [ +  - ]:      33846 :     std::string ret(8, ' ');
     145 [ +  + ][ +  - ]:     304614 :     for (int j = 0; j < 8; ++j) ret[j] = CHECKSUM_CHARSET[(c >> (5 * (7 - j))) & 31];
                 [ +  - ]
     146                 :      33846 :     return ret;
     147         [ +  - ]:      67692 : }
     148                 :            : 
     149 [ +  - ][ +  - ]:      33837 : std::string AddChecksum(const std::string& str) { return str + "#" + DescriptorChecksum(str); }
                 [ -  + ]
     150                 :            : 
     151                 :            : ////////////////////////////////////////////////////////////////////////////
     152                 :            : // Internal representation                                                //
     153                 :            : ////////////////////////////////////////////////////////////////////////////
     154                 :            : 
     155                 :            : typedef std::vector<uint32_t> KeyPath;
     156                 :            : 
     157                 :            : /** Interface for public key objects in descriptors. */
     158                 :            : struct PubkeyProvider
     159                 :            : {
     160                 :            : protected:
     161                 :            :     //! Index of this key expression in the descriptor
     162                 :            :     //! E.g. If this PubkeyProvider is key1 in multi(2, key1, key2, key3), then m_expr_index = 0
     163                 :            :     uint32_t m_expr_index;
     164                 :            : 
     165                 :            : public:
     166                 :     837187 :     explicit PubkeyProvider(uint32_t exp_index) : m_expr_index(exp_index) {}
     167                 :            : 
     168                 :     837187 :     virtual ~PubkeyProvider() = default;
     169                 :            : 
     170                 :            :     /** Compare two public keys represented by this provider.
     171                 :            :      * Used by the Miniscript descriptors to check for duplicate keys in the script.
     172                 :            :      */
     173                 :          0 :     bool operator<(PubkeyProvider& other) const {
     174                 :          0 :         CPubKey a, b;
     175                 :          0 :         SigningProvider dummy;
     176                 :          0 :         KeyOriginInfo dummy_info;
     177                 :            : 
     178         [ #  # ]:          0 :         GetPubKey(0, dummy, a, dummy_info);
     179         [ #  # ]:          0 :         other.GetPubKey(0, dummy, b, dummy_info);
     180                 :            : 
     181                 :          0 :         return a < b;
     182                 :          0 :     }
     183                 :            : 
     184                 :            :     /** Derive a public key.
     185                 :            :      *  read_cache is the cache to read keys from (if not nullptr)
     186                 :            :      *  write_cache is the cache to write keys to (if not nullptr)
     187                 :            :      *  Caches are not exclusive but this is not tested. Currently we use them exclusively
     188                 :            :      */
     189                 :            :     virtual bool GetPubKey(int pos, const SigningProvider& arg, CPubKey& key, KeyOriginInfo& info, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const = 0;
     190                 :            : 
     191                 :            :     /** Whether this represent multiple public keys at different positions. */
     192                 :            :     virtual bool IsRange() const = 0;
     193                 :            : 
     194                 :            :     /** Get the size of the generated public key(s) in bytes (33 or 65). */
     195                 :            :     virtual size_t GetSize() const = 0;
     196                 :            : 
     197                 :            :     enum class StringType {
     198                 :            :         PUBLIC,
     199                 :            :         COMPAT // string calculation that mustn't change over time to stay compatible with previous software versions
     200                 :            :     };
     201                 :            : 
     202                 :            :     /** Get the descriptor string form. */
     203                 :            :     virtual std::string ToString(StringType type=StringType::PUBLIC) const = 0;
     204                 :            : 
     205                 :            :     /** Get the descriptor string form including private data (if available in arg). */
     206                 :            :     virtual bool ToPrivateString(const SigningProvider& arg, std::string& out) const = 0;
     207                 :            : 
     208                 :            :     /** Get the descriptor string form with the xpub at the last hardened derivation,
     209                 :            :      *  and always use h for hardened derivation.
     210                 :            :      */
     211                 :            :     virtual bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache = nullptr) const = 0;
     212                 :            : 
     213                 :            :     /** Derive a private key, if private data is available in arg. */
     214                 :            :     virtual bool GetPrivKey(int pos, const SigningProvider& arg, CKey& key) const = 0;
     215                 :            : };
     216                 :            : 
     217                 :          0 : class OriginPubkeyProvider final : public PubkeyProvider
     218                 :            : {
     219                 :            :     KeyOriginInfo m_origin;
     220                 :            :     std::unique_ptr<PubkeyProvider> m_provider;
     221                 :            :     bool m_apostrophe;
     222                 :            : 
     223                 :          0 :     std::string OriginString(StringType type, bool normalized=false) const
     224                 :            :     {
     225                 :            :         // If StringType==COMPAT, always use the apostrophe to stay compatible with previous versions
     226 [ #  # ][ #  # ]:          0 :         bool use_apostrophe = (!normalized && m_apostrophe) || type == StringType::COMPAT;
     227 [ #  # ][ #  # ]:          0 :         return HexStr(m_origin.fingerprint) + FormatHDKeypath(m_origin.path, use_apostrophe);
     228                 :          0 :     }
     229                 :            : 
     230                 :            : public:
     231                 :     418589 :     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) {}
     232                 :          0 :     bool GetPubKey(int pos, const SigningProvider& arg, CPubKey& key, KeyOriginInfo& info, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
     233                 :            :     {
     234         [ #  # ]:          0 :         if (!m_provider->GetPubKey(pos, arg, key, info, read_cache, write_cache)) return false;
     235                 :          0 :         std::copy(std::begin(m_origin.fingerprint), std::end(m_origin.fingerprint), info.fingerprint);
     236                 :          0 :         info.path.insert(info.path.begin(), m_origin.path.begin(), m_origin.path.end());
     237                 :          0 :         return true;
     238                 :          0 :     }
     239                 :          0 :     bool IsRange() const override { return m_provider->IsRange(); }
     240                 :        428 :     size_t GetSize() const override { return m_provider->GetSize(); }
     241 [ #  # ][ #  # ]:          0 :     std::string ToString(StringType type) const override { return "[" + OriginString(type) + "]" + m_provider->ToString(type); }
         [ #  # ][ #  # ]
     242                 :          0 :     bool ToPrivateString(const SigningProvider& arg, std::string& ret) const override
     243                 :            :     {
     244                 :          0 :         std::string sub;
     245 [ #  # ][ #  # ]:          0 :         if (!m_provider->ToPrivateString(arg, sub)) return false;
     246 [ #  # ][ #  # ]:          0 :         ret = "[" + OriginString(StringType::PUBLIC) + "]" + std::move(sub);
         [ #  # ][ #  # ]
     247                 :          0 :         return true;
     248                 :          0 :     }
     249                 :          0 :     bool ToNormalizedString(const SigningProvider& arg, std::string& ret, const DescriptorCache* cache) const override
     250                 :            :     {
     251                 :          0 :         std::string sub;
     252 [ #  # ][ #  # ]:          0 :         if (!m_provider->ToNormalizedString(arg, sub, cache)) return false;
     253                 :            :         // If m_provider is a BIP32PubkeyProvider, we may get a string formatted like a OriginPubkeyProvider
     254                 :            :         // In that case, we need to strip out the leading square bracket and fingerprint from the substring,
     255                 :            :         // and append that to our own origin string.
     256 [ #  # ][ #  # ]:          0 :         if (sub[0] == '[') {
     257         [ #  # ]:          0 :             sub = sub.substr(9);
     258 [ #  # ][ #  # ]:          0 :             ret = "[" + OriginString(StringType::PUBLIC, /*normalized=*/true) + std::move(sub);
                 [ #  # ]
     259                 :          0 :         } else {
     260 [ #  # ][ #  # ]:          0 :             ret = "[" + OriginString(StringType::PUBLIC, /*normalized=*/true) + "]" + std::move(sub);
         [ #  # ][ #  # ]
     261                 :            :         }
     262                 :          0 :         return true;
     263                 :          0 :     }
     264                 :          0 :     bool GetPrivKey(int pos, const SigningProvider& arg, CKey& key) const override
     265                 :            :     {
     266                 :          0 :         return m_provider->GetPrivKey(pos, arg, key);
     267                 :            :     }
     268                 :            : };
     269                 :            : 
     270                 :            : /** An object representing a parsed constant public key in a descriptor. */
     271                 :          0 : class ConstPubkeyProvider final : public PubkeyProvider
     272                 :            : {
     273                 :            :     CPubKey m_pubkey;
     274                 :            :     bool m_xonly;
     275                 :            : 
     276                 :            : public:
     277                 :     418590 :     ConstPubkeyProvider(uint32_t exp_index, const CPubKey& pubkey, bool xonly) : PubkeyProvider(exp_index), m_pubkey(pubkey), m_xonly(xonly) {}
     278                 :          2 :     bool GetPubKey(int pos, const SigningProvider& arg, CPubKey& key, KeyOriginInfo& info, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
     279                 :            :     {
     280                 :          2 :         key = m_pubkey;
     281                 :          2 :         info.path.clear();
     282                 :          2 :         CKeyID keyid = m_pubkey.GetID();
     283                 :          2 :         std::copy(keyid.begin(), keyid.begin() + sizeof(info.fingerprint), info.fingerprint);
     284                 :          2 :         return true;
     285                 :            :     }
     286                 :        152 :     bool IsRange() const override { return false; }
     287                 :        428 :     size_t GetSize() const override { return m_pubkey.size(); }
     288 [ +  - ][ #  # ]:        465 :     std::string ToString(StringType type) const override { return m_xonly ? HexStr(m_pubkey).substr(2) : HexStr(m_pubkey); }
         [ +  - ][ +  - ]
         [ +  - ][ #  # ]
     289                 :          0 :     bool ToPrivateString(const SigningProvider& arg, std::string& ret) const override
     290                 :            :     {
     291                 :          0 :         CKey key;
     292         [ #  # ]:          0 :         if (m_xonly) {
     293 [ #  # ][ #  # ]:          0 :             for (const auto& keyid : XOnlyPubKey(m_pubkey).GetKeyIDs()) {
                 [ #  # ]
     294         [ #  # ]:          0 :                 arg.GetKey(keyid, key);
     295 [ #  # ][ #  # ]:          0 :                 if (key.IsValid()) break;
     296                 :            :             }
     297                 :          0 :         } else {
     298 [ #  # ][ #  # ]:          0 :             arg.GetKey(m_pubkey.GetID(), key);
     299                 :            :         }
     300 [ #  # ][ #  # ]:          0 :         if (!key.IsValid()) return false;
     301         [ #  # ]:          0 :         ret = EncodeSecret(key);
     302                 :          0 :         return true;
     303                 :          0 :     }
     304                 :          0 :     bool ToNormalizedString(const SigningProvider& arg, std::string& ret, const DescriptorCache* cache) const override
     305                 :            :     {
     306                 :          0 :         ret = ToString(StringType::PUBLIC);
     307                 :          0 :         return true;
     308                 :            :     }
     309                 :       6028 :     bool GetPrivKey(int pos, const SigningProvider& arg, CKey& key) const override
     310                 :            :     {
     311                 :       6028 :         return arg.GetKey(m_pubkey.GetID(), key);
     312                 :            :     }
     313                 :            : };
     314                 :            : 
     315                 :            : enum class DeriveType {
     316                 :            :     NO,
     317                 :            :     UNHARDENED,
     318                 :            :     HARDENED,
     319                 :            : };
     320                 :            : 
     321                 :            : /** An object representing a parsed extended public key in a descriptor. */
     322                 :          0 : class BIP32PubkeyProvider final : public PubkeyProvider
     323                 :            : {
     324                 :            :     // Root xpub, path, and final derivation step type being used, if any
     325                 :            :     CExtPubKey m_root_extkey;
     326         [ +  - ]:          2 :     KeyPath m_path;
     327                 :            :     DeriveType m_derive;
     328 [ +  - ][ -  + ]:          2 :     // Whether ' or h is used in harded derivation
         [ +  - ][ +  - ]
     329                 :            :     bool m_apostrophe;
     330         [ +  - ]:          2 : 
     331                 :          8 :     bool GetExtKey(const SigningProvider& arg, CExtKey& ret) const
     332                 :          2 :     {
     333                 :          8 :         CKey key;
     334 [ +  - ][ +  - ]:         10 :         if (!arg.GetKey(m_root_extkey.pubkey.GetID(), key)) return false;
         [ +  - ][ +  - ]
                 [ +  - ]
     335                 :          8 :         ret.nDepth = m_root_extkey.nDepth;
     336         [ +  - ]:          8 :         std::copy(m_root_extkey.vchFingerprint, m_root_extkey.vchFingerprint + sizeof(ret.vchFingerprint), ret.vchFingerprint);
     337                 :          8 :         ret.nChild = m_root_extkey.nChild;
     338                 :          8 :         ret.chaincode = m_root_extkey.chaincode;
     339         [ +  - ]:          8 :         ret.key = key;
     340                 :          8 :         return true;
     341                 :          8 :     }
     342                 :            : 
     343                 :            :     // Derives the last xprv
     344                 :          8 :     bool GetDerivedExtKey(const SigningProvider& arg, CExtKey& xprv, CExtKey& last_hardened) const
     345                 :            :     {
     346         [ -  + ]:          8 :         if (!GetExtKey(arg, xprv)) return false;
     347         [ +  + ]:         40 :         for (auto entry : m_path) {
     348         [ -  + ]:         32 :             if (!xprv.Derive(xprv, entry)) return false;
     349         [ +  + ]:         32 :             if (entry >> 31) {
     350                 :         24 :                 last_hardened = xprv;
     351                 :         24 :             }
     352                 :            :         }
     353                 :          8 :         return true;
     354                 :          8 :     }
     355                 :            : 
     356                 :          8 :     bool IsHardened() const
     357                 :            :     {
     358         [ -  + ]:          8 :         if (m_derive == DeriveType::HARDENED) return true;
     359         [ +  - ]:          8 :         for (auto entry : m_path) {
     360         [ +  - ]:          8 :             if (entry >> 31) return true;
     361                 :            :         }
     362                 :          0 :         return false;
     363                 :          8 :     }
     364                 :            : 
     365                 :            : public:
     366                 :          8 :     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) {}
     367                 :      44436 :     bool IsRange() const override { return m_derive != DeriveType::NO; }
     368                 :          0 :     size_t GetSize() const override { return 33; }
     369                 :      18926 :     bool GetPubKey(int pos, const SigningProvider& arg, CPubKey& key_out, KeyOriginInfo& final_info_out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
     370                 :            :     {
     371                 :            :         // Info of parent of the to be derived pubkey
     372                 :      18926 :         KeyOriginInfo parent_info;
     373         [ +  - ]:      18926 :         CKeyID keyid = m_root_extkey.pubkey.GetID();
     374         [ +  - ]:      18926 :         std::copy(keyid.begin(), keyid.begin() + sizeof(parent_info.fingerprint), parent_info.fingerprint);
     375         [ +  - ]:      18926 :         parent_info.path = m_path;
     376                 :            : 
     377                 :            :         // Info of the derived key itself which is copied out upon successful completion
     378         [ +  - ]:      18926 :         KeyOriginInfo final_info_out_tmp = parent_info;
     379 [ +  - ][ +  - ]:      18926 :         if (m_derive == DeriveType::UNHARDENED) final_info_out_tmp.path.push_back((uint32_t)pos);
     380 [ -  + ][ #  # ]:      18926 :         if (m_derive == DeriveType::HARDENED) final_info_out_tmp.path.push_back(((uint32_t)pos) | 0x80000000L);
     381                 :            : 
     382                 :            :         // Derive keys or fetch them from cache
     383                 :      18926 :         CExtPubKey final_extkey = m_root_extkey;
     384                 :      18926 :         CExtPubKey parent_extkey = m_root_extkey;
     385         [ +  - ]:      18926 :         CExtPubKey last_hardened_extkey;
     386                 :      18926 :         bool der = true;
     387         [ +  + ]:      18926 :         if (read_cache) {
     388 [ +  - ][ -  + ]:      18918 :             if (!read_cache->GetCachedDerivedExtPubKey(m_expr_index, pos, final_extkey)) {
     389         [ +  - ]:      18918 :                 if (m_derive == DeriveType::HARDENED) return false;
     390                 :            :                 // Try to get the derivation parent
     391 [ +  - ][ +  + ]:      18918 :                 if (!read_cache->GetCachedParentExtPubKey(m_expr_index, parent_extkey)) return false;
     392                 :      18910 :                 final_extkey = parent_extkey;
     393 [ +  - ][ +  - ]:      18910 :                 if (m_derive == DeriveType::UNHARDENED) der = parent_extkey.Derive(final_extkey, pos);
     394                 :      18910 :             }
     395 [ +  - ][ +  - ]:      18918 :         } else if (IsHardened()) {
     396         [ +  - ]:          8 :             CExtKey xprv;
     397         [ +  - ]:          8 :             CExtKey lh_xprv;
     398 [ +  - ][ +  - ]:          8 :             if (!GetDerivedExtKey(arg, xprv, lh_xprv)) return false;
     399         [ +  - ]:          8 :             parent_extkey = xprv.Neuter();
     400 [ +  - ][ +  - ]:          8 :             if (m_derive == DeriveType::UNHARDENED) der = xprv.Derive(xprv, pos);
     401 [ -  + ][ #  # ]:          8 :             if (m_derive == DeriveType::HARDENED) der = xprv.Derive(xprv, pos | 0x80000000UL);
     402         [ +  - ]:          8 :             final_extkey = xprv.Neuter();
     403         [ +  - ]:          8 :             if (lh_xprv.key.IsValid()) {
     404         [ +  - ]:          8 :                 last_hardened_extkey = lh_xprv.Neuter();
     405                 :          8 :             }
     406         [ -  + ]:          8 :         } else {
     407         [ #  # ]:          0 :             for (auto entry : m_path) {
     408 [ #  # ][ #  # ]:          0 :                 if (!parent_extkey.Derive(parent_extkey, entry)) return false;
     409                 :            :             }
     410                 :          0 :             final_extkey = parent_extkey;
     411 [ #  # ][ #  # ]:          0 :             if (m_derive == DeriveType::UNHARDENED) der = parent_extkey.Derive(final_extkey, pos);
     412         [ #  # ]:          0 :             assert(m_derive != DeriveType::HARDENED);
     413                 :            :         }
     414         [ +  - ]:      18918 :         if (!der) return false;
     415                 :            : 
     416         [ +  - ]:      18918 :         final_info_out = final_info_out_tmp;
     417                 :      18918 :         key_out = final_extkey.pubkey;
     418                 :            : 
     419         [ +  + ]:      18918 :         if (write_cache) {
     420                 :            :             // Only cache parent if there is any unhardened derivation
     421         [ +  - ]:          8 :             if (m_derive != DeriveType::HARDENED) {
     422         [ +  - ]:          8 :                 write_cache->CacheParentExtPubKey(m_expr_index, parent_extkey);
     423                 :            :                 // Cache last hardened xpub if we have it
     424 [ +  - ][ +  - ]:          8 :                 if (last_hardened_extkey.pubkey.IsValid()) {
     425         [ +  - ]:          8 :                     write_cache->CacheLastHardenedExtPubKey(m_expr_index, last_hardened_extkey);
     426                 :          8 :                 }
     427         [ #  # ]:          8 :             } else if (final_info_out.path.size() > 0) {
     428         [ #  # ]:          0 :                 write_cache->CacheDerivedExtPubKey(m_expr_index, pos, final_extkey);
     429                 :          0 :             }
     430                 :          8 :         }
     431                 :            : 
     432                 :      18918 :         return true;
     433                 :      18926 :     }
     434                 :      33372 :     std::string ToString(StringType type, bool normalized) const
     435                 :            :     {
     436                 :            :         // If StringType==COMPAT, always use the apostrophe to stay compatible with previous versions
     437 [ +  - ][ -  + ]:      33372 :         const bool use_apostrophe = (!normalized && m_apostrophe) || type == StringType::COMPAT;
     438 [ +  - ][ +  - ]:      33372 :         std::string ret = EncodeExtPubKey(m_root_extkey) + FormatHDKeypath(m_path, /*apostrophe=*/use_apostrophe);
     439         [ -  + ]:      33372 :         if (IsRange()) {
     440         [ +  - ]:      33372 :             ret += "/*";
     441 [ -  + ][ #  # ]:      33372 :             if (m_derive == DeriveType::HARDENED) ret += use_apostrophe ? '\'' : 'h';
     442                 :      33372 :         }
     443                 :      33372 :         return ret;
     444         [ +  - ]:      33372 :     }
     445                 :      33372 :     std::string ToString(StringType type=StringType::PUBLIC) const override
     446                 :            :     {
     447                 :      33372 :         return ToString(type, /*normalized=*/false);
     448                 :            :     }
     449                 :          0 :     bool ToPrivateString(const SigningProvider& arg, std::string& out) const override
     450                 :            :     {
     451                 :          0 :         CExtKey key;
     452 [ #  # ][ #  # ]:          0 :         if (!GetExtKey(arg, key)) return false;
     453 [ #  # ][ #  # ]:          0 :         out = EncodeExtKey(key) + FormatHDKeypath(m_path, /*apostrophe=*/m_apostrophe);
                 [ #  # ]
     454         [ #  # ]:          0 :         if (IsRange()) {
     455         [ #  # ]:          0 :             out += "/*";
     456 [ #  # ][ #  # ]:          0 :             if (m_derive == DeriveType::HARDENED) out += m_apostrophe ? '\'' : 'h';
     457                 :          0 :         }
     458                 :          0 :         return true;
     459                 :          0 :     }
     460                 :          0 :     bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache) const override
     461                 :            :     {
     462         [ #  # ]:          0 :         if (m_derive == DeriveType::HARDENED) {
     463                 :          0 :             out = ToString(StringType::PUBLIC, /*normalized=*/true);
     464                 :            : 
     465                 :          0 :             return true;
     466                 :            :         }
     467                 :            :         // Step backwards to find the last hardened step in the path
     468                 :          0 :         int i = (int)m_path.size() - 1;
     469         [ #  # ]:          0 :         for (; i >= 0; --i) {
     470         [ #  # ]:          0 :             if (m_path.at(i) >> 31) {
     471                 :          0 :                 break;
     472                 :            :             }
     473                 :          0 :         }
     474                 :            :         // Either no derivation or all unhardened derivation
     475         [ #  # ]:          0 :         if (i == -1) {
     476                 :          0 :             out = ToString();
     477                 :          0 :             return true;
     478                 :            :         }
     479                 :            :         // Get the path to the last hardened stup
     480                 :          0 :         KeyOriginInfo origin;
     481                 :          0 :         int k = 0;
     482         [ #  # ]:          0 :         for (; k <= i; ++k) {
     483                 :            :             // Add to the path
     484 [ #  # ][ #  # ]:          0 :             origin.path.push_back(m_path.at(k));
     485                 :          0 :         }
     486                 :            :         // Build the remaining path
     487                 :          0 :         KeyPath end_path;
     488         [ #  # ]:          0 :         for (; k < (int)m_path.size(); ++k) {
     489 [ #  # ][ #  # ]:          0 :             end_path.push_back(m_path.at(k));
     490                 :          0 :         }
     491                 :            :         // Get the fingerprint
     492         [ #  # ]:          0 :         CKeyID id = m_root_extkey.pubkey.GetID();
     493         [ #  # ]:          0 :         std::copy(id.begin(), id.begin() + 4, origin.fingerprint);
     494                 :            : 
     495         [ #  # ]:          0 :         CExtPubKey xpub;
     496         [ #  # ]:          0 :         CExtKey lh_xprv;
     497                 :            :         // If we have the cache, just get the parent xpub
     498         [ #  # ]:          0 :         if (cache != nullptr) {
     499         [ #  # ]:          0 :             cache->GetCachedLastHardenedExtPubKey(m_expr_index, xpub);
     500                 :          0 :         }
     501 [ #  # ][ #  # ]:          0 :         if (!xpub.pubkey.IsValid()) {
     502                 :            :             // Cache miss, or nor cache, or need privkey
     503         [ #  # ]:          0 :             CExtKey xprv;
     504 [ #  # ][ #  # ]:          0 :             if (!GetDerivedExtKey(arg, xprv, lh_xprv)) return false;
     505         [ #  # ]:          0 :             xpub = lh_xprv.Neuter();
     506         [ #  # ]:          0 :         }
     507 [ #  # ][ #  # ]:          0 :         assert(xpub.pubkey.IsValid());
     508                 :            : 
     509                 :            :         // Build the string
     510 [ #  # ][ #  # ]:          0 :         std::string origin_str = HexStr(origin.fingerprint) + FormatHDKeypath(origin.path);
                 [ #  # ]
     511 [ #  # ][ #  # ]:          0 :         out = "[" + origin_str + "]" + EncodeExtPubKey(xpub) + FormatHDKeypath(end_path);
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
     512         [ #  # ]:          0 :         if (IsRange()) {
     513         [ #  # ]:          0 :             out += "/*";
     514         [ #  # ]:          0 :             assert(m_derive == DeriveType::UNHARDENED);
     515                 :          0 :         }
     516                 :          0 :         return true;
     517                 :          0 :     }
     518                 :          0 :     bool GetPrivKey(int pos, const SigningProvider& arg, CKey& key) const override
     519                 :            :     {
     520                 :          0 :         CExtKey extkey;
     521         [ #  # ]:          0 :         CExtKey dummy;
     522 [ #  # ][ #  # ]:          0 :         if (!GetDerivedExtKey(arg, extkey, dummy)) return false;
     523 [ #  # ][ #  # ]:          0 :         if (m_derive == DeriveType::UNHARDENED && !extkey.Derive(extkey, pos)) return false;
                 [ #  # ]
     524 [ #  # ][ #  # ]:          0 :         if (m_derive == DeriveType::HARDENED && !extkey.Derive(extkey, pos | 0x80000000UL)) return false;
                 [ #  # ]
     525         [ #  # ]:          0 :         key = extkey.key;
     526                 :          0 :         return true;
     527                 :          0 :     }
     528                 :            : };
     529                 :            : 
     530                 :            : /** Base class for all Descriptor implementations. */
     531                 :          0 : class DescriptorImpl : public Descriptor
     532                 :            : {
     533                 :            : protected:
     534                 :            :     //! Public key arguments for this descriptor (size 1 for PK, PKH, WPKH; any size for WSH and Multisig).
     535                 :            :     const std::vector<std::unique_ptr<PubkeyProvider>> m_pubkey_args;
     536                 :            :     //! The string name of the descriptor function.
     537                 :            :     const std::string m_name;
     538                 :            : 
     539                 :            :     //! The sub-descriptor arguments (empty for everything but SH and WSH).
     540                 :            :     //! In doc/descriptors.m this is referred to as SCRIPT expressions sh(SCRIPT)
     541                 :            :     //! and wsh(SCRIPT), and distinct from KEY expressions and ADDR expressions.
     542                 :            :     //! Subdescriptors can only ever generate a single script.
     543                 :            :     const std::vector<std::unique_ptr<DescriptorImpl>> m_subdescriptor_args;
     544                 :            : 
     545                 :            :     //! Return a serialization of anything except pubkey and script arguments, to be prepended to those.
     546         [ +  - ]:      35717 :     virtual std::string ToStringExtra() const { return ""; }
     547                 :            : 
     548                 :            :     /** A helper function to construct the scripts for this descriptor.
     549                 :            :      *
     550                 :            :      *  This function is invoked once by ExpandHelper.
     551                 :            :      *
     552                 :            :      *  @param pubkeys The evaluations of the m_pubkey_args field.
     553                 :            :      *  @param scripts The evaluations of m_subdescriptor_args (one for each m_subdescriptor_args element).
     554                 :            :      *  @param out A FlatSigningProvider to put scripts or public keys in that are necessary to the solver.
     555                 :            :      *             The origin info of the provided pubkeys is automatically added.
     556                 :            :      *  @return A vector with scriptPubKeys for this descriptor.
     557                 :            :      */
     558                 :            :     virtual std::vector<CScript> MakeScripts(const std::vector<CPubKey>& pubkeys, Span<const CScript> scripts, FlatSigningProvider& out) const = 0;
     559                 :            : 
     560                 :            : public:
     561         [ +  - ]:     414240 :     DescriptorImpl(std::vector<std::unique_ptr<PubkeyProvider>> pubkeys, const std::string& name) : m_pubkey_args(std::move(pubkeys)), m_name(name), m_subdescriptor_args() {}
     562 [ +  - ][ -  + ]:        290 :     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))) {}
     563         [ +  - ]:       4358 :     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)) {}
     564                 :            : 
     565                 :            :     enum class StringType
     566                 :            :     {
     567                 :            :         PUBLIC,
     568                 :            :         PRIVATE,
     569                 :            :         NORMALIZED,
     570                 :            :         COMPAT, // string calculation that mustn't change over time to stay compatible with previous software versions
     571                 :            :     };
     572                 :            : 
     573                 :          0 :     bool IsSolvable() const override
     574                 :            :     {
     575         [ #  # ]:          0 :         for (const auto& arg : m_subdescriptor_args) {
     576         [ #  # ]:          0 :             if (!arg->IsSolvable()) return false;
     577                 :            :         }
     578                 :          0 :         return true;
     579                 :          0 :     }
     580                 :            : 
     581                 :      11778 :     bool IsRange() const final
     582                 :            :     {
     583         [ +  + ]:      11930 :         for (const auto& pubkey : m_pubkey_args) {
     584         [ +  + ]:      11216 :             if (pubkey->IsRange()) return true;
     585                 :            :         }
     586         [ +  + ]:        714 :         for (const auto& arg : m_subdescriptor_args) {
     587         [ +  - ]:        562 :             if (arg->IsRange()) return true;
     588                 :            :         }
     589                 :        152 :         return false;
     590                 :      11778 :     }
     591                 :            : 
     592                 :       9969 :     virtual bool ToStringSubScriptHelper(const SigningProvider* arg, std::string& ret, const StringType type, const DescriptorCache* cache = nullptr) const
     593                 :            :     {
     594                 :       9969 :         size_t pos = 0;
     595         [ +  + ]:      11849 :         for (const auto& scriptarg : m_subdescriptor_args) {
     596         [ +  - ]:       1880 :             if (pos++) ret += ",";
     597                 :       1880 :             std::string tmp;
     598 [ +  - ][ +  - ]:       1880 :             if (!scriptarg->ToStringHelper(arg, tmp, type, cache)) return false;
     599         [ +  - ]:       1880 :             ret += tmp;
     600      [ -  -  + ]:       1880 :         }
     601                 :       9969 :         return true;
     602                 :       9969 :     }
     603                 :            : 
     604                 :      35717 :     virtual bool ToStringHelper(const SigningProvider* arg, std::string& out, const StringType type, const DescriptorCache* cache = nullptr) const
     605                 :            :     {
     606                 :      35717 :         std::string extra = ToStringExtra();
     607                 :      35717 :         size_t pos = extra.size() > 0 ? 1 : 0;
     608 [ +  - ][ +  - ]:      35717 :         std::string ret = m_name + "(" + extra;
     609         [ +  + ]:      69554 :         for (const auto& pubkey : m_pubkey_args) {
     610 [ +  - ][ #  # ]:      33837 :             if (pos++) ret += ",";
     611                 :      33837 :             std::string tmp;
     612   [ -  -  +  +  :      33837 :             switch (type) {
                      - ]
     613                 :            :                 case StringType::NORMALIZED:
     614 [ #  # ][ #  # ]:          0 :                     if (!pubkey->ToNormalizedString(*arg, tmp, cache)) return false;
     615                 :          0 :                     break;
     616                 :            :                 case StringType::PRIVATE:
     617 [ #  # ][ #  # ]:          0 :                     if (!pubkey->ToPrivateString(*arg, tmp)) return false;
     618                 :          0 :                     break;
     619                 :            :                 case StringType::PUBLIC:
     620         [ +  - ]:      14074 :                     tmp = pubkey->ToString();
     621                 :      14074 :                     break;
     622                 :            :                 case StringType::COMPAT:
     623         [ +  - ]:      19763 :                     tmp = pubkey->ToString(PubkeyProvider::StringType::COMPAT);
     624                 :      19763 :                     break;
     625                 :            :             }
     626         [ +  - ]:      33837 :             ret += tmp;
     627         [ -  + ]:      33837 :         }
     628                 :      35717 :         std::string subscript;
     629 [ +  - ][ +  - ]:      35717 :         if (!ToStringSubScriptHelper(arg, subscript, type, cache)) return false;
     630 [ +  + ][ -  + ]:      35717 :         if (pos && subscript.size()) ret += ',';
                 [ #  # ]
     631 [ +  - ][ -  + ]:      35717 :         out = std::move(ret) + std::move(subscript) + ")";
     632                 :      35717 :         return true;
     633                 :      35717 :     }
     634                 :            : 
     635                 :      33837 :     std::string ToString(bool compat_format) const final
     636                 :            :     {
     637                 :      33837 :         std::string ret;
     638         [ +  - ]:      33837 :         ToStringHelper(nullptr, ret, compat_format ? StringType::COMPAT : StringType::PUBLIC);
     639         [ +  - ]:      33837 :         return AddChecksum(ret);
     640                 :      33837 :     }
     641                 :            : 
     642                 :          0 :     bool ToPrivateString(const SigningProvider& arg, std::string& out) const override
     643                 :            :     {
     644                 :          0 :         bool ret = ToStringHelper(&arg, out, StringType::PRIVATE);
     645                 :          0 :         out = AddChecksum(out);
     646                 :          0 :         return ret;
     647                 :            :     }
     648                 :            : 
     649                 :          0 :     bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache) const override final
     650                 :            :     {
     651                 :          0 :         bool ret = ToStringHelper(&arg, out, StringType::NORMALIZED, cache);
     652                 :          0 :         out = AddChecksum(out);
     653                 :          0 :         return ret;
     654                 :            :     }
     655                 :            : 
     656                 :      21307 :     bool ExpandHelper(int pos, const SigningProvider& arg, const DescriptorCache* read_cache, std::vector<CScript>& output_scripts, FlatSigningProvider& out, DescriptorCache* write_cache) const
     657                 :            :     {
     658                 :      21307 :         std::vector<std::pair<CPubKey, KeyOriginInfo>> entries;
     659         [ +  - ]:      21307 :         entries.reserve(m_pubkey_args.size());
     660                 :            : 
     661                 :            :         // Construct temporary data in `entries`, `subscripts`, and `subprovider` to avoid producing output in case of failure.
     662         [ +  + ]:      40227 :         for (const auto& p : m_pubkey_args) {
     663         [ +  - ]:      18928 :             entries.emplace_back();
     664 [ +  - ][ +  + ]:      18928 :             if (!p->GetPubKey(pos, arg, entries.back().first, entries.back().second, read_cache, write_cache)) return false;
     665                 :            :         }
     666                 :      21299 :         std::vector<CScript> subscripts;
     667                 :      21299 :         FlatSigningProvider subprovider;
     668         [ +  + ]:      23676 :         for (const auto& subarg : m_subdescriptor_args) {
     669                 :       2379 :             std::vector<CScript> outscripts;
     670 [ +  - ][ +  + ]:       2379 :             if (!subarg->ExpandHelper(pos, arg, read_cache, outscripts, subprovider, write_cache)) return false;
     671         [ +  - ]:       2377 :             assert(outscripts.size() == 1);
     672         [ +  - ]:       2377 :             subscripts.emplace_back(std::move(outscripts[0]));
     673         [ +  + ]:       2379 :         }
     674         [ -  + ]:      21297 :         out.Merge(std::move(subprovider));
     675                 :            : 
     676                 :      21297 :         std::vector<CPubKey> pubkeys;
     677         [ +  - ]:      21297 :         pubkeys.reserve(entries.size());
     678         [ +  + ]:      40217 :         for (auto& entry : entries) {
     679         [ +  - ]:      18920 :             pubkeys.push_back(entry.first);
     680 [ +  - ][ +  - ]:      18920 :             out.origins.emplace(entry.first.GetID(), std::make_pair<CPubKey, KeyOriginInfo>(CPubKey(entry.first), std::move(entry.second)));
                 [ +  - ]
     681                 :            :         }
     682                 :            : 
     683 [ +  - ][ +  - ]:      21297 :         output_scripts = MakeScripts(pubkeys, Span{subscripts}, out);
     684                 :      21297 :         return true;
     685                 :      21307 :     }
     686                 :            : 
     687                 :          8 :     bool Expand(int pos, const SigningProvider& provider, std::vector<CScript>& output_scripts, FlatSigningProvider& out, DescriptorCache* write_cache = nullptr) const final
     688                 :            :     {
     689                 :          8 :         return ExpandHelper(pos, provider, nullptr, output_scripts, out, write_cache);
     690                 :            :     }
     691                 :            : 
     692                 :      18920 :     bool ExpandFromCache(int pos, const DescriptorCache& read_cache, std::vector<CScript>& output_scripts, FlatSigningProvider& out) const final
     693                 :            :     {
     694                 :      18920 :         return ExpandHelper(pos, DUMMY_SIGNING_PROVIDER, &read_cache, output_scripts, out, nullptr);
     695                 :            :     }
     696                 :            : 
     697                 :       6028 :     void ExpandPrivate(int pos, const SigningProvider& provider, FlatSigningProvider& out) const final
     698                 :            :     {
     699         [ +  + ]:      12056 :         for (const auto& p : m_pubkey_args) {
     700                 :       6028 :             CKey key;
     701 [ +  - ][ +  - ]:       6028 :             if (!p->GetPrivKey(pos, provider, key)) continue;
     702 [ +  - ][ +  - ]:       6028 :             out.keys.emplace(key.GetPubKey().GetID(), key);
                 [ +  - ]
     703      [ -  -  + ]:       6028 :         }
     704         [ -  + ]:       6028 :         for (const auto& arg : m_subdescriptor_args) {
     705                 :          0 :             arg->ExpandPrivate(pos, provider, out);
     706                 :            :         }
     707                 :       6028 :     }
     708                 :            : 
     709                 :     412903 :     std::optional<OutputType> GetOutputType() const override { return std::nullopt; }
     710                 :            : 
     711                 :          0 :     std::optional<int64_t> ScriptSize() const override { return {}; }
     712                 :            : 
     713                 :            :     /** A helper for MaxSatisfactionWeight.
     714                 :            :      *
     715                 :            :      * @param use_max_sig Whether to assume ECDSA signatures will have a high-r.
     716                 :            :      * @return The maximum size of the satisfaction in raw bytes (with no witness meaning).
     717                 :            :      */
     718                 :          0 :     virtual std::optional<int64_t> MaxSatSize(bool use_max_sig) const { return {}; }
     719                 :            : 
     720                 :          0 :     std::optional<int64_t> MaxSatisfactionWeight(bool) const override { return {}; }
     721                 :            : 
     722                 :          0 :     std::optional<int64_t> MaxSatisfactionElems() const override { return {}; }
     723                 :            : };
     724                 :            : 
     725                 :            : /** A parsed addr(A) descriptor. */
     726                 :          0 : class AddressDescriptor final : public DescriptorImpl
     727                 :            : {
     728                 :            :     const CTxDestination m_destination;
     729                 :            : protected:
     730                 :          0 :     std::string ToStringExtra() const override { return EncodeDestination(m_destination); }
     731         [ #  # ]:          0 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, Span<const CScript>, FlatSigningProvider&) const override { return Vector(GetScriptForDestination(m_destination)); }
     732                 :            : public:
     733 [ #  # ][ #  # ]:          0 :     AddressDescriptor(CTxDestination destination) : DescriptorImpl({}, "addr"), m_destination(std::move(destination)) {}
     734                 :          0 :     bool IsSolvable() const final { return false; }
     735                 :            : 
     736                 :          0 :     std::optional<OutputType> GetOutputType() const override
     737                 :            :     {
     738                 :          0 :         return OutputTypeFromDestination(m_destination);
     739                 :            :     }
     740                 :          0 :     bool IsSingleType() const final { return true; }
     741                 :          0 :     bool ToPrivateString(const SigningProvider& arg, std::string& out) const final { return false; }
     742                 :            : 
     743         [ #  # ]:          0 :     std::optional<int64_t> ScriptSize() const override { return GetScriptForDestination(m_destination).size(); }
     744                 :            : };
     745                 :            : 
     746                 :            : /** A parsed raw(H) descriptor. */
     747                 :          0 : class RawDescriptor final : public DescriptorImpl
     748                 :            : {
     749                 :            :     const CScript m_script;
     750                 :            : protected:
     751                 :          0 :     std::string ToStringExtra() const override { return HexStr(m_script); }
     752                 :          0 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, Span<const CScript>, FlatSigningProvider&) const override { return Vector(m_script); }
     753                 :            : public:
     754 [ #  # ][ #  # ]:          0 :     RawDescriptor(CScript script) : DescriptorImpl({}, "raw"), m_script(std::move(script)) {}
     755                 :          0 :     bool IsSolvable() const final { return false; }
     756                 :            : 
     757                 :          0 :     std::optional<OutputType> GetOutputType() const override
     758                 :            :     {
     759                 :          0 :         CTxDestination dest;
     760         [ #  # ]:          0 :         ExtractDestination(m_script, dest);
     761         [ #  # ]:          0 :         return OutputTypeFromDestination(dest);
     762                 :          0 :     }
     763                 :          0 :     bool IsSingleType() const final { return true; }
     764                 :          0 :     bool ToPrivateString(const SigningProvider& arg, std::string& out) const final { return false; }
     765                 :            : 
     766                 :          0 :     std::optional<int64_t> ScriptSize() const override { return m_script.size(); }
     767                 :            : };
     768                 :            : 
     769                 :            : /** A parsed pk(P) descriptor. */
     770                 :          0 : class PKDescriptor final : public DescriptorImpl
     771                 :            : {
     772                 :            : private:
     773                 :            :     const bool m_xonly;
     774                 :            : protected:
     775                 :          0 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript>, FlatSigningProvider&) const override
     776                 :            :     {
     777         [ #  # ]:          0 :         if (m_xonly) {
     778 [ #  # ][ #  # ]:          0 :             CScript script = CScript() << ToByteVector(XOnlyPubKey(keys[0])) << OP_CHECKSIG;
         [ #  # ][ #  # ]
                 [ #  # ]
     779         [ #  # ]:          0 :             return Vector(std::move(script));
     780                 :          0 :         } else {
     781         [ #  # ]:          0 :             return Vector(GetScriptForRawPubKey(keys[0]));
     782                 :            :         }
     783                 :          0 :     }
     784                 :            : public:
     785 [ +  - ][ -  + ]:     412903 :     PKDescriptor(std::unique_ptr<PubkeyProvider> prov, bool xonly = false) : DescriptorImpl(Vector(std::move(prov)), "pk"), m_xonly(xonly) {}
     786                 :          0 :     bool IsSingleType() const final { return true; }
     787                 :            : 
     788                 :          0 :     std::optional<int64_t> ScriptSize() const override {
     789         [ #  # ]:          0 :         return 1 + (m_xonly ? 32 : m_pubkey_args[0]->GetSize()) + 1;
     790                 :            :     }
     791                 :            : 
     792                 :     361814 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
     793                 :     361814 :         const auto ecdsa_sig_size = use_max_sig ? 72 : 71;
     794         [ -  + ]:     361814 :         return 1 + (m_xonly ? 65 : ecdsa_sig_size);
     795                 :            :     }
     796                 :            : 
     797                 :     361814 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
     798                 :     361814 :         return *MaxSatSize(use_max_sig) * WITNESS_SCALE_FACTOR;
     799                 :            :     }
     800                 :            : 
     801                 :     361814 :     std::optional<int64_t> MaxSatisfactionElems() const override { return 1; }
     802                 :            : };
     803                 :            : 
     804                 :            : /** A parsed pkh(P) descriptor. */
     805                 :          0 : class PKHDescriptor final : public DescriptorImpl
     806                 :            : {
     807                 :            : protected:
     808                 :       3222 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript>, FlatSigningProvider& out) const override
     809                 :            :     {
     810                 :       3222 :         CKeyID id = keys[0].GetID();
     811                 :       3222 :         out.pubkeys.emplace(id, keys[0]);
     812 [ +  - ][ -  + ]:       3222 :         return Vector(GetScriptForDestination(PKHash(id)));
     813                 :          0 :     }
     814                 :            : public:
     815 [ +  - ][ -  + ]:        430 :     PKHDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "pkh") {}
     816                 :        849 :     std::optional<OutputType> GetOutputType() const override { return OutputType::LEGACY; }
     817                 :        842 :     bool IsSingleType() const final { return true; }
     818                 :            : 
     819                 :          0 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 1 + 20 + 1 + 1; }
     820                 :            : 
     821                 :        428 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
     822                 :        428 :         const auto sig_size = use_max_sig ? 72 : 71;
     823                 :        428 :         return 1 + sig_size + 1 + m_pubkey_args[0]->GetSize();
     824                 :            :     }
     825                 :            : 
     826                 :        428 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
     827                 :        428 :         return *MaxSatSize(use_max_sig) * WITNESS_SCALE_FACTOR;
     828                 :            :     }
     829                 :            : 
     830                 :        428 :     std::optional<int64_t> MaxSatisfactionElems() const override { return 2; }
     831                 :            : };
     832                 :            : 
     833                 :            : /** A parsed wpkh(P) descriptor. */
     834                 :          0 : class WPKHDescriptor final : public DescriptorImpl
     835                 :            : {
     836                 :            : protected:
     837                 :       5637 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript>, FlatSigningProvider& out) const override
     838                 :            :     {
     839                 :       5637 :         CKeyID id = keys[0].GetID();
     840                 :       5637 :         out.pubkeys.emplace(id, keys[0]);
     841 [ +  - ][ -  + ]:       5637 :         return Vector(GetScriptForDestination(WitnessV0KeyHash(id)));
     842                 :          0 :     }
     843                 :            : public:
     844 [ +  - ][ -  + ]:        906 :     WPKHDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "wpkh") {}
     845                 :       2073 :     std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32; }
     846                 :       1206 :     bool IsSingleType() const final { return true; }
     847                 :            : 
     848                 :        288 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 20; }
     849                 :            : 
     850                 :        902 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
     851                 :        902 :         const auto sig_size = use_max_sig ? 72 : 71;
     852                 :        902 :         return (1 + sig_size + 1 + 33);
     853                 :            :     }
     854                 :            : 
     855                 :        614 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
     856                 :        614 :         return MaxSatSize(use_max_sig);
     857                 :            :     }
     858                 :            : 
     859                 :        902 :     std::optional<int64_t> MaxSatisfactionElems() const override { return 2; }
     860                 :            : };
     861                 :            : 
     862                 :            : /** A parsed combo(P) descriptor. */
     863                 :          0 : class ComboDescriptor final : public DescriptorImpl
     864                 :            : {
     865                 :            : protected:
     866                 :          2 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript>, FlatSigningProvider& out) const override
     867                 :            :     {
     868                 :          2 :         std::vector<CScript> ret;
     869         [ +  - ]:          2 :         CKeyID id = keys[0].GetID();
     870         [ +  - ]:          2 :         out.pubkeys.emplace(id, keys[0]);
     871 [ +  - ][ +  - ]:          2 :         ret.emplace_back(GetScriptForRawPubKey(keys[0])); // P2PK
     872 [ +  - ][ +  - ]:          2 :         ret.emplace_back(GetScriptForDestination(PKHash(id))); // P2PKH
                 [ +  - ]
     873         [ +  - ]:          2 :         if (keys[0].IsCompressed()) {
     874 [ +  - ][ +  - ]:          2 :             CScript p2wpkh = GetScriptForDestination(WitnessV0KeyHash(id));
     875 [ +  - ][ +  - ]:          2 :             out.scripts.emplace(CScriptID(p2wpkh), p2wpkh);
     876         [ +  - ]:          2 :             ret.emplace_back(p2wpkh);
     877 [ +  - ][ +  - ]:          2 :             ret.emplace_back(GetScriptForDestination(ScriptHash(p2wpkh))); // P2SH-P2WPKH
                 [ -  + ]
     878                 :          2 :         }
     879                 :          2 :         return ret;
     880         [ +  - ]:          2 :     }
     881                 :            : public:
     882 [ +  - ][ -  + ]:          1 :     ComboDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "combo") {}
     883                 :          0 :     bool IsSingleType() const final { return false; }
     884                 :            : };
     885                 :            : 
     886                 :            : /** A parsed multi(...) or sortedmulti(...) descriptor */
     887                 :          0 : class MultisigDescriptor final : public DescriptorImpl
     888                 :            : {
     889                 :            :     const int m_threshold;
     890                 :            :     const bool m_sorted;
     891                 :            : protected:
     892                 :          0 :     std::string ToStringExtra() const override { return strprintf("%i", m_threshold); }
     893                 :          0 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript>, FlatSigningProvider&) const override {
     894         [ #  # ]:          0 :         if (m_sorted) {
     895                 :          0 :             std::vector<CPubKey> sorted_keys(keys);
     896         [ #  # ]:          0 :             std::sort(sorted_keys.begin(), sorted_keys.end());
     897 [ #  # ][ #  # ]:          0 :             return Vector(GetScriptForMultisig(m_threshold, sorted_keys));
     898                 :          0 :         }
     899         [ #  # ]:          0 :         return Vector(GetScriptForMultisig(m_threshold, keys));
     900                 :          0 :     }
     901                 :            : public:
     902 [ #  # ][ #  # ]:          0 :     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) {}
     903                 :          0 :     bool IsSingleType() const final { return true; }
     904                 :            : 
     905                 :          0 :     std::optional<int64_t> ScriptSize() const override {
     906                 :          0 :         const auto n_keys = m_pubkey_args.size();
     907                 :          0 :         auto op = [](int64_t acc, const std::unique_ptr<PubkeyProvider>& pk) { return acc + 1 + pk->GetSize();};
     908                 :          0 :         const auto pubkeys_size{std::accumulate(m_pubkey_args.begin(), m_pubkey_args.end(), int64_t{0}, op)};
     909 [ #  # ][ #  # ]:          0 :         return 1 + BuildScript(n_keys).size() + BuildScript(m_threshold).size() + pubkeys_size;
                 [ #  # ]
     910                 :          0 :     }
     911                 :            : 
     912                 :          0 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
     913                 :          0 :         const auto sig_size = use_max_sig ? 72 : 71;
     914                 :          0 :         return (1 + (1 + sig_size) * m_threshold);
     915                 :            :     }
     916                 :            : 
     917                 :          0 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
     918                 :          0 :         return *MaxSatSize(use_max_sig) * WITNESS_SCALE_FACTOR;
     919                 :            :     }
     920                 :            : 
     921                 :          0 :     std::optional<int64_t> MaxSatisfactionElems() const override { return 1 + m_threshold; }
     922                 :            : };
     923                 :            : 
     924                 :            : /** A parsed (sorted)multi_a(...) descriptor. Always uses x-only pubkeys. */
     925                 :          0 : class MultiADescriptor final : public DescriptorImpl
     926                 :            : {
     927                 :            :     const int m_threshold;
     928                 :            :     const bool m_sorted;
     929                 :            : protected:
     930                 :          0 :     std::string ToStringExtra() const override { return strprintf("%i", m_threshold); }
     931                 :          0 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript>, FlatSigningProvider&) const override {
     932                 :          0 :         CScript ret;
     933                 :          0 :         std::vector<XOnlyPubKey> xkeys;
     934         [ #  # ]:          0 :         xkeys.reserve(keys.size());
     935 [ #  # ][ #  # ]:          0 :         for (const auto& key : keys) xkeys.emplace_back(key);
     936 [ #  # ][ #  # ]:          0 :         if (m_sorted) std::sort(xkeys.begin(), xkeys.end());
     937 [ #  # ][ #  # ]:          0 :         ret << ToByteVector(xkeys[0]) << OP_CHECKSIG;
                 [ #  # ]
     938         [ #  # ]:          0 :         for (size_t i = 1; i < keys.size(); ++i) {
     939 [ #  # ][ #  # ]:          0 :             ret << ToByteVector(xkeys[i]) << OP_CHECKSIGADD;
                 [ #  # ]
     940                 :          0 :         }
     941 [ #  # ][ #  # ]:          0 :         ret << m_threshold << OP_NUMEQUAL;
     942         [ #  # ]:          0 :         return Vector(std::move(ret));
     943                 :          0 :     }
     944                 :            : public:
     945 [ #  # ][ #  # ]:          0 :     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) {}
     946                 :          0 :     bool IsSingleType() const final { return true; }
     947                 :            : 
     948                 :          0 :     std::optional<int64_t> ScriptSize() const override {
     949                 :          0 :         const auto n_keys = m_pubkey_args.size();
     950         [ #  # ]:          0 :         return (1 + 32 + 1) * n_keys + BuildScript(m_threshold).size() + 1;
     951                 :          0 :     }
     952                 :            : 
     953                 :          0 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
     954                 :          0 :         return (1 + 65) * m_threshold + (m_pubkey_args.size() - m_threshold);
     955                 :            :     }
     956                 :            : 
     957                 :          0 :     std::optional<int64_t> MaxSatisfactionElems() const override { return m_pubkey_args.size(); }
     958                 :            : };
     959                 :            : 
     960                 :            : /** A parsed sh(...) descriptor. */
     961                 :          0 : class SHDescriptor final : public DescriptorImpl
     962                 :            : {
     963                 :            : protected:
     964                 :       2377 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, Span<const CScript> scripts, FlatSigningProvider& out) const override
     965                 :            :     {
     966 [ +  - ][ -  + ]:       2377 :         auto ret = Vector(GetScriptForDestination(ScriptHash(scripts[0])));
     967 [ -  + ][ +  - ]:       2377 :         if (ret.size()) out.scripts.emplace(CScriptID(scripts[0]), scripts[0]);
                 [ +  - ]
     968                 :       2377 :         return ret;
     969         [ +  - ]:       2377 :     }
     970                 :            : 
     971                 :        856 :     bool IsSegwit() const { return m_subdescriptor_args[0]->GetOutputType() == OutputType::BECH32; }
     972                 :            : 
     973                 :            : public:
     974 [ +  - ][ -  + ]:        290 :     SHDescriptor(std::unique_ptr<DescriptorImpl> desc) : DescriptorImpl({}, std::move(desc), "sh") {}
     975                 :            : 
     976                 :        568 :     std::optional<OutputType> GetOutputType() const override
     977                 :            :     {
     978         [ +  - ]:        568 :         assert(m_subdescriptor_args.size() == 1);
     979         [ +  - ]:        568 :         if (IsSegwit()) return OutputType::P2SH_SEGWIT;
     980                 :          0 :         return OutputType::LEGACY;
     981                 :        568 :     }
     982                 :        560 :     bool IsSingleType() const final { return true; }
     983                 :            : 
     984                 :          0 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 20 + 1; }
     985                 :            : 
     986                 :        288 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
     987         [ -  + ]:        288 :         if (const auto sat_size = m_subdescriptor_args[0]->MaxSatSize(use_max_sig)) {
     988         [ +  - ]:        288 :             if (const auto subscript_size = m_subdescriptor_args[0]->ScriptSize()) {
     989                 :            :                 // The subscript is never witness data.
     990                 :        288 :                 const auto subscript_weight = (1 + *subscript_size) * WITNESS_SCALE_FACTOR;
     991                 :            :                 // The weight depends on whether the inner descriptor is satisfied using the witness stack.
     992         [ +  - ]:        288 :                 if (IsSegwit()) return subscript_weight + *sat_size;
     993                 :          0 :                 return subscript_weight + *sat_size * WITNESS_SCALE_FACTOR;
     994                 :            :             }
     995                 :          0 :         }
     996                 :          0 :         return {};
     997                 :        288 :     }
     998                 :            : 
     999                 :        288 :     std::optional<int64_t> MaxSatisfactionElems() const override {
    1000         [ +  - ]:        288 :         if (const auto sub_elems = m_subdescriptor_args[0]->MaxSatisfactionElems()) return 1 + *sub_elems;
    1001                 :          0 :         return {};
    1002                 :        288 :     }
    1003                 :            : };
    1004                 :            : 
    1005                 :            : /** A parsed wsh(...) descriptor. */
    1006                 :          0 : class WSHDescriptor final : public DescriptorImpl
    1007                 :            : {
    1008                 :            : protected:
    1009                 :          0 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, Span<const CScript> scripts, FlatSigningProvider& out) const override
    1010                 :            :     {
    1011 [ #  # ][ #  # ]:          0 :         auto ret = Vector(GetScriptForDestination(WitnessV0ScriptHash(scripts[0])));
    1012 [ #  # ][ #  # ]:          0 :         if (ret.size()) out.scripts.emplace(CScriptID(scripts[0]), scripts[0]);
                 [ #  # ]
    1013                 :          0 :         return ret;
    1014         [ #  # ]:          0 :     }
    1015                 :            : public:
    1016 [ #  # ][ #  # ]:          0 :     WSHDescriptor(std::unique_ptr<DescriptorImpl> desc) : DescriptorImpl({}, std::move(desc), "wsh") {}
    1017                 :          0 :     std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32; }
    1018                 :          0 :     bool IsSingleType() const final { return true; }
    1019                 :            : 
    1020                 :          0 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
    1021                 :            : 
    1022                 :          0 :     std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
    1023         [ #  # ]:          0 :         if (const auto sat_size = m_subdescriptor_args[0]->MaxSatSize(use_max_sig)) {
    1024         [ #  # ]:          0 :             if (const auto subscript_size = m_subdescriptor_args[0]->ScriptSize()) {
    1025                 :          0 :                 return GetSizeOfCompactSize(*subscript_size) + *subscript_size + *sat_size;
    1026                 :            :             }
    1027                 :          0 :         }
    1028                 :          0 :         return {};
    1029                 :          0 :     }
    1030                 :            : 
    1031                 :          0 :     std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
    1032                 :          0 :         return MaxSatSize(use_max_sig);
    1033                 :            :     }
    1034                 :            : 
    1035                 :          0 :     std::optional<int64_t> MaxSatisfactionElems() const override {
    1036         [ #  # ]:          0 :         if (const auto sub_elems = m_subdescriptor_args[0]->MaxSatisfactionElems()) return 1 + *sub_elems;
    1037                 :          0 :         return {};
    1038                 :          0 :     }
    1039                 :            : };
    1040                 :            : 
    1041                 :            : /** A parsed tr(...) descriptor. */
    1042                 :          0 : class TRDescriptor final : public DescriptorImpl
    1043                 :            : {
    1044                 :            :     std::vector<int> m_depths;
    1045                 :            : protected:
    1046                 :      10059 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript> scripts, FlatSigningProvider& out) const override
    1047                 :            :     {
    1048                 :      10059 :         TaprootBuilder builder;
    1049         [ +  - ]:      10059 :         assert(m_depths.size() == scripts.size());
    1050         [ +  - ]:      10059 :         for (size_t pos = 0; pos < m_depths.size(); ++pos) {
    1051 [ #  # ][ #  # ]:          0 :             builder.Add(m_depths[pos], scripts[pos], TAPROOT_LEAF_TAPSCRIPT);
    1052                 :          0 :         }
    1053 [ +  - ][ +  - ]:      10059 :         if (!builder.IsComplete()) return {};
    1054         [ +  - ]:      10059 :         assert(keys.size() == 1);
    1055         [ +  - ]:      10059 :         XOnlyPubKey xpk(keys[0]);
    1056 [ +  - ][ +  - ]:      10059 :         if (!xpk.IsFullyValid()) return {};
    1057         [ +  - ]:      10059 :         builder.Finalize(xpk);
    1058         [ +  - ]:      10059 :         WitnessV1Taproot output = builder.GetOutput();
    1059 [ +  - ][ +  - ]:      10059 :         out.tr_trees[output] = builder;
    1060 [ +  - ][ +  - ]:      10059 :         out.pubkeys.emplace(keys[0].GetID(), keys[0]);
    1061 [ +  - ][ -  + ]:      10059 :         return Vector(GetScriptForDestination(output));
    1062                 :      10059 :     }
    1063                 :      25748 :     bool ToStringSubScriptHelper(const SigningProvider* arg, std::string& ret, const StringType type, const DescriptorCache* cache = nullptr) const override
    1064                 :            :     {
    1065         [ +  - ]:      25748 :         if (m_depths.empty()) return true;
    1066                 :          0 :         std::vector<bool> path;
    1067         [ #  # ]:          0 :         for (size_t pos = 0; pos < m_depths.size(); ++pos) {
    1068 [ #  # ][ #  # ]:          0 :             if (pos) ret += ',';
    1069         [ #  # ]:          0 :             while ((int)path.size() <= m_depths[pos]) {
    1070 [ #  # ][ #  # ]:          0 :                 if (path.size()) ret += '{';
    1071         [ #  # ]:          0 :                 path.push_back(false);
    1072                 :            :             }
    1073                 :          0 :             std::string tmp;
    1074 [ #  # ][ #  # ]:          0 :             if (!m_subdescriptor_args[pos]->ToStringHelper(arg, tmp, type, cache)) return false;
    1075         [ #  # ]:          0 :             ret += tmp;
    1076 [ #  # ][ #  # ]:          0 :             while (!path.empty() && path.back()) {
                 [ #  # ]
    1077 [ #  # ][ #  # ]:          0 :                 if (path.size() > 1) ret += '}';
    1078         [ #  # ]:          0 :                 path.pop_back();
    1079                 :            :             }
    1080 [ #  # ][ #  # ]:          0 :             if (!path.empty()) path.back() = true;
    1081         [ #  # ]:          0 :         }
    1082                 :          0 :         return true;
    1083                 :      25748 :     }
    1084                 :            : public:
    1085                 :       4358 :     TRDescriptor(std::unique_ptr<PubkeyProvider> internal_key, std::vector<std::unique_ptr<DescriptorImpl>> descs, std::vector<int> depths) :
    1086 [ +  - ][ +  - ]:       4358 :         DescriptorImpl(Vector(std::move(internal_key)), std::move(descs), "tr"), m_depths(std::move(depths))
    1087                 :       4358 :     {
    1088         [ +  - ]:       4358 :         assert(m_subdescriptor_args.size() == m_depths.size());
    1089                 :       4358 :     }
    1090                 :       8580 :     std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32M; }
    1091                 :       8448 :     bool IsSingleType() const final { return true; }
    1092                 :            : 
    1093                 :          0 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
    1094                 :            : 
    1095                 :       4356 :     std::optional<int64_t> MaxSatisfactionWeight(bool) const override {
    1096                 :            :         // FIXME: We assume keypath spend, which can lead to very large underestimations.
    1097                 :       4356 :         return 1 + 65;
    1098                 :            :     }
    1099                 :            : 
    1100                 :       4356 :     std::optional<int64_t> MaxSatisfactionElems() const override {
    1101                 :            :         // FIXME: See above, we assume keypath spend.
    1102                 :       4356 :         return 1;
    1103                 :            :     }
    1104                 :            : };
    1105                 :            : 
    1106                 :            : /* We instantiate Miniscript here with a simple integer as key type.
    1107                 :            :  * The value of these key integers are an index in the
    1108                 :            :  * DescriptorImpl::m_pubkey_args vector.
    1109                 :            :  */
    1110                 :            : 
    1111                 :            : /**
    1112                 :            :  * The context for converting a Miniscript descriptor into a Script.
    1113                 :            :  */
    1114                 :            : class ScriptMaker {
    1115                 :            :     //! Keys contained in the Miniscript (the evaluation of DescriptorImpl::m_pubkey_args).
    1116                 :            :     const std::vector<CPubKey>& m_keys;
    1117                 :            :     //! The script context we're operating within (Tapscript or P2WSH).
    1118                 :            :     const miniscript::MiniscriptContext m_script_ctx;
    1119                 :            : 
    1120                 :            :     //! Get the ripemd160(sha256()) hash of this key.
    1121                 :            :     //! Any key that is valid in a descriptor serializes as 32 bytes within a Tapscript context. So we
    1122                 :            :     //! must not hash the sign-bit byte in this case.
    1123                 :          0 :     uint160 GetHash160(uint32_t key) const {
    1124         [ #  # ]:          0 :         if (miniscript::IsTapscript(m_script_ctx)) {
    1125                 :          0 :             return Hash160(XOnlyPubKey{m_keys[key]});
    1126                 :            :         }
    1127                 :          0 :         return m_keys[key].GetID();
    1128                 :          0 :     }
    1129                 :            : 
    1130                 :            : public:
    1131                 :          0 :     ScriptMaker(const std::vector<CPubKey>& keys LIFETIMEBOUND, const miniscript::MiniscriptContext script_ctx) : m_keys(keys), m_script_ctx{script_ctx} {}
    1132                 :            : 
    1133                 :          0 :     std::vector<unsigned char> ToPKBytes(uint32_t key) const {
    1134                 :            :         // In Tapscript keys always serialize as x-only, whether an x-only key was used in the descriptor or not.
    1135         [ #  # ]:          0 :         if (!miniscript::IsTapscript(m_script_ctx)) {
    1136         [ #  # ]:          0 :             return {m_keys[key].begin(), m_keys[key].end()};
    1137                 :            :         }
    1138                 :          0 :         const XOnlyPubKey xonly_pubkey{m_keys[key]};
    1139         [ #  # ]:          0 :         return {xonly_pubkey.begin(), xonly_pubkey.end()};
    1140                 :          0 :     }
    1141                 :            : 
    1142                 :          0 :     std::vector<unsigned char> ToPKHBytes(uint32_t key) const {
    1143                 :          0 :         auto id = GetHash160(key);
    1144         [ #  # ]:          0 :         return {id.begin(), id.end()};
    1145                 :          0 :     }
    1146                 :            : };
    1147                 :            : 
    1148                 :            : /**
    1149                 :            :  * The context for converting a Miniscript descriptor to its textual form.
    1150                 :            :  */
    1151                 :            : class StringMaker {
    1152                 :            :     //! To convert private keys for private descriptors.
    1153                 :            :     const SigningProvider* m_arg;
    1154                 :            :     //! Keys contained in the Miniscript (a reference to DescriptorImpl::m_pubkey_args).
    1155                 :            :     const std::vector<std::unique_ptr<PubkeyProvider>>& m_pubkeys;
    1156                 :            :     //! Whether to serialize keys as private or public.
    1157                 :            :     bool m_private;
    1158                 :            : 
    1159                 :            : public:
    1160                 :          0 :     StringMaker(const SigningProvider* arg LIFETIMEBOUND, const std::vector<std::unique_ptr<PubkeyProvider>>& pubkeys LIFETIMEBOUND, bool priv)
    1161                 :          0 :         : m_arg(arg), m_pubkeys(pubkeys), m_private(priv) {}
    1162                 :            : 
    1163                 :          0 :     std::optional<std::string> ToString(uint32_t key) const
    1164                 :            :     {
    1165                 :          0 :         std::string ret;
    1166         [ #  # ]:          0 :         if (m_private) {
    1167 [ #  # ][ #  # ]:          0 :             if (!m_pubkeys[key]->ToPrivateString(*m_arg, ret)) return {};
    1168                 :          0 :         } else {
    1169         [ #  # ]:          0 :             ret = m_pubkeys[key]->ToString();
    1170                 :            :         }
    1171                 :          0 :         return ret;
    1172                 :          0 :     }
    1173                 :            : };
    1174                 :            : 
    1175                 :          0 : class MiniscriptDescriptor final : public DescriptorImpl
    1176                 :            : {
    1177                 :            : private:
    1178                 :            :     miniscript::NodeRef<uint32_t> m_node;
    1179                 :            : 
    1180                 :            : protected:
    1181                 :          0 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript> scripts,
    1182                 :            :                                      FlatSigningProvider& provider) const override
    1183                 :            :     {
    1184                 :          0 :         const auto script_ctx{m_node->GetMsCtx()};
    1185         [ #  # ]:          0 :         for (const auto& key : keys) {
    1186         [ #  # ]:          0 :             if (miniscript::IsTapscript(script_ctx)) {
    1187                 :          0 :                 provider.pubkeys.emplace(Hash160(XOnlyPubKey{key}), key);
    1188                 :          0 :             } else {
    1189                 :          0 :                 provider.pubkeys.emplace(key.GetID(), key);
    1190                 :            :             }
    1191                 :            :         }
    1192         [ #  # ]:          0 :         return Vector(m_node->ToScript(ScriptMaker(keys, script_ctx)));
    1193                 :          0 :     }
    1194                 :            : 
    1195                 :            : public:
    1196                 :          0 :     MiniscriptDescriptor(std::vector<std::unique_ptr<PubkeyProvider>> providers, miniscript::NodeRef<uint32_t> node)
    1197 [ #  # ][ #  # ]:          0 :         : DescriptorImpl(std::move(providers), "?"), m_node(std::move(node)) {}
    1198                 :            : 
    1199                 :          0 :     bool ToStringHelper(const SigningProvider* arg, std::string& out, const StringType type,
    1200                 :            :                         const DescriptorCache* cache = nullptr) const override
    1201                 :            :     {
    1202         [ #  # ]:          0 :         if (const auto res = m_node->ToString(StringMaker(arg, m_pubkey_args, type == StringType::PRIVATE))) {
              [ #  #  # ]
    1203         [ #  # ]:          0 :             out = *res;
    1204                 :          0 :             return true;
    1205                 :            :         }
    1206                 :          0 :         return false;
    1207                 :          0 :     }
    1208                 :            : 
    1209                 :          0 :     bool IsSolvable() const override { return true; }
    1210                 :          0 :     bool IsSingleType() const final { return true; }
    1211                 :            : 
    1212                 :          0 :     std::optional<int64_t> ScriptSize() const override { return m_node->ScriptSize(); }
    1213                 :            : 
    1214                 :          0 :     std::optional<int64_t> MaxSatSize(bool) const override {
    1215                 :            :         // For Miniscript we always assume high-R ECDSA signatures.
    1216                 :          0 :         return m_node->GetWitnessSize();
    1217                 :            :     }
    1218                 :            : 
    1219                 :          0 :     std::optional<int64_t> MaxSatisfactionElems() const override {
    1220                 :          0 :         return m_node->GetStackSize();
    1221                 :            :     }
    1222                 :            : };
    1223                 :            : 
    1224                 :            : /** A parsed rawtr(...) descriptor. */
    1225                 :          0 : class RawTRDescriptor final : public DescriptorImpl
    1226                 :            : {
    1227                 :            : protected:
    1228                 :          0 :     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript> scripts, FlatSigningProvider& out) const override
    1229                 :            :     {
    1230         [ #  # ]:          0 :         assert(keys.size() == 1);
    1231                 :          0 :         XOnlyPubKey xpk(keys[0]);
    1232         [ #  # ]:          0 :         if (!xpk.IsFullyValid()) return {};
    1233                 :          0 :         WitnessV1Taproot output{xpk};
    1234 [ #  # ][ #  # ]:          0 :         return Vector(GetScriptForDestination(output));
    1235                 :          0 :     }
    1236                 :            : public:
    1237 [ #  # ][ #  # ]:          0 :     RawTRDescriptor(std::unique_ptr<PubkeyProvider> output_key) : DescriptorImpl(Vector(std::move(output_key)), "rawtr") {}
    1238                 :          0 :     std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32M; }
    1239                 :          0 :     bool IsSingleType() const final { return true; }
    1240                 :            : 
    1241                 :          0 :     std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
    1242                 :            : 
    1243                 :          0 :     std::optional<int64_t> MaxSatisfactionWeight(bool) const override {
    1244                 :            :         // We can't know whether there is a script path, so assume key path spend.
    1245                 :          0 :         return 1 + 65;
    1246                 :            :     }
    1247                 :            : 
    1248                 :          0 :     std::optional<int64_t> MaxSatisfactionElems() const override {
    1249                 :            :         // See above, we assume keypath spend.
    1250                 :          0 :         return 1;
    1251                 :            :     }
    1252                 :            : };
    1253                 :            : 
    1254                 :            : ////////////////////////////////////////////////////////////////////////////
    1255                 :            : // Parser                                                                 //
    1256                 :            : ////////////////////////////////////////////////////////////////////////////
    1257                 :            : 
    1258                 :            : enum class ParseScriptContext {
    1259                 :            :     TOP,     //!< Top-level context (script goes directly in scriptPubKey)
    1260                 :            :     P2SH,    //!< Inside sh() (script becomes P2SH redeemScript)
    1261                 :            :     P2WPKH,  //!< Inside wpkh() (no script, pubkey only)
    1262                 :            :     P2WSH,   //!< Inside wsh() (script becomes v0 witness script)
    1263                 :            :     P2TR,    //!< Inside tr() (either internal key, or BIP342 script leaf)
    1264                 :            : };
    1265                 :            : 
    1266                 :            : /**
    1267                 :            :  * Parse a key path, being passed a split list of elements (the first element is ignored).
    1268                 :            :  *
    1269                 :            :  * @param[in] split BIP32 path string, using either ' or h for hardened derivation
    1270                 :            :  * @param[out] out the key path
    1271                 :            :  * @param[out] apostrophe only updated if hardened derivation is found
    1272                 :            :  * @param[out] error parsing error message
    1273                 :            :  * @returns false if parsing failed
    1274                 :            :  **/
    1275                 :          8 : [[nodiscard]] bool ParseKeyPath(const std::vector<Span<const char>>& split, KeyPath& out, bool& apostrophe, std::string& error)
    1276                 :            : {
    1277         [ +  + ]:         40 :     for (size_t i = 1; i < split.size(); ++i) {
    1278                 :         32 :         Span<const char> elem = split[i];
    1279                 :         32 :         bool hardened = false;
    1280         [ -  + ]:         32 :         if (elem.size() > 0) {
    1281                 :         32 :             const char last = elem[elem.size() - 1];
    1282 [ +  - ][ +  + ]:         32 :             if (last == '\'' || last == 'h') {
    1283                 :         24 :                 elem = elem.first(elem.size() - 1);
    1284                 :         24 :                 hardened = true;
    1285                 :         24 :                 apostrophe = last == '\'';
    1286                 :         24 :             }
    1287                 :         32 :         }
    1288                 :            :         uint32_t p;
    1289 [ +  - ][ +  - ]:         32 :         if (!ParseUInt32(std::string(elem.begin(), elem.end()), &p)) {
                 [ +  - ]
    1290 [ #  # ][ #  # ]:          0 :             error = strprintf("Key path value '%s' is not a valid uint32", std::string(elem.begin(), elem.end()));
    1291                 :          0 :             return false;
    1292         [ +  - ]:         32 :         } else if (p > 0x7FFFFFFFUL) {
    1293                 :          0 :             error = strprintf("Key path value %u is out of range", p);
    1294                 :          0 :             return false;
    1295                 :            :         }
    1296                 :         32 :         out.push_back(p | (((uint32_t)hardened) << 31));
    1297                 :         32 :     }
    1298                 :          8 :     return true;
    1299                 :          8 : }
    1300                 :            : 
    1301                 :            : /** Parse a public key that excludes origin information. */
    1302                 :          9 : std::unique_ptr<PubkeyProvider> ParsePubkeyInner(uint32_t key_exp_index, const Span<const char>& sp, ParseScriptContext ctx, FlatSigningProvider& out, bool& apostrophe, std::string& error)
    1303                 :            : {
    1304                 :            :     using namespace spanparsing;
    1305                 :            : 
    1306         [ +  + ]:          9 :     bool permit_uncompressed = ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH;
    1307                 :          9 :     auto split = Split(sp, '/');
    1308         [ +  - ]:          9 :     std::string str(split[0].begin(), split[0].end());
    1309         [ -  + ]:          9 :     if (str.size() == 0) {
    1310         [ #  # ]:          0 :         error = "No key provided";
    1311                 :          0 :         return nullptr;
    1312                 :            :     }
    1313         [ +  + ]:          9 :     if (split.size() == 1) {
    1314 [ +  - ][ -  + ]:          1 :         if (IsHex(str)) {
    1315         [ #  # ]:          0 :             std::vector<unsigned char> data = ParseHex(str);
    1316 [ #  # ][ #  # ]:          0 :             CPubKey pubkey(data);
    1317 [ #  # ][ #  # ]:          0 :             if (pubkey.IsValid() && !pubkey.IsValidNonHybrid()) {
                 [ #  # ]
    1318         [ #  # ]:          0 :                 error = "Hybrid public keys are not allowed";
    1319                 :          0 :                 return nullptr;
    1320                 :            :             }
    1321 [ #  # ][ #  # ]:          0 :             if (pubkey.IsFullyValid()) {
    1322 [ #  # ][ #  # ]:          0 :                 if (permit_uncompressed || pubkey.IsCompressed()) {
                 [ #  # ]
    1323         [ #  # ]:          0 :                     return std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, false);
    1324                 :            :                 } else {
    1325         [ #  # ]:          0 :                     error = "Uncompressed keys are not allowed";
    1326                 :          0 :                     return nullptr;
    1327                 :            :                 }
    1328 [ #  # ][ #  # ]:          0 :             } else if (data.size() == 32 && ctx == ParseScriptContext::P2TR) {
    1329                 :          0 :                 unsigned char fullkey[33] = {0x02};
    1330         [ #  # ]:          0 :                 std::copy(data.begin(), data.end(), fullkey + 1);
    1331         [ #  # ]:          0 :                 pubkey.Set(std::begin(fullkey), std::end(fullkey));
    1332 [ #  # ][ #  # ]:          0 :                 if (pubkey.IsFullyValid()) {
    1333         [ #  # ]:          0 :                     return std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, true);
    1334                 :            :                 }
    1335                 :          0 :             }
    1336         [ #  # ]:          0 :             error = strprintf("Pubkey '%s' is invalid", str);
    1337                 :          0 :             return nullptr;
    1338                 :          0 :         }
    1339         [ +  - ]:          1 :         CKey key = DecodeSecret(str);
    1340 [ +  - ][ +  - ]:          1 :         if (key.IsValid()) {
    1341 [ -  + ][ #  # ]:          1 :             if (permit_uncompressed || key.IsCompressed()) {
                 [ #  # ]
    1342         [ +  - ]:          1 :                 CPubKey pubkey = key.GetPubKey();
    1343 [ +  - ][ +  - ]:          1 :                 out.keys.emplace(pubkey.GetID(), key);
    1344         [ +  - ]:          1 :                 return std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, ctx == ParseScriptContext::P2TR);
    1345                 :            :             } else {
    1346         [ #  # ]:          0 :                 error = "Uncompressed keys are not allowed";
    1347                 :          0 :                 return nullptr;
    1348                 :            :             }
    1349                 :            :         }
    1350         [ +  - ]:          1 :     }
    1351         [ +  - ]:          8 :     CExtKey extkey = DecodeExtKey(str);
    1352         [ +  - ]:          8 :     CExtPubKey extpubkey = DecodeExtPubKey(str);
    1353 [ +  - ][ +  - ]:          8 :     if (!extkey.key.IsValid() && !extpubkey.pubkey.IsValid()) {
         [ +  - ][ -  + ]
    1354         [ #  # ]:          0 :         error = strprintf("key '%s' is not valid", str);
    1355                 :          0 :         return nullptr;
    1356                 :            :     }
    1357                 :          8 :     KeyPath path;
    1358                 :          8 :     DeriveType type = DeriveType::NO;
    1359         [ +  - ]:          8 :     if (split.back() == Span{"*"}.first(1)) {
    1360                 :          8 :         split.pop_back();
    1361                 :          8 :         type = DeriveType::UNHARDENED;
    1362 [ #  # ][ #  # ]:          8 :     } else if (split.back() == Span{"*'"}.first(2) || split.back() == Span{"*h"}.first(2)) {
    1363                 :          0 :         apostrophe = split.back() == Span{"*'"}.first(2);
    1364                 :          0 :         split.pop_back();
    1365                 :          0 :         type = DeriveType::HARDENED;
    1366                 :          0 :     }
    1367 [ +  - ][ +  - ]:          8 :     if (!ParseKeyPath(split, path, apostrophe, error)) return nullptr;
    1368 [ +  - ][ -  + ]:          8 :     if (extkey.key.IsValid()) {
    1369         [ #  # ]:          0 :         extpubkey = extkey.Neuter();
    1370 [ #  # ][ #  # ]:          0 :         out.keys.emplace(extpubkey.pubkey.GetID(), extkey.key);
    1371                 :          0 :     }
    1372         [ +  - ]:          8 :     return std::make_unique<BIP32PubkeyProvider>(key_exp_index, extpubkey, std::move(path), type, apostrophe);
    1373                 :          9 : }
    1374                 :            : 
    1375                 :            : /** Parse a public key including origin information (if enabled). */
    1376                 :          9 : std::unique_ptr<PubkeyProvider> ParsePubkey(uint32_t key_exp_index, const Span<const char>& sp, ParseScriptContext ctx, FlatSigningProvider& out, std::string& error)
    1377                 :            : {
    1378                 :            :     using namespace spanparsing;
    1379                 :            : 
    1380                 :          9 :     auto origin_split = Split(sp, ']');
    1381         [ +  - ]:          9 :     if (origin_split.size() > 2) {
    1382         [ #  # ]:          0 :         error = "Multiple ']' characters found for a single pubkey";
    1383                 :          0 :         return nullptr;
    1384                 :            :     }
    1385                 :            :     // This is set if either the origin or path suffix contains a hardened derivation.
    1386                 :          9 :     bool apostrophe = false;
    1387         [ +  - ]:          9 :     if (origin_split.size() == 1) {
    1388         [ +  - ]:          9 :         return ParsePubkeyInner(key_exp_index, origin_split[0], ctx, out, apostrophe, error);
    1389                 :            :     }
    1390 [ #  # ][ #  # ]:          0 :     if (origin_split[0].empty() || origin_split[0][0] != '[') {
    1391         [ #  # ]:          0 :         error = strprintf("Key origin start '[ character expected but not found, got '%c' instead",
    1392         [ #  # ]:          0 :                           origin_split[0].empty() ? /** empty, implies split char */ ']' : origin_split[0][0]);
    1393                 :          0 :         return nullptr;
    1394                 :            :     }
    1395         [ #  # ]:          0 :     auto slash_split = Split(origin_split[0].subspan(1), '/');
    1396         [ #  # ]:          0 :     if (slash_split[0].size() != 8) {
    1397         [ #  # ]:          0 :         error = strprintf("Fingerprint is not 4 bytes (%u characters instead of 8 characters)", slash_split[0].size());
    1398                 :          0 :         return nullptr;
    1399                 :            :     }
    1400         [ #  # ]:          0 :     std::string fpr_hex = std::string(slash_split[0].begin(), slash_split[0].end());
    1401 [ #  # ][ #  # ]:          0 :     if (!IsHex(fpr_hex)) {
    1402         [ #  # ]:          0 :         error = strprintf("Fingerprint '%s' is not hex", fpr_hex);
    1403                 :          0 :         return nullptr;
    1404                 :            :     }
    1405         [ #  # ]:          0 :     auto fpr_bytes = ParseHex(fpr_hex);
    1406                 :          0 :     KeyOriginInfo info;
    1407                 :            :     static_assert(sizeof(info.fingerprint) == 4, "Fingerprint must be 4 bytes");
    1408         [ #  # ]:          0 :     assert(fpr_bytes.size() == 4);
    1409         [ #  # ]:          0 :     std::copy(fpr_bytes.begin(), fpr_bytes.end(), info.fingerprint);
    1410 [ #  # ][ #  # ]:          0 :     if (!ParseKeyPath(slash_split, info.path, apostrophe, error)) return nullptr;
    1411         [ #  # ]:          0 :     auto provider = ParsePubkeyInner(key_exp_index, origin_split[1], ctx, out, apostrophe, error);
    1412         [ #  # ]:          0 :     if (!provider) return nullptr;
    1413         [ #  # ]:          0 :     return std::make_unique<OriginPubkeyProvider>(key_exp_index, std::move(info), std::move(provider), apostrophe);
    1414                 :          9 : }
    1415                 :            : 
    1416                 :     414233 : std::unique_ptr<PubkeyProvider> InferPubkey(const CPubKey& pubkey, ParseScriptContext ctx, const SigningProvider& provider)
    1417                 :            : {
    1418                 :            :     // Key cannot be hybrid
    1419         [ -  + ]:     414233 :     if (!pubkey.IsValidNonHybrid()) {
    1420                 :          0 :         return nullptr;
    1421                 :            :     }
    1422                 :            :     // Uncompressed is only allowed in TOP and P2SH contexts
    1423 [ +  + ][ +  - ]:     414233 :     if (ctx != ParseScriptContext::TOP && ctx != ParseScriptContext::P2SH && !pubkey.IsCompressed()) {
                 [ +  - ]
    1424                 :          0 :         return nullptr;
    1425                 :            :     }
    1426                 :     414233 :     std::unique_ptr<PubkeyProvider> key_provider = std::make_unique<ConstPubkeyProvider>(0, pubkey, false);
    1427                 :     414233 :     KeyOriginInfo info;
    1428 [ +  - ][ +  - ]:     414233 :     if (provider.GetKeyOrigin(pubkey.GetID(), info)) {
                 [ +  - ]
    1429         [ +  - ]:     414233 :         return std::make_unique<OriginPubkeyProvider>(0, std::move(info), std::move(key_provider), /*apostrophe=*/false);
    1430                 :            :     }
    1431                 :          0 :     return key_provider;
    1432                 :     414233 : }
    1433                 :            : 
    1434                 :       4356 : std::unique_ptr<PubkeyProvider> InferXOnlyPubkey(const XOnlyPubKey& xkey, ParseScriptContext ctx, const SigningProvider& provider)
    1435                 :            : {
    1436                 :       4356 :     CPubKey pubkey{xkey.GetEvenCorrespondingCPubKey()};
    1437                 :       4356 :     std::unique_ptr<PubkeyProvider> key_provider = std::make_unique<ConstPubkeyProvider>(0, pubkey, true);
    1438                 :       4356 :     KeyOriginInfo info;
    1439 [ +  - ][ +  - ]:       4356 :     if (provider.GetKeyOriginByXOnly(xkey, info)) {
    1440         [ +  - ]:       4356 :         return std::make_unique<OriginPubkeyProvider>(0, std::move(info), std::move(key_provider), /*apostrophe=*/false);
    1441                 :            :     }
    1442                 :          0 :     return key_provider;
    1443                 :       4356 : }
    1444                 :            : 
    1445                 :            : /**
    1446                 :            :  * The context for parsing a Miniscript descriptor (either from Script or from its textual representation).
    1447                 :            :  */
    1448                 :          0 : struct KeyParser {
    1449                 :            :     //! The Key type is an index in DescriptorImpl::m_pubkey_args
    1450                 :            :     using Key = uint32_t;
    1451                 :            :     //! Must not be nullptr if parsing from string.
    1452                 :            :     FlatSigningProvider* m_out;
    1453                 :            :     //! Must not be nullptr if parsing from Script.
    1454                 :            :     const SigningProvider* m_in;
    1455                 :            :     //! List of keys contained in the Miniscript.
    1456                 :            :     mutable std::vector<std::unique_ptr<PubkeyProvider>> m_keys;
    1457                 :            :     //! Used to detect key parsing errors within a Miniscript.
    1458                 :            :     mutable std::string m_key_parsing_error;
    1459                 :            :     //! The script context we're operating within (Tapscript or P2WSH).
    1460                 :            :     const miniscript::MiniscriptContext m_script_ctx;
    1461                 :            :     //! The number of keys that were parsed before starting to parse this Miniscript descriptor.
    1462                 :            :     uint32_t m_offset;
    1463                 :            : 
    1464                 :          0 :     KeyParser(FlatSigningProvider* out LIFETIMEBOUND, const SigningProvider* in LIFETIMEBOUND,
    1465                 :            :               miniscript::MiniscriptContext ctx, uint32_t offset = 0)
    1466                 :          0 :         : m_out(out), m_in(in), m_script_ctx(ctx), m_offset(offset) {}
    1467                 :            : 
    1468                 :          0 :     bool KeyCompare(const Key& a, const Key& b) const {
    1469                 :          0 :         return *m_keys.at(a) < *m_keys.at(b);
    1470                 :            :     }
    1471                 :            : 
    1472                 :          0 :     ParseScriptContext ParseContext() const {
    1473      [ #  #  # ]:          0 :         switch (m_script_ctx) {
    1474                 :          0 :             case miniscript::MiniscriptContext::P2WSH: return ParseScriptContext::P2WSH;
    1475                 :          0 :             case miniscript::MiniscriptContext::TAPSCRIPT: return ParseScriptContext::P2TR;
    1476                 :            :         }
    1477                 :          0 :         assert(false);
    1478                 :          0 :     }
    1479                 :            : 
    1480                 :          0 :     template<typename I> std::optional<Key> FromString(I begin, I end) const
    1481                 :            :     {
    1482         [ #  # ]:          0 :         assert(m_out);
    1483                 :          0 :         Key key = m_keys.size();
    1484                 :          0 :         auto pk = ParsePubkey(m_offset + key, {&*begin, &*end}, ParseContext(), *m_out, m_key_parsing_error);
    1485         [ #  # ]:          0 :         if (!pk) return {};
    1486         [ #  # ]:          0 :         m_keys.push_back(std::move(pk));
    1487                 :          0 :         return key;
    1488                 :          0 :     }
    1489                 :            : 
    1490                 :          0 :     std::optional<std::string> ToString(const Key& key) const
    1491                 :            :     {
    1492                 :          0 :         return m_keys.at(key)->ToString();
    1493                 :            :     }
    1494                 :            : 
    1495                 :          0 :     template<typename I> std::optional<Key> FromPKBytes(I begin, I end) const
    1496                 :            :     {
    1497         [ #  # ]:          0 :         assert(m_in);
    1498                 :          0 :         Key key = m_keys.size();
    1499 [ #  # ][ #  # ]:          0 :         if (miniscript::IsTapscript(m_script_ctx) && end - begin == 32) {
    1500                 :          0 :             XOnlyPubKey pubkey;
    1501                 :          0 :             std::copy(begin, end, pubkey.begin());
    1502 [ #  # ][ #  # ]:          0 :             if (auto pubkey_provider = InferPubkey(pubkey.GetEvenCorrespondingCPubKey(), ParseContext(), *m_in)) {
    1503         [ #  # ]:          0 :                 m_keys.push_back(std::move(pubkey_provider));
    1504                 :          0 :                 return key;
    1505                 :            :             }
    1506         [ #  # ]:          0 :         } else if (!miniscript::IsTapscript(m_script_ctx)) {
    1507                 :          0 :             CPubKey pubkey(begin, end);
    1508 [ #  # ][ #  # ]:          0 :             if (auto pubkey_provider = InferPubkey(pubkey, ParseContext(), *m_in)) {
    1509         [ #  # ]:          0 :                 m_keys.push_back(std::move(pubkey_provider));
    1510                 :          0 :                 return key;
    1511                 :            :             }
    1512                 :          0 :         }
    1513                 :          0 :         return {};
    1514                 :          0 :     }
    1515                 :            : 
    1516                 :          0 :     template<typename I> std::optional<Key> FromPKHBytes(I begin, I end) const
    1517                 :            :     {
    1518         [ #  # ]:          0 :         assert(end - begin == 20);
    1519         [ #  # ]:          0 :         assert(m_in);
    1520                 :          0 :         uint160 hash;
    1521                 :          0 :         std::copy(begin, end, hash.begin());
    1522                 :          0 :         CKeyID keyid(hash);
    1523                 :          0 :         CPubKey pubkey;
    1524         [ #  # ]:          0 :         if (m_in->GetPubKey(keyid, pubkey)) {
    1525         [ #  # ]:          0 :             if (auto pubkey_provider = InferPubkey(pubkey, ParseContext(), *m_in)) {
              [ #  #  # ]
    1526                 :          0 :                 Key key = m_keys.size();
    1527         [ #  # ]:          0 :                 m_keys.push_back(std::move(pubkey_provider));
    1528                 :          0 :                 return key;
    1529                 :            :             }
    1530                 :          0 :         }
    1531                 :          0 :         return {};
    1532                 :          0 :     }
    1533                 :            : 
    1534                 :          0 :     miniscript::MiniscriptContext MsContext() const {
    1535                 :          0 :         return m_script_ctx;
    1536                 :            :     }
    1537                 :            : };
    1538                 :            : 
    1539                 :            : /** Parse a script in a particular context. */
    1540                 :         11 : std::unique_ptr<DescriptorImpl> ParseScript(uint32_t& key_exp_index, Span<const char>& sp, ParseScriptContext ctx, FlatSigningProvider& out, std::string& error)
    1541                 :            : {
    1542                 :            :     using namespace spanparsing;
    1543                 :            : 
    1544                 :         11 :     auto expr = Expr(sp);
    1545 [ +  - ][ +  - ]:         11 :     if (Func("pk", expr)) {
                 [ -  + ]
    1546                 :          0 :         auto pubkey = ParsePubkey(key_exp_index, expr, ctx, out, error);
    1547         [ #  # ]:          0 :         if (!pubkey) {
    1548         [ #  # ]:          0 :             error = strprintf("pk(): %s", error);
    1549                 :          0 :             return nullptr;
    1550                 :            :         }
    1551                 :          0 :         ++key_exp_index;
    1552         [ #  # ]:          0 :         return std::make_unique<PKDescriptor>(std::move(pubkey), ctx == ParseScriptContext::P2TR);
    1553                 :          0 :     }
    1554 [ +  + ][ -  + ]:         22 :     if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH) && Func("pkh", expr)) {
         [ #  # ][ +  - ]
         [ +  - ][ -  + ]
         [ -  + ][ +  + ]
         [ #  # ][ #  # ]
    1555                 :          2 :         auto pubkey = ParsePubkey(key_exp_index, expr, ctx, out, error);
    1556         [ -  + ]:          2 :         if (!pubkey) {
    1557         [ #  # ]:          0 :             error = strprintf("pkh(): %s", error);
    1558                 :          0 :             return nullptr;
    1559                 :            :         }
    1560                 :          2 :         ++key_exp_index;
    1561         [ +  - ]:          2 :         return std::make_unique<PKHDescriptor>(std::move(pubkey));
    1562 [ -  + ][ +  - ]:         20 :     } else if (ctx != ParseScriptContext::P2TR && Func("pkh", expr)) {
         [ +  - ][ -  + ]
         [ -  + ][ -  + ]
         [ #  # ][ #  # ]
    1563                 :            :         // Under Taproot, always the Miniscript parser deal with it.
    1564                 :          0 :         error = "Can only have pkh at top level, in sh(), wsh(), or in tr()";
    1565                 :          0 :         return nullptr;
    1566                 :            :     }
    1567 [ +  + ][ +  - ]:         16 :     if (ctx == ParseScriptContext::TOP && Func("combo", expr)) {
         [ +  - ][ +  + ]
         [ +  + ][ +  + ]
         [ #  # ][ #  # ]
    1568                 :          1 :         auto pubkey = ParsePubkey(key_exp_index, expr, ctx, out, error);
    1569         [ -  + ]:          1 :         if (!pubkey) {
    1570         [ #  # ]:          0 :             error = strprintf("combo(): %s", error);
    1571                 :          0 :             return nullptr;
    1572                 :            :         }
    1573                 :          1 :         ++key_exp_index;
    1574         [ +  - ]:          1 :         return std::make_unique<ComboDescriptor>(std::move(pubkey));
    1575 [ +  - ][ +  - ]:          9 :     } else if (Func("combo", expr)) {
                 [ -  + ]
    1576                 :          0 :         error = "Can only have combo() at top level";
    1577                 :          0 :         return nullptr;
    1578                 :            :     }
    1579 [ +  - ][ +  - ]:          8 :     const bool multi = Func("multi", expr);
    1580 [ -  + ][ +  - ]:         16 :     const bool sortedmulti = !multi && Func("sortedmulti", expr);
         [ +  - ][ -  + ]
         [ -  + ][ #  # ]
                 [ #  # ]
    1581 [ +  - ][ -  + ]:         16 :     const bool multi_a = !(multi || sortedmulti) && Func("multi_a", expr);
         [ -  + ][ -  + ]
         [ -  + ][ -  + ]
         [ #  # ][ #  # ]
    1582 [ +  - ][ +  - ]:         16 :     const bool sortedmulti_a = !(multi || sortedmulti || multi_a) && Func("sortedmulti_a", expr);
         [ -  + ][ +  - ]
         [ +  - ][ -  + ]
         [ -  + ][ #  # ]
                 [ #  # ]
    1583 [ +  + ][ -  + ]:          8 :     if (((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH) && (multi || sortedmulti)) ||
         [ +  - ][ -  + ]
    1584 [ -  + ][ #  # ]:          8 :         (ctx == ParseScriptContext::P2TR && (multi_a || sortedmulti_a))) {
    1585                 :          0 :         auto threshold = Expr(expr);
    1586                 :            :         uint32_t thres;
    1587                 :          0 :         std::vector<std::unique_ptr<PubkeyProvider>> providers;
    1588 [ #  # ][ #  # ]:          0 :         if (!ParseUInt32(std::string(threshold.begin(), threshold.end()), &thres)) {
                 [ #  # ]
    1589 [ #  # ][ #  # ]:          0 :             error = strprintf("Multi threshold '%s' is not valid", std::string(threshold.begin(), threshold.end()));
    1590                 :          0 :             return nullptr;
    1591                 :            :         }
    1592                 :          0 :         size_t script_size = 0;
    1593         [ #  # ]:          0 :         while (expr.size()) {
    1594 [ #  # ][ #  # ]:          0 :             if (!Const(",", expr)) {
                 [ #  # ]
    1595         [ #  # ]:          0 :                 error = strprintf("Multi: expected ',', got '%c'", expr[0]);
    1596                 :          0 :                 return nullptr;
    1597                 :            :             }
    1598         [ #  # ]:          0 :             auto arg = Expr(expr);
    1599         [ #  # ]:          0 :             auto pk = ParsePubkey(key_exp_index, arg, ctx, out, error);
    1600         [ #  # ]:          0 :             if (!pk) {
    1601         [ #  # ]:          0 :                 error = strprintf("Multi: %s", error);
    1602                 :          0 :                 return nullptr;
    1603                 :            :             }
    1604         [ #  # ]:          0 :             script_size += pk->GetSize() + 1;
    1605         [ #  # ]:          0 :             providers.emplace_back(std::move(pk));
    1606                 :          0 :             key_exp_index++;
    1607         [ #  # ]:          0 :         }
    1608 [ #  # ][ #  # ]:          0 :         if ((multi || sortedmulti) && (providers.empty() || providers.size() > MAX_PUBKEYS_PER_MULTISIG)) {
                 [ #  # ]
    1609         [ #  # ]:          0 :             error = strprintf("Cannot have %u keys in multisig; must have between 1 and %d keys, inclusive", providers.size(), MAX_PUBKEYS_PER_MULTISIG);
    1610                 :          0 :             return nullptr;
    1611 [ #  # ][ #  # ]:          0 :         } else if ((multi_a || sortedmulti_a) && (providers.empty() || providers.size() > MAX_PUBKEYS_PER_MULTI_A)) {
    1612         [ #  # ]:          0 :             error = strprintf("Cannot have %u keys in multi_a; must have between 1 and %d keys, inclusive", providers.size(), MAX_PUBKEYS_PER_MULTI_A);
    1613                 :          0 :             return nullptr;
    1614         [ #  # ]:          0 :         } else if (thres < 1) {
    1615         [ #  # ]:          0 :             error = strprintf("Multisig threshold cannot be %d, must be at least 1", thres);
    1616                 :          0 :             return nullptr;
    1617         [ #  # ]:          0 :         } else if (thres > providers.size()) {
    1618         [ #  # ]:          0 :             error = strprintf("Multisig threshold cannot be larger than the number of keys; threshold is %d but only %u keys specified", thres, providers.size());
    1619                 :          0 :             return nullptr;
    1620                 :            :         }
    1621         [ #  # ]:          0 :         if (ctx == ParseScriptContext::TOP) {
    1622         [ #  # ]:          0 :             if (providers.size() > 3) {
    1623         [ #  # ]:          0 :                 error = strprintf("Cannot have %u pubkeys in bare multisig; only at most 3 pubkeys", providers.size());
    1624                 :          0 :                 return nullptr;
    1625                 :            :             }
    1626                 :          0 :         }
    1627         [ #  # ]:          0 :         if (ctx == ParseScriptContext::P2SH) {
    1628                 :            :             // This limits the maximum number of compressed pubkeys to 15.
    1629         [ #  # ]:          0 :             if (script_size + 3 > MAX_SCRIPT_ELEMENT_SIZE) {
    1630         [ #  # ]:          0 :                 error = strprintf("P2SH script is too large, %d bytes is larger than %d bytes", script_size + 3, MAX_SCRIPT_ELEMENT_SIZE);
    1631                 :          0 :                 return nullptr;
    1632                 :            :             }
    1633                 :          0 :         }
    1634 [ #  # ][ #  # ]:          0 :         if (multi || sortedmulti) {
    1635         [ #  # ]:          0 :             return std::make_unique<MultisigDescriptor>(thres, std::move(providers), sortedmulti);
    1636                 :            :         } else {
    1637         [ #  # ]:          0 :             return std::make_unique<MultiADescriptor>(thres, std::move(providers), sortedmulti_a);
    1638                 :            :         }
    1639 [ +  - ][ -  + ]:          8 :     } else if (multi || sortedmulti) {
    1640                 :          0 :         error = "Can only have multi/sortedmulti at top level, in sh(), or in wsh()";
    1641                 :          0 :         return nullptr;
    1642 [ +  - ][ -  + ]:          8 :     } else if (multi_a || sortedmulti_a) {
    1643                 :          0 :         error = "Can only have multi_a/sortedmulti_a inside tr()";
    1644                 :          0 :         return nullptr;
    1645                 :            :     }
    1646 [ +  + ][ +  - ]:         16 :     if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH) && Func("wpkh", expr)) {
         [ +  - ][ +  - ]
         [ -  + ][ -  + ]
         [ +  + ][ #  # ]
                 [ #  # ]
    1647                 :          4 :         auto pubkey = ParsePubkey(key_exp_index, expr, ParseScriptContext::P2WPKH, out, error);
    1648         [ -  + ]:          4 :         if (!pubkey) {
    1649         [ #  # ]:          0 :             error = strprintf("wpkh(): %s", error);
    1650                 :          0 :             return nullptr;
    1651                 :            :         }
    1652                 :          4 :         key_exp_index++;
    1653         [ +  - ]:          4 :         return std::make_unique<WPKHDescriptor>(std::move(pubkey));
    1654 [ +  - ][ +  - ]:          8 :     } else if (Func("wpkh", expr)) {
                 [ -  + ]
    1655                 :          0 :         error = "Can only have wpkh() at top level or inside sh()";
    1656                 :          0 :         return nullptr;
    1657                 :            :     }
    1658 [ -  + ][ +  - ]:          8 :     if (ctx == ParseScriptContext::TOP && Func("sh", expr)) {
         [ +  - ][ -  + ]
         [ -  + ][ +  + ]
         [ #  # ][ #  # ]
    1659                 :          2 :         auto desc = ParseScript(key_exp_index, expr, ParseScriptContext::P2SH, out, error);
    1660 [ +  - ][ -  + ]:          2 :         if (!desc || expr.size()) return nullptr;
    1661         [ +  - ]:          2 :         return std::make_unique<SHDescriptor>(std::move(desc));
    1662 [ +  - ][ +  - ]:          4 :     } else if (Func("sh", expr)) {
                 [ -  + ]
    1663                 :          0 :         error = "Can only have sh() at top level";
    1664                 :          0 :         return nullptr;
    1665                 :            :     }
    1666 [ -  + ][ #  # ]:          4 :     if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH) && Func("wsh", expr)) {
         [ +  - ][ +  - ]
         [ -  + ][ -  + ]
         [ -  + ][ #  # ]
                 [ #  # ]
    1667                 :          0 :         auto desc = ParseScript(key_exp_index, expr, ParseScriptContext::P2WSH, out, error);
    1668 [ #  # ][ #  # ]:          0 :         if (!desc || expr.size()) return nullptr;
    1669         [ #  # ]:          0 :         return std::make_unique<WSHDescriptor>(std::move(desc));
    1670 [ +  - ][ +  - ]:          2 :     } else if (Func("wsh", expr)) {
                 [ -  + ]
    1671                 :          0 :         error = "Can only have wsh() at top level or inside sh()";
    1672                 :          0 :         return nullptr;
    1673                 :            :     }
    1674 [ -  + ][ +  - ]:          4 :     if (ctx == ParseScriptContext::TOP && Func("addr", expr)) {
         [ +  - ][ -  + ]
         [ -  + ][ -  + ]
         [ #  # ][ #  # ]
    1675 [ #  # ][ #  # ]:          0 :         CTxDestination dest = DecodeDestination(std::string(expr.begin(), expr.end()));
    1676 [ #  # ][ #  # ]:          0 :         if (!IsValidDestination(dest)) {
    1677         [ #  # ]:          0 :             error = "Address is not valid";
    1678                 :          0 :             return nullptr;
    1679                 :            :         }
    1680         [ #  # ]:          0 :         return std::make_unique<AddressDescriptor>(std::move(dest));
    1681 [ +  - ][ +  - ]:          2 :     } else if (Func("addr", expr)) {
                 [ -  + ]
    1682                 :          0 :         error = "Can only have addr() at top level";
    1683                 :          0 :         return nullptr;
    1684                 :            :     }
    1685 [ -  + ][ +  - ]:          4 :     if (ctx == ParseScriptContext::TOP && Func("tr", expr)) {
         [ +  - ][ -  + ]
         [ -  + ][ +  - ]
         [ #  # ][ #  # ]
    1686                 :          2 :         auto arg = Expr(expr);
    1687                 :          2 :         auto internal_key = ParsePubkey(key_exp_index, arg, ParseScriptContext::P2TR, out, error);
    1688         [ +  - ]:          2 :         if (!internal_key) {
    1689         [ #  # ]:          0 :             error = strprintf("tr(): %s", error);
    1690                 :          0 :             return nullptr;
    1691                 :            :         }
    1692                 :          2 :         ++key_exp_index;
    1693                 :          2 :         std::vector<std::unique_ptr<DescriptorImpl>> subscripts; //!< list of script subexpressions
    1694                 :          2 :         std::vector<int> depths; //!< depth in the tree of each subexpression (same length subscripts)
    1695         [ +  - ]:          2 :         if (expr.size()) {
    1696 [ #  # ][ #  # ]:          0 :             if (!Const(",", expr)) {
                 [ #  # ]
    1697         [ #  # ]:          0 :                 error = strprintf("tr: expected ',', got '%c'", expr[0]);
    1698                 :          0 :                 return nullptr;
    1699                 :            :             }
    1700                 :            :             /** The path from the top of the tree to what we're currently processing.
    1701                 :            :              * branches[i] == false: left branch in the i'th step from the top; true: right branch.
    1702                 :            :              */
    1703                 :          0 :             std::vector<bool> branches;
    1704                 :            :             // Loop over all provided scripts. In every iteration exactly one script will be processed.
    1705                 :            :             // Use a do-loop because inside this if-branch we expect at least one script.
    1706                 :          0 :             do {
    1707                 :            :                 // First process all open braces.
    1708 [ #  # ][ #  # ]:          0 :                 while (Const("{", expr)) {
                 [ #  # ]
    1709         [ #  # ]:          0 :                     branches.push_back(false); // new left branch
    1710         [ #  # ]:          0 :                     if (branches.size() > TAPROOT_CONTROL_MAX_NODE_COUNT) {
    1711         [ #  # ]:          0 :                         error = strprintf("tr() supports at most %i nesting levels", TAPROOT_CONTROL_MAX_NODE_COUNT);
    1712                 :          0 :                         return nullptr;
    1713                 :            :                     }
    1714                 :            :                 }
    1715                 :            :                 // Process the actual script expression.
    1716         [ #  # ]:          0 :                 auto sarg = Expr(expr);
    1717 [ #  # ][ #  # ]:          0 :                 subscripts.emplace_back(ParseScript(key_exp_index, sarg, ParseScriptContext::P2TR, out, error));
    1718         [ #  # ]:          0 :                 if (!subscripts.back()) return nullptr;
    1719         [ #  # ]:          0 :                 depths.push_back(branches.size());
    1720                 :            :                 // Process closing braces; one is expected for every right branch we were in.
    1721 [ #  # ][ #  # ]:          0 :                 while (branches.size() && branches.back()) {
                 [ #  # ]
    1722 [ #  # ][ #  # ]:          0 :                     if (!Const("}", expr)) {
                 [ #  # ]
    1723         [ #  # ]:          0 :                         error = strprintf("tr(): expected '}' after script expression");
    1724                 :          0 :                         return nullptr;
    1725                 :            :                     }
    1726         [ #  # ]:          0 :                     branches.pop_back(); // move up one level after encountering '}'
    1727                 :            :                 }
    1728                 :            :                 // If after that, we're at the end of a left branch, expect a comma.
    1729 [ #  # ][ #  # ]:          0 :                 if (branches.size() && !branches.back()) {
                 [ #  # ]
    1730 [ #  # ][ #  # ]:          0 :                     if (!Const(",", expr)) {
                 [ #  # ]
    1731         [ #  # ]:          0 :                         error = strprintf("tr(): expected ',' after script expression");
    1732                 :          0 :                         return nullptr;
    1733                 :            :                     }
    1734         [ #  # ]:          0 :                     branches.back() = true; // And now we're in a right branch.
    1735                 :          0 :                 }
    1736         [ #  # ]:          0 :             } while (branches.size());
    1737                 :            :             // After we've explored a whole tree, we must be at the end of the expression.
    1738         [ #  # ]:          0 :             if (expr.size()) {
    1739         [ #  # ]:          0 :                 error = strprintf("tr(): expected ')' after script expression");
    1740                 :          0 :                 return nullptr;
    1741                 :            :             }
    1742         [ #  # ]:          0 :         }
    1743 [ +  - ][ +  - ]:          2 :         assert(TaprootBuilder::ValidDepths(depths));
    1744         [ +  - ]:          2 :         return std::make_unique<TRDescriptor>(std::move(internal_key), std::move(subscripts), std::move(depths));
    1745 [ #  # ][ #  # ]:          2 :     } else if (Func("tr", expr)) {
                 [ #  # ]
    1746                 :          0 :         error = "Can only have tr at top level";
    1747                 :          0 :         return nullptr;
    1748                 :            :     }
    1749 [ #  # ][ #  # ]:          0 :     if (ctx == ParseScriptContext::TOP && Func("rawtr", expr)) {
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
    1750                 :          0 :         auto arg = Expr(expr);
    1751         [ #  # ]:          0 :         if (expr.size()) {
    1752                 :          0 :             error = strprintf("rawtr(): only one key expected.");
    1753                 :          0 :             return nullptr;
    1754                 :            :         }
    1755                 :          0 :         auto output_key = ParsePubkey(key_exp_index, arg, ParseScriptContext::P2TR, out, error);
    1756         [ #  # ]:          0 :         if (!output_key) return nullptr;
    1757                 :          0 :         ++key_exp_index;
    1758         [ #  # ]:          0 :         return std::make_unique<RawTRDescriptor>(std::move(output_key));
    1759 [ #  # ][ #  # ]:          0 :     } else if (Func("rawtr", expr)) {
                 [ #  # ]
    1760                 :          0 :         error = "Can only have rawtr at top level";
    1761                 :          0 :         return nullptr;
    1762                 :            :     }
    1763 [ #  # ][ #  # ]:          0 :     if (ctx == ParseScriptContext::TOP && Func("raw", expr)) {
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
    1764         [ #  # ]:          0 :         std::string str(expr.begin(), expr.end());
    1765 [ #  # ][ #  # ]:          0 :         if (!IsHex(str)) {
    1766         [ #  # ]:          0 :             error = "Raw script is not hex";
    1767                 :          0 :             return nullptr;
    1768                 :            :         }
    1769         [ #  # ]:          0 :         auto bytes = ParseHex(str);
    1770 [ #  # ][ #  # ]:          0 :         return std::make_unique<RawDescriptor>(CScript(bytes.begin(), bytes.end()));
    1771 [ #  # ][ #  # ]:          0 :     } else if (Func("raw", expr)) {
                 [ #  # ]
    1772                 :          0 :         error = "Can only have raw() at top level";
    1773                 :          0 :         return nullptr;
    1774                 :            :     }
    1775                 :            :     // Process miniscript expressions.
    1776                 :            :     {
    1777                 :          0 :         const auto script_ctx{ctx == ParseScriptContext::P2WSH ? miniscript::MiniscriptContext::P2WSH : miniscript::MiniscriptContext::TAPSCRIPT};
    1778                 :          0 :         KeyParser parser(/*out = */&out, /* in = */nullptr, /* ctx = */script_ctx, key_exp_index);
    1779 [ #  # ][ #  # ]:          0 :         auto node = miniscript::FromString(std::string(expr.begin(), expr.end()), parser);
    1780         [ #  # ]:          0 :         if (node) {
    1781 [ #  # ][ #  # ]:          0 :             if (ctx != ParseScriptContext::P2WSH && ctx != ParseScriptContext::P2TR) {
    1782         [ #  # ]:          0 :                 error = "Miniscript expressions can only be used in wsh or tr.";
    1783                 :          0 :                 return nullptr;
    1784                 :            :             }
    1785 [ #  # ][ #  # ]:          0 :             if (parser.m_key_parsing_error != "") {
    1786                 :          0 :                 error = std::move(parser.m_key_parsing_error);
    1787                 :          0 :                 return nullptr;
    1788                 :            :             }
    1789 [ #  # ][ #  # ]:          0 :             if (!node->IsSane() || node->IsNotSatisfiable()) {
         [ #  # ][ #  # ]
    1790                 :            :                 // Try to find the first insane sub for better error reporting.
    1791                 :          0 :                 auto insane_node = node.get();
    1792 [ #  # ][ #  # ]:          0 :                 if (const auto sub = node->FindInsaneSub()) insane_node = sub;
    1793 [ #  # ][ #  # ]:          0 :                 if (const auto str = insane_node->ToString(parser)) error = *str;
                 [ #  # ]
    1794 [ #  # ][ #  # ]:          0 :                 if (!insane_node->IsValid()) {
    1795         [ #  # ]:          0 :                     error += " is invalid";
    1796 [ #  # ][ #  # ]:          0 :                 } else if (!node->IsSane()) {
    1797         [ #  # ]:          0 :                     error += " is not sane";
    1798 [ #  # ][ #  # ]:          0 :                     if (!insane_node->IsNonMalleable()) {
    1799         [ #  # ]:          0 :                         error += ": malleable witnesses exist";
    1800 [ #  # ][ #  # ]:          0 :                     } else if (insane_node == node.get() && !insane_node->NeedsSignature()) {
                 [ #  # ]
    1801         [ #  # ]:          0 :                         error += ": witnesses without signature exist";
    1802 [ #  # ][ #  # ]:          0 :                     } else if (!insane_node->CheckTimeLocksMix()) {
    1803         [ #  # ]:          0 :                         error += ": contains mixes of timelocks expressed in blocks and seconds";
    1804 [ #  # ][ #  # ]:          0 :                     } else if (!insane_node->CheckDuplicateKey()) {
    1805         [ #  # ]:          0 :                         error += ": contains duplicate public keys";
    1806 [ #  # ][ #  # ]:          0 :                     } else if (!insane_node->ValidSatisfactions()) {
    1807         [ #  # ]:          0 :                         error += ": needs witnesses that may exceed resource limits";
    1808                 :          0 :                     }
    1809                 :          0 :                 } else {
    1810         [ #  # ]:          0 :                     error += " is not satisfiable";
    1811                 :            :                 }
    1812                 :          0 :                 return nullptr;
    1813                 :            :             }
    1814                 :            :             // A signature check is required for a miniscript to be sane. Therefore no sane miniscript
    1815                 :            :             // may have an empty list of public keys.
    1816         [ #  # ]:          0 :             CHECK_NONFATAL(!parser.m_keys.empty());
    1817                 :          0 :             key_exp_index += parser.m_keys.size();
    1818         [ #  # ]:          0 :             return std::make_unique<MiniscriptDescriptor>(std::move(parser.m_keys), std::move(node));
    1819                 :            :         }
    1820      [ #  #  # ]:          0 :     }
    1821         [ #  # ]:          0 :     if (ctx == ParseScriptContext::P2SH) {
    1822                 :          0 :         error = "A function is needed within P2SH";
    1823                 :          0 :         return nullptr;
    1824         [ #  # ]:          0 :     } else if (ctx == ParseScriptContext::P2WSH) {
    1825                 :          0 :         error = "A function is needed within P2WSH";
    1826                 :          0 :         return nullptr;
    1827                 :            :     }
    1828 [ #  # ][ #  # ]:          0 :     error = strprintf("'%s' is not a valid descriptor function", std::string(expr.begin(), expr.end()));
    1829                 :          0 :     return nullptr;
    1830                 :         11 : }
    1831                 :            : 
    1832                 :          0 : std::unique_ptr<DescriptorImpl> InferMultiA(const CScript& script, ParseScriptContext ctx, const SigningProvider& provider)
    1833                 :            : {
    1834                 :          0 :     auto match = MatchMultiA(script);
    1835         [ #  # ]:          0 :     if (!match) return {};
    1836                 :          0 :     std::vector<std::unique_ptr<PubkeyProvider>> keys;
    1837         [ #  # ]:          0 :     keys.reserve(match->second.size());
    1838         [ #  # ]:          0 :     for (const auto keyspan : match->second) {
    1839         [ #  # ]:          0 :         if (keyspan.size() != 32) return {};
    1840 [ #  # ][ #  # ]:          0 :         auto key = InferXOnlyPubkey(XOnlyPubKey{keyspan}, ctx, provider);
    1841         [ #  # ]:          0 :         if (!key) return {};
    1842         [ #  # ]:          0 :         keys.push_back(std::move(key));
    1843         [ #  # ]:          0 :     }
    1844         [ #  # ]:          0 :     return std::make_unique<MultiADescriptor>(match->first, std::move(keys));
    1845                 :          0 : }
    1846                 :            : 
    1847                 :     418877 : std::unique_ptr<DescriptorImpl> InferScript(const CScript& script, ParseScriptContext ctx, const SigningProvider& provider)
    1848                 :            : {
    1849 [ -  + ][ #  # ]:     418877 :     if (ctx == ParseScriptContext::P2TR && script.size() == 34 && script[0] == 32 && script[33] == OP_CHECKSIG) {
         [ #  # ][ #  # ]
    1850                 :          0 :         XOnlyPubKey key{Span{script}.subspan(1, 32)};
    1851         [ #  # ]:          0 :         return std::make_unique<PKDescriptor>(InferXOnlyPubkey(key, ctx, provider), true);
    1852                 :            :     }
    1853                 :            : 
    1854         [ +  - ]:     418877 :     if (ctx == ParseScriptContext::P2TR) {
    1855                 :          0 :         auto ret = InferMultiA(script, ctx, provider);
    1856         [ #  # ]:          0 :         if (ret) return ret;
    1857         [ #  # ]:          0 :     }
    1858                 :            : 
    1859                 :     418877 :     std::vector<std::vector<unsigned char>> data;
    1860         [ +  - ]:     418877 :     TxoutType txntype = Solver(script, data);
    1861                 :            : 
    1862 [ +  + ][ -  + ]:     418877 :     if (txntype == TxoutType::PUBKEY && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
                 [ #  # ]
    1863 [ +  - ][ +  - ]:     412903 :         CPubKey pubkey(data[0]);
    1864 [ +  - ][ +  - ]:     825806 :         if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
                 [ +  - ]
    1865         [ +  - ]:     412903 :             return std::make_unique<PKDescriptor>(std::move(pubkey_provider));
    1866                 :            :         }
    1867                 :          0 :     }
    1868 [ +  + ][ -  + ]:       5974 :     if (txntype == TxoutType::PUBKEYHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
                 [ #  # ]
    1869 [ +  - ][ +  - ]:        428 :         uint160 hash(data[0]);
    1870         [ +  - ]:        428 :         CKeyID keyid(hash);
    1871         [ +  - ]:        428 :         CPubKey pubkey;
    1872 [ +  - ][ +  - ]:        428 :         if (provider.GetPubKey(keyid, pubkey)) {
    1873 [ +  - ][ +  - ]:        856 :             if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
                 [ +  - ]
    1874         [ +  - ]:        428 :                 return std::make_unique<PKHDescriptor>(std::move(pubkey_provider));
    1875                 :            :             }
    1876                 :          0 :         }
    1877                 :          0 :     }
    1878 [ +  + ][ +  + ]:       5546 :     if (txntype == TxoutType::WITNESS_V0_KEYHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH)) {
    1879 [ +  - ][ +  - ]:        902 :         uint160 hash(data[0]);
    1880         [ +  - ]:        902 :         CKeyID keyid(hash);
    1881         [ +  - ]:        902 :         CPubKey pubkey;
    1882 [ +  - ][ +  - ]:        902 :         if (provider.GetPubKey(keyid, pubkey)) {
    1883 [ +  - ][ +  - ]:       1804 :             if (auto pubkey_provider = InferPubkey(pubkey, ParseScriptContext::P2WPKH, provider)) {
                 [ +  - ]
    1884         [ +  - ]:        902 :                 return std::make_unique<WPKHDescriptor>(std::move(pubkey_provider));
    1885                 :            :             }
    1886                 :          0 :         }
    1887                 :          0 :     }
    1888 [ -  + ][ #  # ]:       4644 :     if (txntype == TxoutType::MULTISIG && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
         [ #  # ][ #  # ]
    1889                 :          0 :         bool ok = true;
    1890                 :          0 :         std::vector<std::unique_ptr<PubkeyProvider>> providers;
    1891         [ #  # ]:          0 :         for (size_t i = 1; i + 1 < data.size(); ++i) {
    1892 [ #  # ][ #  # ]:          0 :             CPubKey pubkey(data[i]);
    1893 [ #  # ][ #  # ]:          0 :             if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
                 [ #  # ]
    1894         [ #  # ]:          0 :                 providers.push_back(std::move(pubkey_provider));
    1895                 :          0 :             } else {
    1896                 :          0 :                 ok = false;
    1897                 :          0 :                 break;
    1898                 :            :             }
    1899                 :          0 :         }
    1900 [ #  # ][ #  # ]:          0 :         if (ok) return std::make_unique<MultisigDescriptor>((int)data[0][0], std::move(providers));
    1901         [ #  # ]:          0 :     }
    1902 [ +  + ][ +  - ]:       4644 :     if (txntype == TxoutType::SCRIPTHASH && ctx == ParseScriptContext::TOP) {
    1903 [ +  - ][ +  - ]:        288 :         uint160 hash(data[0]);
    1904         [ +  - ]:        288 :         CScriptID scriptid(hash);
    1905         [ +  - ]:        288 :         CScript subscript;
    1906 [ +  - ][ +  - ]:        288 :         if (provider.GetCScript(scriptid, subscript)) {
    1907         [ +  - ]:        288 :             auto sub = InferScript(subscript, ParseScriptContext::P2SH, provider);
    1908 [ +  - ][ +  - ]:        288 :             if (sub) return std::make_unique<SHDescriptor>(std::move(sub));
    1909         [ +  - ]:        288 :         }
    1910         [ +  - ]:        288 :     }
    1911 [ -  + ][ #  # ]:       4356 :     if (txntype == TxoutType::WITNESS_V0_SCRIPTHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH)) {
    1912 [ #  # ][ #  # ]:          0 :         CScriptID scriptid{RIPEMD160(data[0])};
                 [ #  # ]
    1913         [ #  # ]:          0 :         CScript subscript;
    1914 [ #  # ][ #  # ]:          0 :         if (provider.GetCScript(scriptid, subscript)) {
    1915         [ #  # ]:          0 :             auto sub = InferScript(subscript, ParseScriptContext::P2WSH, provider);
    1916 [ #  # ][ #  # ]:          0 :             if (sub) return std::make_unique<WSHDescriptor>(std::move(sub));
    1917         [ #  # ]:          0 :         }
    1918         [ #  # ]:          0 :     }
    1919 [ +  - ][ +  - ]:       4356 :     if (txntype == TxoutType::WITNESS_V1_TAPROOT && ctx == ParseScriptContext::TOP) {
    1920                 :            :         // Extract x-only pubkey from output.
    1921         [ +  - ]:       4356 :         XOnlyPubKey pubkey;
    1922 [ +  - ][ +  - ]:       4356 :         std::copy(data[0].begin(), data[0].end(), pubkey.begin());
    1923                 :            :         // Request spending data.
    1924         [ +  - ]:       4356 :         TaprootSpendData tap;
    1925 [ +  - ][ +  - ]:       4356 :         if (provider.GetTaprootSpendData(pubkey, tap)) {
    1926                 :            :             // If found, convert it back to tree form.
    1927         [ +  - ]:       4356 :             auto tree = InferTaprootTree(tap, pubkey);
    1928         [ -  + ]:       4356 :             if (tree) {
    1929                 :            :                 // If that works, try to infer subdescriptors for all leaves.
    1930                 :       4356 :                 bool ok = true;
    1931                 :       4356 :                 std::vector<std::unique_ptr<DescriptorImpl>> subscripts; //!< list of script subexpressions
    1932                 :       4356 :                 std::vector<int> depths; //!< depth in the tree of each subexpression (same length subscripts)
    1933         [ +  - ]:       4356 :                 for (const auto& [depth, script, leaf_ver] : *tree) {
    1934                 :          0 :                     std::unique_ptr<DescriptorImpl> subdesc;
    1935         [ #  # ]:          0 :                     if (leaf_ver == TAPROOT_LEAF_TAPSCRIPT) {
    1936 [ #  # ][ #  # ]:          0 :                         subdesc = InferScript(CScript(script.begin(), script.end()), ParseScriptContext::P2TR, provider);
                 [ #  # ]
    1937                 :          0 :                     }
    1938         [ #  # ]:          0 :                     if (!subdesc) {
    1939                 :          0 :                         ok = false;
    1940                 :          0 :                         break;
    1941                 :            :                     } else {
    1942         [ #  # ]:          0 :                         subscripts.push_back(std::move(subdesc));
    1943         [ #  # ]:          0 :                         depths.push_back(depth);
    1944                 :            :                     }
    1945         [ #  # ]:          0 :                 }
    1946         [ +  - ]:       4356 :                 if (ok) {
    1947         [ +  - ]:       4356 :                     auto key = InferXOnlyPubkey(tap.internal_key, ParseScriptContext::P2TR, provider);
    1948         [ +  - ]:       4356 :                     return std::make_unique<TRDescriptor>(std::move(key), std::move(subscripts), std::move(depths));
    1949                 :       4356 :                 }
    1950         [ +  - ]:       4356 :             }
    1951         [ +  - ]:       4356 :         }
    1952                 :            :         // If the above doesn't work, construct a rawtr() descriptor with just the encoded x-only pubkey.
    1953 [ #  # ][ #  # ]:          0 :         if (pubkey.IsFullyValid()) {
    1954         [ #  # ]:          0 :             auto key = InferXOnlyPubkey(pubkey, ParseScriptContext::P2TR, provider);
    1955         [ #  # ]:          0 :             if (key) {
    1956         [ #  # ]:          0 :                 return std::make_unique<RawTRDescriptor>(std::move(key));
    1957                 :            :             }
    1958         [ #  # ]:          0 :         }
    1959         [ +  - ]:       4356 :     }
    1960                 :            : 
    1961 [ #  # ][ #  # ]:          0 :     if (ctx == ParseScriptContext::P2WSH || ctx == ParseScriptContext::P2TR) {
    1962                 :          0 :         const auto script_ctx{ctx == ParseScriptContext::P2WSH ? miniscript::MiniscriptContext::P2WSH : miniscript::MiniscriptContext::TAPSCRIPT};
    1963         [ #  # ]:          0 :         KeyParser parser(/* out = */nullptr, /* in = */&provider, /* ctx = */script_ctx);
    1964         [ #  # ]:          0 :         auto node = miniscript::FromScript(script, parser);
    1965 [ #  # ][ #  # ]:          0 :         if (node && node->IsSane()) {
                 [ #  # ]
    1966         [ #  # ]:          0 :             return std::make_unique<MiniscriptDescriptor>(std::move(parser.m_keys), std::move(node));
    1967                 :            :         }
    1968         [ #  # ]:          0 :     }
    1969                 :            : 
    1970                 :            :     // The following descriptors are all top-level only descriptors.
    1971                 :            :     // So if we are not at the top level, return early.
    1972         [ #  # ]:          0 :     if (ctx != ParseScriptContext::TOP) return nullptr;
    1973                 :            : 
    1974         [ #  # ]:          0 :     CTxDestination dest;
    1975 [ #  # ][ #  # ]:          0 :     if (ExtractDestination(script, dest)) {
    1976 [ #  # ][ #  # ]:          0 :         if (GetScriptForDestination(dest) == script) {
                 [ #  # ]
    1977         [ #  # ]:          0 :             return std::make_unique<AddressDescriptor>(std::move(dest));
    1978                 :            :         }
    1979                 :          0 :     }
    1980                 :            : 
    1981         [ #  # ]:          0 :     return std::make_unique<RawDescriptor>(script);
    1982                 :     418877 : }
    1983                 :            : 
    1984                 :            : 
    1985                 :            : } // namespace
    1986                 :            : 
    1987                 :            : /** Check a descriptor checksum, and update desc to be the checksum-less part. */
    1988                 :          9 : bool CheckChecksum(Span<const char>& sp, bool require_checksum, std::string& error, std::string* out_checksum = nullptr)
    1989                 :            : {
    1990                 :            :     using namespace spanparsing;
    1991                 :            : 
    1992                 :          9 :     auto check_split = Split(sp, '#');
    1993         [ -  + ]:          9 :     if (check_split.size() > 2) {
    1994         [ #  # ]:          0 :         error = "Multiple '#' symbols";
    1995                 :          0 :         return false;
    1996                 :            :     }
    1997 [ +  - ][ -  + ]:          9 :     if (check_split.size() == 1 && require_checksum){
    1998         [ #  # ]:          0 :         error = "Missing checksum";
    1999                 :          0 :         return false;
    2000                 :            :     }
    2001         [ +  - ]:          9 :     if (check_split.size() == 2) {
    2002         [ #  # ]:          0 :         if (check_split[1].size() != 8) {
    2003         [ #  # ]:          0 :             error = strprintf("Expected 8 character checksum, not %u characters", check_split[1].size());
    2004                 :          0 :             return false;
    2005                 :            :         }
    2006                 :          0 :     }
    2007         [ +  - ]:          9 :     auto checksum = DescriptorChecksum(check_split[0]);
    2008         [ -  + ]:          9 :     if (checksum.empty()) {
    2009         [ #  # ]:          0 :         error = "Invalid characters in payload";
    2010                 :          0 :         return false;
    2011                 :            :     }
    2012         [ -  + ]:          9 :     if (check_split.size() == 2) {
    2013 [ #  # ][ #  # ]:          0 :         if (!std::equal(checksum.begin(), checksum.end(), check_split[1].begin())) {
    2014 [ #  # ][ #  # ]:          0 :             error = strprintf("Provided checksum '%s' does not match computed checksum '%s'", std::string(check_split[1].begin(), check_split[1].end()), checksum);
    2015                 :          0 :             return false;
    2016                 :            :         }
    2017                 :          0 :     }
    2018         [ +  - ]:          9 :     if (out_checksum) *out_checksum = std::move(checksum);
    2019                 :          9 :     sp = check_split[0];
    2020                 :          9 :     return true;
    2021                 :          9 : }
    2022                 :            : 
    2023                 :          9 : std::unique_ptr<Descriptor> Parse(const std::string& descriptor, FlatSigningProvider& out, std::string& error, bool require_checksum)
    2024                 :            : {
    2025                 :          9 :     Span<const char> sp{descriptor};
    2026         [ -  + ]:          9 :     if (!CheckChecksum(sp, require_checksum, error)) return nullptr;
    2027                 :          9 :     uint32_t key_exp_index = 0;
    2028                 :          9 :     auto ret = ParseScript(key_exp_index, sp, ParseScriptContext::TOP, out, error);
    2029 [ +  - ][ +  - ]:          9 :     if (sp.size() == 0 && ret) return std::unique_ptr<Descriptor>(std::move(ret));
    2030                 :          0 :     return nullptr;
    2031                 :          9 : }
    2032                 :            : 
    2033                 :          0 : std::string GetDescriptorChecksum(const std::string& descriptor)
    2034                 :            : {
    2035                 :          0 :     std::string ret;
    2036                 :          0 :     std::string error;
    2037         [ #  # ]:          0 :     Span<const char> sp{descriptor};
    2038 [ #  # ][ #  # ]:          0 :     if (!CheckChecksum(sp, false, error, &ret)) return "";
                 [ #  # ]
    2039                 :          0 :     return ret;
    2040                 :          0 : }
    2041                 :            : 
    2042                 :     418589 : std::unique_ptr<Descriptor> InferDescriptor(const CScript& script, const SigningProvider& provider)
    2043                 :            : {
    2044                 :     418589 :     return InferScript(script, ParseScriptContext::TOP, provider);
    2045                 :            : }
    2046                 :            : 
    2047                 :      19763 : uint256 DescriptorID(const Descriptor& desc)
    2048                 :            : {
    2049                 :      19763 :     std::string desc_str = desc.ToString(/*compat_format=*/true);
    2050         [ +  - ]:      19763 :     uint256 id;
    2051 [ +  - ][ +  - ]:      19763 :     CSHA256().Write((unsigned char*)desc_str.data(), desc_str.size()).Finalize(id.begin());
         [ +  - ][ +  - ]
    2052                 :            :     return id;
    2053                 :      19763 : }
    2054                 :            : 
    2055                 :         24 : void DescriptorCache::CacheParentExtPubKey(uint32_t key_exp_pos, const CExtPubKey& xpub)
    2056                 :            : {
    2057                 :         24 :     m_parent_xpubs[key_exp_pos] = xpub;
    2058                 :         24 : }
    2059                 :            : 
    2060                 :          0 : void DescriptorCache::CacheDerivedExtPubKey(uint32_t key_exp_pos, uint32_t der_index, const CExtPubKey& xpub)
    2061                 :            : {
    2062                 :          0 :     auto& xpubs = m_derived_xpubs[key_exp_pos];
    2063                 :          0 :     xpubs[der_index] = xpub;
    2064                 :          0 : }
    2065                 :            : 
    2066                 :         24 : void DescriptorCache::CacheLastHardenedExtPubKey(uint32_t key_exp_pos, const CExtPubKey& xpub)
    2067                 :            : {
    2068                 :         24 :     m_last_hardened_xpubs[key_exp_pos] = xpub;
    2069                 :         24 : }
    2070                 :            : 
    2071                 :      18926 : bool DescriptorCache::GetCachedParentExtPubKey(uint32_t key_exp_pos, CExtPubKey& xpub) const
    2072                 :            : {
    2073                 :      18926 :     const auto& it = m_parent_xpubs.find(key_exp_pos);
    2074         [ +  + ]:      18926 :     if (it == m_parent_xpubs.end()) return false;
    2075                 :      18910 :     xpub = it->second;
    2076                 :      18910 :     return true;
    2077                 :      18926 : }
    2078                 :            : 
    2079                 :      18918 : bool DescriptorCache::GetCachedDerivedExtPubKey(uint32_t key_exp_pos, uint32_t der_index, CExtPubKey& xpub) const
    2080                 :            : {
    2081                 :      18918 :     const auto& key_exp_it = m_derived_xpubs.find(key_exp_pos);
    2082         [ +  - ]:      18918 :     if (key_exp_it == m_derived_xpubs.end()) return false;
    2083                 :          0 :     const auto& der_it = key_exp_it->second.find(der_index);
    2084         [ #  # ]:          0 :     if (der_it == key_exp_it->second.end()) return false;
    2085                 :          0 :     xpub = der_it->second;
    2086                 :          0 :     return true;
    2087                 :      18918 : }
    2088                 :            : 
    2089                 :          8 : bool DescriptorCache::GetCachedLastHardenedExtPubKey(uint32_t key_exp_pos, CExtPubKey& xpub) const
    2090                 :            : {
    2091                 :          8 :     const auto& it = m_last_hardened_xpubs.find(key_exp_pos);
    2092         [ +  - ]:          8 :     if (it == m_last_hardened_xpubs.end()) return false;
    2093                 :          0 :     xpub = it->second;
    2094                 :          0 :     return true;
    2095                 :          8 : }
    2096                 :            : 
    2097                 :      10694 : DescriptorCache DescriptorCache::MergeAndDiff(const DescriptorCache& other)
    2098                 :            : {
    2099                 :      10694 :     DescriptorCache diff;
    2100 [ +  - ][ +  + ]:      10702 :     for (const auto& parent_xpub_pair : other.GetCachedParentExtPubKeys()) {
    2101         [ +  - ]:          8 :         CExtPubKey xpub;
    2102 [ +  - ][ -  + ]:          8 :         if (GetCachedParentExtPubKey(parent_xpub_pair.first, xpub)) {
    2103 [ #  # ][ #  # ]:          0 :             if (xpub != parent_xpub_pair.second) {
    2104 [ #  # ][ #  # ]:          0 :                 throw std::runtime_error(std::string(__func__) + ": New cached parent xpub does not match already cached parent xpub");
         [ #  # ][ #  # ]
    2105                 :            :             }
    2106                 :          0 :             continue;
    2107                 :            :         }
    2108         [ +  - ]:          8 :         CacheParentExtPubKey(parent_xpub_pair.first, parent_xpub_pair.second);
    2109         [ +  - ]:          8 :         diff.CacheParentExtPubKey(parent_xpub_pair.first, parent_xpub_pair.second);
    2110                 :            :     }
    2111 [ +  - ][ +  - ]:      10694 :     for (const auto& derived_xpub_map_pair : other.GetCachedDerivedExtPubKeys()) {
    2112         [ #  # ]:          0 :         for (const auto& derived_xpub_pair : derived_xpub_map_pair.second) {
    2113         [ #  # ]:          0 :             CExtPubKey xpub;
    2114 [ #  # ][ #  # ]:          0 :             if (GetCachedDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, xpub)) {
    2115 [ #  # ][ #  # ]:          0 :                 if (xpub != derived_xpub_pair.second) {
    2116 [ #  # ][ #  # ]:          0 :                     throw std::runtime_error(std::string(__func__) + ": New cached derived xpub does not match already cached derived xpub");
         [ #  # ][ #  # ]
    2117                 :            :                 }
    2118                 :          0 :                 continue;
    2119                 :            :             }
    2120         [ #  # ]:          0 :             CacheDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, derived_xpub_pair.second);
    2121         [ #  # ]:          0 :             diff.CacheDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, derived_xpub_pair.second);
    2122                 :            :         }
    2123                 :            :     }
    2124 [ +  - ][ +  + ]:      10702 :     for (const auto& lh_xpub_pair : other.GetCachedLastHardenedExtPubKeys()) {
    2125         [ +  - ]:          8 :         CExtPubKey xpub;
    2126 [ +  - ][ -  + ]:          8 :         if (GetCachedLastHardenedExtPubKey(lh_xpub_pair.first, xpub)) {
    2127 [ #  # ][ #  # ]:          0 :             if (xpub != lh_xpub_pair.second) {
    2128 [ #  # ][ #  # ]:          0 :                 throw std::runtime_error(std::string(__func__) + ": New cached last hardened xpub does not match already cached last hardened xpub");
         [ #  # ][ #  # ]
    2129                 :            :             }
    2130                 :          0 :             continue;
    2131                 :            :         }
    2132         [ +  - ]:          8 :         CacheLastHardenedExtPubKey(lh_xpub_pair.first, lh_xpub_pair.second);
    2133         [ +  - ]:          8 :         diff.CacheLastHardenedExtPubKey(lh_xpub_pair.first, lh_xpub_pair.second);
    2134                 :            :     }
    2135                 :      10694 :     return diff;
    2136         [ +  - ]:      10694 : }
    2137                 :            : 
    2138                 :      21388 : ExtPubKeyMap DescriptorCache::GetCachedParentExtPubKeys() const
    2139                 :            : {
    2140                 :      21388 :     return m_parent_xpubs;
    2141                 :            : }
    2142                 :            : 
    2143                 :      21388 : std::unordered_map<uint32_t, ExtPubKeyMap> DescriptorCache::GetCachedDerivedExtPubKeys() const
    2144                 :            : {
    2145                 :      21388 :     return m_derived_xpubs;
    2146                 :            : }
    2147                 :            : 
    2148                 :      21388 : ExtPubKeyMap DescriptorCache::GetCachedLastHardenedExtPubKeys() const
    2149                 :            : {
    2150                 :      21388 :     return m_last_hardened_xpubs;
    2151                 :            : }

Generated by: LCOV version 1.14