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