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