Coverage Report

Created: 2026-11-13 17:38

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