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