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
24namespace {
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 */
84uint64_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
96std::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
143std::string AddChecksum(const std::string& str) { return str + "#" + DescriptorChecksum(str); }
144
146// Internal representation //
148
149typedef std::vector<uint32_t> KeyPath;
150
152struct PubkeyProvider
153{
154protected:
157 uint32_t m_expr_index;
158
159public:
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
190class 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
200public:
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
241class ConstPubkeyProvider final : public PubkeyProvider
242{
243 CPubKey m_pubkey;
244 bool m_xonly;
245
246public:
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
277enum class DeriveType {
278 NO,
279 UNHARDENED,
280 HARDENED,
281};
282
284class 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
325public:
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
486class DescriptorImpl : public Descriptor
487{
489 const std::vector<std::unique_ptr<PubkeyProvider>> m_pubkey_args;
491 const std::string m_name;
492
493protected:
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
515public:
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, MakeSpan(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
664class AddressDescriptor final : public DescriptorImpl
665{
666 const CTxDestination m_destination;
667protected:
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)); }
670public:
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
682class RawDescriptor final : public DescriptorImpl
683{
684 const CScript m_script;
685protected:
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); }
688public:
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
702class PKDescriptor final : public DescriptorImpl
703{
704private:
705 const bool m_xonly;
706protected:
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 }
716public:
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
722class PKHDescriptor final : public DescriptorImpl
723{
724protected:
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 }
731public:
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
738class WPKHDescriptor final : public DescriptorImpl
739{
740protected:
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 }
747public:
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
754class ComboDescriptor final : public DescriptorImpl
755{
756protected:
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 }
772public:
773 ComboDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "combo") {}
774 bool IsSingleType() const final { return false; }
775};
776
778class MultisigDescriptor final : public DescriptorImpl
779{
780 const int m_threshold;
781 const bool m_sorted;
782protected:
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 }
792public:
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
798class SHDescriptor final : public DescriptorImpl
799{
800protected:
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 }
807public:
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
820class WSHDescriptor final : public DescriptorImpl
821{
822protected:
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 }
829public:
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
836class TRDescriptor final : public DescriptorImpl
837{
838 std::vector<int> m_depths;
839protected:
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 return Vector(GetScriptForDestination(output));
855 }
856 bool ToStringSubScriptHelper(const SigningProvider* arg, std::string& ret, const StringType type, const DescriptorCache* cache = nullptr) const override
857 {
858 if (m_depths.empty()) return true;
859 std::vector<bool> path;
860 for (size_t pos = 0; pos < m_depths.size(); ++pos) {
861 if (pos) ret += ',';
862 while ((int)path.size() <= m_depths[pos]) {
863 if (path.size()) ret += '{';
864 path.push_back(false);
865 }
866 std::string tmp;
867 if (!m_subdescriptor_args[pos]->ToStringHelper(arg, tmp, type, cache)) return false;
868 ret += std::move(tmp);
869 while (!path.empty() && path.back()) {
870 if (path.size() > 1) ret += '}';
871 path.pop_back();
872 }
873 if (!path.empty()) path.back() = true;
874 }
875 return true;
876 }
877public:
878 TRDescriptor(std::unique_ptr<PubkeyProvider> internal_key, std::vector<std::unique_ptr<DescriptorImpl>> descs, std::vector<int> depths) :
879 DescriptorImpl(Vector(std::move(internal_key)), std::move(descs), "tr"), m_depths(std::move(depths))
880 {
881 assert(m_subdescriptor_args.size() == m_depths.size());
882 }
883 std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32M; }
884 bool IsSingleType() const final { return true; }
885};
886
888// Parser //
890
891enum class ParseScriptContext {
892 TOP,
893 P2SH,
894 P2WPKH,
895 P2WSH,
896 P2TR,
897};
898
900[[nodiscard]] bool ParseKeyPath(const std::vector<Span<const char>>& split, KeyPath& out, std::string& error)
901{
902 for (size_t i = 1; i < split.size(); ++i) {
903 Span<const char> elem = split[i];
904 bool hardened = false;
905 if (elem.size() > 0 && (elem[elem.size() - 1] == '\'' || elem[elem.size() - 1] == 'h')) {
906 elem = elem.first(elem.size() - 1);
907 hardened = true;
908 }
909 uint32_t p;
910 if (!ParseUInt32(std::string(elem.begin(), elem.end()), &p)) {
911 error = strprintf("Key path value '%s' is not a valid uint32", std::string(elem.begin(), elem.end()));
912 return false;
913 } else if (p > 0x7FFFFFFFUL) {
914 error = strprintf("Key path value %u is out of range", p);
915 return false;
916 }
917 out.push_back(p | (((uint32_t)hardened) << 31));
918 }
919 return true;
920}
921
923std::unique_ptr<PubkeyProvider> ParsePubkeyInner(uint32_t key_exp_index, const Span<const char>& sp, ParseScriptContext ctx, FlatSigningProvider& out, std::string& error)
924{
925 using namespace spanparsing;
926
927 bool permit_uncompressed = ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH;
928 auto split = Split(sp, '/');
929 std::string str(split[0].begin(), split[0].end());
930 if (str.size() == 0) {
931 error = "No key provided";
932 return nullptr;
933 }
934 if (split.size() == 1) {
935 if (IsHex(str)) {
936 std::vector<unsigned char> data = ParseHex(str);
937 CPubKey pubkey(data);
938 if (pubkey.IsFullyValid()) {
939 if (permit_uncompressed || pubkey.IsCompressed()) {
940 return std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, false);
941 } else {
942 error = "Uncompressed keys are not allowed";
943 return nullptr;
944 }
945 } else if (data.size() == 32 && ctx == ParseScriptContext::P2TR) {
946 unsigned char fullkey[33] = {0x02};
947 std::copy(data.begin(), data.end(), fullkey + 1);
948 pubkey.Set(std::begin(fullkey), std::end(fullkey));
949 if (pubkey.IsFullyValid()) {
950 return std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, true);
951 }
952 }
953 error = strprintf("Pubkey '%s' is invalid", str);
954 return nullptr;
955 }
956 CKey key = DecodeSecret(str);
957 if (key.IsValid()) {
958 if (permit_uncompressed || key.IsCompressed()) {
959 CPubKey pubkey = key.GetPubKey();
960 out.keys.emplace(pubkey.GetID(), key);
961 return std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, ctx == ParseScriptContext::P2TR);
962 } else {
963 error = "Uncompressed keys are not allowed";
964 return nullptr;
965 }
966 }
967 }
968 CExtKey extkey = DecodeExtKey(str);
969 CExtPubKey extpubkey = DecodeExtPubKey(str);
970 if (!extkey.key.IsValid() && !extpubkey.pubkey.IsValid()) {
971 error = strprintf("key '%s' is not valid", str);
972 return nullptr;
973 }
974 KeyPath path;
975 DeriveType type = DeriveType::NO;
976 if (split.back() == MakeSpan("*").first(1)) {
977 split.pop_back();
978 type = DeriveType::UNHARDENED;
979 } else if (split.back() == MakeSpan("*'").first(2) || split.back() == MakeSpan("*h").first(2)) {
980 split.pop_back();
981 type = DeriveType::HARDENED;
982 }
983 if (!ParseKeyPath(split, path, error)) return nullptr;
984 if (extkey.key.IsValid()) {
985 extpubkey = extkey.Neuter();
986 out.keys.emplace(extpubkey.pubkey.GetID(), extkey.key);
987 }
988 return std::make_unique<BIP32PubkeyProvider>(key_exp_index, extpubkey, std::move(path), type);
989}
990
992std::unique_ptr<PubkeyProvider> ParsePubkey(uint32_t key_exp_index, const Span<const char>& sp, ParseScriptContext ctx, FlatSigningProvider& out, std::string& error)
993{
994 using namespace spanparsing;
995
996 auto origin_split = Split(sp, ']');
997 if (origin_split.size() > 2) {
998 error = "Multiple ']' characters found for a single pubkey";
999 return nullptr;
1000 }
1001 if (origin_split.size() == 1) return ParsePubkeyInner(key_exp_index, origin_split[0], ctx, out, error);
1002 if (origin_split[0].empty() || origin_split[0][0] != '[') {
1003 error = strprintf("Key origin start '[ character expected but not found, got '%c' instead",
1004 origin_split[0].empty() ? ']' : origin_split[0][0]);
1005 return nullptr;
1006 }
1007 auto slash_split = Split(origin_split[0].subspan(1), '/');
1008 if (slash_split[0].size() != 8) {
1009 error = strprintf("Fingerprint is not 4 bytes (%u characters instead of 8 characters)", slash_split[0].size());
1010 return nullptr;
1011 }
1012 std::string fpr_hex = std::string(slash_split[0].begin(), slash_split[0].end());
1013 if (!IsHex(fpr_hex)) {
1014 error = strprintf("Fingerprint '%s' is not hex", fpr_hex);
1015 return nullptr;
1016 }
1017 auto fpr_bytes = ParseHex(fpr_hex);
1018 KeyOriginInfo info;
1019 static_assert(sizeof(info.fingerprint) == 4, "Fingerprint must be 4 bytes");
1020 assert(fpr_bytes.size() == 4);
1021 std::copy(fpr_bytes.begin(), fpr_bytes.end(), info.fingerprint);
1022 if (!ParseKeyPath(slash_split, info.path, error)) return nullptr;
1023 auto provider = ParsePubkeyInner(key_exp_index, origin_split[1], ctx, out, error);
1024 if (!provider) return nullptr;
1025 return std::make_unique<OriginPubkeyProvider>(key_exp_index, std::move(info), std::move(provider));
1026}
1027
1029std::unique_ptr<DescriptorImpl> ParseScript(uint32_t& key_exp_index, Span<const char>& sp, ParseScriptContext ctx, FlatSigningProvider& out, std::string& error)
1030{
1031 using namespace spanparsing;
1032
1033 auto expr = Expr(sp);
1034 bool sorted_multi = false;
1035 if (Func("pk", expr)) {
1036 auto pubkey = ParsePubkey(key_exp_index, expr, ctx, out, error);
1037 if (!pubkey) return nullptr;
1038 ++key_exp_index;
1039 return std::make_unique<PKDescriptor>(std::move(pubkey), ctx == ParseScriptContext::P2TR);
1040 }
1041 if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH) && Func("pkh", expr)) {
1042 auto pubkey = ParsePubkey(key_exp_index, expr, ctx, out, error);
1043 if (!pubkey) return nullptr;
1044 ++key_exp_index;
1045 return std::make_unique<PKHDescriptor>(std::move(pubkey));
1046 } else if (Func("pkh", expr)) {
1047 error = "Can only have pkh at top level, in sh(), or in wsh()";
1048 return nullptr;
1049 }
1050 if (ctx == ParseScriptContext::TOP && Func("combo", expr)) {
1051 auto pubkey = ParsePubkey(key_exp_index, expr, ctx, out, error);
1052 if (!pubkey) return nullptr;
1053 ++key_exp_index;
1054 return std::make_unique<ComboDescriptor>(std::move(pubkey));
1055 } else if (Func("combo", expr)) {
1056 error = "Can only have combo() at top level";
1057 return nullptr;
1058 }
1059 if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH) && ((sorted_multi = Func("sortedmulti", expr)) || Func("multi", expr))) {
1060 auto threshold = Expr(expr);
1061 uint32_t thres;
1062 std::vector<std::unique_ptr<PubkeyProvider>> providers;
1063 if (!ParseUInt32(std::string(threshold.begin(), threshold.end()), &thres)) {
1064 error = strprintf("Multi threshold '%s' is not valid", std::string(threshold.begin(), threshold.end()));
1065 return nullptr;
1066 }
1067 size_t script_size = 0;
1068 while (expr.size()) {
1069 if (!Const(",", expr)) {
1070 error = strprintf("Multi: expected ',', got '%c'", expr[0]);
1071 return nullptr;
1072 }
1073 auto arg = Expr(expr);
1074 auto pk = ParsePubkey(key_exp_index, arg, ctx, out, error);
1075 if (!pk) return nullptr;
1076 script_size += pk->GetSize() + 1;
1077 providers.emplace_back(std::move(pk));
1078 key_exp_index++;
1079 }
1080 if (providers.empty() || providers.size() > MAX_PUBKEYS_PER_MULTISIG) {
1081 error = strprintf("Cannot have %u keys in multisig; must have between 1 and %d keys, inclusive", providers.size(), MAX_PUBKEYS_PER_MULTISIG);
1082 return nullptr;
1083 } else if (thres < 1) {
1084 error = strprintf("Multisig threshold cannot be %d, must be at least 1", thres);
1085 return nullptr;
1086 } else if (thres > providers.size()) {
1087 error = strprintf("Multisig threshold cannot be larger than the number of keys; threshold is %d but only %u keys specified", thres, providers.size());
1088 return nullptr;
1089 }
1090 if (ctx == ParseScriptContext::TOP) {
1091 if (providers.size() > 3) {
1092 error = strprintf("Cannot have %u pubkeys in bare multisig; only at most 3 pubkeys", providers.size());
1093 return nullptr;
1094 }
1095 }
1096 if (ctx == ParseScriptContext::P2SH) {
1097 // This limits the maximum number of compressed pubkeys to 15.
1098 if (script_size + 3 > MAX_SCRIPT_ELEMENT_SIZE) {
1099 error = strprintf("P2SH script is too large, %d bytes is larger than %d bytes", script_size + 3, MAX_SCRIPT_ELEMENT_SIZE);
1100 return nullptr;
1101 }
1102 }
1103 return std::make_unique<MultisigDescriptor>(thres, std::move(providers), sorted_multi);
1104 } else if (Func("sortedmulti", expr) || Func("multi", expr)) {
1105 error = "Can only have multi/sortedmulti at top level, in sh(), or in wsh()";
1106 return nullptr;
1107 }
1108 if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH) && Func("wpkh", expr)) {
1109 auto pubkey = ParsePubkey(key_exp_index, expr, ParseScriptContext::P2WPKH, out, error);
1110 if (!pubkey) return nullptr;
1111 key_exp_index++;
1112 return std::make_unique<WPKHDescriptor>(std::move(pubkey));
1113 } else if (Func("wpkh", expr)) {
1114 error = "Can only have wpkh() at top level or inside sh()";
1115 return nullptr;
1116 }
1117 if (ctx == ParseScriptContext::TOP && Func("sh", expr)) {
1118 auto desc = ParseScript(key_exp_index, expr, ParseScriptContext::P2SH, out, error);
1119 if (!desc || expr.size()) return nullptr;
1120 return std::make_unique<SHDescriptor>(std::move(desc));
1121 } else if (Func("sh", expr)) {
1122 error = "Can only have sh() at top level";
1123 return nullptr;
1124 }
1125 if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH) && Func("wsh", expr)) {
1126 auto desc = ParseScript(key_exp_index, expr, ParseScriptContext::P2WSH, out, error);
1127 if (!desc || expr.size()) return nullptr;
1128 return std::make_unique<WSHDescriptor>(std::move(desc));
1129 } else if (Func("wsh", expr)) {
1130 error = "Can only have wsh() at top level or inside sh()";
1131 return nullptr;
1132 }
1133 if (ctx == ParseScriptContext::TOP && Func("addr", expr)) {
1134 CTxDestination dest = DecodeDestination(std::string(expr.begin(), expr.end()));
1135 if (!IsValidDestination(dest)) {
1136 error = "Address is not valid";
1137 return nullptr;
1138 }
1139 return std::make_unique<AddressDescriptor>(std::move(dest));
1140 } else if (Func("addr", expr)) {
1141 error = "Can only have addr() at top level";
1142 return nullptr;
1143 }
1144 if (ctx == ParseScriptContext::TOP && Func("tr", expr)) {
1145 auto arg = Expr(expr);
1146 auto internal_key = ParsePubkey(key_exp_index, arg, ParseScriptContext::P2TR, out, error);
1147 if (!internal_key) return nullptr;
1148 ++key_exp_index;
1149 std::vector<std::unique_ptr<DescriptorImpl>> subscripts;
1150 std::vector<int> depths;
1151 if (expr.size()) {
1152 if (!Const(",", expr)) {
1153 error = strprintf("tr: expected ',', got '%c'", expr[0]);
1154 return nullptr;
1155 }
1159 std::vector<bool> branches;
1160 // Loop over all provided scripts. In every iteration exactly one script will be processed.
1161 // Use a do-loop because inside this if-branch we expect at least one script.
1162 do {
1163 // First process all open braces.
1164 while (Const("{", expr)) {
1165 branches.push_back(false); // new left branch
1166 if (branches.size() > TAPROOT_CONTROL_MAX_NODE_COUNT) {
1167 error = strprintf("tr() supports at most %i nesting levels", TAPROOT_CONTROL_MAX_NODE_COUNT);
1168 return nullptr;
1169 }
1170 }
1171 // Process the actual script expression.
1172 auto sarg = Expr(expr);
1173 subscripts.emplace_back(ParseScript(key_exp_index, sarg, ParseScriptContext::P2TR, out, error));
1174 if (!subscripts.back()) return nullptr;
1175 depths.push_back(branches.size());
1176 // Process closing braces; one is expected for every right branch we were in.
1177 while (branches.size() && branches.back()) {
1178 if (!Const("}", expr)) {
1179 error = strprintf("tr(): expected '}' after script expression");
1180 return nullptr;
1181 }
1182 branches.pop_back(); // move up one level after encountering '}'
1183 }
1184 // If after that, we're at the end of a left branch, expect a comma.
1185 if (branches.size() && !branches.back()) {
1186 if (!Const(",", expr)) {
1187 error = strprintf("tr(): expected ',' after script expression");
1188 return nullptr;
1189 }
1190 branches.back() = true; // And now we're in a right branch.
1191 }
1192 } while (branches.size());
1193 // After we've explored a whole tree, we must be at the end of the expression.
1194 if (expr.size()) {
1195 error = strprintf("tr(): expected ')' after script expression");
1196 return nullptr;
1197 }
1198 }
1200 return std::make_unique<TRDescriptor>(std::move(internal_key), std::move(subscripts), std::move(depths));
1201 } else if (Func("tr", expr)) {
1202 error = "Can only have tr at top level";
1203 return nullptr;
1204 }
1205 if (ctx == ParseScriptContext::TOP && Func("raw", expr)) {
1206 std::string str(expr.begin(), expr.end());
1207 if (!IsHex(str)) {
1208 error = "Raw script is not hex";
1209 return nullptr;
1210 }
1211 auto bytes = ParseHex(str);
1212 return std::make_unique<RawDescriptor>(CScript(bytes.begin(), bytes.end()));
1213 } else if (Func("raw", expr)) {
1214 error = "Can only have raw() at top level";
1215 return nullptr;
1216 }
1217 if (ctx == ParseScriptContext::P2SH) {
1218 error = "A function is needed within P2SH";
1219 return nullptr;
1220 } else if (ctx == ParseScriptContext::P2WSH) {
1221 error = "A function is needed within P2WSH";
1222 return nullptr;
1223 }
1224 error = strprintf("%s is not a valid descriptor function", std::string(expr.begin(), expr.end()));
1225 return nullptr;
1226}
1227
1228std::unique_ptr<PubkeyProvider> InferPubkey(const CPubKey& pubkey, ParseScriptContext, const SigningProvider& provider)
1229{
1230 std::unique_ptr<PubkeyProvider> key_provider = std::make_unique<ConstPubkeyProvider>(0, pubkey, false);
1231 KeyOriginInfo info;
1232 if (provider.GetKeyOrigin(pubkey.GetID(), info)) {
1233 return std::make_unique<OriginPubkeyProvider>(0, std::move(info), std::move(key_provider));
1234 }
1235 return key_provider;
1236}
1237
1238std::unique_ptr<PubkeyProvider> InferXOnlyPubkey(const XOnlyPubKey& xkey, ParseScriptContext ctx, const SigningProvider& provider)
1239{
1240 unsigned char full_key[CPubKey::COMPRESSED_SIZE] = {0x02};
1241 std::copy(xkey.begin(), xkey.end(), full_key + 1);
1242 CPubKey pubkey(full_key);
1243 std::unique_ptr<PubkeyProvider> key_provider = std::make_unique<ConstPubkeyProvider>(0, pubkey, true);
1244 KeyOriginInfo info;
1245 if (provider.GetKeyOriginByXOnly(xkey, info)) {
1246 return std::make_unique<OriginPubkeyProvider>(0, std::move(info), std::move(key_provider));
1247 }
1248 return key_provider;
1249}
1250
1251std::unique_ptr<DescriptorImpl> InferScript(const CScript& script, ParseScriptContext ctx, const SigningProvider& provider)
1252{
1253 if (ctx == ParseScriptContext::P2TR && script.size() == 34 && script[0] == 32 && script[33] == OP_CHECKSIG) {
1254 XOnlyPubKey key{Span<const unsigned char>{script.data() + 1, script.data() + 33}};
1255 return std::make_unique<PKDescriptor>(InferXOnlyPubkey(key, ctx, provider));
1256 }
1257
1258 std::vector<std::vector<unsigned char>> data;
1259 TxoutType txntype = Solver(script, data);
1260
1261 if (txntype == TxoutType::PUBKEY && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
1262 CPubKey pubkey(data[0]);
1263 if (pubkey.IsValid()) {
1264 return std::make_unique<PKDescriptor>(InferPubkey(pubkey, ctx, provider));
1265 }
1266 }
1267 if (txntype == TxoutType::PUBKEYHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
1268 uint160 hash(data[0]);
1269 CKeyID keyid(hash);
1270 CPubKey pubkey;
1271 if (provider.GetPubKey(keyid, pubkey)) {
1272 return std::make_unique<PKHDescriptor>(InferPubkey(pubkey, ctx, provider));
1273 }
1274 }
1275 if (txntype == TxoutType::WITNESS_V0_KEYHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH)) {
1276 uint160 hash(data[0]);
1277 CKeyID keyid(hash);
1278 CPubKey pubkey;
1279 if (provider.GetPubKey(keyid, pubkey)) {
1280 return std::make_unique<WPKHDescriptor>(InferPubkey(pubkey, ctx, provider));
1281 }
1282 }
1283 if (txntype == TxoutType::MULTISIG && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
1284 std::vector<std::unique_ptr<PubkeyProvider>> providers;
1285 for (size_t i = 1; i + 1 < data.size(); ++i) {
1286 CPubKey pubkey(data[i]);
1287 providers.push_back(InferPubkey(pubkey, ctx, provider));
1288 }
1289 return std::make_unique<MultisigDescriptor>((int)data[0][0], std::move(providers));
1290 }
1291 if (txntype == TxoutType::SCRIPTHASH && ctx == ParseScriptContext::TOP) {
1292 uint160 hash(data[0]);
1293 CScriptID scriptid(hash);
1294 CScript subscript;
1295 if (provider.GetCScript(scriptid, subscript)) {
1296 auto sub = InferScript(subscript, ParseScriptContext::P2SH, provider);
1297 if (sub) return std::make_unique<SHDescriptor>(std::move(sub));
1298 }
1299 }
1300 if (txntype == TxoutType::WITNESS_V0_SCRIPTHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH)) {
1301 CScriptID scriptid;
1302 CRIPEMD160().Write(data[0].data(), data[0].size()).Finalize(scriptid.begin());
1303 CScript subscript;
1304 if (provider.GetCScript(scriptid, subscript)) {
1305 auto sub = InferScript(subscript, ParseScriptContext::P2WSH, provider);
1306 if (sub) return std::make_unique<WSHDescriptor>(std::move(sub));
1307 }
1308 }
1309 if (txntype == TxoutType::WITNESS_V1_TAPROOT && ctx == ParseScriptContext::TOP) {
1310 // Extract x-only pubkey from output.
1311 XOnlyPubKey pubkey;
1312 std::copy(data[0].begin(), data[0].end(), pubkey.begin());
1313 // Request spending data.
1314 TaprootSpendData tap;
1315 if (provider.GetTaprootSpendData(pubkey, tap)) {
1316 // If found, convert it back to tree form.
1317 auto tree = InferTaprootTree(tap, pubkey);
1318 if (tree) {
1319 // If that works, try to infer subdescriptors for all leaves.
1320 bool ok = true;
1321 std::vector<std::unique_ptr<DescriptorImpl>> subscripts;
1322 std::vector<int> depths;
1323 for (const auto& [depth, script, leaf_ver] : *tree) {
1324 std::unique_ptr<DescriptorImpl> subdesc;
1325 if (leaf_ver == TAPROOT_LEAF_TAPSCRIPT) {
1326 subdesc = InferScript(script, ParseScriptContext::P2TR, provider);
1327 }
1328 if (!subdesc) {
1329 ok = false;
1330 break;
1331 } else {
1332 subscripts.push_back(std::move(subdesc));
1333 depths.push_back(depth);
1334 }
1335 }
1336 if (ok) {
1337 auto key = InferXOnlyPubkey(tap.internal_key, ParseScriptContext::P2TR, provider);
1338 return std::make_unique<TRDescriptor>(std::move(key), std::move(subscripts), std::move(depths));
1339 }
1340 }
1341 }
1342 }
1343
1344 CTxDestination dest;
1345 if (ExtractDestination(script, dest)) {
1346 if (GetScriptForDestination(dest) == script) {
1347 return std::make_unique<AddressDescriptor>(std::move(dest));
1348 }
1349 }
1350
1351 return std::make_unique<RawDescriptor>(script);
1352}
1353
1354
1355} // namespace
1356
1358bool CheckChecksum(Span<const char>& sp, bool require_checksum, std::string& error, std::string* out_checksum = nullptr)
1359{
1360 using namespace spanparsing;
1361
1362 auto check_split = Split(sp, '#');
1363 if (check_split.size() > 2) {
1364 error = "Multiple '#' symbols";
1365 return false;
1366 }
1367 if (check_split.size() == 1 && require_checksum){
1368 error = "Missing checksum";
1369 return false;
1370 }
1371 if (check_split.size() == 2) {
1372 if (check_split[1].size() != 8) {
1373 error = strprintf("Expected 8 character checksum, not %u characters", check_split[1].size());
1374 return false;
1375 }
1376 }
1377 auto checksum = DescriptorChecksum(check_split[0]);
1378 if (checksum.empty()) {
1379 error = "Invalid characters in payload";
1380 return false;
1381 }
1382 if (check_split.size() == 2) {
1383 if (!std::equal(checksum.begin(), checksum.end(), check_split[1].begin())) {
1384 error = strprintf("Provided checksum '%s' does not match computed checksum '%s'", std::string(check_split[1].begin(), check_split[1].end()), checksum);
1385 return false;
1386 }
1387 }
1388 if (out_checksum) *out_checksum = std::move(checksum);
1389 sp = check_split[0];
1390 return true;
1391}
1392
1393std::unique_ptr<Descriptor> Parse(const std::string& descriptor, FlatSigningProvider& out, std::string& error, bool require_checksum)
1394{
1395 Span<const char> sp{descriptor};
1396 if (!CheckChecksum(sp, require_checksum, error)) return nullptr;
1397 uint32_t key_exp_index = 0;
1398 auto ret = ParseScript(key_exp_index, sp, ParseScriptContext::TOP, out, error);
1399 if (sp.size() == 0 && ret) return std::unique_ptr<Descriptor>(std::move(ret));
1400 return nullptr;
1401}
1402
1403std::string GetDescriptorChecksum(const std::string& descriptor)
1404{
1405 std::string ret;
1406 std::string error;
1407 Span<const char> sp{descriptor};
1408 if (!CheckChecksum(sp, false, error, &ret)) return "";
1409 return ret;
1410}
1411
1412std::unique_ptr<Descriptor> InferDescriptor(const CScript& script, const SigningProvider& provider)
1413{
1414 return InferScript(script, ParseScriptContext::TOP, provider);
1415}
1416
1417void DescriptorCache::CacheParentExtPubKey(uint32_t key_exp_pos, const CExtPubKey& xpub)
1418{
1419 m_parent_xpubs[key_exp_pos] = xpub;
1420}
1421
1422void DescriptorCache::CacheDerivedExtPubKey(uint32_t key_exp_pos, uint32_t der_index, const CExtPubKey& xpub)
1423{
1424 auto& xpubs = m_derived_xpubs[key_exp_pos];
1425 xpubs[der_index] = xpub;
1426}
1427
1428void DescriptorCache::CacheLastHardenedExtPubKey(uint32_t key_exp_pos, const CExtPubKey& xpub)
1429{
1430 m_last_hardened_xpubs[key_exp_pos] = xpub;
1431}
1432
1433bool DescriptorCache::GetCachedParentExtPubKey(uint32_t key_exp_pos, CExtPubKey& xpub) const
1434{
1435 const auto& it = m_parent_xpubs.find(key_exp_pos);
1436 if (it == m_parent_xpubs.end()) return false;
1437 xpub = it->second;
1438 return true;
1439}
1440
1441bool DescriptorCache::GetCachedDerivedExtPubKey(uint32_t key_exp_pos, uint32_t der_index, CExtPubKey& xpub) const
1442{
1443 const auto& key_exp_it = m_derived_xpubs.find(key_exp_pos);
1444 if (key_exp_it == m_derived_xpubs.end()) return false;
1445 const auto& der_it = key_exp_it->second.find(der_index);
1446 if (der_it == key_exp_it->second.end()) return false;
1447 xpub = der_it->second;
1448 return true;
1449}
1450
1452{
1453 const auto& it = m_last_hardened_xpubs.find(key_exp_pos);
1454 if (it == m_last_hardened_xpubs.end()) return false;
1455 xpub = it->second;
1456 return true;
1457}
1458
1460{
1461 DescriptorCache diff;
1462 for (const auto& parent_xpub_pair : other.GetCachedParentExtPubKeys()) {
1463 CExtPubKey xpub;
1464 if (GetCachedParentExtPubKey(parent_xpub_pair.first, xpub)) {
1465 if (xpub != parent_xpub_pair.second) {
1466 throw std::runtime_error(std::string(__func__) + ": New cached parent xpub does not match already cached parent xpub");
1467 }
1468 continue;
1469 }
1470 CacheParentExtPubKey(parent_xpub_pair.first, parent_xpub_pair.second);
1471 diff.CacheParentExtPubKey(parent_xpub_pair.first, parent_xpub_pair.second);
1472 }
1473 for (const auto& derived_xpub_map_pair : other.GetCachedDerivedExtPubKeys()) {
1474 for (const auto& derived_xpub_pair : derived_xpub_map_pair.second) {
1475 CExtPubKey xpub;
1476 if (GetCachedDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, xpub)) {
1477 if (xpub != derived_xpub_pair.second) {
1478 throw std::runtime_error(std::string(__func__) + ": New cached derived xpub does not match already cached derived xpub");
1479 }
1480 continue;
1481 }
1482 CacheDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, derived_xpub_pair.second);
1483 diff.CacheDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, derived_xpub_pair.second);
1484 }
1485 }
1486 for (const auto& lh_xpub_pair : other.GetCachedLastHardenedExtPubKeys()) {
1487 CExtPubKey xpub;
1488 if (GetCachedLastHardenedExtPubKey(lh_xpub_pair.first, xpub)) {
1489 if (xpub != lh_xpub_pair.second) {
1490 throw std::runtime_error(std::string(__func__) + ": New cached last hardened xpub does not match already cached last hardened xpub");
1491 }
1492 continue;
1493 }
1494 CacheLastHardenedExtPubKey(lh_xpub_pair.first, lh_xpub_pair.second);
1495 diff.CacheLastHardenedExtPubKey(lh_xpub_pair.first, lh_xpub_pair.second);
1496 }
1497 return diff;
1498}
1499
1501{
1502 return m_parent_xpubs;
1503}
1504
1505const std::unordered_map<uint32_t, ExtPubKeyMap> DescriptorCache::GetCachedDerivedExtPubKeys() const
1506{
1507 return m_derived_xpubs;
1508}
1509
1511{
1512 return m_last_hardened_xpubs;
1513}
std::string FormatHDKeypath(const std::vector< uint32_t > &path)
Definition: bip32.cpp:53
unsigned char * begin()
Definition: hash_type.h:18
An encapsulated private key.
Definition: key.h:27
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:23
An encapsulated public key.
Definition: pubkey.h:33
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:160
static constexpr unsigned int COMPRESSED_SIZE
Definition: pubkey.h:39
bool IsValid() const
Definition: pubkey.h:185
A hasher class for RIPEMD-160.
Definition: ripemd160.h:13
CRIPEMD160 & Write(const unsigned char *data, size_t len)
Definition: ripemd160.cpp:247
void Finalize(unsigned char hash[OUTPUT_SIZE])
Definition: ripemd160.cpp:273
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:406
A reference to a CScript: the Hash160 of its serialization (see script.h)
Definition: standard.h:26
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:93
constexpr std::size_t size() const noexcept
Definition: span.h:182
CONSTEXPR_IF_NOT_DEBUG Span< C > first(std::size_t count) const noexcept
Definition: span.h:199
constexpr C * begin() const noexcept
Definition: span.h:170
constexpr C * end() const noexcept
Definition: span.h:171
Utility class to construct Taproot outputs from internal key and script tree.
Definition: standard.h:226
WitnessV1Taproot GetOutput()
Compute scriptPubKey (after Finalize()).
Definition: standard.cpp:462
TaprootSpendData GetSpendData() const
Compute spending data (after Finalize()).
Definition: standard.cpp:464
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
bool IsComplete() const
Return whether there were either no leaves, or the leaves form a Huffman tree.
Definition: standard.h:308
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 & Finalize(const XOnlyPubKey &internal_key)
Finalize the construction.
Definition: standard.cpp:451
const unsigned char * end() const
Definition: pubkey.h:279
const unsigned char * begin() const
Definition: pubkey.h:278
unsigned char * begin()
Definition: uint256.h:58
size_type size() const
Definition: prevector.h:282
value_type * data()
Definition: prevector.h:528
160-bit opaque blob.
Definition: uint256.h:113
CScript ParseScript(const std::string &s)
Definition: core_read.cpp:55
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::unique_ptr< Descriptor > Parse(const std::string &descriptor, FlatSigningProvider &out, std::string &error, bool require_checksum)
Parse a descriptor string.
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::unordered_map< uint32_t, CExtPubKey > ExtPubKeyMap
Definition: descriptor.h:16
static constexpr uint8_t TAPROOT_LEAF_TAPSCRIPT
Definition: interpreter.h:226
static constexpr size_t TAPROOT_CONTROL_MAX_NODE_COUNT
Definition: interpreter.h:229
std::string EncodeExtKey(const CExtKey &key)
Definition: key_io.cpp:245
CExtPubKey DecodeExtPubKey(const std::string &str)
Definition: key_io.cpp:209
std::string EncodeSecret(const CKey &key)
Definition: key_io.cpp:196
std::string EncodeDestination(const CTxDestination &dest)
Definition: key_io.cpp:256
CKey DecodeSecret(const std::string &str)
Definition: key_io.cpp:178
std::string EncodeExtPubKey(const CExtPubKey &key)
Definition: key_io.cpp:222
CTxDestination DecodeDestination(const std::string &str, std::string &error_msg)
Definition: key_io.cpp:261
CExtKey DecodeExtKey(const std::string &str)
Definition: key_io.cpp:232
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
Span< const char > Expr(Span< const char > &sp)
Extract the expression that sp begins with.
Definition: spanparsing.cpp:32
bool Const(const std::string &str, Span< const char > &sp)
Parse a constant.
Definition: spanparsing.cpp:14
bool Func(const std::string &str, Span< const char > &sp)
Parse a function call.
Definition: spanparsing.cpp:23
std::optional< OutputType > OutputTypeFromDestination(const CTxDestination &dest)
Get the OutputType for a CTxDestination.
Definition: outputtype.cpp:109
const char * name
Definition: rest.cpp:43
@ P2SH
P2SH redeemScript.
@ TOP
Top-level scriptPubKey.
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
Definition: script.h:24
@ OP_CHECKSIG
Definition: script.h:183
static const int MAX_PUBKEYS_PER_MULTISIG
Definition: script.h:30
std::vector< unsigned char > ToByteVector(const T &in)
Definition: script.h:60
bool IsSolvable(const SigningProvider &provider, const CScript &script)
Definition: sign.cpp:581
static bool GetPubKey(const SigningProvider &provider, const SignatureData &sigdata, const CKeyID &address, CPubKey &pubkey)
Definition: sign.cpp:105
const SigningProvider & DUMMY_SIGNING_PROVIDER
FlatSigningProvider Merge(const FlatSigningProvider &a, const FlatSigningProvider &b)
constexpr Span< A > MakeSpan(A(&a)[N])
MakeSpan for arrays:
Definition: span.h:222
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
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
CScript GetScriptForMultisig(int nRequired, const std::vector< CPubKey > &keys)
Generate a multisig script.
Definition: standard.cpp:320
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
Definition: standard.cpp:213
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
Definition: standard.cpp:315
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition: standard.cpp:332
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:310
TxoutType
Definition: standard.h:59
@ 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:157
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
std::vector< unsigned char > ParseHex(const char *psz)
bool ParseUInt32(const std::string &str, uint32_t *out)
Convert decimal string to unsigned 32-bit integer with strict parse error feedback.
bool IsHex(const std::string &str)
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:87
Definition: key.h:161
unsigned char vchFingerprint[4]
Definition: key.h:163
CExtPubKey Neuter() const
Definition: key.cpp:334
bool Derive(CExtKey &out, unsigned int nChild) const
Definition: key.cpp:314
CKey key
Definition: key.h:166
unsigned char nDepth
Definition: key.h:162
ChainCode chaincode
Definition: key.h:165
unsigned int nChild
Definition: key.h:164
bool Derive(CExtPubKey &out, unsigned int nChild) const
Definition: pubkey.cpp:355
CPubKey pubkey
Definition: pubkey.h:292
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 bool ToNormalizedString(const SigningProvider &provider, std::string &out, const DescriptorCache *cache=nullptr) const =0
Convert the descriptor to a normalized string.
virtual std::optional< OutputType > GetOutputType() const =0
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.
std::map< CKeyID, std::pair< CPubKey, KeyOriginInfo > > origins
std::map< XOnlyPubKey, TaprootSpendData > tr_spenddata
std::map< CKeyID, CPubKey > pubkeys
std::map< CKeyID, CKey > keys
std::map< CScriptID, CScript > scripts
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:210
bool error(const char *fmt, const Args &... args)
Definition: system.h:49
static secp256k1_context * ctx
Definition: tests.c:42
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
assert(!tx.IsCoinBase())
std::vector< typename std::common_type< Args... >::type > Vector(Args &&... args)
Construct a vector with the specified elements.
Definition: vector.h:20