Coverage Report

Created: 2026-09-21 19:49

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/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 <addresstype.h>
8
#include <attributes.h>
9
#include <consensus/consensus.h>
10
#include <crypto/hex_base.h>
11
#include <crypto/sha256.h>
12
#include <hash.h>
13
#include <key.h>
14
#include <key_io.h>
15
#include <musig.h>
16
#include <primitives/transaction.h>
17
#include <pubkey.h>
18
#include <script/interpreter.h>
19
#include <script/keyorigin.h>
20
#include <script/miniscript.h>
21
#include <script/parsing.h>
22
#include <script/script.h>
23
#include <script/signingprovider.h>
24
#include <script/solver.h>
25
#include <serialize.h>
26
#include <tinyformat.h>
27
#include <uint256.h>
28
#include <util/bip32.h>
29
#include <util/check.h>
30
#include <util/expected.h>
31
#include <util/strencodings.h>
32
#include <util/string.h>
33
#include <util/vector.h>
34
35
#include <algorithm>
36
#include <compare>
37
#include <iterator>
38
#include <map>
39
#include <memory>
40
#include <numeric>
41
#include <optional>
42
#include <span>
43
#include <stdexcept>
44
#include <string>
45
#include <tuple>
46
#include <unordered_set>
47
#include <utility>
48
#include <vector>
49
50
using util::Split;
51
52
util::Expected<void, std::string> CheckDescriptorRangeBounds(int64_t low, int64_t high)
53
432
{
54
432
    if (low < 0) {
55
5
        return util::Unexpected<std::string>("Range should be greater or equal than 0");
56
5
    }
57
427
    if ((high >> 31) != 0) {
58
8
        return util::Unexpected<std::string>("End of range is too high");
59
8
    }
60
419
    if (high >= low + 1000000) {
61
5
        return util::Unexpected<std::string>("Range is too large");
62
5
    }
63
414
    if (low > high) {
64
5
        return util::Unexpected<std::string>("Range specified as [begin,end] must not have begin after end");
65
5
    }
66
409
    return {};
67
414
}
68
69
namespace {
70
71
////////////////////////////////////////////////////////////////////////////
72
// Checksum                                                               //
73
////////////////////////////////////////////////////////////////////////////
74
75
// This section implements a checksum algorithm for descriptors with the
76
// following properties:
77
// * Mistakes in a descriptor string are measured in "symbol errors". The higher
78
//   the number of symbol errors, the harder it is to detect:
79
//   * An error substituting a character from 0123456789()[],'/*abcdefgh@:$%{} for
80
//     another in that set always counts as 1 symbol error.
81
//     * Note that hex encoded keys are covered by these characters. Xprvs and
82
//       xpubs use other characters too, but already have their own checksum
83
//       mechanism.
84
//     * Function names like "multi()" use other characters, but mistakes in
85
//       these would generally result in an unparsable descriptor.
86
//   * A case error always counts as 1 symbol error.
87
//   * Any other 1 character substitution error counts as 1 or 2 symbol errors.
88
// * Any 1 symbol error is always detected.
89
// * Any 2 or 3 symbol error in a descriptor of up to 49154 characters is always detected.
90
// * Any 4 symbol error in a descriptor of up to 507 characters is always detected.
91
// * Any 5 symbol error in a descriptor of up to 77 characters is always detected.
92
// * Is optimized to minimize the chance a 5 symbol error in a descriptor up to 387 characters is undetected
93
// * Random errors have a chance of 1 in 2**40 of being undetected.
94
//
95
// These properties are achieved by expanding every group of 3 (non checksum) characters into
96
// 4 GF(32) symbols, over which a cyclic code is defined.
97
98
/*
99
 * Interprets c as 8 groups of 5 bits which are the coefficients of a degree 8 polynomial over GF(32),
100
 * multiplies that polynomial by x, computes its remainder modulo a generator, and adds the constant term val.
101
 *
102
 * 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}.
103
 * It is chosen to define an cyclic error detecting code which is selected by:
104
 * - Starting from all BCH codes over GF(32) of degree 8 and below, which by construction guarantee detecting
105
 *   3 errors in windows up to 19000 symbols.
106
 * - Taking all those generators, and for degree 7 ones, extend them to degree 8 by adding all degree-1 factors.
107
 * - Selecting just the set of generators that guarantee detecting 4 errors in a window of length 512.
108
 * - Selecting one of those with best worst-case behavior for 5 errors in windows of length up to 512.
109
 *
110
 * The generator and the constants to implement it can be verified using this Sage code:
111
 *   B = GF(2) # Binary field
112
 *   BP.<b> = B[] # Polynomials over the binary field
113
 *   F_mod = b**5 + b**3 + 1
114
 *   F.<f> = GF(32, modulus=F_mod, repr='int') # GF(32) definition
115
 *   FP.<x> = F[] # Polynomials over GF(32)
116
 *   E_mod = x**3 + x + F.fetch_int(8)
117
 *   E.<e> = F.extension(E_mod) # Extension field definition
118
 *   alpha = e**2743 # Choice of an element in extension field
119
 *   for p in divisors(E.order() - 1): # Verify alpha has order 32767.
120
 *       assert((alpha**p == 1) == (p % 32767 == 0))
121
 *   G = lcm([(alpha**i).minpoly() for i in [1056,1057,1058]] + [x + 1])
122
 *   print(G) # Print out the generator
123
 *   for i in [1,2,4,8,16]: # Print out {1,2,4,8,16}*(G mod x^8), packed in hex integers.
124
 *       v = 0
125
 *       for coef in reversed((F.fetch_int(i)*(G % x**8)).coefficients(sparse=True)):
126
 *           v = v*32 + coef.integer_representation()
127
 *       print("0x%x" % v)
128
 */
129
uint64_t PolyMod(uint64_t c, int val)
130
359M
{
131
359M
    uint8_t c0 = c >> 35;
132
359M
    c = ((c & 0x7ffffffff) << 5) ^ val;
133
359M
    if (c0 & 1) c ^= 0xf5dee51989;
134
359M
    if (c0 & 2) c ^= 0xa9fdca3312;
135
359M
    if (c0 & 4) c ^= 0x1bab10e32d;
136
359M
    if (c0 & 8) c ^= 0x3706b1677a;
137
359M
    if (c0 & 16) c ^= 0x644d626ffd;
138
359M
    return c;
139
359M
}
140
141
std::string DescriptorChecksum(const std::span<const char>& span)
142
241k
{
143
    /** A character set designed such that:
144
     *  - The most common 'unprotected' descriptor characters (hex, keypaths) are in the first group of 32.
145
     *  - Case errors cause an offset that's a multiple of 32.
146
     *  - As many alphabetic characters are in the same group (while following the above restrictions).
147
     *
148
     * If p(x) gives the position of a character c in this character set, every group of 3 characters
149
     * (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).
150
     * This means that changes that only affect the lower 5 bits of the position, or only the higher 2 bits, will just
151
     * affect a single symbol.
152
     *
153
     * As a result, within-group-of-32 errors count as 1 symbol, as do cross-group errors that don't affect
154
     * the position within the groups.
155
     */
156
241k
    static const std::string INPUT_CHARSET =
157
241k
        "0123456789()[],'/*abcdefgh@:$%{}"
158
241k
        "IJKLMNOPQRSTUVWXYZ&+-.;<=>?!^_|~"
159
241k
        "ijklmnopqrstuvwxyzABCDEFGH`#\"\\ ";
160
161
    /** The character set for the checksum itself (same as bech32). */
162
241k
    static const std::string CHECKSUM_CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
163
164
241k
    uint64_t c = 1;
165
241k
    int cls = 0;
166
241k
    int clscount = 0;
167
267M
    for (auto ch : span) {
168
267M
        auto pos = INPUT_CHARSET.find(ch);
169
267M
        if (pos == std::string::npos) return "";
170
267M
        c = PolyMod(c, pos & 31); // Emit a symbol for the position inside the group, for every character.
171
267M
        cls = cls * 3 + (pos >> 5); // Accumulate the group numbers
172
267M
        if (++clscount == 3) {
173
            // Emit an extra symbol representing the group numbers, for every 3 characters.
174
89.1M
            c = PolyMod(c, cls);
175
89.1M
            cls = 0;
176
89.1M
            clscount = 0;
177
89.1M
        }
178
267M
    }
179
241k
    if (clscount > 0) c = PolyMod(c, cls);
180
2.17M
    for (int j = 0; j < 8; ++j) c = PolyMod(c, 0); // Shift further to determine the checksum.
181
241k
    c ^= 1; // Prevent appending zeroes from not affecting the checksum.
182
183
241k
    std::string ret(8, ' ');
184
2.17M
    for (int j = 0; j < 8; ++j) ret[j] = CHECKSUM_CHARSET[(c >> (5 * (7 - j))) & 31];
185
241k
    return ret;
186
241k
}
187
188
229k
std::string AddChecksum(const std::string& str) { return str + "#" + DescriptorChecksum(str); }
189
190
////////////////////////////////////////////////////////////////////////////
191
// Internal representation                                                //
192
////////////////////////////////////////////////////////////////////////////
193
194
typedef std::vector<uint32_t> KeyPath;
195
196
/** Interface for public key objects in descriptors. */
197
struct PubkeyProvider
198
{
199
public:
200
    //! Index of this key expression in the descriptor
201
    //! E.g. If this PubkeyProvider is key1 in multi(2, key1, key2, key3), then m_expr_index = 0
202
    const uint32_t m_expr_index;
203
204
829k
    explicit PubkeyProvider(uint32_t exp_index) : m_expr_index(exp_index) {}
205
206
829k
    virtual ~PubkeyProvider() = default;
207
208
    /** Derive a public key and put it into out.
209
     *  read_cache is the cache to read keys from (if not nullptr)
210
     *  write_cache is the cache to write keys to (if not nullptr)
211
     *  Caches are not exclusive but this is not tested. Currently we use them exclusively
212
     */
213
    virtual std::optional<CPubKey> GetPubKey(int pos, const SigningProvider& arg, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const = 0;
214
215
    /** Whether this represent multiple public keys at different positions. */
216
    virtual bool IsRange() const = 0;
217
218
    /** Get the size of the generated public key(s) in bytes (33 or 65). */
219
    virtual size_t GetSize() const = 0;
220
221
    enum class StringType {
222
        PUBLIC,
223
        CANONICAL, // string calculation that always use h
224
        COMPAT // string calculation that mustn't change over time to stay compatible with previous software versions
225
    };
226
227
    /** Get the descriptor string form. */
228
    virtual std::string ToString(StringType type) const = 0;
229
230
    /** Get the descriptor string form including private data (if available in arg).
231
     *  If the private data is not available, the output string in the "out" parameter
232
     *  will not contain any private key information,
233
     *  and this function will return "false".
234
     */
235
    virtual bool ToPrivateString(const SigningProvider& arg, std::string& out) const = 0;
236
237
    /** Get the descriptor string form with the xpub at the last hardened derivation,
238
     *  and always use h for hardened derivation.
239
     */
240
    virtual bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache = nullptr) const = 0;
241
242
    /** Derive a private key, if private data is available in arg and put it into out. */
243
    virtual void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const = 0;
244
245
    /** Whether private data for this provider is available in arg. */
246
    virtual bool HavePrivateKeys(const SigningProvider& arg) const
247
1.64k
    {
248
1.64k
        FlatSigningProvider tmp_provider;
249
1.64k
        GetPrivKey(/*pos=*/0, arg, tmp_provider);
250
1.64k
        return !tmp_provider.keys.empty();
251
1.64k
    }
252
253
    /** Return the non-extended public key for this PubkeyProvider, if it has one. */
254
    virtual std::optional<CPubKey> GetRootPubKey() const = 0;
255
    /** Return the extended public key for this PubkeyProvider, if it has one. */
256
    virtual std::optional<CExtPubKey> GetRootExtPubKey() const = 0;
257
258
    /** Make a deep copy of this PubkeyProvider */
259
    virtual std::unique_ptr<PubkeyProvider> Clone() const = 0;
260
261
    /** Whether this PubkeyProvider is a BIP 32 extended key that can be derived from */
262
    virtual bool IsBIP32() const = 0;
263
264
    /** Get the count of keys known by this PubkeyProvider. Usually one, but may be more for key aggregation schemes */
265
480
    virtual size_t GetKeyCount() const { return 1; }
266
267
    /** Whether this PubkeyProvider can always provide a public key without cache or private key arguments */
268
    virtual bool CanSelfExpand() const = 0;
269
270
protected:
271
    static bool DetermineApostropheUse(StringType type, bool normalized, bool public_apostrophe)
272
205k
    {
273
205k
        bool use_apostrophe{false};
274
205k
        switch (type) {
275
5.91k
        case StringType::COMPAT:
276
            // COMPAT always uses apostrophe to stay compatible with previous versions
277
5.91k
            use_apostrophe = true;
278
5.91k
            break;
279
4.74k
        case StringType::CANONICAL:
280
            // CANONICAL always uses h
281
4.74k
            use_apostrophe = false;
282
4.74k
            break;
283
195k
        case StringType::PUBLIC:
284
195k
            use_apostrophe = !normalized && public_apostrophe;
285
195k
            break;
286
205k
        } // no default case, so the compiler can warn about missing cases
287
205k
        return use_apostrophe;
288
205k
    }
289
};
290
291
class OriginPubkeyProvider final : public PubkeyProvider
292
{
293
    KeyOriginInfo m_origin;
294
    std::unique_ptr<PubkeyProvider> m_provider;
295
    bool m_apostrophe;
296
297
    std::string OriginString(StringType type, bool normalized=false) const
298
92.0k
    {
299
92.0k
        bool use_apostrophe{DetermineApostropheUse(type, normalized, m_apostrophe)};
300
92.0k
        return HexStr(m_origin.fingerprint) + FormatHDKeypath(m_origin.path, use_apostrophe);
301
92.0k
    }
302
303
public:
304
394k
    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) {}
305
    std::optional<CPubKey> GetPubKey(int pos, const SigningProvider& arg, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
306
64.6k
    {
307
        // Derive into a temporary provider. Another key expression may have already put this
308
        // key into out with its origin prefixed, and prefixing that entry would double it up.
309
64.6k
        FlatSigningProvider subprovider;
310
64.6k
        std::optional<CPubKey> pub = m_provider->GetPubKey(pos, arg, subprovider, read_cache, write_cache);
311
64.6k
        if (!pub) return std::nullopt;
312
64.4k
        const CKeyID keyid{pub->GetID()};
313
64.4k
        Assert(subprovider.pubkeys.contains(keyid));
314
64.4k
        auto& [pubkey, suborigin] = subprovider.origins[keyid];
315
64.4k
        Assert(pubkey == *pub); // m_provider must have a valid origin by this point.
316
64.4k
        suborigin.fingerprint = m_origin.fingerprint;
317
64.4k
        suborigin.path.insert(suborigin.path.begin(), m_origin.path.begin(), m_origin.path.end());
318
64.4k
        auto origin{subprovider.origins.extract(keyid)};
319
64.4k
        out.Merge(std::move(subprovider));
320
        // An explicit origin takes precedence over an implicit one for the same key.
321
64.4k
        out.origins.insert_or_assign(keyid, std::move(origin.mapped()));
322
64.4k
        return pub;
323
64.6k
    }
324
30.7k
    bool IsRange() const override { return m_provider->IsRange(); }
325
55.5k
    size_t GetSize() const override { return m_provider->GetSize(); }
326
190
    bool IsBIP32() const override { return m_provider->IsBIP32(); }
327
91.0k
    std::string ToString(StringType type) const override { return "[" + OriginString(type) + "]" + m_provider->ToString(type); }
328
    bool ToPrivateString(const SigningProvider& arg, std::string& ret) const override
329
105
    {
330
105
        std::string sub;
331
105
        bool has_priv_key{m_provider->ToPrivateString(arg, sub)};
332
105
        ret = "[" + OriginString(StringType::PUBLIC) + "]" + std::move(sub);
333
105
        return has_priv_key;
334
105
    }
335
    bool ToNormalizedString(const SigningProvider& arg, std::string& ret, const DescriptorCache* cache) const override
336
818
    {
337
818
        std::string sub;
338
818
        if (!m_provider->ToNormalizedString(arg, sub, cache)) return false;
339
        // If m_provider is a BIP32PubkeyProvider, we may get a string formatted like a OriginPubkeyProvider
340
        // In that case, we need to strip out the leading square bracket and fingerprint from the substring,
341
        // and append that to our own origin string.
342
818
        if (sub[0] == '[') {
343
24
            sub = sub.substr(9);
344
24
            ret = "[" + OriginString(StringType::PUBLIC, /*normalized=*/true) + std::move(sub);
345
794
        } else {
346
794
            ret = "[" + OriginString(StringType::PUBLIC, /*normalized=*/true) + "]" + std::move(sub);
347
794
        }
348
818
        return true;
349
818
    }
350
    void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const override
351
3.49k
    {
352
3.49k
        m_provider->GetPrivKey(pos, arg, out);
353
3.49k
    }
354
    std::optional<CPubKey> GetRootPubKey() const override
355
0
    {
356
0
        return m_provider->GetRootPubKey();
357
0
    }
358
    std::optional<CExtPubKey> GetRootExtPubKey() const override
359
0
    {
360
0
        return m_provider->GetRootExtPubKey();
361
0
    }
362
    std::unique_ptr<PubkeyProvider> Clone() const override
363
122
    {
364
122
        return std::make_unique<OriginPubkeyProvider>(m_expr_index, m_origin, m_provider->Clone(), m_apostrophe);
365
122
    }
366
443
    bool CanSelfExpand() const override { return m_provider->CanSelfExpand(); }
367
};
368
369
/** An object representing a parsed constant public key in a descriptor. */
370
class ConstPubkeyProvider final : public PubkeyProvider
371
{
372
    CPubKey m_pubkey;
373
    bool m_xonly;
374
375
    std::optional<CKey> GetPrivKey(const SigningProvider& arg) const
376
51.4k
    {
377
51.4k
        CKey key;
378
51.4k
        if (!(m_xonly ? arg.GetKeyByXOnly(XOnlyPubKey(m_pubkey), key) :
379
51.4k
                        arg.GetKey(m_pubkey.GetID(), key))) return std::nullopt;
380
7.62k
        return key;
381
51.4k
    }
382
383
public:
384
424k
    ConstPubkeyProvider(uint32_t exp_index, const CPubKey& pubkey, bool xonly) : PubkeyProvider(exp_index), m_pubkey(pubkey), m_xonly(xonly) {}
385
    std::optional<CPubKey> GetPubKey(int pos, const SigningProvider&, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
386
1.01M
    {
387
1.01M
        KeyOriginInfo info;
388
1.01M
        CKeyID keyid = m_pubkey.GetID();
389
1.01M
        info.fingerprint = keyid.fingerprint();
390
1.01M
        out.origins.emplace(keyid, std::make_pair(m_pubkey, info));
391
1.01M
        out.pubkeys.emplace(keyid, m_pubkey);
392
1.01M
        return m_pubkey;
393
1.01M
    }
394
41.9k
    bool IsRange() const override { return false; }
395
69.9k
    size_t GetSize() const override { return m_pubkey.size(); }
396
10
    bool IsBIP32() const override { return false; }
397
239k
    std::string ToString(StringType type) const override { return m_xonly ? HexStr(m_pubkey).substr(2) : HexStr(m_pubkey); }
398
    bool ToPrivateString(const SigningProvider& arg, std::string& ret) const override
399
417
    {
400
417
        std::optional<CKey> key = GetPrivKey(arg);
401
417
        if (!key) {
402
204
            ret = ToString(StringType::PUBLIC);
403
204
            return false;
404
204
        }
405
213
        ret = EncodeSecret(*key);
406
213
        return true;
407
417
    }
408
    bool ToNormalizedString(const SigningProvider& arg, std::string& ret, const DescriptorCache* cache) const override
409
10.6k
    {
410
10.6k
        ret = ToString(StringType::PUBLIC);
411
10.6k
        return true;
412
10.6k
    }
413
    void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const override
414
51.0k
    {
415
51.0k
        std::optional<CKey> key = GetPrivKey(arg);
416
51.0k
        if (!key) return;
417
7.40k
        out.keys.emplace(key->GetPubKey().GetID(), *key);
418
7.40k
    }
419
    std::optional<CPubKey> GetRootPubKey() const override
420
12
    {
421
12
        return m_pubkey;
422
12
    }
423
    std::optional<CExtPubKey> GetRootExtPubKey() const override
424
12
    {
425
12
        return std::nullopt;
426
12
    }
427
    std::unique_ptr<PubkeyProvider> Clone() const override
428
30
    {
429
30
        return std::make_unique<ConstPubkeyProvider>(m_expr_index, m_pubkey, m_xonly);
430
30
    }
431
813
    bool CanSelfExpand() const final { return true; }
432
};
433
434
enum class DeriveType {
435
    NON_RANGED,
436
    UNHARDENED_RANGED,
437
    HARDENED_RANGED,
438
};
439
440
/** An object representing a parsed extended public key in a descriptor. */
441
class BIP32PubkeyProvider final : public PubkeyProvider
442
{
443
    // Root xpub, path, and final derivation step type being used, if any
444
    CExtPubKey m_root_extkey;
445
    KeyPath m_path;
446
    DeriveType m_derive;
447
    // Whether ' or h is used in harded derivation
448
    bool m_apostrophe;
449
450
    bool GetExtKey(const SigningProvider& arg, CExtKey& ret) const
451
58.7k
    {
452
58.7k
        CKey key;
453
58.7k
        if (!arg.GetKey(m_root_extkey.pubkey.GetID(), key)) return false;
454
51.7k
        ret.nDepth = m_root_extkey.nDepth;
455
51.7k
        ret.fingerprint = m_root_extkey.fingerprint;
456
51.7k
        ret.nChild = m_root_extkey.nChild;
457
51.7k
        ret.chaincode = m_root_extkey.chaincode;
458
51.7k
        ret.key = key;
459
51.7k
        return true;
460
58.7k
    }
461
462
    // Derives the last xprv
463
    bool GetDerivedExtKey(const SigningProvider& arg, CExtKey& xprv, CExtKey& last_hardened) const
464
57.3k
    {
465
57.3k
        if (!GetExtKey(arg, xprv)) return false;
466
92.6k
        for (auto entry : m_path) {
467
92.6k
            if (!xprv.Derive(xprv, entry)) return false;
468
92.6k
            if (entry >> 31) {
469
75.5k
                last_hardened = xprv;
470
75.5k
            }
471
92.6k
        }
472
50.6k
        return true;
473
50.6k
    }
474
475
    bool IsHardened() const
476
59.1k
    {
477
59.1k
        if (m_derive == DeriveType::HARDENED_RANGED) return true;
478
28.9k
        return HasHardenedDerivation(m_path);
479
59.1k
    }
480
481
public:
482
9.84k
    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) {}
483
533k
    bool IsRange() const override { return m_derive != DeriveType::NON_RANGED; }
484
559
    size_t GetSize() const override { return 33; }
485
427
    bool IsBIP32() const override { return true; }
486
    std::optional<CPubKey> GetPubKey(int pos, const SigningProvider& arg, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
487
783k
    {
488
783k
        KeyOriginInfo info;
489
783k
        info.fingerprint = m_root_extkey.id_key_fingerprint();
490
783k
        info.path = m_path;
491
783k
        if (m_derive == DeriveType::UNHARDENED_RANGED) info.path.push_back((uint32_t)pos);
492
783k
        if (m_derive == DeriveType::HARDENED_RANGED) info.path.push_back(((uint32_t)pos) | BIP32_HARDENED_FLAG);
493
494
        // Derive keys or fetch them from cache
495
783k
        CExtPubKey final_extkey = m_root_extkey;
496
783k
        CExtPubKey parent_extkey = m_root_extkey;
497
783k
        CExtPubKey last_hardened_extkey;
498
783k
        bool der = true;
499
783k
        if (read_cache) {
500
725k
            if (!read_cache->GetCachedDerivedExtPubKey(m_expr_index, pos, final_extkey)) {
501
721k
                if (m_derive == DeriveType::HARDENED_RANGED) return std::nullopt;
502
                // Try to get the derivation parent
503
697k
                if (!read_cache->GetCachedParentExtPubKey(m_expr_index, parent_extkey)) return std::nullopt;
504
692k
                final_extkey = parent_extkey;
505
692k
                if (m_derive == DeriveType::UNHARDENED_RANGED) der = parent_extkey.Derive(final_extkey, pos);
506
692k
            }
507
725k
        } else if (IsHardened()) {
508
39.7k
            CExtKey xprv;
509
39.7k
            CExtKey lh_xprv;
510
39.7k
            if (!GetDerivedExtKey(arg, xprv, lh_xprv)) return std::nullopt;
511
39.5k
            parent_extkey = xprv.Neuter();
512
39.5k
            if (m_derive == DeriveType::UNHARDENED_RANGED) der = xprv.Derive(xprv, pos);
513
39.5k
            if (m_derive == DeriveType::HARDENED_RANGED) der = xprv.Derive(xprv, pos | BIP32_HARDENED_FLAG);
514
39.5k
            final_extkey = xprv.Neuter();
515
39.5k
            if (lh_xprv.key.IsValid()) {
516
36.5k
                last_hardened_extkey = lh_xprv.Neuter();
517
36.5k
            }
518
39.5k
        } else {
519
18.1k
            for (auto entry : m_path) {
520
18.0k
                if (!parent_extkey.Derive(parent_extkey, entry)) return std::nullopt;
521
18.0k
            }
522
18.1k
            final_extkey = parent_extkey;
523
18.1k
            if (m_derive == DeriveType::UNHARDENED_RANGED) der = parent_extkey.Derive(final_extkey, pos);
524
18.1k
            assert(m_derive != DeriveType::HARDENED_RANGED);
525
18.1k
        }
526
754k
        if (!der) return std::nullopt;
527
528
754k
        out.origins.emplace(final_extkey.pubkey.GetID(), std::make_pair(final_extkey.pubkey, info));
529
754k
        out.pubkeys.emplace(final_extkey.pubkey.GetID(), final_extkey.pubkey);
530
531
754k
        if (write_cache) {
532
            // Only cache parent if there is any unhardened derivation
533
30.8k
            if (m_derive != DeriveType::HARDENED_RANGED) {
534
6.76k
                write_cache->CacheParentExtPubKey(m_expr_index, parent_extkey);
535
                // Cache last hardened xpub if we have it
536
6.76k
                if (last_hardened_extkey.pubkey.IsValid()) {
537
4.36k
                    write_cache->CacheLastHardenedExtPubKey(m_expr_index, last_hardened_extkey);
538
4.36k
                }
539
24.1k
            } else if (info.path.size() > 0) {
540
24.1k
                write_cache->CacheDerivedExtPubKey(m_expr_index, pos, final_extkey);
541
24.1k
            }
542
30.8k
        }
543
544
754k
        return final_extkey.pubkey;
545
754k
    }
546
    std::string ToString(StringType type, bool normalized) const
547
113k
    {
548
113k
        bool use_apostrophe{DetermineApostropheUse(type, normalized, m_apostrophe)};
549
113k
        std::string ret = EncodeExtPubKey(m_root_extkey) + FormatHDKeypath(m_path, /*apostrophe=*/use_apostrophe);
550
113k
        if (IsRange()) {
551
107k
            ret += "/*";
552
107k
            if (m_derive == DeriveType::HARDENED_RANGED) ret += use_apostrophe ? '\'' : 'h';
553
107k
        }
554
113k
        return ret;
555
113k
    }
556
    std::string ToString(StringType type) const override
557
113k
    {
558
113k
        return ToString(type, /*normalized=*/false);
559
113k
    }
560
    bool ToPrivateString(const SigningProvider& arg, std::string& out) const override
561
1.41k
    {
562
1.41k
        CExtKey key;
563
1.41k
        if (!GetExtKey(arg, key)) {
564
368
            out = ToString(StringType::PUBLIC);
565
368
            return false;
566
368
        }
567
1.04k
        out = EncodeExtKey(key) + FormatHDKeypath(m_path, /*apostrophe=*/m_apostrophe);
568
1.04k
        if (IsRange()) {
569
827
            out += "/*";
570
827
            if (m_derive == DeriveType::HARDENED_RANGED) out += m_apostrophe ? '\'' : 'h';
571
827
        }
572
1.04k
        return true;
573
1.41k
    }
574
    bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache) const override
575
7.03k
    {
576
7.03k
        if (m_derive == DeriveType::HARDENED_RANGED) {
577
283
            out = ToString(StringType::PUBLIC, /*normalized=*/true);
578
579
283
            return true;
580
283
        }
581
        // Step backwards to find the last hardened step in the path
582
6.75k
        int i = (int)m_path.size() - 1;
583
12.7k
        for (; i >= 0; --i) {
584
11.6k
            if (m_path.at(i) >> 31) {
585
5.57k
                break;
586
5.57k
            }
587
11.6k
        }
588
        // Either no derivation or all unhardened derivation
589
6.75k
        if (i == -1) {
590
1.17k
            out = ToString(StringType::PUBLIC);
591
1.17k
            return true;
592
1.17k
        }
593
        // Get the path to the last hardened stup
594
5.57k
        KeyOriginInfo origin;
595
5.57k
        int k = 0;
596
22.1k
        for (; k <= i; ++k) {
597
            // Add to the path
598
16.5k
            origin.path.push_back(m_path.at(k));
599
16.5k
        }
600
        // Build the remaining path
601
5.57k
        KeyPath end_path;
602
11.0k
        for (; k < (int)m_path.size(); ++k) {
603
5.46k
            end_path.push_back(m_path.at(k));
604
5.46k
        }
605
5.57k
        origin.fingerprint = m_root_extkey.id_key_fingerprint();
606
607
5.57k
        CExtPubKey xpub;
608
5.57k
        CExtKey lh_xprv;
609
        // If we have the cache, just get the parent xpub
610
5.57k
        if (cache != nullptr) {
611
5.52k
            cache->GetCachedLastHardenedExtPubKey(m_expr_index, xpub);
612
5.52k
        }
613
5.57k
        if (!xpub.pubkey.IsValid()) {
614
            // Cache miss, or nor cache, or need privkey
615
54
            CExtKey xprv;
616
54
            if (!GetDerivedExtKey(arg, xprv, lh_xprv)) return false;
617
54
            xpub = lh_xprv.Neuter();
618
54
        }
619
5.57k
        assert(xpub.pubkey.IsValid());
620
621
        // Build the string
622
5.57k
        std::string origin_str = HexStr(origin.fingerprint) + FormatHDKeypath(origin.path);
623
5.57k
        out = "[" + origin_str + "]" + EncodeExtPubKey(xpub) + FormatHDKeypath(end_path);
624
5.57k
        if (IsRange()) {
625
5.45k
            out += "/*";
626
5.45k
            assert(m_derive == DeriveType::UNHARDENED_RANGED);
627
5.45k
        }
628
5.57k
        return true;
629
5.57k
    }
630
    void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const override
631
17.5k
    {
632
17.5k
        CExtKey extkey;
633
17.5k
        CExtKey dummy;
634
17.5k
        if (!GetDerivedExtKey(arg, extkey, dummy)) return;
635
11.0k
        if (m_derive == DeriveType::UNHARDENED_RANGED && !extkey.Derive(extkey, pos)) return;
636
11.0k
        if (m_derive == DeriveType::HARDENED_RANGED && !extkey.Derive(extkey, pos | BIP32_HARDENED_FLAG)) return;
637
11.0k
        out.keys.emplace(extkey.key.GetPubKey().GetID(), extkey.key);
638
11.0k
    }
639
    std::optional<CPubKey> GetRootPubKey() const override
640
384
    {
641
384
        return std::nullopt;
642
384
    }
643
    std::optional<CExtPubKey> GetRootExtPubKey() const override
644
384
    {
645
384
        return m_root_extkey;
646
384
    }
647
    std::unique_ptr<PubkeyProvider> Clone() const override
648
314
    {
649
314
        return std::make_unique<BIP32PubkeyProvider>(m_expr_index, m_root_extkey, m_path, m_derive, m_apostrophe);
650
314
    }
651
1.32k
    bool CanSelfExpand() const override { return !IsHardened(); }
652
};
653
654
/** PubkeyProvider for a musig() expression */
655
class MuSigPubkeyProvider final : public PubkeyProvider
656
{
657
private:
658
    //! PubkeyProvider for the participants
659
    const std::vector<std::unique_ptr<PubkeyProvider>> m_participants;
660
    //! Derivation path
661
    const KeyPath m_path;
662
    //! PubkeyProvider for the aggregate pubkey if it can be cached (i.e. participants are not ranged)
663
    mutable std::unique_ptr<PubkeyProvider> m_aggregate_provider;
664
    mutable std::optional<CPubKey> m_aggregate_pubkey;
665
    const DeriveType m_derive;
666
    const bool m_ranged_participants;
667
668
5.37k
    bool IsRangedDerivation() const { return m_derive != DeriveType::NON_RANGED; }
669
670
public:
671
    MuSigPubkeyProvider(
672
        uint32_t exp_index,
673
        std::vector<std::unique_ptr<PubkeyProvider>> providers,
674
        KeyPath path,
675
        DeriveType derive
676
    )
677
289
        : PubkeyProvider(exp_index),
678
289
        m_participants(std::move(providers)),
679
289
        m_path(std::move(path)),
680
289
        m_derive(derive),
681
641
        m_ranged_participants(std::any_of(m_participants.begin(), m_participants.end(), [](const auto& pubkey) { return pubkey->IsRange(); }))
682
289
    {
683
289
        if (!Assume(!(m_ranged_participants && IsRangedDerivation()))) {
684
0
            throw std::runtime_error("musig(): Cannot have both ranged participants and ranged derivation");
685
0
        }
686
289
        if (!Assume(m_derive != DeriveType::HARDENED_RANGED)) {
687
0
            throw std::runtime_error("musig(): Cannot have hardened derivation");
688
0
        }
689
289
    }
690
691
    std::optional<CPubKey> GetPubKey(int pos, const SigningProvider& arg, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
692
1.67k
    {
693
1.67k
        FlatSigningProvider dummy;
694
        // If the participants are not ranged, we can compute and cache the aggregate pubkey by creating a PubkeyProvider for it
695
1.67k
        if (!m_aggregate_provider && !m_ranged_participants) {
696
            // Retrieve the pubkeys from the providers
697
188
            std::vector<CPubKey> pubkeys;
698
484
            for (const auto& prov : m_participants) {
699
484
                std::optional<CPubKey> pubkey = prov->GetPubKey(0, arg, dummy, read_cache, write_cache);
700
484
                if (!pubkey.has_value()) {
701
6
                    return std::nullopt;
702
6
                }
703
478
                pubkeys.push_back(pubkey.value());
704
478
            }
705
182
            std::sort(pubkeys.begin(), pubkeys.end());
706
707
            // Aggregate the pubkey
708
182
            m_aggregate_pubkey = MuSig2AggregatePubkeys(pubkeys);
709
182
            if (!Assume(m_aggregate_pubkey.has_value())) return std::nullopt;
710
711
            // Make our pubkey provider
712
182
            if (IsRangedDerivation() || !m_path.empty()) {
713
                // Make the synthetic xpub and construct the BIP32PubkeyProvider
714
176
                CExtPubKey extpub = CreateMuSig2SyntheticXpub(m_aggregate_pubkey.value());
715
176
                m_aggregate_provider = std::make_unique<BIP32PubkeyProvider>(m_expr_index, extpub, m_path, m_derive, /*apostrophe=*/false);
716
176
            } else {
717
6
                m_aggregate_provider = std::make_unique<ConstPubkeyProvider>(m_expr_index, m_aggregate_pubkey.value(), /*xonly=*/false);
718
6
            }
719
182
        }
720
721
        // Retrieve all participant pubkeys
722
1.66k
        std::vector<CPubKey> pubkeys;
723
4.19k
        for (const auto& prov : m_participants) {
724
4.19k
            std::optional<CPubKey> pub = prov->GetPubKey(pos, arg, out, read_cache, write_cache);
725
4.19k
            if (!pub) return std::nullopt;
726
4.05k
            pubkeys.emplace_back(*pub);
727
4.05k
        }
728
1.52k
        std::sort(pubkeys.begin(), pubkeys.end());
729
730
1.52k
        CPubKey pubout;
731
1.52k
        if (m_aggregate_provider) {
732
            // When we have a cached aggregate key, we are either returning it or deriving from it
733
            // Either way, we can passthrough to its GetPubKey
734
            // Use a dummy signing provider as private keys do not exist for the aggregate pubkey
735
1.18k
            std::optional<CPubKey> pub = m_aggregate_provider->GetPubKey(pos, dummy, out, read_cache, write_cache);
736
1.18k
            if (!pub) return std::nullopt;
737
1.18k
            pubout = *pub;
738
1.18k
            out.aggregate_pubkeys.emplace(m_aggregate_pubkey.value(), pubkeys);
739
1.18k
        } else {
740
343
            if (!Assume(m_ranged_participants) || !Assume(m_path.empty())) return std::nullopt;
741
            // Compute aggregate key from derived participants
742
343
            std::optional<CPubKey> aggregate_pubkey = MuSig2AggregatePubkeys(pubkeys);
743
343
            if (!aggregate_pubkey) return std::nullopt;
744
343
            pubout = *aggregate_pubkey;
745
746
343
            std::unique_ptr<ConstPubkeyProvider> this_agg_provider = std::make_unique<ConstPubkeyProvider>(m_expr_index, aggregate_pubkey.value(), /*xonly=*/false);
747
343
            this_agg_provider->GetPubKey(0, dummy, out, read_cache, write_cache);
748
343
            out.aggregate_pubkeys.emplace(pubout, pubkeys);
749
343
        }
750
751
1.52k
        if (!Assume(pubout.IsValid())) return std::nullopt;
752
1.52k
        return pubout;
753
1.52k
    }
754
3.00k
    bool IsRange() const override { return IsRangedDerivation() || m_ranged_participants; }
755
    // musig() expressions can only be used in tr() contexts which have 32 byte xonly pubkeys
756
0
    size_t GetSize() const override { return 32; }
757
758
    std::string ToString(StringType type) const override
759
1.87k
    {
760
1.87k
        std::string out = "musig(";
761
7.03k
        for (size_t i = 0; i < m_participants.size(); ++i) {
762
5.16k
            const auto& pubkey = m_participants.at(i);
763
5.16k
            if (i) out += ",";
764
5.16k
            out += pubkey->ToString(type);
765
5.16k
        }
766
1.87k
        out += ")";
767
1.87k
        out += FormatHDKeypath(m_path);
768
1.87k
        if (IsRangedDerivation()) {
769
1.42k
            out += "/*";
770
1.42k
        }
771
1.87k
        return out;
772
1.87k
    }
773
    bool ToPrivateString(const SigningProvider& arg, std::string& out) const override
774
67
    {
775
67
        bool any_privkeys = false;
776
67
        out = "musig(";
777
239
        for (size_t i = 0; i < m_participants.size(); ++i) {
778
172
            const auto& pubkey = m_participants.at(i);
779
172
            if (i) out += ",";
780
172
            std::string tmp;
781
172
            if (pubkey->ToPrivateString(arg, tmp)) {
782
84
                any_privkeys = true;
783
84
            }
784
172
            out += tmp;
785
172
        }
786
67
        out += ")";
787
67
        out += FormatHDKeypath(m_path);
788
67
        if (IsRangedDerivation()) {
789
37
            out += "/*";
790
37
        }
791
67
        return any_privkeys;
792
67
    }
793
    bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache = nullptr) const override
794
166
    {
795
166
        out = "musig(";
796
608
        for (size_t i = 0; i < m_participants.size(); ++i) {
797
442
            const auto& pubkey = m_participants.at(i);
798
442
            if (i) out += ",";
799
442
            std::string tmp;
800
442
            if (!pubkey->ToNormalizedString(arg, tmp, cache)) {
801
0
                return false;
802
0
            }
803
442
            out += tmp;
804
442
        }
805
166
        out += ")";
806
166
        out += FormatHDKeypath(m_path);
807
166
        if (IsRangedDerivation()) {
808
119
            out += "/*";
809
119
        }
810
166
        return true;
811
166
    }
812
813
    void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const override
814
1.60k
    {
815
        // Get the private keys for any participants that we have
816
        // If there is participant derivation, it will be done.
817
        // If there is not, then the participant privkeys will be included directly
818
4.48k
        for (const auto& prov : m_participants) {
819
4.48k
            prov->GetPrivKey(pos, arg, out);
820
4.48k
        }
821
1.60k
    }
822
823
    bool HavePrivateKeys(const SigningProvider& arg) const override
824
229
    {
825
346
        return std::ranges::all_of(m_participants, [&](const auto& prov) { return prov->HavePrivateKeys(arg); });
826
229
    }
827
828
    // Get RootPubKey and GetRootExtPubKey are used to return the single pubkey underlying the pubkey provider
829
    // to be presented to the user in gethdkeys. As this is a multisig construction, there is no single underlying
830
    // pubkey hence nothing should be returned.
831
    // While the aggregate pubkey could be returned as the root (ext)pubkey, it is not a pubkey that anyone should
832
    // be using by itself in a descriptor as it is unspendable without knowing its participants.
833
    std::optional<CPubKey> GetRootPubKey() const override
834
0
    {
835
0
        return std::nullopt;
836
0
    }
837
    std::optional<CExtPubKey> GetRootExtPubKey() const override
838
0
    {
839
0
        return std::nullopt;
840
0
    }
841
842
    std::unique_ptr<PubkeyProvider> Clone() const override
843
29
    {
844
29
        std::vector<std::unique_ptr<PubkeyProvider>> providers;
845
29
        providers.reserve(m_participants.size());
846
78
        for (const std::unique_ptr<PubkeyProvider>& p : m_participants) {
847
78
            providers.emplace_back(p->Clone());
848
78
        }
849
29
        return std::make_unique<MuSigPubkeyProvider>(m_expr_index, std::move(providers), m_path, m_derive);
850
29
    }
851
    bool IsBIP32() const override
852
0
    {
853
        // musig() can only be a BIP 32 key if all participants are bip32 too
854
0
        return std::all_of(m_participants.begin(), m_participants.end(), [](const auto& pubkey) { return pubkey->IsBIP32(); });
855
0
    }
856
    size_t GetKeyCount() const override
857
46
    {
858
46
        return 1 + m_participants.size();
859
46
    }
860
    bool CanSelfExpand() const override
861
138
    {
862
        // Participants must be self expandable for all MuSig expressions to be self expandable; the aggregate pubkey cannot be stored
863
        // in the descriptor cache, so even aggregate-then-derive still requires the self expansion of participants prior to aggregation.
864
318
        for (const auto& key : m_participants) {
865
318
            if (!key->CanSelfExpand()) return false;
866
318
        }
867
114
        return true;
868
138
    }
869
};
870
871
/** Base class for all Descriptor implementations. */
872
class DescriptorImpl : public Descriptor
873
{
874
protected:
875
    //! Public key arguments for this descriptor (size 1 for PK, PKH, WPKH; any size for WSH and Multisig).
876
    const std::vector<std::unique_ptr<PubkeyProvider>> m_pubkey_args;
877
    //! The string name of the descriptor function.
878
    const std::string m_name;
879
    //! Warnings (not including subdescriptors).
880
    std::vector<std::string> m_warnings;
881
882
    //! The sub-descriptor arguments (empty for everything but SH and WSH).
883
    //! In doc/descriptors.md this is referred to as SCRIPT expressions sh(SCRIPT)
884
    //! and wsh(SCRIPT), and distinct from KEY expressions and ADDR expressions.
885
    //! Subdescriptors can only ever generate a single script.
886
    const std::vector<std::unique_ptr<DescriptorImpl>> m_subdescriptor_args;
887
888
    //! Return a serialization of anything except pubkey and script arguments, to be prepended to those.
889
255k
    virtual std::string ToStringExtra() const { return ""; }
890
891
    /** A helper function to construct the scripts for this descriptor.
892
     *
893
     *  This function is invoked once by ExpandHelper.
894
     *
895
     *  @param pubkeys The evaluations of the m_pubkey_args field.
896
     *  @param scripts The evaluations of m_subdescriptor_args (one for each m_subdescriptor_args element).
897
     *  @param out A FlatSigningProvider to put scripts or public keys in that are necessary to the solver.
898
     *             The origin info of the provided pubkeys is automatically added.
899
     *  @return A vector with scriptPubKeys for this descriptor.
900
     */
901
    virtual std::vector<CScript> MakeScripts(const std::vector<CPubKey>& pubkeys, std::span<const CScript> scripts, FlatSigningProvider& out) const = 0;
902
903
public:
904
305k
    DescriptorImpl(std::vector<std::unique_ptr<PubkeyProvider>> pubkeys, const std::string& name) : m_pubkey_args(std::move(pubkeys)), m_name(name), m_subdescriptor_args() {}
905
23.5k
    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))) {}
