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