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