LCOV - code coverage report
Current view: top level - src/script - descriptor.cpp (source / functions) Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 90.2 % 1242 1120
Test Date: 2024-08-28 04:44:32 Functions: 85.5 % 186 159
Branches: 61.9 % 1977 1223

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

Generated by: LCOV version 2.0-1