906
7.24k
    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)) {}
907
908
    enum class StringType
909
    {
910
        PUBLIC,
911
        PRIVATE,
912
        NORMALIZED,
913
        CANONICAL,
914
        COMPAT, // string calculation that mustn't change over time to stay compatible with previous software versions
915
    };
916
917
    // NOLINTNEXTLINE(misc-no-recursion)
918
    bool IsSolvable() const override
919
3.96k
    {
920
3.96k
        for (const auto& arg : m_subdescriptor_args) {
921
1.73k
            if (!arg->IsSolvable()) return false;
922
1.73k
        }
923
3.96k
        return true;
924
3.96k
    }
925
926
    // NOLINTNEXTLINE(misc-no-recursion)
927
    bool HavePrivateKeys(const SigningProvider& arg) const override
928
1.77k
    {
929
1.77k
        if (m_pubkey_args.empty() && m_subdescriptor_args.empty()) return false;
930
931
1.75k
        for (const auto& sub: m_subdescriptor_args) {
932
599
            if (!sub->HavePrivateKeys(arg)) return false;
933
599
        }
934
935
1.53k
        for (const auto& pubkey : m_pubkey_args) {
936
1.53k
            if (!pubkey->HavePrivateKeys(arg)) return false;
937
1.53k
        }
938
939
852
        return true;
940
1.40k
    }
