Coverage Report

Created: 2026-07-14 18:13

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