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