941
942
    // NOLINTNEXTLINE(misc-no-recursion)
943
    bool IsRange() const final
944
489k
    {
945
489k
        for (const auto& pubkey : m_pubkey_args) {
946
456k
            if (pubkey->IsRange()) return true;
947
456k
        }
948
75.4k
        for (const auto& arg : m_subdescriptor_args) {
949
44.1k
            if (arg->IsRange()) return true;
950
44.1k
        }
951
34.0k
        return false;
952
75.4k
    }
953
954
    // NOLINTNEXTLINE(misc-no-recursion)
955
    virtual bool ToStringSubScriptHelper(const SigningProvider* arg, std::string& ret, const StringType type, const DescriptorCache* cache = nullptr) const
956
252k
    {
957
252k
        size_t pos = 0;
958
252k
        bool is_private{type == StringType::PRIVATE};
959
        // For private string output, track if at least one key has a private key available.
960
        // Initialize to true for non-private types.
961
252k
        bool any_success{!is_private};
962
252k
        for (const auto& scriptarg : m_subdescriptor_args) {
963
29.1k
            if (pos++) ret += ",";
964
29.1k
            std::string tmp;
965
29.1k
            bool subscript_res{scriptarg->ToStringHelper(arg, tmp, type, cache)};
966
29.1k
            if (!is_private && !subscript_res) return false;
967
29.1k
            any_success = any_success || subscript_res;
968
29.1k
            ret += tmp;
969
29.1k
        }
970
252k
        return any_success;
971
252k
    }
972
973
    // NOLINTNEXTLINE(misc-no-recursion)
974
    virtual bool ToStringHelper(const SigningProvider* arg, std::string& out, const StringType type, const DescriptorCache* cache = nullptr) const
975
262k
    {
976
262k
        std::string extra = ToStringExtra();
977
262k
        size_t pos = extra.size() > 0 ? 1 : 0;
978
262k
        std::string ret = m_name + "(" + extra;
979
262k
        bool is_private{type == StringType::PRIVATE};
980
        // For private string output, track if at least one key has a private key available.
981
        // Initialize to true for non-private types.
982
262k
        bool any_success{!is_private};
983
984
349k
        for (const auto& pubkey : m_pubkey_args) {
985
349k
            if (pos++) ret += ",";
986
349k
            std::string tmp;
987
349k
            switch (type) {
988
16.7k
                case StringType::NORMALIZED:
989
16.7k
                    if (!pubkey->ToNormalizedString(*arg, tmp, cache)) return false;
990
16.7k
                    break;
991
16.7k
                case StringType::PRIVATE:
992
1.46k
                    any_success = pubkey->ToPrivateString(*arg, tmp) || any_success;
993
1.46k
                    break;
994
306k
                case StringType::PUBLIC:
995
306k
                    tmp = pubkey->ToString(PubkeyProvider::StringType::PUBLIC);
996
306k
                    break;
997
14.8k
                case StringType::COMPAT:
998
14.8k
                    tmp = pubkey->ToString(PubkeyProvider::StringType::COMPAT);
999
14.8k
                    break;
1000
9.83k
                case StringType::CANONICAL:
1001
9.83k
                    tmp = pubkey->ToString(PubkeyProvider::StringType::CANONICAL);
1002
9.83k
                    break;
1003
349k
            }
1004
349k
            ret += tmp;
1005
349k
        }
1006
262k
        std::string subscript;
1007
262k
        bool subscript_res{ToStringSubScriptHelper(arg, subscript, type, cache)};
1008
262k
        if (!is_private && !subscript_res) return false;
1009
262k
        any_success = any_success || subscript_res;
1010
262k
        if (pos && subscript.size()) ret += ',';
1011
262k
        out = std::move(ret) + std::move(subscript) + ")";
1012
262k
        return any_success;
1013
262k
    }
1014
1015
    std::string ToString(bool compat_format) const final
1016
212k
    {
1017
212k
        std::string ret;
1018
212k
        ToStringHelper(nullptr, ret, compat_format ? StringType::COMPAT : StringType::PUBLIC);
1019
212k
        return AddChecksum(ret);
1020
212k
    }
1021
1022
    std::string ToCanonicalString() const final
1023
3.22k
    {
1024
3.22k
        std::string ret;
1025
3.22k
        ToStringHelper(nullptr, ret, StringType::CANONICAL);
1026
3.22k
        return AddChecksum(ret);
1027
3.22k
    }
1028
1029
    bool ToPrivateString(const SigningProvider& arg, std::string& out) const override
1030
1.13k
    {
1031
1.13k
        bool has_priv_key{ToStringHelper(&arg, out, StringType::PRIVATE)};
1032
1.13k
        out = AddChecksum(out);
1033
1.13k
        return has_priv_key;
1034
1.13k
    }
1035
1036
    bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache) const override final
1037
12.4k
    {
1038
12.4k
        bool ret = ToStringHelper(&arg, out, StringType::NORMALIZED, cache);
1039
12.4k
        out = AddChecksum(out);
1040
12.4k
        return ret;
1041
12.4k
    }
1042
1043
    // NOLINTNEXTLINE(misc-no-recursion)
1044
    bool ExpandHelper(int pos, const SigningProvider& arg, const DescriptorCache* read_cache, std::vector<CScript>& output_scripts, FlatSigningProvider& out, DescriptorCache* write_cache) const
1045
847k
    {
1046
847k
        FlatSigningProvider subprovider;
1047
847k
        std::vector<CPubKey> pubkeys;
1048
847k
        pubkeys.reserve(m_pubkey_args.size());
1049
1050
        // Construct temporary data in `pubkeys`, `subscripts`, and `subprovider` to avoid producing output in case of failure.
1051
1.78M
        for (const auto& p : m_pubkey_args) {
1052
1.78M
            std::optional<CPubKey> pubkey = p->GetPubKey(pos, arg, subprovider, read_cache, write_cache);
1053
1.78M
            if (!pubkey) return false;
1054
1.75M
            pubkeys.push_back(pubkey.value());
1055
1.75M
        }
1056
818k
        std::vector<CScript> subscripts;
1057
818k
        for (const auto& subarg : m_subdescriptor_args) {
1058
183k
            std::vector<CScript> outscripts;
1059
183k
            if (!subarg->ExpandHelper(pos, arg, read_cache, outscripts, subprovider, write_cache)) return false;
1060
183k
            assert(outscripts.size() == 1);
1061
181k
            subscripts.emplace_back(std::move(outscripts[0]));
1062
181k
        }
1063
817k
        out.Merge(std::move(subprovider));
1064
1065
817k
        output_scripts = MakeScripts(pubkeys, std::span{subscripts}, out);
1066
817k
        return true;
1067
818k
    }
1068
1069
    bool Expand(int pos, const SigningProvider& provider, std::vector<CScript>& output_scripts, FlatSigningProvider& out, DescriptorCache* write_cache = nullptr) const final
1070
54.8k
    {
1071
54.8k
        return ExpandHelper(pos, provider, nullptr, output_scripts, out, write_cache);
1072
54.8k
    }
1073
1074
    bool ExpandFromCache(int pos, const DescriptorCache& read_cache, std::vector<CScript>& output_scripts, FlatSigningProvider& out) const final
1075
609k
    {
1076
609k
        return ExpandHelper(pos, DUMMY_SIGNING_PROVIDER, &read_cache, output_scripts, out, nullptr);
1077
609k
    }
1078
1079
    // NOLINTNEXTLINE(misc-no-recursion)
1080
    void ExpandPrivate(int pos, const SigningProvider& provider, FlatSigningProvider& out) const final
1081
22.0k
    {
1082
64.0k
        for (const auto& p : m_pubkey_args) {
1083
64.0k
            p->GetPrivKey(pos, provider, out);
1084
64.0k
        }
1085
22.0k
        for (const auto& arg : m_subdescriptor_args) {
1086
5.55k
            arg->ExpandPrivate(pos, provider, out);
1087
5.55k
        }
1088
22.0k
    }
1089
1090
413
    std::optional<OutputType> GetOutputType() const override { return std::nullopt; }
1091
1092
0
    std::optional<int64_t> ScriptSize() const override { return {}; }
1093
1094
    /** A helper for MaxSatisfactionWeight.
1095
     *
1096
     * @param use_max_sig Whether to assume ECDSA signatures will have a high-r.
1097
     * @return The maximum size of the satisfaction in raw bytes (with no witness meaning).
1098
     */
1099
0
    virtual std::optional<int64_t> MaxSatSize(bool use_max_sig) const { return {}; }
1100
1101
18
    std::optional<int64_t> MaxSatisfactionWeight(bool) const override { return {}; }
1102
1103
4
    std::optional<int64_t> MaxSatisfactionElems() const override { return {}; }
1104
1105
    // NOLINTNEXTLINE(misc-no-recursion)
1106
    void GetPubKeys(std::set<CPubKey>& pubkeys, std::set<CExtPubKey>& ext_pubs) const override
1107
476
    {
1108
476
        for (const auto& p : m_pubkey_args) {
1109
396
            std::optional<CPubKey> pub = p->GetRootPubKey();
1110
396
            if (pub) pubkeys.insert(*pub);
1111
396
            std::optional<CExtPubKey> ext_pub = p->GetRootExtPubKey();
1112
396
            if (ext_pub) ext_pubs.insert(*ext_pub);
1113
396
        }
1114
476
        for (const auto& arg : m_subdescriptor_args) {
1115
83
            arg->GetPubKeys(pubkeys, ext_pubs);
1116
83
        }
1117
476
    }
1118
1119
    virtual std::unique_ptr<DescriptorImpl> Clone() const = 0;
1120
1121
1.21k
    bool HasScripts() const override { return true; }
1122
1123
    // NOLINTNEXTLINE(misc-no-recursion)
1124
1.39k
    std::vector<std::string> Warnings() const override {
1125
1.39k
        std::vector<std::string> all = m_warnings;
1126
1.39k
        for (const auto& sub : m_subdescriptor_args) {
1127
584
            auto sub_w = sub->Warnings();
1128
584
            all.insert(all.end(), sub_w.begin(), sub_w.end());
1129
584
        }
1130
1.39k
        return all;
1131
1.39k
    }
1132
1133
    uint32_t GetMaxKeyExpr() const final
1134
250
    {
1135
250
        uint32_t max_key_expr{0};
1136
250
        std::vector<const DescriptorImpl*> todo = {this};
1137
684
        while (!todo.empty()) {
1138
434
            const DescriptorImpl* desc = todo.back();
1139
434
            todo.pop_back();
1140
526
            for (const auto& p : desc->m_pubkey_args) {
1141
526
                max_key_expr = std::max(max_key_expr, p->m_expr_index);
1142
526
            }
1143
434
            for (const auto& s : desc->m_subdescriptor_args) {
1144
184
                todo.push_back(s.get());
1145
184
            }
1146
434
        }
1147
250
        return max_key_expr;
1148
250
    }
1149
1150
    size_t GetKeyCount() const final
1151
250
    {
1152
250
        size_t count{0};
1153
250
        std::vector<const DescriptorImpl*> todo = {this};
1154
684
        while (!todo.empty()) {
1155
434
            const DescriptorImpl* desc = todo.back();
1156
434
            todo.pop_back();
1157
526
            for (const auto& p : desc->m_pubkey_args) {
1158
526
                count += p->GetKeyCount();
1159
526
            }
1160
434
            for (const auto& s : desc->m_subdescriptor_args) {
1161
184
                todo.push_back(s.get());
1162
184
            }
1163
434
        }
1164
250
        return count;
1165
250
    }
1166
1167
    // NOLINTNEXTLINE(misc-no-recursion)
1168
    bool CanSelfExpand() const override
1169
1.71k
    {
1170
1.95k
        for (const auto& key : m_pubkey_args) {
1171
1.95k
            if (!key->CanSelfExpand()) return false;
1172
1.95k
        }
1173
1.60k
        for (const auto& sub : m_subdescriptor_args) {
1174
633
            if (!sub->CanSelfExpand()) return false;
1175
633
        }
1176
1.53k
        return true;
1177
1.60k
    }
1178
};
1179
1180
/** A parsed addr(A) descriptor. */
1181
class AddressDescriptor final : public DescriptorImpl
1182
{
1183
    const CTxDestination m_destination;
1184
protected:
1185
3.19k
    std::string ToStringExtra() const override { return EncodeDestination(m_destination); }
1186
130
    std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, std::span<const CScript>, FlatSigningProvider&) const override { return Vector(GetScriptForDestination(m_destination)); }
1187
public:
1188
3.20k
    AddressDescriptor(CTxDestination destination) : DescriptorImpl({}, "addr"), m_destination(std::move(destination)) {}
1189
14
    bool IsSolvable() const final { return false; }
1190
1191
    std::optional<OutputType> GetOutputType() const override
1192
33
    {
1193
33
        return OutputTypeFromDestination(m_destination);
1194
33
    }
1195
78
    bool IsSingleType() const final { return true; }
1196
0
    bool ToPrivateString(const SigningProvider& arg, std::string& out) const final { return false; }
1197
1198
0
    std::optional<int64_t> ScriptSize() const override { return GetScriptForDestination(m_destination).size(); }
1199
    std::unique_ptr<DescriptorImpl> Clone() const override
1200
0
    {
1201
0
        return std::make_unique<AddressDescriptor>(m_destination);
1202
0
    }
1203
};
1204
1205
/** A parsed raw(H) descriptor. */
1206
class RawDescriptor final : public DescriptorImpl
1207
{
1208
    const CScript m_script;
1209
protected:
1210
2.26k
    std::string ToStringExtra() const override { return HexStr(m_script); }
1211
2.33k
    std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, std::span<const CScript>, FlatSigningProvider&) const override { return Vector(m_script); }
1212
public:
1213
4.46k
    RawDescriptor(CScript script) : DescriptorImpl({}, "raw"), m_script(std::move(script)) {}
1214
0
    bool IsSolvable() const final { return false; }
1215
1216
    std::optional<OutputType> GetOutputType() const override
1217
5
    {
1218
5
        CTxDestination dest;
1219
5
        ExtractDestination(m_script, dest);
1220
5
        return OutputTypeFromDestination(dest);
1221
5
    }
1222
190
    bool IsSingleType() const final { return true; }
1223
0
    bool ToPrivateString(const SigningProvider& arg, std::string& out) const final { return false; }
1224
1225
0
    std::optional<int64_t> ScriptSize() const override { return m_script.size(); }
1226
1227
    std::unique_ptr<DescriptorImpl> Clone() const override
1228
0
    {
1229
0
        return std::make_unique<RawDescriptor>(m_script);
1230
0
    }
