Coverage Report

Created: 2026-08-14 20:23

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