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