1231
};
1232
1233
/** A parsed pk(P) descriptor. */
1234
class PKDescriptor final : public DescriptorImpl
1235
{
1236
private:
1237
    const bool m_xonly;
1238
protected:
1239
    std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override
1240
30.0k
    {
1241
30.0k
        if (m_xonly) {
1242
29.7k
            CScript script = CScript() << ToByteVector(XOnlyPubKey(keys[0])) << OP_CHECKSIG;
1243
29.7k
            return Vector(std::move(script));
1244
29.7k
        } else {
1245
310
            return Vector(GetScriptForRawPubKey(keys[0]));
1246
310
        }
1247
30.0k
    }
1248
public:
1249
22.7k
    PKDescriptor(std::unique_ptr<PubkeyProvider> prov, bool xonly = false) : DescriptorImpl(Vector(std::move(prov)), "pk"), m_xonly(xonly) {}
1250
28
    bool IsSingleType() const final { return true; }
1251
1252
11
    std::optional<int64_t> ScriptSize() const override {
1253
11
        return 1 + (m_xonly ? 32 : m_pubkey_args[0]->GetSize()) + 1;
1254
11
    }
1255
1256
64
    std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
1257
64
        const auto ecdsa_sig_size = use_max_sig ? 72 : 71;
1258
64
        return 1 + (m_xonly ? 65 : ecdsa_sig_size);
1259
64
    }
1260
1261
58
    std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
1262
58
        return *MaxSatSize(use_max_sig) * WITNESS_SCALE_FACTOR;
1263
58
    }
1264
1265
56
    std::optional<int64_t> MaxSatisfactionElems() const override { return 1; }
1266
1267
    std::unique_ptr<DescriptorImpl> Clone() const override
1268
15
    {
1269
15
        return std::make_unique<PKDescriptor>(m_pubkey_args.at(0)->Clone(), m_xonly);
1270
15
    }
1271
};
1272
1273
/** A parsed pkh(P) descriptor. */
1274
class PKHDescriptor final : public DescriptorImpl
1275
{
1276
protected:
1277
    std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override
1278
157k
    {
1279
157k
        CKeyID id = keys[0].GetID();
1280
157k
        return Vector(GetScriptForDestination(PKHash(id)));
1281
157k
    }
1282
public:
1283
88.4k
    PKHDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "pkh") {}
1284
72.6k
    std::optional<OutputType> GetOutputType() const override { return OutputType::LEGACY; }
1285
68.8k
    bool IsSingleType() const final { return true; }
1286
1287
74
    std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 1 + 20 + 1 + 1; }
1288
1289
50.8k
    std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
1290
50.8k
        const auto sig_size = use_max_sig ? 72 : 71;
1291
50.8k
        return 1 + sig_size + 1 + m_pubkey_args[0]->GetSize();
1292
50.8k
    }
1293
1294
50.7k
    std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
1295
50.7k
        return *MaxSatSize(use_max_sig) * WITNESS_SCALE_FACTOR;
1296
50.7k
    }
1297
1298
50.8k
    std::optional<int64_t> MaxSatisfactionElems() const override { return 2; }
1299
1300
    std::unique_ptr<DescriptorImpl> Clone() const override
1301
0
    {
1302
0
        return std::make_unique<PKHDescriptor>(m_pubkey_args.at(0)->Clone());
1303
0
    }
1304
};
1305
1306
/** A parsed wpkh(P) descriptor. */
1307
class WPKHDescriptor final : public DescriptorImpl
1308
{
1309
protected:
1310
    std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override
1311
294k
    {
1312
294k
        CKeyID id = keys[0].GetID();
1313
294k
        return Vector(GetScriptForDestination(WitnessV0KeyHash(id)));
1314
294k
    }
1315
public:
1316
167k
    WPKHDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "wpkh") {}
1317
150k
    std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32; }
1318
160k
    bool IsSingleType() const final { return true; }
1319
1320
1.65k
    std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 20; }
1321
1322
123k
    std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
1323
123k
        const auto sig_size = use_max_sig ? 72 : 71;
1324
123k
        return (1 + sig_size + 1 + 33);
1325
123k
    }
1326
1327
122k
    std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
1328
122k
        return MaxSatSize(use_max_sig);
1329
122k
    }
1330
1331
123k
    std::optional<int64_t> MaxSatisfactionElems() const override { return 2; }
1332
1333
    std::unique_ptr<DescriptorImpl> Clone() const override
1334
0
    {
1335
0
        return std::make_unique<WPKHDescriptor>(m_pubkey_args.at(0)->Clone());
1336
0
    }
1337
};
1338
1339
/** A parsed combo(P) descriptor. */
1340
class ComboDescriptor final : public DescriptorImpl
1341
{
1342
protected:
1343
    std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider& out) const override
1344
19.5k
    {
1345
19.5k
        std::vector<CScript> ret;
1346
19.5k
        CKeyID id = keys[0].GetID();
1347
19.5k
        ret.emplace_back(GetScriptForRawPubKey(keys[0])); // P2PK
1348
19.5k
        ret.emplace_back(GetScriptForDestination(PKHash(id))); // P2PKH
1349
19.5k
        if (keys[0].IsCompressed()) {
1350
19.4k
            CScript p2wpkh = GetScriptForDestination(WitnessV0KeyHash(id));
1351
19.4k
            out.scripts.emplace(CScriptID(p2wpkh), p2wpkh);
1352
19.4k
            ret.emplace_back(p2wpkh);
1353
19.4k
            ret.emplace_back(GetScriptForDestination(ScriptHash(p2wpkh))); // P2SH-P2WPKH
1354
19.4k
        }
1355
19.5k
        return ret;
1356
19.5k
    }
1357
public:
1358
681
    ComboDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "combo") {}
1359
23.7k
    bool IsSingleType() const final { return false; }
1360
    std::unique_ptr<DescriptorImpl> Clone() const override
1361
0
    {
1362
0
        return std::make_unique<ComboDescriptor>(m_pubkey_args.at(0)->Clone());
1363
0
    }
1364
};
1365
1366
/** A parsed multi(...) or sortedmulti(...) descriptor */
1367
class MultisigDescriptor final : public DescriptorImpl
1368
{
1369
    const int m_threshold;
1370
    const bool m_sorted;
1371
protected:
1372
1.18k
    std::string ToStringExtra() const override { return strprintf("%i", m_threshold); }
1373
18.6k
    std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override {
1374
18.6k
        if (m_sorted) {
1375
2.83k
            std::vector<CPubKey> sorted_keys(keys);
1376
2.83k
            std::sort(sorted_keys.begin(), sorted_keys.end());
1377
2.83k
            return Vector(GetScriptForMultisig(m_threshold, sorted_keys));
1378
2.83k
        }
1379
15.8k
        return Vector(GetScriptForMultisig(m_threshold, keys));
1380
18.6k
    }
1381
public:
1382
902
    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) {}
1383
12
    bool IsSingleType() const final { return true; }
1384
1385
241
    std::optional<int64_t> ScriptSize() const override {
1386
241
        const auto n_keys = m_pubkey_args.size();
1387
746
        auto op = [](int64_t acc, const std::unique_ptr<PubkeyProvider>& pk) { return acc + 1 + pk->GetSize();};
1388
241
        const auto pubkeys_size{std::accumulate(m_pubkey_args.begin(), m_pubkey_args.end(), int64_t{0}, op)};
1389
241
        return 1 + BuildScript(n_keys).size() + BuildScript(m_threshold).size() + pubkeys_size;
1390
241
    }
1391
1392
249
    std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
1393
249
        const auto sig_size = use_max_sig ? 72 : 71;
1394
249
        return (1 + (1 + sig_size) * m_threshold);
1395
249
    }
1396
1397
16
    std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
1398
16
        return *MaxSatSize(use_max_sig) * WITNESS_SCALE_FACTOR;
1399
16
    }
1400
1401
226
    std::optional<int64_t> MaxSatisfactionElems() const override { return 1 + m_threshold; }
1402
1403
    std::unique_ptr<DescriptorImpl> Clone() const override
1404
0
    {
1405
0
        std::vector<std::unique_ptr<PubkeyProvider>> providers;
1406
0
        providers.reserve(m_pubkey_args.size());
1407
0
        std::transform(m_pubkey_args.begin(), m_pubkey_args.end(), std::back_inserter(providers), [](const std::unique_ptr<PubkeyProvider>& p) { return p->Clone(); });
1408
0
        return std::make_unique<MultisigDescriptor>(m_threshold, std::move(providers), m_sorted);
1409
0
    }
1410
};
1411
1412
/** A parsed (sorted)multi_a(...) descriptor. Always uses x-only pubkeys. */
1413
class MultiADescriptor final : public DescriptorImpl
1414
{
1415
    const int m_threshold;
1416
    const bool m_sorted;
1417
protected:
1418
850
    std::string ToStringExtra() const override { return strprintf("%i", m_threshold); }
1419
6.95k
    std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override {
1420
6.95k
        CScript ret;
1421
6.95k
        std::vector<XOnlyPubKey> xkeys;
1422
6.95k
        xkeys.reserve(keys.size());
1423
992k
        for (const auto& key : keys) xkeys.emplace_back(key);
1424
6.95k
        if (m_sorted) std::sort(xkeys.begin(), xkeys.end());
1425
6.95k
        ret << ToByteVector(xkeys[0]) << OP_CHECKSIG;
1426
992k
        for (size_t i = 1; i < keys.size(); ++i) {
1427
985k
            ret << ToByteVector(xkeys[i]) << OP_CHECKSIGADD;
1428
985k
        }
1429
6.95k
        ret << m_threshold << OP_NUMEQUAL;
1430
6.95k
        return Vector(std::move(ret));
1431
6.95k
    }
1432
public:
1433
920
    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) {}
1434
0
    bool IsSingleType() const final { return true; }
1435
1436
0
    std::optional<int64_t> ScriptSize() const override {
1437
0
        const auto n_keys = m_pubkey_args.size();
1438
0
        return (1 + 32 + 1) * n_keys + BuildScript(m_threshold).size() + 1;
1439
0
    }
1440
1441
0
    std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
1442
0
        return (1 + 65) * m_threshold + (m_pubkey_args.size() - m_threshold);
1443
0
    }
1444
1445
0
    std::optional<int64_t> MaxSatisfactionElems() const override { return m_pubkey_args.size(); }
1446
1447
    std::unique_ptr<DescriptorImpl> Clone() const override
1448
0
    {
1449
0
        std::vector<std::unique_ptr<PubkeyProvider>> providers;
1450
0
        providers.reserve(m_pubkey_args.size());
1451
0
        for (const auto& arg : m_pubkey_args) {
1452
0
            providers.push_back(arg->Clone());
1453
0
        }
1454
0
        return std::make_unique<MultiADescriptor>(m_threshold, std::move(providers), m_sorted);
1455
0
    }
1456
};
1457
1458
/** A parsed sh(...) descriptor. */
1459
class SHDescriptor final : public DescriptorImpl
1460
{
1461
protected:
1462
    std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, std::span<const CScript> scripts, FlatSigningProvider& out) const override
1463
126k
    {
1464
126k
        auto ret = Vector(GetScriptForDestination(ScriptHash(scripts[0])));
1465
126k
        if (ret.size()) out.scripts.emplace(CScriptID(scripts[0]), scripts[0]);
1466
126k
        return ret;
1467
126k
    }
1468
1469
7.96k
    bool IsSegwit() const { return m_subdescriptor_args[0]->GetOutputType() == OutputType::BECH32; }
1470
1471
public:
1472
22.3k
    SHDescriptor(std::unique_ptr<DescriptorImpl> desc) : DescriptorImpl({}, std::move(desc), "sh") {}
1473
1474
    std::optional<OutputType> GetOutputType() const override
1475
6.18k
    {
1476
6.18k
        assert(m_subdescriptor_args.size() == 1);
1477
6.18k
        if (IsSegwit()) return OutputType::P2SH_SEGWIT;
1478
122
        return OutputType::LEGACY;
1479
6.18k
    }
1480
22.5k
    bool IsSingleType() const final { return true; }
1481
1482
24
    std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 20 + 1; }
1483
1484
1.77k
    std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
1485
1.77k
        if (const auto sat_size = m_subdescriptor_args[0]->MaxSatSize(use_max_sig)) {
1486
1.77k
            if (const auto subscript_size = m_subdescriptor_args[0]->ScriptSize()) {
1487
                // The subscript is never witness data.
1488
1.77k
                const auto subscript_weight = (1 + *subscript_size) * WITNESS_SCALE_FACTOR;
1489
                // The weight depends on whether the inner descriptor is satisfied using the witness stack.
1490
1.77k
                if (IsSegwit()) return subscript_weight + *sat_size;
1491
58
                return subscript_weight + *sat_size * WITNESS_SCALE_FACTOR;
1492
1.77k
            }
1493
1.77k
        }
1494
0
        return {};
1495
1.77k
    }
1496
1497
1.75k
    std::optional<int64_t> MaxSatisfactionElems() const override {
1498
1.75k
        if (const auto sub_elems = m_subdescriptor_args[0]->MaxSatisfactionElems()) return 1 + *sub_elems;
1499
0
        return {};
1500
1.75k
    }
1501
1502
    std::unique_ptr<DescriptorImpl> Clone() const override
1503
0
    {
1504
0
        return std::make_unique<SHDescriptor>(m_subdescriptor_args.at(0)->Clone());
1505
0
    }
1506
};
1507
1508
/** A parsed wsh(...) descriptor. */
1509
class WSHDescriptor final : public DescriptorImpl
1510
{
1511
protected:
1512
    std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, std::span<const CScript> scripts, FlatSigningProvider& out) const override
1513
17.2k
    {
1514
17.2k
        auto ret = Vector(GetScriptForDestination(WitnessV0ScriptHash(scripts[0])));
1515
17.2k
        if (ret.size()) out.scripts.emplace(CScriptID(scripts[0]), scripts[0]);
1516
17.2k
        return ret;
1517
17.2k
    }
1518
public:
1519
1.15k
    WSHDescriptor(std::unique_ptr<DescriptorImpl> desc) : DescriptorImpl({}, std::move(desc), "wsh") {}
1520
930
    std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32; }
1521
1.91k
    bool IsSingleType() const final { return true; }
1522
1523
88
    std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
1524
1525
419
    std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
1526
419
        if (const auto sat_size = m_subdescriptor_args[0]->MaxSatSize(use_max_sig)) {
1527
419
            if (const auto subscript_size = m_subdescriptor_args[0]->ScriptSize()) {
1528
419
                return GetSizeOfCompactSize(*subscript_size) + *subscript_size + *sat_size;
1529
419
            }
1530
419
        }
1531
0
        return {};
1532
419
    }
1533
1534
351
    std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
1535
351
        return MaxSatSize(use_max_sig);
1536
351
    }
1537
1538
391
    std::optional<int64_t> MaxSatisfactionElems() const override {
1539
391
        if (const auto sub_elems = m_subdescriptor_args[0]->MaxSatisfactionElems()) return 1 + *sub_elems;
1540
0
        return {};
1541
391
    }
1542
1543
    std::unique_ptr<DescriptorImpl> Clone() const override
1544
0
    {
1545
0
        return std::make_unique<WSHDescriptor>(m_subdescriptor_args.at(0)->Clone());
1546
0
    }
1547
};
1548
1549
/** A parsed tr(...) descriptor. */
1550
class TRDescriptor final : public DescriptorImpl
1551
{
1552
    std::vector<int> m_depths;
1553
protected:
1554
    std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript> scripts, FlatSigningProvider& out) const override
1555
140k
    {
1556
140k
        TaprootBuilder builder;
1557
140k
        assert(m_depths.size() == scripts.size());
1558
177k
        for (size_t pos = 0; pos < m_depths.size(); ++pos) {
1559
37.4k
            builder.Add(m_depths[pos], scripts[pos], TAPROOT_LEAF_TAPSCRIPT);
1560
37.4k
        }
1561
140k
        if (!builder.IsComplete()) return {};
1562
140k
        assert(keys.size() == 1);
1563
140k
        XOnlyPubKey xpk(keys[0]);
1564
140k
        if (!xpk.IsFullyValid()) return {};
1565
140k
        builder.Finalize(xpk);
1566
140k
        WitnessV1Taproot output = builder.GetOutput();
1567
140k
        out.tr_trees[output] = builder;
1568
140k
        return Vector(GetScriptForDestination(output));
1569
140k
    }
1570
    bool ToStringSubScriptHelper(const SigningProvider* arg, std::string& ret, const StringType type, const DescriptorCache* cache = nullptr) const override
1571
10.3k
    {
1572
10.3k
        if (m_depths.empty()) {
1573
            // If there are no sub-descriptors and a PRIVATE string
1574
            // is requested, return `false` to indicate that the presence
1575
            // of a private key depends solely on the internal key (which is checked
1576
            // in the caller), not on any sub-descriptor. This ensures correct behavior for
1577
            // descriptors like tr(internal_key) when checking for private keys.
1578
7.73k
            return type != StringType::PRIVATE;
1579
7.73k
        }
1580
2.66k
        std::vector<bool> path;
1581
2.66k
        bool is_private{type == StringType::PRIVATE};
1582
        // For private string output, track if at least one key has a private key available.
1583
        // Initialize to true for non-private types.
1584
2.66k
        bool any_success{!is_private};
1585
1586
8.35k
        for (size_t pos = 0; pos < m_depths.size(); ++pos) {
1587
5.69k
            if (pos) ret += ',';
1588
11.3k
            while ((int)path.size() <= m_depths[pos]) {
1589
5.69k
                if (path.size()) ret += '{';
1590
5.69k
                path.push_back(false);
1591
5.69k
            }
1592
5.69k
            std::string tmp;
1593
5.69k
            bool subscript_res{m_subdescriptor_args[pos]->ToStringHelper(arg, tmp, type, cache)};
1594
5.69k
            if (!is_private && !subscript_res) return false;
1595
5.69k
            any_success = any_success || subscript_res;
1596
5.69k
            ret += tmp;
1597
8.73k
            while (!path.empty() && path.back()) {
1598
3.03k
                if (path.size() > 1) ret += '}';
1599
3.03k
                path.pop_back();
1600
3.03k
            }
1601
5.69k
            if (!path.empty()) path.back() = true;
1602
5.69k
        }
1603
2.66k
        return any_success;
1604
2.66k
    }
1605
public:
1606
    TRDescriptor(std::unique_ptr<PubkeyProvider> internal_key, std::vector<std::unique_ptr<DescriptorImpl>> descs, std::vector<int> depths) :
1607
7.24k
        DescriptorImpl(Vector(std::move(internal_key)), std::move(descs), "tr"), m_depths(std::move(depths))
1608
7.24k
    {
1609
7.24k
        assert(m_subdescriptor_args.size() == m_depths.size());
1610
7.24k
    }
1611
9.33k
    std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32M; }
1612
23.5k
    bool IsSingleType() const final { return true; }
1613
1614
32
    std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
1615
1616
4.04k
    std::optional<int64_t> MaxSatisfactionWeight(bool) const override {
1617
        // FIXME: We assume keypath spend, which can lead to very large underestimations.
1618
4.04k
        return 1 + 65;
1619
4.04k
    }
1620
1621
4.01k
    std::optional<int64_t> MaxSatisfactionElems() const override {
1622
        // FIXME: See above, we assume keypath spend.
1623
4.01k
        return 1;
1624
4.01k
    }
1625
1626
    std::unique_ptr<DescriptorImpl> Clone() const override
1627
0
    {
1628
0
        std::vector<std::unique_ptr<DescriptorImpl>> subdescs;
1629
0
        subdescs.reserve(m_subdescriptor_args.size());
1630
0
        std::transform(m_subdescriptor_args.begin(), m_subdescriptor_args.end(), std::back_inserter(subdescs), [](const std::unique_ptr<DescriptorImpl>& d) { return d->Clone(); });
1631
0
        return std::make_unique<TRDescriptor>(m_pubkey_args.at(0)->Clone(), std::move(subdescs), m_depths);
1632
0
    }
1633
};
1634
1635
/* We instantiate Miniscript here with a simple integer as key type.
1636
 * The value of these key integers are an index in the
1637
 * DescriptorImpl::m_pubkey_args vector.
1638
 */
1639
1640
/**
1641
 * The context for converting a Miniscript descriptor into a Script.
1642
 */
