Coverage Report

Created: 2025-06-10 13:21

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