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