1643
class ScriptMaker {
1644
    //! Keys contained in the Miniscript (the evaluation of DescriptorImpl::m_pubkey_args).
1645
    const std::vector<CPubKey>& m_keys;
1646
    //! The script context we're operating within (Tapscript or P2WSH).
1647
    const miniscript::MiniscriptContext m_script_ctx;
1648
1649
    //! Get the ripemd160(sha256()) hash of this key.
1650
    //! Any key that is valid in a descriptor serializes as 32 bytes within a Tapscript context. So we
1651
    //! must not hash the sign-bit byte in this case.
1652
512
    uint160 GetHash160(uint32_t key) const {
1653
512
        if (miniscript::IsTapscript(m_script_ctx)) {
1654
241
            return Hash160(XOnlyPubKey{m_keys[key]});
1655
241
        }
1656
271
        return m_keys[key].GetID();
1657
512
    }
1658
1659
public:
1660
1.69k
    ScriptMaker(const std::vector<CPubKey>& keys LIFETIMEBOUND, const miniscript::MiniscriptContext script_ctx) : m_keys(keys), m_script_ctx{script_ctx} {}
1661
1662
3.19k
    std::vector<unsigned char> ToPKBytes(uint32_t key) const {
1663
        // In Tapscript keys always serialize as x-only, whether an x-only key was used in the descriptor or not.
1664
3.19k
        if (!miniscript::IsTapscript(m_script_ctx)) {
1665
2.09k
            return {m_keys[key].begin(), m_keys[key].end()};
1666
2.09k
        }
1667
1.09k
        const XOnlyPubKey xonly_pubkey{m_keys[key]};
1668
1.09k
        return {xonly_pubkey.begin(), xonly_pubkey.end()};
1669
3.19k
    }
1670
1671
512
    std::vector<unsigned char> ToPKHBytes(uint32_t key) const {
1672
512
        auto id = GetHash160(key);
1673
512
        return {id.begin(), id.end()};
1674
512
    }
1675
};
1676
1677
/**
1678
 * The context for converting a Miniscript descriptor to its textual form.
1679
 */
1680
class StringMaker {
1681
    //! To convert private keys for private descriptors.
1682
    const SigningProvider* m_arg;
1683
    //! Keys contained in the Miniscript (a reference to DescriptorImpl::m_pubkey_args).
1684
    const std::vector<std::unique_ptr<PubkeyProvider>>& m_pubkeys;
1685
    //! StringType to serialize keys
1686
    const DescriptorImpl::StringType m_type;
1687
    const DescriptorCache* m_cache;
1688
1689
public:
1690
    StringMaker(const SigningProvider* arg LIFETIMEBOUND,
1691
                const std::vector<std::unique_ptr<PubkeyProvider>>& pubkeys LIFETIMEBOUND,
1692
                DescriptorImpl::StringType type,
1693
                const DescriptorCache* cache LIFETIMEBOUND)
1694
1.34k
        : m_arg(arg), m_pubkeys(pubkeys), m_type(type), m_cache(cache) {}
1695
1696
    std::optional<std::string> ToString(uint32_t key, bool& has_priv_key) const
1697
6.08k
    {
1698
6.08k
        std::string ret;
1699
6.08k
        has_priv_key = false;
1700
6.08k
        switch (m_type) {
1701
4.27k
        case DescriptorImpl::StringType::PUBLIC:
1702
4.27k
            ret = m_pubkeys[key]->ToString(PubkeyProvider::StringType::PUBLIC);
1703
4.27k
            break;
1704
258
        case DescriptorImpl::StringType::PRIVATE:
1705
258
            has_priv_key = m_pubkeys[key]->ToPrivateString(*m_arg, ret);
1706
258
            break;
1707
602
        case DescriptorImpl::StringType::NORMALIZED:
1708
602
            if (!m_pubkeys[key]->ToNormalizedString(*m_arg, ret, m_cache)) return {};
1709
602
            break;
1710
602
        case DescriptorImpl::StringType::COMPAT:
1711
            // For backwards compatibility, we do not pass StringType::COMPAT.
1712
            // Prior to 31.0, COMPAT was not provided, so PUBLIC was in use. From this string,
1713
            // DescriptorSPKM IDs were computed from this string, so the incorrect behavior
1714
            // must be preserved for wallets with Miniscript descriptors to be loaded
1715
414
            ret = m_pubkeys[key]->ToString(PubkeyProvider::StringType::PUBLIC);
1716
414
            break;
1717
536
        case DescriptorImpl::StringType::CANONICAL:
1718
536
            ret = m_pubkeys[key]->ToString(PubkeyProvider::StringType::CANONICAL);
1719
536
            break;
1720
6.08k
        }
1721
6.08k
        return ret;
1722
6.08k
    }
1723
};
1724
1725
class MiniscriptDescriptor final : public DescriptorImpl
1726
{
1727
private:
1728
    miniscript::Node<uint32_t> m_node;
1729
1730
protected:
1731
    std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript> scripts,
1732
                                     FlatSigningProvider& provider) const override
1733
1.69k
    {
1734
1.69k
        const auto script_ctx{m_node.GetMsCtx()};
1735
3.70k
        for (const auto& key : keys) {
1736
3.70k
            if (miniscript::IsTapscript(script_ctx)) {
1737
1.34k
                provider.pubkeys.emplace(Hash160(XOnlyPubKey{key}), key);
1738
2.36k
            } else {
1739
2.36k
                provider.pubkeys.emplace(key.GetID(), key);
1740
2.36k
            }
1741
3.70k
        }
1742
1.69k
        return Vector(m_node.ToScript(ScriptMaker(keys, script_ctx)));
1743
1.69k
    }
1744
1745
public:
1746
    MiniscriptDescriptor(std::vector<std::unique_ptr<PubkeyProvider>> providers, miniscript::Node<uint32_t>&& node)
1747
911
        : DescriptorImpl(std::move(providers), "?"), m_node(std::move(node))
1748
911
    {
1749
        // Traverse miniscript tree for unsafe use of older()
1750
996k
        miniscript::ForEachNode(m_node, [&](const miniscript::Node<uint32_t>& node) {
1751
996k
            if (node.Fragment() == miniscript::Fragment::OLDER) {
1752
267
                const uint32_t raw = node.K();
1753
267
                const uint32_t value_part = raw & ~CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG;
1754
267
                if (value_part > CTxIn::SEQUENCE_LOCKTIME_MASK) {
1755
4
                    const bool is_time_based = (raw & CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) != 0;
1756
4
                    if (is_time_based) {
1757
2
                        m_warnings.push_back(strprintf("time-based relative locktime: older(%u) > (65535 * 512) seconds is unsafe", raw));
1758
2
                    } else {
1759
2
                        m_warnings.push_back(strprintf("height-based relative locktime: older(%u) > 65535 blocks is unsafe", raw));
1760
2
                    }
1761
4
                }
1762
267
            }
1763
996k
        });
1764
911
    }
1765
1766
    bool ToStringHelper(const SigningProvider* arg, std::string& out, const StringType type,
1767
                        const DescriptorCache* cache = nullptr) const override
1768
1.34k
    {
1769
1.34k
        bool has_priv_key{false};
1770
1.34k
        auto res = m_node.ToString(StringMaker(arg, m_pubkey_args, type, cache), has_priv_key);
1771
1.34k
        if (res) out = *res;
1772
1.34k
        if (type == StringType::PRIVATE) {
1773
99
            Assume(res.has_value());
1774
99
            return has_priv_key;
1775
1.25k
        } else {
1776
1.25k
            return res.has_value();
1777
1.25k
        }
1778
1.34k
    }
1779
1780
403
    bool IsSolvable() const override { return true; }
1781
0
    bool IsSingleType() const final { return true; }
1782
1783
176
    std::optional<int64_t> ScriptSize() const override { return m_node.ScriptSize(); }
1784
1785
    std::optional<int64_t> MaxSatSize(bool) const override
1786
176
    {
1787
        // For Miniscript we always assume high-R ECDSA signatures.
1788
176
        return m_node.GetWitnessSize();
1789
176
    }
1790
1791
    std::optional<int64_t> MaxSatisfactionElems() const override
1792
158
    {
1793
158
        return m_node.GetStackSize();
1794
158
    }
1795
1796
    std::unique_ptr<DescriptorImpl> Clone() const override
1797
5
    {
1798
5
        std::vector<std::unique_ptr<PubkeyProvider>> providers;
1799
5
        providers.reserve(m_pubkey_args.size());
1800
5
        for (const auto& arg : m_pubkey_args) {
1801
5
            providers.push_back(arg->Clone());
1802
5
        }
1803
5
        return std::make_unique<MiniscriptDescriptor>(std::move(providers), m_node.Clone());
1804
5
    }
1805
};
1806
1807
/** A parsed rawtr(...) descriptor. */
1808
class RawTRDescriptor final : public DescriptorImpl
1809
{
1810
protected:
1811
    std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript> scripts, FlatSigningProvider& out) const override
1812
1.60k
    {
1813
1.60k
        assert(keys.size() == 1);
1814
1.60k
        XOnlyPubKey xpk(keys[0]);
1815
1.60k
        if (!xpk.IsFullyValid()) return {};
1816
1.60k
        WitnessV1Taproot output{xpk};
1817
1.60k
        return Vector(GetScriptForDestination(output));
1818
1.60k
    }
1819
public:
1820
15.1k
    RawTRDescriptor(std::unique_ptr<PubkeyProvider> output_key) : DescriptorImpl(Vector(std::move(output_key)), "rawtr") {}
1821
367
    std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32M; }
1822
587
    bool IsSingleType() const final { return true; }
1823
1824
15
    std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
1825
1826
185
    std::optional<int64_t> MaxSatisfactionWeight(bool) const override {
1827
        // We can't know whether there is a script path, so assume key path spend.
1828
185
        return 1 + 65;
1829
185
    }
1830
1831
170
    std::optional<int64_t> MaxSatisfactionElems() const override {
1832
        // See above, we assume keypath spend.
1833
170
        return 1;
1834
170
    }
1835
1836
    std::unique_ptr<DescriptorImpl> Clone() const override
1837
0
    {
1838
0
        return std::make_unique<RawTRDescriptor>(m_pubkey_args.at(0)->Clone());
1839
0
    }
1840
};
1841
1842
/** A parsed unused(KEY) descriptor */
1843
class UnusedDescriptor final : public DescriptorImpl
1844
{
1845
protected:
1846
15
    std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript> scripts, FlatSigningProvider& out) const override { return {}; }
1847
public:
1848
21
    UnusedDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "unused") {}
1849
22
    bool IsSingleType() const final { return true; }
1850
30
    bool HasScripts() const override { return false; }
1851
1852
    std::unique_ptr<DescriptorImpl> Clone() const override
1853
0
    {
1854
0
        return std::make_unique<UnusedDescriptor>(m_pubkey_args.at(0)->Clone());
1855
0
    }
1856
};
1857
1858
1859
////////////////////////////////////////////////////////////////////////////
1860
// Parser                                                                 //
1861
////////////////////////////////////////////////////////////////////////////
1862
1863
enum class ParseScriptContext {
1864
    TOP,     //!< Top-level context (script goes directly in scriptPubKey)
1865
    P2SH,    //!< Inside sh() (script becomes P2SH redeemScript)
1866
    P2WPKH,  //!< Inside wpkh() (no script, pubkey only)
1867
    P2WSH,   //!< Inside wsh() (script becomes v0 witness script)
1868
    P2TR,    //!< Inside tr() (either internal key, or BIP342 script leaf)
1869
    MUSIG,   //!< Inside musig() (implies P2TR, cannot have nested musig())
1870
};
1871
1872
/**
1873
 * Parse a key path, being passed a split list of elements (the first element is ignored because it is always the key).
1874
 *
1875
 * @param[in] split BIP32 path string, using either ' or h for hardened derivation
1876
 * @param[out] out Vector of parsed key paths
1877
 * @param[out] apostrophe only updated if hardened derivation is found
1878
 * @param[out] error parsing error message
1879
 * @param[in] allow_multipath Allows the parsed path to use the multipath specifier
1880
 * @param[out] has_hardened Records whether the path contains any hardened derivation
1881
 * @returns false if parsing failed
1882
 **/
1883
[[nodiscard]] bool ParseKeyPath(const std::vector<std::span<const char>>& split, std::vector<KeyPath>& out, bool& apostrophe, std::string& error, bool allow_multipath, bool& has_hardened)
1884
14.3k
{
1885
31.8k
    auto parse_elem = [&](std::span<const char> elem) -> std::optional<uint32_t> {
1886
31.8k
        const auto parsed{ParseKeyPathElement(elem)};
1887
31.8k
        if (!parsed) {
1888
18
            error = parsed.error();
1889
18
            return std::nullopt;
1890
18
        }
1891
31.8k
        if (parsed->is_hardened) {
1892
23.0k
            has_hardened = true;
1893
23.0k
            apostrophe = elem.back() == '\'';
1894
23.0k
        }
1895
31.8k
        return parsed->ChildNumber();
1896
31.8k
    };
1897
1898
14.3k
    KeyPath path;
1899
14.3k
    struct MultipathSubstitutes {
1900
14.3k
        size_t placeholder_index;
1901
14.3k
        std::vector<uint32_t> values;
1902
14.3k
    };
1903
14.3k
    std::optional<MultipathSubstitutes> substitutes;
1904
14.3k
    has_hardened = false;
1905
1906
45.7k
    for (size_t i = 1; i < split.size(); ++i) {
1907
31.4k
        const std::span<const char>& elem = split[i];
1908
1909
        // Check if element contains multipath specifier
1910
31.4k
        if (!elem.empty() && elem.front() == '<' && elem.back() == '>') {
1911
336
            if (!allow_multipath) {
1912
2
                error = strprintf("Key path value '%s' specifies multipath in a section where multipath is not allowed", std::string(elem.begin(), elem.end()));
1913
2
                return false;
1914
2
            }
1915
334
            if (substitutes) {
1916
2
                error = "Multiple multipath key path specifiers found";
1917
2
                return false;
1918
2
            }
1919
1920
            // Parse each possible value
1921
332
            std::vector<std::span<const char>> nums = Split(std::span(elem.begin()+1, elem.end()-1), ";");
1922
332
            if (nums.size() < 2) {
1923
4
                error = "Multipath key path specifiers must have at least two items";
1924
4
                return false;
1925
4
            }
1926
1927
328
            substitutes.emplace();
1928
328
            std::unordered_set<uint32_t> seen_substitutes;
1929
773
            for (const auto& num : nums) {
1930
773
                const auto& op_num = parse_elem(num);
1931
773
                if (!op_num) return false;
1932
767
                auto [_, inserted] = seen_substitutes.insert(*op_num);
1933
767
                if (!inserted) {
1934
2
                    error = strprintf("Duplicated key path value %u in multipath specifier", *op_num);
1935
2
                    return false;
1936
2
                }
1937
765
                substitutes->values.emplace_back(*op_num);
1938
765
            }
1939
1940
320
            path.emplace_back(); // Placeholder for multipath segment
1941
320
            substitutes->placeholder_index = path.size() - 1;
1942
31.0k
        } else {
1943
31.0k
            const auto& op_num = parse_elem(elem);
1944
31.0k
            if (!op_num) return false;
1945
31.0k
            path.emplace_back(*op_num);
1946
31.0k
        }
1947
31.4k
    }
1948
1949
14.3k
    if (!substitutes) {
1950
14.0k
        out.emplace_back(std::move(path));
1951
14.0k
    } else {
1952
        // Replace the multipath placeholder with each value while generating paths
1953
753
        for (uint32_t substitute : substitutes->values) {
1954
753
            KeyPath branch_path = path;
1955
753
            branch_path[substitutes->placeholder_index] = substitute;
1956
753
            out.emplace_back(std::move(branch_path));
1957
753
        }
1958
318
    }
1959
14.3k
    return true;
1960
14.3k
}
1961
1962
[[nodiscard]] bool ParseKeyPath(const std::vector<std::span<const char>>& split, std::vector<KeyPath>& out, bool& apostrophe, std::string& error, bool allow_multipath)
1963
14.2k
{
1964
14.2k
    bool dummy;
1965
14.2k
    return ParseKeyPath(split, out, apostrophe, error, allow_multipath, /*has_hardened=*/dummy);
1966
14.2k
}
1967
1968
static DeriveType ParseDeriveType(std::vector<std::span<const char>>& split, bool& apostrophe)
1969
9.12k
{
1970
9.12k
    DeriveType type = DeriveType::NON_RANGED;
1971
9.12k
    if (std::ranges::equal(split.back(), std::span{"*"}.first(1))) {
1972
8.35k
        split.pop_back();
1973
8.35k
        type = DeriveType::UNHARDENED_RANGED;
1974
8.35k
    } else if (std::ranges::equal(split.back(), std::span{"*'"}.first(2)) || std::ranges::equal(split.back(), std::span{"*h"}.first(2))) {
1975
197
        apostrophe = std::ranges::equal(split.back(), std::span{"*'"}.first(2));
1976
197
        split.pop_back();
1977
197
        type = DeriveType::HARDENED_RANGED;
1978
197
    }
1979
9.12k
    return type;
1980
9.12k
}
1981
1982
/** Parse a public key that excludes origin information. */
1983
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)
1984
29.3k
{
1985
29.3k
    std::vector<std::unique_ptr<PubkeyProvider>> ret;
1986
29.3k
    bool permit_uncompressed = ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH;
1987
29.3k
    auto split = Split(sp, '/');
1988
29.3k
    std::string str(split[0].begin(), split[0].end());
1989
29.3k
    if (str.size() == 0) {
1990
4
        error = "No key provided";
1991
4
        return {};
1992
4
    }
1993
29.3k
    if (IsSpace(str.front()) || IsSpace(str.back())) {
1994
11
        error = strprintf("Key '%s' is invalid due to whitespace", str);
1995
11
        return {};
1996
11
    }
1997
29.3k
    if (split.size() == 1) {
1998
20.6k
        if (IsHex(str)) {
1999
19.8k
            std::vector<unsigned char> data = ParseHex(str);
2000
19.8k
            CPubKey pubkey(data);
2001
19.8k
            if (pubkey.IsValid() && !pubkey.IsValidNonHybrid()) {
2002
4
                error = "Hybrid public keys are not allowed";
2003
4
                return {};
2004
4
            }
2005
19.8k
            if (pubkey.IsFullyValid()) {
2006
1.22k
                if (permit_uncompressed || pubkey.IsCompressed()) {
2007
1.22k
                    ret.emplace_back(std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, false));
2008
1.22k
                    ++key_exp_index;
2009
1.22k
                    return ret;
2010
1.22k
                } else {
2011
4
                    error = "Uncompressed keys are not allowed";
2012
4
                    return {};
2013
4
                }
2014
18.5k
            } else if (data.size() == 32 && ctx == ParseScriptContext::P2TR) {
2015
18.5k
                unsigned char fullkey[33] = {0x02};
2016
18.5k
                std::copy(data.begin(), data.end(), fullkey + 1);
2017
18.5k
                pubkey.Set(std::begin(fullkey), std::end(fullkey));
2018
18.5k
                if (pubkey.IsFullyValid()) {
2019
18.5k
                    ret.emplace_back(std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, true));
2020
18.5k
                    ++key_exp_index;
2021
18.5k
                    return ret;
2022
18.5k
                }
2023
18.5k
            }
2024
6
            error = strprintf("Pubkey '%s' is invalid", str);
2025
6
            return {};
2026
19.8k
        }
2027
820
        CKey key = DecodeSecret(str);
2028
820
        if (key.IsValid()) {
2029
483
            if (permit_uncompressed || key.IsCompressed()) {
2030
478
                CPubKey pubkey = key.GetPubKey();
2031
478
                out.keys.emplace(pubkey.GetID(), key);
2032
478
                ret.emplace_back(std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, ctx == ParseScriptContext::P2TR));
2033
478
                ++key_exp_index;
2034
478
                return ret;
2035
478
            } else {
2036
5
                error = "Uncompressed keys are not allowed";
2037
5
                return {};
2038
5
            }
2039
483
        }
2040
820
    }
2041
9.01k
    CExtKey extkey = DecodeExtKey(str);
2042
9.01k
    CExtPubKey extpubkey = DecodeExtPubKey(str);
2043
9.01k
    if (!extkey.key.IsValid() && !extpubkey.pubkey.IsValid()) {
2044
4
        error = strprintf("key '%s' is not valid", str);
2045
4
        return {};
2046
4
    }
2047
9.00k
    std::vector<KeyPath> paths;
2048
9.00k
    DeriveType type = ParseDeriveType(split, apostrophe);
2049
9.00k
    if (!ParseKeyPath(split, paths, apostrophe, error, /*allow_multipath=*/true)) return {};
