Coverage Report

Created: 2026-09-14 20:36

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