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