2050
8.98k
    if (extkey.key.IsValid()) {
2051
895
        extpubkey = extkey.Neuter();
2052
895
        out.keys.emplace(extpubkey.pubkey.GetID(), extkey.key);
2053
895
    }
2054
9.35k
    for (auto& path : paths) {
2055
9.35k
        ret.emplace_back(std::make_unique<BIP32PubkeyProvider>(key_exp_index, extpubkey, std::move(path), type, apostrophe));
2056
9.35k
    }
2057
8.98k
    ++key_exp_index;
2058
8.98k
    return ret;
2059
9.00k
}
2060
2061
/** Parse a public key including origin information (if enabled). */
2062
// NOLINTNEXTLINE(misc-no-recursion)
2063
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)
2064
29.5k
{
2065
29.5k
    std::vector<std::unique_ptr<PubkeyProvider>> ret;
2066
2067
29.5k
    using namespace script;
2068
2069
    // musig cannot be nested inside of an origin
2070
29.5k
    std::span<const char> span = sp;
2071
29.5k
    if (Const("musig(", span, /*skip=*/false)) {
2072
196
        if (ctx != ParseScriptContext::P2TR) {
2073
12
            error = "musig() is only allowed in tr() and rawtr()";
2074
12
            return {};
2075
12
        }
2076
2077
        // Split the span on the end parentheses. The end parentheses must
2078
        // be included in the resulting span so that Expr is happy.
2079
184
        auto split = Split(sp, ')', /*include_sep=*/true);
2080
184
        if (split.size() > 2) {
2081
2
            error = "Too many ')' in musig() expression";
2082
2
            return {};
2083
2
        }
2084
182
        std::span<const char> expr(split.at(0).begin(), split.at(0).end());
2085
182
        if (!Func("musig", expr)) {
2086
2
            error = "Invalid musig() expression";
2087
2
            return {};
2088
2
        }
2089
2090
        // Parse the participant pubkeys
2091
180
        bool any_ranged = false;
2092
180
        bool all_bip32 = true;
2093
180
        std::vector<std::vector<std::unique_ptr<PubkeyProvider>>> providers;
2094
180
        bool any_key_parsed = false;
2095
180
        size_t max_multipath_len = 0;
2096
633
        while (expr.size()) {
2097
457
            if (any_key_parsed && !Const(",", expr)) {
2098
2
                error = strprintf("musig(): expected ',', got '%c'", expr[0]);
2099
2
                return {};
2100
2
            }
2101
455
            auto arg = Expr(expr);
2102
455
            auto pk = ParsePubkey(key_exp_index, arg, ParseScriptContext::MUSIG, out, error);
2103
455
            if (pk.empty()) {
2104
2
                error = strprintf("musig(): %s", error);
2105
2
                return {};
2106
2
            }
2107
453
            any_key_parsed = true;
2108
2109
453
            any_ranged = any_ranged || pk.at(0)->IsRange();
2110
453
            all_bip32 = all_bip32 &&  pk.at(0)->IsBIP32();
2111
2112
453
            max_multipath_len = std::max(max_multipath_len, pk.size());
2113
2114
453
            providers.emplace_back(std::move(pk));
2115
453
        }
2116
176
        if (!any_key_parsed) {
2117
2
            error = "musig(): Must contain key expressions";
2118
2
            return {};
2119
2
        }
2120
2121
        // Parse any derivation
2122
174
        DeriveType deriv_type = DeriveType::NON_RANGED;
2123
174
        std::vector<KeyPath> derivation_multipaths;
2124
174
        if (split.size() == 2 && Const("/", split.at(1), /*skip=*/false)) {
2125
129
            if (!all_bip32) {
2126
4
                error = "musig(): derivation requires all participants to be xpubs or xprvs";
2127
4
                return {};
2128
4
            }
2129
125
            if (any_ranged) {
2130
4
                error = "musig(): Cannot have ranged participant keys if musig() also has derivation";
2131
4
                return {};
2132
4
            }
2133
121
            bool dummy = false;
2134
121
            auto deriv_split = Split(split.at(1), '/');
2135
121
            deriv_type = ParseDeriveType(deriv_split, dummy);
2136
121
            if (deriv_type == DeriveType::HARDENED_RANGED) {
2137
2
                error = "musig(): Cannot have hardened child derivation";
2138
2
                return {};
2139
2
            }
2140
119
            bool has_hardened = false;
2141
119
            if (!ParseKeyPath(deriv_split, derivation_multipaths, dummy, error, /*allow_multipath=*/true, has_hardened)) {
2142
2
                error = "musig(): " + error;
2143
2
                return {};
2144
2
            }
2145
117
            if (has_hardened) {
2146
2
                error = "musig(): cannot have hardened derivation steps";
2147
2
                return {};
2148
2
            }
2149
117
        } else {
2150
45
            derivation_multipaths.emplace_back();
2151
45
        }
2152
2153
        // Makes sure that all providers vectors in providers are the given length, or exactly length 1
2154
        // Length 1 vectors have the single provider cloned until it matches the given length.
2155
160
        const auto& clone_providers = [&providers](size_t length) -> bool {
2156
255
            for (auto& multipath_providers : providers) {
2157
255
                if (multipath_providers.size() == 1) {
2158
360
                    for (size_t i = 1; i < length; ++i) {
2159
194
                        multipath_providers.emplace_back(multipath_providers.at(0)->Clone());
2160
194
                    }
2161
166
                } else if (multipath_providers.size() != length) {
2162
2
                    return false;
2163
2
                }
2164
255
            }
2165
87
            return true;
2166
89
        };
2167
2168
        // Emplace the final MuSigPubkeyProvider into ret with the pubkey providers from the specified provider vectors index
2169
        // and the path from the specified path index
2170
260
        const auto& emplace_final_provider = [&ret, &key_exp_index, &deriv_type, &derivation_multipaths, &providers](size_t vec_idx, size_t path_idx) -> void {
2171
260
            KeyPath& path = derivation_multipaths.at(path_idx);
2172
260
            std::vector<std::unique_ptr<PubkeyProvider>> pubs;
2173
260
            pubs.reserve(providers.size());
2174
715
            for (auto& vec : providers) {
2175
715
                pubs.emplace_back(std::move(vec.at(vec_idx)));
2176
715
            }
2177
260
            ret.emplace_back(std::make_unique<MuSigPubkeyProvider>(key_exp_index, std::move(pubs), path, deriv_type));
2178
260
        };
2179
2180
160
        if (max_multipath_len > 1 && derivation_multipaths.size() > 1) {
2181
2
            error = "musig(): Cannot have multipath participant keys if musig() is also multipath";
2182
2
            return {};
2183
158
        } else if (max_multipath_len > 1) {
2184
34
            if (!clone_providers(max_multipath_len)) {
2185
2
                error = strprintf("musig(): Multipath derivation paths have mismatched lengths");
2186
2
                return {};
2187
2
            }
2188
106
            for (size_t i = 0; i < max_multipath_len; ++i) {
2189
                // Final MuSigPubkeyProvider uses participant pubkey providers at each multipath position, and the first (and only) path
2190
74
                emplace_final_provider(i, 0);
2191
74
            }
2192
124
        } else if (derivation_multipaths.size() > 1) {
2193
            // All key provider vectors should be length 1. Clone them until they have the same length as paths
2194
55
            if (!Assume(clone_providers(derivation_multipaths.size()))) {
2195
0
                error = "musig(): Multipath derivation path with multipath participants is disallowed"; // This error is unreachable due to earlier check
2196
0
                return {};
2197
0
            }
2198
172
            for (size_t i = 0; i < derivation_multipaths.size(); ++i) {
2199
                // Final MuSigPubkeyProvider uses cloned participant pubkey providers, and the multipath derivation paths
2200
117
                emplace_final_provider(i, i);
2201
117
            }
2202
69
        } else {
2203
            // No multipath derivation, MuSigPubkeyProvider uses the first (and only) participant pubkey providers, and the first (and only) path
2204
69
            emplace_final_provider(0, 0);
2205
69
        }
2206
156
        ++key_exp_index; // Increment key expression index for the MuSigPubkeyProvider too
2207
156
        return ret;
2208
160
    }
2209
2210
29.3k
    auto origin_split = Split(sp, ']');
2211
29.3k
    if (origin_split.size() > 2) {
2212
4
        error = "Multiple ']' characters found for a single pubkey";
2213
4
        return {};
2214
4
    }
2215
    // This is set if either the origin or path suffix contains a hardened derivation.
2216
29.3k
    bool apostrophe = false;
2217
29.3k
    if (origin_split.size() == 1) {
2218
24.1k
        return ParsePubkeyInner(key_exp_index, origin_split[0], ctx, out, apostrophe, error);
2219
24.1k
    }
2220
5.23k
    if (origin_split[0].empty() || origin_split[0][0] != '[') {
2221
2
        error = strprintf("Key origin start '[ character expected but not found, got '%c' instead",
2222
2
                          origin_split[0].empty() ? /** empty, implies split char */ ']' : origin_split[0][0]);
2223
2
        return {};
2224
2
    }
2225
5.23k
    auto slash_split = Split(origin_split[0].subspan(1), '/');
2226
5.23k
    if (slash_split[0].size() != 8) {
2227
6
        error = strprintf("Fingerprint is not 4 bytes (%u characters instead of 8 characters)", slash_split[0].size());
2228
6
        return {};
2229
6
    }
2230
5.23k
    std::string fpr_hex = std::string(slash_split[0].begin(), slash_split[0].end());
2231
5.23k
    if (!IsHex(fpr_hex)) {
2232
2
        error = strprintf("Fingerprint '%s' is not hex", fpr_hex);
2233
2
        return {};
2234
2
    }
2235
5.22k
    auto fpr_bytes = ParseHex(fpr_hex);
2236
5.22k
    KeyOriginInfo info;
2237
5.22k
    static_assert(sizeof(info.fingerprint) == 4, "Fingerprint must be 4 bytes");
2238
5.22k
    assert(fpr_bytes.size() == 4);
2239
5.22k
    std::copy_n(fpr_bytes.begin(), info.fingerprint.size(), info.fingerprint.begin());
2240
5.22k
    std::vector<KeyPath> path;
2241
5.22k
    if (!ParseKeyPath(slash_split, path, apostrophe, error, /*allow_multipath=*/false)) return {};
2242
5.22k
    info.path = path.at(0);
2243
5.22k
    auto providers = ParsePubkeyInner(key_exp_index, origin_split[1], ctx, out, apostrophe, error);
2244
5.22k
    if (providers.empty()) return {};
2245
5.22k
    ret.reserve(providers.size());
2246
5.31k
    for (auto& prov : providers) {
2247
5.31k
        ret.emplace_back(std::make_unique<OriginPubkeyProvider>(prov->m_expr_index, info, std::move(prov), apostrophe));
2248
5.31k
    }
2249
5.22k
    return ret;
2250
5.22k
}
2251
2252
std::unique_ptr<PubkeyProvider> InferPubkey(const CPubKey& pubkey, ParseScriptContext ctx, const SigningProvider& provider)
2253
273k
{
2254
    // Key cannot be hybrid
2255
273k
    if (!pubkey.IsValidNonHybrid()) {
2256
7
        return nullptr;
2257
7
    }
2258
    // Uncompressed is only allowed in TOP and P2SH contexts
2259
273k
    if (ctx != ParseScriptContext::TOP && ctx != ParseScriptContext::P2SH && !pubkey.IsCompressed()) {
2260
5
        return nullptr;
2261
5
    }
2262
273k
    std::unique_ptr<PubkeyProvider> key_provider = std::make_unique<ConstPubkeyProvider>(0, pubkey, false);
2263
273k
    KeyOriginInfo info;
2264
273k
    if (provider.GetKeyOrigin(pubkey.GetID(), info)) {
2265
272k
        return std::make_unique<OriginPubkeyProvider>(0, std::move(info), std::move(key_provider), /*apostrophe=*/false);
2266
272k
    }
2267
983
    return key_provider;
2268
273k
}
2269
2270
std::unique_ptr<PubkeyProvider> InferXOnlyPubkey(const XOnlyPubKey& xkey, ParseScriptContext ctx, const SigningProvider& provider)
2271
131k
{
2272
131k
    CPubKey pubkey{xkey.GetEvenCorrespondingCPubKey()};
2273
131k
    std::unique_ptr<PubkeyProvider> key_provider = std::make_unique<ConstPubkeyProvider>(0, pubkey, true);
2274
131k
    KeyOriginInfo info;
2275
131k
    if (provider.GetKeyOriginByXOnly(xkey, info)) {
2276
116k
        return std::make_unique<OriginPubkeyProvider>(0, std::move(info), std::move(key_provider), /*apostrophe=*/false);
2277
116k
    }
2278
14.6k
    return key_provider;
2279
131k
}
2280
2281
/**
2282
 * The context for parsing a Miniscript descriptor (either from Script or from its textual representation).
2283
 */
2284
struct KeyParser {
2285
    //! The Key type is an index in DescriptorImpl::m_pubkey_args
2286
    using Key = uint32_t;
2287
    //! Must not be nullptr if parsing from string.
2288
    FlatSigningProvider* m_out;
2289
    //! Must not be nullptr if parsing from Script.
2290
    const SigningProvider* m_in;
2291
    //! List of multipath expanded keys contained in the Miniscript.
2292
    mutable std::vector<std::vector<std::unique_ptr<PubkeyProvider>>> m_keys;
2293
    //! Used to detect key parsing errors within a Miniscript.
2294
    mutable std::string m_key_parsing_error;
2295
    //! The script context we're operating within (Tapscript or P2WSH).
2296
    const miniscript::MiniscriptContext m_script_ctx;
2297
    //! The current key expression index
2298
    uint32_t& m_expr_index;
2299
2300
    KeyParser(FlatSigningProvider* out LIFETIMEBOUND, const SigningProvider* in LIFETIMEBOUND,
2301
              miniscript::MiniscriptContext ctx, uint32_t& key_exp_index LIFETIMEBOUND)
2302
1.27k
        : m_out(out), m_in(in), m_script_ctx(ctx), m_expr_index(key_exp_index) {}
2303
2304
4.97k
    bool KeyCompare(const Key& a, const Key& b) const {
2305
        // Deriving a hardened step needs the private key, so use the provider that was filled
2306
        // while parsing, or the one we are inferring from, rather than an empty one.
2307
4.97k
        const SigningProvider& provider{m_out ? *m_out : (m_in ? *m_in : DUMMY_SIGNING_PROVIDER)};
2308
4.97k
        const PubkeyProvider& key_a{*m_keys.at(a).at(0)};
2309
4.97k
        const PubkeyProvider& key_b{*m_keys.at(b).at(0)};
2310
4.97k
        FlatSigningProvider out_a, out_b;
2311
4.97k
        const std::optional<CPubKey> pub_a{key_a.GetPubKey(0, provider, out_a)};
2312
4.97k
        const std::optional<CPubKey> pub_b{key_b.GetPubKey(0, provider, out_b)};
2313
4.97k
        if (pub_a && pub_b) return *pub_a < *pub_b;
2314
        // Keys that cannot be derived sort before the ones that can, and are compared by their
2315
        // expression so that two different keys are not taken for duplicates.
2316
47
        if (pub_a.has_value() != pub_b.has_value()) return !pub_a.has_value();
2317
14
        return key_a.ToString(PubkeyProvider::StringType::PUBLIC) < key_b.ToString(PubkeyProvider::StringType::PUBLIC);
2318
47
    }
2319
2320
2.21k
    ParseScriptContext ParseContext() const {
2321
2.21k
        switch (m_script_ctx) {
2322
1.55k
            case miniscript::MiniscriptContext::P2WSH: return ParseScriptContext::P2WSH;
2323
657
            case miniscript::MiniscriptContext::TAPSCRIPT: return ParseScriptContext::P2TR;
2324
2.21k
        }
2325
2.21k
        assert(false);
2326
0
    }
2327
2328
    std::optional<Key> FromString(std::span<const char>& in) const
2329
499
    {
2330
499
        assert(m_out);
2331
499
        Key key = m_keys.size();
2332
499
        auto pk = ParsePubkey(m_expr_index, in, ParseContext(), *m_out, m_key_parsing_error);
2333
499
        if (pk.empty()) return {};
2334
497
        m_keys.emplace_back(std::move(pk));
2335
497
        return key;
2336
499
    }
2337
2338
    std::optional<std::string> ToString(const Key& key, bool&) const
2339
38
    {
2340
38
        return m_keys.at(key).at(0)->ToString(PubkeyProvider::StringType::PUBLIC);
2341
38
    }
2342
2343
    template<typename I> std::optional<Key> FromPKBytes(I begin, I end) const
2344
1.36k
    {
2345
1.36k
        assert(m_in);
2346
1.36k
        Key key = m_keys.size();
2347
1.36k
        if (miniscript::IsTapscript(m_script_ctx) && end - begin == 32) {
2348
354
            XOnlyPubKey pubkey;
2349
354
            std::copy(begin, end, pubkey.begin());
2350
354
            if (auto pubkey_provider = InferXOnlyPubkey(pubkey, ParseContext(), *m_in)) {
2351
354
                m_keys.emplace_back();
2352
354
                m_keys.back().push_back(std::move(pubkey_provider));
2353
354
                return key;
2354
354
            }
2355
1.01k
        } else if (!miniscript::IsTapscript(m_script_ctx)) {
2356
1.01k
            CPubKey pubkey(begin, end);
2357
1.01k
            if (auto pubkey_provider = InferPubkey(pubkey, ParseContext(), *m_in)) {
2358
1.01k
                m_keys.emplace_back();
2359
1.01k
                m_keys.back().push_back(std::move(pubkey_provider));
2360
1.01k
                return key;
2361
1.01k
            }
2362
1.01k
        }
2363
2
        return {};
2364
1.36k
    }
2365
2366
    template<typename I> std::optional<Key> FromPKHBytes(I begin, I end) const
2367
344
    {
2368
344
        assert(end - begin == 20);
2369
344
        assert(m_in);
2370
344
        uint160 hash;
2371
344
        std::copy(begin, end, hash.begin());
2372
344
        CKeyID keyid(hash);
2373
344
        CPubKey pubkey;
2374
344
        if (m_in->GetPubKey(keyid, pubkey)) {
2375
344
            if (auto pubkey_provider = InferPubkey(pubkey, ParseContext(), *m_in)) {
2376
342
                Key key = m_keys.size();
2377
342
                m_keys.emplace_back();
2378
342
                m_keys.back().push_back(std::move(pubkey_provider));
2379
342
                return key;
2380
342
            }
2381
344
        }
2382
2
        return {};
2383
344
    }
2384
2385
998k
    miniscript::MiniscriptContext MsContext() const {
2386
998k
        return m_script_ctx;
2387
998k
    }
2388
};
2389
2390
/** Parse a script in a particular context. */
2391
// NOLINTNEXTLINE(misc-no-recursion)
2392
std::vector<std::unique_ptr<DescriptorImpl>> ParseScript(uint32_t& key_exp_index, std::span<const char>& sp, ParseScriptContext ctx, FlatSigningProvider& out, std::string& error)
2393
15.3k
{
2394
15.3k
    using namespace script;
2395
15.3k
    Assume(ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH || ctx == ParseScriptContext::P2TR);
2396
15.3k
    std::vector<std::unique_ptr<DescriptorImpl>> ret;
2397
15.3k
    auto expr = Expr(sp);
2398
15.3k
    if (Func("pk", expr)) {
2399
817
        auto pubkeys = ParsePubkey(key_exp_index, expr, ctx, out, error);
2400
817
        if (pubkeys.empty()) {
2401
12
            error = strprintf("pk(): %s", error);
2402
12
            return {};
2403
12
        }
2404
923
        for (auto& pubkey : pubkeys) {
2405
923
            ret.emplace_back(std::make_unique<PKDescriptor>(std::move(pubkey), ctx == ParseScriptContext::P2TR));
2406
923
        }
2407
805
        return ret;
2408
817
    }
2409
14.5k
    if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH) && Func("pkh", expr)) {
2410
1.90k
        auto pubkeys = ParsePubkey(key_exp_index, expr, ctx, out, error);
2411
1.90k
        if (pubkeys.empty()) {
2412
20
            error = strprintf("pkh(): %s", error);
2413
20
            return {};
2414
20
        }
2415
1.90k
        for (auto& pubkey : pubkeys) {
2416
1.90k
            ret.emplace_back(std::make_unique<PKHDescriptor>(std::move(pubkey)));
2417
1.90k
        }
2418
1.88k
        return ret;
2419
1.90k
    }
