Bitcoin Core 32.99.0
P2P Digital Currency
Loading...
Searching...
No Matches
descriptor.cpp
Go to the documentation of this file.
1// Copyright (c) 2018-present 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 <addresstype.h>
8#include <attributes.h>
10#include <crypto/hex_base.h>
11#include <crypto/sha256.h>
12#include <hash.h>
13#include <key.h>
14#include <key_io.h>
15#include <musig.h>
17#include <pubkey.h>
18#include <script/interpreter.h>
19#include <script/keyorigin.h>
20#include <script/miniscript.h>
21#include <script/parsing.h>
22#include <script/script.h>
24#include <script/solver.h>
25#include <serialize.h>
26#include <tinyformat.h>
27#include <uint256.h>
28#include <util/bip32.h>
29#include <util/check.h>
30#include <util/expected.h>
31#include <util/strencodings.h>
32#include <util/string.h>
33#include <util/vector.h>
34
35#include <algorithm>
36#include <compare>
37#include <array>
38#include <iterator>
39#include <map>
40#include <memory>
41#include <numeric>
42#include <optional>
43#include <span>
44#include <stdexcept>
45#include <string>
46#include <tuple>
47#include <unordered_set>
48#include <utility>
49#include <vector>
50
51using util::Split;
52
54{
55 if (low < 0) {
56 return util::Unexpected<std::string>("Range should be greater or equal than 0");
57 }
58 if ((high >> 31) != 0) {
59 return util::Unexpected<std::string>("End of range is too high");
60 }
61 if (low > high) {
62 return util::Unexpected<std::string>("Range specified as [begin,end] must not have begin after end");
63 }
64 if (high - low >= 1000000) {
65 return util::Unexpected<std::string>("Range is too large");
66 }
67 return {};
68}
69
70namespace {
71
73// Checksum //
75
76// This section implements a checksum algorithm for descriptors with the
77// following properties:
78// * Mistakes in a descriptor string are measured in "symbol errors". The higher
79// the number of symbol errors, the harder it is to detect:
80// * An error substituting a character from 0123456789()[],'/*abcdefgh@:$%{} for
81// another in that set always counts as 1 symbol error.
82// * Note that hex encoded keys are covered by these characters. Xprvs and
83// xpubs use other characters too, but already have their own checksum
84// mechanism.
85// * Function names like "multi()" use other characters, but mistakes in
86// these would generally result in an unparsable descriptor.
87// * A case error always counts as 1 symbol error.
88// * Any other 1 character substitution error counts as 1 or 2 symbol errors.
89// * Any 1 symbol error is always detected.
90// * Any 2 or 3 symbol error in a descriptor of up to 49154 characters is always detected.
91// * Any 4 symbol error in a descriptor of up to 507 characters is always detected.
92// * Any 5 symbol error in a descriptor of up to 77 characters is always detected.
93// * Is optimized to minimize the chance a 5 symbol error in a descriptor up to 387 characters is undetected
94// * Random errors have a chance of 1 in 2**40 of being undetected.
95//
96// These properties are achieved by expanding every group of 3 (non checksum) characters into
97// 4 GF(32) symbols, over which a cyclic code is defined.
98
99/*
100 * Interprets c as 8 groups of 5 bits which are the coefficients of a degree 8 polynomial over GF(32),
101 * multiplies that polynomial by x, computes its remainder modulo a generator, and adds the constant term val.
102 *
103 * 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}.
104 * It is chosen to define an cyclic error detecting code which is selected by:
105 * - Starting from all BCH codes over GF(32) of degree 8 and below, which by construction guarantee detecting
106 * 3 errors in windows up to 19000 symbols.
107 * - Taking all those generators, and for degree 7 ones, extend them to degree 8 by adding all degree-1 factors.
108 * - Selecting just the set of generators that guarantee detecting 4 errors in a window of length 512.
109 * - Selecting one of those with best worst-case behavior for 5 errors in windows of length up to 512.
110 *
111 * The generator and the constants to implement it can be verified using this Sage code:
112 * B = GF(2) # Binary field
113 * BP.<b> = B[] # Polynomials over the binary field
114 * F_mod = b**5 + b**3 + 1
115 * F.<f> = GF(32, modulus=F_mod, repr='int') # GF(32) definition
116 * FP.<x> = F[] # Polynomials over GF(32)
117 * E_mod = x**3 + x + F.fetch_int(8)
118 * E.<e> = F.extension(E_mod) # Extension field definition
119 * alpha = e**2743 # Choice of an element in extension field
120 * for p in divisors(E.order() - 1): # Verify alpha has order 32767.
121 * assert((alpha**p == 1) == (p % 32767 == 0))
122 * G = lcm([(alpha**i).minpoly() for i in [1056,1057,1058]] + [x + 1])
123 * print(G) # Print out the generator
124 * for i in [1,2,4,8,16]: # Print out {1,2,4,8,16}*(G mod x^8), packed in hex integers.
125 * v = 0
126 * for coef in reversed((F.fetch_int(i)*(G % x**8)).coefficients(sparse=True)):
127 * v = v*32 + coef.integer_representation()
128 * print("0x%x" % v)
129 */
130uint64_t PolyMod(uint64_t c, int val)
131{
132 uint8_t c0 = c >> 35;
133 c = ((c & 0x7ffffffff) << 5) ^ val;
134 if (c0 & 1) c ^= 0xf5dee51989;
135 if (c0 & 2) c ^= 0xa9fdca3312;
136 if (c0 & 4) c ^= 0x1bab10e32d;
137 if (c0 & 8) c ^= 0x3706b1677a;
138 if (c0 & 16) c ^= 0x644d626ffd;
139 return c;
140}
141
142std::string DescriptorChecksum(const std::span<const char>& span)
143{
157 static constexpr std::string_view INPUT_CHARSET =
158 "0123456789()[],'/*abcdefgh@:$%{}"
159 "IJKLMNOPQRSTUVWXYZ&+-.;<=>?!^_|~"
160 "ijklmnopqrstuvwxyzABCDEFGH`#\"\\ ";
161
163 static constexpr std::array<int8_t, 256> INPUT_CHARSET_POS = []() {
164 std::array<int8_t, 256> table;
165 table.fill(-1);
166 for (size_t i = 0; i < INPUT_CHARSET.size(); ++i) {
167 table[static_cast<uint8_t>(INPUT_CHARSET[i])] = i;
168 }
169 return table;
170 }();
171
173 static constexpr std::string_view CHECKSUM_CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
174
175 uint64_t c = 1;
176 int cls = 0;
177 int clscount = 0;
178 for (auto ch : span) {
179 auto pos = INPUT_CHARSET_POS[static_cast<uint8_t>(ch)];
180 if (pos == -1) return "";
181 c = PolyMod(c, pos & 31); // Emit a symbol for the position inside the group, for every character.
182 cls = cls * 3 + (pos >> 5); // Accumulate the group numbers
183 if (++clscount == 3) {
184 // Emit an extra symbol representing the group numbers, for every 3 characters.
185 c = PolyMod(c, cls);
186 cls = 0;
187 clscount = 0;
188 }
189 }
190 if (clscount > 0) c = PolyMod(c, cls);
191 for (int j = 0; j < 8; ++j) c = PolyMod(c, 0); // Shift further to determine the checksum.
192 c ^= 1; // Prevent appending zeroes from not affecting the checksum.
193
194 std::string ret(8, ' ');
195 for (int j = 0; j < 8; ++j) ret[j] = CHECKSUM_CHARSET[(c >> (5 * (7 - j))) & 31];
196 return ret;
197}
198
199std::string AddChecksum(const std::string& str) { return str + "#" + DescriptorChecksum(str); }
200
202// Internal representation //
204
205typedef std::vector<uint32_t> KeyPath;
206
208struct PubkeyProvider
209{
210public:
213 const uint32_t m_expr_index;
214
215 explicit PubkeyProvider(uint32_t exp_index) : m_expr_index(exp_index) {}
216
217 virtual ~PubkeyProvider() = default;
218
224 virtual std::optional<CPubKey> GetPubKey(int pos, const SigningProvider& arg, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const = 0;
225
227 virtual bool IsRange() const = 0;
228
230 virtual size_t GetSize() const = 0;
231
232 enum class StringType {
233 PUBLIC,
234 CANONICAL, // string calculation that always use h
235 COMPAT // string calculation that mustn't change over time to stay compatible with previous software versions
236 };
237
239 virtual std::string ToString(StringType type) const = 0;
240
246 virtual bool ToPrivateString(const SigningProvider& arg, std::string& out) const = 0;
247
251 virtual bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache = nullptr) const = 0;
252
254 virtual void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const = 0;
255
257 virtual bool HavePrivateKeys(const SigningProvider& arg) const
258 {
260 GetPrivKey(/*pos=*/0, arg, tmp_provider);
261 return !tmp_provider.keys.empty();
262 }
263
265 virtual std::optional<CPubKey> GetRootPubKey() const = 0;
267 virtual std::optional<CExtPubKey> GetRootExtPubKey() const = 0;
268
270 virtual std::unique_ptr<PubkeyProvider> Clone() const = 0;
271
273 virtual bool IsBIP32() const = 0;
274
276 virtual size_t GetKeyCount() const { return 1; }
277
279 virtual bool CanSelfExpand() const = 0;
280
281protected:
282 static bool DetermineApostropheUse(StringType type, bool normalized, bool public_apostrophe)
283 {
284 bool use_apostrophe{false};
285 switch (type) {
286 case StringType::COMPAT:
287 // COMPAT always uses apostrophe to stay compatible with previous versions
288 use_apostrophe = true;
289 break;
290 case StringType::CANONICAL:
291 // CANONICAL always uses h
292 use_apostrophe = false;
293 break;
294 case StringType::PUBLIC:
296 break;
297 } // no default case, so the compiler can warn about missing cases
298 return use_apostrophe;
299 }
300};
301
302class OriginPubkeyProvider final : public PubkeyProvider
303{
304 KeyOriginInfo m_origin;
305 std::unique_ptr<PubkeyProvider> m_provider;
306 bool m_apostrophe;
307
308 std::string OriginString(StringType type, bool normalized=false) const
309 {
310 bool use_apostrophe{DetermineApostropheUse(type, normalized, m_apostrophe)};
311 return HexStr(m_origin.fingerprint) + FormatHDKeypath(m_origin.path, use_apostrophe);
312 }
313
314public:
315 OriginPubkeyProvider(uint32_t exp_index, KeyOriginInfo info, std::unique_ptr<PubkeyProvider> provider, bool apostrophe) : PubkeyProvider(exp_index), m_origin(std::move(info)), m_provider(std::move(provider)), m_apostrophe(apostrophe) {}
316 std::optional<CPubKey> GetPubKey(int pos, const SigningProvider& arg, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
317 {
318 // Derive into a temporary provider. Another key expression may have already put this
319 // key into out with its origin prefixed, and prefixing that entry would double it up.
321 std::optional<CPubKey> pub = m_provider->GetPubKey(pos, arg, subprovider, read_cache, write_cache);
322 if (!pub) return std::nullopt;
323 const CKeyID keyid{pub->GetID()};
324 Assert(subprovider.pubkeys.contains(keyid));
325 auto& [pubkey, suborigin] = subprovider.origins[keyid];
326 Assert(pubkey == *pub); // m_provider must have a valid origin by this point.
327 suborigin.fingerprint = m_origin.fingerprint;
328 suborigin.path.insert(suborigin.path.begin(), m_origin.path.begin(), m_origin.path.end());
329 auto origin{subprovider.origins.extract(keyid)};
330 out.Merge(std::move(subprovider));
331 // An explicit origin takes precedence over an implicit one for the same key.
332 out.origins.insert_or_assign(keyid, std::move(origin.mapped()));
333 return pub;
334 }
335 bool IsRange() const override { return m_provider->IsRange(); }
336 size_t GetSize() const override { return m_provider->GetSize(); }
337 bool IsBIP32() const override { return m_provider->IsBIP32(); }
338 std::string ToString(StringType type) const override { return "[" + OriginString(type) + "]" + m_provider->ToString(type); }
339 bool ToPrivateString(const SigningProvider& arg, std::string& ret) const override
340 {
341 std::string sub;
342 bool has_priv_key{m_provider->ToPrivateString(arg, sub)};
343 ret = "[" + OriginString(StringType::PUBLIC) + "]" + std::move(sub);
344 return has_priv_key;
345 }
346 bool ToNormalizedString(const SigningProvider& arg, std::string& ret, const DescriptorCache* cache) const override
347 {
348 std::string sub;
349 if (!m_provider->ToNormalizedString(arg, sub, cache)) return false;
350 // If m_provider is a BIP32PubkeyProvider, we may get a string formatted like a OriginPubkeyProvider
351 // In that case, we need to strip out the leading square bracket and fingerprint from the substring,
352 // and append that to our own origin string.
353 if (sub[0] == '[') {
354 sub = sub.substr(9);
355 ret = "[" + OriginString(StringType::PUBLIC, /*normalized=*/true) + std::move(sub);
356 } else {
357 ret = "[" + OriginString(StringType::PUBLIC, /*normalized=*/true) + "]" + std::move(sub);
358 }
359 return true;
360 }
361 void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const override
362 {
363 m_provider->GetPrivKey(pos, arg, out);
364 }
365 std::optional<CPubKey> GetRootPubKey() const override
366 {
367 return m_provider->GetRootPubKey();
368 }
369 std::optional<CExtPubKey> GetRootExtPubKey() const override
370 {
371 return m_provider->GetRootExtPubKey();
372 }
373 std::unique_ptr<PubkeyProvider> Clone() const override
374 {
375 return std::make_unique<OriginPubkeyProvider>(m_expr_index, m_origin, m_provider->Clone(), m_apostrophe);
376 }
377 bool CanSelfExpand() const override { return m_provider->CanSelfExpand(); }
378};
379
381class ConstPubkeyProvider final : public PubkeyProvider
382{
383 CPubKey m_pubkey;
384 bool m_xonly;
385
386 std::optional<CKey> GetPrivKey(const SigningProvider& arg) const
387 {
388 CKey key;
389 if (!(m_xonly ? arg.GetKeyByXOnly(XOnlyPubKey(m_pubkey), key) :
390 arg.GetKey(m_pubkey.GetID(), key))) return std::nullopt;
391 return key;
392 }
393
394public:
395 ConstPubkeyProvider(uint32_t exp_index, const CPubKey& pubkey, bool xonly) : PubkeyProvider(exp_index), m_pubkey(pubkey), m_xonly(xonly) {}
396 std::optional<CPubKey> GetPubKey(int pos, const SigningProvider&, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
397 {
398 KeyOriginInfo info;
399 CKeyID keyid = m_pubkey.GetID();
400 info.fingerprint = keyid.fingerprint();
401 out.origins.emplace(keyid, std::make_pair(m_pubkey, info));
402 out.pubkeys.emplace(keyid, m_pubkey);
403 return m_pubkey;
404 }
405 bool IsRange() const override { return false; }
406 size_t GetSize() const override { return m_pubkey.size(); }
407 bool IsBIP32() const override { return false; }
408 std::string ToString(StringType type) const override { return m_xonly ? HexStr(m_pubkey).substr(2) : HexStr(m_pubkey); }
409 bool ToPrivateString(const SigningProvider& arg, std::string& ret) const override
410 {
411 std::optional<CKey> key = GetPrivKey(arg);
412 if (!key) {
413 ret = ToString(StringType::PUBLIC);
414 return false;
415 }
416 ret = EncodeSecret(*key);
417 return true;
418 }
419 bool ToNormalizedString(const SigningProvider& arg, std::string& ret, const DescriptorCache* cache) const override
420 {
421 ret = ToString(StringType::PUBLIC);
422 return true;
423 }
424 void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const override
425 {
426 std::optional<CKey> key = GetPrivKey(arg);
427 if (!key) return;
428 out.keys.emplace(key->GetPubKey().GetID(), *key);
429 }
430 std::optional<CPubKey> GetRootPubKey() const override
431 {
432 return m_pubkey;
433 }
434 std::optional<CExtPubKey> GetRootExtPubKey() const override
435 {
436 return std::nullopt;
437 }
438 std::unique_ptr<PubkeyProvider> Clone() const override
439 {
440 return std::make_unique<ConstPubkeyProvider>(m_expr_index, m_pubkey, m_xonly);
441 }
442 bool CanSelfExpand() const final { return true; }
443};
444
445enum class DeriveType {
446 NON_RANGED,
447 UNHARDENED_RANGED,
448 HARDENED_RANGED,
449};
450
452class BIP32PubkeyProvider final : public PubkeyProvider
453{
454 // Root xpub, path, and final derivation step type being used, if any
455 CExtPubKey m_root_extkey;
456 KeyPath m_path;
457 DeriveType m_derive;
458 // Whether ' or h is used in harded derivation
459 bool m_apostrophe;
460
461 bool GetExtKey(const SigningProvider& arg, CExtKey& ret) const
462 {
463 CKey key;
464 if (!arg.GetKey(m_root_extkey.pubkey.GetID(), key)) return false;
465 ret.nDepth = m_root_extkey.nDepth;
466 ret.fingerprint = m_root_extkey.fingerprint;
467 ret.nChild = m_root_extkey.nChild;
468 ret.chaincode = m_root_extkey.chaincode;
469 ret.key = key;
470 return true;
471 }
472
473 // Derives the last xprv
475 {
476 if (!GetExtKey(arg, xprv)) return false;
477 for (auto entry : m_path) {
478 if (!xprv.Derive(xprv, entry)) return false;
479 if (entry >> 31) {
481 }
482 }
483 return true;
484 }
485
486 bool IsHardened() const
487 {
488 if (m_derive == DeriveType::HARDENED_RANGED) return true;
489 return HasHardenedDerivation(m_path);
490 }
491
492public:
493 BIP32PubkeyProvider(uint32_t exp_index, const CExtPubKey& extkey, KeyPath path, DeriveType derive, bool apostrophe) : PubkeyProvider(exp_index), m_root_extkey(extkey), m_path(std::move(path)), m_derive(derive), m_apostrophe(apostrophe) {}
494 bool IsRange() const override { return m_derive != DeriveType::NON_RANGED; }
495 size_t GetSize() const override { return 33; }
496 bool IsBIP32() const override { return true; }
497 std::optional<CPubKey> GetPubKey(int pos, const SigningProvider& arg, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
498 {
499 KeyOriginInfo info;
500 info.fingerprint = m_root_extkey.id_key_fingerprint();
501 info.path = m_path;
502 if (m_derive == DeriveType::UNHARDENED_RANGED) info.path.push_back((uint32_t)pos);
503 if (m_derive == DeriveType::HARDENED_RANGED) info.path.push_back(((uint32_t)pos) | BIP32_HARDENED_FLAG);
504
505 // Derive keys or fetch them from cache
506 CExtPubKey final_extkey = m_root_extkey;
507 CExtPubKey parent_extkey = m_root_extkey;
509 bool der = true;
510 if (read_cache) {
511 if (!read_cache->GetCachedDerivedExtPubKey(m_expr_index, pos, final_extkey)) {
512 if (m_derive == DeriveType::HARDENED_RANGED) return std::nullopt;
513 // Try to get the derivation parent
514 if (!read_cache->GetCachedParentExtPubKey(m_expr_index, parent_extkey)) return std::nullopt;
516 if (m_derive == DeriveType::UNHARDENED_RANGED) der = parent_extkey.Derive(final_extkey, pos);
517 }
518 } else if (IsHardened()) {
521 if (!GetDerivedExtKey(arg, xprv, lh_xprv)) return std::nullopt;
523 if (m_derive == DeriveType::UNHARDENED_RANGED) der = xprv.Derive(xprv, pos);
524 if (m_derive == DeriveType::HARDENED_RANGED) der = xprv.Derive(xprv, pos | BIP32_HARDENED_FLAG);
525 final_extkey = xprv.Neuter();
526 if (lh_xprv.key.IsValid()) {
527 last_hardened_extkey = lh_xprv.Neuter();
528 }
529 } else {
530 for (auto entry : m_path) {
531 if (!parent_extkey.Derive(parent_extkey, entry)) return std::nullopt;
532 }
534 if (m_derive == DeriveType::UNHARDENED_RANGED) der = parent_extkey.Derive(final_extkey, pos);
535 assert(m_derive != DeriveType::HARDENED_RANGED);
536 }
537 if (!der) return std::nullopt;
538
539 out.origins.emplace(final_extkey.pubkey.GetID(), std::make_pair(final_extkey.pubkey, info));
540 out.pubkeys.emplace(final_extkey.pubkey.GetID(), final_extkey.pubkey);
541
542 if (write_cache) {
543 // Only cache parent if there is any unhardened derivation
544 if (m_derive != DeriveType::HARDENED_RANGED) {
545 write_cache->CacheParentExtPubKey(m_expr_index, parent_extkey);
546 // Cache last hardened xpub if we have it
547 if (last_hardened_extkey.pubkey.IsValid()) {
548 write_cache->CacheLastHardenedExtPubKey(m_expr_index, last_hardened_extkey);
549 }
550 } else if (info.path.size() > 0) {
551 write_cache->CacheDerivedExtPubKey(m_expr_index, pos, final_extkey);
552 }
553 }
554
555 return final_extkey.pubkey;
556 }
557 std::string ToString(StringType type, bool normalized) const
558 {
559 bool use_apostrophe{DetermineApostropheUse(type, normalized, m_apostrophe)};
560 std::string ret = EncodeExtPubKey(m_root_extkey) + FormatHDKeypath(m_path, /*apostrophe=*/use_apostrophe);
561 if (IsRange()) {
562 ret += "/*";
563 if (m_derive == DeriveType::HARDENED_RANGED) ret += use_apostrophe ? '\'' : 'h';
564 }
565 return ret;
566 }
567 std::string ToString(StringType type) const override
568 {
569 return ToString(type, /*normalized=*/false);
570 }
571 bool ToPrivateString(const SigningProvider& arg, std::string& out) const override
572 {
573 CExtKey key;
574 if (!GetExtKey(arg, key)) {
575 out = ToString(StringType::PUBLIC);
576 return false;
577 }
578 out = EncodeExtKey(key) + FormatHDKeypath(m_path, /*apostrophe=*/m_apostrophe);
579 if (IsRange()) {
580 out += "/*";
581 if (m_derive == DeriveType::HARDENED_RANGED) out += m_apostrophe ? '\'' : 'h';
582 }
583 return true;
584 }
585 bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache) const override
586 {
587 if (m_derive == DeriveType::HARDENED_RANGED) {
588 out = ToString(StringType::PUBLIC, /*normalized=*/true);
589
590 return true;
591 }
592 // Step backwards to find the last hardened step in the path
593 int i = (int)m_path.size() - 1;
594 for (; i >= 0; --i) {
595 if (m_path.at(i) >> 31) {
596 break;
597 }
598 }
599 // Either no derivation or all unhardened derivation
600 if (i == -1) {
601 out = ToString(StringType::PUBLIC);
602 return true;
603 }
604 // Get the path to the last hardened stup
605 KeyOriginInfo origin;
606 int k = 0;
607 for (; k <= i; ++k) {
608 // Add to the path
609 origin.path.push_back(m_path.at(k));
610 }
611 // Build the remaining path
613 for (; k < (int)m_path.size(); ++k) {
614 end_path.push_back(m_path.at(k));
615 }
616 origin.fingerprint = m_root_extkey.id_key_fingerprint();
617
620 // If we have the cache, just get the parent xpub
621 if (cache != nullptr) {
622 cache->GetCachedLastHardenedExtPubKey(m_expr_index, xpub);
623 }
624 if (!xpub.pubkey.IsValid()) {
625 // Cache miss, or nor cache, or need privkey
627 if (!GetDerivedExtKey(arg, xprv, lh_xprv)) return false;
628 xpub = lh_xprv.Neuter();
629 }
630 assert(xpub.pubkey.IsValid());
631
632 // Build the string
633 std::string origin_str = HexStr(origin.fingerprint) + FormatHDKeypath(origin.path);
635 if (IsRange()) {
636 out += "/*";
637 assert(m_derive == DeriveType::UNHARDENED_RANGED);
638 }
639 return true;
640 }
641 void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const override
642 {
644 CExtKey dummy;
645 if (!GetDerivedExtKey(arg, extkey, dummy)) return;
646 if (m_derive == DeriveType::UNHARDENED_RANGED && !extkey.Derive(extkey, pos)) return;
647 if (m_derive == DeriveType::HARDENED_RANGED && !extkey.Derive(extkey, pos | BIP32_HARDENED_FLAG)) return;
648 out.keys.emplace(extkey.key.GetPubKey().GetID(), extkey.key);
649 }
650 std::optional<CPubKey> GetRootPubKey() const override
651 {
652 return std::nullopt;
653 }
654 std::optional<CExtPubKey> GetRootExtPubKey() const override
655 {
656 return m_root_extkey;
657 }
658 std::unique_ptr<PubkeyProvider> Clone() const override
659 {
660 return std::make_unique<BIP32PubkeyProvider>(m_expr_index, m_root_extkey, m_path, m_derive, m_apostrophe);
661 }
662 bool CanSelfExpand() const override { return !IsHardened(); }
663};
664
666class MuSigPubkeyProvider final : public PubkeyProvider
667{
668private:
670 const std::vector<std::unique_ptr<PubkeyProvider>> m_participants;
672 const KeyPath m_path;
674 mutable std::unique_ptr<PubkeyProvider> m_aggregate_provider;
675 mutable std::optional<CPubKey> m_aggregate_pubkey;
676 const DeriveType m_derive;
677 const bool m_ranged_participants;
678
679 bool IsRangedDerivation() const { return m_derive != DeriveType::NON_RANGED; }
680
681public:
682 MuSigPubkeyProvider(
684 std::vector<std::unique_ptr<PubkeyProvider>> providers,
685 KeyPath path,
686 DeriveType derive
687 )
688 : PubkeyProvider(exp_index),
689 m_participants(std::move(providers)),
690 m_path(std::move(path)),
691 m_derive(derive),
692 m_ranged_participants(std::any_of(m_participants.begin(), m_participants.end(), [](const auto& pubkey) { return pubkey->IsRange(); }))
693 {
694 if (!Assume(!(m_ranged_participants && IsRangedDerivation()))) {
695 throw std::runtime_error("musig(): Cannot have both ranged participants and ranged derivation");
696 }
697 if (!Assume(m_derive != DeriveType::HARDENED_RANGED)) {
698 throw std::runtime_error("musig(): Cannot have hardened derivation");
699 }
700 }
701
702 std::optional<CPubKey> GetPubKey(int pos, const SigningProvider& arg, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
703 {
705 // If the participants are not ranged, we can compute and cache the aggregate pubkey by creating a PubkeyProvider for it
706 if (!m_aggregate_provider && !m_ranged_participants) {
707 // Retrieve the pubkeys from the providers
708 std::vector<CPubKey> pubkeys;
709 for (const auto& prov : m_participants) {
710 std::optional<CPubKey> pubkey = prov->GetPubKey(0, arg, dummy, read_cache, write_cache);
711 if (!pubkey.has_value()) {
712 return std::nullopt;
713 }
714 pubkeys.push_back(pubkey.value());
715 }
716 std::sort(pubkeys.begin(), pubkeys.end());
717
718 // Aggregate the pubkey
719 m_aggregate_pubkey = MuSig2AggregatePubkeys(pubkeys);
720 if (!Assume(m_aggregate_pubkey.has_value())) return std::nullopt;
721
722 // Make our pubkey provider
723 if (IsRangedDerivation() || !m_path.empty()) {
724 // Make the synthetic xpub and construct the BIP32PubkeyProvider
725 CExtPubKey extpub = CreateMuSig2SyntheticXpub(m_aggregate_pubkey.value());
726 m_aggregate_provider = std::make_unique<BIP32PubkeyProvider>(m_expr_index, extpub, m_path, m_derive, /*apostrophe=*/false);
727 } else {
728 m_aggregate_provider = std::make_unique<ConstPubkeyProvider>(m_expr_index, m_aggregate_pubkey.value(), /*xonly=*/false);
729 }
730 }
731
732 // Retrieve all participant pubkeys
733 std::vector<CPubKey> pubkeys;
734 for (const auto& prov : m_participants) {
735 std::optional<CPubKey> pub = prov->GetPubKey(pos, arg, out, read_cache, write_cache);
736 if (!pub) return std::nullopt;
737 pubkeys.emplace_back(*pub);
738 }
739 std::sort(pubkeys.begin(), pubkeys.end());
740
742 if (m_aggregate_provider) {
743 // When we have a cached aggregate key, we are either returning it or deriving from it
744 // Either way, we can passthrough to its GetPubKey
745 // Use a dummy signing provider as private keys do not exist for the aggregate pubkey
746 std::optional<CPubKey> pub = m_aggregate_provider->GetPubKey(pos, dummy, out, read_cache, write_cache);
747 if (!pub) return std::nullopt;
748 pubout = *pub;
749 out.aggregate_pubkeys.emplace(m_aggregate_pubkey.value(), pubkeys);
750 } else {
751 if (!Assume(m_ranged_participants) || !Assume(m_path.empty())) return std::nullopt;
752 // Compute aggregate key from derived participants
753 std::optional<CPubKey> aggregate_pubkey = MuSig2AggregatePubkeys(pubkeys);
754 if (!aggregate_pubkey) return std::nullopt;
756
757 std::unique_ptr<ConstPubkeyProvider> this_agg_provider = std::make_unique<ConstPubkeyProvider>(m_expr_index, aggregate_pubkey.value(), /*xonly=*/false);
758 this_agg_provider->GetPubKey(0, dummy, out, read_cache, write_cache);
759 out.aggregate_pubkeys.emplace(pubout, pubkeys);
760 }
761
762 if (!Assume(pubout.IsValid())) return std::nullopt;
763 return pubout;
764 }
765 bool IsRange() const override { return IsRangedDerivation() || m_ranged_participants; }
766 // musig() expressions can only be used in tr() contexts which have 32 byte xonly pubkeys
767 size_t GetSize() const override { return 32; }
768
769 std::string ToString(StringType type) const override
770 {
771 std::string out = "musig(";
772 for (size_t i = 0; i < m_participants.size(); ++i) {
773 const auto& pubkey = m_participants.at(i);
774 if (i) out += ',';
775 out += pubkey->ToString(type);
776 }
777 out += ')';
778 out += FormatHDKeypath(m_path);
779 if (IsRangedDerivation()) {
780 out += "/*";
781 }
782 return out;
783 }
784 bool ToPrivateString(const SigningProvider& arg, std::string& out) const override
785 {
786 bool any_privkeys = false;
787 out = "musig(";
788 for (size_t i = 0; i < m_participants.size(); ++i) {
789 const auto& pubkey = m_participants.at(i);
790 if (i) out += ',';
791 std::string tmp;
792 if (pubkey->ToPrivateString(arg, tmp)) {
793 any_privkeys = true;
794 }
795 out += tmp;
796 }
797 out += ')';
798 out += FormatHDKeypath(m_path);
799 if (IsRangedDerivation()) {
800 out += "/*";
801 }
802 return any_privkeys;
803 }
804 bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache = nullptr) const override
805 {
806 out = "musig(";
807 for (size_t i = 0; i < m_participants.size(); ++i) {
808 const auto& pubkey = m_participants.at(i);
809 if (i) out += ',';
810 std::string tmp;
811 if (!pubkey->ToNormalizedString(arg, tmp, cache)) {
812 return false;
813 }
814 out += tmp;
815 }
816 out += ')';
817 out += FormatHDKeypath(m_path);
818 if (IsRangedDerivation()) {
819 out += "/*";
820 }
821 return true;
822 }
823
824 void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const override
825 {
826 // Get the private keys for any participants that we have
827 // If there is participant derivation, it will be done.
828 // If there is not, then the participant privkeys will be included directly
829 for (const auto& prov : m_participants) {
830 prov->GetPrivKey(pos, arg, out);
831 }
832 }
833
834 bool HavePrivateKeys(const SigningProvider& arg) const override
835 {
836 return std::ranges::all_of(m_participants, [&](const auto& prov) { return prov->HavePrivateKeys(arg); });
837 }
838
839 // Get RootPubKey and GetRootExtPubKey are used to return the single pubkey underlying the pubkey provider
840 // to be presented to the user in gethdkeys. As this is a multisig construction, there is no single underlying
841 // pubkey hence nothing should be returned.
842 // While the aggregate pubkey could be returned as the root (ext)pubkey, it is not a pubkey that anyone should
843 // be using by itself in a descriptor as it is unspendable without knowing its participants.
844 std::optional<CPubKey> GetRootPubKey() const override
845 {
846 return std::nullopt;
847 }
848 std::optional<CExtPubKey> GetRootExtPubKey() const override
849 {
850 return std::nullopt;
851 }
852
853 std::unique_ptr<PubkeyProvider> Clone() const override
854 {
855 std::vector<std::unique_ptr<PubkeyProvider>> providers;
856 providers.reserve(m_participants.size());
857 for (const std::unique_ptr<PubkeyProvider>& p : m_participants) {
858 providers.emplace_back(p->Clone());
859 }
860 return std::make_unique<MuSigPubkeyProvider>(m_expr_index, std::move(providers), m_path, m_derive);
861 }
862 bool IsBIP32() const override
863 {
864 // musig() can only be a BIP 32 key if all participants are bip32 too
865 return std::all_of(m_participants.begin(), m_participants.end(), [](const auto& pubkey) { return pubkey->IsBIP32(); });
866 }
867 size_t GetKeyCount() const override
868 {
869 return 1 + m_participants.size();
870 }
871 bool CanSelfExpand() const override
872 {
873 // Participants must be self expandable for all MuSig expressions to be self expandable; the aggregate pubkey cannot be stored
874 // in the descriptor cache, so even aggregate-then-derive still requires the self expansion of participants prior to aggregation.
875 for (const auto& key : m_participants) {
876 if (!key->CanSelfExpand()) return false;
877 }
878 return true;
879 }
880};
881
883class DescriptorImpl : public Descriptor
884{
885protected:
887 const std::vector<std::unique_ptr<PubkeyProvider>> m_pubkey_args;
889 const std::string m_name;
891 std::vector<std::string> m_warnings;
892
897 const std::vector<std::unique_ptr<DescriptorImpl>> m_subdescriptor_args;
898
900 virtual std::string ToStringExtra() const { return ""; }
901
912 virtual std::vector<CScript> MakeScripts(const std::vector<CPubKey>& pubkeys, std::span<const CScript> scripts, FlatSigningProvider& out) const = 0;
913
914public:
915 DescriptorImpl(std::vector<std::unique_ptr<PubkeyProvider>> pubkeys, const std::string& name) : m_pubkey_args(std::move(pubkeys)), m_name(name), m_subdescriptor_args() {}
916 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))) {}
917 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)) {}
918
919 enum class StringType
920 {
921 PUBLIC,
922 PRIVATE,
924 CANONICAL,
925 COMPAT, // string calculation that mustn't change over time to stay compatible with previous software versions
926 };
927
928 // NOLINTNEXTLINE(misc-no-recursion)
929 bool IsSolvable() const override
930 {
931 for (const auto& arg : m_subdescriptor_args) {
932 if (!arg->IsSolvable()) return false;
933 }
934 return true;
935 }
936
937 // NOLINTNEXTLINE(misc-no-recursion)
938 bool HavePrivateKeys(const SigningProvider& arg) const override
939 {
940 if (m_pubkey_args.empty() && m_subdescriptor_args.empty()) return false;
941
942 for (const auto& sub: m_subdescriptor_args) {
943 if (!sub->HavePrivateKeys(arg)) return false;
944 }
945
946 for (const auto& pubkey : m_pubkey_args) {
947 if (!pubkey->HavePrivateKeys(arg)) return false;
948 }
949
950 return true;
951 }
952
953 // NOLINTNEXTLINE(misc-no-recursion)
954 bool IsRange() const final
955 {
956 for (const auto& pubkey : m_pubkey_args) {
957 if (pubkey->IsRange()) return true;
958 }
959 for (const auto& arg : m_subdescriptor_args) {
960 if (arg->IsRange()) return true;
961 }
962 return false;
963 }
964
965 // NOLINTNEXTLINE(misc-no-recursion)
966 virtual bool ToStringSubScriptHelper(const SigningProvider* arg, std::string& ret, const StringType type, const DescriptorCache* cache = nullptr) const
967 {
968 size_t pos = 0;
969 bool is_private{type == StringType::PRIVATE};
970 // For private string output, track if at least one key has a private key available.
971 // Initialize to true for non-private types.
972 bool any_success{!is_private};
973 for (const auto& scriptarg : m_subdescriptor_args) {
974 if (pos++) ret += ',';
975 std::string tmp;
976 bool subscript_res{scriptarg->ToStringHelper(arg, tmp, type, cache)};
977 if (!is_private && !subscript_res) return false;
979 ret += tmp;
980 }
981 return any_success;
982 }
983
984 // NOLINTNEXTLINE(misc-no-recursion)
985 virtual bool ToStringHelper(const SigningProvider* arg, std::string& out, const StringType type, const DescriptorCache* cache = nullptr) const
986 {
987 std::string extra = ToStringExtra();
988 size_t pos = extra.size() > 0 ? 1 : 0;
989 std::string ret = m_name + "(" + extra;
990 bool is_private{type == StringType::PRIVATE};
991 // For private string output, track if at least one key has a private key available.
992 // Initialize to true for non-private types.
993 bool any_success{!is_private};
994
995 for (const auto& pubkey : m_pubkey_args) {
996 if (pos++) ret += ',';
997 std::string tmp;
998 switch (type) {
999 case StringType::NORMALIZED:
1000 if (!pubkey->ToNormalizedString(*arg, tmp, cache)) return false;
1001 break;
1002 case StringType::PRIVATE:
1003 any_success = pubkey->ToPrivateString(*arg, tmp) || any_success;
1004 break;
1005 case StringType::PUBLIC:
1006 tmp = pubkey->ToString(PubkeyProvider::StringType::PUBLIC);
1007 break;
1008 case StringType::COMPAT:
1009 tmp = pubkey->ToString(PubkeyProvider::StringType::COMPAT);
1010 break;
1011 case StringType::CANONICAL:
1012 tmp = pubkey->ToString(PubkeyProvider::StringType::CANONICAL);
1013 break;
1014 }
1015 ret += tmp;
1016 }
1017 std::string subscript;
1018 bool subscript_res{ToStringSubScriptHelper(arg, subscript, type, cache)};
1019 if (!is_private && !subscript_res) return false;
1021 if (pos && subscript.size()) ret += ',';
1022 out = std::move(ret) + std::move(subscript) + ")";
1023 return any_success;
1024 }
1025
1026 std::string ToString(bool compat_format) const final
1027 {
1028 std::string ret;
1029 ToStringHelper(nullptr, ret, compat_format ? StringType::COMPAT : StringType::PUBLIC);
1030 return AddChecksum(ret);
1031 }
1032
1033 std::string ToCanonicalString() const final
1034 {
1035 std::string ret;
1036 ToStringHelper(nullptr, ret, StringType::CANONICAL);
1037 return AddChecksum(ret);
1038 }
1039
1040 bool ToPrivateString(const SigningProvider& arg, std::string& out) const override
1041 {
1042 bool has_priv_key{ToStringHelper(&arg, out, StringType::PRIVATE)};
1043 out = AddChecksum(out);
1044 return has_priv_key;
1045 }
1046
1047 bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache) const override final
1048 {
1049 bool ret = ToStringHelper(&arg, out, StringType::NORMALIZED, cache);
1050 out = AddChecksum(out);
1051 return ret;
1052 }
1053
1054 // NOLINTNEXTLINE(misc-no-recursion)
1055 bool ExpandHelper(int pos, const SigningProvider& arg, const DescriptorCache* read_cache, std::vector<CScript>& output_scripts, FlatSigningProvider& out, DescriptorCache* write_cache) const
1056 {
1058 std::vector<CPubKey> pubkeys;
1059 pubkeys.reserve(m_pubkey_args.size());
1060
1061 // Construct temporary data in `pubkeys`, `subscripts`, and `subprovider` to avoid producing output in case of failure.
1062 for (const auto& p : m_pubkey_args) {
1063 std::optional<CPubKey> pubkey = p->GetPubKey(pos, arg, subprovider, read_cache, write_cache);
1064 if (!pubkey) return false;
1065 pubkeys.push_back(pubkey.value());
1066 }
1067 std::vector<CScript> subscripts;
1068 for (const auto& subarg : m_subdescriptor_args) {
1069 std::vector<CScript> outscripts;
1070 if (!subarg->ExpandHelper(pos, arg, read_cache, outscripts, subprovider, write_cache)) return false;
1071 assert(outscripts.size() == 1);
1072 subscripts.emplace_back(std::move(outscripts[0]));
1073 }
1074 out.Merge(std::move(subprovider));
1075
1076 output_scripts = MakeScripts(pubkeys, std::span{subscripts}, out);
1077 return true;
1078 }
1079
1080 bool Expand(int pos, const SigningProvider& provider, std::vector<CScript>& output_scripts, FlatSigningProvider& out, DescriptorCache* write_cache = nullptr) const final
1081 {
1082 return ExpandHelper(pos, provider, nullptr, output_scripts, out, write_cache);
1083 }
1084
1085 bool ExpandFromCache(int pos, const DescriptorCache& read_cache, std::vector<CScript>& output_scripts, FlatSigningProvider& out) const final
1086 {
1087 return ExpandHelper(pos, DUMMY_SIGNING_PROVIDER, &read_cache, output_scripts, out, nullptr);
1088 }
1089
1090 // NOLINTNEXTLINE(misc-no-recursion)
1091 void ExpandPrivate(int pos, const SigningProvider& provider, FlatSigningProvider& out) const final
1092 {
1093 for (const auto& p : m_pubkey_args) {
1094 p->GetPrivKey(pos, provider, out);
1095 }
1096 for (const auto& arg : m_subdescriptor_args) {
1097 arg->ExpandPrivate(pos, provider, out);
1098 }
1099 }
1100
1101 std::optional<OutputType> GetOutputType() const override { return std::nullopt; }
1102
1103 std::optional<int64_t> ScriptSize() const override { return {}; }
1104
1110 virtual std::optional<int64_t> MaxSatSize(bool use_max_sig) const { return {}; }
1111
1112 std::optional<int64_t> MaxSatisfactionWeight(bool) const override { return {}; }
1113
1114 std::optional<int64_t> MaxSatisfactionElems() const override { return {}; }
1115
1116 // NOLINTNEXTLINE(misc-no-recursion)
1117 void GetPubKeys(std::set<CPubKey>& pubkeys, std::set<CExtPubKey>& ext_pubs) const override
1118 {
1119 for (const auto& p : m_pubkey_args) {
1120 std::optional<CPubKey> pub = p->GetRootPubKey();
1121 if (pub) pubkeys.insert(*pub);
1122 std::optional<CExtPubKey> ext_pub = p->GetRootExtPubKey();
1123 if (ext_pub) ext_pubs.insert(*ext_pub);
1124 }
1125 for (const auto& arg : m_subdescriptor_args) {
1126 arg->GetPubKeys(pubkeys, ext_pubs);
1127 }
1128 }
1129
1130 virtual std::unique_ptr<DescriptorImpl> Clone() const = 0;
1131
1132 bool HasScripts() const override { return true; }
1133
1134 // NOLINTNEXTLINE(misc-no-recursion)
1135 std::vector<std::string> Warnings() const override {
1136 std::vector<std::string> all = m_warnings;
1137 for (const auto& sub : m_subdescriptor_args) {
1138 auto sub_w = sub->Warnings();
1139 all.insert(all.end(), sub_w.begin(), sub_w.end());
1140 }
1141 return all;
1142 }
1143
1144 uint32_t GetMaxKeyExpr() const final
1145 {
1147 std::vector<const DescriptorImpl*> todo = {this};
1148 while (!todo.empty()) {
1149 const DescriptorImpl* desc = todo.back();
1150 todo.pop_back();
1151 for (const auto& p : desc->m_pubkey_args) {
1152 max_key_expr = std::max(max_key_expr, p->m_expr_index);
1153 }
1154 for (const auto& s : desc->m_subdescriptor_args) {
1155 todo.push_back(s.get());
1156 }
1157 }
1158 return max_key_expr;
1159 }
1160
1161 size_t GetKeyCount() const final
1162 {
1163 size_t count{0};
1164 std::vector<const DescriptorImpl*> todo = {this};
1165 while (!todo.empty()) {
1166 const DescriptorImpl* desc = todo.back();
1167 todo.pop_back();
1168 for (const auto& p : desc->m_pubkey_args) {
1169 count += p->GetKeyCount();
1170 }
1171 for (const auto& s : desc->m_subdescriptor_args) {
1172 todo.push_back(s.get());
1173 }
1174 }
1175 return count;
1176 }
1177
1178 // NOLINTNEXTLINE(misc-no-recursion)
1179 bool CanSelfExpand() const override
1180 {
1181 for (const auto& key : m_pubkey_args) {
1182 if (!key->CanSelfExpand()) return false;
1183 }
1184 for (const auto& sub : m_subdescriptor_args) {
1185 if (!sub->CanSelfExpand()) return false;
1186 }
1187 return true;
1188 }
1189};
1190
1192class AddressDescriptor final : public DescriptorImpl
1193{
1194 const CTxDestination m_destination;
1195protected:
1196 std::string ToStringExtra() const override { return EncodeDestination(m_destination); }
1197 std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, std::span<const CScript>, FlatSigningProvider&) const override { return Vector(GetScriptForDestination(m_destination)); }
1198public:
1199 AddressDescriptor(CTxDestination destination) : DescriptorImpl({}, "addr"), m_destination(std::move(destination)) {}
1200 bool IsSolvable() const final { return false; }
1201
1202 std::optional<OutputType> GetOutputType() const override
1203 {
1204 return OutputTypeFromDestination(m_destination);
1205 }
1206 bool IsSingleType() const final { return true; }
1207 bool ToPrivateString(const SigningProvider& arg, std::string& out) const final { return false; }
1208
1209 std::optional<int64_t> ScriptSize() const override { return GetScriptForDestination(m_destination).size(); }
1210 std::unique_ptr<DescriptorImpl> Clone() const override
1211 {
1212 return std::make_unique<AddressDescriptor>(m_destination);
1213 }
1214};
1215
1217class RawDescriptor final : public DescriptorImpl
1218{
1219 const CScript m_script;
1220protected:
1221 std::string ToStringExtra() const override { return HexStr(m_script); }
1222 std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, std::span<const CScript>, FlatSigningProvider&) const override { return Vector(m_script); }
1223public:
1224 RawDescriptor(CScript script) : DescriptorImpl({}, "raw"), m_script(std::move(script)) {}
1225 bool IsSolvable() const final { return false; }
1226
1227 std::optional<OutputType> GetOutputType() const override
1228 {
1229 CTxDestination dest;
1230 ExtractDestination(m_script, dest);
1231 return OutputTypeFromDestination(dest);
1232 }
1233 bool IsSingleType() const final { return true; }
1234 bool ToPrivateString(const SigningProvider& arg, std::string& out) const final { return false; }
1235
1236 std::optional<int64_t> ScriptSize() const override { return m_script.size(); }
1237
1238 std::unique_ptr<DescriptorImpl> Clone() const override
1239 {
1240 return std::make_unique<RawDescriptor>(m_script);
1241 }
1242};
1243
1245class PKDescriptor final : public DescriptorImpl
1246{
1247private:
1248 const bool m_xonly;
1249protected:
1250 std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override
1251 {
1252 if (m_xonly) {
1254 return Vector(std::move(script));
1255 } else {
1256 return Vector(GetScriptForRawPubKey(keys[0]));
1257 }
1258 }
1259public:
1260 PKDescriptor(std::unique_ptr<PubkeyProvider> prov, bool xonly = false) : DescriptorImpl(Vector(std::move(prov)), "pk"), m_xonly(xonly) {}
1261 bool IsSingleType() const final { return true; }
1262
1263 std::optional<int64_t> ScriptSize() const override {
1264 return 1 + (m_xonly ? 32 : m_pubkey_args[0]->GetSize()) + 1;
1265 }
1266
1267 std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
1268 const auto ecdsa_sig_size = use_max_sig ? 72 : 71;
1269 return 1 + (m_xonly ? 65 : ecdsa_sig_size);
1270 }
1271
1272 std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
1274 }
1275
1276 std::optional<int64_t> MaxSatisfactionElems() const override { return 1; }
1277
1278 std::unique_ptr<DescriptorImpl> Clone() const override
1279 {
1280 return std::make_unique<PKDescriptor>(m_pubkey_args.at(0)->Clone(), m_xonly);
1281 }
1282};
1283
1285class PKHDescriptor final : public DescriptorImpl
1286{
1287protected:
1288 std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override
1289 {
1290 CKeyID id = keys[0].GetID();
1292 }
1293public:
1294 PKHDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "pkh") {}
1295 std::optional<OutputType> GetOutputType() const override { return OutputType::LEGACY; }
1296 bool IsSingleType() const final { return true; }
1297
1298 std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 1 + 20 + 1 + 1; }
1299
1300 std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
1301 const auto sig_size = use_max_sig ? 72 : 71;
1302 return 1 + sig_size + 1 + m_pubkey_args[0]->GetSize();
1303 }
1304
1305 std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
1307 }
1308
1309 std::optional<int64_t> MaxSatisfactionElems() const override { return 2; }
1310
1311 std::unique_ptr<DescriptorImpl> Clone() const override
1312 {
1313 return std::make_unique<PKHDescriptor>(m_pubkey_args.at(0)->Clone());
1314 }
1315};
1316
1318class WPKHDescriptor final : public DescriptorImpl
1319{
1320protected:
1321 std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override
1322 {
1323 CKeyID id = keys[0].GetID();
1325 }
1326public:
1327 WPKHDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "wpkh") {}
1328 std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32; }
1329 bool IsSingleType() const final { return true; }
1330
1331 std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 20; }
1332
1333 std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
1334 const auto sig_size = use_max_sig ? 72 : 71;
1335 return (1 + sig_size + 1 + 33);
1336 }
1337
1338 std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
1339 return MaxSatSize(use_max_sig);
1340 }
1341
1342 std::optional<int64_t> MaxSatisfactionElems() const override { return 2; }
1343
1344 std::unique_ptr<DescriptorImpl> Clone() const override
1345 {
1346 return std::make_unique<WPKHDescriptor>(m_pubkey_args.at(0)->Clone());
1347 }
1348};
1349
1351class ComboDescriptor final : public DescriptorImpl
1352{
1353protected:
1354 std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider& out) const override
1355 {
1356 std::vector<CScript> ret;
1357 CKeyID id = keys[0].GetID();
1358 ret.emplace_back(GetScriptForRawPubKey(keys[0])); // P2PK
1359 ret.emplace_back(GetScriptForDestination(PKHash(id))); // P2PKH
1360 if (keys[0].IsCompressed()) {
1362 out.scripts.emplace(CScriptID(p2wpkh), p2wpkh);
1363 ret.emplace_back(p2wpkh);
1364 ret.emplace_back(GetScriptForDestination(ScriptHash(p2wpkh))); // P2SH-P2WPKH
1365 }
1366 return ret;
1367 }
1368public:
1369 ComboDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "combo") {}
1370 bool IsSingleType() const final { return false; }
1371 std::unique_ptr<DescriptorImpl> Clone() const override
1372 {
1373 return std::make_unique<ComboDescriptor>(m_pubkey_args.at(0)->Clone());
1374 }
1375};
1376
1378class MultisigDescriptor final : public DescriptorImpl
1379{
1380 const int m_threshold;
1381 const bool m_sorted;
1382protected:
1383 std::string ToStringExtra() const override { return strprintf("%i", m_threshold); }
1384 std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override {
1385 if (m_sorted) {
1386 std::vector<CPubKey> sorted_keys(keys);
1387 std::sort(sorted_keys.begin(), sorted_keys.end());
1388 return Vector(GetScriptForMultisig(m_threshold, sorted_keys));
1389 }
1390 return Vector(GetScriptForMultisig(m_threshold, keys));
1391 }
1392public:
1393 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) {}
1394 bool IsSingleType() const final { return true; }
1395
1396 std::optional<int64_t> ScriptSize() const override {
1397 const auto n_keys = m_pubkey_args.size();
1398 auto op = [](int64_t acc, const std::unique_ptr<PubkeyProvider>& pk) { return acc + 1 + pk->GetSize();};
1399 const auto pubkeys_size{std::accumulate(m_pubkey_args.begin(), m_pubkey_args.end(), int64_t{0}, op)};
1400 return 1 + BuildScript(n_keys).size() + BuildScript(m_threshold).size() + pubkeys_size;
1401 }
1402
1403 std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
1404 const auto sig_size = use_max_sig ? 72 : 71;
1405 return (1 + (1 + sig_size) * m_threshold);
1406 }
1407
1408 std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
1410 }
1411
1412 std::optional<int64_t> MaxSatisfactionElems() const override { return 1 + m_threshold; }
1413
1414 std::unique_ptr<DescriptorImpl> Clone() const override
1415 {
1416 std::vector<std::unique_ptr<PubkeyProvider>> providers;
1417 providers.reserve(m_pubkey_args.size());
1418 std::transform(m_pubkey_args.begin(), m_pubkey_args.end(), std::back_inserter(providers), [](const std::unique_ptr<PubkeyProvider>& p) { return p->Clone(); });
1419 return std::make_unique<MultisigDescriptor>(m_threshold, std::move(providers), m_sorted);
1420 }
1421};
1422
1424class MultiADescriptor final : public DescriptorImpl
1425{
1426 const int m_threshold;
1427 const bool m_sorted;
1428protected:
1429 std::string ToStringExtra() const override { return strprintf("%i", m_threshold); }
1430 std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override {
1431 CScript ret;
1432 std::vector<XOnlyPubKey> xkeys;
1433 xkeys.reserve(keys.size());
1434 for (const auto& key : keys) xkeys.emplace_back(key);
1435 if (m_sorted) std::sort(xkeys.begin(), xkeys.end());
1437 for (size_t i = 1; i < keys.size(); ++i) {
1439 }
1440 ret << m_threshold << OP_NUMEQUAL;
1441 return Vector(std::move(ret));
1442 }
1443public:
1444 MultiADescriptor(int threshold, std::vector<std::unique_ptr<PubkeyProvider>> providers, bool sorted = false) : DescriptorImpl(std::move(providers), sorted ? "sortedmulti_a" : "multi_a"), m_threshold(threshold), m_sorted(sorted) {}
1445 bool IsSingleType() const final { return true; }
1446
1447 std::optional<int64_t> ScriptSize() const override {
1448 const auto n_keys = m_pubkey_args.size();
1449 return (1 + 32 + 1) * n_keys + BuildScript(m_threshold).size() + 1;
1450 }
1451
1452 std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
1453 return (1 + 65) * m_threshold + (m_pubkey_args.size() - m_threshold);
1454 }
1455
1456 std::optional<int64_t> MaxSatisfactionElems() const override { return m_pubkey_args.size(); }
1457
1458 std::unique_ptr<DescriptorImpl> Clone() const override
1459 {
1460 std::vector<std::unique_ptr<PubkeyProvider>> providers;
1461 providers.reserve(m_pubkey_args.size());
1462 for (const auto& arg : m_pubkey_args) {
1463 providers.push_back(arg->Clone());
1464 }
1465 return std::make_unique<MultiADescriptor>(m_threshold, std::move(providers), m_sorted);
1466 }
1467};
1468
1470class SHDescriptor final : public DescriptorImpl
1471{
1472protected:
1473 std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, std::span<const CScript> scripts, FlatSigningProvider& out) const override
1474 {
1475 auto ret = Vector(GetScriptForDestination(ScriptHash(scripts[0])));
1476 if (ret.size()) out.scripts.emplace(CScriptID(scripts[0]), scripts[0]);
1477 return ret;
1478 }
1479
1480 bool IsSegwit() const { return m_subdescriptor_args[0]->GetOutputType() == OutputType::BECH32; }
1481
1482public:
1483 SHDescriptor(std::unique_ptr<DescriptorImpl> desc) : DescriptorImpl({}, std::move(desc), "sh") {}
1484
1485 std::optional<OutputType> GetOutputType() const override
1486 {
1487 assert(m_subdescriptor_args.size() == 1);
1488 if (IsSegwit()) return OutputType::P2SH_SEGWIT;
1489 return OutputType::LEGACY;
1490 }
1491 bool IsSingleType() const final { return true; }
1492
1493 std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 20 + 1; }
1494
1495 std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
1496 if (const auto sat_size = m_subdescriptor_args[0]->MaxSatSize(use_max_sig)) {
1497 if (const auto subscript_size = m_subdescriptor_args[0]->ScriptSize()) {
1498 // The subscript is never witness data.
1500 // The weight depends on whether the inner descriptor is satisfied using the witness stack.
1501 if (IsSegwit()) return subscript_weight + *sat_size;
1503 }
1504 }
1505 return {};
1506 }
1507
1508 std::optional<int64_t> MaxSatisfactionElems() const override {
1509 if (const auto sub_elems = m_subdescriptor_args[0]->MaxSatisfactionElems()) return 1 + *sub_elems;
1510 return {};
1511 }
1512
1513 std::unique_ptr<DescriptorImpl> Clone() const override
1514 {
1515 return std::make_unique<SHDescriptor>(m_subdescriptor_args.at(0)->Clone());
1516 }
1517};
1518
1520class WSHDescriptor final : public DescriptorImpl
1521{
1522protected:
1523 std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, std::span<const CScript> scripts, FlatSigningProvider& out) const override
1524 {
1526 if (ret.size()) out.scripts.emplace(CScriptID(scripts[0]), scripts[0]);
1527 return ret;
1528 }
1529public:
1530 WSHDescriptor(std::unique_ptr<DescriptorImpl> desc) : DescriptorImpl({}, std::move(desc), "wsh") {}
1531 std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32; }
1532 bool IsSingleType() const final { return true; }
1533
1534 std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
1535
1536 std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
1537 if (const auto sat_size = m_subdescriptor_args[0]->MaxSatSize(use_max_sig)) {
1538 if (const auto subscript_size = m_subdescriptor_args[0]->ScriptSize()) {
1540 }
1541 }
1542 return {};
1543 }
1544
1545 std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
1546 return MaxSatSize(use_max_sig);
1547 }
1548
1549 std::optional<int64_t> MaxSatisfactionElems() const override {
1550 if (const auto sub_elems = m_subdescriptor_args[0]->MaxSatisfactionElems()) return 1 + *sub_elems;
1551 return {};
1552 }
1553
1554 std::unique_ptr<DescriptorImpl> Clone() const override
1555 {
1556 return std::make_unique<WSHDescriptor>(m_subdescriptor_args.at(0)->Clone());
1557 }
1558};
1559
1561class TRDescriptor final : public DescriptorImpl
1562{
1563 std::vector<int> m_depths;
1564protected:
1565 std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript> scripts, FlatSigningProvider& out) const override
1566 {
1568 assert(m_depths.size() == scripts.size());
1569 for (size_t pos = 0; pos < m_depths.size(); ++pos) {
1570 builder.Add(m_depths[pos], scripts[pos], TAPROOT_LEAF_TAPSCRIPT);
1571 }
1572 if (!builder.IsComplete()) return {};
1573 assert(keys.size() == 1);
1574 XOnlyPubKey xpk(keys[0]);
1575 if (!xpk.IsFullyValid()) return {};
1576 builder.Finalize(xpk);
1577 WitnessV1Taproot output = builder.GetOutput();
1578 out.tr_trees[output] = builder;
1579 return Vector(GetScriptForDestination(output));
1580 }
1581 bool ToStringSubScriptHelper(const SigningProvider* arg, std::string& ret, const StringType type, const DescriptorCache* cache = nullptr) const override
1582 {
1583 if (m_depths.empty()) {
1584 // If there are no sub-descriptors and a PRIVATE string
1585 // is requested, return `false` to indicate that the presence
1586 // of a private key depends solely on the internal key (which is checked
1587 // in the caller), not on any sub-descriptor. This ensures correct behavior for
1588 // descriptors like tr(internal_key) when checking for private keys.
1589 return type != StringType::PRIVATE;
1590 }
1591 std::vector<bool> path;
1592 bool is_private{type == StringType::PRIVATE};
1593 // For private string output, track if at least one key has a private key available.
1594 // Initialize to true for non-private types.
1595 bool any_success{!is_private};
1596
1597 for (size_t pos = 0; pos < m_depths.size(); ++pos) {
1598 if (pos) ret += ',';
1599 while ((int)path.size() <= m_depths[pos]) {
1600 if (path.size()) ret += '{';
1601 path.push_back(false);
1602 }
1603 std::string tmp;
1604 bool subscript_res{m_subdescriptor_args[pos]->ToStringHelper(arg, tmp, type, cache)};
1605 if (!is_private && !subscript_res) return false;
1607 ret += tmp;
1608 while (!path.empty() && path.back()) {
1609 if (path.size() > 1) ret += '}';
1610 path.pop_back();
1611 }
1612 if (!path.empty()) path.back() = true;
1613 }
1614 return any_success;
1615 }
1616public:
1617 TRDescriptor(std::unique_ptr<PubkeyProvider> internal_key, std::vector<std::unique_ptr<DescriptorImpl>> descs, std::vector<int> depths) :
1618 DescriptorImpl(Vector(std::move(internal_key)), std::move(descs), "tr"), m_depths(std::move(depths))
1619 {
1620 assert(m_subdescriptor_args.size() == m_depths.size());
1621 }
1622 std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32M; }
1623 bool IsSingleType() const final { return true; }
1624
1625 std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
1626
1627 std::optional<int64_t> MaxSatisfactionWeight(bool) const override {
1628 // FIXME: We assume keypath spend, which can lead to very large underestimations.
1629 return 1 + 65;
1630 }
1631
1632 std::optional<int64_t> MaxSatisfactionElems() const override {
1633 // FIXME: See above, we assume keypath spend.
1634 return 1;
1635 }
1636
1637 std::unique_ptr<DescriptorImpl> Clone() const override
1638 {
1639 std::vector<std::unique_ptr<DescriptorImpl>> subdescs;
1640 subdescs.reserve(m_subdescriptor_args.size());
1641 std::transform(m_subdescriptor_args.begin(), m_subdescriptor_args.end(), std::back_inserter(subdescs), [](const std::unique_ptr<DescriptorImpl>& d) { return d->Clone(); });
1642 return std::make_unique<TRDescriptor>(m_pubkey_args.at(0)->Clone(), std::move(subdescs), m_depths);
1643 }
1644};
1645
1646/* We instantiate Miniscript here with a simple integer as key type.
1647 * The value of these key integers are an index in the
1648 * DescriptorImpl::m_pubkey_args vector.
1649 */
1650
1654class ScriptMaker {
1656 const std::vector<CPubKey>& m_keys;
1658 const miniscript::MiniscriptContext m_script_ctx;
1659
1663 uint160 GetHash160(uint32_t key) const {
1664 if (miniscript::IsTapscript(m_script_ctx)) {
1665 return Hash160(XOnlyPubKey{m_keys[key]});
1666 }
1667 return m_keys[key].GetID();
1668 }
1669
1670public:
1671 ScriptMaker(const std::vector<CPubKey>& keys LIFETIMEBOUND, const miniscript::MiniscriptContext script_ctx) : m_keys(keys), m_script_ctx{script_ctx} {}
1672
1673 std::vector<unsigned char> ToPKBytes(uint32_t key) const {
1674 // In Tapscript keys always serialize as x-only, whether an x-only key was used in the descriptor or not.
1675 if (!miniscript::IsTapscript(m_script_ctx)) {
1676 return {m_keys[key].begin(), m_keys[key].end()};
1677 }
1678 const XOnlyPubKey xonly_pubkey{m_keys[key]};
1679 return {xonly_pubkey.begin(), xonly_pubkey.end()};
1680 }
1681
1682 std::vector<unsigned char> ToPKHBytes(uint32_t key) const {
1683 auto id = GetHash160(key);
1684 return {id.begin(), id.end()};
1685 }
1686};
1687
1691class StringMaker {
1693 const SigningProvider* m_arg;
1695 const std::vector<std::unique_ptr<PubkeyProvider>>& m_pubkeys;
1697 const DescriptorImpl::StringType m_type;
1698 const DescriptorCache* m_cache;
1699
1700public:
1701 StringMaker(const SigningProvider* arg LIFETIMEBOUND,
1702 const std::vector<std::unique_ptr<PubkeyProvider>>& pubkeys LIFETIMEBOUND,
1703 DescriptorImpl::StringType type,
1704 const DescriptorCache* cache LIFETIMEBOUND)
1705 : m_arg(arg), m_pubkeys(pubkeys), m_type(type), m_cache(cache) {}
1706
1707 std::optional<std::string> ToString(uint32_t key, bool& has_priv_key) const
1708 {
1709 std::string ret;
1710 has_priv_key = false;
1711 switch (m_type) {
1712 case DescriptorImpl::StringType::PUBLIC:
1713 ret = m_pubkeys[key]->ToString(PubkeyProvider::StringType::PUBLIC);
1714 break;
1715 case DescriptorImpl::StringType::PRIVATE:
1716 has_priv_key = m_pubkeys[key]->ToPrivateString(*m_arg, ret);
1717 break;
1718 case DescriptorImpl::StringType::NORMALIZED:
1719 if (!m_pubkeys[key]->ToNormalizedString(*m_arg, ret, m_cache)) return {};
1720 break;
1721 case DescriptorImpl::StringType::COMPAT:
1722 // For backwards compatibility, we do not pass StringType::COMPAT.
1723 // Prior to 31.0, COMPAT was not provided, so PUBLIC was in use. From this string,
1724 // DescriptorSPKM IDs were computed from this string, so the incorrect behavior
1725 // must be preserved for wallets with Miniscript descriptors to be loaded
1726 ret = m_pubkeys[key]->ToString(PubkeyProvider::StringType::PUBLIC);
1727 break;
1728 case DescriptorImpl::StringType::CANONICAL:
1729 ret = m_pubkeys[key]->ToString(PubkeyProvider::StringType::CANONICAL);
1730 break;
1731 }
1732 return ret;
1733 }
1734};
1735
1736class MiniscriptDescriptor final : public DescriptorImpl
1737{
1738private:
1740
1741protected:
1742 std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript> scripts,
1743 FlatSigningProvider& provider) const override
1744 {
1745 const auto script_ctx{m_node.GetMsCtx()};
1746 for (const auto& key : keys) {
1747 if (miniscript::IsTapscript(script_ctx)) {
1748 provider.pubkeys.emplace(Hash160(XOnlyPubKey{key}), key);
1749 } else {
1750 provider.pubkeys.emplace(key.GetID(), key);
1751 }
1752 }
1753 return Vector(m_node.ToScript(ScriptMaker(keys, script_ctx)));
1754 }
1755
1756public:
1757 MiniscriptDescriptor(std::vector<std::unique_ptr<PubkeyProvider>> providers, miniscript::Node<uint32_t>&& node)
1758 : DescriptorImpl(std::move(providers), "?"), m_node(std::move(node))
1759 {
1760 // Traverse miniscript tree for unsafe use of older()
1762 if (node.Fragment() == miniscript::Fragment::OLDER) {
1763 const uint32_t raw = node.K();
1764 const uint32_t value_part = raw & ~CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG;
1765 if (value_part > CTxIn::SEQUENCE_LOCKTIME_MASK) {
1766 const bool is_time_based = (raw & CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) != 0;
1767 if (is_time_based) {
1768 m_warnings.push_back(strprintf("time-based relative locktime: older(%u) > (65535 * 512) seconds is unsafe", raw));
1769 } else {
1770 m_warnings.push_back(strprintf("height-based relative locktime: older(%u) > 65535 blocks is unsafe", raw));
1771 }
1772 }
1773 }
1774 });
1775 }
1776
1777 bool ToStringHelper(const SigningProvider* arg, std::string& out, const StringType type,
1778 const DescriptorCache* cache = nullptr) const override
1779 {
1780 bool has_priv_key{false};
1781 auto res = m_node.ToString(StringMaker(arg, m_pubkey_args, type, cache), has_priv_key);
1782 if (res) out = *res;
1783 if (type == StringType::PRIVATE) {
1784 Assume(res.has_value());
1785 return has_priv_key;
1786 } else {
1787 return res.has_value();
1788 }
1789 }
1790
1791 bool IsSolvable() const override { return true; }
1792 bool IsSingleType() const final { return true; }
1793
1794 std::optional<int64_t> ScriptSize() const override { return m_node.ScriptSize(); }
1795
1796 std::optional<int64_t> MaxSatSize(bool) const override
1797 {
1798 // For Miniscript we always assume high-R ECDSA signatures.
1799 return m_node.GetWitnessSize();
1800 }
1801
1802 std::optional<int64_t> MaxSatisfactionElems() const override
1803 {
1804 return m_node.GetStackSize();
1805 }
1806
1807 std::unique_ptr<DescriptorImpl> Clone() const override
1808 {
1809 std::vector<std::unique_ptr<PubkeyProvider>> providers;
1810 providers.reserve(m_pubkey_args.size());
1811 for (const auto& arg : m_pubkey_args) {
1812 providers.push_back(arg->Clone());
1813 }
1814 return std::make_unique<MiniscriptDescriptor>(std::move(providers), m_node.Clone());
1815 }
1816};
1817
1819class RawTRDescriptor final : public DescriptorImpl
1820{
1821protected:
1822 std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript> scripts, FlatSigningProvider& out) const override
1823 {
1824 assert(keys.size() == 1);
1825 XOnlyPubKey xpk(keys[0]);
1826 if (!xpk.IsFullyValid()) return {};
1827 WitnessV1Taproot output{xpk};
1828 return Vector(GetScriptForDestination(output));
1829 }
1830public:
1831 RawTRDescriptor(std::unique_ptr<PubkeyProvider> output_key) : DescriptorImpl(Vector(std::move(output_key)), "rawtr") {}
1832 std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32M; }
1833 bool IsSingleType() const final { return true; }
1834
1835 std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
1836
1837 std::optional<int64_t> MaxSatisfactionWeight(bool) const override {
1838 // We can't know whether there is a script path, so assume key path spend.
1839 return 1 + 65;
1840 }
1841
1842 std::optional<int64_t> MaxSatisfactionElems() const override {
1843 // See above, we assume keypath spend.
1844 return 1;
1845 }
1846
1847 std::unique_ptr<DescriptorImpl> Clone() const override
1848 {
1849 return std::make_unique<RawTRDescriptor>(m_pubkey_args.at(0)->Clone());
1850 }
1851};
1852
1854class UnusedDescriptor final : public DescriptorImpl
1855{
1856protected:
1857 std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript> scripts, FlatSigningProvider& out) const override { return {}; }
1858public:
1859 UnusedDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "unused") {}
1860 bool IsSingleType() const final { return true; }
1861 bool HasScripts() const override { return false; }
1862
1863 std::unique_ptr<DescriptorImpl> Clone() const override
1864 {
1865 return std::make_unique<UnusedDescriptor>(m_pubkey_args.at(0)->Clone());
1866 }
1867};
1868
1869
1871// Parser //
1873
1874enum class ParseScriptContext {
1875 TOP,
1876 P2SH,
1877 P2WPKH,
1878 P2WSH,
1879 P2TR,
1880 MUSIG,
1881};
1882
1894[[nodiscard]] bool ParseKeyPath(const std::vector<std::span<const char>>& split, std::vector<KeyPath>& out, bool& apostrophe, std::string& error, bool allow_multipath, bool& has_hardened)
1895{
1896 auto parse_elem = [&](std::span<const char> elem) -> std::optional<uint32_t> {
1897 const auto parsed{ParseKeyPathElement(elem)};
1898 if (!parsed) {
1899 error = parsed.error();
1900 return std::nullopt;
1901 }
1902 if (parsed->is_hardened) {
1903 has_hardened = true;
1904 apostrophe = elem.back() == '\'';
1905 }
1906 return parsed->ChildNumber();
1907 };
1908
1909 KeyPath path;
1910 struct MultipathSubstitutes {
1911 size_t placeholder_index;
1912 std::vector<uint32_t> values;
1913 };
1914 std::optional<MultipathSubstitutes> substitutes;
1915 has_hardened = false;
1916
1917 for (size_t i = 1; i < split.size(); ++i) {
1918 const std::span<const char>& elem = split[i];
1919
1920 // Check if element contains multipath specifier
1921 if (!elem.empty() && elem.front() == '<' && elem.back() == '>') {
1922 if (!allow_multipath) {
1923 error = strprintf("Key path value '%s' specifies multipath in a section where multipath is not allowed", std::string(elem.begin(), elem.end()));
1924 return false;
1925 }
1926 if (substitutes) {
1927 error = "Multiple multipath key path specifiers found";
1928 return false;
1929 }
1930
1931 // Parse each possible value
1932 std::vector<std::span<const char>> nums = Split(std::span(elem.begin()+1, elem.end()-1), ";");
1933 if (nums.size() < 2) {
1934 error = "Multipath key path specifiers must have at least two items";
1935 return false;
1936 }
1937
1938 substitutes.emplace();
1939 std::unordered_set<uint32_t> seen_substitutes;
1940 for (const auto& num : nums) {
1941 const auto& op_num = parse_elem(num);
1942 if (!op_num) return false;
1943 auto [_, inserted] = seen_substitutes.insert(*op_num);
1944 if (!inserted) {
1945 error = strprintf("Duplicated key path value %u in multipath specifier", *op_num);
1946 return false;
1947 }
1948 substitutes->values.emplace_back(*op_num);
1949 }
1950
1951 path.emplace_back(); // Placeholder for multipath segment
1952 substitutes->placeholder_index = path.size() - 1;
1953 } else {
1954 const auto& op_num = parse_elem(elem);
1955 if (!op_num) return false;
1956 path.emplace_back(*op_num);
1957 }
1958 }
1959
1960 if (!substitutes) {
1961 out.emplace_back(std::move(path));
1962 } else {
1963 // Replace the multipath placeholder with each value while generating paths
1965 KeyPath branch_path = path;
1966 branch_path[substitutes->placeholder_index] = substitute;
1967 out.emplace_back(std::move(branch_path));
1968 }
1969 }
1970 return true;
1971}
1972
1973[[nodiscard]] bool ParseKeyPath(const std::vector<std::span<const char>>& split, std::vector<KeyPath>& out, bool& apostrophe, std::string& error, bool allow_multipath)
1974{
1975 bool dummy;
1976 return ParseKeyPath(split, out, apostrophe, error, allow_multipath, /*has_hardened=*/dummy);
1977}
1978
1979static DeriveType ParseDeriveType(std::vector<std::span<const char>>& split, bool& apostrophe)
1980{
1981 DeriveType type = DeriveType::NON_RANGED;
1982 if (std::ranges::equal(split.back(), std::span{"*"}.first(1))) {
1983 split.pop_back();
1984 type = DeriveType::UNHARDENED_RANGED;
1985 } else if (std::ranges::equal(split.back(), std::span{"*'"}.first(2)) || std::ranges::equal(split.back(), std::span{"*h"}.first(2))) {
1986 apostrophe = std::ranges::equal(split.back(), std::span{"*'"}.first(2));
1987 split.pop_back();
1988 type = DeriveType::HARDENED_RANGED;
1989 }
1990 return type;
1991}
1992
1994std::vector<std::unique_ptr<PubkeyProvider>> ParsePubkeyInner(uint32_t& key_exp_index, const std::span<const char>& sp, ParseScriptContext ctx, FlatSigningProvider& out, bool& apostrophe, std::string& error)
1995{
1996 std::vector<std::unique_ptr<PubkeyProvider>> ret;
1997 bool permit_uncompressed = ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH;
1998 auto split = Split(sp, '/');
1999 std::string_view str(split[0].data(), split[0].size());
2000 if (str.size() == 0) {
2001 error = "No key provided";
2002 return {};
2003 }
2004 if (IsSpace(str.front()) || IsSpace(str.back())) {
2005 error = strprintf("Key '%s' is invalid due to whitespace", str);
2006 return {};
2007 }
2008 if (split.size() == 1) {
2009 if (IsHex(str)) {
2010 std::vector<unsigned char> data = ParseHex(str);
2011 CPubKey pubkey(data);
2012 if (pubkey.IsValid() && !pubkey.IsValidNonHybrid()) {
2013 error = "Hybrid public keys are not allowed";
2014 return {};
2015 }
2016 if (pubkey.IsFullyValid()) {
2017 if (permit_uncompressed || pubkey.IsCompressed()) {
2018 ret.emplace_back(std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, false));
2019 ++key_exp_index;
2020 return ret;
2021 } else {
2022 error = "Uncompressed keys are not allowed";
2023 return {};
2024 }
2025 } else if (data.size() == 32 && ctx == ParseScriptContext::P2TR) {
2026 unsigned char fullkey[33] = {0x02};
2027 std::copy(data.begin(), data.end(), fullkey + 1);
2028 pubkey.Set(std::begin(fullkey), std::end(fullkey));
2029 if (pubkey.IsFullyValid()) {
2030 ret.emplace_back(std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, true));
2031 ++key_exp_index;
2032 return ret;
2033 }
2034 }
2035 error = strprintf("Pubkey '%s' is invalid", str);
2036 return {};
2037 }
2038 CKey key = DecodeSecret(str);
2039 if (key.IsValid()) {
2040 if (permit_uncompressed || key.IsCompressed()) {
2041 CPubKey pubkey = key.GetPubKey();
2042 out.keys.emplace(pubkey.GetID(), key);
2043 ret.emplace_back(std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, ctx == ParseScriptContext::P2TR));
2044 ++key_exp_index;
2045 return ret;
2046 } else {
2047 error = "Uncompressed keys are not allowed";
2048 return {};
2049 }
2050 }
2051 }
2052 auto [extkey, extpubkey] = DecodeExtKeyOrPubKey(str);
2053 if (!extkey.key.IsValid() && !extpubkey.pubkey.IsValid()) {
2054 error = strprintf("key '%s' is not valid", str);
2055 return {};
2056 }
2057 std::vector<KeyPath> paths;
2058 DeriveType type = ParseDeriveType(split, apostrophe);
2059 if (!ParseKeyPath(split, paths, apostrophe, error, /*allow_multipath=*/true)) return {};
2060 if (extkey.key.IsValid()) {
2061 extpubkey = extkey.Neuter();
2062 out.keys.emplace(extpubkey.pubkey.GetID(), extkey.key);
2063 }
2064 for (auto& path : paths) {
2065 ret.emplace_back(std::make_unique<BIP32PubkeyProvider>(key_exp_index, extpubkey, std::move(path), type, apostrophe));
2066 }
2067 ++key_exp_index;
2068 return ret;
2069}
2070
2072// NOLINTNEXTLINE(misc-no-recursion)
2073std::vector<std::unique_ptr<PubkeyProvider>> ParsePubkey(uint32_t& key_exp_index, const std::span<const char>& sp, ParseScriptContext ctx, FlatSigningProvider& out, std::string& error)
2074{
2075 std::vector<std::unique_ptr<PubkeyProvider>> ret;
2076
2077 using namespace script;
2078
2079 // musig cannot be nested inside of an origin
2080 std::span<const char> span = sp;
2081 if (Const("musig(", span, /*skip=*/false)) {
2082 if (ctx != ParseScriptContext::P2TR) {
2083 error = "musig() is only allowed in tr() and rawtr()";
2084 return {};
2085 }
2086
2087 // Split the span on the end parentheses. The end parentheses must
2088 // be included in the resulting span so that Expr is happy.
2089 auto split = Split(sp, ')', /*include_sep=*/true);
2090 if (split.size() > 2) {
2091 error = "Too many ')' in musig() expression";
2092 return {};
2093 }
2094 std::span<const char> expr(split.at(0).begin(), split.at(0).end());
2095 if (!Func("musig", expr)) {
2096 error = "Invalid musig() expression";
2097 return {};
2098 }
2099
2100 // Parse the participant pubkeys
2101 bool any_ranged = false;
2102 bool all_bip32 = true;
2103 std::vector<std::vector<std::unique_ptr<PubkeyProvider>>> providers;
2104 bool any_key_parsed = false;
2105 size_t max_multipath_len = 0;
2106 while (expr.size()) {
2107 if (any_key_parsed && !Const(",", expr)) {
2108 error = strprintf("musig(): expected ',', got '%c'", expr[0]);
2109 return {};
2110 }
2111 auto arg = Expr(expr);
2112 auto pk = ParsePubkey(key_exp_index, arg, ParseScriptContext::MUSIG, out, error);
2113 if (pk.empty()) {
2114 error = strprintf("musig(): %s", error);
2115 return {};
2116 }
2117 any_key_parsed = true;
2118
2119 any_ranged = any_ranged || pk.at(0)->IsRange();
2120 all_bip32 = all_bip32 && pk.at(0)->IsBIP32();
2121
2122 max_multipath_len = std::max(max_multipath_len, pk.size());
2123
2124 providers.emplace_back(std::move(pk));
2125 }
2126 if (!any_key_parsed) {
2127 error = "musig(): Must contain key expressions";
2128 return {};
2129 }
2130
2131 // Parse any derivation
2132 DeriveType deriv_type = DeriveType::NON_RANGED;
2133 std::vector<KeyPath> derivation_multipaths;
2134 if (split.size() == 2 && Const("/", split.at(1), /*skip=*/false)) {
2135 if (!all_bip32) {
2136 error = "musig(): derivation requires all participants to be xpubs or xprvs";
2137 return {};
2138 }
2139 if (any_ranged) {
2140 error = "musig(): Cannot have ranged participant keys if musig() also has derivation";
2141 return {};
2142 }
2143 bool dummy = false;
2144 auto deriv_split = Split(split.at(1), '/');
2146 if (deriv_type == DeriveType::HARDENED_RANGED) {
2147 error = "musig(): Cannot have hardened child derivation";
2148 return {};
2149 }
2150 bool has_hardened = false;
2151 if (!ParseKeyPath(deriv_split, derivation_multipaths, dummy, error, /*allow_multipath=*/true, has_hardened)) {
2152 error = "musig(): " + error;
2153 return {};
2154 }
2155 if (has_hardened) {
2156 error = "musig(): cannot have hardened derivation steps";
2157 return {};
2158 }
2159 } else {
2160 derivation_multipaths.emplace_back();
2161 }
2162
2163 // Makes sure that all providers vectors in providers are the given length, or exactly length 1
2164 // Length 1 vectors have the single provider cloned until it matches the given length.
2165 const auto& clone_providers = [&providers](size_t length) -> bool {
2166 for (auto& multipath_providers : providers) {
2167 if (multipath_providers.size() == 1) {
2168 for (size_t i = 1; i < length; ++i) {
2169 multipath_providers.emplace_back(multipath_providers.at(0)->Clone());
2170 }
2171 } else if (multipath_providers.size() != length) {
2172 return false;
2173 }
2174 }
2175 return true;
2176 };
2177
2178 // Emplace the final MuSigPubkeyProvider into ret with the pubkey providers from the specified provider vectors index
2179 // and the path from the specified path index
2180 const auto& emplace_final_provider = [&ret, &key_exp_index, &deriv_type, &derivation_multipaths, &providers](size_t vec_idx, size_t path_idx) -> void {
2182 std::vector<std::unique_ptr<PubkeyProvider>> pubs;
2183 pubs.reserve(providers.size());
2184 for (auto& vec : providers) {
2185 pubs.emplace_back(std::move(vec.at(vec_idx)));
2186 }
2187 ret.emplace_back(std::make_unique<MuSigPubkeyProvider>(key_exp_index, std::move(pubs), path, deriv_type));
2188 };
2189
2190 if (max_multipath_len > 1 && derivation_multipaths.size() > 1) {
2191 error = "musig(): Cannot have multipath participant keys if musig() is also multipath";
2192 return {};
2193 } else if (max_multipath_len > 1) {
2195 error = strprintf("musig(): Multipath derivation paths have mismatched lengths");
2196 return {};
2197 }
2198 for (size_t i = 0; i < max_multipath_len; ++i) {
2199 // Final MuSigPubkeyProvider uses participant pubkey providers at each multipath position, and the first (and only) path
2201 }
2202 } else if (derivation_multipaths.size() > 1) {
2203 // All key provider vectors should be length 1. Clone them until they have the same length as paths
2205 error = "musig(): Multipath derivation path with multipath participants is disallowed"; // This error is unreachable due to earlier check
2206 return {};
2207 }
2208 for (size_t i = 0; i < derivation_multipaths.size(); ++i) {
2209 // Final MuSigPubkeyProvider uses cloned participant pubkey providers, and the multipath derivation paths
2211 }
2212 } else {
2213 // No multipath derivation, MuSigPubkeyProvider uses the first (and only) participant pubkey providers, and the first (and only) path
2215 }
2216 ++key_exp_index; // Increment key expression index for the MuSigPubkeyProvider too
2217 return ret;
2218 }
2219
2220 auto origin_split = Split(sp, ']');
2221 if (origin_split.size() > 2) {
2222 error = "Multiple ']' characters found for a single pubkey";
2223 return {};
2224 }
2225 // This is set if either the origin or path suffix contains a hardened derivation.
2226 bool apostrophe = false;
2227 if (origin_split.size() == 1) {
2228 return ParsePubkeyInner(key_exp_index, origin_split[0], ctx, out, apostrophe, error);
2229 }
2230 if (origin_split[0].empty() || origin_split[0][0] != '[') {
2231 error = strprintf("Key origin start '[ character expected but not found, got '%c' instead",
2232 origin_split[0].empty() ? ']' : origin_split[0][0]);
2233 return {};
2234 }
2235 auto slash_split = Split(origin_split[0].subspan(1), '/');
2236 if (slash_split[0].size() != 8) {
2237 error = strprintf("Fingerprint is not 4 bytes (%u characters instead of 8 characters)", slash_split[0].size());
2238 return {};
2239 }
2240 std::string fpr_hex = std::string(slash_split[0].begin(), slash_split[0].end());
2241 if (!IsHex(fpr_hex)) {
2242 error = strprintf("Fingerprint '%s' is not hex", fpr_hex);
2243 return {};
2244 }
2245 auto fpr_bytes = ParseHex(fpr_hex);
2246 KeyOriginInfo info;
2247 static_assert(sizeof(info.fingerprint) == 4, "Fingerprint must be 4 bytes");
2248 assert(fpr_bytes.size() == 4);
2249 std::copy_n(fpr_bytes.begin(), info.fingerprint.size(), info.fingerprint.begin());
2250 std::vector<KeyPath> path;
2251 if (!ParseKeyPath(slash_split, path, apostrophe, error, /*allow_multipath=*/false)) return {};
2252 info.path = path.at(0);
2253 auto providers = ParsePubkeyInner(key_exp_index, origin_split[1], ctx, out, apostrophe, error);
2254 if (providers.empty()) return {};
2255 ret.reserve(providers.size());
2256 for (auto& prov : providers) {
2257 ret.emplace_back(std::make_unique<OriginPubkeyProvider>(prov->m_expr_index, info, std::move(prov), apostrophe));
2258 }
2259 return ret;
2260}
2261
2262std::unique_ptr<PubkeyProvider> InferPubkey(const CPubKey& pubkey, ParseScriptContext ctx, const SigningProvider& provider)
2263{
2264 // Key cannot be hybrid
2265 if (!pubkey.IsValidNonHybrid()) {
2266 return nullptr;
2267 }
2268 // Uncompressed is only allowed in TOP and P2SH contexts
2269 if (ctx != ParseScriptContext::TOP && ctx != ParseScriptContext::P2SH && !pubkey.IsCompressed()) {
2270 return nullptr;
2271 }
2272 std::unique_ptr<PubkeyProvider> key_provider = std::make_unique<ConstPubkeyProvider>(0, pubkey, false);
2273 KeyOriginInfo info;
2274 if (provider.GetKeyOrigin(pubkey.GetID(), info)) {
2275 return std::make_unique<OriginPubkeyProvider>(0, std::move(info), std::move(key_provider), /*apostrophe=*/false);
2276 }
2277 return key_provider;
2278}
2279
2280std::unique_ptr<PubkeyProvider> InferXOnlyPubkey(const XOnlyPubKey& xkey, ParseScriptContext ctx, const SigningProvider& provider)
2281{
2282 CPubKey pubkey{xkey.GetEvenCorrespondingCPubKey()};
2283 std::unique_ptr<PubkeyProvider> key_provider = std::make_unique<ConstPubkeyProvider>(0, pubkey, true);
2284 KeyOriginInfo info;
2285 if (provider.GetKeyOriginByXOnly(xkey, info)) {
2286 return std::make_unique<OriginPubkeyProvider>(0, std::move(info), std::move(key_provider), /*apostrophe=*/false);
2287 }
2288 return key_provider;
2289}
2290
2294struct KeyParser {
2296 using Key = uint32_t;
2298 FlatSigningProvider* m_out;
2300 const SigningProvider* m_in;
2302 mutable std::vector<std::vector<std::unique_ptr<PubkeyProvider>>> m_keys;
2304 mutable std::string m_key_parsing_error;
2306 const miniscript::MiniscriptContext m_script_ctx;
2308 uint32_t& m_expr_index;
2309
2312 : m_out(out), m_in(in), m_script_ctx(ctx), m_expr_index(key_exp_index) {}
2313
2314 bool KeyCompare(const Key& a, const Key& b) const {
2315 // Deriving a hardened step needs the private key, so use the provider that was filled
2316 // while parsing, or the one we are inferring from, rather than an empty one.
2317 const SigningProvider& provider{m_out ? *m_out : (m_in ? *m_in : DUMMY_SIGNING_PROVIDER)};
2318 const PubkeyProvider& key_a{*m_keys.at(a).at(0)};
2319 const PubkeyProvider& key_b{*m_keys.at(b).at(0)};
2321 const std::optional<CPubKey> pub_a{key_a.GetPubKey(0, provider, out_a)};
2322 const std::optional<CPubKey> pub_b{key_b.GetPubKey(0, provider, out_b)};
2323 if (pub_a && pub_b) return *pub_a < *pub_b;
2324 // Keys that cannot be derived sort before the ones that can, and are compared by their
2325 // expression so that two different keys are not taken for duplicates.
2326 if (pub_a.has_value() != pub_b.has_value()) return !pub_a.has_value();
2327 return key_a.ToString(PubkeyProvider::StringType::PUBLIC) < key_b.ToString(PubkeyProvider::StringType::PUBLIC);
2328 }
2329
2330 ParseScriptContext ParseContext() const {
2331 switch (m_script_ctx) {
2332 case miniscript::MiniscriptContext::P2WSH: return ParseScriptContext::P2WSH;
2333 case miniscript::MiniscriptContext::TAPSCRIPT: return ParseScriptContext::P2TR;
2334 }
2335 assert(false);
2336 }
2337
2338 std::optional<Key> FromString(std::span<const char>& in) const
2339 {
2340 assert(m_out);
2341 Key key = m_keys.size();
2342 auto pk = ParsePubkey(m_expr_index, in, ParseContext(), *m_out, m_key_parsing_error);
2343 if (pk.empty()) return {};
2344 m_keys.emplace_back(std::move(pk));
2345 return key;
2346 }
2347
2348 std::optional<std::string> ToString(const Key& key, bool&) const
2349 {
2350 return m_keys.at(key).at(0)->ToString(PubkeyProvider::StringType::PUBLIC);
2351 }
2352
2353 template<typename I> std::optional<Key> FromPKBytes(I begin, I end) const
2354 {
2355 assert(m_in);
2356 Key key = m_keys.size();
2357 if (miniscript::IsTapscript(m_script_ctx) && end - begin == 32) {
2358 XOnlyPubKey pubkey;
2359 std::copy(begin, end, pubkey.begin());
2360 if (auto pubkey_provider = InferXOnlyPubkey(pubkey, ParseContext(), *m_in)) {
2361 m_keys.emplace_back();
2362 m_keys.back().push_back(std::move(pubkey_provider));
2363 return key;
2364 }
2365 } else if (!miniscript::IsTapscript(m_script_ctx)) {
2366 CPubKey pubkey(begin, end);
2367 if (auto pubkey_provider = InferPubkey(pubkey, ParseContext(), *m_in)) {
2368 m_keys.emplace_back();
2369 m_keys.back().push_back(std::move(pubkey_provider));
2370 return key;
2371 }
2372 }
2373 return {};
2374 }
2375
2376 template<typename I> std::optional<Key> FromPKHBytes(I begin, I end) const
2377 {
2378 assert(end - begin == 20);
2379 assert(m_in);
2380 uint160 hash;
2381 std::copy(begin, end, hash.begin());
2382 CKeyID keyid(hash);
2383 CPubKey pubkey;
2384 if (m_in->GetPubKey(keyid, pubkey)) {
2385 if (auto pubkey_provider = InferPubkey(pubkey, ParseContext(), *m_in)) {
2386 Key key = m_keys.size();
2387 m_keys.emplace_back();
2388 m_keys.back().push_back(std::move(pubkey_provider));
2389 return key;
2390 }
2391 }
2392 return {};
2393 }
2394
2395 miniscript::MiniscriptContext MsContext() const {
2396 return m_script_ctx;
2397 }
2398};
2399
2401// NOLINTNEXTLINE(misc-no-recursion)
2402std::vector<std::unique_ptr<DescriptorImpl>> ParseScript(uint32_t& key_exp_index, std::span<const char>& sp, ParseScriptContext ctx, FlatSigningProvider& out, std::string& error)
2403{
2404 using namespace script;
2405 Assume(ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH || ctx == ParseScriptContext::P2TR);
2406 std::vector<std::unique_ptr<DescriptorImpl>> ret;
2407 auto expr = Expr(sp);
2408 if (Func("pk", expr)) {
2409 auto pubkeys = ParsePubkey(key_exp_index, expr, ctx, out, error);
2410 if (pubkeys.empty()) {
2411 error = strprintf("pk(): %s", error);
2412 return {};
2413 }
2414 for (auto& pubkey : pubkeys) {
2415 ret.emplace_back(std::make_unique<PKDescriptor>(std::move(pubkey), ctx == ParseScriptContext::P2TR));
2416 }
2417 return ret;
2418 }
2419 if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH) && Func("pkh", expr)) {
2420 auto pubkeys = ParsePubkey(key_exp_index, expr, ctx, out, error);
2421 if (pubkeys.empty()) {
2422 error = strprintf("pkh(): %s", error);
2423 return {};
2424 }
2425 for (auto& pubkey : pubkeys) {
2426 ret.emplace_back(std::make_unique<PKHDescriptor>(std::move(pubkey)));
2427 }
2428 return ret;
2429 }
2430 if (ctx == ParseScriptContext::TOP && Func("combo", expr)) {
2431 auto pubkeys = ParsePubkey(key_exp_index, expr, ctx, out, error);
2432 if (pubkeys.empty()) {
2433 error = strprintf("combo(): %s", error);
2434 return {};
2435 }
2436 for (auto& pubkey : pubkeys) {
2437 ret.emplace_back(std::make_unique<ComboDescriptor>(std::move(pubkey)));
2438 }
2439 return ret;
2440 } else if (Func("combo", expr)) {
2441 error = "Can only have combo() at top level";
2442 return {};
2443 }
2444 const bool multi = Func("multi", expr);
2445 const bool sortedmulti = !multi && Func("sortedmulti", expr);
2446 const bool multi_a = !(multi || sortedmulti) && Func("multi_a", expr);
2447 const bool sortedmulti_a = !(multi || sortedmulti || multi_a) && Func("sortedmulti_a", expr);
2448 if (((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH) && (multi || sortedmulti)) ||
2449 (ctx == ParseScriptContext::P2TR && (multi_a || sortedmulti_a))) {
2450 auto threshold = Expr(expr);
2452 std::vector<std::vector<std::unique_ptr<PubkeyProvider>>> providers; // List of multipath expanded pubkeys
2453 if (const auto maybe_thres{ToIntegral<uint32_t>(std::string_view{threshold.begin(), threshold.end()})}) {
2454 thres = *maybe_thres;
2455 } else {
2456 error = strprintf("Multi threshold '%s' is not valid", std::string(threshold.begin(), threshold.end()));
2457 return {};
2458 }
2459 size_t script_size = 0;
2460 size_t max_providers_len = 0;
2461 while (expr.size()) {
2462 if (!Const(",", expr)) {
2463 error = strprintf("Multi: expected ',', got '%c'", expr[0]);
2464 return {};
2465 }
2466 auto arg = Expr(expr);
2467 auto pks = ParsePubkey(key_exp_index, arg, ctx, out, error);
2468 if (pks.empty()) {
2469 error = strprintf("Multi: %s", error);
2470 return {};
2471 }
2472 script_size += pks.at(0)->GetSize() + 1;
2473 max_providers_len = std::max(max_providers_len, pks.size());
2474 providers.emplace_back(std::move(pks));
2475 }
2476 if ((multi || sortedmulti) && (providers.empty() || providers.size() > MAX_PUBKEYS_PER_MULTISIG)) {
2477 error = strprintf("Cannot have %u keys in multisig; must have between 1 and %d keys, inclusive", providers.size(), MAX_PUBKEYS_PER_MULTISIG);
2478 return {};
2479 } else if ((multi_a || sortedmulti_a) && (providers.empty() || providers.size() > MAX_PUBKEYS_PER_MULTI_A)) {
2480 error = strprintf("Cannot have %u keys in multi_a; must have between 1 and %d keys, inclusive", providers.size(), MAX_PUBKEYS_PER_MULTI_A);
2481 return {};
2482 } else if (thres < 1) {
2483 error = strprintf("Multisig threshold cannot be %d, must be at least 1", thres);
2484 return {};
2485 } else if (thres > providers.size()) {
2486 error = strprintf("Multisig threshold cannot be larger than the number of keys; threshold is %d but only %u keys specified", thres, providers.size());
2487 return {};
2488 }
2489 if (ctx == ParseScriptContext::TOP) {
2490 if (providers.size() > 3) {
2491 error = strprintf("Cannot have %u pubkeys in bare multisig; only at most 3 pubkeys", providers.size());
2492 return {};
2493 }
2494 }
2495 if (ctx == ParseScriptContext::P2SH) {
2496 // This limits the maximum number of compressed pubkeys to 15.
2498 error = strprintf("P2SH script is too large, %d bytes is larger than %d bytes", script_size + 3, MAX_SCRIPT_ELEMENT_SIZE);
2499 return {};
2500 }
2501 }
2502
2503 // Make sure all vecs are of the same length, or exactly length 1
2504 // For length 1 vectors, clone key providers until vector is the same length
2505 for (auto& vec : providers) {
2506 if (vec.size() == 1) {
2507 for (size_t i = 1; i < max_providers_len; ++i) {
2508 vec.emplace_back(vec.at(0)->Clone());
2509 }
2510 } else if (vec.size() != max_providers_len) {
2511 error = strprintf("multi(): Multipath derivation paths have mismatched lengths");
2512 return {};
2513 }
2514 }
2515
2516 // Build the final descriptors vector
2517 for (size_t i = 0; i < max_providers_len; ++i) {
2518 // Build final pubkeys vectors by retrieving the i'th subscript for each vector in subscripts
2519 std::vector<std::unique_ptr<PubkeyProvider>> pubs;
2520 pubs.reserve(providers.size());
2521 for (auto& pub : providers) {
2522 pubs.emplace_back(std::move(pub.at(i)));
2523 }
2524 if (multi || sortedmulti) {
2525 ret.emplace_back(std::make_unique<MultisigDescriptor>(thres, std::move(pubs), sortedmulti));
2526 } else {
2527 ret.emplace_back(std::make_unique<MultiADescriptor>(thres, std::move(pubs), sortedmulti_a));
2528 }
2529 }
2530 return ret;
2531 } else if (multi || sortedmulti) {
2532 error = "Can only have multi/sortedmulti at top level, in sh(), or in wsh()";
2533 return {};
2534 } else if (multi_a || sortedmulti_a) {
2535 error = "Can only have multi_a/sortedmulti_a inside tr()";
2536 return {};
2537 }
2538 if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH) && Func("wpkh", expr)) {
2539 auto pubkeys = ParsePubkey(key_exp_index, expr, ParseScriptContext::P2WPKH, out, error);
2540 if (pubkeys.empty()) {
2541 error = strprintf("wpkh(): %s", error);
2542 return {};
2543 }
2544 for (auto& pubkey : pubkeys) {
2545 ret.emplace_back(std::make_unique<WPKHDescriptor>(std::move(pubkey)));
2546 }
2547 return ret;
2548 } else if (Func("wpkh", expr)) {
2549 error = "Can only have wpkh() at top level or inside sh()";
2550 return {};
2551 }
2552 if (ctx == ParseScriptContext::TOP && Func("sh", expr)) {
2553 auto descs = ParseScript(key_exp_index, expr, ParseScriptContext::P2SH, out, error);
2554 if (descs.empty() || expr.size()) return {};
2555 std::vector<std::unique_ptr<DescriptorImpl>> ret;
2556 ret.reserve(descs.size());
2557 for (auto& desc : descs) {
2558 ret.push_back(std::make_unique<SHDescriptor>(std::move(desc)));
2559 }
2560 return ret;
2561 } else if (Func("sh", expr)) {
2562 error = "Can only have sh() at top level";
2563 return {};
2564 }
2565 if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH) && Func("wsh", expr)) {
2566 auto descs = ParseScript(key_exp_index, expr, ParseScriptContext::P2WSH, out, error);
2567 if (descs.empty() || expr.size()) return {};
2568 for (auto& desc : descs) {
2569 ret.emplace_back(std::make_unique<WSHDescriptor>(std::move(desc)));
2570 }
2571 return ret;
2572 } else if (Func("wsh", expr)) {
2573 error = "Can only have wsh() at top level or inside sh()";
2574 return {};
2575 }
2576 if (ctx == ParseScriptContext::TOP && Func("addr", expr)) {
2577 CTxDestination dest = DecodeDestination(std::string(expr.begin(), expr.end()));
2578 if (!IsValidDestination(dest)) {
2579 error = "Address is not valid";
2580 return {};
2581 }
2582 ret.emplace_back(std::make_unique<AddressDescriptor>(std::move(dest)));
2583 return ret;
2584 } else if (Func("addr", expr)) {
2585 error = "Can only have addr() at top level";
2586 return {};
2587 }
2588 if (ctx == ParseScriptContext::TOP && Func("tr", expr)) {
2589 auto arg = Expr(expr);
2590 auto internal_keys = ParsePubkey(key_exp_index, arg, ParseScriptContext::P2TR, out, error);
2591 if (internal_keys.empty()) {
2592 error = strprintf("tr(): %s", error);
2593 return {};
2594 }
2595 size_t max_providers_len = internal_keys.size();
2596 std::vector<std::vector<std::unique_ptr<DescriptorImpl>>> subscripts;
2597 std::vector<int> depths;
2598 if (expr.size()) {
2599 if (!Const(",", expr)) {
2600 error = strprintf("tr: expected ',', got '%c'", expr[0]);
2601 return {};
2602 }
2606 std::vector<bool> branches;
2607 // Loop over all provided scripts. In every iteration exactly one script will be processed.
2608 // Use a do-loop because inside this if-branch we expect at least one script.
2609 do {
2610 // First process all open braces.
2611 while (Const("{", expr)) {
2612 branches.push_back(false); // new left branch
2614 error = strprintf("tr() supports at most %i nesting levels", TAPROOT_CONTROL_MAX_NODE_COUNT);
2615 return {};
2616 }
2617 }
2618 // Process the actual script expression.
2619 auto sarg = Expr(expr);
2620 subscripts.emplace_back(ParseScript(key_exp_index, sarg, ParseScriptContext::P2TR, out, error));
2621 if (subscripts.back().empty()) return {};
2622 max_providers_len = std::max(max_providers_len, subscripts.back().size());
2623 depths.push_back(branches.size());
2624 // Process closing braces; one is expected for every right branch we were in.
2625 while (branches.size() && branches.back()) {
2626 if (!Const("}", expr)) {
2627 error = strprintf("tr(): expected '}' after script expression");
2628 return {};
2629 }
2630 branches.pop_back(); // move up one level after encountering '}'
2631 }
2632 // If after that, we're at the end of a left branch, expect a comma.
2633 if (branches.size() && !branches.back()) {
2634 if (!Const(",", expr)) {
2635 error = strprintf("tr(): expected ',' after script expression");
2636 return {};
2637 }
2638 branches.back() = true; // And now we're in a right branch.
2639 }
2640 } while (branches.size());
2641 // After we've explored a whole tree, we must be at the end of the expression.
2642 if (expr.size()) {
2643 error = strprintf("tr(): expected ')' after script expression");
2644 return {};
2645 }
2646 }
2648
2649 // Make sure all vecs are of the same length, or exactly length 1
2650 // For length 1 vectors, clone subdescs until vector is the same length
2651 for (auto& vec : subscripts) {
2652 if (vec.size() == 1) {
2653 for (size_t i = 1; i < max_providers_len; ++i) {
2654 vec.emplace_back(vec.at(0)->Clone());
2655 }
2656 } else if (vec.size() != max_providers_len) {
2657 error = strprintf("tr(): Multipath subscripts have mismatched lengths");
2658 return {};
2659 }
2660 }
2661
2662 if (internal_keys.size() > 1 && internal_keys.size() != max_providers_len) {
2663 error = strprintf("tr(): Multipath internal key mismatches multipath subscripts lengths");
2664 return {};
2665 }
2666
2667 while (internal_keys.size() < max_providers_len) {
2668 internal_keys.emplace_back(internal_keys.at(0)->Clone());
2669 }
2670
2671 // Build the final descriptors vector
2672 for (size_t i = 0; i < max_providers_len; ++i) {
2673 // Build final subscripts vectors by retrieving the i'th subscript for each vector in subscripts
2674 std::vector<std::unique_ptr<DescriptorImpl>> this_subs;
2675 this_subs.reserve(subscripts.size());
2676 for (auto& subs : subscripts) {
2677 this_subs.emplace_back(std::move(subs.at(i)));
2678 }
2679 ret.emplace_back(std::make_unique<TRDescriptor>(std::move(internal_keys.at(i)), std::move(this_subs), depths));
2680 }
2681 return ret;
2682
2683
2684 } else if (Func("tr", expr)) {
2685 error = "Can only have tr at top level";
2686 return {};
2687 }
2688 if (ctx == ParseScriptContext::TOP && Func("rawtr", expr)) {
2689 auto arg = Expr(expr);
2690 if (expr.size()) {
2691 error = strprintf("rawtr(): only one key expected.");
2692 return {};
2693 }
2694 auto output_keys = ParsePubkey(key_exp_index, arg, ParseScriptContext::P2TR, out, error);
2695 if (output_keys.empty()) {
2696 error = strprintf("rawtr(): %s", error);
2697 return {};
2698 }
2699 for (auto& pubkey : output_keys) {
2700 ret.emplace_back(std::make_unique<RawTRDescriptor>(std::move(pubkey)));
2701 }
2702 return ret;
2703 } else if (Func("rawtr", expr)) {
2704 error = "Can only have rawtr at top level";
2705 return {};
2706 }
2707 if (ctx == ParseScriptContext::TOP && Func("unused", expr)) {
2708 // Check for only one expression, should not find commas, brackets, or parentheses
2709 auto arg = Expr(expr);
2710 if (expr.size()) {
2711 error = strprintf("unused(): only one key expected");
2712 return {};
2713 }
2714 auto keys = ParsePubkey(key_exp_index, arg, ctx, out, error);
2715 if (keys.empty()) return {};
2716 for (auto& pubkey : keys) {
2717 if (pubkey->IsRange()) {
2718 error = "unused(): key cannot be ranged";
2719 return {};
2720 }
2721 ret.emplace_back(std::make_unique<UnusedDescriptor>(std::move(pubkey)));
2722 }
2723 return ret;
2724 } else if (Func("unused", expr)) {
2725 error = "Can only have unused at top level";
2726 return {};
2727 }
2728 if (ctx == ParseScriptContext::TOP && Func("raw", expr)) {
2729 std::string str(expr.begin(), expr.end());
2730 if (!IsHex(str)) {
2731 error = "Raw script is not hex";
2732 return {};
2733 }
2734 auto bytes = ParseHex(str);
2735 ret.emplace_back(std::make_unique<RawDescriptor>(CScript(bytes.begin(), bytes.end())));
2736 return ret;
2737 } else if (Func("raw", expr)) {
2738 error = "Can only have raw() at top level";
2739 return {};
2740 }
2741 // Process miniscript expressions.
2742 {
2743 const auto script_ctx{ctx == ParseScriptContext::P2WSH ? miniscript::MiniscriptContext::P2WSH : miniscript::MiniscriptContext::TAPSCRIPT};
2744 KeyParser parser(/*out = */&out, /* in = */nullptr, /* ctx = */script_ctx, key_exp_index);
2745 auto node = miniscript::FromString(std::string(expr.begin(), expr.end()), parser);
2746 if (parser.m_key_parsing_error != "") {
2747 error = std::move(parser.m_key_parsing_error);
2748 return {};
2749 }
2750 if (node) {
2751 if (ctx != ParseScriptContext::P2WSH && ctx != ParseScriptContext::P2TR) {
2752 error = "Miniscript expressions can only be used in wsh or tr.";
2753 return {};
2754 }
2755 if (!node->IsSane() || node->IsNotSatisfiable()) {
2756 // Try to find the first insane sub for better error reporting.
2757 const auto* insane_node = &node.value();
2758 if (const auto sub = node->FindInsaneSub()) insane_node = sub;
2759 error = *insane_node->ToString(parser);
2760 if (!insane_node->IsValid()) {
2761 error += " is invalid";
2762 } else if (!node->IsSane()) {
2763 error += " is not sane";
2764 if (!insane_node->IsNonMalleable()) {
2765 error += ": malleable witnesses exist";
2766 } else if (insane_node == &node.value() && !insane_node->NeedsSignature()) {
2767 error += ": witnesses without signature exist";
2768 } else if (!insane_node->CheckTimeLocksMix()) {
2769 error += ": contains mixes of timelocks expressed in blocks and seconds";
2770 } else if (!insane_node->CheckDuplicateKey()) {
2771 error += ": contains duplicate public keys";
2772 } else if (!insane_node->ValidSatisfactions()) {
2773 error += ": needs witnesses that may exceed resource limits";
2774 }
2775 } else {
2776 error += " is not satisfiable";
2777 }
2778 return {};
2779 }
2780 // A signature check is required for a miniscript to be sane. Therefore no sane miniscript
2781 // may have an empty list of public keys.
2782 CHECK_NONFATAL(!parser.m_keys.empty());
2783 // Make sure all vecs are of the same length, or exactly length 1
2784 // For length 1 vectors, clone subdescs until vector is the same length
2785 size_t num_multipath = std::max_element(parser.m_keys.begin(), parser.m_keys.end(),
2786 [](const std::vector<std::unique_ptr<PubkeyProvider>>& a, const std::vector<std::unique_ptr<PubkeyProvider>>& b) {
2787 return a.size() < b.size();
2788 })->size();
2789
2790 for (auto& vec : parser.m_keys) {
2791 if (vec.size() == 1) {
2792 for (size_t i = 1; i < num_multipath; ++i) {
2793 vec.emplace_back(vec.at(0)->Clone());
2794 }
2795 } else if (vec.size() != num_multipath) {
2796 error = strprintf("Miniscript: Multipath derivation paths have mismatched lengths");
2797 return {};
2798 }
2799 }
2800
2801 // Build the final descriptors vector
2802 for (size_t i = 0; i < num_multipath; ++i) {
2803 // Build final pubkeys vectors by retrieving the i'th subscript for each vector in subscripts
2804 std::vector<std::unique_ptr<PubkeyProvider>> pubs;
2805 pubs.reserve(parser.m_keys.size());
2806 for (auto& pub : parser.m_keys) {
2807 pubs.emplace_back(std::move(pub.at(i)));
2808 }
2809 ret.emplace_back(std::make_unique<MiniscriptDescriptor>(std::move(pubs), node->Clone()));
2810 }
2811 return ret;
2812 }
2813 }
2814 if (ctx == ParseScriptContext::P2SH) {
2815 error = "A function is needed within P2SH";
2816 return {};
2817 } else if (ctx == ParseScriptContext::P2WSH) {
2818 error = "A function is needed within P2WSH";
2819 return {};
2820 }
2821 error = strprintf("'%s' is not a valid descriptor function", std::string(expr.begin(), expr.end()));
2822 return {};
2823}
2824
2825std::unique_ptr<DescriptorImpl> InferMultiA(const CScript& script, ParseScriptContext ctx, const SigningProvider& provider)
2826{
2827 auto match = MatchMultiA(script);
2828 if (!match) return {};
2829 std::vector<std::unique_ptr<PubkeyProvider>> keys;
2830 keys.reserve(match->second.size());
2831 for (const auto keyspan : match->second) {
2832 if (keyspan.size() != 32) return {};
2833 auto key = InferXOnlyPubkey(XOnlyPubKey{keyspan}, ctx, provider);
2834 if (!key) return {};
2835 keys.push_back(std::move(key));
2836 }
2837 return std::make_unique<MultiADescriptor>(match->first, std::move(keys));
2838}
2839
2840// NOLINTNEXTLINE(misc-no-recursion)
2841std::unique_ptr<DescriptorImpl> InferScript(const CScript& script, ParseScriptContext ctx, const SigningProvider& provider)
2842{
2843 if (ctx == ParseScriptContext::P2TR && script.size() == 34 && script[0] == 32 && script[33] == OP_CHECKSIG) {
2844 XOnlyPubKey key{std::span{script}.subspan(1, 32)};
2845 return std::make_unique<PKDescriptor>(InferXOnlyPubkey(key, ctx, provider), true);
2846 }
2847
2848 if (ctx == ParseScriptContext::P2TR) {
2849 auto ret = InferMultiA(script, ctx, provider);
2850 if (ret) return ret;
2851 }
2852
2853 std::vector<std::vector<unsigned char>> data;
2855
2856 if (txntype == TxoutType::PUBKEY && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
2857 CPubKey pubkey(data[0]);
2858 if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
2859 return std::make_unique<PKDescriptor>(std::move(pubkey_provider));
2860 }
2861 }
2862 if (txntype == TxoutType::PUBKEYHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
2863 uint160 hash(data[0]);
2864 CKeyID keyid(hash);
2865 CPubKey pubkey;
2866 if (provider.GetPubKey(keyid, pubkey)) {
2867 if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
2868 return std::make_unique<PKHDescriptor>(std::move(pubkey_provider));
2869 }
2870 }
2871 }
2872 if (txntype == TxoutType::WITNESS_V0_KEYHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH)) {
2873 uint160 hash(data[0]);
2874 CKeyID keyid(hash);
2875 CPubKey pubkey;
2876 if (provider.GetPubKey(keyid, pubkey)) {
2877 if (auto pubkey_provider = InferPubkey(pubkey, ParseScriptContext::P2WPKH, provider)) {
2878 return std::make_unique<WPKHDescriptor>(std::move(pubkey_provider));
2879 }
2880 }
2881 }
2882 if (txntype == TxoutType::MULTISIG && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
2883 bool ok = true;
2884 std::vector<std::unique_ptr<PubkeyProvider>> providers;
2885 for (size_t i = 1; i + 1 < data.size(); ++i) {
2886 CPubKey pubkey(data[i]);
2887 if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
2888 providers.push_back(std::move(pubkey_provider));
2889 } else {
2890 ok = false;
2891 break;
2892 }
2893 }
2894 if (ok) return std::make_unique<MultisigDescriptor>((int)data[0][0], std::move(providers));
2895 }
2896 if (txntype == TxoutType::SCRIPTHASH && ctx == ParseScriptContext::TOP) {
2897 uint160 hash(data[0]);
2898 CScriptID scriptid(hash);
2900 if (provider.GetCScript(scriptid, subscript)) {
2901 auto sub = InferScript(subscript, ParseScriptContext::P2SH, provider);
2902 if (sub) return std::make_unique<SHDescriptor>(std::move(sub));
2903 }
2904 }
2905 if (txntype == TxoutType::WITNESS_V0_SCRIPTHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH)) {
2908 if (provider.GetCScript(scriptid, subscript)) {
2909 auto sub = InferScript(subscript, ParseScriptContext::P2WSH, provider);
2910 if (sub) return std::make_unique<WSHDescriptor>(std::move(sub));
2911 }
2912 }
2913 if (txntype == TxoutType::WITNESS_V1_TAPROOT && ctx == ParseScriptContext::TOP) {
2914 // Extract x-only pubkey from output.
2915 XOnlyPubKey pubkey;
2916 std::copy(data[0].begin(), data[0].end(), pubkey.begin());
2917 // Request spending data.
2919 if (provider.GetTaprootSpendData(pubkey, tap)) {
2920 // If found, convert it back to tree form.
2921 auto tree = InferTaprootTree(tap, pubkey);
2922 if (tree) {
2923 // If that works, try to infer subdescriptors for all leaves.
2924 bool ok = true;
2925 std::vector<std::unique_ptr<DescriptorImpl>> subscripts;
2926 std::vector<int> depths;
2927 for (const auto& [depth, script, leaf_ver] : *tree) {
2928 std::unique_ptr<DescriptorImpl> subdesc;
2930 subdesc = InferScript(CScript(script.begin(), script.end()), ParseScriptContext::P2TR, provider);
2931 }
2932 if (!subdesc) {
2933 ok = false;
2934 break;
2935 } else {
2936 subscripts.push_back(std::move(subdesc));
2937 depths.push_back(depth);
2938 }
2939 }
2940 if (ok) {
2941 auto key = InferXOnlyPubkey(tap.internal_key, ParseScriptContext::P2TR, provider);
2942 return std::make_unique<TRDescriptor>(std::move(key), std::move(subscripts), std::move(depths));
2943 }
2944 }
2945 }
2946 // If the above doesn't work, construct a rawtr() descriptor with just the encoded x-only pubkey.
2947 if (pubkey.IsFullyValid()) {
2948 auto key = InferXOnlyPubkey(pubkey, ParseScriptContext::P2TR, provider);
2949 if (key) {
2950 return std::make_unique<RawTRDescriptor>(std::move(key));
2951 }
2952 }
2953 }
2954
2955 if (ctx == ParseScriptContext::P2WSH || ctx == ParseScriptContext::P2TR) {
2956 const auto script_ctx{ctx == ParseScriptContext::P2WSH ? miniscript::MiniscriptContext::P2WSH : miniscript::MiniscriptContext::TAPSCRIPT};
2958 KeyParser parser(/* out = */nullptr, /* in = */&provider, /* ctx = */script_ctx, key_exp_index);
2960 if (node && node->IsSane()) {
2961 std::vector<std::unique_ptr<PubkeyProvider>> keys;
2962 keys.reserve(parser.m_keys.size());
2963 for (auto& key : parser.m_keys) {
2964 keys.emplace_back(std::move(key.at(0)));
2965 }
2966 return std::make_unique<MiniscriptDescriptor>(std::move(keys), std::move(*node));
2967 }
2968 }
2969
2970 // The following descriptors are all top-level only descriptors.
2971 // So if we are not at the top level, return early.
2972 if (ctx != ParseScriptContext::TOP) return nullptr;
2973
2974 CTxDestination dest;
2975 if (ExtractDestination(script, dest)) {
2976 if (GetScriptForDestination(dest) == script) {
2977 return std::make_unique<AddressDescriptor>(std::move(dest));
2978 }
2979 }
2980
2981 return std::make_unique<RawDescriptor>(script);
2982}
2983
2984
2985} // namespace
2986
2988bool CheckChecksum(std::span<const char>& sp, bool require_checksum, std::string& error, std::string* out_checksum = nullptr)
2989{
2990 auto check_split = Split(sp, '#');
2991 if (check_split.size() > 2) {
2992 error = "Multiple '#' symbols";
2993 return false;
2994 }
2995 if (check_split.size() == 1 && require_checksum){
2996 error = "Missing checksum";
2997 return false;
2998 }
2999 if (check_split.size() == 2) {
3000 if (check_split[1].size() != 8) {
3001 error = strprintf("Expected 8 character checksum, not %u characters", check_split[1].size());
3002 return false;
3003 }
3004 }
3006 if (checksum.empty()) {
3007 error = "Invalid characters in payload";
3008 return false;
3009 }
3010 if (check_split.size() == 2) {
3011 if (!std::equal(checksum.begin(), checksum.end(), check_split[1].begin())) {
3012 error = strprintf("Provided checksum '%s' does not match computed checksum '%s'", std::string(check_split[1].begin(), check_split[1].end()), checksum);
3013 return false;
3014 }
3015 }
3016 if (out_checksum) *out_checksum = std::move(checksum);
3017 sp = check_split[0];
3018 return true;
3019}
3020
3021std::vector<std::unique_ptr<Descriptor>> Parse(std::string_view descriptor, FlatSigningProvider& out, std::string& error, bool require_checksum)
3022{
3023 std::span<const char> sp{descriptor};
3024 if (!CheckChecksum(sp, require_checksum, error)) return {};
3026 auto ret = ParseScript(key_exp_index, sp, ParseScriptContext::TOP, out, error);
3027 if (sp.empty() && !ret.empty()) {
3028 std::vector<std::unique_ptr<Descriptor>> descs;
3029 descs.reserve(ret.size());
3030 for (auto& r : ret) {
3031 descs.emplace_back(std::unique_ptr<Descriptor>(std::move(r)));
3032 }
3033 return descs;
3034 }
3035 return {};
3036}
3037
3038std::string GetDescriptorChecksum(const std::string& descriptor)
3039{
3040 std::string ret;
3041 std::string error;
3042 std::span<const char> sp{descriptor};
3043 if (!CheckChecksum(sp, false, error, &ret)) return "";
3044 return ret;
3045}
3046
3047std::unique_ptr<Descriptor> InferDescriptor(const CScript& script, const SigningProvider& provider)
3048{
3049 return InferScript(script, ParseScriptContext::TOP, provider);
3050}
3051
3053{
3054 std::string desc_str = desc.ToString(/*compat_format=*/true);
3055 uint256 id;
3056 CSHA256().Write((unsigned char*)desc_str.data(), desc_str.size()).Finalize(id.begin());
3057 return id;
3058}
3059
3064
3070
3075
3077{
3078 const auto& it = m_parent_xpubs.find(key_exp_pos);
3079 if (it == m_parent_xpubs.end()) return false;
3080 xpub = it->second;
3081 return true;
3082}
3083
3085{
3086 const auto& key_exp_it = m_derived_xpubs.find(key_exp_pos);
3087 if (key_exp_it == m_derived_xpubs.end()) return false;
3088 const auto& der_it = key_exp_it->second.find(der_index);
3089 if (der_it == key_exp_it->second.end()) return false;
3090 xpub = der_it->second;
3091 return true;
3092}
3093
3095{
3096 const auto& it = m_last_hardened_xpubs.find(key_exp_pos);
3097 if (it == m_last_hardened_xpubs.end()) return false;
3098 xpub = it->second;
3099 return true;
3100}
3101
3103{
3105 for (const auto& parent_xpub_pair : other.GetCachedParentExtPubKeys()) {
3108 if (xpub != parent_xpub_pair.second) {
3109 throw std::runtime_error(std::string(__func__) + ": New cached parent xpub does not match already cached parent xpub");
3110 }
3111 continue;
3112 }
3114 diff.CacheParentExtPubKey(parent_xpub_pair.first, parent_xpub_pair.second);
3115 }
3116 for (const auto& derived_xpub_map_pair : other.GetCachedDerivedExtPubKeys()) {
3117 for (const auto& derived_xpub_pair : derived_xpub_map_pair.second) {
3120 if (xpub != derived_xpub_pair.second) {
3121 throw std::runtime_error(std::string(__func__) + ": New cached derived xpub does not match already cached derived xpub");
3122 }
3123 continue;
3124 }
3126 diff.CacheDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, derived_xpub_pair.second);
3127 }
3128 }
3129 for (const auto& lh_xpub_pair : other.GetCachedLastHardenedExtPubKeys()) {
3132 if (xpub != lh_xpub_pair.second) {
3133 throw std::runtime_error(std::string(__func__) + ": New cached last hardened xpub does not match already cached last hardened xpub");
3134 }
3135 continue;
3136 }
3138 diff.CacheLastHardenedExtPubKey(lh_xpub_pair.first, lh_xpub_pair.second);
3139 }
3140 return diff;
3141}
3142
3147
3148std::unordered_map<uint32_t, ExtPubKeyMap> DescriptorCache::GetCachedDerivedExtPubKeys() const
3149{
3150 return m_derived_xpubs;
3151}
3152
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a scriptPubKey for the destination.
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination corresponds to one with an address.
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
std::variant< CNoDestination, PubKeyDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, PayToAnchor, WitnessUnknown > CTxDestination
A txout script categorized into standard templates.
#define LIFETIMEBOUND
Definition attributes.h:12
std::string FormatHDKeypath(const std::vector< uint32_t > &path, bool apostrophe)
Definition bip32.cpp:62
util::Expected< KeyPathElement, std::string > ParseKeyPathElement(std::span< const char > elem)
Parse a single key path element like "0", "0'", or "0h".
Definition bip32.cpp:17
bool HasHardenedDerivation(std::span< const uint32_t > keypath)
Whether a parsed HD keypath contains at least one hardened derivation step.
Definition bip32.cpp:77
static constexpr uint32_t BIP32_HARDENED_FLAG
BIP32 hardened derivation flag (2^31)
Definition bip32.h:17
int ret
node::NodeContext m_node
#define CHECK_NONFATAL(condition)
Identity function.
Definition check.h:115
#define Assert(val)
Identity function.
Definition check.h:119
#define Assume(val)
Assume is the identity function.
Definition check.h:131
An encapsulated private key.
Definition key.h:46
unsigned int size() const
Simple read-only vector-like interface.
Definition key.h:128
bool IsValid() const
Check whether this private key is valid.
Definition key.h:134
bool IsCompressed() const
Check whether the public key corresponding to this private key is (to be) compressed.
Definition key.h:137
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition key.cpp:184
A reference to a CKey: the Hash160 of its serialized public key.
Definition pubkey.h:29
An encapsulated public key.
Definition pubkey.h:43
bool IsCompressed() const
Check whether this is a compressed public key.
Definition pubkey.h:209
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition pubkey.h:169
bool IsValidNonHybrid() const noexcept
Check if a public key is a syntactically valid compressed or uncompressed key.
Definition pubkey.h:200
A hasher class for SHA-256.
Definition sha256.h:14
void Finalize(unsigned char hash[OUTPUT_SIZE])
Definition sha256.cpp:725
CSHA256 & Write(const unsigned char *data, size_t len)
Definition sha256.cpp:699
Serialized script, used inside transaction inputs and outputs.
Definition script.h:406
A reference to a CScript: the Hash160 of its serialization.
Definition script.h:597
Cache for single descriptor's derived extended pubkeys.
Definition descriptor.h:30
bool GetCachedParentExtPubKey(uint32_t key_exp_pos, CExtPubKey &xpub) const
Retrieve a cached parent xpub.
std::unordered_map< uint32_t, ExtPubKeyMap > GetCachedDerivedExtPubKeys() const
Retrieve all cached derived xpubs.
ExtPubKeyMap m_last_hardened_xpubs
Map key expression index -> last hardened xpub.
Definition descriptor.h:37
void CacheDerivedExtPubKey(uint32_t key_exp_pos, uint32_t der_index, const CExtPubKey &xpub)
Cache an xpub derived at an index.
DescriptorCache MergeAndDiff(const DescriptorCache &other)
Combine another DescriptorCache into this one.
ExtPubKeyMap GetCachedParentExtPubKeys() const
Retrieve all cached parent xpubs.
ExtPubKeyMap GetCachedLastHardenedExtPubKeys() const
Retrieve all cached last hardened xpubs.
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:33
bool GetCachedLastHardenedExtPubKey(uint32_t key_exp_pos, CExtPubKey &xpub) const
Retrieve a cached last hardened xpub.
ExtPubKeyMap m_parent_xpubs
Map key expression index -> parent xpub.
Definition descriptor.h:35
An interface to be implemented by keystores that support signing.
bool GetKeyByXOnly(const XOnlyPubKey &pubkey, CKey &key) const
virtual bool GetPubKey(const CKeyID &address, CPubKey &pubkey) const
virtual bool GetKey(const CKeyID &address, CKey &key) const
Utility class to construct Taproot outputs from internal key and script tree.
static bool ValidDepths(const std::vector< int > &depths)
Check if a list of depths is legal (will lead to IsComplete()).
const unsigned char * begin() const
Definition pubkey.h:304
static constexpr size_t size()
Definition pubkey.h:302
bool IsFullyValid() const
Determine if this pubkey is fully valid.
Definition pubkey.cpp:230
constexpr unsigned char * begin()
Definition uint256.h:101
A node in a miniscript expression.
Definition miniscript.h:535
size_type size() const
Definition prevector.h:247
void reserve(size_type new_capacity)
Definition prevector.h:293
160-bit opaque blob.
Definition uint256.h:184
256-bit opaque blob.
Definition uint256.h:196
The util::Expected class provides a standard way for low-level functions to return either error value...
Definition expected.h:44
The util::Unexpected class represents an unexpected value stored in util::Expected.
Definition expected.h:21
static const PrecomputedData data
Precomputed COutPoint and CCoins values.
constexpr int WITNESS_SCALE_FACTOR
Definition consensus.h:21
CScript ParseScript(const std::string &s)
Definition core_io.cpp:92
uint160 Hash160(const T1 &in1)
Compute the 160-bit hash an object.
Definition hash.h:100
uint160 RIPEMD160(std::span< const unsigned char > data)
Compute the 160-bit RIPEMD-160 hash of an array.
Definition hash.h:230
std::string HexStr(const std::span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition hex_base.cpp:30
constexpr uint8_t TAPROOT_LEAF_TAPSCRIPT
constexpr size_t TAPROOT_CONTROL_MAX_NODE_COUNT
std::string EncodeExtKey(const CExtKey &key)
Definition key_io.cpp:302
CTxDestination DecodeDestination(const std::string &str, std::string &error_msg, std::vector< int > *error_locations)
Definition key_io.cpp:316
std::pair< CExtKey, CExtPubKey > DecodeExtKeyOrPubKey(std::string_view str)
Decode a base58-encoded extended key string as either an xprv or xpub, using a single base58 decode.
Definition key_io.cpp:283
std::string EncodeSecret(const CKey &key)
Definition key_io.cpp:233
std::string EncodeDestination(const CTxDestination &dest)
Definition key_io.cpp:311
std::string EncodeExtPubKey(const CExtPubKey &key)
Definition key_io.cpp:259
CKey DecodeSecret(std::string_view str)
Definition key_io.cpp:215
CExtPubKey CreateMuSig2SyntheticXpub(const CPubKey &pubkey)
Construct the BIP 328 synthetic xpub for a pubkey.
Definition musig.cpp:74
std::optional< CPubKey > MuSig2AggregatePubkeys(const std::vector< CPubKey > &pubkeys, secp256k1_musig_keyagg_cache &keyagg_cache, const std::optional< CPubKey > &expected_aggregate)
Compute the full aggregate pubkey from the given participant pubkeys in their current order.
Definition musig.cpp:57
constexpr bool IsTapscript(MiniscriptContext ms_ctx)
Whether the context Tapscript, ensuring the only other possibility is P2WSH.
Definition miniscript.h:259
std::optional< Node< typename Ctx::Key > > FromScript(const CScript &script, const Ctx &ctx)
void ForEachNode(const Node< Key > &root, Fn &&fn)
Unordered traversal of a miniscript node tree.
Definition miniscript.h:199
std::optional< Node< typename Ctx::Key > > FromString(const std::string &str, const Ctx &ctx)
@ OLDER
[n] OP_CHECKSEQUENCEVERIFY
std::span< const char > Expr(std::span< const char > &sp)
Extract the expression that sp begins with.
Definition parsing.cpp:31
bool Func(const std::string &str, std::span< const char > &sp)
Parse a function call.
Definition parsing.cpp:22
bool Const(const std::string &str, std::span< const char > &sp, bool skip)
Parse a constant.
Definition parsing.cpp:13
std::vector< T > Split(std::span< const char > sp LIFETIMEBOUND, std::string_view separators, bool include_sep=false)
Split a string on any char found in separators, returning a vector.
Definition string.h:120
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition string.h:250
std::optional< OutputType > OutputTypeFromDestination(const CTxDestination &dest)
Get the OutputType for a CTxDestination.
const char * name
Definition rest.cpp:71
std::unique_ptr< Descriptor > InferDescriptor(const CScript &script, const SigningProvider &provider)
Find a descriptor for the specified script, using information from provider where possible.
bool CheckChecksum(std::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::vector< std::unique_ptr< Descriptor > > Parse(std::string_view descriptor, FlatSigningProvider &out, std::string &error, bool require_checksum)
Parse a descriptor string.
std::string GetDescriptorChecksum(const std::string &descriptor)
Get the checksum for a descriptor.
uint256 CompatDescriptorHash(const Descriptor &desc)
Hash of the COMPAT string representation of the descriptor that is not supposed to change over time.
util::Expected< void, std::string > CheckDescriptorRangeBounds(int64_t low, int64_t high)
Validate the numeric bounds of a descriptor key-expression range [low, high] (high inclusive).
std::unordered_map< uint32_t, CExtPubKey > ExtPubKeyMap
Definition descriptor.h:27
@ OP_CHECKSIG
Definition script.h:191
@ OP_NUMEQUAL
Definition script.h:172
@ OP_CHECKSIGADD
Definition script.h:211
constexpr unsigned int MAX_PUBKEYS_PER_MULTI_A
The limit of keys in OP_CHECKSIGADD-based scripts.
Definition script.h:38
constexpr unsigned int MAX_SCRIPT_ELEMENT_SIZE
Definition script.h:29
constexpr int MAX_PUBKEYS_PER_MULTISIG
Definition script.h:35
CScript BuildScript(Ts &&... inputs)
Build a script by concatenating other scripts, or any argument accepted by CScript::operator<<.
Definition script.h:611
std::vector< unsigned char > ToByteVector(const T &in)
Definition script.h:68
static const int64_t values[]
A selection of numbers that do not trigger int64_t overflow when added/subtracted.
constexpr unsigned int GetSizeOfCompactSize(uint64_t nSize)
Compact Size size < 253 – 1 byte size <= USHRT_MAX – 3 bytes (253 + 2 bytes) size <= UINT_MAX – 5 byt...
Definition serialize.h:291
static bool GetPubKey(const SigningProvider &provider, const SignatureData &sigdata, const CKeyID &address, CPubKey &pubkey)
Definition sign.cpp:243
std::optional< std::vector< std::tuple< int, std::vector< unsigned char >, int > > > InferTaprootTree(const TaprootSpendData &spenddata, const XOnlyPubKey &output)
Given a TaprootSpendData and the output key, reconstruct its script tree.
const SigningProvider & DUMMY_SIGNING_PROVIDER
void PolyMod(const std::vector< typename F::Elem > &mod, std::vector< typename F::Elem > &val, const F &field)
Compute the remainder of a polynomial division of val by mod, putting the result in mod.
Definition sketch_impl.h:18
TxoutType Solver(const CScript &scriptPubKey, std::vector< std::vector< unsigned char > > &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
Definition solver.cpp:141
CScript GetScriptForMultisig(int nRequired, const std::vector< CPubKey > &keys)
Generate a multisig script.
Definition solver.cpp:218
std::optional< std::pair< int, std::vector< std::span< const unsigned char > > > > MatchMultiA(const CScript &script)
Definition solver.cpp:107
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
Definition solver.cpp:213
TxoutType
Definition solver.h:22
@ WITNESS_V1_TAPROOT
@ WITNESS_V0_SCRIPTHASH
@ WITNESS_V0_KEYHASH
std::vector< Byte > ParseHex(std::string_view hex_str)
Like TryParseHex, but returns an empty vector on invalid input.
constexpr bool IsSpace(char c) noexcept
Tests if the given character is a whitespace character.
Definition key.h:238
CExtPubKey Neuter() const
Definition key.cpp:394
bool Derive(CExtPubKey &out, unsigned int nChild, uint256 *bip32_tweak_out=nullptr) const
Definition pubkey.cpp:385
Interface for parsed descriptor objects.
Definition descriptor.h:109
virtual std::optional< int64_t > MaxSatisfactionElems() const =0
Get the maximum size number of stack elements for satisfying this descriptor.
virtual void GetPubKeys(std::set< CPubKey > &pubkeys, std::set< CExtPubKey > &ext_pubs) const =0
Return all (extended) public keys for this descriptor, including any from subdescriptors.
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< int64_t > MaxSatisfactionWeight(bool use_max_sig) const =0
Get the maximum size of a satisfaction for this descriptor, in weight units.
virtual std::vector< std::string > Warnings() const =0
Semantic/safety warnings (includes subdescriptors).
virtual std::string ToCanonicalString() const =0
Convert the descriptor to the canonical string.
virtual std::string ToString(bool compat_format=false) const =0
Convert the descriptor back to a string, undoing parsing.
virtual std::optional< OutputType > GetOutputType() const =0
virtual bool HasScripts() const =0
Whether this descriptor produces any scripts with the Expand functions.
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 std::optional< int64_t > ScriptSize() const =0
Get the size of the scriptPubKey for this descriptor.
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 uint32_t GetMaxKeyExpr() const =0
Get the maximum key expression index.
virtual bool ToPrivateString(const SigningProvider &provider, std::string &out) const =0
Convert the descriptor to a private string.
virtual bool HavePrivateKeys(const SigningProvider &provider) const =0
Whether the given provider has all private keys required by this descriptor.
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.
bool GetPubKey(const CKeyID &keyid, CPubKey &pubkey) const override
KeyFingerprint fingerprint
First 32 bits of the Hash160 of the public key at the root of the path.
Definition keyorigin.h:14
std::vector< uint32_t > path
Definition keyorigin.h:15
std::vector< uint16_t > keys
FuzzedDataProvider provider
static int count
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
consteval auto _(util::TranslatedLiteral str)
Definition translation.h:79
bool IsHex(std::string_view str)
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.
Definition time.h:82
assert(!tx.IsCoinBase())
std::vector< std::common_type_t< Args... > > Vector(Args &&... args)
Construct a vector with the specified elements.
Definition vector.h:23