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