2420
12.6k
    if (ctx == ParseScriptContext::TOP && Func("combo", expr)) {
2421
686
        auto pubkeys = ParsePubkey(key_exp_index, expr, ctx, out, error);
2422
686
        if (pubkeys.empty()) {
2423
5
            error = strprintf("combo(): %s", error);
2424
5
            return {};
2425
5
        }
2426
681
        for (auto& pubkey : pubkeys) {
2427
681
            ret.emplace_back(std::make_unique<ComboDescriptor>(std::move(pubkey)));
2428
681
        }
2429
681
        return ret;
2430
11.9k
    } else if (Func("combo", expr)) {
2431
2
        error = "Can only have combo() at top level";
2432
2
        return {};
2433
2
    }
2434
11.9k
    const bool multi = Func("multi", expr);
2435
11.9k
    const bool sortedmulti = !multi && Func("sortedmulti", expr);
2436
11.9k
    const bool multi_a = !(multi || sortedmulti) && Func("multi_a", expr);
2437
11.9k
    const bool sortedmulti_a = !(multi || sortedmulti || multi_a) && Func("sortedmulti_a", expr);
2438
11.9k
    if (((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH) && (multi || sortedmulti)) ||
2439
11.9k
        (ctx == ParseScriptContext::P2TR && (multi_a || sortedmulti_a))) {
2440
376
        auto threshold = Expr(expr);
2441
376
        uint32_t thres;
2442
376
        std::vector<std::vector<std::unique_ptr<PubkeyProvider>>> providers; // List of multipath expanded pubkeys
2443
376
        if (const auto maybe_thres{ToIntegral<uint32_t>(std::string_view{threshold.begin(), threshold.end()})}) {
2444
372
            thres = *maybe_thres;
2445
372
        } else {
2446
4
            error = strprintf("Multi threshold '%s' is not valid", std::string(threshold.begin(), threshold.end()));
2447
4
            return {};
2448
4
        }
2449
372
        size_t script_size = 0;
2450
372
        size_t max_providers_len = 0;
2451
19.3k
        while (expr.size()) {
2452
18.9k
            if (!Const(",", expr)) {
2453
1
                error = strprintf("Multi: expected ',', got '%c'", expr[0]);
2454
1
                return {};
2455
1
            }
2456
18.9k
            auto arg = Expr(expr);
2457
18.9k
            auto pks = ParsePubkey(key_exp_index, arg, ctx, out, error);
2458
18.9k
            if (pks.empty()) {
2459
14
                error = strprintf("Multi: %s", error);
2460
14
                return {};
2461
14
            }
2462
18.9k
            script_size += pks.at(0)->GetSize() + 1;
2463
18.9k
            max_providers_len = std::max(max_providers_len, pks.size());
2464
18.9k
            providers.emplace_back(std::move(pks));
2465
18.9k
        }
2466
357
        if ((multi || sortedmulti) && (providers.empty() || providers.size() > MAX_PUBKEYS_PER_MULTISIG)) {
2467
1
            error = strprintf("Cannot have %u keys in multisig; must have between 1 and %d keys, inclusive", providers.size(), MAX_PUBKEYS_PER_MULTISIG);
2468
1
            return {};
2469
356
        } else if ((multi_a || sortedmulti_a) && (providers.empty() || providers.size() > MAX_PUBKEYS_PER_MULTI_A)) {
2470
1
            error = strprintf("Cannot have %u keys in multi_a; must have between 1 and %d keys, inclusive", providers.size(), MAX_PUBKEYS_PER_MULTI_A);
2471
1
            return {};
2472
355
        } else if (thres < 1) {
2473
2
            error = strprintf("Multisig threshold cannot be %d, must be at least 1", thres);
2474
2
            return {};
2475
353
        } else if (thres > providers.size()) {
2476
2
            error = strprintf("Multisig threshold cannot be larger than the number of keys; threshold is %d but only %u keys specified", thres, providers.size());
2477
2
            return {};
2478
2
        }
2479
351
        if (ctx == ParseScriptContext::TOP) {
2480
26
            if (providers.size() > 3) {
2481
2
                error = strprintf("Cannot have %u pubkeys in bare multisig; only at most 3 pubkeys", providers.size());
2482
2
                return {};
2483
2
            }
2484
26
        }
2485
349
        if (ctx == ParseScriptContext::P2SH) {
2486
            // This limits the maximum number of compressed pubkeys to 15.
2487
59
            if (script_size + 3 > MAX_SCRIPT_ELEMENT_SIZE) {
2488
4
                error = strprintf("P2SH script is too large, %d bytes is larger than %d bytes", script_size + 3, MAX_SCRIPT_ELEMENT_SIZE);
2489
4
                return {};
2490
4
            }
2491
59
        }
2492
2493
        // Make sure all vecs are of the same length, or exactly length 1
2494
        // For length 1 vectors, clone key providers until vector is the same length
2495
18.8k
        for (auto& vec : providers) {
2496
18.8k
            if (vec.size() == 1) {
2497
18.8k
                for (size_t i = 1; i < max_providers_len; ++i) {
2498
18
                    vec.emplace_back(vec.at(0)->Clone());
2499
18
                }
2500
18.8k
            } else if (vec.size() != max_providers_len) {
2501
2
                error = strprintf("multi(): Multipath derivation paths have mismatched lengths");
2502
2
                return {};
2503
2
            }
2504
18.8k
        }
2505
2506
        // Build the final descriptors vector
2507
710
        for (size_t i = 0; i < max_providers_len; ++i) {
2508
            // Build final pubkeys vectors by retrieving the i'th subscript for each vector in subscripts
2509
367
            std::vector<std::unique_ptr<PubkeyProvider>> pubs;
2510
367
            pubs.reserve(providers.size());
2511
18.9k
            for (auto& pub : providers) {
2512
18.9k
                pubs.emplace_back(std::move(pub.at(i)));
2513
18.9k
            }
2514
367
            if (multi || sortedmulti) {
2515
235
                ret.emplace_back(std::make_unique<MultisigDescriptor>(thres, std::move(pubs), sortedmulti));
2516
235
            } else {
2517
132
                ret.emplace_back(std::make_unique<MultiADescriptor>(thres, std::move(pubs), sortedmulti_a));
2518
132
            }
2519
367
        }
2520
343
        return ret;
2521
11.5k
    } else if (multi || sortedmulti) {
2522
2
        error = "Can only have multi/sortedmulti at top level, in sh(), or in wsh()";
2523
2
        return {};
2524
11.5k
    } else if (multi_a || sortedmulti_a) {
2525
2
        error = "Can only have multi_a/sortedmulti_a inside tr()";
2526
2
        return {};
2527
2
    }
2528
11.5k
    if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH) && Func("wpkh", expr)) {
2529
3.88k
        auto pubkeys = ParsePubkey(key_exp_index, expr, ParseScriptContext::P2WPKH, out, error);
2530
3.88k
        if (pubkeys.empty()) {
2531
27
            error = strprintf("wpkh(): %s", error);
2532
27
            return {};
2533
27
        }
2534
3.87k
        for (auto& pubkey : pubkeys) {
2535
3.87k
            ret.emplace_back(std::make_unique<WPKHDescriptor>(std::move(pubkey)));
2536
3.87k
        }
2537
3.86k
        return ret;
2538
7.69k
    } else if (Func("wpkh", expr)) {
2539
3
        error = "Can only have wpkh() at top level or inside sh()";
2540
3
        return {};
2541
3
    }
2542
7.69k
    if (ctx == ParseScriptContext::TOP && Func("sh", expr)) {
2543
2.03k
        auto descs = ParseScript(key_exp_index, expr, ParseScriptContext::P2SH, out, error);
2544
2.03k
        if (descs.empty() || expr.size()) return {};
2545
1.99k
        std::vector<std::unique_ptr<DescriptorImpl>> ret;
2546
1.99k
        ret.reserve(descs.size());
2547
2.01k
        for (auto& desc : descs) {
2548
2.01k
            ret.push_back(std::make_unique<SHDescriptor>(std::move(desc)));
2549
2.01k
        }
2550
1.99k
        return ret;
2551
5.66k
    } else if (Func("sh", expr)) {
2552
6
        error = "Can only have sh() at top level";
2553
6
        return {};
2554
6
    }
2555
5.65k
    if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH) && Func("wsh", expr)) {
2556
311
        auto descs = ParseScript(key_exp_index, expr, ParseScriptContext::P2WSH, out, error);
2557
311
        if (descs.empty() || expr.size()) return {};
2558
271
        for (auto& desc : descs) {
2559
271
            ret.emplace_back(std::make_unique<WSHDescriptor>(std::move(desc)));
2560
271
        }
2561
259
        return ret;
2562
5.34k
    } else if (Func("wsh", expr)) {
2563
3
        error = "Can only have wsh() at top level or inside sh()";
2564
3
        return {};
2565
3
    }
2566
5.34k
    if (ctx == ParseScriptContext::TOP && Func("addr", expr)) {
2567
97
        CTxDestination dest = DecodeDestination(std::string(expr.begin(), expr.end()));
2568
97
        if (!IsValidDestination(dest)) {
2569
3
            error = "Address is not valid";
2570
3
            return {};
2571
3
        }
2572
94
        ret.emplace_back(std::make_unique<AddressDescriptor>(std::move(dest)));
2573
94
        return ret;
2574
5.24k
    } else if (Func("addr", expr)) {
2575
2
        error = "Can only have addr() at top level";
2576
2
        return {};
2577
2
    }
2578
5.24k
    if (ctx == ParseScriptContext::TOP && Func("tr", expr)) {
2579
2.21k
        auto arg = Expr(expr);
2580
2.21k
        auto internal_keys = ParsePubkey(key_exp_index, arg, ParseScriptContext::P2TR, out, error);
2581
2.21k
        if (internal_keys.empty()) {
2582
30
            error = strprintf("tr(): %s", error);
2583
30
            return {};
2584
30
        }
2585
2.18k
        size_t max_providers_len = internal_keys.size();
2586
2.18k
        std::vector<std::vector<std::unique_ptr<DescriptorImpl>>> subscripts; //!< list of multipath expanded script subexpressions
2587
2.18k
        std::vector<int> depths; //!< depth in the tree of each subexpression (same length subscripts)
2588
2.18k
        if (expr.size()) {
2589
397
            if (!Const(",", expr)) {
2590
2
                error = strprintf("tr: expected ',', got '%c'", expr[0]);
2591
2
                return {};
2592
2
            }
2593
            /** The path from the top of the tree to what we're currently processing.
2594
             * branches[i] == false: left branch in the i'th step from the top; true: right branch.
2595
             */
2596
395
            std::vector<bool> branches;
2597
            // Loop over all provided scripts. In every iteration exactly one script will be processed.
2598
            // Use a do-loop because inside this if-branch we expect at least one script.
2599
985
            do {
2600
                // First process all open braces.
2601
1.85k
                while (Const("{", expr)) {
2602
872
                    branches.push_back(false); // new left branch
2603
872
                    if (branches.size() > TAPROOT_CONTROL_MAX_NODE_COUNT) {
2604
2
                        error = strprintf("tr() supports at most %i nesting levels", TAPROOT_CONTROL_MAX_NODE_COUNT);
2605
2
                        return {};
2606
2
                    }
2607
872
                }
2608
                // Process the actual script expression.
2609
983
                auto sarg = Expr(expr);
2610
983
                subscripts.emplace_back(ParseScript(key_exp_index, sarg, ParseScriptContext::P2TR, out, error));
2611
983
                if (subscripts.back().empty()) return {};
2612
978
                max_providers_len = std::max(max_providers_len, subscripts.back().size());
2613
978
                depths.push_back(branches.size());
2614
                // Process closing braces; one is expected for every right branch we were in.
2615
1.56k
                while (branches.size() && branches.back()) {
2616
590
                    if (!Const("}", expr)) {
2617
2
                        error = strprintf("tr(): expected '}' after script expression");
2618
2
                        return {};
2619
2
                    }
2620
588
                    branches.pop_back(); // move up one level after encountering '}'
2621
588
                }
2622
                // If after that, we're at the end of a left branch, expect a comma.
2623
976
                if (branches.size() && !branches.back()) {
2624
592
                    if (!Const(",", expr)) {
2625
2
                        error = strprintf("tr(): expected ',' after script expression");
2626
2
                        return {};
2627
2
                    }
2628
590
                    branches.back() = true; // And now we're in a right branch.
2629
590
                }
2630
976
            } while (branches.size());
2631
            // After we've explored a whole tree, we must be at the end of the expression.
2632
384
            if (expr.size()) {
2633
2
                error = strprintf("tr(): expected ')' after script expression");
2634
2
                return {};
2635
2
            }
2636
384
        }
2637
2.18k
        assert(TaprootBuilder::ValidDepths(depths));
2638
2639
        // Make sure all vecs are of the same length, or exactly length 1
2640
        // For length 1 vectors, clone subdescs until vector is the same length
2641
2.16k
        for (auto& vec : subscripts) {
2642
968
            if (vec.size() == 1) {
2643
902
                for (size_t i = 1; i < max_providers_len; ++i) {
2644
20
                    vec.emplace_back(vec.at(0)->Clone());
2645
20
                }
2646
882
            } else if (vec.size() != max_providers_len) {
2647
4
                error = strprintf("tr(): Multipath subscripts have mismatched lengths");
2648
4
                return {};
2649
4
            }
2650
968
        }
2651
2652
2.16k
        if (internal_keys.size() > 1 && internal_keys.size() != max_providers_len) {
2653
2
            error = strprintf("tr(): Multipath internal key mismatches multipath subscripts lengths");
2654
2
            return {};
2655
2
        }
2656
2657
2.22k
        while (internal_keys.size() < max_providers_len) {
2658
63
            internal_keys.emplace_back(internal_keys.at(0)->Clone());
2659
63
        }
2660
2661
        // Build the final descriptors vector
2662
4.43k
        for (size_t i = 0; i < max_providers_len; ++i) {
2663
            // Build final subscripts vectors by retrieving the i'th subscript for each vector in subscripts
2664
2.26k
            std::vector<std::unique_ptr<DescriptorImpl>> this_subs;
2665
2.26k
            this_subs.reserve(subscripts.size());
2666
2.26k
            for (auto& subs : subscripts) {
2667
1.08k
                this_subs.emplace_back(std::move(subs.at(i)));
2668
1.08k
            }
2669
2.26k
            ret.emplace_back(std::make_unique<TRDescriptor>(std::move(internal_keys.at(i)), std::move(this_subs), depths));
2670
2.26k
        }
2671
2.16k
        return ret;
2672
2673
2674
3.02k
    } else if (Func("tr", expr)) {
2675
2
        error = "Can only have tr at top level";
2676
2
        return {};
2677
2
    }
2678
3.02k
    if (ctx == ParseScriptContext::TOP && Func("rawtr", expr)) {
2679
83
        auto arg = Expr(expr);
2680
83
        if (expr.size()) {
2681
1
            error = strprintf("rawtr(): only one key expected.");
2682
1
            return {};
2683
1
        }
2684
82
        auto output_keys = ParsePubkey(key_exp_index, arg, ParseScriptContext::P2TR, out, error);
2685
82
        if (output_keys.empty()) {
2686
2
            error = strprintf("rawtr(): %s", error);
2687
2
            return {};
2688
2
        }
2689
123
        for (auto& pubkey : output_keys) {
2690
123
            ret.emplace_back(std::make_unique<RawTRDescriptor>(std::move(pubkey)));
2691
123
        }
2692
80
        return ret;
2693
2.94k
    } else if (Func("rawtr", expr)) {
2694
2
        error = "Can only have rawtr at top level";
2695
2
        return {};
2696
2
    }
2697
2.94k
    if (ctx == ParseScriptContext::TOP && Func("unused", expr)) {
2698
        // Check for only one expression, should not find commas, brackets, or parentheses
2699
29
        auto arg = Expr(expr);
2700
29
        if (expr.size()) {
2701
2
            error = strprintf("unused(): only one key expected");
2702
2
            return {};
2703
2
        }
2704
27
        auto keys = ParsePubkey(key_exp_index, arg, ctx, out, error);
2705
27
        if (keys.empty()) return {};
2706
23
        for (auto& pubkey : keys) {
2707
23
            if (pubkey->IsRange()) {
2708
2
                error = "unused(): key cannot be ranged";
2709
2
                return {};
2710
2
            }
2711
21
            ret.emplace_back(std::make_unique<UnusedDescriptor>(std::move(pubkey)));
2712
21
        }
2713
21
        return ret;
2714
2.91k
    } else if (Func("unused", expr)) {
2715
2
        error = "Can only have unused at top level";
2716
2
        return {};
2717
2
    }
2718
2.91k
    if (ctx == ParseScriptContext::TOP && Func("raw", expr)) {
2719
2.33k
        std::string str(expr.begin(), expr.end());
2720
2.33k
        if (!IsHex(str)) {
2721
2
            error = "Raw script is not hex";
2722
2
            return {};
2723
2
        }
2724
2.33k
        auto bytes = ParseHex(str);
2725
2.33k
        ret.emplace_back(std::make_unique<RawDescriptor>(CScript(bytes.begin(), bytes.end())));
2726
2.33k
        return ret;
2727
2.33k
    } else if (Func("raw", expr)) {
2728
2
        error = "Can only have raw() at top level";
2729
2
        return {};
2730
2
    }
2731
    // Process miniscript expressions.
2732
576
    {
2733
576
        const auto script_ctx{ctx == ParseScriptContext::P2WSH ? miniscript::MiniscriptContext::P2WSH : miniscript::MiniscriptContext::TAPSCRIPT};
2734
576
        KeyParser parser(/*out = */&out, /* in = */nullptr, /* ctx = */script_ctx, key_exp_index);
2735
576
        auto node = miniscript::FromString(std::string(expr.begin(), expr.end()), parser);
2736
576
        if (parser.m_key_parsing_error != "") {
2737
2
            error = std::move(parser.m_key_parsing_error);
2738
2
            return {};
2739
2
        }
2740
574
        if (node) {
2741
211
            if (ctx != ParseScriptContext::P2WSH && ctx != ParseScriptContext::P2TR) {
2742
3
                error = "Miniscript expressions can only be used in wsh or tr.";
2743
3
                return {};
2744
3
            }
2745
208
            if (!node->IsSane() || node->IsNotSatisfiable()) {
2746
                // Try to find the first insane sub for better error reporting.
2747
16
                const auto* insane_node = &node.value();
2748
16
                if (const auto sub = node->FindInsaneSub()) insane_node = sub;
2749
16
                error = *insane_node->ToString(parser);
2750
16
                if (!insane_node->IsValid()) {
2751
4
                    error += " is invalid";
2752
12
                } else if (!node->IsSane()) {
2753
11
                    error += " is not sane";
2754
11
                    if (!insane_node->IsNonMalleable()) {
2755
2
                        error += ": malleable witnesses exist";
2756
9
                    } else if (insane_node == &node.value() && !insane_node->NeedsSignature()) {
2757
3
                        error += ": witnesses without signature exist";
2758
6
                    } else if (!insane_node->CheckTimeLocksMix()) {
2759
2
                        error += ": contains mixes of timelocks expressed in blocks and seconds";
2760
4
                    } else if (!insane_node->CheckDuplicateKey()) {
2761
4
                        error += ": contains duplicate public keys";
2762
4
                    } else if (!insane_node->ValidSatisfactions()) {
2763
0
                        error += ": needs witnesses that may exceed resource limits";
2764
0
                    }
2765
11
                } else {
2766
1
                    error += " is not satisfiable";
2767
1
                }
2768
16
                return {};
2769
16
            }
2770
            // A signature check is required for a miniscript to be sane. Therefore no sane miniscript
2771
            // may have an empty list of public keys.
2772
192
            CHECK_NONFATAL(!parser.m_keys.empty());
2773
            // Make sure all vecs are of the same length, or exactly length 1
2774
            // For length 1 vectors, clone subdescs until vector is the same length
2775
192
            size_t num_multipath = std::max_element(parser.m_keys.begin(), parser.m_keys.end(),
2776
263
                    [](const std::vector<std::unique_ptr<PubkeyProvider>>& a, const std::vector<std::unique_ptr<PubkeyProvider>>& b) {
2777
263
                        return a.size() < b.size();
2778
263
                    })->size();
2779
2780
455
            for (auto& vec : parser.m_keys) {
2781
455
                if (vec.size() == 1) {
2782
410
                    for (size_t i = 1; i < num_multipath; ++i) {
2783
0
                        vec.emplace_back(vec.at(0)->Clone());
2784
0
                    }
2785
410
                } else if (vec.size() != num_multipath) {
2786
2
                    error = strprintf("Miniscript: Multipath derivation paths have mismatched lengths");
2787
2
                    return {};
2788
2
                }
2789
455
            }
2790
2791
            // Build the final descriptors vector
2792
407
            for (size_t i = 0; i < num_multipath; ++i) {
2793
                // Build final pubkeys vectors by retrieving the i'th subscript for each vector in subscripts
2794
217
                std::vector<std::unique_ptr<PubkeyProvider>> pubs;
2795
217
                pubs.reserve(parser.m_keys.size());
2796
492
                for (auto& pub : parser.m_keys) {
2797
492
                    pubs.emplace_back(std::move(pub.at(i)));
2798
492
                }
2799
217
                ret.emplace_back(std::make_unique<MiniscriptDescriptor>(std::move(pubs), node->Clone()));
2800
217
            }
2801
190
            return ret;
2802
192
        }
2803
574
    }
