descriptor.cpp raw
1 // Copyright (c) 2018-2022 The Limenka 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 <hash.h>
8 #include <key_io.h>
9 #include <pubkey.h>
10 #include <script/miniscript.h>
11 #include <script/parsing.h>
12 #include <script/script.h>
13 #include <script/signingprovider.h>
14 #include <script/solver.h>
15 #include <uint256.h>
16
17 #include <common/args.h>
18 #include <span.h>
19 #include <util/bip32.h>
20 #include <util/check.h>
21 #include <util/strencodings.h>
22 #include <util/vector.h>
23
24 #include <algorithm>
25 #include <memory>
26 #include <numeric>
27 #include <optional>
28 #include <string>
29 #include <vector>
30
31 using util::Split;
32
33 namespace {
34
35 ////////////////////////////////////////////////////////////////////////////
36 // Checksum //
37 ////////////////////////////////////////////////////////////////////////////
38
39 // This section implements a checksum algorithm for descriptors with the
40 // following properties:
41 // * Mistakes in a descriptor string are measured in "symbol errors". The higher
42 // the number of symbol errors, the harder it is to detect:
43 // * An error substituting a character from 0123456789()[],'/*abcdefgh@:$%{} for
44 // another in that set always counts as 1 symbol error.
45 // * Note that hex encoded keys are covered by these characters. Xprvs and
46 // xpubs use other characters too, but already have their own checksum
47 // mechanism.
48 // * Function names like "multi()" use other characters, but mistakes in
49 // these would generally result in an unparsable descriptor.
50 // * A case error always counts as 1 symbol error.
51 // * Any other 1 character substitution error counts as 1 or 2 symbol errors.
52 // * Any 1 symbol error is always detected.
53 // * Any 2 or 3 symbol error in a descriptor of up to 49154 characters is always detected.
54 // * Any 4 symbol error in a descriptor of up to 507 characters is always detected.
55 // * Any 5 symbol error in a descriptor of up to 77 characters is always detected.
56 // * Is optimized to minimize the chance a 5 symbol error in a descriptor up to 387 characters is undetected
57 // * Random errors have a chance of 1 in 2**40 of being undetected.
58 //
59 // These properties are achieved by expanding every group of 3 (non checksum) characters into
60 // 4 GF(32) symbols, over which a cyclic code is defined.
61
62 /*
63 * Interprets c as 8 groups of 5 bits which are the coefficients of a degree 8 polynomial over GF(32),
64 * multiplies that polynomial by x, computes its remainder modulo a generator, and adds the constant term val.
65 *
66 * 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}.
67 * It is chosen to define an cyclic error detecting code which is selected by:
68 * - Starting from all BCH codes over GF(32) of degree 8 and below, which by construction guarantee detecting
69 * 3 errors in windows up to 19000 symbols.
70 * - Taking all those generators, and for degree 7 ones, extend them to degree 8 by adding all degree-1 factors.
71 * - Selecting just the set of generators that guarantee detecting 4 errors in a window of length 512.
72 * - Selecting one of those with best worst-case behavior for 5 errors in windows of length up to 512.
73 *
74 * The generator and the constants to implement it can be verified using this Sage code:
75 * B = GF(2) # Binary field
76 * BP.<b> = B[] # Polynomials over the binary field
77 * F_mod = b**5 + b**3 + 1
78 * F.<f> = GF(32, modulus=F_mod, repr='int') # GF(32) definition
79 * FP.<x> = F[] # Polynomials over GF(32)
80 * E_mod = x**3 + x + F.fetch_int(8)
81 * E.<e> = F.extension(E_mod) # Extension field definition
82 * alpha = e**2743 # Choice of an element in extension field
83 * for p in divisors(E.order() - 1): # Verify alpha has order 32767.
84 * assert((alpha**p == 1) == (p % 32767 == 0))
85 * G = lcm([(alpha**i).minpoly() for i in [1056,1057,1058]] + [x + 1])
86 * print(G) # Print out the generator
87 * for i in [1,2,4,8,16]: # Print out {1,2,4,8,16}*(G mod x^8), packed in hex integers.
88 * v = 0
89 * for coef in reversed((F.fetch_int(i)*(G % x**8)).coefficients(sparse=True)):
90 * v = v*32 + coef.integer_representation()
91 * print("0x%x" % v)
92 */
93 uint64_t PolyMod(uint64_t c, int val)
94 {
95 uint8_t c0 = c >> 35;
96 c = ((c & 0x7ffffffff) << 5) ^ val;
97 if (c0 & 1) c ^= 0xf5dee51989;
98 if (c0 & 2) c ^= 0xa9fdca3312;
99 if (c0 & 4) c ^= 0x1bab10e32d;
100 if (c0 & 8) c ^= 0x3706b1677a;
101 if (c0 & 16) c ^= 0x644d626ffd;
102 return c;
103 }
104
105 std::string DescriptorChecksum(const Span<const char>& span)
106 {
107 /** A character set designed such that:
108 * - The most common 'unprotected' descriptor characters (hex, keypaths) are in the first group of 32.
109 * - Case errors cause an offset that's a multiple of 32.
110 * - As many alphabetic characters are in the same group (while following the above restrictions).
111 *
112 * If p(x) gives the position of a character c in this character set, every group of 3 characters
113 * (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).
114 * This means that changes that only affect the lower 5 bits of the position, or only the higher 2 bits, will just
115 * affect a single symbol.
116 *
117 * As a result, within-group-of-32 errors count as 1 symbol, as do cross-group errors that don't affect
118 * the position within the groups.
119 */
120 static const std::string INPUT_CHARSET =
121 "0123456789()[],'/*abcdefgh@:$%{}"
122 "IJKLMNOPQRSTUVWXYZ&+-.;<=>?!^_|~"
123 "ijklmnopqrstuvwxyzABCDEFGH`#\"\\ ";
124
125 /** The character set for the checksum itself (same as bech32). */
126 static const std::string CHECKSUM_CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
127
128 uint64_t c = 1;
129 int cls = 0;
130 int clscount = 0;
131 for (auto ch : span) {
132 auto pos = INPUT_CHARSET.find(ch);
133 if (pos == std::string::npos) return "";
134 c = PolyMod(c, pos & 31); // Emit a symbol for the position inside the group, for every character.
135 cls = cls * 3 + (pos >> 5); // Accumulate the group numbers
136 if (++clscount == 3) {
137 // Emit an extra symbol representing the group numbers, for every 3 characters.
138 c = PolyMod(c, cls);
139 cls = 0;
140 clscount = 0;
141 }
142 }
143 if (clscount > 0) c = PolyMod(c, cls);
144 for (int j = 0; j < 8; ++j) c = PolyMod(c, 0); // Shift further to determine the checksum.
145 c ^= 1; // Prevent appending zeroes from not affecting the checksum.
146
147 std::string ret(8, ' ');
148 for (int j = 0; j < 8; ++j) ret[j] = CHECKSUM_CHARSET[(c >> (5 * (7 - j))) & 31];
149 return ret;
150 }
151
152 ////////////////////////////////////////////////////////////////////////////
153 // Internal representation //
154 ////////////////////////////////////////////////////////////////////////////
155
156 typedef std::vector<uint32_t> KeyPath;
157
158 /** Interface for public key objects in descriptors. */
159 struct PubkeyProvider
160 {
161 protected:
162 //! Index of this key expression in the descriptor
163 //! E.g. If this PubkeyProvider is key1 in multi(2, key1, key2, key3), then m_expr_index = 0
164 uint32_t m_expr_index;
165
166 public:
167 explicit PubkeyProvider(uint32_t exp_index) : m_expr_index(exp_index) {}
168
169 virtual ~PubkeyProvider() = default;
170
171 /** Compare two public keys represented by this provider.
172 * Used by the Miniscript descriptors to check for duplicate keys in the script.
173 */
174 bool operator<(PubkeyProvider& other) const {
175 CPubKey a, b;
176 SigningProvider dummy;
177 KeyOriginInfo dummy_info;
178
179 GetPubKey(0, dummy, a, dummy_info);
180 other.GetPubKey(0, dummy, b, dummy_info);
181
182 return a < b;
183 }
184
185 /** Derive a public key.
186 * read_cache is the cache to read keys from (if not nullptr)
187 * write_cache is the cache to write keys to (if not nullptr)
188 * Caches are not exclusive but this is not tested. Currently we use them exclusively
189 */
190 virtual bool GetPubKey(int pos, const SigningProvider& arg, CPubKey& key, KeyOriginInfo& info, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const = 0;
191
192 /** Whether this represent multiple public keys at different positions. */
193 virtual bool IsRange() const = 0;
194
195 /** Get the size of the generated public key(s) in bytes (33 or 65). */
196 virtual size_t GetSize() const = 0;
197
198 enum class StringType {
199 PUBLIC,
200 COMPAT // string calculation that mustn't change over time to stay compatible with previous software versions
201 };
202
203 /** Get the descriptor string form. */
204 virtual std::string ToString(StringType type=StringType::PUBLIC) const = 0;
205
206 /** Get the descriptor string form including private data (if available in arg). */
207 virtual bool ToPrivateString(const SigningProvider& arg, std::string& out) const = 0;
208
209 /** Get the descriptor string form with the xpub at the last hardened derivation,
210 * and always use h for hardened derivation.
211 */
212 virtual bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache = nullptr) const = 0;
213
214 /** Derive a private key, if private data is available in arg. */
215 virtual bool GetPrivKey(int pos, const SigningProvider& arg, CKey& key) const = 0;
216
217 /** Return the non-extended public key for this PubkeyProvider, if it has one. */
218 virtual std::optional<CPubKey> GetRootPubKey() const = 0;
219 /** Return the extended public key for this PubkeyProvider, if it has one. */
220 virtual std::optional<CExtPubKey> GetRootExtPubKey() const = 0;
221
222 /** Make a deep copy of this PubkeyProvider */
223 virtual std::unique_ptr<PubkeyProvider> Clone() const = 0;
224 };
225
226 class OriginPubkeyProvider final : public PubkeyProvider
227 {
228 KeyOriginInfo m_origin;
229 std::unique_ptr<PubkeyProvider> m_provider;
230 bool m_apostrophe;
231
232 std::string OriginString(StringType type, bool normalized=false) const
233 {
234 // If StringType==COMPAT, always use the apostrophe to stay compatible with previous versions
235 bool use_apostrophe = (!normalized && m_apostrophe) || type == StringType::COMPAT;
236 return HexStr(m_origin.fingerprint) + FormatHDKeypath(m_origin.path, use_apostrophe);
237 }
238
239 public:
240 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) {}
241 bool GetPubKey(int pos, const SigningProvider& arg, CPubKey& key, KeyOriginInfo& info, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
242 {
243 if (!m_provider->GetPubKey(pos, arg, key, info, read_cache, write_cache)) return false;
244 std::copy(std::begin(m_origin.fingerprint), std::end(m_origin.fingerprint), info.fingerprint);
245 info.path.insert(info.path.begin(), m_origin.path.begin(), m_origin.path.end());
246 return true;
247 }
248 bool IsRange() const override { return m_provider->IsRange(); }
249 size_t GetSize() const override { return m_provider->GetSize(); }
250 std::string ToString(StringType type) const override { return "[" + OriginString(type) + "]" + m_provider->ToString(type); }
251 bool ToPrivateString(const SigningProvider& arg, std::string& ret) const override
252 {
253 std::string sub;
254 if (!m_provider->ToPrivateString(arg, sub)) return false;
255 ret = "[" + OriginString(StringType::PUBLIC) + "]" + std::move(sub);
256 return true;
257 }
258 bool ToNormalizedString(const SigningProvider& arg, std::string& ret, const DescriptorCache* cache) const override
259 {
260 std::string sub;
261 if (!m_provider->ToNormalizedString(arg, sub, cache)) return false;
262 // If m_provider is a BIP32PubkeyProvider, we may get a string formatted like a OriginPubkeyProvider
263 // In that case, we need to strip out the leading square bracket and fingerprint from the substring,
264 // and append that to our own origin string.
265 if (sub[0] == '[') {
266 sub = sub.substr(9);
267 ret = "[" + OriginString(StringType::PUBLIC, /*normalized=*/true) + std::move(sub);
268 } else {
269 ret = "[" + OriginString(StringType::PUBLIC, /*normalized=*/true) + "]" + std::move(sub);
270 }
271 return true;
272 }
273 bool GetPrivKey(int pos, const SigningProvider& arg, CKey& key) const override
274 {
275 return m_provider->GetPrivKey(pos, arg, key);
276 }
277 std::optional<CPubKey> GetRootPubKey() const override
278 {
279 return m_provider->GetRootPubKey();
280 }
281 std::optional<CExtPubKey> GetRootExtPubKey() const override
282 {
283 return m_provider->GetRootExtPubKey();
284 }
285 std::unique_ptr<PubkeyProvider> Clone() const override
286 {
287 return std::make_unique<OriginPubkeyProvider>(m_expr_index, m_origin, m_provider->Clone(), m_apostrophe);
288 }
289 };
290
291 /** An object representing a parsed constant public key in a descriptor. */
292 class ConstPubkeyProvider final : public PubkeyProvider
293 {
294 CPubKey m_pubkey;
295 bool m_xonly;
296
297 public:
298 ConstPubkeyProvider(uint32_t exp_index, const CPubKey& pubkey, bool xonly) : PubkeyProvider(exp_index), m_pubkey(pubkey), m_xonly(xonly) {}
299 bool GetPubKey(int pos, const SigningProvider& arg, CPubKey& key, KeyOriginInfo& info, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
300 {
301 key = m_pubkey;
302 info.path.clear();
303 CKeyID keyid = m_pubkey.GetID();
304 std::copy(keyid.begin(), keyid.begin() + sizeof(info.fingerprint), info.fingerprint);
305 return true;
306 }
307 bool IsRange() const override { return false; }
308 size_t GetSize() const override { return m_pubkey.size(); }
309 std::string ToString(StringType type) const override { return m_xonly ? HexStr(m_pubkey).substr(2) : HexStr(m_pubkey); }
310 bool ToPrivateString(const SigningProvider& arg, std::string& ret) const override
311 {
312 CKey key;
313 if (!GetPrivKey(/*pos=*/0, arg, key)) return false;
314 ret = EncodeSecret(key);
315 return true;
316 }
317 bool ToNormalizedString(const SigningProvider& arg, std::string& ret, const DescriptorCache* cache) const override
318 {
319 ret = ToString(StringType::PUBLIC);
320 return true;
321 }
322 bool GetPrivKey(int pos, const SigningProvider& arg, CKey& key) const override
323 {
324 return m_xonly ? arg.GetKeyByXOnly(XOnlyPubKey(m_pubkey), key) :
325 arg.GetKey(m_pubkey.GetID(), key);
326 }
327 std::optional<CPubKey> GetRootPubKey() const override
328 {
329 return m_pubkey;
330 }
331 std::optional<CExtPubKey> GetRootExtPubKey() const override
332 {
333 return std::nullopt;
334 }
335 std::unique_ptr<PubkeyProvider> Clone() const override
336 {
337 return std::make_unique<ConstPubkeyProvider>(m_expr_index, m_pubkey, m_xonly);
338 }
339 };
340
341 enum class DeriveType {
342 NO,
343 UNHARDENED,
344 HARDENED,
345 };
346
347 /** An object representing a parsed extended public key in a descriptor. */
348 class BIP32PubkeyProvider final : public PubkeyProvider
349 {
350 // Root xpub, path, and final derivation step type being used, if any
351 CExtPubKey m_root_extkey;
352 KeyPath m_path;
353 DeriveType m_derive;
354 // Whether ' or h is used in harded derivation
355 bool m_apostrophe;
356
357 bool GetExtKey(const SigningProvider& arg, CExtKey& ret) const
358 {
359 CKey key;
360 if (!arg.GetKey(m_root_extkey.pubkey.GetID(), key)) return false;
361 ret.nDepth = m_root_extkey.nDepth;
362 std::copy(m_root_extkey.vchFingerprint, m_root_extkey.vchFingerprint + sizeof(ret.vchFingerprint), ret.vchFingerprint);
363 ret.nChild = m_root_extkey.nChild;
364 ret.chaincode = m_root_extkey.chaincode;
365 ret.key = key;
366 return true;
367 }
368
369 // Derives the last xprv
370 bool GetDerivedExtKey(const SigningProvider& arg, CExtKey& xprv, CExtKey& last_hardened) const
371 {
372 if (!GetExtKey(arg, xprv)) return false;
373 for (auto entry : m_path) {
374 if (!xprv.Derive(xprv, entry)) return false;
375 if (entry >> 31) {
376 last_hardened = xprv;
377 }
378 }
379 return true;
380 }
381
382 bool IsHardened() const
383 {
384 if (m_derive == DeriveType::HARDENED) return true;
385 for (auto entry : m_path) {
386 if (entry >> 31) return true;
387 }
388 return false;
389 }
390
391 public:
392 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) {}
393 bool IsRange() const override { return m_derive != DeriveType::NO; }
394 size_t GetSize() const override { return 33; }
395 bool GetPubKey(int pos, const SigningProvider& arg, CPubKey& key_out, KeyOriginInfo& final_info_out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
396 {
397 // Info of parent of the to be derived pubkey
398 KeyOriginInfo parent_info;
399 CKeyID keyid = m_root_extkey.pubkey.GetID();
400 std::copy(keyid.begin(), keyid.begin() + sizeof(parent_info.fingerprint), parent_info.fingerprint);
401 parent_info.path = m_path;
402
403 // Info of the derived key itself which is copied out upon successful completion
404 KeyOriginInfo final_info_out_tmp = parent_info;
405 if (m_derive == DeriveType::UNHARDENED) final_info_out_tmp.path.push_back((uint32_t)pos);
406 if (m_derive == DeriveType::HARDENED) final_info_out_tmp.path.push_back(((uint32_t)pos) | 0x80000000L);
407
408 // Derive keys or fetch them from cache
409 CExtPubKey final_extkey = m_root_extkey;
410 CExtPubKey parent_extkey = m_root_extkey;
411 CExtPubKey last_hardened_extkey;
412 bool der = true;
413 if (read_cache) {
414 if (!read_cache->GetCachedDerivedExtPubKey(m_expr_index, pos, final_extkey)) {
415 if (m_derive == DeriveType::HARDENED) return false;
416 // Try to get the derivation parent
417 if (!read_cache->GetCachedParentExtPubKey(m_expr_index, parent_extkey)) return false;
418 final_extkey = parent_extkey;
419 if (m_derive == DeriveType::UNHARDENED) der = parent_extkey.Derive(final_extkey, pos);
420 }
421 } else if (IsHardened()) {
422 CExtKey xprv;
423 CExtKey lh_xprv;
424 if (!GetDerivedExtKey(arg, xprv, lh_xprv)) return false;
425 parent_extkey = xprv.Neuter();
426 if (m_derive == DeriveType::UNHARDENED) der = xprv.Derive(xprv, pos);
427 if (m_derive == DeriveType::HARDENED) der = xprv.Derive(xprv, pos | 0x80000000UL);
428 final_extkey = xprv.Neuter();
429 if (lh_xprv.key.IsValid()) {
430 last_hardened_extkey = lh_xprv.Neuter();
431 }
432 } else {
433 for (auto entry : m_path) {
434 if (!parent_extkey.Derive(parent_extkey, entry)) return false;
435 }
436 final_extkey = parent_extkey;
437 if (m_derive == DeriveType::UNHARDENED) der = parent_extkey.Derive(final_extkey, pos);
438 assert(m_derive != DeriveType::HARDENED);
439 }
440 if (!der) return false;
441
442 final_info_out = final_info_out_tmp;
443 key_out = final_extkey.pubkey;
444
445 if (write_cache) {
446 // Only cache parent if there is any unhardened derivation
447 if (m_derive != DeriveType::HARDENED) {
448 write_cache->CacheParentExtPubKey(m_expr_index, parent_extkey);
449 // Cache last hardened xpub if we have it
450 if (last_hardened_extkey.pubkey.IsValid()) {
451 write_cache->CacheLastHardenedExtPubKey(m_expr_index, last_hardened_extkey);
452 }
453 } else if (final_info_out.path.size() > 0) {
454 write_cache->CacheDerivedExtPubKey(m_expr_index, pos, final_extkey);
455 }
456 }
457
458 return true;
459 }
460 std::string ToString(StringType type, bool normalized) const
461 {
462 // If StringType==COMPAT, always use the apostrophe to stay compatible with previous versions
463 const bool use_apostrophe = (!normalized && m_apostrophe) || type == StringType::COMPAT;
464 std::string ret = EncodeExtPubKey(m_root_extkey) + FormatHDKeypath(m_path, /*apostrophe=*/use_apostrophe);
465 if (IsRange()) {
466 ret += "/*";
467 if (m_derive == DeriveType::HARDENED) ret += use_apostrophe ? '\'' : 'h';
468 }
469 return ret;
470 }
471 std::string ToString(StringType type=StringType::PUBLIC) const override
472 {
473 return ToString(type, /*normalized=*/false);
474 }
475 bool ToPrivateString(const SigningProvider& arg, std::string& out) const override
476 {
477 CExtKey key;
478 if (!GetExtKey(arg, key)) return false;
479 out = EncodeExtKey(key) + FormatHDKeypath(m_path, /*apostrophe=*/m_apostrophe);
480 if (IsRange()) {
481 out += "/*";
482 if (m_derive == DeriveType::HARDENED) out += m_apostrophe ? '\'' : 'h';
483 }
484 return true;
485 }
486 bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache) const override
487 {
488 if (m_derive == DeriveType::HARDENED) {
489 out = ToString(StringType::PUBLIC, /*normalized=*/true);
490
491 return true;
492 }
493 // Step backwards to find the last hardened step in the path
494 int i = (int)m_path.size() - 1;
495 for (; i >= 0; --i) {
496 if (m_path.at(i) >> 31) {
497 break;
498 }
499 }
500 // Either no derivation or all unhardened derivation
501 if (i == -1) {
502 out = ToString();
503 return true;
504 }
505 // Get the path to the last hardened stup
506 KeyOriginInfo origin;
507 int k = 0;
508 for (; k <= i; ++k) {
509 // Add to the path
510 origin.path.push_back(m_path.at(k));
511 }
512 // Build the remaining path
513 KeyPath end_path;
514 for (; k < (int)m_path.size(); ++k) {
515 end_path.push_back(m_path.at(k));
516 }
517 // Get the fingerprint
518 CKeyID id = m_root_extkey.pubkey.GetID();
519 std::copy(id.begin(), id.begin() + 4, origin.fingerprint);
520
521 CExtPubKey xpub;
522 CExtKey lh_xprv;
523 // If we have the cache, just get the parent xpub
524 if (cache != nullptr) {
525 cache->GetCachedLastHardenedExtPubKey(m_expr_index, xpub);
526 }
527 if (!xpub.pubkey.IsValid()) {
528 // Cache miss, or nor cache, or need privkey
529 CExtKey xprv;
530 if (!GetDerivedExtKey(arg, xprv, lh_xprv)) return false;
531 xpub = lh_xprv.Neuter();
532 }
533 assert(xpub.pubkey.IsValid());
534
535 // Build the string
536 std::string origin_str = HexStr(origin.fingerprint) + FormatHDKeypath(origin.path);
537 out = "[" + origin_str + "]" + EncodeExtPubKey(xpub) + FormatHDKeypath(end_path);
538 if (IsRange()) {
539 out += "/*";
540 assert(m_derive == DeriveType::UNHARDENED);
541 }
542 return true;
543 }
544 bool GetPrivKey(int pos, const SigningProvider& arg, CKey& key) const override
545 {
546 CExtKey extkey;
547 CExtKey dummy;
548 if (!GetDerivedExtKey(arg, extkey, dummy)) return false;
549 if (m_derive == DeriveType::UNHARDENED && !extkey.Derive(extkey, pos)) return false;
550 if (m_derive == DeriveType::HARDENED && !extkey.Derive(extkey, pos | 0x80000000UL)) return false;
551 key = extkey.key;
552 return true;
553 }
554 std::optional<CPubKey> GetRootPubKey() const override
555 {
556 return std::nullopt;
557 }
558 std::optional<CExtPubKey> GetRootExtPubKey() const override
559 {
560 return m_root_extkey;
561 }
562 std::unique_ptr<PubkeyProvider> Clone() const override
563 {
564 return std::make_unique<BIP32PubkeyProvider>(m_expr_index, m_root_extkey, m_path, m_derive, m_apostrophe);
565 }
566 };
567
568 /** Base class for all Descriptor implementations. */
569 class DescriptorImpl : public Descriptor
570 {
571 protected:
572 //! Public key arguments for this descriptor (size 1 for PK, PKH, WPKH; any size for WSH and Multisig).
573 const std::vector<std::unique_ptr<PubkeyProvider>> m_pubkey_args;
574 //! The string name of the descriptor function.
575 const std::string m_name;
576
577 //! The sub-descriptor arguments (empty for everything but SH and WSH).
578 //! In doc/descriptors.m this is referred to as SCRIPT expressions sh(SCRIPT)
579 //! and wsh(SCRIPT), and distinct from KEY expressions and ADDR expressions.
580 //! Subdescriptors can only ever generate a single script.
581 const std::vector<std::unique_ptr<DescriptorImpl>> m_subdescriptor_args;
582
583 //! Return a serialization of anything except pubkey and script arguments, to be prepended to those.
584 virtual std::string ToStringExtra() const { return ""; }
585
586 /** A helper function to construct the scripts for this descriptor.
587 *
588 * This function is invoked once by ExpandHelper.
589 *
590 * @param pubkeys The evaluations of the m_pubkey_args field.
591 * @param scripts The evaluations of m_subdescriptor_args (one for each m_subdescriptor_args element).
592 * @param out A FlatSigningProvider to put scripts or public keys in that are necessary to the solver.
593 * The origin info of the provided pubkeys is automatically added.
594 * @return A vector with scriptPubKeys for this descriptor.
595 */
596 virtual std::vector<CScript> MakeScripts(const std::vector<CPubKey>& pubkeys, Span<const CScript> scripts, FlatSigningProvider& out) const = 0;
597
598 public:
599 DescriptorImpl(std::vector<std::unique_ptr<PubkeyProvider>> pubkeys, const std::string& name) : m_pubkey_args(std::move(pubkeys)), m_name(name), m_subdescriptor_args() {}
600 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))) {}
601 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)) {}
602
603 enum class StringType
604 {
605 PUBLIC,
606 PRIVATE,
607 NORMALIZED,
608 COMPAT, // string calculation that mustn't change over time to stay compatible with previous software versions
609 };
610
611 // NOLINTNEXTLINE(misc-no-recursion)
612 bool IsSolvable() const override
613 {
614 for (const auto& arg : m_subdescriptor_args) {
615 if (!arg->IsSolvable()) return false;
616 }
617 return true;
618 }
619
620 // NOLINTNEXTLINE(misc-no-recursion)
621 bool IsRange() const final
622 {
623 for (const auto& pubkey : m_pubkey_args) {
624 if (pubkey->IsRange()) return true;
625 }
626 for (const auto& arg : m_subdescriptor_args) {
627 if (arg->IsRange()) return true;
628 }
629 return false;
630 }
631
632 // NOLINTNEXTLINE(misc-no-recursion)
633 virtual bool ToStringSubScriptHelper(const SigningProvider* arg, std::string& ret, const StringType type, const DescriptorCache* cache = nullptr) const
634 {
635 size_t pos = 0;
636 for (const auto& scriptarg : m_subdescriptor_args) {
637 if (pos++) ret += ",";
638 std::string tmp;
639 if (!scriptarg->ToStringHelper(arg, tmp, type, cache)) return false;
640 ret += tmp;
641 }
642 return true;
643 }
644
645 // NOLINTNEXTLINE(misc-no-recursion)
646 virtual bool ToStringHelper(const SigningProvider* arg, std::string& out, const StringType type, const DescriptorCache* cache = nullptr) const
647 {
648 std::string extra = ToStringExtra();
649 size_t pos = extra.size() > 0 ? 1 : 0;
650 std::string ret = m_name + "(" + extra;
651 for (const auto& pubkey : m_pubkey_args) {
652 if (pos++) ret += ",";
653 std::string tmp;
654 switch (type) {
655 case StringType::NORMALIZED:
656 if (!pubkey->ToNormalizedString(*arg, tmp, cache)) return false;
657 break;
658 case StringType::PRIVATE:
659 if (!pubkey->ToPrivateString(*arg, tmp)) return false;
660 break;
661 case StringType::PUBLIC:
662 tmp = pubkey->ToString();
663 break;
664 case StringType::COMPAT:
665 tmp = pubkey->ToString(PubkeyProvider::StringType::COMPAT);
666 break;
667 }
668 ret += tmp;
669 }
670 std::string subscript;
671 if (!ToStringSubScriptHelper(arg, subscript, type, cache)) return false;
672 if (pos && subscript.size()) ret += ',';
673 out = std::move(ret) + std::move(subscript) + ")";
674 return true;
675 }
676
677 std::string ToString(bool compat_format) const final
678 {
679 std::string ret;
680 ToStringHelper(nullptr, ret, compat_format ? StringType::COMPAT : StringType::PUBLIC);
681 return AddChecksum(ret);
682 }
683
684 bool ToPrivateString(const SigningProvider& arg, std::string& out) const override
685 {
686 bool ret = ToStringHelper(&arg, out, StringType::PRIVATE);
687 out = AddChecksum(out);
688 return ret;
689 }
690
691 bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache) const override final
692 {
693 bool ret = ToStringHelper(&arg, out, StringType::NORMALIZED, cache);
694 out = AddChecksum(out);
695 return ret;
696 }
697
698 // NOLINTNEXTLINE(misc-no-recursion)
699 bool ExpandHelper(int pos, const SigningProvider& arg, const DescriptorCache* read_cache, std::vector<CScript>& output_scripts, FlatSigningProvider& out, DescriptorCache* write_cache) const
700 {
701 std::vector<std::pair<CPubKey, KeyOriginInfo>> entries;
702 entries.reserve(m_pubkey_args.size());
703
704 // Construct temporary data in `entries`, `subscripts`, and `subprovider` to avoid producing output in case of failure.
705 for (const auto& p : m_pubkey_args) {
706 entries.emplace_back();
707 if (!p->GetPubKey(pos, arg, entries.back().first, entries.back().second, read_cache, write_cache)) return false;
708 }
709 std::vector<CScript> subscripts;
710 FlatSigningProvider subprovider;
711 for (const auto& subarg : m_subdescriptor_args) {
712 std::vector<CScript> outscripts;
713 if (!subarg->ExpandHelper(pos, arg, read_cache, outscripts, subprovider, write_cache)) return false;
714 assert(outscripts.size() == 1);
715 subscripts.emplace_back(std::move(outscripts[0]));
716 }
717 out.Merge(std::move(subprovider));
718
719 std::vector<CPubKey> pubkeys;
720 pubkeys.reserve(entries.size());
721 for (auto& entry : entries) {
722 pubkeys.push_back(entry.first);
723 out.origins.emplace(entry.first.GetID(), std::make_pair<CPubKey, KeyOriginInfo>(CPubKey(entry.first), std::move(entry.second)));
724 }
725
726 output_scripts = MakeScripts(pubkeys, Span{subscripts}, out);
727 return true;
728 }
729
730 bool Expand(int pos, const SigningProvider& provider, std::vector<CScript>& output_scripts, FlatSigningProvider& out, DescriptorCache* write_cache = nullptr) const final
731 {
732 return ExpandHelper(pos, provider, nullptr, output_scripts, out, write_cache);
733 }
734
735 bool ExpandFromCache(int pos, const DescriptorCache& read_cache, std::vector<CScript>& output_scripts, FlatSigningProvider& out) const final
736 {
737 return ExpandHelper(pos, DUMMY_SIGNING_PROVIDER, &read_cache, output_scripts, out, nullptr);
738 }
739
740 // NOLINTNEXTLINE(misc-no-recursion)
741 void ExpandPrivate(int pos, const SigningProvider& provider, FlatSigningProvider& out) const final
742 {
743 for (const auto& p : m_pubkey_args) {
744 CKey key;
745 if (!p->GetPrivKey(pos, provider, key)) continue;
746 out.keys.emplace(key.GetPubKey().GetID(), key);
747 }
748 for (const auto& arg : m_subdescriptor_args) {
749 arg->ExpandPrivate(pos, provider, out);
750 }
751 }
752
753 std::optional<OutputType> GetOutputType() const override { return std::nullopt; }
754
755 std::optional<int64_t> ScriptSize() const override { return {}; }
756
757 /** A helper for MaxSatisfactionWeight.
758 *
759 * @param use_max_sig Whether to assume ECDSA signatures will have a high-r.
760 * @return The maximum size of the satisfaction in raw bytes (with no witness meaning).
761 */
762 virtual std::optional<int64_t> MaxSatSize(bool use_max_sig) const { return {}; }
763
764 std::optional<int64_t> MaxSatisfactionWeight(bool) const override { return {}; }
765
766 std::optional<int64_t> MaxSatisfactionElems() const override { return {}; }
767
768 // NOLINTNEXTLINE(misc-no-recursion)
769 void GetPubKeys(std::set<CPubKey>& pubkeys, std::set<CExtPubKey>& ext_pubs) const override
770 {
771 for (const auto& p : m_pubkey_args) {
772 std::optional<CPubKey> pub = p->GetRootPubKey();
773 if (pub) pubkeys.insert(*pub);
774 std::optional<CExtPubKey> ext_pub = p->GetRootExtPubKey();
775 if (ext_pub) ext_pubs.insert(*ext_pub);
776 }
777 for (const auto& arg : m_subdescriptor_args) {
778 arg->GetPubKeys(pubkeys, ext_pubs);
779 }
780 }
781
782 virtual std::unique_ptr<DescriptorImpl> Clone() const = 0;
783 };
784
785 /** A parsed addr(A) descriptor. */
786 class AddressDescriptor final : public DescriptorImpl
787 {
788 const CTxDestination m_destination;
789 protected:
790 std::string ToStringExtra() const override { return EncodeDestination(m_destination); }
791 std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, Span<const CScript>, FlatSigningProvider&) const override { return Vector(GetScriptForDestination(m_destination)); }
792 public:
793 AddressDescriptor(CTxDestination destination) : DescriptorImpl({}, "addr"), m_destination(std::move(destination)) {}
794 bool IsSolvable() const final { return false; }
795
796 std::optional<OutputType> GetOutputType() const override
797 {
798 return OutputTypeFromDestination(m_destination);
799 }
800 bool IsSingleType() const final { return true; }
801 bool ToPrivateString(const SigningProvider& arg, std::string& out) const final { return false; }
802
803 std::optional<int64_t> ScriptSize() const override { return GetScriptForDestination(m_destination).size(); }
804 std::unique_ptr<DescriptorImpl> Clone() const override
805 {
806 return std::make_unique<AddressDescriptor>(m_destination);
807 }
808 };
809
810 /** A parsed raw(H) descriptor. */
811 class RawDescriptor final : public DescriptorImpl
812 {
813 const CScript m_script;
814 protected:
815 std::string ToStringExtra() const override { return HexStr(m_script); }
816 std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, Span<const CScript>, FlatSigningProvider&) const override { return Vector(m_script); }
817 public:
818 RawDescriptor(CScript script) : DescriptorImpl({}, "raw"), m_script(std::move(script)) {}
819 bool IsSolvable() const final { return false; }
820
821 std::optional<OutputType> GetOutputType() const override
822 {
823 CTxDestination dest;
824 ExtractDestination(m_script, dest);
825 return OutputTypeFromDestination(dest);
826 }
827 bool IsSingleType() const final { return true; }
828 bool ToPrivateString(const SigningProvider& arg, std::string& out) const final { return false; }
829
830 std::optional<int64_t> ScriptSize() const override { return m_script.size(); }
831
832 std::unique_ptr<DescriptorImpl> Clone() const override
833 {
834 return std::make_unique<RawDescriptor>(m_script);
835 }
836 };
837
838 /** A parsed pk(P) descriptor. */
839 class PKDescriptor final : public DescriptorImpl
840 {
841 private:
842 const bool m_xonly;
843 protected:
844 std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript>, FlatSigningProvider& out) const override
845 {
846 CKeyID id = keys[0].GetID();
847 out.pubkeys.emplace(id, keys[0]);
848
849 if (m_xonly) {
850 CScript script = CScript() << ToByteVector(XOnlyPubKey(keys[0])) << OP_CHECKSIG;
851 return Vector(std::move(script));
852 } else {
853 return Vector(GetScriptForRawPubKey(keys[0]));
854 }
855 }
856 public:
857 PKDescriptor(std::unique_ptr<PubkeyProvider> prov, bool xonly = false) : DescriptorImpl(Vector(std::move(prov)), "pk"), m_xonly(xonly) {}
858 bool IsSingleType() const final { return true; }
859
860 std::optional<int64_t> ScriptSize() const override {
861 return 1 + (m_xonly ? 32 : m_pubkey_args[0]->GetSize()) + 1;
862 }
863
864 std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
865 const auto ecdsa_sig_size = use_max_sig ? 72 : 71;
866 return 1 + (m_xonly ? 65 : ecdsa_sig_size);
867 }
868
869 std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
870 return *MaxSatSize(use_max_sig) * WITNESS_SCALE_FACTOR;
871 }
872
873 std::optional<int64_t> MaxSatisfactionElems() const override { return 1; }
874
875 std::unique_ptr<DescriptorImpl> Clone() const override
876 {
877 return std::make_unique<PKDescriptor>(m_pubkey_args.at(0)->Clone(), m_xonly);
878 }
879 };
880
881 /** A parsed pkh(P) descriptor. */
882 class PKHDescriptor final : public DescriptorImpl
883 {
884 protected:
885 std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript>, FlatSigningProvider& out) const override
886 {
887 CKeyID id = keys[0].GetID();
888 out.pubkeys.emplace(id, keys[0]);
889 return Vector(GetScriptForDestination(PKHash(id)));
890 }
891 public:
892 PKHDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "pkh") {}
893 std::optional<OutputType> GetOutputType() const override { return OutputType::LEGACY; }
894 bool IsSingleType() const final { return true; }
895
896 std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 1 + 20 + 1 + 1; }
897
898 std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
899 const auto sig_size = use_max_sig ? 72 : 71;
900 return 1 + sig_size + 1 + m_pubkey_args[0]->GetSize();
901 }
902
903 std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
904 return *MaxSatSize(use_max_sig) * WITNESS_SCALE_FACTOR;
905 }
906
907 std::optional<int64_t> MaxSatisfactionElems() const override { return 2; }
908
909 std::unique_ptr<DescriptorImpl> Clone() const override
910 {
911 return std::make_unique<PKHDescriptor>(m_pubkey_args.at(0)->Clone());
912 }
913 };
914
915 /** A parsed wpkh(P) descriptor. */
916 class WPKHDescriptor final : public DescriptorImpl
917 {
918 protected:
919 std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript>, FlatSigningProvider& out) const override
920 {
921 CKeyID id = keys[0].GetID();
922 out.pubkeys.emplace(id, keys[0]);
923 return Vector(GetScriptForDestination(WitnessV0KeyHash(id)));
924 }
925 public:
926 WPKHDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "wpkh") {}
927 std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32; }
928 bool IsSingleType() const final { return true; }
929
930 std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 20; }
931
932 std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
933 const auto sig_size = use_max_sig ? 72 : 71;
934 return (1 + sig_size + 1 + 33);
935 }
936
937 std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
938 return MaxSatSize(use_max_sig);
939 }
940
941 std::optional<int64_t> MaxSatisfactionElems() const override { return 2; }
942
943 std::unique_ptr<DescriptorImpl> Clone() const override
944 {
945 return std::make_unique<WPKHDescriptor>(m_pubkey_args.at(0)->Clone());
946 }
947 };
948
949 /** A parsed spk(P) descriptor. */
950 class SPKDescriptor final : public DescriptorImpl
951 {
952 protected:
953 std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript>, FlatSigningProvider& out) const override
954 {
955 XOnlyPubKey xpk(keys[0]);
956 if (!xpk.IsFullyValid()) return {};
957 WitnessV3SpkHash hash(xpk);
958 out.spk_keys[uint256(hash)] = xpk;
959 return Vector(GetScriptForDestination(hash));
960 }
961 public:
962 SPKDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "spk") {}
963 std::optional<OutputType> GetOutputType() const override { return OutputType::P2SPKH; }
964 bool IsSingleType() const final { return true; }
965
966 std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
967
968 std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
969 return 1 + (use_max_sig ? 65 : 64) + 1 + 32;
970 }
971
972 std::optional<int64_t> MaxSatisfactionElems() const override { return 2; }
973
974 std::unique_ptr<DescriptorImpl> Clone() const override
975 {
976 return std::make_unique<SPKDescriptor>(m_pubkey_args.at(0)->Clone());
977 }
978 };
979
980 /** A parsed combo(P) descriptor. */
981 class ComboDescriptor final : public DescriptorImpl
982 {
983 protected:
984 std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript>, FlatSigningProvider& out) const override
985 {
986 std::vector<CScript> ret;
987 CKeyID id = keys[0].GetID();
988 out.pubkeys.emplace(id, keys[0]);
989 ret.emplace_back(GetScriptForRawPubKey(keys[0])); // P2PK
990 ret.emplace_back(GetScriptForDestination(PKHash(id))); // P2PKH
991 if (keys[0].IsCompressed()) {
992 CScript p2wpkh = GetScriptForDestination(WitnessV0KeyHash(id));
993 out.scripts.emplace(CScriptID(p2wpkh), p2wpkh);
994 ret.emplace_back(p2wpkh);
995 ret.emplace_back(GetScriptForDestination(ScriptHash(p2wpkh))); // P2SH-P2WPKH
996 }
997 return ret;
998 }
999 public:
1000 ComboDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "combo") {}
1001 bool IsSingleType() const final { return false; }
1002 std::unique_ptr<DescriptorImpl> Clone() const override
1003 {
1004 return std::make_unique<ComboDescriptor>(m_pubkey_args.at(0)->Clone());
1005 }
1006 };
1007
1008 /** A parsed multi(...) or sortedmulti(...) descriptor */
1009 class MultisigDescriptor final : public DescriptorImpl
1010 {
1011 const int m_threshold;
1012 const bool m_sorted;
1013 protected:
1014 std::string ToStringExtra() const override { return strprintf("%i", m_threshold); }
1015 std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript>, FlatSigningProvider&) const override {
1016 if (m_sorted) {
1017 std::vector<CPubKey> sorted_keys(keys);
1018 std::sort(sorted_keys.begin(), sorted_keys.end());
1019 return Vector(GetScriptForMultisig(m_threshold, sorted_keys));
1020 }
1021 return Vector(GetScriptForMultisig(m_threshold, keys));
1022 }
1023 public:
1024 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) {}
1025 bool IsSingleType() const final { return true; }
1026
1027 std::optional<int64_t> ScriptSize() const override {
1028 const auto n_keys = m_pubkey_args.size();
1029 auto op = [](int64_t acc, const std::unique_ptr<PubkeyProvider>& pk) { return acc + 1 + pk->GetSize();};
1030 const auto pubkeys_size{std::accumulate(m_pubkey_args.begin(), m_pubkey_args.end(), int64_t{0}, op)};
1031 return 1 + BuildScript(n_keys).size() + BuildScript(m_threshold).size() + pubkeys_size;
1032 }
1033
1034 std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
1035 const auto sig_size = use_max_sig ? 72 : 71;
1036 return (1 + (1 + sig_size) * m_threshold);
1037 }
1038
1039 std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
1040 return *MaxSatSize(use_max_sig) * WITNESS_SCALE_FACTOR;
1041 }
1042
1043 std::optional<int64_t> MaxSatisfactionElems() const override { return 1 + m_threshold; }
1044
1045 std::unique_ptr<DescriptorImpl> Clone() const override
1046 {
1047 std::vector<std::unique_ptr<PubkeyProvider>> providers;
1048 providers.reserve(m_pubkey_args.size());
1049 std::transform(m_pubkey_args.begin(), m_pubkey_args.end(), providers.begin(), [](const std::unique_ptr<PubkeyProvider>& p) { return p->Clone(); });
1050 return std::make_unique<MultisigDescriptor>(m_threshold, std::move(providers), m_sorted);
1051 }
1052 };
1053
1054 /** A parsed (sorted)multi_a(...) descriptor. Always uses x-only pubkeys. */
1055 class MultiADescriptor final : public DescriptorImpl
1056 {
1057 const int m_threshold;
1058 const bool m_sorted;
1059 protected:
1060 std::string ToStringExtra() const override { return strprintf("%i", m_threshold); }
1061 std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript>, FlatSigningProvider&) const override {
1062 CScript ret;
1063 std::vector<XOnlyPubKey> xkeys;
1064 xkeys.reserve(keys.size());
1065 for (const auto& key : keys) xkeys.emplace_back(key);
1066 if (m_sorted) std::sort(xkeys.begin(), xkeys.end());
1067 ret << ToByteVector(xkeys[0]) << OP_CHECKSIG;
1068 for (size_t i = 1; i < keys.size(); ++i) {
1069 ret << ToByteVector(xkeys[i]) << OP_CHECKSIGADD;
1070 }
1071 ret << m_threshold << OP_NUMEQUAL;
1072 return Vector(std::move(ret));
1073 }
1074 public:
1075 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) {}
1076 bool IsSingleType() const final { return true; }
1077
1078 std::optional<int64_t> ScriptSize() const override {
1079 const auto n_keys = m_pubkey_args.size();
1080 return (1 + 32 + 1) * n_keys + BuildScript(m_threshold).size() + 1;
1081 }
1082
1083 std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
1084 return (1 + 65) * m_threshold + (m_pubkey_args.size() - m_threshold);
1085 }
1086
1087 std::optional<int64_t> MaxSatisfactionElems() const override { return m_pubkey_args.size(); }
1088
1089 std::unique_ptr<DescriptorImpl> Clone() const override
1090 {
1091 std::vector<std::unique_ptr<PubkeyProvider>> providers;
1092 providers.reserve(m_pubkey_args.size());
1093 for (const auto& arg : m_pubkey_args) {
1094 providers.push_back(arg->Clone());
1095 }
1096 return std::make_unique<MultiADescriptor>(m_threshold, std::move(providers), m_sorted);
1097 }
1098 };
1099
1100 /** A parsed sh(...) descriptor. */
1101 class SHDescriptor final : public DescriptorImpl
1102 {
1103 protected:
1104 std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, Span<const CScript> scripts, FlatSigningProvider& out) const override
1105 {
1106 auto ret = Vector(GetScriptForDestination(ScriptHash(scripts[0])));
1107 if (ret.size()) out.scripts.emplace(CScriptID(scripts[0]), scripts[0]);
1108 return ret;
1109 }
1110
1111 bool IsSegwit() const { return m_subdescriptor_args[0]->GetOutputType() == OutputType::BECH32; }
1112
1113 public:
1114 SHDescriptor(std::unique_ptr<DescriptorImpl> desc) : DescriptorImpl({}, std::move(desc), "sh") {}
1115
1116 std::optional<OutputType> GetOutputType() const override
1117 {
1118 assert(m_subdescriptor_args.size() == 1);
1119 if (IsSegwit()) return OutputType::P2SH_SEGWIT;
1120 return OutputType::LEGACY;
1121 }
1122 bool IsSingleType() const final { return true; }
1123
1124 std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 20 + 1; }
1125
1126 std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
1127 if (const auto sat_size = m_subdescriptor_args[0]->MaxSatSize(use_max_sig)) {
1128 if (const auto subscript_size = m_subdescriptor_args[0]->ScriptSize()) {
1129 // The subscript is never witness data.
1130 const auto subscript_weight = (1 + *subscript_size) * WITNESS_SCALE_FACTOR;
1131 // The weight depends on whether the inner descriptor is satisfied using the witness stack.
1132 if (IsSegwit()) return subscript_weight + *sat_size;
1133 return subscript_weight + *sat_size * WITNESS_SCALE_FACTOR;
1134 }
1135 }
1136 return {};
1137 }
1138
1139 std::optional<int64_t> MaxSatisfactionElems() const override {
1140 if (const auto sub_elems = m_subdescriptor_args[0]->MaxSatisfactionElems()) return 1 + *sub_elems;
1141 return {};
1142 }
1143
1144 std::unique_ptr<DescriptorImpl> Clone() const override
1145 {
1146 return std::make_unique<SHDescriptor>(m_subdescriptor_args.at(0)->Clone());
1147 }
1148 };
1149
1150 /** A parsed wsh(...) descriptor. */
1151 class WSHDescriptor final : public DescriptorImpl
1152 {
1153 protected:
1154 std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, Span<const CScript> scripts, FlatSigningProvider& out) const override
1155 {
1156 auto ret = Vector(GetScriptForDestination(WitnessV0ScriptHash(scripts[0])));
1157 if (ret.size()) out.scripts.emplace(CScriptID(scripts[0]), scripts[0]);
1158 return ret;
1159 }
1160 public:
1161 WSHDescriptor(std::unique_ptr<DescriptorImpl> desc) : DescriptorImpl({}, std::move(desc), "wsh") {}
1162 std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32; }
1163 bool IsSingleType() const final { return true; }
1164
1165 std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
1166
1167 std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
1168 if (const auto sat_size = m_subdescriptor_args[0]->MaxSatSize(use_max_sig)) {
1169 if (const auto subscript_size = m_subdescriptor_args[0]->ScriptSize()) {
1170 return GetSizeOfCompactSize(*subscript_size) + *subscript_size + *sat_size;
1171 }
1172 }
1173 return {};
1174 }
1175
1176 std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
1177 return MaxSatSize(use_max_sig);
1178 }
1179
1180 std::optional<int64_t> MaxSatisfactionElems() const override {
1181 if (const auto sub_elems = m_subdescriptor_args[0]->MaxSatisfactionElems()) return 1 + *sub_elems;
1182 return {};
1183 }
1184
1185 std::unique_ptr<DescriptorImpl> Clone() const override
1186 {
1187 return std::make_unique<WSHDescriptor>(m_subdescriptor_args.at(0)->Clone());
1188 }
1189 };
1190
1191 /** A parsed tr(...) descriptor. */
1192 class TRDescriptor final : public DescriptorImpl
1193 {
1194 std::vector<int> m_depths;
1195 protected:
1196 std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript> scripts, FlatSigningProvider& out) const override
1197 {
1198 TaprootBuilder builder;
1199 assert(m_depths.size() == scripts.size());
1200 for (size_t pos = 0; pos < m_depths.size(); ++pos) {
1201 builder.Add(m_depths[pos], scripts[pos], TAPROOT_LEAF_TAPSCRIPT);
1202 }
1203 if (!builder.IsComplete()) return {};
1204 assert(keys.size() == 1);
1205 XOnlyPubKey xpk(keys[0]);
1206 if (!xpk.IsFullyValid()) return {};
1207 builder.Finalize(xpk);
1208 WitnessV1Taproot output = builder.GetOutput();
1209 out.tr_trees[output] = builder;
1210 out.pubkeys.emplace(keys[0].GetID(), keys[0]);
1211 return Vector(GetScriptForDestination(output));
1212 }
1213 bool ToStringSubScriptHelper(const SigningProvider* arg, std::string& ret, const StringType type, const DescriptorCache* cache = nullptr) const override
1214 {
1215 if (m_depths.empty()) return true;
1216 std::vector<bool> path;
1217 for (size_t pos = 0; pos < m_depths.size(); ++pos) {
1218 if (pos) ret += ',';
1219 while ((int)path.size() <= m_depths[pos]) {
1220 if (path.size()) ret += '{';
1221 path.push_back(false);
1222 }
1223 std::string tmp;
1224 if (!m_subdescriptor_args[pos]->ToStringHelper(arg, tmp, type, cache)) return false;
1225 ret += tmp;
1226 while (!path.empty() && path.back()) {
1227 if (path.size() > 1) ret += '}';
1228 path.pop_back();
1229 }
1230 if (!path.empty()) path.back() = true;
1231 }
1232 return true;
1233 }
1234 public:
1235 TRDescriptor(std::unique_ptr<PubkeyProvider> internal_key, std::vector<std::unique_ptr<DescriptorImpl>> descs, std::vector<int> depths) :
1236 DescriptorImpl(Vector(std::move(internal_key)), std::move(descs), "tr"), m_depths(std::move(depths))
1237 {
1238 assert(m_subdescriptor_args.size() == m_depths.size());
1239 }
1240 std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32M; }
1241 bool IsSingleType() const final { return true; }
1242
1243 std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
1244
1245 std::optional<int64_t> MaxSatisfactionWeight(bool) const override {
1246 // FIXME: We assume keypath spend, which can lead to very large underestimations.
1247 return 1 + 65;
1248 }
1249
1250 std::optional<int64_t> MaxSatisfactionElems() const override {
1251 // FIXME: See above, we assume keypath spend.
1252 return 1;
1253 }
1254
1255 std::unique_ptr<DescriptorImpl> Clone() const override
1256 {
1257 std::vector<std::unique_ptr<DescriptorImpl>> subdescs;
1258 subdescs.reserve(m_subdescriptor_args.size());
1259 std::transform(m_subdescriptor_args.begin(), m_subdescriptor_args.end(), subdescs.begin(), [](const std::unique_ptr<DescriptorImpl>& d) { return d->Clone(); });
1260 return std::make_unique<TRDescriptor>(m_pubkey_args.at(0)->Clone(), std::move(subdescs), m_depths);
1261 }
1262 };
1263
1264 /* We instantiate Miniscript here with a simple integer as key type.
1265 * The value of these key integers are an index in the
1266 * DescriptorImpl::m_pubkey_args vector.
1267 */
1268
1269 /**
1270 * The context for converting a Miniscript descriptor into a Script.
1271 */
1272 class ScriptMaker {
1273 //! Keys contained in the Miniscript (the evaluation of DescriptorImpl::m_pubkey_args).
1274 const std::vector<CPubKey>& m_keys;
1275 //! The script context we're operating within (Tapscript or P2WSH).
1276 const miniscript::MiniscriptContext m_script_ctx;
1277
1278 //! Get the ripemd160(sha256()) hash of this key.
1279 //! Any key that is valid in a descriptor serializes as 32 bytes within a Tapscript context. So we
1280 //! must not hash the sign-bit byte in this case.
1281 uint160 GetHash160(uint32_t key) const {
1282 if (miniscript::IsTapscript(m_script_ctx)) {
1283 return Hash160(XOnlyPubKey{m_keys[key]});
1284 }
1285 return m_keys[key].GetID();
1286 }
1287
1288 public:
1289 ScriptMaker(const std::vector<CPubKey>& keys LIFETIMEBOUND, const miniscript::MiniscriptContext script_ctx) : m_keys(keys), m_script_ctx{script_ctx} {}
1290
1291 std::vector<unsigned char> ToPKBytes(uint32_t key) const {
1292 // In Tapscript keys always serialize as x-only, whether an x-only key was used in the descriptor or not.
1293 if (!miniscript::IsTapscript(m_script_ctx)) {
1294 return {m_keys[key].begin(), m_keys[key].end()};
1295 }
1296 const XOnlyPubKey xonly_pubkey{m_keys[key]};
1297 return {xonly_pubkey.begin(), xonly_pubkey.end()};
1298 }
1299
1300 std::vector<unsigned char> ToPKHBytes(uint32_t key) const {
1301 auto id = GetHash160(key);
1302 return {id.begin(), id.end()};
1303 }
1304 };
1305
1306 /**
1307 * The context for converting a Miniscript descriptor to its textual form.
1308 */
1309 class StringMaker {
1310 //! To convert private keys for private descriptors.
1311 const SigningProvider* m_arg;
1312 //! Keys contained in the Miniscript (a reference to DescriptorImpl::m_pubkey_args).
1313 const std::vector<std::unique_ptr<PubkeyProvider>>& m_pubkeys;
1314 //! Whether to serialize keys as private or public.
1315 bool m_private;
1316
1317 public:
1318 StringMaker(const SigningProvider* arg LIFETIMEBOUND, const std::vector<std::unique_ptr<PubkeyProvider>>& pubkeys LIFETIMEBOUND, bool priv)
1319 : m_arg(arg), m_pubkeys(pubkeys), m_private(priv) {}
1320
1321 std::optional<std::string> ToString(uint32_t key) const
1322 {
1323 std::string ret;
1324 if (m_private) {
1325 if (!m_pubkeys[key]->ToPrivateString(*m_arg, ret)) return {};
1326 } else {
1327 ret = m_pubkeys[key]->ToString();
1328 }
1329 return ret;
1330 }
1331 };
1332
1333 class MiniscriptDescriptor final : public DescriptorImpl
1334 {
1335 private:
1336 miniscript::NodeRef<uint32_t> m_node;
1337
1338 protected:
1339 std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript> scripts,
1340 FlatSigningProvider& provider) const override
1341 {
1342 const auto script_ctx{m_node->GetMsCtx()};
1343 for (const auto& key : keys) {
1344 if (miniscript::IsTapscript(script_ctx)) {
1345 provider.pubkeys.emplace(Hash160(XOnlyPubKey{key}), key);
1346 } else {
1347 provider.pubkeys.emplace(key.GetID(), key);
1348 }
1349 }
1350 return Vector(m_node->ToScript(ScriptMaker(keys, script_ctx)));
1351 }
1352
1353 public:
1354 MiniscriptDescriptor(std::vector<std::unique_ptr<PubkeyProvider>> providers, miniscript::NodeRef<uint32_t> node)
1355 : DescriptorImpl(std::move(providers), "?"), m_node(std::move(node)) {}
1356
1357 bool ToStringHelper(const SigningProvider* arg, std::string& out, const StringType type,
1358 const DescriptorCache* cache = nullptr) const override
1359 {
1360 if (const auto res = m_node->ToString(StringMaker(arg, m_pubkey_args, type == StringType::PRIVATE))) {
1361 out = *res;
1362 return true;
1363 }
1364 return false;
1365 }
1366
1367 bool IsSolvable() const override { return true; }
1368 bool IsSingleType() const final { return true; }
1369
1370 std::optional<int64_t> ScriptSize() const override { return m_node->ScriptSize(); }
1371
1372 std::optional<int64_t> MaxSatSize(bool) const override {
1373 // For Miniscript we always assume high-R ECDSA signatures.
1374 return m_node->GetWitnessSize();
1375 }
1376
1377 std::optional<int64_t> MaxSatisfactionElems() const override {
1378 return m_node->GetStackSize();
1379 }
1380
1381 std::unique_ptr<DescriptorImpl> Clone() const override
1382 {
1383 std::vector<std::unique_ptr<PubkeyProvider>> providers;
1384 providers.reserve(m_pubkey_args.size());
1385 for (const auto& arg : m_pubkey_args) {
1386 providers.push_back(arg->Clone());
1387 }
1388 return std::make_unique<MiniscriptDescriptor>(std::move(providers), m_node->Clone());
1389 }
1390 };
1391
1392 /** A parsed rawtr(...) descriptor. */
1393 class RawTRDescriptor final : public DescriptorImpl
1394 {
1395 protected:
1396 std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript> scripts, FlatSigningProvider& out) const override
1397 {
1398 assert(keys.size() == 1);
1399 XOnlyPubKey xpk(keys[0]);
1400 if (!xpk.IsFullyValid()) return {};
1401 WitnessV1Taproot output{xpk};
1402 return Vector(GetScriptForDestination(output));
1403 }
1404 public:
1405 RawTRDescriptor(std::unique_ptr<PubkeyProvider> output_key) : DescriptorImpl(Vector(std::move(output_key)), "rawtr") {}
1406 std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32M; }
1407 bool IsSingleType() const final { return true; }
1408
1409 std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
1410
1411 std::optional<int64_t> MaxSatisfactionWeight(bool) const override {
1412 // We can't know whether there is a script path, so assume key path spend.
1413 return 1 + 65;
1414 }
1415
1416 std::optional<int64_t> MaxSatisfactionElems() const override {
1417 // See above, we assume keypath spend.
1418 return 1;
1419 }
1420
1421 std::unique_ptr<DescriptorImpl> Clone() const override
1422 {
1423 return std::make_unique<RawTRDescriptor>(m_pubkey_args.at(0)->Clone());
1424 }
1425 };
1426
1427 ////////////////////////////////////////////////////////////////////////////
1428 // Parser //
1429 ////////////////////////////////////////////////////////////////////////////
1430
1431 enum class ParseScriptContext {
1432 TOP, //!< Top-level context (script goes directly in scriptPubKey)
1433 P2SH, //!< Inside sh() (script becomes P2SH redeemScript)
1434 P2WPKH, //!< Inside wpkh() (no script, pubkey only)
1435 P2WSH, //!< Inside wsh() (script becomes v0 witness script)
1436 P2TR, //!< Inside tr() (either internal key, or BIP342 script leaf)
1437 MUSIG, //!< Inside musig() (implies P2TR, cannot have nested musig())
1438 P2SPK, //!< Inside spk() (no script, x-only pubkey only)
1439 };
1440
1441 std::optional<uint32_t> ParseKeyPathNum(Span<const char> elem, bool& apostrophe, std::string& error)
1442 {
1443 bool hardened = false;
1444 if (elem.size() > 0) {
1445 const char last = elem[elem.size() - 1];
1446 if (last == '\'' || last == 'h') {
1447 elem = elem.first(elem.size() - 1);
1448 hardened = true;
1449 apostrophe = last == '\'';
1450 }
1451 }
1452 uint32_t p;
1453 if (!ParseUInt32(std::string(elem.begin(), elem.end()), &p)) {
1454 error = strprintf("Key path value '%s' is not a valid uint32", std::string(elem.begin(), elem.end()));
1455 return std::nullopt;
1456 } else if (p > 0x7FFFFFFFUL) {
1457 error = strprintf("Key path value %u is out of range", p);
1458 return std::nullopt;
1459 }
1460
1461 return std::make_optional<uint32_t>(p | (((uint32_t)hardened) << 31));
1462 }
1463
1464 /**
1465 * Parse a key path, being passed a split list of elements (the first element is ignored because it is always the key).
1466 *
1467 * @param[in] split BIP32 path string, using either ' or h for hardened derivation
1468 * @param[out] out Vector of parsed key paths
1469 * @param[out] apostrophe only updated if hardened derivation is found
1470 * @param[out] error parsing error message
1471 * @param[in] allow_multipath Allows the parsed path to use the multipath specifier
1472 * @returns false if parsing failed
1473 **/
1474 [[nodiscard]] bool ParseKeyPath(const std::vector<Span<const char>>& split, std::vector<KeyPath>& out, bool& apostrophe, std::string& error, bool allow_multipath)
1475 {
1476 KeyPath path;
1477 std::optional<size_t> multipath_segment_index;
1478 std::vector<uint32_t> multipath_values;
1479 std::unordered_set<uint32_t> seen_multipath;
1480
1481 for (size_t i = 1; i < split.size(); ++i) {
1482 const Span<const char>& elem = split[i];
1483
1484 // Check if element contain multipath specifier
1485 if (!elem.empty() && elem.front() == '<' && elem.back() == '>') {
1486 if (!allow_multipath) {
1487 error = strprintf("Key path value '%s' specifies multipath in a section where multipath is not allowed", std::string(elem.begin(), elem.end()));
1488 return false;
1489 }
1490 if (multipath_segment_index) {
1491 error = "Multiple multipath key path specifiers found";
1492 return false;
1493 }
1494
1495 // Parse each possible value
1496 std::vector<Span<const char>> nums = Split(Span(elem.begin()+1, elem.end()-1), ";");
1497 if (nums.size() < 2) {
1498 error = "Multipath key path specifiers must have at least two items";
1499 return false;
1500 }
1501
1502 for (const auto& num : nums) {
1503 const auto& op_num = ParseKeyPathNum(num, apostrophe, error);
1504 if (!op_num) return false;
1505 auto [_, inserted] = seen_multipath.insert(*op_num);
1506 if (!inserted) {
1507 error = strprintf("Duplicated key path value %u in multipath specifier", *op_num);
1508 return false;
1509 }
1510 multipath_values.emplace_back(*op_num);
1511 }
1512
1513 path.emplace_back(); // Placeholder for multipath segment
1514 multipath_segment_index = path.size()-1;
1515 } else {
1516 const auto& op_num = ParseKeyPathNum(elem, apostrophe, error);
1517 if (!op_num) return false;
1518 path.emplace_back(*op_num);
1519 }
1520 }
1521
1522 if (!multipath_segment_index) {
1523 out.emplace_back(std::move(path));
1524 } else {
1525 // Replace the multipath placeholder with each value while generating paths
1526 for (size_t i = 0; i < multipath_values.size(); i++) {
1527 KeyPath branch_path = path;
1528 branch_path[*multipath_segment_index] = multipath_values[i];
1529 out.emplace_back(std::move(branch_path));
1530 }
1531 }
1532 return true;
1533 }
1534
1535 /** Parse a public key that excludes origin information. */
1536 std::vector<std::unique_ptr<PubkeyProvider>> ParsePubkeyInner(uint32_t key_exp_index, const Span<const char>& sp, ParseScriptContext ctx, FlatSigningProvider& out, bool& apostrophe, std::string& error)
1537 {
1538 std::vector<std::unique_ptr<PubkeyProvider>> ret;
1539 bool permit_uncompressed = ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH;
1540 auto split = Split(sp, '/');
1541 std::string str(split[0].begin(), split[0].end());
1542 if (str.size() == 0) {
1543 error = "No key provided";
1544 return {};
1545 }
1546 if (split.size() == 1) {
1547 if (IsHex(str)) {
1548 std::vector<unsigned char> data = ParseHex(str);
1549 CPubKey pubkey(data);
1550 if (pubkey.IsValid() && !pubkey.IsValidNonHybrid()) {
1551 error = "Hybrid public keys are not allowed";
1552 return {};
1553 }
1554 if (pubkey.IsFullyValid()) {
1555 if (permit_uncompressed || pubkey.IsCompressed()) {
1556 ret.emplace_back(std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, false));
1557 return ret;
1558 } else {
1559 error = "Uncompressed keys are not allowed";
1560 return {};
1561 }
1562 } else if (data.size() == 32 && (ctx == ParseScriptContext::P2TR || ctx == ParseScriptContext::P2SPK)) {
1563 unsigned char fullkey[33] = {0x02};
1564 std::copy(data.begin(), data.end(), fullkey + 1);
1565 pubkey.Set(std::begin(fullkey), std::end(fullkey));
1566 if (pubkey.IsFullyValid()) {
1567 ret.emplace_back(std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, true));
1568 return ret;
1569 }
1570 }
1571 error = strprintf("Pubkey '%s' is invalid", str);
1572 return {};
1573 }
1574 CKey key = DecodeSecret(str);
1575 if (key.IsValid()) {
1576 if (permit_uncompressed || key.IsCompressed()) {
1577 CPubKey pubkey = key.GetPubKey();
1578 out.keys.emplace(pubkey.GetID(), key);
1579 ret.emplace_back(std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, ctx == ParseScriptContext::P2TR || ctx == ParseScriptContext::P2SPK));
1580 ++key_exp_index;
1581 return ret;
1582 } else {
1583 error = "Uncompressed keys are not allowed";
1584 return {};
1585 }
1586 }
1587 }
1588 CExtKey extkey = DecodeExtKey(str);
1589 CExtPubKey extpubkey = DecodeExtPubKey(str);
1590 if (!extkey.key.IsValid() && !extpubkey.pubkey.IsValid()) {
1591 error = strprintf("key '%s' is not valid", str);
1592 return {};
1593 }
1594 std::vector<KeyPath> paths;
1595 DeriveType type = DeriveType::NO;
1596 if (std::ranges::equal(split.back(), Span{"*"}.first(1))) {
1597 split.pop_back();
1598 type = DeriveType::UNHARDENED;
1599 } else if (std::ranges::equal(split.back(), Span{"*'"}.first(2)) || std::ranges::equal(split.back(), Span{"*h"}.first(2))) {
1600 apostrophe = std::ranges::equal(split.back(), Span{"*'"}.first(2));
1601 split.pop_back();
1602 type = DeriveType::HARDENED;
1603 }
1604 if (!ParseKeyPath(split, paths, apostrophe, error, /*allow_multipath=*/true)) return {};
1605 if (extkey.key.IsValid()) {
1606 extpubkey = extkey.Neuter();
1607 out.keys.emplace(extpubkey.pubkey.GetID(), extkey.key);
1608 }
1609 for (auto& path : paths) {
1610 ret.emplace_back(std::make_unique<BIP32PubkeyProvider>(key_exp_index, extpubkey, std::move(path), type, apostrophe));
1611 }
1612 return ret;
1613 }
1614
1615 /** Parse a public key including origin information (if enabled). */
1616 std::vector<std::unique_ptr<PubkeyProvider>> ParsePubkey(uint32_t key_exp_index, const Span<const char>& sp, ParseScriptContext ctx, FlatSigningProvider& out, std::string& error)
1617 {
1618 std::vector<std::unique_ptr<PubkeyProvider>> ret;
1619 auto origin_split = Split(sp, ']');
1620 if (origin_split.size() > 2) {
1621 error = "Multiple ']' characters found for a single pubkey";
1622 return {};
1623 }
1624 // This is set if either the origin or path suffix contains a hardened derivation.
1625 bool apostrophe = false;
1626 if (origin_split.size() == 1) {
1627 return ParsePubkeyInner(key_exp_index, origin_split[0], ctx, out, apostrophe, error);
1628 }
1629 if (origin_split[0].empty() || origin_split[0][0] != '[') {
1630 error = strprintf("Key origin start '[ character expected but not found, got '%c' instead",
1631 origin_split[0].empty() ? /** empty, implies split char */ ']' : origin_split[0][0]);
1632 return {};
1633 }
1634 auto slash_split = Split(origin_split[0].subspan(1), '/');
1635 if (slash_split[0].size() != 8) {
1636 error = strprintf("Fingerprint is not 4 bytes (%u characters instead of 8 characters)", slash_split[0].size());
1637 return {};
1638 }
1639 std::string fpr_hex = std::string(slash_split[0].begin(), slash_split[0].end());
1640 if (!IsHex(fpr_hex)) {
1641 error = strprintf("Fingerprint '%s' is not hex", fpr_hex);
1642 return {};
1643 }
1644 auto fpr_bytes = ParseHex(fpr_hex);
1645 KeyOriginInfo info;
1646 static_assert(sizeof(info.fingerprint) == 4, "Fingerprint must be 4 bytes");
1647 assert(fpr_bytes.size() == 4);
1648 std::copy(fpr_bytes.begin(), fpr_bytes.end(), info.fingerprint);
1649 std::vector<KeyPath> path;
1650 if (!ParseKeyPath(slash_split, path, apostrophe, error, /*allow_multipath=*/false)) return {};
1651 info.path = path.at(0);
1652 auto providers = ParsePubkeyInner(key_exp_index, origin_split[1], ctx, out, apostrophe, error);
1653 if (providers.empty()) return {};
1654 ret.reserve(providers.size());
1655 for (auto& prov : providers) {
1656 ret.emplace_back(std::make_unique<OriginPubkeyProvider>(key_exp_index, info, std::move(prov), apostrophe));
1657 }
1658 return ret;
1659 }
1660
1661 std::unique_ptr<PubkeyProvider> InferPubkey(const CPubKey& pubkey, ParseScriptContext ctx, const SigningProvider& provider)
1662 {
1663 // Key cannot be hybrid
1664 if (!pubkey.IsValidNonHybrid()) {
1665 return nullptr;
1666 }
1667 // Uncompressed is only allowed in TOP and P2SH contexts
1668 if (ctx != ParseScriptContext::TOP && ctx != ParseScriptContext::P2SH && !pubkey.IsCompressed()) {
1669 return nullptr;
1670 }
1671 std::unique_ptr<PubkeyProvider> key_provider = std::make_unique<ConstPubkeyProvider>(0, pubkey, false);
1672 KeyOriginInfo info;
1673 if (provider.GetKeyOrigin(pubkey.GetID(), info)) {
1674 return std::make_unique<OriginPubkeyProvider>(0, std::move(info), std::move(key_provider), /*apostrophe=*/false);
1675 }
1676 return key_provider;
1677 }
1678
1679 std::unique_ptr<PubkeyProvider> InferXOnlyPubkey(const XOnlyPubKey& xkey, ParseScriptContext ctx, const SigningProvider& provider)
1680 {
1681 CPubKey pubkey{xkey.GetEvenCorrespondingCPubKey()};
1682 std::unique_ptr<PubkeyProvider> key_provider = std::make_unique<ConstPubkeyProvider>(0, pubkey, true);
1683 KeyOriginInfo info;
1684 if (provider.GetKeyOriginByXOnly(xkey, info)) {
1685 return std::make_unique<OriginPubkeyProvider>(0, std::move(info), std::move(key_provider), /*apostrophe=*/false);
1686 }
1687 return key_provider;
1688 }
1689
1690 /**
1691 * The context for parsing a Miniscript descriptor (either from Script or from its textual representation).
1692 */
1693 struct KeyParser {
1694 //! The Key type is an index in DescriptorImpl::m_pubkey_args
1695 using Key = uint32_t;
1696 //! Must not be nullptr if parsing from string.
1697 FlatSigningProvider* m_out;
1698 //! Must not be nullptr if parsing from Script.
1699 const SigningProvider* m_in;
1700 //! List of multipath expanded keys contained in the Miniscript.
1701 mutable std::vector<std::vector<std::unique_ptr<PubkeyProvider>>> m_keys;
1702 //! Used to detect key parsing errors within a Miniscript.
1703 mutable std::string m_key_parsing_error;
1704 //! The script context we're operating within (Tapscript or P2WSH).
1705 const miniscript::MiniscriptContext m_script_ctx;
1706 //! The number of keys that were parsed before starting to parse this Miniscript descriptor.
1707 uint32_t m_offset;
1708
1709 KeyParser(FlatSigningProvider* out LIFETIMEBOUND, const SigningProvider* in LIFETIMEBOUND,
1710 miniscript::MiniscriptContext ctx, uint32_t offset = 0)
1711 : m_out(out), m_in(in), m_script_ctx(ctx), m_offset(offset) {}
1712
1713 bool KeyCompare(const Key& a, const Key& b) const {
1714 return *m_keys.at(a).at(0) < *m_keys.at(b).at(0);
1715 }
1716
1717 ParseScriptContext ParseContext() const {
1718 switch (m_script_ctx) {
1719 case miniscript::MiniscriptContext::P2WSH: return ParseScriptContext::P2WSH;
1720 case miniscript::MiniscriptContext::TAPSCRIPT: return ParseScriptContext::P2TR;
1721 }
1722 assert(false);
1723 }
1724
1725 template<typename I> std::optional<Key> FromString(I begin, I end) const
1726 {
1727 assert(m_out);
1728 Key key = m_keys.size();
1729 auto pk = ParsePubkey(m_offset + key, {&*begin, &*end}, ParseContext(), *m_out, m_key_parsing_error);
1730 if (pk.empty()) return {};
1731 m_keys.emplace_back(std::move(pk));
1732 return key;
1733 }
1734
1735 std::optional<std::string> ToString(const Key& key) const
1736 {
1737 return m_keys.at(key).at(0)->ToString();
1738 }
1739
1740 template<typename I> std::optional<Key> FromPKBytes(I begin, I end) const
1741 {
1742 assert(m_in);
1743 Key key = m_keys.size();
1744 if (miniscript::IsTapscript(m_script_ctx) && end - begin == 32) {
1745 XOnlyPubKey pubkey;
1746 std::copy(begin, end, pubkey.begin());
1747 if (auto pubkey_provider = InferXOnlyPubkey(pubkey, ParseContext(), *m_in)) {
1748 m_keys.emplace_back();
1749 m_keys.back().push_back(std::move(pubkey_provider));
1750 return key;
1751 }
1752 } else if (!miniscript::IsTapscript(m_script_ctx)) {
1753 CPubKey pubkey(begin, end);
1754 if (auto pubkey_provider = InferPubkey(pubkey, ParseContext(), *m_in)) {
1755 m_keys.emplace_back();
1756 m_keys.back().push_back(std::move(pubkey_provider));
1757 return key;
1758 }
1759 }
1760 return {};
1761 }
1762
1763 template<typename I> std::optional<Key> FromPKHBytes(I begin, I end) const
1764 {
1765 assert(end - begin == 20);
1766 assert(m_in);
1767 uint160 hash;
1768 std::copy(begin, end, hash.begin());
1769 CKeyID keyid(hash);
1770 CPubKey pubkey;
1771 if (m_in->GetPubKey(keyid, pubkey)) {
1772 if (auto pubkey_provider = InferPubkey(pubkey, ParseContext(), *m_in)) {
1773 Key key = m_keys.size();
1774 m_keys.emplace_back();
1775 m_keys.back().push_back(std::move(pubkey_provider));
1776 return key;
1777 }
1778 }
1779 return {};
1780 }
1781
1782 miniscript::MiniscriptContext MsContext() const {
1783 return m_script_ctx;
1784 }
1785 };
1786
1787 /** Parse a script in a particular context. */
1788 // NOLINTNEXTLINE(misc-no-recursion)
1789 std::vector<std::unique_ptr<DescriptorImpl>> ParseScript(uint32_t& key_exp_index, Span<const char>& sp, ParseScriptContext ctx, FlatSigningProvider& out, std::string& error)
1790 {
1791 using namespace script;
1792 Assume(ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH || ctx == ParseScriptContext::P2TR);
1793 std::vector<std::unique_ptr<DescriptorImpl>> ret;
1794 auto expr = Expr(sp);
1795 if (Func("pk", expr)) {
1796 auto pubkeys = ParsePubkey(key_exp_index, expr, ctx, out, error);
1797 if (pubkeys.empty()) {
1798 error = strprintf("pk(): %s", error);
1799 return {};
1800 }
1801 ++key_exp_index;
1802 for (auto& pubkey : pubkeys) {
1803 ret.emplace_back(std::make_unique<PKDescriptor>(std::move(pubkey), ctx == ParseScriptContext::P2TR));
1804 }
1805 return ret;
1806 }
1807 if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH) && Func("pkh", expr)) {
1808 auto pubkeys = ParsePubkey(key_exp_index, expr, ctx, out, error);
1809 if (pubkeys.empty()) {
1810 error = strprintf("pkh(): %s", error);
1811 return {};
1812 }
1813 ++key_exp_index;
1814 for (auto& pubkey : pubkeys) {
1815 ret.emplace_back(std::make_unique<PKHDescriptor>(std::move(pubkey)));
1816 }
1817 return ret;
1818 }
1819 if (ctx == ParseScriptContext::TOP && Func("combo", expr)) {
1820 auto pubkeys = ParsePubkey(key_exp_index, expr, ctx, out, error);
1821 if (pubkeys.empty()) {
1822 error = strprintf("combo(): %s", error);
1823 return {};
1824 }
1825 ++key_exp_index;
1826 for (auto& pubkey : pubkeys) {
1827 ret.emplace_back(std::make_unique<ComboDescriptor>(std::move(pubkey)));
1828 }
1829 return ret;
1830 } else if (Func("combo", expr)) {
1831 error = "Can only have combo() at top level";
1832 return {};
1833 }
1834 const bool multi = Func("multi", expr);
1835 const bool sortedmulti = !multi && Func("sortedmulti", expr);
1836 const bool multi_a = !(multi || sortedmulti) && Func("multi_a", expr);
1837 const bool sortedmulti_a = !(multi || sortedmulti || multi_a) && Func("sortedmulti_a", expr);
1838 if (((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH) && (multi || sortedmulti)) ||
1839 (ctx == ParseScriptContext::P2TR && (multi_a || sortedmulti_a))) {
1840 auto threshold = Expr(expr);
1841 uint32_t thres;
1842 std::vector<std::vector<std::unique_ptr<PubkeyProvider>>> providers; // List of multipath expanded pubkeys
1843 if (!ParseUInt32(std::string(threshold.begin(), threshold.end()), &thres)) {
1844 error = strprintf("Multi threshold '%s' is not valid", std::string(threshold.begin(), threshold.end()));
1845 return {};
1846 }
1847 size_t script_size = 0;
1848 size_t max_providers_len = 0;
1849 while (expr.size()) {
1850 if (!Const(",", expr)) {
1851 error = strprintf("Multi: expected ',', got '%c'", expr[0]);
1852 return {};
1853 }
1854 auto arg = Expr(expr);
1855 auto pks = ParsePubkey(key_exp_index, arg, ctx, out, error);
1856 if (pks.empty()) {
1857 error = strprintf("Multi: %s", error);
1858 return {};
1859 }
1860 script_size += pks.at(0)->GetSize() + 1;
1861 max_providers_len = std::max(max_providers_len, pks.size());
1862 providers.emplace_back(std::move(pks));
1863 key_exp_index++;
1864 }
1865 if ((multi || sortedmulti) && (providers.empty() || providers.size() > MAX_PUBKEYS_PER_MULTISIG)) {
1866 error = strprintf("Cannot have %u keys in multisig; must have between 1 and %d keys, inclusive", providers.size(), MAX_PUBKEYS_PER_MULTISIG);
1867 return {};
1868 } else if ((multi_a || sortedmulti_a) && (providers.empty() || providers.size() > MAX_PUBKEYS_PER_MULTI_A)) {
1869 error = strprintf("Cannot have %u keys in multi_a; must have between 1 and %d keys, inclusive", providers.size(), MAX_PUBKEYS_PER_MULTI_A);
1870 return {};
1871 } else if (thres < 1) {
1872 error = strprintf("Multisig threshold cannot be %d, must be at least 1", thres);
1873 return {};
1874 } else if (thres > providers.size()) {
1875 error = strprintf("Multisig threshold cannot be larger than the number of keys; threshold is %d but only %u keys specified", thres, providers.size());
1876 return {};
1877 }
1878 if (ctx == ParseScriptContext::TOP) {
1879 if (providers.size() > 3) {
1880 error = strprintf("Cannot have %u pubkeys in bare multisig; only at most 3 pubkeys", providers.size());
1881 return {};
1882 }
1883 }
1884 if (ctx == ParseScriptContext::P2SH) {
1885 // This limits the maximum number of compressed pubkeys to 15.
1886 if (script_size + 3 > MAX_SCRIPT_ELEMENT_SIZE) {
1887 error = strprintf("P2SH script is too large, %d bytes is larger than %d bytes", script_size + 3, MAX_SCRIPT_ELEMENT_SIZE);
1888 return {};
1889 }
1890 }
1891
1892 // Make sure all vecs are of the same length, or exactly length 1
1893 // For length 1 vectors, clone key providers until vector is the same length
1894 for (auto& vec : providers) {
1895 if (vec.size() == 1) {
1896 for (size_t i = 1; i < max_providers_len; ++i) {
1897 vec.emplace_back(vec.at(0)->Clone());
1898 }
1899 } else if (vec.size() != max_providers_len) {
1900 error = strprintf("multi(): Multipath derivation paths have mismatched lengths");
1901 return {};
1902 }
1903 }
1904
1905 // Build the final descriptors vector
1906 for (size_t i = 0; i < max_providers_len; ++i) {
1907 // Build final pubkeys vectors by retrieving the i'th subscript for each vector in subscripts
1908 std::vector<std::unique_ptr<PubkeyProvider>> pubs;
1909 pubs.reserve(providers.size());
1910 for (auto& pub : providers) {
1911 pubs.emplace_back(std::move(pub.at(i)));
1912 }
1913 if (multi || sortedmulti) {
1914 ret.emplace_back(std::make_unique<MultisigDescriptor>(thres, std::move(pubs), sortedmulti));
1915 } else {
1916 ret.emplace_back(std::make_unique<MultiADescriptor>(thres, std::move(pubs), sortedmulti_a));
1917 }
1918 }
1919 return ret;
1920 } else if (multi || sortedmulti) {
1921 error = "Can only have multi/sortedmulti at top level, in sh(), or in wsh()";
1922 return {};
1923 } else if (multi_a || sortedmulti_a) {
1924 error = "Can only have multi_a/sortedmulti_a inside tr()";
1925 return {};
1926 }
1927 if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH) && Func("wpkh", expr)) {
1928 auto pubkeys = ParsePubkey(key_exp_index, expr, ParseScriptContext::P2WPKH, out, error);
1929 if (pubkeys.empty()) {
1930 error = strprintf("wpkh(): %s", error);
1931 return {};
1932 }
1933 key_exp_index++;
1934 for (auto& pubkey : pubkeys) {
1935 ret.emplace_back(std::make_unique<WPKHDescriptor>(std::move(pubkey)));
1936 }
1937 return ret;
1938 } else if (Func("wpkh", expr)) {
1939 error = "Can only have wpkh() at top level or inside sh()";
1940 return {};
1941 }
1942 if (ctx == ParseScriptContext::TOP && Func("spk", expr)) {
1943 auto pubkeys = ParsePubkey(key_exp_index, expr, ParseScriptContext::P2SPK, out, error);
1944 if (pubkeys.empty()) {
1945 error = strprintf("spk(): %s", error);
1946 return {};
1947 }
1948 for (auto& pubkey : pubkeys) {
1949 ret.emplace_back(std::make_unique<SPKDescriptor>(std::move(pubkey)));
1950 }
1951 return ret;
1952 } else if (Func("spk", expr)) {
1953 error = "Can only have spk() at top level";
1954 return {};
1955 }
1956 if (ctx == ParseScriptContext::TOP && Func("sh", expr)) {
1957 auto descs = ParseScript(key_exp_index, expr, ParseScriptContext::P2SH, out, error);
1958 if (descs.empty() || expr.size()) return {};
1959 std::vector<std::unique_ptr<DescriptorImpl>> ret;
1960 ret.reserve(descs.size());
1961 for (auto& desc : descs) {
1962 ret.push_back(std::make_unique<SHDescriptor>(std::move(desc)));
1963 }
1964 return ret;
1965 } else if (Func("sh", expr)) {
1966 error = "Can only have sh() at top level";
1967 return {};
1968 }
1969 if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH) && Func("wsh", expr)) {
1970 auto descs = ParseScript(key_exp_index, expr, ParseScriptContext::P2WSH, out, error);
1971 if (descs.empty() || expr.size()) return {};
1972 for (auto& desc : descs) {
1973 ret.emplace_back(std::make_unique<WSHDescriptor>(std::move(desc)));
1974 }
1975 return ret;
1976 } else if (Func("wsh", expr)) {
1977 error = "Can only have wsh() at top level or inside sh()";
1978 return {};
1979 }
1980 if (ctx == ParseScriptContext::TOP && Func("addr", expr)) {
1981 CTxDestination dest = DecodeDestination(std::string(expr.begin(), expr.end()));
1982 if (!IsValidDestination(dest)) {
1983 error = "Address is not valid";
1984 return {};
1985 }
1986 ret.emplace_back(std::make_unique<AddressDescriptor>(std::move(dest)));
1987 return ret;
1988 } else if (Func("addr", expr)) {
1989 error = "Can only have addr() at top level";
1990 return {};
1991 }
1992 if (ctx == ParseScriptContext::TOP && Func("tr", expr)) {
1993 auto arg = Expr(expr);
1994 auto internal_keys = ParsePubkey(key_exp_index, arg, ParseScriptContext::P2TR, out, error);
1995 if (internal_keys.empty()) {
1996 error = strprintf("tr(): %s", error);
1997 return {};
1998 }
1999 size_t max_providers_len = internal_keys.size();
2000 ++key_exp_index;
2001 std::vector<std::vector<std::unique_ptr<DescriptorImpl>>> subscripts; //!< list of multipath expanded script subexpressions
2002 std::vector<int> depths; //!< depth in the tree of each subexpression (same length subscripts)
2003 if (expr.size()) {
2004 if (!Const(",", expr)) {
2005 error = strprintf("tr: expected ',', got '%c'", expr[0]);
2006 return {};
2007 }
2008 /** The path from the top of the tree to what we're currently processing.
2009 * branches[i] == false: left branch in the i'th step from the top; true: right branch.
2010 */
2011 std::vector<bool> branches;
2012 // Loop over all provided scripts. In every iteration exactly one script will be processed.
2013 // Use a do-loop because inside this if-branch we expect at least one script.
2014 do {
2015 // First process all open braces.
2016 while (Const("{", expr)) {
2017 branches.push_back(false); // new left branch
2018 if (branches.size() > TAPROOT_CONTROL_MAX_NODE_COUNT_REDUCED) {
2019 error = strprintf("tr() supports at most %i nesting levels", TAPROOT_CONTROL_MAX_NODE_COUNT_REDUCED);
2020 return {};
2021 }
2022 }
2023 // Process the actual script expression.
2024 auto sarg = Expr(expr);
2025 subscripts.emplace_back(ParseScript(key_exp_index, sarg, ParseScriptContext::P2TR, out, error));
2026 if (subscripts.back().empty()) return {};
2027 max_providers_len = std::max(max_providers_len, subscripts.back().size());
2028 depths.push_back(branches.size());
2029 // Process closing braces; one is expected for every right branch we were in.
2030 while (branches.size() && branches.back()) {
2031 if (!Const("}", expr)) {
2032 error = strprintf("tr(): expected '}' after script expression");
2033 return {};
2034 }
2035 branches.pop_back(); // move up one level after encountering '}'
2036 }
2037 // If after that, we're at the end of a left branch, expect a comma.
2038 if (branches.size() && !branches.back()) {
2039 if (!Const(",", expr)) {
2040 error = strprintf("tr(): expected ',' after script expression");
2041 return {};
2042 }
2043 branches.back() = true; // And now we're in a right branch.
2044 }
2045 } while (branches.size());
2046 // After we've explored a whole tree, we must be at the end of the expression.
2047 if (expr.size()) {
2048 error = strprintf("tr(): expected ')' after script expression");
2049 return {};
2050 }
2051 }
2052 assert(TaprootBuilder::ValidDepths(depths));
2053
2054 // Make sure all vecs are of the same length, or exactly length 1
2055 // For length 1 vectors, clone subdescs until vector is the same length
2056 for (auto& vec : subscripts) {
2057 if (vec.size() == 1) {
2058 for (size_t i = 1; i < max_providers_len; ++i) {
2059 vec.emplace_back(vec.at(0)->Clone());
2060 }
2061 } else if (vec.size() != max_providers_len) {
2062 error = strprintf("tr(): Multipath subscripts have mismatched lengths");
2063 return {};
2064 }
2065 }
2066
2067 if (internal_keys.size() > 1 && internal_keys.size() != max_providers_len) {
2068 error = strprintf("tr(): Multipath internal key mismatches multipath subscripts lengths");
2069 return {};
2070 }
2071
2072 while (internal_keys.size() < max_providers_len) {
2073 internal_keys.emplace_back(internal_keys.at(0)->Clone());
2074 }
2075
2076 // Build the final descriptors vector
2077 for (size_t i = 0; i < max_providers_len; ++i) {
2078 // Build final subscripts vectors by retrieving the i'th subscript for each vector in subscripts
2079 std::vector<std::unique_ptr<DescriptorImpl>> this_subs;
2080 this_subs.reserve(subscripts.size());
2081 for (auto& subs : subscripts) {
2082 this_subs.emplace_back(std::move(subs.at(i)));
2083 }
2084 ret.emplace_back(std::make_unique<TRDescriptor>(std::move(internal_keys.at(i)), std::move(this_subs), depths));
2085 }
2086 return ret;
2087
2088
2089 } else if (Func("tr", expr)) {
2090 error = "Can only have tr at top level";
2091 return {};
2092 }
2093 if (ctx == ParseScriptContext::TOP && Func("rawtr", expr)) {
2094 auto arg = Expr(expr);
2095 if (expr.size()) {
2096 error = strprintf("rawtr(): only one key expected.");
2097 return {};
2098 }
2099 auto output_keys = ParsePubkey(key_exp_index, arg, ParseScriptContext::P2TR, out, error);
2100 if (output_keys.empty()) {
2101 error = strprintf("rawtr(): %s", error);
2102 return {};
2103 }
2104 ++key_exp_index;
2105 for (auto& pubkey : output_keys) {
2106 ret.emplace_back(std::make_unique<RawTRDescriptor>(std::move(pubkey)));
2107 }
2108 return ret;
2109 } else if (Func("rawtr", expr)) {
2110 error = "Can only have rawtr at top level";
2111 return {};
2112 }
2113 if (ctx == ParseScriptContext::TOP && Func("raw", expr)) {
2114 std::string str(expr.begin(), expr.end());
2115 if (!IsHex(str)) {
2116 error = "Raw script is not hex";
2117 return {};
2118 }
2119 auto bytes = ParseHex(str);
2120 ret.emplace_back(std::make_unique<RawDescriptor>(CScript(bytes.begin(), bytes.end())));
2121 return ret;
2122 } else if (Func("raw", expr)) {
2123 error = "Can only have raw() at top level";
2124 return {};
2125 }
2126 // Process miniscript expressions.
2127 {
2128 const auto script_ctx{ctx == ParseScriptContext::P2WSH ? miniscript::MiniscriptContext::P2WSH : miniscript::MiniscriptContext::TAPSCRIPT};
2129 KeyParser parser(/*out = */&out, /* in = */nullptr, /* ctx = */script_ctx, key_exp_index);
2130 auto node = miniscript::FromString(std::string(expr.begin(), expr.end()), parser);
2131 if (parser.m_key_parsing_error != "") {
2132 error = std::move(parser.m_key_parsing_error);
2133 return {};
2134 }
2135 if (node) {
2136 if (ctx != ParseScriptContext::P2WSH && ctx != ParseScriptContext::P2TR) {
2137 error = "Miniscript expressions can only be used in wsh or tr.";
2138 return {};
2139 }
2140 if (!node->IsSane() || node->IsNotSatisfiable()) {
2141 // Try to find the first insane sub for better error reporting.
2142 auto insane_node = node.get();
2143 if (const auto sub = node->FindInsaneSub()) insane_node = sub;
2144 if (const auto str = insane_node->ToString(parser)) error = *str;
2145 if (!insane_node->IsValid()) {
2146 error += " is invalid";
2147 } else if (!node->IsSane()) {
2148 error += " is not sane";
2149 if (!insane_node->IsNonMalleable()) {
2150 error += ": malleable witnesses exist";
2151 } else if (insane_node == node.get() && !insane_node->NeedsSignature()) {
2152 error += ": witnesses without signature exist";
2153 } else if (!insane_node->CheckTimeLocksMix()) {
2154 error += ": contains mixes of timelocks expressed in blocks and seconds";
2155 } else if (!insane_node->CheckDuplicateKey()) {
2156 error += ": contains duplicate public keys";
2157 } else if (!insane_node->ValidSatisfactions()) {
2158 error += ": needs witnesses that may exceed resource limits";
2159 }
2160 } else {
2161 error += " is not satisfiable";
2162 }
2163 return {};
2164 }
2165 // A signature check is required for a miniscript to be sane. Therefore no sane miniscript
2166 // may have an empty list of public keys.
2167 CHECK_NONFATAL(!parser.m_keys.empty());
2168 key_exp_index += parser.m_keys.size();
2169 // Make sure all vecs are of the same length, or exactly length 1
2170 // For length 1 vectors, clone subdescs until vector is the same length
2171 size_t num_multipath = std::max_element(parser.m_keys.begin(), parser.m_keys.end(),
2172 [](const std::vector<std::unique_ptr<PubkeyProvider>>& a, const std::vector<std::unique_ptr<PubkeyProvider>>& b) {
2173 return a.size() < b.size();
2174 })->size();
2175
2176 for (auto& vec : parser.m_keys) {
2177 if (vec.size() == 1) {
2178 for (size_t i = 1; i < num_multipath; ++i) {
2179 vec.emplace_back(vec.at(0)->Clone());
2180 }
2181 } else if (vec.size() != num_multipath) {
2182 error = strprintf("Miniscript: Multipath derivation paths have mismatched lengths");
2183 return {};
2184 }
2185 }
2186
2187 // Build the final descriptors vector
2188 for (size_t i = 0; i < num_multipath; ++i) {
2189 // Build final pubkeys vectors by retrieving the i'th subscript for each vector in subscripts
2190 std::vector<std::unique_ptr<PubkeyProvider>> pubs;
2191 pubs.reserve(parser.m_keys.size());
2192 for (auto& pub : parser.m_keys) {
2193 pubs.emplace_back(std::move(pub.at(i)));
2194 }
2195 ret.emplace_back(std::make_unique<MiniscriptDescriptor>(std::move(pubs), node->Clone()));
2196 }
2197 return ret;
2198 }
2199 }
2200 if (ctx == ParseScriptContext::P2SH) {
2201 error = "A function is needed within P2SH";
2202 return {};
2203 } else if (ctx == ParseScriptContext::P2WSH) {
2204 error = "A function is needed within P2WSH";
2205 return {};
2206 }
2207 error = strprintf("'%s' is not a valid descriptor function", std::string(expr.begin(), expr.end()));
2208 return {};
2209 }
2210
2211 std::unique_ptr<DescriptorImpl> InferMultiA(const CScript& script, ParseScriptContext ctx, const SigningProvider& provider)
2212 {
2213 auto match = MatchMultiA(script);
2214 if (!match) return {};
2215 std::vector<std::unique_ptr<PubkeyProvider>> keys;
2216 keys.reserve(match->second.size());
2217 for (const auto keyspan : match->second) {
2218 if (keyspan.size() != 32) return {};
2219 auto key = InferXOnlyPubkey(XOnlyPubKey{keyspan}, ctx, provider);
2220 if (!key) return {};
2221 keys.push_back(std::move(key));
2222 }
2223 return std::make_unique<MultiADescriptor>(match->first, std::move(keys));
2224 }
2225
2226 // NOLINTNEXTLINE(misc-no-recursion)
2227 std::unique_ptr<DescriptorImpl> InferScript(const CScript& script, ParseScriptContext ctx, const SigningProvider& provider)
2228 {
2229 if (ctx == ParseScriptContext::P2TR && script.size() == 34 && script[0] == 32 && script[33] == OP_CHECKSIG) {
2230 XOnlyPubKey key{Span{script}.subspan(1, 32)};
2231 return std::make_unique<PKDescriptor>(InferXOnlyPubkey(key, ctx, provider), true);
2232 }
2233
2234 if (ctx == ParseScriptContext::P2TR) {
2235 auto ret = InferMultiA(script, ctx, provider);
2236 if (ret) return ret;
2237 }
2238
2239 std::vector<std::vector<unsigned char>> data;
2240 TxoutType txntype = Solver(script, data);
2241
2242 if (txntype == TxoutType::PUBKEY && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
2243 CPubKey pubkey(data[0]);
2244 if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
2245 return std::make_unique<PKDescriptor>(std::move(pubkey_provider));
2246 }
2247 }
2248 if (txntype == TxoutType::PUBKEYHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
2249 uint160 hash(data[0]);
2250 CKeyID keyid(hash);
2251 CPubKey pubkey;
2252 if (provider.GetPubKey(keyid, pubkey)) {
2253 if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
2254 return std::make_unique<PKHDescriptor>(std::move(pubkey_provider));
2255 }
2256 }
2257 }
2258 if (txntype == TxoutType::WITNESS_V0_KEYHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH)) {
2259 uint160 hash(data[0]);
2260 CKeyID keyid(hash);
2261 CPubKey pubkey;
2262 if (provider.GetPubKey(keyid, pubkey)) {
2263 if (auto pubkey_provider = InferPubkey(pubkey, ParseScriptContext::P2WPKH, provider)) {
2264 return std::make_unique<WPKHDescriptor>(std::move(pubkey_provider));
2265 }
2266 }
2267 }
2268 if (txntype == TxoutType::MULTISIG && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
2269 bool ok = true;
2270 std::vector<std::unique_ptr<PubkeyProvider>> providers;
2271 for (size_t i = 1; i + 1 < data.size(); ++i) {
2272 CPubKey pubkey(data[i]);
2273 if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
2274 providers.push_back(std::move(pubkey_provider));
2275 } else {
2276 ok = false;
2277 break;
2278 }
2279 }
2280 if (ok) return std::make_unique<MultisigDescriptor>((int)data[0][0], std::move(providers));
2281 }
2282 if (txntype == TxoutType::SCRIPTHASH && ctx == ParseScriptContext::TOP) {
2283 uint160 hash(data[0]);
2284 CScriptID scriptid(hash);
2285 CScript subscript;
2286 if (provider.GetCScript(scriptid, subscript)) {
2287 auto sub = InferScript(subscript, ParseScriptContext::P2SH, provider);
2288 if (sub) return std::make_unique<SHDescriptor>(std::move(sub));
2289 }
2290 }
2291 if (txntype == TxoutType::WITNESS_V0_SCRIPTHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH)) {
2292 CScriptID scriptid{RIPEMD160(data[0])};
2293 CScript subscript;
2294 if (provider.GetCScript(scriptid, subscript)) {
2295 auto sub = InferScript(subscript, ParseScriptContext::P2WSH, provider);
2296 if (sub) return std::make_unique<WSHDescriptor>(std::move(sub));
2297 }
2298 }
2299 if (txntype == TxoutType::WITNESS_V1_TAPROOT && ctx == ParseScriptContext::TOP) {
2300 // Extract x-only pubkey from output.
2301 XOnlyPubKey pubkey;
2302 std::copy(data[0].begin(), data[0].end(), pubkey.begin());
2303 // Request spending data.
2304 TaprootSpendData tap;
2305 if (provider.GetTaprootSpendData(pubkey, tap)) {
2306 // If found, convert it back to tree form.
2307 auto tree = InferTaprootTree(tap, pubkey);
2308 if (tree) {
2309 // If that works, try to infer subdescriptors for all leaves.
2310 bool ok = true;
2311 std::vector<std::unique_ptr<DescriptorImpl>> subscripts; //!< list of script subexpressions
2312 std::vector<int> depths; //!< depth in the tree of each subexpression (same length subscripts)
2313 for (const auto& [depth, script, leaf_ver] : *tree) {
2314 std::unique_ptr<DescriptorImpl> subdesc;
2315 if (leaf_ver == TAPROOT_LEAF_TAPSCRIPT) {
2316 subdesc = InferScript(CScript(script.begin(), script.end()), ParseScriptContext::P2TR, provider);
2317 }
2318 if (!subdesc) {
2319 ok = false;
2320 break;
2321 } else {
2322 subscripts.push_back(std::move(subdesc));
2323 depths.push_back(depth);
2324 }
2325 }
2326 if (ok) {
2327 auto key = InferXOnlyPubkey(tap.internal_key, ParseScriptContext::P2TR, provider);
2328 return std::make_unique<TRDescriptor>(std::move(key), std::move(subscripts), std::move(depths));
2329 }
2330 }
2331 }
2332 // If the above doesn't work, construct a rawtr() descriptor with just the encoded x-only pubkey.
2333 if (pubkey.IsFullyValid()) {
2334 auto key = InferXOnlyPubkey(pubkey, ParseScriptContext::P2TR, provider);
2335 if (key) {
2336 return std::make_unique<RawTRDescriptor>(std::move(key));
2337 }
2338 }
2339 }
2340 if (txntype == TxoutType::WITNESS_V3_SPKHASH && ctx == ParseScriptContext::TOP) {
2341 uint256 key_hash(data[0]);
2342 XOnlyPubKey pubkey;
2343 if (provider.GetSpkPubKey(key_hash, pubkey)) {
2344 auto key = InferXOnlyPubkey(pubkey, ParseScriptContext::P2SPK, provider);
2345 if (key) {
2346 return std::make_unique<SPKDescriptor>(std::move(key));
2347 }
2348 }
2349 }
2350
2351 if (ctx == ParseScriptContext::P2WSH || ctx == ParseScriptContext::P2TR) {
2352 const auto script_ctx{ctx == ParseScriptContext::P2WSH ? miniscript::MiniscriptContext::P2WSH : miniscript::MiniscriptContext::TAPSCRIPT};
2353 KeyParser parser(/* out = */nullptr, /* in = */&provider, /* ctx = */script_ctx);
2354 auto node = miniscript::FromScript(script, parser);
2355 if (node && node->IsSane()) {
2356 std::vector<std::unique_ptr<PubkeyProvider>> keys;
2357 keys.reserve(parser.m_keys.size());
2358 for (auto& key : parser.m_keys) {
2359 keys.emplace_back(std::move(key.at(0)));
2360 }
2361 return std::make_unique<MiniscriptDescriptor>(std::move(keys), std::move(node));
2362 }
2363 }
2364
2365 // The following descriptors are all top-level only descriptors.
2366 // So if we are not at the top level, return early.
2367 if (ctx != ParseScriptContext::TOP) return nullptr;
2368
2369 CTxDestination dest;
2370 if (ExtractDestination(script, dest)) {
2371 if (GetScriptForDestination(dest) == script) {
2372 return std::make_unique<AddressDescriptor>(std::move(dest));
2373 }
2374 }
2375
2376 return std::make_unique<RawDescriptor>(script);
2377 }
2378
2379
2380 } // namespace
2381
2382 /** Check a descriptor checksum, and update desc to be the checksum-less part. */
2383 bool CheckChecksum(Span<const char>& sp, bool require_checksum, std::string& error, std::string* out_checksum = nullptr)
2384 {
2385 auto check_split = Split(sp, '#');
2386 if (check_split.size() > 2) {
2387 error = "Multiple '#' symbols";
2388 return false;
2389 }
2390 if (check_split.size() == 1 && require_checksum){
2391 error = "Missing checksum";
2392 return false;
2393 }
2394 if (check_split.size() == 2) {
2395 if (check_split[1].size() != 8) {
2396 error = strprintf("Expected 8 character checksum, not %u characters", check_split[1].size());
2397 return false;
2398 }
2399 }
2400 auto checksum = DescriptorChecksum(check_split[0]);
2401 if (checksum.empty()) {
2402 error = "Invalid characters in payload";
2403 return false;
2404 }
2405 if (check_split.size() == 2) {
2406 if (!std::equal(checksum.begin(), checksum.end(), check_split[1].begin())) {
2407 error = strprintf("Provided checksum '%s' does not match computed checksum '%s'", std::string(check_split[1].begin(), check_split[1].end()), checksum);
2408 return false;
2409 }
2410 }
2411 if (out_checksum) *out_checksum = std::move(checksum);
2412 sp = check_split[0];
2413 return true;
2414 }
2415
2416 std::vector<std::unique_ptr<Descriptor>> Parse(const std::string& descriptor, FlatSigningProvider& out, std::string& error, bool require_checksum)
2417 {
2418 Span<const char> sp{descriptor};
2419 if (!CheckChecksum(sp, require_checksum, error)) return {};
2420 uint32_t key_exp_index = 0;
2421 auto ret = ParseScript(key_exp_index, sp, ParseScriptContext::TOP, out, error);
2422 if (sp.size() == 0 && !ret.empty()) {
2423 std::vector<std::unique_ptr<Descriptor>> descs;
2424 descs.reserve(ret.size());
2425 for (auto& r : ret) {
2426 descs.emplace_back(std::unique_ptr<Descriptor>(std::move(r)));
2427 }
2428 return descs;
2429 }
2430 return {};
2431 }
2432
2433 std::string GetDescriptorChecksum(const std::string& descriptor)
2434 {
2435 std::string ret;
2436 std::string error;
2437 Span<const char> sp{descriptor};
2438 if (!CheckChecksum(sp, false, error, &ret)) return "";
2439 return ret;
2440 }
2441
2442 std::string AddChecksum(const std::string& str) { return str + "#" + DescriptorChecksum(str); }
2443
2444 std::unique_ptr<Descriptor> InferDescriptor(const CScript& script, const SigningProvider& provider)
2445 {
2446 return InferScript(script, ParseScriptContext::TOP, provider);
2447 }
2448
2449 uint256 DescriptorID(const Descriptor& desc)
2450 {
2451 std::string desc_str = desc.ToString(/*compat_format=*/true);
2452 uint256 id;
2453 CSHA256().Write((unsigned char*)desc_str.data(), desc_str.size()).Finalize(id.begin());
2454 return id;
2455 }
2456
2457 void DescriptorCache::CacheParentExtPubKey(uint32_t key_exp_pos, const CExtPubKey& xpub)
2458 {
2459 m_parent_xpubs[key_exp_pos] = xpub;
2460 }
2461
2462 void DescriptorCache::CacheDerivedExtPubKey(uint32_t key_exp_pos, uint32_t der_index, const CExtPubKey& xpub)
2463 {
2464 auto& xpubs = m_derived_xpubs[key_exp_pos];
2465 xpubs[der_index] = xpub;
2466 }
2467
2468 void DescriptorCache::CacheLastHardenedExtPubKey(uint32_t key_exp_pos, const CExtPubKey& xpub)
2469 {
2470 m_last_hardened_xpubs[key_exp_pos] = xpub;
2471 }
2472
2473 bool DescriptorCache::GetCachedParentExtPubKey(uint32_t key_exp_pos, CExtPubKey& xpub) const
2474 {
2475 const auto& it = m_parent_xpubs.find(key_exp_pos);
2476 if (it == m_parent_xpubs.end()) return false;
2477 xpub = it->second;
2478 return true;
2479 }
2480
2481 bool DescriptorCache::GetCachedDerivedExtPubKey(uint32_t key_exp_pos, uint32_t der_index, CExtPubKey& xpub) const
2482 {
2483 const auto& key_exp_it = m_derived_xpubs.find(key_exp_pos);
2484 if (key_exp_it == m_derived_xpubs.end()) return false;
2485 const auto& der_it = key_exp_it->second.find(der_index);
2486 if (der_it == key_exp_it->second.end()) return false;
2487 xpub = der_it->second;
2488 return true;
2489 }
2490
2491 bool DescriptorCache::GetCachedLastHardenedExtPubKey(uint32_t key_exp_pos, CExtPubKey& xpub) const
2492 {
2493 const auto& it = m_last_hardened_xpubs.find(key_exp_pos);
2494 if (it == m_last_hardened_xpubs.end()) return false;
2495 xpub = it->second;
2496 return true;
2497 }
2498
2499 DescriptorCache DescriptorCache::MergeAndDiff(const DescriptorCache& other)
2500 {
2501 DescriptorCache diff;
2502 for (const auto& parent_xpub_pair : other.GetCachedParentExtPubKeys()) {
2503 CExtPubKey xpub;
2504 if (GetCachedParentExtPubKey(parent_xpub_pair.first, xpub)) {
2505 if (xpub != parent_xpub_pair.second) {
2506 throw std::runtime_error(std::string(__func__) + ": New cached parent xpub does not match already cached parent xpub");
2507 }
2508 continue;
2509 }
2510 CacheParentExtPubKey(parent_xpub_pair.first, parent_xpub_pair.second);
2511 diff.CacheParentExtPubKey(parent_xpub_pair.first, parent_xpub_pair.second);
2512 }
2513 for (const auto& derived_xpub_map_pair : other.GetCachedDerivedExtPubKeys()) {
2514 for (const auto& derived_xpub_pair : derived_xpub_map_pair.second) {
2515 CExtPubKey xpub;
2516 if (GetCachedDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, xpub)) {
2517 if (xpub != derived_xpub_pair.second) {
2518 throw std::runtime_error(std::string(__func__) + ": New cached derived xpub does not match already cached derived xpub");
2519 }
2520 continue;
2521 }
2522 CacheDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, derived_xpub_pair.second);
2523 diff.CacheDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, derived_xpub_pair.second);
2524 }
2525 }
2526 for (const auto& lh_xpub_pair : other.GetCachedLastHardenedExtPubKeys()) {
2527 CExtPubKey xpub;
2528 if (GetCachedLastHardenedExtPubKey(lh_xpub_pair.first, xpub)) {
2529 if (xpub != lh_xpub_pair.second) {
2530 throw std::runtime_error(std::string(__func__) + ": New cached last hardened xpub does not match already cached last hardened xpub");
2531 }
2532 continue;
2533 }
2534 CacheLastHardenedExtPubKey(lh_xpub_pair.first, lh_xpub_pair.second);
2535 diff.CacheLastHardenedExtPubKey(lh_xpub_pair.first, lh_xpub_pair.second);
2536 }
2537 return diff;
2538 }
2539
2540 ExtPubKeyMap DescriptorCache::GetCachedParentExtPubKeys() const
2541 {
2542 return m_parent_xpubs;
2543 }
2544
2545 std::unordered_map<uint32_t, ExtPubKeyMap> DescriptorCache::GetCachedDerivedExtPubKeys() const
2546 {
2547 return m_derived_xpubs;
2548 }
2549
2550 ExtPubKeyMap DescriptorCache::GetCachedLastHardenedExtPubKeys() const
2551 {
2552 return m_last_hardened_xpubs;
2553 }
2554