1 // Copyright (c) 2018-2020 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 <key_io.h>
8 #include <pubkey.h>
9 #include <script/script.h>
10 #include <script/standard.h>
11 
12 #include <span.h>
13 #include <util/bip32.h>
14 #include <util/spanparsing.h>
15 #include <util/system.h>
16 #include <util/strencodings.h>
17 #include <util/vector.h>
18 
19 #include <memory>
20 #include <optional>
21 #include <string>
22 #include <vector>
23 
24 namespace {
25 
26 ////////////////////////////////////////////////////////////////////////////
27 // Checksum                                                               //
28 ////////////////////////////////////////////////////////////////////////////
29 
30 // This section implements a checksum algorithm for descriptors with the
31 // following properties:
32 // * Mistakes in a descriptor string are measured in "symbol errors". The higher
33 //   the number of symbol errors, the harder it is to detect:
34 //   * An error substituting a character from 0123456789()[],'/*abcdefgh@:$%{} for
35 //     another in that set always counts as 1 symbol error.
36 //     * Note that hex encoded keys are covered by these characters. Xprvs and
37 //       xpubs use other characters too, but already have their own checksum
38 //       mechanism.
39 //     * Function names like "multi()" use other characters, but mistakes in
40 //       these would generally result in an unparsable descriptor.
41 //   * A case error always counts as 1 symbol error.
42 //   * Any other 1 character substitution error counts as 1 or 2 symbol errors.
43 // * Any 1 symbol error is always detected.
44 // * Any 2 or 3 symbol error in a descriptor of up to 49154 characters is always detected.
45 // * Any 4 symbol error in a descriptor of up to 507 characters is always detected.
46 // * Any 5 symbol error in a descriptor of up to 77 characters is always detected.
47 // * Is optimized to minimize the chance a 5 symbol error in a descriptor up to 387 characters is undetected
48 // * Random errors have a chance of 1 in 2**40 of being undetected.
49 //
50 // These properties are achieved by expanding every group of 3 (non checksum) characters into
51 // 4 GF(32) symbols, over which a cyclic code is defined.
52 
53 /*
54  * Interprets c as 8 groups of 5 bits which are the coefficients of a degree 8 polynomial over GF(32),
55  * multiplies that polynomial by x, computes its remainder modulo a generator, and adds the constant term val.
56  *
57  * 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}.
58  * It is chosen to define an cyclic error detecting code which is selected by:
59  * - Starting from all BCH codes over GF(32) of degree 8 and below, which by construction guarantee detecting
60  *   3 errors in windows up to 19000 symbols.
61  * - Taking all those generators, and for degree 7 ones, extend them to degree 8 by adding all degree-1 factors.
62  * - Selecting just the set of generators that guarantee detecting 4 errors in a window of length 512.
63  * - Selecting one of those with best worst-case behavior for 5 errors in windows of length up to 512.
64  *
65  * The generator and the constants to implement it can be verified using this Sage code:
66  *   B = GF(2) # Binary field
67  *   BP.<b> = B[] # Polynomials over the binary field
68  *   F_mod = b**5 + b**3 + 1
69  *   F.<f> = GF(32, modulus=F_mod, repr='int') # GF(32) definition
70  *   FP.<x> = F[] # Polynomials over GF(32)
71  *   E_mod = x**3 + x + F.fetch_int(8)
72  *   E.<e> = F.extension(E_mod) # Extension field definition
73  *   alpha = e**2743 # Choice of an element in extension field
74  *   for p in divisors(E.order() - 1): # Verify alpha has order 32767.
75  *       assert((alpha**p == 1) == (p % 32767 == 0))
76  *   G = lcm([(alpha**i).minpoly() for i in [1056,1057,1058]] + [x + 1])
77  *   print(G) # Print out the generator
78  *   for i in [1,2,4,8,16]: # Print out {1,2,4,8,16}*(G mod x^8), packed in hex integers.
79  *       v = 0
80  *       for coef in reversed((F.fetch_int(i)*(G % x**8)).coefficients(sparse=True)):
81  *           v = v*32 + coef.integer_representation()
82  *       print("0x%x" % v)
83  */
PolyMod(uint64_t c,int val)84 uint64_t PolyMod(uint64_t c, int val)
85 {
86     uint8_t c0 = c >> 35;
87     c = ((c & 0x7ffffffff) << 5) ^ val;
88     if (c0 & 1) c ^= 0xf5dee51989;
89     if (c0 & 2) c ^= 0xa9fdca3312;
90     if (c0 & 4) c ^= 0x1bab10e32d;
91     if (c0 & 8) c ^= 0x3706b1677a;
92     if (c0 & 16) c ^= 0x644d626ffd;
93     return c;
94 }
95 
DescriptorChecksum(const Span<const char> & span)96 std::string DescriptorChecksum(const Span<const char>& span)
97 {
98     /** A character set designed such that:
99      *  - The most common 'unprotected' descriptor characters (hex, keypaths) are in the first group of 32.
100      *  - Case errors cause an offset that's a multiple of 32.
101      *  - As many alphabetic characters are in the same group (while following the above restrictions).
102      *
103      * If p(x) gives the position of a character c in this character set, every group of 3 characters
104      * (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).
105      * This means that changes that only affect the lower 5 bits of the position, or only the higher 2 bits, will just
106      * affect a single symbol.
107      *
108      * As a result, within-group-of-32 errors count as 1 symbol, as do cross-group errors that don't affect
109      * the position within the groups.
110      */
111     static std::string INPUT_CHARSET =
112         "0123456789()[],'/*abcdefgh@:$%{}"
113         "IJKLMNOPQRSTUVWXYZ&+-.;<=>?!^_|~"
114         "ijklmnopqrstuvwxyzABCDEFGH`#\"\\ ";
115 
116     /** The character set for the checksum itself (same as bech32). */
117     static std::string CHECKSUM_CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
118 
119     uint64_t c = 1;
120     int cls = 0;
121     int clscount = 0;
122     for (auto ch : span) {
123         auto pos = INPUT_CHARSET.find(ch);
124         if (pos == std::string::npos) return "";
125         c = PolyMod(c, pos & 31); // Emit a symbol for the position inside the group, for every character.
126         cls = cls * 3 + (pos >> 5); // Accumulate the group numbers
127         if (++clscount == 3) {
128             // Emit an extra symbol representing the group numbers, for every 3 characters.
129             c = PolyMod(c, cls);
130             cls = 0;
131             clscount = 0;
132         }
133     }
134     if (clscount > 0) c = PolyMod(c, cls);
135     for (int j = 0; j < 8; ++j) c = PolyMod(c, 0); // Shift further to determine the checksum.
136     c ^= 1; // Prevent appending zeroes from not affecting the checksum.
137 
138     std::string ret(8, ' ');
139     for (int j = 0; j < 8; ++j) ret[j] = CHECKSUM_CHARSET[(c >> (5 * (7 - j))) & 31];
140     return ret;
141 }
142 
AddChecksum(const std::string & str)143 std::string AddChecksum(const std::string& str) { return str + "#" + DescriptorChecksum(str); }
144 
145 ////////////////////////////////////////////////////////////////////////////
146 // Internal representation                                                //
147 ////////////////////////////////////////////////////////////////////////////
148 
149 typedef std::vector<uint32_t> KeyPath;
150 
151 /** Interface for public key objects in descriptors. */
152 struct PubkeyProvider
153 {
154 protected:
155     //! Index of this key expression in the descriptor
156     //! E.g. If this PubkeyProvider is key1 in multi(2, key1, key2, key3), then m_expr_index = 0
157     uint32_t m_expr_index;
158 
159 public:
PubkeyProvider__anonaf76fbc70111::PubkeyProvider160     explicit PubkeyProvider(uint32_t exp_index) : m_expr_index(exp_index) {}
161 
162     virtual ~PubkeyProvider() = default;
163 
164     /** Derive a public key.
165      *  read_cache is the cache to read keys from (if not nullptr)
166      *  write_cache is the cache to write keys to (if not nullptr)
167      *  Caches are not exclusive but this is not tested. Currently we use them exclusively
168      */
169     virtual bool GetPubKey(int pos, const SigningProvider& arg, CPubKey& key, KeyOriginInfo& info, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const = 0;
170 
171     /** Whether this represent multiple public keys at different positions. */
172     virtual bool IsRange() const = 0;
173 
174     /** Get the size of the generated public key(s) in bytes (33 or 65). */
175     virtual size_t GetSize() const = 0;
176 
177     /** Get the descriptor string form. */
178     virtual std::string ToString() const = 0;
179 
180     /** Get the descriptor string form including private data (if available in arg). */
181     virtual bool ToPrivateString(const SigningProvider& arg, std::string& out) const = 0;
182 
183     /** Get the descriptor string form with the xpub at the last hardened derivation */
184     virtual bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache = nullptr) const = 0;
185 
186     /** Derive a private key, if private data is available in arg. */
187     virtual bool GetPrivKey(int pos, const SigningProvider& arg, CKey& key) const = 0;
188 };
189 
190 class OriginPubkeyProvider final : public PubkeyProvider
191 {
192     KeyOriginInfo m_origin;
193     std::unique_ptr<PubkeyProvider> m_provider;
194 
OriginString() const195     std::string OriginString() const
196     {
197         return HexStr(m_origin.fingerprint) + FormatHDKeypath(m_origin.path);
198     }
199 
200 public:
OriginPubkeyProvider(uint32_t exp_index,KeyOriginInfo info,std::unique_ptr<PubkeyProvider> provider)201     OriginPubkeyProvider(uint32_t exp_index, KeyOriginInfo info, std::unique_ptr<PubkeyProvider> provider) : PubkeyProvider(exp_index), m_origin(std::move(info)), m_provider(std::move(provider)) {}
GetPubKey(int pos,const SigningProvider & arg,CPubKey & key,KeyOriginInfo & info,const DescriptorCache * read_cache=nullptr,DescriptorCache * write_cache=nullptr) const202     bool GetPubKey(int pos, const SigningProvider& arg, CPubKey& key, KeyOriginInfo& info, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
203     {
204         if (!m_provider->GetPubKey(pos, arg, key, info, read_cache, write_cache)) return false;
205         std::copy(std::begin(m_origin.fingerprint), std::end(m_origin.fingerprint), info.fingerprint);
206         info.path.insert(info.path.begin(), m_origin.path.begin(), m_origin.path.end());
207         return true;
208     }
IsRange() const209     bool IsRange() const override { return m_provider->IsRange(); }
GetSize() const210     size_t GetSize() const override { return m_provider->GetSize(); }
ToString() const211     std::string ToString() const override { return "[" + OriginString() + "]" + m_provider->ToString(); }
ToPrivateString(const SigningProvider & arg,std::string & ret) const212     bool ToPrivateString(const SigningProvider& arg, std::string& ret) const override
213     {
214         std::string sub;
215         if (!m_provider->ToPrivateString(arg, sub)) return false;
216         ret = "[" + OriginString() + "]" + std::move(sub);
217         return true;
218     }
ToNormalizedString(const SigningProvider & arg,std::string & ret,const DescriptorCache * cache) const219     bool ToNormalizedString(const SigningProvider& arg, std::string& ret, const DescriptorCache* cache) const override
220     {
221         std::string sub;
222         if (!m_provider->ToNormalizedString(arg, sub, cache)) return false;
223         // If m_provider is a BIP32PubkeyProvider, we may get a string formatted like a OriginPubkeyProvider
224         // In that case, we need to strip out the leading square bracket and fingerprint from the substring,
225         // and append that to our own origin string.
226         if (sub[0] == '[') {
227             sub = sub.substr(9);
228             ret = "[" + OriginString() + std::move(sub);
229         } else {
230             ret = "[" + OriginString() + "]" + std::move(sub);
231         }
232         return true;
233     }
GetPrivKey(int pos,const SigningProvider & arg,CKey & key) const234     bool GetPrivKey(int pos, const SigningProvider& arg, CKey& key) const override
235     {
236         return m_provider->GetPrivKey(pos, arg, key);
237     }
238 };
239 
240 /** An object representing a parsed constant public key in a descriptor. */
241 class ConstPubkeyProvider final : public PubkeyProvider
242 {
243     CPubKey m_pubkey;
244     bool m_xonly;
245 
246 public:
ConstPubkeyProvider(uint32_t exp_index,const CPubKey & pubkey,bool xonly)247     ConstPubkeyProvider(uint32_t exp_index, const CPubKey& pubkey, bool xonly) : PubkeyProvider(exp_index), m_pubkey(pubkey), m_xonly(xonly) {}
GetPubKey(int pos,const SigningProvider & arg,CPubKey & key,KeyOriginInfo & info,const DescriptorCache * read_cache=nullptr,DescriptorCache * write_cache=nullptr) const248     bool GetPubKey(int pos, const SigningProvider& arg, CPubKey& key, KeyOriginInfo& info, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
249     {
250         key = m_pubkey;
251         info.path.clear();
252         CKeyID keyid = m_pubkey.GetID();
253         std::copy(keyid.begin(), keyid.begin() + sizeof(info.fingerprint), info.fingerprint);
254         return true;
255     }
IsRange() const256     bool IsRange() const override { return false; }
GetSize() const257     size_t GetSize() const override { return m_pubkey.size(); }
ToString() const258     std::string ToString() const override { return m_xonly ? HexStr(m_pubkey).substr(2) : HexStr(m_pubkey); }
ToPrivateString(const SigningProvider & arg,std::string & ret) const259     bool ToPrivateString(const SigningProvider& arg, std::string& ret) const override
260     {
261         CKey key;
262         if (!arg.GetKey(m_pubkey.GetID(), key)) return false;
263         ret = EncodeSecret(key);
264         return true;
265     }
ToNormalizedString(const SigningProvider & arg,std::string & ret,const DescriptorCache * cache) const266     bool ToNormalizedString(const SigningProvider& arg, std::string& ret, const DescriptorCache* cache) const override
267     {
268         ret = ToString();
269         return true;
270     }
GetPrivKey(int pos,const SigningProvider & arg,CKey & key) const271     bool GetPrivKey(int pos, const SigningProvider& arg, CKey& key) const override
272     {
273         return arg.GetKey(m_pubkey.GetID(), key);
274     }
275 };
276 
277 enum class DeriveType {
278     NO,
279     UNHARDENED,
280     HARDENED,
281 };
282 
283 /** An object representing a parsed extended public key in a descriptor. */
284 class BIP32PubkeyProvider final : public PubkeyProvider
285 {
286     // Root xpub, path, and final derivation step type being used, if any
287     CExtPubKey m_root_extkey;
288     KeyPath m_path;
289     DeriveType m_derive;
290 
GetExtKey(const SigningProvider & arg,CExtKey & ret) const291     bool GetExtKey(const SigningProvider& arg, CExtKey& ret) const
292     {
293         CKey key;
294         if (!arg.GetKey(m_root_extkey.pubkey.GetID(), key)) return false;
295         ret.nDepth = m_root_extkey.nDepth;
296         std::copy(m_root_extkey.vchFingerprint, m_root_extkey.vchFingerprint + sizeof(ret.vchFingerprint), ret.vchFingerprint);
297         ret.nChild = m_root_extkey.nChild;
298         ret.chaincode = m_root_extkey.chaincode;
299         ret.key = key;
300         return true;
301     }
302 
303     // Derives the last xprv
GetDerivedExtKey(const SigningProvider & arg,CExtKey & xprv,CExtKey & last_hardened) const304     bool GetDerivedExtKey(const SigningProvider& arg, CExtKey& xprv, CExtKey& last_hardened) const
305     {
306         if (!GetExtKey(arg, xprv)) return false;
307         for (auto entry : m_path) {
308             xprv.Derive(xprv, entry);
309             if (entry >> 31) {
310                 last_hardened = xprv;
311             }
312         }
313         return true;
314     }
315 
IsHardened() const316     bool IsHardened() const
317     {
318         if (m_derive == DeriveType::HARDENED) return true;
319         for (auto entry : m_path) {
320             if (entry >> 31) return true;
321         }
322         return false;
323     }
324 
325 public:
BIP32PubkeyProvider(uint32_t exp_index,const CExtPubKey & extkey,KeyPath path,DeriveType derive)326     BIP32PubkeyProvider(uint32_t exp_index, const CExtPubKey& extkey, KeyPath path, DeriveType derive) : PubkeyProvider(exp_index), m_root_extkey(extkey), m_path(std::move(path)), m_derive(derive) {}
IsRange() const327     bool IsRange() const override { return m_derive != DeriveType::NO; }
GetSize() const328     size_t GetSize() const override { return 33; }
GetPubKey(int pos,const SigningProvider & arg,CPubKey & key_out,KeyOriginInfo & final_info_out,const DescriptorCache * read_cache=nullptr,DescriptorCache * write_cache=nullptr) const329     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
330     {
331         // Info of parent of the to be derived pubkey
332         KeyOriginInfo parent_info;
333         CKeyID keyid = m_root_extkey.pubkey.GetID();
334         std::copy(keyid.begin(), keyid.begin() + sizeof(parent_info.fingerprint), parent_info.fingerprint);
335         parent_info.path = m_path;
336 
337         // Info of the derived key itself which is copied out upon successful completion
338         KeyOriginInfo final_info_out_tmp = parent_info;
339         if (m_derive == DeriveType::UNHARDENED) final_info_out_tmp.path.push_back((uint32_t)pos);
340         if (m_derive == DeriveType::HARDENED) final_info_out_tmp.path.push_back(((uint32_t)pos) | 0x80000000L);
341 
342         // Derive keys or fetch them from cache
343         CExtPubKey final_extkey = m_root_extkey;
344         CExtPubKey parent_extkey = m_root_extkey;
345         CExtPubKey last_hardened_extkey;
346         bool der = true;
347         if (read_cache) {
348             if (!read_cache->GetCachedDerivedExtPubKey(m_expr_index, pos, final_extkey)) {
349                 if (m_derive == DeriveType::HARDENED) return false;
350                 // Try to get the derivation parent
351                 if (!read_cache->GetCachedParentExtPubKey(m_expr_index, parent_extkey)) return false;
352                 final_extkey = parent_extkey;
353                 if (m_derive == DeriveType::UNHARDENED) der = parent_extkey.Derive(final_extkey, pos);
354             }
355         } else if (IsHardened()) {
356             CExtKey xprv;
357             CExtKey lh_xprv;
358             if (!GetDerivedExtKey(arg, xprv, lh_xprv)) return false;
359             parent_extkey = xprv.Neuter();
360             if (m_derive == DeriveType::UNHARDENED) der = xprv.Derive(xprv, pos);
361             if (m_derive == DeriveType::HARDENED) der = xprv.Derive(xprv, pos | 0x80000000UL);
362             final_extkey = xprv.Neuter();
363             if (lh_xprv.key.IsValid()) {
364                 last_hardened_extkey = lh_xprv.Neuter();
365             }
366         } else {
367             for (auto entry : m_path) {
368                 der = parent_extkey.Derive(parent_extkey, entry);
369                 assert(der);
370             }
371             final_extkey = parent_extkey;
372             if (m_derive == DeriveType::UNHARDENED) der = parent_extkey.Derive(final_extkey, pos);
373             assert(m_derive != DeriveType::HARDENED);
374         }
375         assert(der);
376 
377         final_info_out = final_info_out_tmp;
378         key_out = final_extkey.pubkey;
379 
380         if (write_cache) {
381             // Only cache parent if there is any unhardened derivation
382             if (m_derive != DeriveType::HARDENED) {
383                 write_cache->CacheParentExtPubKey(m_expr_index, parent_extkey);
384                 // Cache last hardened xpub if we have it
385                 if (last_hardened_extkey.pubkey.IsValid()) {
386                     write_cache->CacheLastHardenedExtPubKey(m_expr_index, last_hardened_extkey);
387                 }
388             } else if (final_info_out.path.size() > 0) {
389                 write_cache->CacheDerivedExtPubKey(m_expr_index, pos, final_extkey);
390             }
391         }
392 
393         return true;
394     }
ToString() const395     std::string ToString() const override
396     {
397         std::string ret = EncodeExtPubKey(m_root_extkey) + FormatHDKeypath(m_path);
398         if (IsRange()) {
399             ret += "/*";
400             if (m_derive == DeriveType::HARDENED) ret += '\'';
401         }
402         return ret;
403     }
ToPrivateString(const SigningProvider & arg,std::string & out) const404     bool ToPrivateString(const SigningProvider& arg, std::string& out) const override
405     {
406         CExtKey key;
407         if (!GetExtKey(arg, key)) return false;
408         out = EncodeExtKey(key) + FormatHDKeypath(m_path);
409         if (IsRange()) {
410             out += "/*";
411             if (m_derive == DeriveType::HARDENED) out += '\'';
412         }
413         return true;
414     }
ToNormalizedString(const SigningProvider & arg,std::string & out,const DescriptorCache * cache) const415     bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache) const override
416     {
417         // For hardened derivation type, just return the typical string, nothing to normalize
418         if (m_derive == DeriveType::HARDENED) {
419             out = ToString();
420             return true;
421         }
422         // Step backwards to find the last hardened step in the path
423         int i = (int)m_path.size() - 1;
424         for (; i >= 0; --i) {
425             if (m_path.at(i) >> 31) {
426                 break;
427             }
428         }
429         // Either no derivation or all unhardened derivation
430         if (i == -1) {
431             out = ToString();
432             return true;
433         }
434         // Get the path to the last hardened stup
435         KeyOriginInfo origin;
436         int k = 0;
437         for (; k <= i; ++k) {
438             // Add to the path
439             origin.path.push_back(m_path.at(k));
440         }
441         // Build the remaining path
442         KeyPath end_path;
443         for (; k < (int)m_path.size(); ++k) {
444             end_path.push_back(m_path.at(k));
445         }
446         // Get the fingerprint
447         CKeyID id = m_root_extkey.pubkey.GetID();
448         std::copy(id.begin(), id.begin() + 4, origin.fingerprint);
449 
450         CExtPubKey xpub;
451         CExtKey lh_xprv;
452         // If we have the cache, just get the parent xpub
453         if (cache != nullptr) {
454             cache->GetCachedLastHardenedExtPubKey(m_expr_index, xpub);
455         }
456         if (!xpub.pubkey.IsValid()) {
457             // Cache miss, or nor cache, or need privkey
458             CExtKey xprv;
459             if (!GetDerivedExtKey(arg, xprv, lh_xprv)) return false;
460             xpub = lh_xprv.Neuter();
461         }
462         assert(xpub.pubkey.IsValid());
463 
464         // Build the string
465         std::string origin_str = HexStr(origin.fingerprint) + FormatHDKeypath(origin.path);
466         out = "[" + origin_str + "]" + EncodeExtPubKey(xpub) + FormatHDKeypath(end_path);
467         if (IsRange()) {
468             out += "/*";
469             assert(m_derive == DeriveType::UNHARDENED);
470         }
471         return true;
472     }
GetPrivKey(int pos,const SigningProvider & arg,CKey & key) const473     bool GetPrivKey(int pos, const SigningProvider& arg, CKey& key) const override
474     {
475         CExtKey extkey;
476         CExtKey dummy;
477         if (!GetDerivedExtKey(arg, extkey, dummy)) return false;
478         if (m_derive == DeriveType::UNHARDENED) extkey.Derive(extkey, pos);
479         if (m_derive == DeriveType::HARDENED) extkey.Derive(extkey, pos | 0x80000000UL);
480         key = extkey.key;
481         return true;
482     }
483 };
484 
485 /** Base class for all Descriptor implementations. */
486 class DescriptorImpl : public Descriptor
487 {
488     //! Public key arguments for this descriptor (size 1 for PK, PKH, WPKH; any size for Multisig).
489     const std::vector<std::unique_ptr<PubkeyProvider>> m_pubkey_args;
490     //! The string name of the descriptor function.
491     const std::string m_name;
492 
493 protected:
494     //! The sub-descriptor arguments (empty for everything but SH and WSH).
495     //! In doc/descriptors.m this is referred to as SCRIPT expressions sh(SCRIPT)
496     //! and wsh(SCRIPT), and distinct from KEY expressions and ADDR expressions.
497     //! Subdescriptors can only ever generate a single script.
498     const std::vector<std::unique_ptr<DescriptorImpl>> m_subdescriptor_args;
499 
500     //! Return a serialization of anything except pubkey and script arguments, to be prepended to those.
ToStringExtra() const501     virtual std::string ToStringExtra() const { return ""; }
502 
503     /** A helper function to construct the scripts for this descriptor.
504      *
505      *  This function is invoked once by ExpandHelper.
506      *
507      *  @param pubkeys The evaluations of the m_pubkey_args field.
508      *  @param scripts The evaluations of m_subdescriptor_args (one for each m_subdescriptor_args element).
509      *  @param out A FlatSigningProvider to put scripts or public keys in that are necessary to the solver.
510      *             The origin info of the provided pubkeys is automatically added.
511      *  @return A vector with scriptPubKeys for this descriptor.
512      */
513     virtual std::vector<CScript> MakeScripts(const std::vector<CPubKey>& pubkeys, Span<const CScript> scripts, FlatSigningProvider& out) const = 0;
514 
515 public:
DescriptorImpl(std::vector<std::unique_ptr<PubkeyProvider>> pubkeys,const std::string & name)516     DescriptorImpl(std::vector<std::unique_ptr<PubkeyProvider>> pubkeys, const std::string& name) : m_pubkey_args(std::move(pubkeys)), m_name(name), m_subdescriptor_args() {}
DescriptorImpl(std::vector<std::unique_ptr<PubkeyProvider>> pubkeys,std::unique_ptr<DescriptorImpl> script,const std::string & name)517     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))) {}
DescriptorImpl(std::vector<std::unique_ptr<PubkeyProvider>> pubkeys,std::vector<std::unique_ptr<DescriptorImpl>> scripts,const std::string & name)518     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)) {}
519 
520     enum class StringType
521     {
522         PUBLIC,
523         PRIVATE,
524         NORMALIZED,
525     };
526 
IsSolvable() const527     bool IsSolvable() const override
528     {
529         for (const auto& arg : m_subdescriptor_args) {
530             if (!arg->IsSolvable()) return false;
531         }
532         return true;
533     }
534 
IsRange() const535     bool IsRange() const final
536     {
537         for (const auto& pubkey : m_pubkey_args) {
538             if (pubkey->IsRange()) return true;
539         }
540         for (const auto& arg : m_subdescriptor_args) {
541             if (arg->IsRange()) return true;
542         }
543         return false;
544     }
545 
ToStringSubScriptHelper(const SigningProvider * arg,std::string & ret,const StringType type,const DescriptorCache * cache=nullptr) const546     virtual bool ToStringSubScriptHelper(const SigningProvider* arg, std::string& ret, const StringType type, const DescriptorCache* cache = nullptr) const
547     {
548         size_t pos = 0;
549         for (const auto& scriptarg : m_subdescriptor_args) {
550             if (pos++) ret += ",";
551             std::string tmp;
552             if (!scriptarg->ToStringHelper(arg, tmp, type, cache)) return false;
553             ret += std::move(tmp);
554         }
555         return true;
556     }
557 
ToStringHelper(const SigningProvider * arg,std::string & out,const StringType type,const DescriptorCache * cache=nullptr) const558     bool ToStringHelper(const SigningProvider* arg, std::string& out, const StringType type, const DescriptorCache* cache = nullptr) const
559     {
560         std::string extra = ToStringExtra();
561         size_t pos = extra.size() > 0 ? 1 : 0;
562         std::string ret = m_name + "(" + extra;
563         for (const auto& pubkey : m_pubkey_args) {
564             if (pos++) ret += ",";
565             std::string tmp;
566             switch (type) {
567                 case StringType::NORMALIZED:
568                     if (!pubkey->ToNormalizedString(*arg, tmp, cache)) return false;
569                     break;
570                 case StringType::PRIVATE:
571                     if (!pubkey->ToPrivateString(*arg, tmp)) return false;
572                     break;
573                 case StringType::PUBLIC:
574                     tmp = pubkey->ToString();
575                     break;
576             }
577             ret += std::move(tmp);
578         }
579         std::string subscript;
580         if (!ToStringSubScriptHelper(arg, subscript, type, cache)) return false;
581         if (pos && subscript.size()) ret += ',';
582         out = std::move(ret) + std::move(subscript) + ")";
583         return true;
584     }
585 
ToString() const586     std::string ToString() const final
587     {
588         std::string ret;
589         ToStringHelper(nullptr, ret, StringType::PUBLIC);
590         return AddChecksum(ret);
591     }
592 
ToPrivateString(const SigningProvider & arg,std::string & out) const593     bool ToPrivateString(const SigningProvider& arg, std::string& out) const final
594     {
595         bool ret = ToStringHelper(&arg, out, StringType::PRIVATE);
596         out = AddChecksum(out);
597         return ret;
598     }
599 
ToNormalizedString(const SigningProvider & arg,std::string & out,const DescriptorCache * cache) const600     bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache) const override final
601     {
602         bool ret = ToStringHelper(&arg, out, StringType::NORMALIZED, cache);
603         out = AddChecksum(out);
604         return ret;
605     }
606 
ExpandHelper(int pos,const SigningProvider & arg,const DescriptorCache * read_cache,std::vector<CScript> & output_scripts,FlatSigningProvider & out,DescriptorCache * write_cache) const607     bool ExpandHelper(int pos, const SigningProvider& arg, const DescriptorCache* read_cache, std::vector<CScript>& output_scripts, FlatSigningProvider& out, DescriptorCache* write_cache) const
608     {
609         std::vector<std::pair<CPubKey, KeyOriginInfo>> entries;
610         entries.reserve(m_pubkey_args.size());
611 
612         // Construct temporary data in `entries`, `subscripts`, and `subprovider` to avoid producing output in case of failure.
613         for (const auto& p : m_pubkey_args) {
614             entries.emplace_back();
615             if (!p->GetPubKey(pos, arg, entries.back().first, entries.back().second, read_cache, write_cache)) return false;
616         }
617         std::vector<CScript> subscripts;
618         FlatSigningProvider subprovider;
619         for (const auto& subarg : m_subdescriptor_args) {
620             std::vector<CScript> outscripts;
621             if (!subarg->ExpandHelper(pos, arg, read_cache, outscripts, subprovider, write_cache)) return false;
622             assert(outscripts.size() == 1);
623             subscripts.emplace_back(std::move(outscripts[0]));
624         }
625         out = Merge(std::move(out), std::move(subprovider));
626 
627         std::vector<CPubKey> pubkeys;
628         pubkeys.reserve(entries.size());
629         for (auto& entry : entries) {
630             pubkeys.push_back(entry.first);
631             out.origins.emplace(entry.first.GetID(), std::make_pair<CPubKey, KeyOriginInfo>(CPubKey(entry.first), std::move(entry.second)));
632         }
633 
634         output_scripts = MakeScripts(pubkeys, MakeSpan(subscripts), out);
635         return true;
636     }
637 
Expand(int pos,const SigningProvider & provider,std::vector<CScript> & output_scripts,FlatSigningProvider & out,DescriptorCache * write_cache=nullptr) const638     bool Expand(int pos, const SigningProvider& provider, std::vector<CScript>& output_scripts, FlatSigningProvider& out, DescriptorCache* write_cache = nullptr) const final
639     {
640         return ExpandHelper(pos, provider, nullptr, output_scripts, out, write_cache);
641     }
642 
ExpandFromCache(int pos,const DescriptorCache & read_cache,std::vector<CScript> & output_scripts,FlatSigningProvider & out) const643     bool ExpandFromCache(int pos, const DescriptorCache& read_cache, std::vector<CScript>& output_scripts, FlatSigningProvider& out) const final
644     {
645         return ExpandHelper(pos, DUMMY_SIGNING_PROVIDER, &read_cache, output_scripts, out, nullptr);
646     }
647 
ExpandPrivate(int pos,const SigningProvider & provider,FlatSigningProvider & out) const648     void ExpandPrivate(int pos, const SigningProvider& provider, FlatSigningProvider& out) const final
649     {
650         for (const auto& p : m_pubkey_args) {
651             CKey key;
652             if (!p->GetPrivKey(pos, provider, key)) continue;
653             out.keys.emplace(key.GetPubKey().GetID(), key);
654         }
655         for (const auto& arg : m_subdescriptor_args) {
656             arg->ExpandPrivate(pos, provider, out);
657         }
658     }
659 
GetOutputType() const660     std::optional<OutputType> GetOutputType() const override { return std::nullopt; }
661 };
662 
663 /** A parsed addr(A) descriptor. */
664 class AddressDescriptor final : public DescriptorImpl
665 {
666     const CTxDestination m_destination;
667 protected:
ToStringExtra() const668     std::string ToStringExtra() const override { return EncodeDestination(m_destination); }
MakeScripts(const std::vector<CPubKey> &,Span<const CScript>,FlatSigningProvider &) const669     std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, Span<const CScript>, FlatSigningProvider&) const override { return Vector(GetScriptForDestination(m_destination)); }
670 public:
AddressDescriptor(CTxDestination destination)671     AddressDescriptor(CTxDestination destination) : DescriptorImpl({}, "addr"), m_destination(std::move(destination)) {}
IsSolvable() const672     bool IsSolvable() const final { return false; }
673 
GetOutputType() const674     std::optional<OutputType> GetOutputType() const override
675     {
676         return OutputTypeFromDestination(m_destination);
677     }
IsSingleType() const678     bool IsSingleType() const final { return true; }
679 };
680 
681 /** A parsed raw(H) descriptor. */
682 class RawDescriptor final : public DescriptorImpl
683 {
684     const CScript m_script;
685 protected:
ToStringExtra() const686     std::string ToStringExtra() const override { return HexStr(m_script); }
MakeScripts(const std::vector<CPubKey> &,Span<const CScript>,FlatSigningProvider &) const687     std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, Span<const CScript>, FlatSigningProvider&) const override { return Vector(m_script); }
688 public:
RawDescriptor(CScript script)689     RawDescriptor(CScript script) : DescriptorImpl({}, "raw"), m_script(std::move(script)) {}
IsSolvable() const690     bool IsSolvable() const final { return false; }
691 
GetOutputType() const692     std::optional<OutputType> GetOutputType() const override
693     {
694         CTxDestination dest;
695         ExtractDestination(m_script, dest);
696         return OutputTypeFromDestination(dest);
697     }
IsSingleType() const698     bool IsSingleType() const final { return true; }
699 };
700 
701 /** A parsed pk(P) descriptor. */
702 class PKDescriptor final : public DescriptorImpl
703 {
704 private:
705     const bool m_xonly;
706 protected:
MakeScripts(const std::vector<CPubKey> & keys,Span<const CScript>,FlatSigningProvider &) const707     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript>, FlatSigningProvider&) const override
708     {
709         if (m_xonly) {
710             CScript script = CScript() << ToByteVector(XOnlyPubKey(keys[0])) << OP_CHECKSIG;
711             return Vector(std::move(script));
712         } else {
713             return Vector(GetScriptForRawPubKey(keys[0]));
714         }
715     }
716 public:
PKDescriptor(std::unique_ptr<PubkeyProvider> prov,bool xonly=false)717     PKDescriptor(std::unique_ptr<PubkeyProvider> prov, bool xonly = false) : DescriptorImpl(Vector(std::move(prov)), "pk"), m_xonly(xonly) {}
IsSingleType() const718     bool IsSingleType() const final { return true; }
719 };
720 
721 /** A parsed pkh(P) descriptor. */
722 class PKHDescriptor final : public DescriptorImpl
723 {
724 protected:
MakeScripts(const std::vector<CPubKey> & keys,Span<const CScript>,FlatSigningProvider & out) const725     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript>, FlatSigningProvider& out) const override
726     {
727         CKeyID id = keys[0].GetID();
728         out.pubkeys.emplace(id, keys[0]);
729         return Vector(GetScriptForDestination(PKHash(id)));
730     }
731 public:
PKHDescriptor(std::unique_ptr<PubkeyProvider> prov)732     PKHDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "pkh") {}
GetOutputType() const733     std::optional<OutputType> GetOutputType() const override { return OutputType::LEGACY; }
IsSingleType() const734     bool IsSingleType() const final { return true; }
735 };
736 
737 /** A parsed wpkh(P) descriptor. */
738 class WPKHDescriptor final : public DescriptorImpl
739 {
740 protected:
MakeScripts(const std::vector<CPubKey> & keys,Span<const CScript>,FlatSigningProvider & out) const741     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript>, FlatSigningProvider& out) const override
742     {
743         CKeyID id = keys[0].GetID();
744         out.pubkeys.emplace(id, keys[0]);
745         return Vector(GetScriptForDestination(WitnessV0KeyHash(id)));
746     }
747 public:
WPKHDescriptor(std::unique_ptr<PubkeyProvider> prov)748     WPKHDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "wpkh") {}
GetOutputType() const749     std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32; }
IsSingleType() const750     bool IsSingleType() const final { return true; }
751 };
752 
753 /** A parsed combo(P) descriptor. */
754 class ComboDescriptor final : public DescriptorImpl
755 {
756 protected:
MakeScripts(const std::vector<CPubKey> & keys,Span<const CScript>,FlatSigningProvider & out) const757     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript>, FlatSigningProvider& out) const override
758     {
759         std::vector<CScript> ret;
760         CKeyID id = keys[0].GetID();
761         out.pubkeys.emplace(id, keys[0]);
762         ret.emplace_back(GetScriptForRawPubKey(keys[0])); // P2PK
763         ret.emplace_back(GetScriptForDestination(PKHash(id))); // P2PKH
764         if (keys[0].IsCompressed()) {
765             CScript p2wpkh = GetScriptForDestination(WitnessV0KeyHash(id));
766             out.scripts.emplace(CScriptID(p2wpkh), p2wpkh);
767             ret.emplace_back(p2wpkh);
768             ret.emplace_back(GetScriptForDestination(ScriptHash(p2wpkh))); // P2SH-P2WPKH
769         }
770         return ret;
771     }
772 public:
ComboDescriptor(std::unique_ptr<PubkeyProvider> prov)773     ComboDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "combo") {}
IsSingleType() const774     bool IsSingleType() const final { return false; }
775 };
776 
777 /** A parsed multi(...) or sortedmulti(...) descriptor */
778 class MultisigDescriptor final : public DescriptorImpl
779 {
780     const int m_threshold;
781     const bool m_sorted;
782 protected:
ToStringExtra() const783     std::string ToStringExtra() const override { return strprintf("%i", m_threshold); }
MakeScripts(const std::vector<CPubKey> & keys,Span<const CScript>,FlatSigningProvider &) const784     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript>, FlatSigningProvider&) const override {
785         if (m_sorted) {
786             std::vector<CPubKey> sorted_keys(keys);
787             std::sort(sorted_keys.begin(), sorted_keys.end());
788             return Vector(GetScriptForMultisig(m_threshold, sorted_keys));
789         }
790         return Vector(GetScriptForMultisig(m_threshold, keys));
791     }
792 public:
MultisigDescriptor(int threshold,std::vector<std::unique_ptr<PubkeyProvider>> providers,bool sorted=false)793     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) {}
IsSingleType() const794     bool IsSingleType() const final { return true; }
795 };
796 
797 /** A parsed sh(...) descriptor. */
798 class SHDescriptor final : public DescriptorImpl
799 {
800 protected:
MakeScripts(const std::vector<CPubKey> &,Span<const CScript> scripts,FlatSigningProvider & out) const801     std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, Span<const CScript> scripts, FlatSigningProvider& out) const override
802     {
803         auto ret = Vector(GetScriptForDestination(ScriptHash(scripts[0])));
804         if (ret.size()) out.scripts.emplace(CScriptID(scripts[0]), scripts[0]);
805         return ret;
806     }
807 public:
SHDescriptor(std::unique_ptr<DescriptorImpl> desc)808     SHDescriptor(std::unique_ptr<DescriptorImpl> desc) : DescriptorImpl({}, std::move(desc), "sh") {}
809 
GetOutputType() const810     std::optional<OutputType> GetOutputType() const override
811     {
812         assert(m_subdescriptor_args.size() == 1);
813         if (m_subdescriptor_args[0]->GetOutputType() == OutputType::BECH32) return OutputType::P2SH_SEGWIT;
814         return OutputType::LEGACY;
815     }
IsSingleType() const816     bool IsSingleType() const final { return true; }
817 };
818 
819 /** A parsed wsh(...) descriptor. */
820 class WSHDescriptor final : public DescriptorImpl
821 {
822 protected:
MakeScripts(const std::vector<CPubKey> &,Span<const CScript> scripts,FlatSigningProvider & out) const823     std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, Span<const CScript> scripts, FlatSigningProvider& out) const override
824     {
825         auto ret = Vector(GetScriptForDestination(WitnessV0ScriptHash(scripts[0])));
826         if (ret.size()) out.scripts.emplace(CScriptID(scripts[0]), scripts[0]);
827         return ret;
828     }
829 public:
WSHDescriptor(std::unique_ptr<DescriptorImpl> desc)830     WSHDescriptor(std::unique_ptr<DescriptorImpl> desc) : DescriptorImpl({}, std::move(desc), "wsh") {}
GetOutputType() const831     std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32; }
IsSingleType() const832     bool IsSingleType() const final { return true; }
833 };
834 
835 /** A parsed tr(...) descriptor. */
836 class TRDescriptor final : public DescriptorImpl
837 {
838     std::vector<int> m_depths;
839 protected:
MakeScripts(const std::vector<CPubKey> & keys,Span<const CScript> scripts,FlatSigningProvider & out) const840     std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript> scripts, FlatSigningProvider& out) const override
841     {
842         TaprootBuilder builder;
843         assert(m_depths.size() == scripts.size());
844         for (size_t pos = 0; pos < m_depths.size(); ++pos) {
845             builder.Add(m_depths[pos], scripts[pos], TAPROOT_LEAF_TAPSCRIPT);
846         }
847         if (!builder.IsComplete()) return {};
848         assert(keys.size() == 1);
849         XOnlyPubKey xpk(keys[0]);
850         if (!xpk.IsFullyValid()) return {};
851         builder.Finalize(xpk);
852         WitnessV1Taproot output = builder.GetOutput();
853         out.tr_spenddata[output].Merge(builder.GetSpendData());
854         return Vector(GetScriptForDestination(output));
855     }
ToStringSubScriptHelper(const SigningProvider * arg,std::string & ret,const StringType type,const DescriptorCache * cache=nullptr) const856     bool ToStringSubScriptHelper(const SigningProvider* arg, std::string& ret, const StringType type, const DescriptorCache* cache = nullptr) const override
857     {
858         if (m_depths.empty()) return true;
859         std::vector<bool> path;
860         for (size_t pos = 0; pos < m_depths.size(); ++pos) {
861             if (pos) ret += ',';
862             while ((int)path.size() <= m_depths[pos]) {
863                 if (path.size()) ret += '{';
864                 path.push_back(false);
865             }
866             std::string tmp;
867             if (!m_subdescriptor_args[pos]->ToStringHelper(arg, tmp, type, cache)) return false;
868             ret += std::move(tmp);
869             while (!path.empty() && path.back()) {
870                 if (path.size() > 1) ret += '}';
871                 path.pop_back();
872             }
873             if (!path.empty()) path.back() = true;
874         }
875         return true;
876     }
877 public:
TRDescriptor(std::unique_ptr<PubkeyProvider> internal_key,std::vector<std::unique_ptr<DescriptorImpl>> descs,std::vector<int> depths)878     TRDescriptor(std::unique_ptr<PubkeyProvider> internal_key, std::vector<std::unique_ptr<DescriptorImpl>> descs, std::vector<int> depths) :
879         DescriptorImpl(Vector(std::move(internal_key)), std::move(descs), "tr"), m_depths(std::move(depths))
880     {
881         assert(m_subdescriptor_args.size() == m_depths.size());
882     }
GetOutputType() const883     std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32M; }
IsSingleType() const884     bool IsSingleType() const final { return true; }
885 };
886 
887 ////////////////////////////////////////////////////////////////////////////
888 // Parser                                                                 //
889 ////////////////////////////////////////////////////////////////////////////
890 
891 enum class ParseScriptContext {
892     TOP,     //!< Top-level context (script goes directly in scriptPubKey)
893     P2SH,    //!< Inside sh() (script becomes P2SH redeemScript)
894     P2WPKH,  //!< Inside wpkh() (no script, pubkey only)
895     P2WSH,   //!< Inside wsh() (script becomes v0 witness script)
896     P2TR,    //!< Inside tr() (either internal key, or BIP342 script leaf)
897 };
898 
899 /** Parse a key path, being passed a split list of elements (the first element is ignored). */
ParseKeyPath(const std::vector<Span<const char>> & split,KeyPath & out,std::string & error)900 [[nodiscard]] bool ParseKeyPath(const std::vector<Span<const char>>& split, KeyPath& out, std::string& error)
901 {
902     for (size_t i = 1; i < split.size(); ++i) {
903         Span<const char> elem = split[i];
904         bool hardened = false;
905         if (elem.size() > 0 && (elem[elem.size() - 1] == '\'' || elem[elem.size() - 1] == 'h')) {
906             elem = elem.first(elem.size() - 1);
907             hardened = true;
908         }
909         uint32_t p;
910         if (!ParseUInt32(std::string(elem.begin(), elem.end()), &p)) {
911             error = strprintf("Key path value '%s' is not a valid uint32", std::string(elem.begin(), elem.end()));
912             return false;
913         } else if (p > 0x7FFFFFFFUL) {
914             error = strprintf("Key path value %u is out of range", p);
915             return false;
916         }
917         out.push_back(p | (((uint32_t)hardened) << 31));
918     }
919     return true;
920 }
921 
922 /** Parse a public key that excludes origin information. */
ParsePubkeyInner(uint32_t key_exp_index,const Span<const char> & sp,ParseScriptContext ctx,FlatSigningProvider & out,std::string & error)923 std::unique_ptr<PubkeyProvider> ParsePubkeyInner(uint32_t key_exp_index, const Span<const char>& sp, ParseScriptContext ctx, FlatSigningProvider& out, std::string& error)
924 {
925     using namespace spanparsing;
926 
927     bool permit_uncompressed = ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH;
928     auto split = Split(sp, '/');
929     std::string str(split[0].begin(), split[0].end());
930     if (str.size() == 0) {
931         error = "No key provided";
932         return nullptr;
933     }
934     if (split.size() == 1) {
935         if (IsHex(str)) {
936             std::vector<unsigned char> data = ParseHex(str);
937             CPubKey pubkey(data);
938             if (pubkey.IsFullyValid()) {
939                 if (permit_uncompressed || pubkey.IsCompressed()) {
940                     return std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, false);
941                 } else {
942                     error = "Uncompressed keys are not allowed";
943                     return nullptr;
944                 }
945             } else if (data.size() == 32 && ctx == ParseScriptContext::P2TR) {
946                 unsigned char fullkey[33] = {0x02};
947                 std::copy(data.begin(), data.end(), fullkey + 1);
948                 pubkey.Set(std::begin(fullkey), std::end(fullkey));
949                 if (pubkey.IsFullyValid()) {
950                     return std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, true);
951                 }
952             }
953             error = strprintf("Pubkey '%s' is invalid", str);
954             return nullptr;
955         }
956         CKey key = DecodeSecret(str);
957         if (key.IsValid()) {
958             if (permit_uncompressed || key.IsCompressed()) {
959                 CPubKey pubkey = key.GetPubKey();
960                 out.keys.emplace(pubkey.GetID(), key);
961                 return std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, ctx == ParseScriptContext::P2TR);
962             } else {
963                 error = "Uncompressed keys are not allowed";
964                 return nullptr;
965             }
966         }
967     }
968     CExtKey extkey = DecodeExtKey(str);
969     CExtPubKey extpubkey = DecodeExtPubKey(str);
970     if (!extkey.key.IsValid() && !extpubkey.pubkey.IsValid()) {
971         error = strprintf("key '%s' is not valid", str);
972         return nullptr;
973     }
974     KeyPath path;
975     DeriveType type = DeriveType::NO;
976     if (split.back() == MakeSpan("*").first(1)) {
977         split.pop_back();
978         type = DeriveType::UNHARDENED;
979     } else if (split.back() == MakeSpan("*'").first(2) || split.back() == MakeSpan("*h").first(2)) {
980         split.pop_back();
981         type = DeriveType::HARDENED;
982     }
983     if (!ParseKeyPath(split, path, error)) return nullptr;
984     if (extkey.key.IsValid()) {
985         extpubkey = extkey.Neuter();
986         out.keys.emplace(extpubkey.pubkey.GetID(), extkey.key);
987     }
988     return std::make_unique<BIP32PubkeyProvider>(key_exp_index, extpubkey, std::move(path), type);
989 }
990 
991 /** Parse a public key including origin information (if enabled). */
ParsePubkey(uint32_t key_exp_index,const Span<const char> & sp,ParseScriptContext ctx,FlatSigningProvider & out,std::string & error)992 std::unique_ptr<PubkeyProvider> ParsePubkey(uint32_t key_exp_index, const Span<const char>& sp, ParseScriptContext ctx, FlatSigningProvider& out, std::string& error)
993 {
994     using namespace spanparsing;
995 
996     auto origin_split = Split(sp, ']');
997     if (origin_split.size() > 2) {
998         error = "Multiple ']' characters found for a single pubkey";
999         return nullptr;
1000     }
1001     if (origin_split.size() == 1) return ParsePubkeyInner(key_exp_index, origin_split[0], ctx, out, error);
1002     if (origin_split[0].empty() || origin_split[0][0] != '[') {
1003         error = strprintf("Key origin start '[ character expected but not found, got '%c' instead",
1004                           origin_split[0].empty() ? /** empty, implies split char */ ']' : origin_split[0][0]);
1005         return nullptr;
1006     }
1007     auto slash_split = Split(origin_split[0].subspan(1), '/');
1008     if (slash_split[0].size() != 8) {
1009         error = strprintf("Fingerprint is not 4 bytes (%u characters instead of 8 characters)", slash_split[0].size());
1010         return nullptr;
1011     }
1012     std::string fpr_hex = std::string(slash_split[0].begin(), slash_split[0].end());
1013     if (!IsHex(fpr_hex)) {
1014         error = strprintf("Fingerprint '%s' is not hex", fpr_hex);
1015         return nullptr;
1016     }
1017     auto fpr_bytes = ParseHex(fpr_hex);
1018     KeyOriginInfo info;
1019     static_assert(sizeof(info.fingerprint) == 4, "Fingerprint must be 4 bytes");
1020     assert(fpr_bytes.size() == 4);
1021     std::copy(fpr_bytes.begin(), fpr_bytes.end(), info.fingerprint);
1022     if (!ParseKeyPath(slash_split, info.path, error)) return nullptr;
1023     auto provider = ParsePubkeyInner(key_exp_index, origin_split[1], ctx, out, error);
1024     if (!provider) return nullptr;
1025     return std::make_unique<OriginPubkeyProvider>(key_exp_index, std::move(info), std::move(provider));
1026 }
1027 
1028 /** Parse a script in a particular context. */
ParseScript(uint32_t & key_exp_index,Span<const char> & sp,ParseScriptContext ctx,FlatSigningProvider & out,std::string & error)1029 std::unique_ptr<DescriptorImpl> ParseScript(uint32_t& key_exp_index, Span<const char>& sp, ParseScriptContext ctx, FlatSigningProvider& out, std::string& error)
1030 {
1031     using namespace spanparsing;
1032 
1033     auto expr = Expr(sp);
1034     bool sorted_multi = false;
1035     if (Func("pk", expr)) {
1036         auto pubkey = ParsePubkey(key_exp_index, expr, ctx, out, error);
1037         if (!pubkey) return nullptr;
1038         ++key_exp_index;
1039         return std::make_unique<PKDescriptor>(std::move(pubkey), ctx == ParseScriptContext::P2TR);
1040     }
1041     if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH) && Func("pkh", expr)) {
1042         auto pubkey = ParsePubkey(key_exp_index, expr, ctx, out, error);
1043         if (!pubkey) return nullptr;
1044         ++key_exp_index;
1045         return std::make_unique<PKHDescriptor>(std::move(pubkey));
1046     } else if (Func("pkh", expr)) {
1047         error = "Can only have pkh at top level, in sh(), or in wsh()";
1048         return nullptr;
1049     }
1050     if (ctx == ParseScriptContext::TOP && Func("combo", expr)) {
1051         auto pubkey = ParsePubkey(key_exp_index, expr, ctx, out, error);
1052         if (!pubkey) return nullptr;
1053         ++key_exp_index;
1054         return std::make_unique<ComboDescriptor>(std::move(pubkey));
1055     } else if (Func("combo", expr)) {
1056         error = "Can only have combo() at top level";
1057         return nullptr;
1058     }
1059     if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH) && ((sorted_multi = Func("sortedmulti", expr)) || Func("multi", expr))) {
1060         auto threshold = Expr(expr);
1061         uint32_t thres;
1062         std::vector<std::unique_ptr<PubkeyProvider>> providers;
1063         if (!ParseUInt32(std::string(threshold.begin(), threshold.end()), &thres)) {
1064             error = strprintf("Multi threshold '%s' is not valid", std::string(threshold.begin(), threshold.end()));
1065             return nullptr;
1066         }
1067         size_t script_size = 0;
1068         while (expr.size()) {
1069             if (!Const(",", expr)) {
1070                 error = strprintf("Multi: expected ',', got '%c'", expr[0]);
1071                 return nullptr;
1072             }
1073             auto arg = Expr(expr);
1074             auto pk = ParsePubkey(key_exp_index, arg, ctx, out, error);
1075             if (!pk) return nullptr;
1076             script_size += pk->GetSize() + 1;
1077             providers.emplace_back(std::move(pk));
1078             key_exp_index++;
1079         }
1080         if (providers.empty() || providers.size() > MAX_PUBKEYS_PER_MULTISIG) {
1081             error = strprintf("Cannot have %u keys in multisig; must have between 1 and %d keys, inclusive", providers.size(), MAX_PUBKEYS_PER_MULTISIG);
1082             return nullptr;
1083         } else if (thres < 1) {
1084             error = strprintf("Multisig threshold cannot be %d, must be at least 1", thres);
1085             return nullptr;
1086         } else if (thres > providers.size()) {
1087             error = strprintf("Multisig threshold cannot be larger than the number of keys; threshold is %d but only %u keys specified", thres, providers.size());
1088             return nullptr;
1089         }
1090         if (ctx == ParseScriptContext::TOP) {
1091             if (providers.size() > 3) {
1092                 error = strprintf("Cannot have %u pubkeys in bare multisig; only at most 3 pubkeys", providers.size());
1093                 return nullptr;
1094             }
1095         }
1096         if (ctx == ParseScriptContext::P2SH) {
1097             // This limits the maximum number of compressed pubkeys to 15.
1098             if (script_size + 3 > MAX_SCRIPT_ELEMENT_SIZE) {
1099                 error = strprintf("P2SH script is too large, %d bytes is larger than %d bytes", script_size + 3, MAX_SCRIPT_ELEMENT_SIZE);
1100                 return nullptr;
1101             }
1102         }
1103         return std::make_unique<MultisigDescriptor>(thres, std::move(providers), sorted_multi);
1104     } else if (Func("sortedmulti", expr) || Func("multi", expr)) {
1105         error = "Can only have multi/sortedmulti at top level, in sh(), or in wsh()";
1106         return nullptr;
1107     }
1108     if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH) && Func("wpkh", expr)) {
1109         auto pubkey = ParsePubkey(key_exp_index, expr, ParseScriptContext::P2WPKH, out, error);
1110         if (!pubkey) return nullptr;
1111         key_exp_index++;
1112         return std::make_unique<WPKHDescriptor>(std::move(pubkey));
1113     } else if (Func("wpkh", expr)) {
1114         error = "Can only have wpkh() at top level or inside sh()";
1115         return nullptr;
1116     }
1117     if (ctx == ParseScriptContext::TOP && Func("sh", expr)) {
1118         auto desc = ParseScript(key_exp_index, expr, ParseScriptContext::P2SH, out, error);
1119         if (!desc || expr.size()) return nullptr;
1120         return std::make_unique<SHDescriptor>(std::move(desc));
1121     } else if (Func("sh", expr)) {
1122         error = "Can only have sh() at top level";
1123         return nullptr;
1124     }
1125     if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH) && Func("wsh", expr)) {
1126         auto desc = ParseScript(key_exp_index, expr, ParseScriptContext::P2WSH, out, error);
1127         if (!desc || expr.size()) return nullptr;
1128         return std::make_unique<WSHDescriptor>(std::move(desc));
1129     } else if (Func("wsh", expr)) {
1130         error = "Can only have wsh() at top level or inside sh()";
1131         return nullptr;
1132     }
1133     if (ctx == ParseScriptContext::TOP && Func("addr", expr)) {
1134         CTxDestination dest = DecodeDestination(std::string(expr.begin(), expr.end()));
1135         if (!IsValidDestination(dest)) {
1136             error = "Address is not valid";
1137             return nullptr;
1138         }
1139         return std::make_unique<AddressDescriptor>(std::move(dest));
1140     } else if (Func("addr", expr)) {
1141         error = "Can only have addr() at top level";
1142         return nullptr;
1143     }
1144     if (ctx == ParseScriptContext::TOP && Func("tr", expr)) {
1145         auto arg = Expr(expr);
1146         auto internal_key = ParsePubkey(key_exp_index, arg, ParseScriptContext::P2TR, out, error);
1147         if (!internal_key) return nullptr;
1148         ++key_exp_index;
1149         std::vector<std::unique_ptr<DescriptorImpl>> subscripts; //!< list of script subexpressions
1150         std::vector<int> depths; //!< depth in the tree of each subexpression (same length subscripts)
1151         if (expr.size()) {
1152             if (!Const(",", expr)) {
1153                 error = strprintf("tr: expected ',', got '%c'", expr[0]);
1154                 return nullptr;
1155             }
1156             /** The path from the top of the tree to what we're currently processing.
1157              * branches[i] == false: left branch in the i'th step from the top; true: right branch.
1158              */
1159             std::vector<bool> branches;
1160             // Loop over all provided scripts. In every iteration exactly one script will be processed.
1161             // Use a do-loop because inside this if-branch we expect at least one script.
1162             do {
1163                 // First process all open braces.
1164                 while (Const("{", expr)) {
1165                     branches.push_back(false); // new left branch
1166                     if (branches.size() > TAPROOT_CONTROL_MAX_NODE_COUNT) {
1167                         error = strprintf("tr() supports at most %i nesting levels", TAPROOT_CONTROL_MAX_NODE_COUNT);
1168                         return nullptr;
1169                     }
1170                 }
1171                 // Process the actual script expression.
1172                 auto sarg = Expr(expr);
1173                 subscripts.emplace_back(ParseScript(key_exp_index, sarg, ParseScriptContext::P2TR, out, error));
1174                 if (!subscripts.back()) return nullptr;
1175                 depths.push_back(branches.size());
1176                 // Process closing braces; one is expected for every right branch we were in.
1177                 while (branches.size() && branches.back()) {
1178                     if (!Const("}", expr)) {
1179                         error = strprintf("tr(): expected '}' after script expression");
1180                         return nullptr;
1181                     }
1182                     branches.pop_back(); // move up one level after encountering '}'
1183                 }
1184                 // If after that, we're at the end of a left branch, expect a comma.
1185                 if (branches.size() && !branches.back()) {
1186                     if (!Const(",", expr)) {
1187                         error = strprintf("tr(): expected ',' after script expression");
1188                         return nullptr;
1189                     }
1190                     branches.back() = true; // And now we're in a right branch.
1191                 }
1192             } while (branches.size());
1193             // After we've explored a whole tree, we must be at the end of the expression.
1194             if (expr.size()) {
1195                 error = strprintf("tr(): expected ')' after script expression");
1196                 return nullptr;
1197             }
1198         }
1199         assert(TaprootBuilder::ValidDepths(depths));
1200         return std::make_unique<TRDescriptor>(std::move(internal_key), std::move(subscripts), std::move(depths));
1201     } else if (Func("tr", expr)) {
1202         error = "Can only have tr at top level";
1203         return nullptr;
1204     }
1205     if (ctx == ParseScriptContext::TOP && Func("raw", expr)) {
1206         std::string str(expr.begin(), expr.end());
1207         if (!IsHex(str)) {
1208             error = "Raw script is not hex";
1209             return nullptr;
1210         }
1211         auto bytes = ParseHex(str);
1212         return std::make_unique<RawDescriptor>(CScript(bytes.begin(), bytes.end()));
1213     } else if (Func("raw", expr)) {
1214         error = "Can only have raw() at top level";
1215         return nullptr;
1216     }
1217     if (ctx == ParseScriptContext::P2SH) {
1218         error = "A function is needed within P2SH";
1219         return nullptr;
1220     } else if (ctx == ParseScriptContext::P2WSH) {
1221         error = "A function is needed within P2WSH";
1222         return nullptr;
1223     }
1224     error = strprintf("%s is not a valid descriptor function", std::string(expr.begin(), expr.end()));
1225     return nullptr;
1226 }
1227 
InferPubkey(const CPubKey & pubkey,ParseScriptContext,const SigningProvider & provider)1228 std::unique_ptr<PubkeyProvider> InferPubkey(const CPubKey& pubkey, ParseScriptContext, const SigningProvider& provider)
1229 {
1230     std::unique_ptr<PubkeyProvider> key_provider = std::make_unique<ConstPubkeyProvider>(0, pubkey, false);
1231     KeyOriginInfo info;
1232     if (provider.GetKeyOrigin(pubkey.GetID(), info)) {
1233         return std::make_unique<OriginPubkeyProvider>(0, std::move(info), std::move(key_provider));
1234     }
1235     return key_provider;
1236 }
1237 
InferXOnlyPubkey(const XOnlyPubKey & xkey,ParseScriptContext ctx,const SigningProvider & provider)1238 std::unique_ptr<PubkeyProvider> InferXOnlyPubkey(const XOnlyPubKey& xkey, ParseScriptContext ctx, const SigningProvider& provider)
1239 {
1240     unsigned char full_key[CPubKey::COMPRESSED_SIZE] = {0x02};
1241     std::copy(xkey.begin(), xkey.end(), full_key + 1);
1242     CPubKey pubkey(full_key);
1243     std::unique_ptr<PubkeyProvider> key_provider = std::make_unique<ConstPubkeyProvider>(0, pubkey, true);
1244     KeyOriginInfo info;
1245     if (provider.GetKeyOrigin(pubkey.GetID(), info)) {
1246         return std::make_unique<OriginPubkeyProvider>(0, std::move(info), std::move(key_provider));
1247     } else {
1248         full_key[0] = 0x03;
1249         pubkey = CPubKey(full_key);
1250         if (provider.GetKeyOrigin(pubkey.GetID(), info)) {
1251             return std::make_unique<OriginPubkeyProvider>(0, std::move(info), std::move(key_provider));
1252         }
1253     }
1254     return key_provider;
1255 }
1256 
InferScript(const CScript & script,ParseScriptContext ctx,const SigningProvider & provider)1257 std::unique_ptr<DescriptorImpl> InferScript(const CScript& script, ParseScriptContext ctx, const SigningProvider& provider)
1258 {
1259     if (ctx == ParseScriptContext::P2TR && script.size() == 34 && script[0] == 32 && script[33] == OP_CHECKSIG) {
1260         XOnlyPubKey key{Span<const unsigned char>{script.data() + 1, script.data() + 33}};
1261         return std::make_unique<PKDescriptor>(InferXOnlyPubkey(key, ctx, provider));
1262     }
1263 
1264     std::vector<std::vector<unsigned char>> data;
1265     TxoutType txntype = Solver(script, data);
1266 
1267     if (txntype == TxoutType::PUBKEY && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
1268         CPubKey pubkey(data[0]);
1269         if (pubkey.IsValid()) {
1270             return std::make_unique<PKDescriptor>(InferPubkey(pubkey, ctx, provider));
1271         }
1272     }
1273     if (txntype == TxoutType::PUBKEYHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
1274         uint160 hash(data[0]);
1275         CKeyID keyid(hash);
1276         CPubKey pubkey;
1277         if (provider.GetPubKey(keyid, pubkey)) {
1278             return std::make_unique<PKHDescriptor>(InferPubkey(pubkey, ctx, provider));
1279         }
1280     }
1281     if (txntype == TxoutType::WITNESS_V0_KEYHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH)) {
1282         uint160 hash(data[0]);
1283         CKeyID keyid(hash);
1284         CPubKey pubkey;
1285         if (provider.GetPubKey(keyid, pubkey)) {
1286             return std::make_unique<WPKHDescriptor>(InferPubkey(pubkey, ctx, provider));
1287         }
1288     }
1289     if (txntype == TxoutType::MULTISIG && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
1290         std::vector<std::unique_ptr<PubkeyProvider>> providers;
1291         for (size_t i = 1; i + 1 < data.size(); ++i) {
1292             CPubKey pubkey(data[i]);
1293             providers.push_back(InferPubkey(pubkey, ctx, provider));
1294         }
1295         return std::make_unique<MultisigDescriptor>((int)data[0][0], std::move(providers));
1296     }
1297     if (txntype == TxoutType::SCRIPTHASH && ctx == ParseScriptContext::TOP) {
1298         uint160 hash(data[0]);
1299         CScriptID scriptid(hash);
1300         CScript subscript;
1301         if (provider.GetCScript(scriptid, subscript)) {
1302             auto sub = InferScript(subscript, ParseScriptContext::P2SH, provider);
1303             if (sub) return std::make_unique<SHDescriptor>(std::move(sub));
1304         }
1305     }
1306     if (txntype == TxoutType::WITNESS_V0_SCRIPTHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH)) {
1307         CScriptID scriptid;
1308         CRIPEMD160().Write(data[0].data(), data[0].size()).Finalize(scriptid.begin());
1309         CScript subscript;
1310         if (provider.GetCScript(scriptid, subscript)) {
1311             auto sub = InferScript(subscript, ParseScriptContext::P2WSH, provider);
1312             if (sub) return std::make_unique<WSHDescriptor>(std::move(sub));
1313         }
1314     }
1315     if (txntype == TxoutType::WITNESS_V1_TAPROOT && ctx == ParseScriptContext::TOP) {
1316         // Extract x-only pubkey from output.
1317         XOnlyPubKey pubkey;
1318         std::copy(data[0].begin(), data[0].end(), pubkey.begin());
1319         // Request spending data.
1320         TaprootSpendData tap;
1321         if (provider.GetTaprootSpendData(pubkey, tap)) {
1322             // If found, convert it back to tree form.
1323             auto tree = InferTaprootTree(tap, pubkey);
1324             if (tree) {
1325                 // If that works, try to infer subdescriptors for all leaves.
1326                 bool ok = true;
1327                 std::vector<std::unique_ptr<DescriptorImpl>> subscripts; //!< list of script subexpressions
1328                 std::vector<int> depths; //!< depth in the tree of each subexpression (same length subscripts)
1329                 for (const auto& [depth, script, leaf_ver] : *tree) {
1330                     std::unique_ptr<DescriptorImpl> subdesc;
1331                     if (leaf_ver == TAPROOT_LEAF_TAPSCRIPT) {
1332                         subdesc = InferScript(script, ParseScriptContext::P2TR, provider);
1333                     }
1334                     if (!subdesc) {
1335                         ok = false;
1336                         break;
1337                     } else {
1338                         subscripts.push_back(std::move(subdesc));
1339                         depths.push_back(depth);
1340                     }
1341                 }
1342                 if (ok) {
1343                     auto key = InferXOnlyPubkey(tap.internal_key, ParseScriptContext::P2TR, provider);
1344                     return std::make_unique<TRDescriptor>(std::move(key), std::move(subscripts), std::move(depths));
1345                 }
1346             }
1347         }
1348     }
1349 
1350     CTxDestination dest;
1351     if (ExtractDestination(script, dest)) {
1352         if (GetScriptForDestination(dest) == script) {
1353             return std::make_unique<AddressDescriptor>(std::move(dest));
1354         }
1355     }
1356 
1357     return std::make_unique<RawDescriptor>(script);
1358 }
1359 
1360 
1361 } // namespace
1362 
1363 /** Check a descriptor checksum, and update desc to be the checksum-less part. */
CheckChecksum(Span<const char> & sp,bool require_checksum,std::string & error,std::string * out_checksum=nullptr)1364 bool CheckChecksum(Span<const char>& sp, bool require_checksum, std::string& error, std::string* out_checksum = nullptr)
1365 {
1366     using namespace spanparsing;
1367 
1368     auto check_split = Split(sp, '#');
1369     if (check_split.size() > 2) {
1370         error = "Multiple '#' symbols";
1371         return false;
1372     }
1373     if (check_split.size() == 1 && require_checksum){
1374         error = "Missing checksum";
1375         return false;
1376     }
1377     if (check_split.size() == 2) {
1378         if (check_split[1].size() != 8) {
1379             error = strprintf("Expected 8 character checksum, not %u characters", check_split[1].size());
1380             return false;
1381         }
1382     }
1383     auto checksum = DescriptorChecksum(check_split[0]);
1384     if (checksum.empty()) {
1385         error = "Invalid characters in payload";
1386         return false;
1387     }
1388     if (check_split.size() == 2) {
1389         if (!std::equal(checksum.begin(), checksum.end(), check_split[1].begin())) {
1390             error = strprintf("Provided checksum '%s' does not match computed checksum '%s'", std::string(check_split[1].begin(), check_split[1].end()), checksum);
1391             return false;
1392         }
1393     }
1394     if (out_checksum) *out_checksum = std::move(checksum);
1395     sp = check_split[0];
1396     return true;
1397 }
1398 
Parse(const std::string & descriptor,FlatSigningProvider & out,std::string & error,bool require_checksum)1399 std::unique_ptr<Descriptor> Parse(const std::string& descriptor, FlatSigningProvider& out, std::string& error, bool require_checksum)
1400 {
1401     Span<const char> sp{descriptor};
1402     if (!CheckChecksum(sp, require_checksum, error)) return nullptr;
1403     uint32_t key_exp_index = 0;
1404     auto ret = ParseScript(key_exp_index, sp, ParseScriptContext::TOP, out, error);
1405     if (sp.size() == 0 && ret) return std::unique_ptr<Descriptor>(std::move(ret));
1406     return nullptr;
1407 }
1408 
GetDescriptorChecksum(const std::string & descriptor)1409 std::string GetDescriptorChecksum(const std::string& descriptor)
1410 {
1411     std::string ret;
1412     std::string error;
1413     Span<const char> sp{descriptor};
1414     if (!CheckChecksum(sp, false, error, &ret)) return "";
1415     return ret;
1416 }
1417 
InferDescriptor(const CScript & script,const SigningProvider & provider)1418 std::unique_ptr<Descriptor> InferDescriptor(const CScript& script, const SigningProvider& provider)
1419 {
1420     return InferScript(script, ParseScriptContext::TOP, provider);
1421 }
1422 
CacheParentExtPubKey(uint32_t key_exp_pos,const CExtPubKey & xpub)1423 void DescriptorCache::CacheParentExtPubKey(uint32_t key_exp_pos, const CExtPubKey& xpub)
1424 {
1425     m_parent_xpubs[key_exp_pos] = xpub;
1426 }
1427 
CacheDerivedExtPubKey(uint32_t key_exp_pos,uint32_t der_index,const CExtPubKey & xpub)1428 void DescriptorCache::CacheDerivedExtPubKey(uint32_t key_exp_pos, uint32_t der_index, const CExtPubKey& xpub)
1429 {
1430     auto& xpubs = m_derived_xpubs[key_exp_pos];
1431     xpubs[der_index] = xpub;
1432 }
1433 
CacheLastHardenedExtPubKey(uint32_t key_exp_pos,const CExtPubKey & xpub)1434 void DescriptorCache::CacheLastHardenedExtPubKey(uint32_t key_exp_pos, const CExtPubKey& xpub)
1435 {
1436     m_last_hardened_xpubs[key_exp_pos] = xpub;
1437 }
1438 
GetCachedParentExtPubKey(uint32_t key_exp_pos,CExtPubKey & xpub) const1439 bool DescriptorCache::GetCachedParentExtPubKey(uint32_t key_exp_pos, CExtPubKey& xpub) const
1440 {
1441     const auto& it = m_parent_xpubs.find(key_exp_pos);
1442     if (it == m_parent_xpubs.end()) return false;
1443     xpub = it->second;
1444     return true;
1445 }
1446 
GetCachedDerivedExtPubKey(uint32_t key_exp_pos,uint32_t der_index,CExtPubKey & xpub) const1447 bool DescriptorCache::GetCachedDerivedExtPubKey(uint32_t key_exp_pos, uint32_t der_index, CExtPubKey& xpub) const
1448 {
1449     const auto& key_exp_it = m_derived_xpubs.find(key_exp_pos);
1450     if (key_exp_it == m_derived_xpubs.end()) return false;
1451     const auto& der_it = key_exp_it->second.find(der_index);
1452     if (der_it == key_exp_it->second.end()) return false;
1453     xpub = der_it->second;
1454     return true;
1455 }
1456 
GetCachedLastHardenedExtPubKey(uint32_t key_exp_pos,CExtPubKey & xpub) const1457 bool DescriptorCache::GetCachedLastHardenedExtPubKey(uint32_t key_exp_pos, CExtPubKey& xpub) const
1458 {
1459     const auto& it = m_last_hardened_xpubs.find(key_exp_pos);
1460     if (it == m_last_hardened_xpubs.end()) return false;
1461     xpub = it->second;
1462     return true;
1463 }
1464 
MergeAndDiff(const DescriptorCache & other)1465 DescriptorCache DescriptorCache::MergeAndDiff(const DescriptorCache& other)
1466 {
1467     DescriptorCache diff;
1468     for (const auto& parent_xpub_pair : other.GetCachedParentExtPubKeys()) {
1469         CExtPubKey xpub;
1470         if (GetCachedParentExtPubKey(parent_xpub_pair.first, xpub)) {
1471             if (xpub != parent_xpub_pair.second) {
1472                 throw std::runtime_error(std::string(__func__) + ": New cached parent xpub does not match already cached parent xpub");
1473             }
1474             continue;
1475         }
1476         CacheParentExtPubKey(parent_xpub_pair.first, parent_xpub_pair.second);
1477         diff.CacheParentExtPubKey(parent_xpub_pair.first, parent_xpub_pair.second);
1478     }
1479     for (const auto& derived_xpub_map_pair : other.GetCachedDerivedExtPubKeys()) {
1480         for (const auto& derived_xpub_pair : derived_xpub_map_pair.second) {
1481             CExtPubKey xpub;
1482             if (GetCachedDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, xpub)) {
1483                 if (xpub != derived_xpub_pair.second) {
1484                     throw std::runtime_error(std::string(__func__) + ": New cached derived xpub does not match already cached derived xpub");
1485                 }
1486                 continue;
1487             }
1488             CacheDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, derived_xpub_pair.second);
1489             diff.CacheDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, derived_xpub_pair.second);
1490         }
1491     }
1492     for (const auto& lh_xpub_pair : other.GetCachedLastHardenedExtPubKeys()) {
1493         CExtPubKey xpub;
1494         if (GetCachedLastHardenedExtPubKey(lh_xpub_pair.first, xpub)) {
1495             if (xpub != lh_xpub_pair.second) {
1496                 throw std::runtime_error(std::string(__func__) + ": New cached last hardened xpub does not match already cached last hardened xpub");
1497             }
1498             continue;
1499         }
1500         CacheLastHardenedExtPubKey(lh_xpub_pair.first, lh_xpub_pair.second);
1501         diff.CacheLastHardenedExtPubKey(lh_xpub_pair.first, lh_xpub_pair.second);
1502     }
1503     return diff;
1504 }
1505 
GetCachedParentExtPubKeys() const1506 const ExtPubKeyMap DescriptorCache::GetCachedParentExtPubKeys() const
1507 {
1508     return m_parent_xpubs;
1509 }
1510 
GetCachedDerivedExtPubKeys() const1511 const std::unordered_map<uint32_t, ExtPubKeyMap> DescriptorCache::GetCachedDerivedExtPubKeys() const
1512 {
1513     return m_derived_xpubs;
1514 }
1515 
GetCachedLastHardenedExtPubKeys() const1516 const ExtPubKeyMap DescriptorCache::GetCachedLastHardenedExtPubKeys() const
1517 {
1518     return m_last_hardened_xpubs;
1519 }
1520