2804
363
    if (ctx == ParseScriptContext::P2SH) {
2805
4
        error = "A function is needed within P2SH";
2806
4
        return {};
2807
359
    } else if (ctx == ParseScriptContext::P2WSH) {
2808
4
        error = "A function is needed within P2WSH";
2809
4
        return {};
2810
4
    }
2811
355
    error = strprintf("'%s' is not a valid descriptor function", std::string(expr.begin(), expr.end()));
2812
355
    return {};
2813
363
}
2814
2815
std::unique_ptr<DescriptorImpl> InferMultiA(const CScript& script, ParseScriptContext ctx, const SigningProvider& provider)
2816
1.08k
{
2817
1.08k
    auto match = MatchMultiA(script);
2818
1.08k
    if (!match) return {};
2819
788
    std::vector<std::unique_ptr<PubkeyProvider>> keys;
2820
788
    keys.reserve(match->second.size());
2821
107k
    for (const auto keyspan : match->second) {
2822
107k
        if (keyspan.size() != 32) return {};
2823
107k
        auto key = InferXOnlyPubkey(XOnlyPubKey{keyspan}, ctx, provider);
2824
107k
        if (!key) return {};
2825
107k
        keys.push_back(std::move(key));
2826
107k
    }
2827
788
    return std::make_unique<MultiADescriptor>(match->first, std::move(keys));
2828
788
}
2829
2830
// NOLINTNEXTLINE(misc-no-recursion)
2831
std::unique_ptr<DescriptorImpl> InferScript(const CScript& script, ParseScriptContext ctx, const SigningProvider& provider)
2832
321k
{
2833
321k
    if (ctx == ParseScriptContext::P2TR && script.size() == 34 && script[0] == 32 && script[33] == OP_CHECKSIG) {
2834
3.31k
        XOnlyPubKey key{std::span{script}.subspan(1, 32)};
2835
3.31k
        return std::make_unique<PKDescriptor>(InferXOnlyPubkey(key, ctx, provider), true);
2836
3.31k
    }
2837
2838
317k
    if (ctx == ParseScriptContext::P2TR) {
2839
1.08k
        auto ret = InferMultiA(script, ctx, provider);
2840
1.08k
        if (ret) return ret;
2841
1.08k
    }
2842
2843
316k
    std::vector<std::vector<unsigned char>> data;
2844
316k
    TxoutType txntype = Solver(script, data);
2845
2846
316k
    if (txntype == TxoutType::PUBKEY && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
2847
18.5k
        CPubKey pubkey(data[0]);
2848
18.5k
        if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
2849
18.5k
            return std::make_unique<PKDescriptor>(std::move(pubkey_provider));
2850
18.5k
        }
2851
18.5k
    }
2852
298k
    if (txntype == TxoutType::PUBKEYHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
2853
87.1k
        uint160 hash(data[0]);
2854
87.1k
        CKeyID keyid(hash);
2855
87.1k
        CPubKey pubkey;
2856
87.1k
        if (provider.GetPubKey(keyid, pubkey)) {
2857
86.5k
            if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
2858
86.5k
                return std::make_unique<PKHDescriptor>(std::move(pubkey_provider));
2859
86.5k
            }
2860
86.5k
        }
2861
87.1k
    }
2862
211k
    if (txntype == TxoutType::WITNESS_V0_KEYHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH)) {
2863
165k
        uint160 hash(data[0]);
2864
165k
        CKeyID keyid(hash);
2865
165k
        CPubKey pubkey;
2866
165k
        if (provider.GetPubKey(keyid, pubkey)) {
2867
163k
            if (auto pubkey_provider = InferPubkey(pubkey, ParseScriptContext::P2WPKH, provider)) {
2868
163k
                return std::make_unique<WPKHDescriptor>(std::move(pubkey_provider));
2869
163k
            }
2870
163k
        }
2871
165k
    }
2872
47.8k
    if (txntype == TxoutType::MULTISIG && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
2873
667
        bool ok = true;
2874
667
        std::vector<std::unique_ptr<PubkeyProvider>> providers;
2875
3.31k
        for (size_t i = 1; i + 1 < data.size(); ++i) {
2876
2.64k
            CPubKey pubkey(data[i]);
2877
2.64k
            if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
2878
2.64k
                providers.push_back(std::move(pubkey_provider));
2879
2.64k
            } else {
2880
0
                ok = false;
2881
0
                break;
2882
0
            }
2883
2.64k
        }
2884
667
        if (ok) return std::make_unique<MultisigDescriptor>((int)data[0][0], std::move(providers));
2885
667
    }
2886
47.1k
    if (txntype == TxoutType::SCRIPTHASH && ctx == ParseScriptContext::TOP) {
2887
20.9k
        uint160 hash(data[0]);
2888
20.9k
        CScriptID scriptid(hash);
2889
20.9k
        CScript subscript;
2890
20.9k
        if (provider.GetCScript(scriptid, subscript)) {
2891
20.3k
            auto sub = InferScript(subscript, ParseScriptContext::P2SH, provider);
2892
20.3k
            if (sub) return std::make_unique<SHDescriptor>(std::move(sub));
2893
20.3k
        }
2894
20.9k
    }
2895
26.8k
    if (txntype == TxoutType::WITNESS_V0_SCRIPTHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH)) {
2896
1.05k
        CScriptID scriptid{RIPEMD160(data[0])};
2897
1.05k
        CScript subscript;
2898
1.05k
        if (provider.GetCScript(scriptid, subscript)) {
2899
894
            auto sub = InferScript(subscript, ParseScriptContext::P2WSH, provider);
2900
894
            if (sub) return std::make_unique<WSHDescriptor>(std::move(sub));
2901
894
        }
2902
1.05k
    }
2903
25.9k
    if (txntype == TxoutType::WITNESS_V1_TAPROOT && ctx == ParseScriptContext::TOP) {
2904
        // Extract x-only pubkey from output.
2905
20.0k
        XOnlyPubKey pubkey;
2906
20.0k
        std::copy(data[0].begin(), data[0].end(), pubkey.begin());
2907
        // Request spending data.
2908
20.0k
        TaprootSpendData tap;
2909
20.0k
        if (provider.GetTaprootSpendData(pubkey, tap)) {
2910
            // If found, convert it back to tree form.
2911
4.97k
            auto tree = InferTaprootTree(tap, pubkey);
2912
4.97k
            if (tree) {
2913
                // If that works, try to infer subdescriptors for all leaves.
2914
4.97k
                bool ok = true;
2915
4.97k
                std::vector<std::unique_ptr<DescriptorImpl>> subscripts; //!< list of script subexpressions
2916
4.97k
                std::vector<int> depths; //!< depth in the tree of each subexpression (same length subscripts)
2917
4.97k
                for (const auto& [depth, script, leaf_ver] : *tree) {
2918
4.39k
                    std::unique_ptr<DescriptorImpl> subdesc;
2919
4.39k
                    if (leaf_ver == TAPROOT_LEAF_TAPSCRIPT) {
2920
4.39k
                        subdesc = InferScript(CScript(script.begin(), script.end()), ParseScriptContext::P2TR, provider);
2921
4.39k
                    }
2922
4.39k
                    if (!subdesc) {
2923
0
                        ok = false;
2924
0
                        break;
2925
4.39k
                    } else {
2926
4.39k
                        subscripts.push_back(std::move(subdesc));
2927
4.39k
                        depths.push_back(depth);
2928
4.39k
                    }
2929
4.39k
                }
2930
4.97k
                if (ok) {
2931
4.97k
                    auto key = InferXOnlyPubkey(tap.internal_key, ParseScriptContext::P2TR, provider);
2932
4.97k
                    return std::make_unique<TRDescriptor>(std::move(key), std::move(subscripts), std::move(depths));
2933
4.97k
                }
2934
4.97k
            }
2935
4.97k
        }
2936
        // If the above doesn't work, construct a rawtr() descriptor with just the encoded x-only pubkey.
2937
15.0k
        if (pubkey.IsFullyValid()) {
2938
15.0k
            auto key = InferXOnlyPubkey(pubkey, ParseScriptContext::P2TR, provider);
2939
15.0k
            if (key) {
2940
15.0k
                return std::make_unique<RawTRDescriptor>(std::move(key));
2941
15.0k
            }
2942
15.0k
        }
2943
15.0k
    }
2944
2945
5.95k
    if (ctx == ParseScriptContext::P2WSH || ctx == ParseScriptContext::P2TR) {
2946
702
        const auto script_ctx{ctx == ParseScriptContext::P2WSH ? miniscript::MiniscriptContext::P2WSH : miniscript::MiniscriptContext::TAPSCRIPT};
2947
702
        uint32_t key_exp_index = 0;
2948
702
        KeyParser parser(/* out = */nullptr, /* in = */&provider, /* ctx = */script_ctx, key_exp_index);
2949
702
        auto node = miniscript::FromScript(script, parser);
2950
702
        if (node && node->IsSane()) {
2951
689
            std::vector<std::unique_ptr<PubkeyProvider>> keys;
2952
689
            keys.reserve(parser.m_keys.size());
2953
1.70k
            for (auto& key : parser.m_keys) {
2954
1.70k
                keys.emplace_back(std::move(key.at(0)));
2955
1.70k
            }
2956
689
            return std::make_unique<MiniscriptDescriptor>(std::move(keys), std::move(*node));
2957
689
        }
2958
702
    }
2959
2960
    // The following descriptors are all top-level only descriptors.
2961
    // So if we are not at the top level, return early.
2962
5.26k
    if (ctx != ParseScriptContext::TOP) return nullptr;
2963
2964
5.24k
    CTxDestination dest;
2965
5.24k
    if (ExtractDestination(script, dest)) {
2966
3.10k
        if (GetScriptForDestination(dest) == script) {
2967
3.10k
            return std::make_unique<AddressDescriptor>(std::move(dest));
2968
3.10k
        }
2969
3.10k
    }
2970
2971
2.13k
    return std::make_unique<RawDescriptor>(script);
2972
5.24k
}
2973
2974
2975
} // namespace
2976
2977
/** Check a descriptor checksum, and update desc to be the checksum-less part. */
2978
bool CheckChecksum(std::span<const char>& sp, bool require_checksum, std::string& error, std::string* out_checksum = nullptr)
2979
12.5k
{
2980
12.5k
    auto check_split = Split(sp, '#');
2981
12.5k
    if (check_split.size() > 2) {
2982
2
        error = "Multiple '#' symbols";
2983
2
        return false;
2984
2
    }
2985
12.5k
    if (check_split.size() == 1 && require_checksum){
2986
7
        error = "Missing checksum";
2987
7
        return false;
2988
7
    }
2989
12.5k
    if (check_split.size() == 2) {
2990
6.94k
        if (check_split[1].size() != 8) {
2991
6
            error = strprintf("Expected 8 character checksum, not %u characters", check_split[1].size());
2992
6
            return false;
2993
6
        }
2994
6.94k
    }
2995
12.5k
    auto checksum = DescriptorChecksum(check_split[0]);
2996
12.5k
    if (checksum.empty()) {
2997
1
        error = "Invalid characters in payload";
2998
1
        return false;
2999
1
    }
3000
12.5k
    if (check_split.size() == 2) {
3001
6.93k
        if (!std::equal(checksum.begin(), checksum.end(), check_split[1].begin())) {
3002
13
            error = strprintf("Provided checksum '%s' does not match computed checksum '%s'", std::string(check_split[1].begin(), check_split[1].end()), checksum);
3003
13
            return false;
3004
13
        }
3005
6.93k
    }
3006
12.4k
    if (out_checksum) *out_checksum = std::move(checksum);
3007
12.4k
    sp = check_split[0];
3008
12.4k
    return true;
3009
12.5k
}
3010
3011
std::vector<std::unique_ptr<Descriptor>> Parse(std::string_view descriptor, FlatSigningProvider& out, std::string& error, bool require_checksum)
3012
12.0k
{
3013
12.0k
    std::span<const char> sp{descriptor};
3014
12.0k
    if (!CheckChecksum(sp, require_checksum, error)) return {};
3015
12.0k
    uint32_t key_exp_index = 0;
3016
12.0k
    auto ret = ParseScript(key_exp_index, sp, ParseScriptContext::TOP, out, error);
3017
12.0k
    if (sp.empty() && !ret.empty()) {
3018
11.4k
        std::vector<std::unique_ptr<Descriptor>> descs;
3019
11.4k
        descs.reserve(ret.size());
3020
11.6k
        for (auto& r : ret) {
3021
11.6k
            descs.emplace_back(std::unique_ptr<Descriptor>(std::move(r)));
3022
11.6k
        }
3023
11.4k
        return descs;
3024
11.4k
    }
3025
573
    return {};
3026
12.0k
}
3027
3028
std::string GetDescriptorChecksum(const std::string& descriptor)
3029
449
{
3030
449
    std::string ret;
3031
449
    std::string error;
3032
449
    std::span<const char> sp{descriptor};
3033
449
    if (!CheckChecksum(sp, false, error, &ret)) return "";
3034
443
    return ret;
3035
449
}
3036
3037
std::unique_ptr<Descriptor> InferDescriptor(const CScript& script, const SigningProvider& provider)
3038
295k
{
3039
295k
    return InferScript(script, ParseScriptContext::TOP, provider);
3040
295k
}
3041
3042
uint256 CompatDescriptorHash(const Descriptor& desc)
3043
5.25k
{
3044
5.25k
    std::string desc_str = desc.ToString(/*compat_format=*/true);
3045
5.25k
    uint256 id;
3046
5.25k
    CSHA256().Write((unsigned char*)desc_str.data(), desc_str.size()).Finalize(id.begin());
3047
5.25k
    return id;
3048
5.25k
}
3049
3050
void DescriptorCache::CacheParentExtPubKey(uint32_t key_exp_pos, const CExtPubKey& xpub)
3051
20.5k
{
3052
20.5k
    m_parent_xpubs[key_exp_pos] = xpub;
3053
20.5k
}
3054
3055
void DescriptorCache::CacheDerivedExtPubKey(uint32_t key_exp_pos, uint32_t der_index, const CExtPubKey& xpub)
3056
72.5k
{
3057
72.5k
    auto& xpubs = m_derived_xpubs[key_exp_pos];
3058
72.5k
    xpubs[der_index] = xpub;
3059
72.5k
}
3060
3061
void DescriptorCache::CacheLastHardenedExtPubKey(uint32_t key_exp_pos, const CExtPubKey& xpub)
3062
15.3k
{
3063
15.3k
    m_last_hardened_xpubs[key_exp_pos] = xpub;
3064
15.3k
}
3065
3066
bool DescriptorCache::GetCachedParentExtPubKey(uint32_t key_exp_pos, CExtPubKey& xpub) const
3067
702k
{
3068
702k
    const auto& it = m_parent_xpubs.find(key_exp_pos);
3069
702k
    if (it == m_parent_xpubs.end()) return false;
3070
692k
    xpub = it->second;
3071
692k
    return true;
3072
702k
}
3073
3074
bool DescriptorCache::GetCachedDerivedExtPubKey(uint32_t key_exp_pos, uint32_t der_index, CExtPubKey& xpub) const
3075
749k
{
3076
749k
    const auto& key_exp_it = m_derived_xpubs.find(key_exp_pos);
3077
749k
    if (key_exp_it == m_derived_xpubs.end()) return false;
3078
52.5k
    const auto& der_it = key_exp_it->second.find(der_index);
3079
52.5k
    if (der_it == key_exp_it->second.end()) return false;
3080
4.48k
    xpub = der_it->second;
3081
4.48k
    return true;
3082
52.5k
}
3083
3084
bool DescriptorCache::GetCachedLastHardenedExtPubKey(uint32_t key_exp_pos, CExtPubKey& xpub) const
3085
9.76k
{
3086
9.76k
    const auto& it = m_last_hardened_xpubs.find(key_exp_pos);
3087
9.76k
    if (it == m_last_hardened_xpubs.end()) return false;
3088
5.52k
    xpub = it->second;
3089
5.52k
    return true;
3090
9.76k
}
3091
3092
DescriptorCache DescriptorCache::MergeAndDiff(const DescriptorCache& other)
3093
477k
{
3094
477k
    DescriptorCache diff;
3095
477k
    for (const auto& parent_xpub_pair : other.GetCachedParentExtPubKeys()) {
3096
5.59k
        CExtPubKey xpub;
3097
5.59k
        if (GetCachedParentExtPubKey(parent_xpub_pair.first, xpub)) {
3098
6
            if (xpub != parent_xpub_pair.second) {
3099
0
                throw std::runtime_error(std::string(__func__) + ": New cached parent xpub does not match already cached parent xpub");
3100
0
            }
3101
6
            continue;
3102
6
        }
3103
5.58k
        CacheParentExtPubKey(parent_xpub_pair.first, parent_xpub_pair.second);
3104
5.58k
        diff.CacheParentExtPubKey(parent_xpub_pair.first, parent_xpub_pair.second);
3105
5.58k
    }
3106
477k
    for (const auto& derived_xpub_map_pair : other.GetCachedDerivedExtPubKeys()) {
3107
24.0k
        for (const auto& derived_xpub_pair : derived_xpub_map_pair.second) {
3108
24.0k
            CExtPubKey xpub;
3109
24.0k
            if (GetCachedDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, xpub)) {
3110
0
                if (xpub != derived_xpub_pair.second) {
3111
0
                    throw std::runtime_error(std::string(__func__) + ": New cached derived xpub does not match already cached derived xpub");
3112
0
                }
3113
0
                continue;
3114
0
            }
3115
24.0k
            CacheDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, derived_xpub_pair.second);
3116
24.0k
            diff.CacheDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, derived_xpub_pair.second);
3117
24.0k
        }
3118
24.0k
    }
3119
477k
    for (const auto& lh_xpub_pair : other.GetCachedLastHardenedExtPubKeys()) {
3120
4.24k
        CExtPubKey xpub;
3121
4.24k
        if (GetCachedLastHardenedExtPubKey(lh_xpub_pair.first, xpub)) {
3122
0
            if (xpub != lh_xpub_pair.second) {
3123
0
                throw std::runtime_error(std::string(__func__) + ": New cached last hardened xpub does not match already cached last hardened xpub");
3124
0
            }
3125
0
            continue;
3126
0
        }
3127
4.24k
        CacheLastHardenedExtPubKey(lh_xpub_pair.first, lh_xpub_pair.second);
3128
4.24k
        diff.CacheLastHardenedExtPubKey(lh_xpub_pair.first, lh_xpub_pair.second);
3129
4.24k
    }
3130
477k
    return diff;
3131
477k
}
3132
3133
ExtPubKeyMap DescriptorCache::GetCachedParentExtPubKeys() const
3134
957k
{
3135
957k
    return m_parent_xpubs;
3136
957k
}
3137
3138
std::unordered_map<uint32_t, ExtPubKeyMap> DescriptorCache::GetCachedDerivedExtPubKeys() const
3139
957k
{
3140
957k
    return m_derived_xpubs;
3141
957k
}
3142
3143
ExtPubKeyMap DescriptorCache::GetCachedLastHardenedExtPubKeys() const
3144
956k
{
3145
956k
    return m_last_hardened_xpubs;
3146
956k
}