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 <script/miniscript.h>
11 : : #include <script/parsing.h>
12 : : #include <script/script.h>
13 : : #include <script/signingprovider.h>
14 : : #include <script/solver.h>
15 : : #include <uint256.h>
16 : :
17 : : #include <common/args.h>
18 : : #include <span.h>
19 : : #include <util/bip32.h>
20 : : #include <util/check.h>
21 : : #include <util/strencodings.h>
22 : : #include <util/vector.h>
23 : :
24 : : #include <algorithm>
25 : : #include <memory>
26 : : #include <numeric>
27 : : #include <optional>
28 : : #include <string>
29 : : #include <vector>
30 : :
31 : : using util::Split;
32 : :
33 : : namespace {
34 : :
35 : : ////////////////////////////////////////////////////////////////////////////
36 : : // Checksum //
37 : : ////////////////////////////////////////////////////////////////////////////
38 : :
39 : : // This section implements a checksum algorithm for descriptors with the
40 : : // following properties:
41 : : // * Mistakes in a descriptor string are measured in "symbol errors". The higher
42 : : // the number of symbol errors, the harder it is to detect:
43 : : // * An error substituting a character from 0123456789()[],'/*abcdefgh@:$%{} for
44 : : // another in that set always counts as 1 symbol error.
45 : : // * Note that hex encoded keys are covered by these characters. Xprvs and
46 : : // xpubs use other characters too, but already have their own checksum
47 : : // mechanism.
48 : : // * Function names like "multi()" use other characters, but mistakes in
49 : : // these would generally result in an unparsable descriptor.
50 : : // * A case error always counts as 1 symbol error.
51 : : // * Any other 1 character substitution error counts as 1 or 2 symbol errors.
52 : : // * Any 1 symbol error is always detected.
53 : : // * Any 2 or 3 symbol error in a descriptor of up to 49154 characters is always detected.
54 : : // * Any 4 symbol error in a descriptor of up to 507 characters is always detected.
55 : : // * Any 5 symbol error in a descriptor of up to 77 characters is always detected.
56 : : // * Is optimized to minimize the chance a 5 symbol error in a descriptor up to 387 characters is undetected
57 : : // * Random errors have a chance of 1 in 2**40 of being undetected.
58 : : //
59 : : // These properties are achieved by expanding every group of 3 (non checksum) characters into
60 : : // 4 GF(32) symbols, over which a cyclic code is defined.
61 : :
62 : : /*
63 : : * Interprets c as 8 groups of 5 bits which are the coefficients of a degree 8 polynomial over GF(32),
64 : : * multiplies that polynomial by x, computes its remainder modulo a generator, and adds the constant term val.
65 : : *
66 : : * 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}.
67 : : * It is chosen to define an cyclic error detecting code which is selected by:
68 : : * - Starting from all BCH codes over GF(32) of degree 8 and below, which by construction guarantee detecting
69 : : * 3 errors in windows up to 19000 symbols.
70 : : * - Taking all those generators, and for degree 7 ones, extend them to degree 8 by adding all degree-1 factors.
71 : : * - Selecting just the set of generators that guarantee detecting 4 errors in a window of length 512.
72 : : * - Selecting one of those with best worst-case behavior for 5 errors in windows of length up to 512.
73 : : *
74 : : * The generator and the constants to implement it can be verified using this Sage code:
75 : : * B = GF(2) # Binary field
76 : : * BP.<b> = B[] # Polynomials over the binary field
77 : : * F_mod = b**5 + b**3 + 1
78 : : * F.<f> = GF(32, modulus=F_mod, repr='int') # GF(32) definition
79 : : * FP.<x> = F[] # Polynomials over GF(32)
80 : : * E_mod = x**3 + x + F.fetch_int(8)
81 : : * E.<e> = F.extension(E_mod) # Extension field definition
82 : : * alpha = e**2743 # Choice of an element in extension field
83 : : * for p in divisors(E.order() - 1): # Verify alpha has order 32767.
84 : : * assert((alpha**p == 1) == (p % 32767 == 0))
85 : : * G = lcm([(alpha**i).minpoly() for i in [1056,1057,1058]] + [x + 1])
86 : : * print(G) # Print out the generator
87 : : * for i in [1,2,4,8,16]: # Print out {1,2,4,8,16}*(G mod x^8), packed in hex integers.
88 : : * v = 0
89 : : * for coef in reversed((F.fetch_int(i)*(G % x**8)).coefficients(sparse=True)):
90 : : * v = v*32 + coef.integer_representation()
91 : : * print("0x%x" % v)
92 : : */
93 : 281445522 : uint64_t PolyMod(uint64_t c, int val)
94 : : {
95 : 281445522 : uint8_t c0 = c >> 35;
96 : 281445522 : c = ((c & 0x7ffffffff) << 5) ^ val;
97 [ + + ]: 281445522 : if (c0 & 1) c ^= 0xf5dee51989;
98 [ + + ]: 281445522 : if (c0 & 2) c ^= 0xa9fdca3312;
99 [ + + ]: 281445522 : if (c0 & 4) c ^= 0x1bab10e32d;
100 [ + + ]: 281445522 : if (c0 & 8) c ^= 0x3706b1677a;
101 [ + + ]: 281445522 : if (c0 & 16) c ^= 0x644d626ffd;
102 : 281445522 : return c;
103 : : }
104 : :
105 : 277834 : std::string DescriptorChecksum(const std::span<const char>& span)
106 : : {
107 : : /** A character set designed such that:
108 : : * - The most common 'unprotected' descriptor characters (hex, keypaths) are in the first group of 32.
109 : : * - Case errors cause an offset that's a multiple of 32.
110 : : * - As many alphabetic characters are in the same group (while following the above restrictions).
111 : : *
112 : : * If p(x) gives the position of a character c in this character set, every group of 3 characters
113 : : * (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).
114 : : * This means that changes that only affect the lower 5 bits of the position, or only the higher 2 bits, will just
115 : : * affect a single symbol.
116 : : *
117 : : * As a result, within-group-of-32 errors count as 1 symbol, as do cross-group errors that don't affect
118 : : * the position within the groups.
119 : : */
120 : 277834 : static const std::string INPUT_CHARSET =
121 : : "0123456789()[],'/*abcdefgh@:$%{}"
122 : : "IJKLMNOPQRSTUVWXYZ&+-.;<=>?!^_|~"
123 [ + + + - : 278299 : "ijklmnopqrstuvwxyzABCDEFGH`#\"\\ ";
+ - ]
124 : :
125 : : /** The character set for the checksum itself (same as bech32). */
126 [ + + + - : 278299 : static const std::string CHECKSUM_CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
+ - ]
127 : :
128 : 277834 : uint64_t c = 1;
129 : 277834 : int cls = 0;
130 : 277834 : int clscount = 0;
131 [ + + ]: 209617757 : for (auto ch : span) {
132 : 209339924 : auto pos = INPUT_CHARSET.find(ch);
133 [ + + ]: 209339924 : if (pos == std::string::npos) return "";
134 : 209339923 : c = PolyMod(c, pos & 31); // Emit a symbol for the position inside the group, for every character.
135 : 209339923 : cls = cls * 3 + (pos >> 5); // Accumulate the group numbers
136 [ + + ]: 209339923 : if (++clscount == 3) {
137 : : // Emit an extra symbol representing the group numbers, for every 3 characters.
138 : 69666672 : c = PolyMod(c, cls);
139 : 69666672 : cls = 0;
140 : 69666672 : clscount = 0;
141 : : }
142 : : }
143 [ + + ]: 277833 : if (clscount > 0) c = PolyMod(c, cls);
144 [ + + ]: 2500497 : for (int j = 0; j < 8; ++j) c = PolyMod(c, 0); // Shift further to determine the checksum.
145 : 277833 : c ^= 1; // Prevent appending zeroes from not affecting the checksum.
146 : :
147 : 277833 : std::string ret(8, ' ');
148 [ + + ]: 2500497 : for (int j = 0; j < 8; ++j) ret[j] = CHECKSUM_CHARSET[(c >> (5 * (7 - j))) & 31];
149 : 277833 : return ret;
150 : 277833 : }
151 : :
152 [ + - + - ]: 536386 : std::string AddChecksum(const std::string& str) { return str + "#" + DescriptorChecksum(str); }
153 : :
154 : : ////////////////////////////////////////////////////////////////////////////
155 : : // Internal representation //
156 : : ////////////////////////////////////////////////////////////////////////////
157 : :
158 : : typedef std::vector<uint32_t> KeyPath;
159 : :
160 : : /** Interface for public key objects in descriptors. */
161 : : struct PubkeyProvider
162 : : {
163 : : protected:
164 : : //! Index of this key expression in the descriptor
165 : : //! E.g. If this PubkeyProvider is key1 in multi(2, key1, key2, key3), then m_expr_index = 0
166 : : uint32_t m_expr_index;
167 : :
168 : : public:
169 : 907666 : explicit PubkeyProvider(uint32_t exp_index) : m_expr_index(exp_index) {}
170 : :
171 : 0 : virtual ~PubkeyProvider() = default;
172 : :
173 : : /** Compare two public keys represented by this provider.
174 : : * Used by the Miniscript descriptors to check for duplicate keys in the script.
175 : : */
176 : 4636 : bool operator<(PubkeyProvider& other) const {
177 [ + - ]: 4636 : CPubKey a, b;
178 : 4636 : SigningProvider dummy;
179 [ + - ]: 4636 : KeyOriginInfo dummy_info;
180 : :
181 [ + - ]: 4636 : GetPubKey(0, dummy, a, dummy_info);
182 [ + - ]: 4636 : other.GetPubKey(0, dummy, b, dummy_info);
183 : :
184 : 4636 : return a < b;
185 : 4636 : }
186 : :
187 : : /** Derive a public key.
188 : : * read_cache is the cache to read keys from (if not nullptr)
189 : : * write_cache is the cache to write keys to (if not nullptr)
190 : : * Caches are not exclusive but this is not tested. Currently we use them exclusively
191 : : */
192 : : virtual bool GetPubKey(int pos, const SigningProvider& arg, CPubKey& key, KeyOriginInfo& info, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const = 0;
193 : :
194 : : /** Whether this represent multiple public keys at different positions. */
195 : : virtual bool IsRange() const = 0;
196 : :
197 : : /** Get the size of the generated public key(s) in bytes (33 or 65). */
198 : : virtual size_t GetSize() const = 0;
199 : :
200 : : enum class StringType {
201 : : PUBLIC,
202 : : COMPAT // string calculation that mustn't change over time to stay compatible with previous software versions
203 : : };
204 : :
205 : : /** Get the descriptor string form. */
206 : : virtual std::string ToString(StringType type=StringType::PUBLIC) const = 0;
207 : :
208 : : /** Get the descriptor string form including private data (if available in arg). */
209 : : virtual bool ToPrivateString(const SigningProvider& arg, std::string& out) const = 0;
210 : :
211 : : /** Get the descriptor string form with the xpub at the last hardened derivation,
212 : : * and always use h for hardened derivation.
213 : : */
214 : : virtual bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache = nullptr) const = 0;
215 : :
216 : : /** Derive a private key, if private data is available in arg. */
217 : : virtual bool GetPrivKey(int pos, const SigningProvider& arg, CKey& key) const = 0;
218 : :
219 : : /** Return the non-extended public key for this PubkeyProvider, if it has one. */
220 : : virtual std::optional<CPubKey> GetRootPubKey() const = 0;
221 : : /** Return the extended public key for this PubkeyProvider, if it has one. */
222 : : virtual std::optional<CExtPubKey> GetRootExtPubKey() const = 0;
223 : :
224 : : /** Make a deep copy of this PubkeyProvider */
225 : : virtual std::unique_ptr<PubkeyProvider> Clone() const = 0;
226 : : };
227 : :
228 : : class OriginPubkeyProvider final : public PubkeyProvider
229 : : {
230 : : KeyOriginInfo m_origin;
231 : : std::unique_ptr<PubkeyProvider> m_provider;
232 : : bool m_apostrophe;
233 : :
234 : 112803 : std::string OriginString(StringType type, bool normalized=false) const
235 : : {
236 : : // If StringType==COMPAT, always use the apostrophe to stay compatible with previous versions
237 [ + + + + : 112803 : bool use_apostrophe = (!normalized && m_apostrophe) || type == StringType::COMPAT;
+ + ]
238 [ + - + - ]: 225606 : return HexStr(m_origin.fingerprint) + FormatHDKeypath(m_origin.path, use_apostrophe);
239 : : }
240 : :
241 : : public:
242 : 434468 : 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) {}
243 : 63134 : bool GetPubKey(int pos, const SigningProvider& arg, CPubKey& key, KeyOriginInfo& info, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
244 : : {
245 [ + + ]: 63134 : if (!m_provider->GetPubKey(pos, arg, key, info, read_cache, write_cache)) return false;
246 : 63072 : std::copy(std::begin(m_origin.fingerprint), std::end(m_origin.fingerprint), info.fingerprint);
247 : 63072 : info.path.insert(info.path.begin(), m_origin.path.begin(), m_origin.path.end());
248 : 63072 : return true;
249 : : }
250 : 9824 : bool IsRange() const override { return m_provider->IsRange(); }
251 : 62509 : size_t GetSize() const override { return m_provider->GetSize(); }
252 [ + - + - : 337968 : std::string ToString(StringType type) const override { return "[" + OriginString(type) + "]" + m_provider->ToString(type); }
+ - ]
253 : 114 : bool ToPrivateString(const SigningProvider& arg, std::string& ret) const override
254 : : {
255 [ + - ]: 114 : std::string sub;
256 [ + - + + ]: 114 : if (!m_provider->ToPrivateString(arg, sub)) return false;
257 [ + - + - : 138 : ret = "[" + OriginString(StringType::PUBLIC) + "]" + std::move(sub);
+ - ]
258 : 69 : return true;
259 : 114 : }
260 : 78 : bool ToNormalizedString(const SigningProvider& arg, std::string& ret, const DescriptorCache* cache) const override
261 : : {
262 [ + - ]: 78 : std::string sub;
263 [ + - + - ]: 78 : if (!m_provider->ToNormalizedString(arg, sub, cache)) return false;
264 : : // If m_provider is a BIP32PubkeyProvider, we may get a string formatted like a OriginPubkeyProvider
265 : : // In that case, we need to strip out the leading square bracket and fingerprint from the substring,
266 : : // and append that to our own origin string.
267 [ + + ]: 78 : if (sub[0] == '[') {
268 [ + - ]: 4 : sub = sub.substr(9);
269 [ + - + - : 4 : ret = "[" + OriginString(StringType::PUBLIC, /*normalized=*/true) + std::move(sub);
+ - ]
270 : : } else {
271 [ + - + - : 148 : ret = "[" + OriginString(StringType::PUBLIC, /*normalized=*/true) + "]" + std::move(sub);
+ - ]
272 : : }
273 : : return true;
274 : 78 : }
275 : 137 : bool GetPrivKey(int pos, const SigningProvider& arg, CKey& key) const override
276 : : {
277 : 137 : return m_provider->GetPrivKey(pos, arg, key);
278 : : }
279 : 0 : std::optional<CPubKey> GetRootPubKey() const override
280 : : {
281 : 0 : return m_provider->GetRootPubKey();
282 : : }
283 : 0 : std::optional<CExtPubKey> GetRootExtPubKey() const override
284 : : {
285 : 0 : return m_provider->GetRootExtPubKey();
286 : : }
287 : 0 : std::unique_ptr<PubkeyProvider> Clone() const override
288 : : {
289 [ # # # # ]: 0 : return std::make_unique<OriginPubkeyProvider>(m_expr_index, m_origin, m_provider->Clone(), m_apostrophe);
290 : : }
291 : : };
292 : :
293 : : /** An object representing a parsed constant public key in a descriptor. */
294 : 0 : class ConstPubkeyProvider final : public PubkeyProvider
295 : : {
296 : : CPubKey m_pubkey;
297 : : bool m_xonly;
298 : :
299 : : public:
300 : 466258 : ConstPubkeyProvider(uint32_t exp_index, const CPubKey& pubkey, bool xonly) : PubkeyProvider(exp_index), m_pubkey(pubkey), m_xonly(xonly) {}
301 : 1012309 : bool GetPubKey(int pos, const SigningProvider& arg, CPubKey& key, KeyOriginInfo& info, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
302 : : {
303 : 1012309 : key = m_pubkey;
304 [ + + ]: 1012309 : info.path.clear();
305 : 1012309 : CKeyID keyid = m_pubkey.GetID();
306 : 1012309 : std::copy(keyid.begin(), keyid.begin() + sizeof(info.fingerprint), info.fingerprint);
307 : 1012309 : return true;
308 : : }
309 : 27970 : bool IsRange() const override { return false; }
310 : 77108 : size_t GetSize() const override { return m_pubkey.size(); }
311 [ + + + - ]: 392099 : std::string ToString(StringType type) const override { return m_xonly ? HexStr(m_pubkey).substr(2) : HexStr(m_pubkey); }
312 : 279 : bool ToPrivateString(const SigningProvider& arg, std::string& ret) const override
313 : : {
314 : 279 : CKey key;
315 [ + - + + ]: 279 : if (!GetPrivKey(/*pos=*/0, arg, key)) return false;
316 [ + - ]: 198 : ret = EncodeSecret(key);
317 : 198 : return true;
318 : 279 : }
319 : 4329 : bool ToNormalizedString(const SigningProvider& arg, std::string& ret, const DescriptorCache* cache) const override
320 : : {
321 : 4329 : ret = ToString(StringType::PUBLIC);
322 : 4329 : return true;
323 : : }
324 : 42639 : bool GetPrivKey(int pos, const SigningProvider& arg, CKey& key) const override
325 : : {
326 [ + + ]: 42639 : return m_xonly ? arg.GetKeyByXOnly(XOnlyPubKey(m_pubkey), key) :
327 : 5845 : arg.GetKey(m_pubkey.GetID(), key);
328 : : }
329 : 9 : std::optional<CPubKey> GetRootPubKey() const override
330 : : {
331 : 9 : return m_pubkey;
332 : : }
333 : 9 : std::optional<CExtPubKey> GetRootExtPubKey() const override
334 : : {
335 : 9 : return std::nullopt;
336 : : }
337 : 0 : std::unique_ptr<PubkeyProvider> Clone() const override
338 : : {
339 : 0 : return std::make_unique<ConstPubkeyProvider>(m_expr_index, m_pubkey, m_xonly);
340 : : }
341 : : };
342 : :
343 : : enum class DeriveType {
344 : : NO,
345 : : UNHARDENED,
346 : : HARDENED,
347 : : };
348 : :
349 : : /** An object representing a parsed extended public key in a descriptor. */
350 : : class BIP32PubkeyProvider final : public PubkeyProvider
351 : : {
352 : : // Root xpub, path, and final derivation step type being used, if any
353 : : CExtPubKey m_root_extkey;
354 : : KeyPath m_path;
355 : : DeriveType m_derive;
356 : : // Whether ' or h is used in harded derivation
357 : : bool m_apostrophe;
358 : :
359 : 33322 : bool GetExtKey(const SigningProvider& arg, CExtKey& ret) const
360 : : {
361 : 33322 : CKey key;
362 [ + - + - : 33322 : if (!arg.GetKey(m_root_extkey.pubkey.GetID(), key)) return false;
+ + ]
363 : 31879 : ret.nDepth = m_root_extkey.nDepth;
364 : 31879 : std::copy(m_root_extkey.vchFingerprint, m_root_extkey.vchFingerprint + sizeof(ret.vchFingerprint), ret.vchFingerprint);
365 : 31879 : ret.nChild = m_root_extkey.nChild;
366 : 31879 : ret.chaincode = m_root_extkey.chaincode;
367 [ + - ]: 31879 : ret.key = key;
368 : : return true;
369 : 33322 : }
370 : :
371 : : // Derives the last xprv
372 : 32885 : bool GetDerivedExtKey(const SigningProvider& arg, CExtKey& xprv, CExtKey& last_hardened) const
373 : : {
374 [ + + ]: 32885 : if (!GetExtKey(arg, xprv)) return false;
375 [ + + ]: 99482 : for (auto entry : m_path) {
376 [ + - ]: 67907 : if (!xprv.Derive(xprv, entry)) return false;
377 [ + + ]: 67907 : if (entry >> 31) {
378 : 53138 : last_hardened = xprv;
379 : : }
380 : : }
381 : : return true;
382 : : }
383 : :
384 : 36516 : bool IsHardened() const
385 : : {
386 [ + + ]: 36516 : if (m_derive == DeriveType::HARDENED) return true;
387 [ + + ]: 36171 : for (auto entry : m_path) {
388 [ + + ]: 24463 : if (entry >> 31) return true;
389 : : }
390 : : return false;
391 : : }
392 : :
393 : : public:
394 : 6940 : 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) {}
395 : 218908 : bool IsRange() const override { return m_derive != DeriveType::NO; }
396 : 580 : size_t GetSize() const override { return 33; }
397 : 708887 : bool GetPubKey(int pos, const SigningProvider& arg, CPubKey& key_out, KeyOriginInfo& final_info_out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
398 : : {
399 : : // Info of parent of the to be derived pubkey
400 [ + - ]: 708887 : KeyOriginInfo parent_info;
401 [ + - ]: 708887 : CKeyID keyid = m_root_extkey.pubkey.GetID();
402 : 708887 : std::copy(keyid.begin(), keyid.begin() + sizeof(parent_info.fingerprint), parent_info.fingerprint);
403 [ + - ]: 708887 : parent_info.path = m_path;
404 : :
405 : : // Info of the derived key itself which is copied out upon successful completion
406 [ + - ]: 708887 : KeyOriginInfo final_info_out_tmp = parent_info;
407 [ + + + - ]: 708887 : if (m_derive == DeriveType::UNHARDENED) final_info_out_tmp.path.push_back((uint32_t)pos);
408 [ + + + - ]: 708887 : if (m_derive == DeriveType::HARDENED) final_info_out_tmp.path.push_back(((uint32_t)pos) | 0x80000000L);
409 : :
410 : : // Derive keys or fetch them from cache
411 : 708887 : CExtPubKey final_extkey = m_root_extkey;
412 : 708887 : CExtPubKey parent_extkey = m_root_extkey;
413 [ + + ]: 708887 : CExtPubKey last_hardened_extkey;
414 : 708887 : bool der = true;
415 [ + + ]: 708887 : if (read_cache) {
416 [ + - + + ]: 672371 : if (!read_cache->GetCachedDerivedExtPubKey(m_expr_index, pos, final_extkey)) {
417 [ + + ]: 668053 : if (m_derive == DeriveType::HARDENED) return false;
418 : : // Try to get the derivation parent
419 [ + - + + ]: 656996 : if (!read_cache->GetCachedParentExtPubKey(m_expr_index, parent_extkey)) return false;
420 : 653664 : final_extkey = parent_extkey;
421 [ + + + - ]: 653664 : if (m_derive == DeriveType::UNHARDENED) der = parent_extkey.Derive(final_extkey, pos);
422 : : }
423 [ + + ]: 36516 : } else if (IsHardened()) {
424 [ + - ]: 24808 : CExtKey xprv;
425 : 24808 : CExtKey lh_xprv;
426 [ + - + + ]: 24808 : if (!GetDerivedExtKey(arg, xprv, lh_xprv)) return false;
427 [ + - ]: 24691 : parent_extkey = xprv.Neuter();
428 [ + + + - ]: 24691 : if (m_derive == DeriveType::UNHARDENED) der = xprv.Derive(xprv, pos);
429 [ + + + - ]: 24691 : if (m_derive == DeriveType::HARDENED) der = xprv.Derive(xprv, pos | 0x80000000UL);
430 [ + - ]: 24691 : final_extkey = xprv.Neuter();
431 [ + + ]: 24691 : if (lh_xprv.key.IsValid()) {
432 [ + - ]: 21660 : last_hardened_extkey = lh_xprv.Neuter();
433 : : }
434 : 24808 : } else {
435 [ + + ]: 28510 : for (auto entry : m_path) {
436 [ + - + - ]: 16802 : if (!parent_extkey.Derive(parent_extkey, entry)) return false;
437 : : }
438 : 11708 : final_extkey = parent_extkey;
439 [ + + + - ]: 11708 : if (m_derive == DeriveType::UNHARDENED) der = parent_extkey.Derive(final_extkey, pos);
440 [ - + ]: 11708 : assert(m_derive != DeriveType::HARDENED);
441 : : }
442 [ + - ]: 689294 : if (!der) return false;
443 : :
444 [ + - ]: 694381 : final_info_out = final_info_out_tmp;
445 : 694381 : key_out = final_extkey.pubkey;
446 : :
447 [ + + ]: 694381 : if (write_cache) {
448 : : // Only cache parent if there is any unhardened derivation
449 [ + + ]: 15395 : if (m_derive != DeriveType::HARDENED) {
450 [ + - ]: 4373 : write_cache->CacheParentExtPubKey(m_expr_index, parent_extkey);
451 : : // Cache last hardened xpub if we have it
452 [ + + ]: 4373 : if (last_hardened_extkey.pubkey.IsValid()) {
453 [ + - ]: 3064 : write_cache->CacheLastHardenedExtPubKey(m_expr_index, last_hardened_extkey);
454 : : }
455 [ + - ]: 11022 : } else if (final_info_out.path.size() > 0) {
456 [ + - ]: 11022 : write_cache->CacheDerivedExtPubKey(m_expr_index, pos, final_extkey);
457 : : }
458 : : }
459 : :
460 : : return true;
461 : 708887 : }
462 : 124862 : std::string ToString(StringType type, bool normalized) const
463 : : {
464 : : // If StringType==COMPAT, always use the apostrophe to stay compatible with previous versions
465 [ + + + + : 124862 : const bool use_apostrophe = (!normalized && m_apostrophe) || type == StringType::COMPAT;
+ + ]
466 [ + - + - ]: 249724 : std::string ret = EncodeExtPubKey(m_root_extkey) + FormatHDKeypath(m_path, /*apostrophe=*/use_apostrophe);
467 [ + + ]: 124862 : if (IsRange()) {
468 [ + - ]: 123528 : ret += "/*";
469 [ + + + + ]: 123528 : if (m_derive == DeriveType::HARDENED) ret += use_apostrophe ? '\'' : 'h';
470 : : }
471 : 124862 : return ret;
472 : 0 : }
473 : 124836 : std::string ToString(StringType type=StringType::PUBLIC) const override
474 : : {
475 : 124496 : return ToString(type, /*normalized=*/false);
476 : : }
477 : 437 : bool ToPrivateString(const SigningProvider& arg, std::string& out) const override
478 : : {
479 [ + - ]: 437 : CExtKey key;
480 [ + - + + ]: 437 : if (!GetExtKey(arg, key)) return false;
481 [ + - + - : 304 : out = EncodeExtKey(key) + FormatHDKeypath(m_path, /*apostrophe=*/m_apostrophe);
+ - ]
482 [ + + ]: 304 : if (IsRange()) {
483 [ + - ]: 164 : out += "/*";
484 [ + + + + ]: 449 : if (m_derive == DeriveType::HARDENED) out += m_apostrophe ? '\'' : 'h';
485 : : }
486 : : return true;
487 : 437 : }
488 : 1326 : bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache) const override
489 : : {
490 [ + + ]: 1326 : if (m_derive == DeriveType::HARDENED) {
491 : 26 : out = ToString(StringType::PUBLIC, /*normalized=*/true);
492 : :
493 : 26 : return true;
494 : : }
495 : : // Step backwards to find the last hardened step in the path
496 : 1300 : int i = (int)m_path.size() - 1;
497 [ + + ]: 2480 : for (; i >= 0; --i) {
498 [ + + ]: 2140 : if (m_path.at(i) >> 31) {
499 : : break;
500 : : }
501 : : }
502 : : // Either no derivation or all unhardened derivation
503 [ + + ]: 1300 : if (i == -1) {
504 : 340 : out = ToString();
505 : 340 : return true;
506 : : }
507 : : // Get the path to the last hardened stup
508 : 960 : KeyOriginInfo origin;
509 : 960 : int k = 0;
510 [ + + ]: 3812 : for (; k <= i; ++k) {
511 : : // Add to the path
512 [ + - + - ]: 2852 : origin.path.push_back(m_path.at(k));
513 : : }
514 : : // Build the remaining path
515 : 960 : KeyPath end_path;
516 [ + + ]: 1925 : for (; k < (int)m_path.size(); ++k) {
517 [ + - + - ]: 965 : end_path.push_back(m_path.at(k));
518 : : }
519 : : // Get the fingerprint
520 [ + - ]: 960 : CKeyID id = m_root_extkey.pubkey.GetID();
521 : 960 : std::copy(id.begin(), id.begin() + 4, origin.fingerprint);
522 : :
523 [ + + ]: 960 : CExtPubKey xpub;
524 [ + + ]: 960 : CExtKey lh_xprv;
525 : : // If we have the cache, just get the parent xpub
526 [ + + ]: 960 : if (cache != nullptr) {
527 [ + - ]: 942 : cache->GetCachedLastHardenedExtPubKey(m_expr_index, xpub);
528 : : }
529 [ + + ]: 960 : if (!xpub.pubkey.IsValid()) {
530 : : // Cache miss, or nor cache, or need privkey
531 [ + - ]: 18 : CExtKey xprv;
532 [ + - - + ]: 18 : if (!GetDerivedExtKey(arg, xprv, lh_xprv)) return false;
533 [ + - ]: 18 : xpub = lh_xprv.Neuter();
534 : 18 : }
535 [ - + ]: 960 : assert(xpub.pubkey.IsValid());
536 : :
537 : : // Build the string
538 [ + - + - : 1920 : std::string origin_str = HexStr(origin.fingerprint) + FormatHDKeypath(origin.path);
+ - ]
539 [ + - + - : 1920 : out = "[" + origin_str + "]" + EncodeExtPubKey(xpub) + FormatHDKeypath(end_path);
+ - + - +
- ]
540 [ + + ]: 960 : if (IsRange()) {
541 [ + - ]: 946 : out += "/*";
542 [ - + ]: 946 : assert(m_derive == DeriveType::UNHARDENED);
543 : : }
544 : 960 : return true;
545 : 1920 : }
546 : 8059 : bool GetPrivKey(int pos, const SigningProvider& arg, CKey& key) const override
547 : : {
548 [ + - ]: 8059 : CExtKey extkey;
549 : 8059 : CExtKey dummy;
550 [ + - + + ]: 8059 : if (!GetDerivedExtKey(arg, extkey, dummy)) return false;
551 [ + + + - : 6866 : if (m_derive == DeriveType::UNHARDENED && !extkey.Derive(extkey, pos)) return false;
+ - ]
552 [ + + + - : 6866 : if (m_derive == DeriveType::HARDENED && !extkey.Derive(extkey, pos | 0x80000000UL)) return false;
+ - ]
553 [ + - ]: 6866 : key = extkey.key;
554 : : return true;
555 : 8059 : }
556 : 248 : std::optional<CPubKey> GetRootPubKey() const override
557 : : {
558 : 248 : return std::nullopt;
559 : : }
560 : 248 : std::optional<CExtPubKey> GetRootExtPubKey() const override
561 : : {
562 : 248 : return m_root_extkey;
563 : : }
564 : 42 : std::unique_ptr<PubkeyProvider> Clone() const override
565 : : {
566 [ - + ]: 42 : return std::make_unique<BIP32PubkeyProvider>(m_expr_index, m_root_extkey, m_path, m_derive, m_apostrophe);
567 : : }
568 : : };
569 : :
570 : : /** Base class for all Descriptor implementations. */
571 : : class DescriptorImpl : public Descriptor
572 : : {
573 : : protected:
574 : : //! Public key arguments for this descriptor (size 1 for PK, PKH, WPKH; any size for WSH and Multisig).
575 : : const std::vector<std::unique_ptr<PubkeyProvider>> m_pubkey_args;
576 : : //! The string name of the descriptor function.
577 : : const std::string m_name;
578 : :
579 : : //! The sub-descriptor arguments (empty for everything but SH and WSH).
580 : : //! In doc/descriptors.m this is referred to as SCRIPT expressions sh(SCRIPT)
581 : : //! and wsh(SCRIPT), and distinct from KEY expressions and ADDR expressions.
582 : : //! Subdescriptors can only ever generate a single script.
583 : : const std::vector<std::unique_ptr<DescriptorImpl>> m_subdescriptor_args;
584 : :
585 : : //! Return a serialization of anything except pubkey and script arguments, to be prepended to those.
586 : 308478 : virtual std::string ToStringExtra() const { return ""; }
587 : :
588 : : /** A helper function to construct the scripts for this descriptor.
589 : : *
590 : : * This function is invoked once by ExpandHelper.
591 : : *
592 : : * @param pubkeys The evaluations of the m_pubkey_args field.
593 : : * @param scripts The evaluations of m_subdescriptor_args (one for each m_subdescriptor_args element).
594 : : * @param out A FlatSigningProvider to put scripts or public keys in that are necessary to the solver.
595 : : * The origin info of the provided pubkeys is automatically added.
596 : : * @return A vector with scriptPubKeys for this descriptor.
597 : : */
598 : : virtual std::vector<CScript> MakeScripts(const std::vector<CPubKey>& pubkeys, std::span<const CScript> scripts, FlatSigningProvider& out) const = 0;
599 : :
600 : : public:
601 [ + - ]: 347239 : DescriptorImpl(std::vector<std::unique_ptr<PubkeyProvider>> pubkeys, const std::string& name) : m_pubkey_args(std::move(pubkeys)), m_name(name), m_subdescriptor_args() {}
602 [ + - + - ]: 39068 : 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))) {}
603 [ + - ]: 6751 : 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)) {}
604 : :
605 : : enum class StringType
606 : : {
607 : : PUBLIC,
608 : : PRIVATE,
609 : : NORMALIZED,
610 : : COMPAT, // string calculation that mustn't change over time to stay compatible with previous software versions
611 : : };
612 : :
613 : : // NOLINTNEXTLINE(misc-no-recursion)
614 : 3587 : bool IsSolvable() const override
615 : : {
616 [ + + ]: 5233 : for (const auto& arg : m_subdescriptor_args) {
617 [ + - ]: 1646 : if (!arg->IsSolvable()) return false;
618 : : }
619 : : return true;
620 : : }
621 : :
622 : : // NOLINTNEXTLINE(misc-no-recursion)
623 : 119092 : bool IsRange() const final
624 : : {
625 [ + + ]: 147344 : for (const auto& pubkey : m_pubkey_args) {
626 [ + + ]: 120752 : if (pubkey->IsRange()) return true;
627 : : }
628 [ + + ]: 28608 : for (const auto& arg : m_subdescriptor_args) {
629 [ + + ]: 9777 : if (arg->IsRange()) return true;
630 : : }
631 : : return false;
632 : : }
633 : :
634 : : // NOLINTNEXTLINE(misc-no-recursion)
635 : 309445 : virtual bool ToStringSubScriptHelper(const SigningProvider* arg, std::string& ret, const StringType type, const DescriptorCache* cache = nullptr) const
636 : : {
637 : 309445 : size_t pos = 0;
638 [ + + ]: 354625 : for (const auto& scriptarg : m_subdescriptor_args) {
639 [ - + ]: 45291 : if (pos++) ret += ",";
640 [ + - ]: 45291 : std::string tmp;
641 [ + - + + ]: 45291 : if (!scriptarg->ToStringHelper(arg, tmp, type, cache)) return false;
642 [ + - ]: 90360 : ret += tmp;
643 : 45291 : }
644 : : return true;
645 : : }
646 : :
647 : : // NOLINTNEXTLINE(misc-no-recursion)
648 : 316895 : virtual bool ToStringHelper(const SigningProvider* arg, std::string& out, const StringType type, const DescriptorCache* cache = nullptr) const
649 : : {
650 : 316895 : std::string extra = ToStringExtra();
651 [ + + ]: 316895 : size_t pos = extra.size() > 0 ? 1 : 0;
652 [ + - + - ]: 316895 : std::string ret = m_name + "(" + extra;
653 [ + + ]: 700979 : for (const auto& pubkey : m_pubkey_args) {
654 [ + + + - ]: 384265 : if (pos++) ret += ",";
655 [ + + + + : 384265 : std::string tmp;
- ]
656 [ + + + + : 384265 : switch (type) {
- ]
657 : 5655 : case StringType::NORMALIZED:
658 [ + - + - ]: 5655 : if (!pubkey->ToNormalizedString(*arg, tmp, cache)) return false;
659 : : break;
660 : 583 : case StringType::PRIVATE:
661 [ + - + + ]: 583 : if (!pubkey->ToPrivateString(*arg, tmp)) return false;
662 : : break;
663 : 362065 : case StringType::PUBLIC:
664 [ + - ]: 362065 : tmp = pubkey->ToString();
665 : 362065 : break;
666 : 15962 : case StringType::COMPAT:
667 [ + - ]: 15962 : tmp = pubkey->ToString(PubkeyProvider::StringType::COMPAT);
668 : 15962 : break;
669 : : }
670 [ + - ]: 768168 : ret += tmp;
671 : 384265 : }
672 [ + - ]: 633428 : std::string subscript;
673 [ + - + + ]: 316714 : if (!ToStringSubScriptHelper(arg, subscript, type, cache)) return false;
674 [ + + + + : 316603 : if (pos && subscript.size()) ret += ',';
+ - ]
675 [ + - ]: 633206 : out = std::move(ret) + std::move(subscript) + ")";
676 : 316603 : return true;
677 : 316895 : }
678 : :
679 : 266418 : std::string ToString(bool compat_format) const final
680 : : {
681 [ + + ]: 266418 : std::string ret;
682 [ + + + - ]: 526572 : ToStringHelper(nullptr, ret, compat_format ? StringType::COMPAT : StringType::PUBLIC);
683 [ + - ]: 266418 : return AddChecksum(ret);
684 : 266418 : }
685 : :
686 : 457 : bool ToPrivateString(const SigningProvider& arg, std::string& out) const override
687 : : {
688 : 457 : bool ret = ToStringHelper(&arg, out, StringType::PRIVATE);
689 : 457 : out = AddChecksum(out);
690 : 457 : return ret;
691 : : }
692 : :
693 : 1318 : bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache) const override final
694 : : {
695 : 1318 : bool ret = ToStringHelper(&arg, out, StringType::NORMALIZED, cache);
696 : 1318 : out = AddChecksum(out);
697 : 1318 : return ret;
698 : : }
699 : :
700 : : // NOLINTNEXTLINE(misc-no-recursion)
701 : 766682 : bool ExpandHelper(int pos, const SigningProvider& arg, const DescriptorCache* read_cache, std::vector<CScript>& output_scripts, FlatSigningProvider& out, DescriptorCache* write_cache) const
702 : : {
703 : 766682 : std::vector<std::pair<CPubKey, KeyOriginInfo>> entries;
704 [ + - ]: 766682 : entries.reserve(m_pubkey_args.size());
705 : :
706 : : // Construct temporary data in `entries`, `subscripts`, and `subprovider` to avoid producing output in case of failure.
707 [ + + ]: 2464104 : for (const auto& p : m_pubkey_args) {
708 [ + - ]: 1711924 : entries.emplace_back();
709 [ + - + + ]: 1711924 : if (!p->GetPubKey(pos, arg, entries.back().first, entries.back().second, read_cache, write_cache)) return false;
710 : : }
711 : 752180 : std::vector<CScript> subscripts;
712 : 752180 : FlatSigningProvider subprovider;
713 [ + + ]: 921752 : for (const auto& subarg : m_subdescriptor_args) {
714 : 170745 : std::vector<CScript> outscripts;
715 [ + - + + ]: 170745 : if (!subarg->ExpandHelper(pos, arg, read_cache, outscripts, subprovider, write_cache)) return false;
716 [ - + ]: 169572 : assert(outscripts.size() == 1);
717 [ + - ]: 169572 : subscripts.emplace_back(std::move(outscripts[0]));
718 : 170745 : }
719 [ + - ]: 751007 : out.Merge(std::move(subprovider));
720 : :
721 : 751007 : std::vector<CPubKey> pubkeys;
722 [ + - ]: 751007 : pubkeys.reserve(entries.size());
723 [ + + ]: 2448365 : for (auto& entry : entries) {
724 [ + - ]: 1697358 : pubkeys.push_back(entry.first);
725 [ + - + - ]: 3394716 : out.origins.emplace(entry.first.GetID(), std::make_pair<CPubKey, KeyOriginInfo>(CPubKey(entry.first), std::move(entry.second)));
726 : : }
727 : :
728 [ + - ]: 1502014 : output_scripts = MakeScripts(pubkeys, std::span{subscripts}, out);
729 : 751007 : return true;
730 : 766682 : }
731 : :
732 : 37413 : bool Expand(int pos, const SigningProvider& provider, std::vector<CScript>& output_scripts, FlatSigningProvider& out, DescriptorCache* write_cache = nullptr) const final
733 : : {
734 : 37413 : return ExpandHelper(pos, provider, nullptr, output_scripts, out, write_cache);
735 : : }
736 : :
737 : 558524 : bool ExpandFromCache(int pos, const DescriptorCache& read_cache, std::vector<CScript>& output_scripts, FlatSigningProvider& out) const final
738 : : {
739 : 558524 : return ExpandHelper(pos, DUMMY_SIGNING_PROVIDER, &read_cache, output_scripts, out, nullptr);
740 : : }
741 : :
742 : : // NOLINTNEXTLINE(misc-no-recursion)
743 : 14311 : void ExpandPrivate(int pos, const SigningProvider& provider, FlatSigningProvider& out) const final
744 : : {
745 [ + + ]: 64730 : for (const auto& p : m_pubkey_args) {
746 : 50419 : CKey key;
747 [ + - + + ]: 50419 : if (!p->GetPrivKey(pos, provider, key)) continue;
748 [ + - + - : 12193 : out.keys.emplace(key.GetPubKey().GetID(), key);
+ - ]
749 : 50419 : }
750 [ + + ]: 16825 : for (const auto& arg : m_subdescriptor_args) {
751 : 2514 : arg->ExpandPrivate(pos, provider, out);
752 : : }
753 : 14311 : }
754 : :
755 : 479 : std::optional<OutputType> GetOutputType() const override { return std::nullopt; }
756 : :
757 : 0 : std::optional<int64_t> ScriptSize() const override { return {}; }
758 : :
759 : : /** A helper for MaxSatisfactionWeight.
760 : : *
761 : : * @param use_max_sig Whether to assume ECDSA signatures will have a high-r.
762 : : * @return The maximum size of the satisfaction in raw bytes (with no witness meaning).
763 : : */
764 : 0 : virtual std::optional<int64_t> MaxSatSize(bool use_max_sig) const { return {}; }
765 : :
766 : 11 : std::optional<int64_t> MaxSatisfactionWeight(bool) const override { return {}; }
767 : :
768 : 4 : std::optional<int64_t> MaxSatisfactionElems() const override { return {}; }
769 : :
770 : : // NOLINTNEXTLINE(misc-no-recursion)
771 : 313 : void GetPubKeys(std::set<CPubKey>& pubkeys, std::set<CExtPubKey>& ext_pubs) const override
772 : : {
773 [ + + ]: 570 : for (const auto& p : m_pubkey_args) {
774 : 257 : std::optional<CPubKey> pub = p->GetRootPubKey();
775 [ + + ]: 257 : if (pub) pubkeys.insert(*pub);
776 : 257 : std::optional<CExtPubKey> ext_pub = p->GetRootExtPubKey();
777 [ + + ]: 257 : if (ext_pub) ext_pubs.insert(*ext_pub);
778 : : }
779 [ + + ]: 371 : for (const auto& arg : m_subdescriptor_args) {
780 : 58 : arg->GetPubKeys(pubkeys, ext_pubs);
781 : : }
782 : 313 : }
783 : :
784 : : virtual std::unique_ptr<DescriptorImpl> Clone() const = 0;
785 : : };
786 : :
787 : : /** A parsed addr(A) descriptor. */
788 : : class AddressDescriptor final : public DescriptorImpl
789 : : {
790 : : const CTxDestination m_destination;
791 : : protected:
792 : 4390 : std::string ToStringExtra() const override { return EncodeDestination(m_destination); }
793 [ + - ]: 312 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, std::span<const CScript>, FlatSigningProvider&) const override { return Vector(GetScriptForDestination(m_destination)); }
794 : : public:
795 [ + - ]: 4293 : AddressDescriptor(CTxDestination destination) : DescriptorImpl({}, "addr"), m_destination(std::move(destination)) {}
796 : 15 : bool IsSolvable() const final { return false; }
797 : :
798 : 48 : std::optional<OutputType> GetOutputType() const override
799 : : {
800 : 48 : return OutputTypeFromDestination(m_destination);
801 : : }
802 : 0 : bool IsSingleType() const final { return true; }
803 : 14 : bool ToPrivateString(const SigningProvider& arg, std::string& out) const final { return false; }
804 : :
805 [ # # ]: 0 : std::optional<int64_t> ScriptSize() const override { return GetScriptForDestination(m_destination).size(); }
806 : 0 : std::unique_ptr<DescriptorImpl> Clone() const override
807 : : {
808 [ # # ]: 0 : return std::make_unique<AddressDescriptor>(m_destination);
809 : : }
810 : : };
811 : :
812 : : /** A parsed raw(H) descriptor. */
813 : : class RawDescriptor final : public DescriptorImpl
814 : : {
815 : : const CScript m_script;
816 : : protected:
817 [ + + ]: 3068 : std::string ToStringExtra() const override { return HexStr(m_script); }
818 : 1888 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, std::span<const CScript>, FlatSigningProvider&) const override { return Vector(m_script); }
819 : : public:
820 [ + - ]: 3348 : RawDescriptor(CScript script) : DescriptorImpl({}, "raw"), m_script(std::move(script)) {}
821 : 0 : bool IsSolvable() const final { return false; }
822 : :
823 : 2 : std::optional<OutputType> GetOutputType() const override
824 : : {
825 : 2 : CTxDestination dest;
826 [ + - ]: 2 : ExtractDestination(m_script, dest);
827 [ + - ]: 2 : return OutputTypeFromDestination(dest);
828 : 2 : }
829 : 0 : bool IsSingleType() const final { return true; }
830 : 1 : bool ToPrivateString(const SigningProvider& arg, std::string& out) const final { return false; }
831 : :
832 [ # # ]: 0 : std::optional<int64_t> ScriptSize() const override { return m_script.size(); }
833 : :
834 : 0 : std::unique_ptr<DescriptorImpl> Clone() const override
835 : : {
836 [ # # ]: 0 : return std::make_unique<RawDescriptor>(m_script);
837 : : }
838 : : };
839 : :
840 : : /** A parsed pk(P) descriptor. */
841 : : class PKDescriptor final : public DescriptorImpl
842 : : {
843 : : private:
844 : : const bool m_xonly;
845 : : protected:
846 : 27354 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override
847 : : {
848 [ + + ]: 27354 : if (m_xonly) {
849 [ + - + - ]: 27033 : CScript script = CScript() << ToByteVector(XOnlyPubKey(keys[0])) << OP_CHECKSIG;
850 [ + - ]: 27033 : return Vector(std::move(script));
851 : 27033 : } else {
852 [ + - ]: 642 : return Vector(GetScriptForRawPubKey(keys[0]));
853 : : }
854 : : }
855 : : public:
856 [ + - + - ]: 22251 : PKDescriptor(std::unique_ptr<PubkeyProvider> prov, bool xonly = false) : DescriptorImpl(Vector(std::move(prov)), "pk"), m_xonly(xonly) {}
857 : 6 : bool IsSingleType() const final { return true; }
858 : :
859 : 11 : std::optional<int64_t> ScriptSize() const override {
860 [ + - ]: 11 : return 1 + (m_xonly ? 32 : m_pubkey_args[0]->GetSize()) + 1;
861 : : }
862 : :
863 : 64 : std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
864 [ + + ]: 6 : const auto ecdsa_sig_size = use_max_sig ? 72 : 71;
865 [ + - + - ]: 64 : return 1 + (m_xonly ? 65 : ecdsa_sig_size);
866 : : }
867 : :
868 : 58 : std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
869 [ + + ]: 58 : return *MaxSatSize(use_max_sig) * WITNESS_SCALE_FACTOR;
870 : : }
871 : :
872 : 56 : std::optional<int64_t> MaxSatisfactionElems() const override { return 1; }
873 : :
874 : 0 : std::unique_ptr<DescriptorImpl> Clone() const override
875 : : {
876 [ # # # # ]: 0 : return std::make_unique<PKDescriptor>(m_pubkey_args.at(0)->Clone(), m_xonly);
877 : : }
878 : : };
879 : :
880 : : /** A parsed pkh(P) descriptor. */
881 : : class PKHDescriptor final : public DescriptorImpl
882 : : {
883 : : protected:
884 : 135232 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider& out) const override
885 : : {
886 : 135232 : CKeyID id = keys[0].GetID();
887 : 135232 : out.pubkeys.emplace(id, keys[0]);
888 [ + - + - ]: 270464 : return Vector(GetScriptForDestination(PKHash(id)));
889 : : }
890 : : public:
891 [ + - + - ]: 104142 : PKHDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "pkh") {}
892 : 77619 : std::optional<OutputType> GetOutputType() const override { return OutputType::LEGACY; }
893 : 16546 : bool IsSingleType() const final { return true; }
894 : :
895 : 72 : std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 1 + 20 + 1 + 1; }
896 : :
897 : 57789 : std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
898 [ + + ]: 57789 : const auto sig_size = use_max_sig ? 72 : 71;
899 : 57789 : return 1 + sig_size + 1 + m_pubkey_args[0]->GetSize();
900 : : }
901 : :
902 : 57729 : std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
903 : 57729 : return *MaxSatSize(use_max_sig) * WITNESS_SCALE_FACTOR;
904 : : }
905 : :
906 : 57774 : std::optional<int64_t> MaxSatisfactionElems() const override { return 2; }
907 : :
908 : 0 : std::unique_ptr<DescriptorImpl> Clone() const override
909 : : {
910 [ # # # # ]: 0 : return std::make_unique<PKHDescriptor>(m_pubkey_args.at(0)->Clone());
911 : : }
912 : : };
913 : :
914 : : /** A parsed wpkh(P) descriptor. */
915 : : class WPKHDescriptor final : public DescriptorImpl
916 : : {
917 : : protected:
918 : 275833 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider& out) const override
919 : : {
920 : 275833 : CKeyID id = keys[0].GetID();
921 : 275833 : out.pubkeys.emplace(id, keys[0]);
922 [ + - + - ]: 551666 : return Vector(GetScriptForDestination(WitnessV0KeyHash(id)));
923 : : }
924 : : public:
925 [ + - + - ]: 194601 : WPKHDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "wpkh") {}
926 : 170829 : std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32; }
927 : 26796 : bool IsSingleType() const final { return true; }
928 : :
929 : 9573 : std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 20; }
930 : :
931 : 137063 : std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
932 [ + + ]: 9568 : const auto sig_size = use_max_sig ? 72 : 71;
933 : 137063 : return (1 + sig_size + 1 + 33);
934 : : }
935 : :
936 : 127495 : std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
937 [ + + ]: 127495 : return MaxSatSize(use_max_sig);
938 : : }
939 : :
940 : 137053 : std::optional<int64_t> MaxSatisfactionElems() const override { return 2; }
941 : :
942 : 0 : std::unique_ptr<DescriptorImpl> Clone() const override
943 : : {
944 [ # # # # ]: 0 : return std::make_unique<WPKHDescriptor>(m_pubkey_args.at(0)->Clone());
945 : : }
946 : : };
947 : :
948 : : /** A parsed combo(P) descriptor. */
949 : : class ComboDescriptor final : public DescriptorImpl
950 : : {
951 : : protected:
952 : 19217 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider& out) const override
953 : : {
954 : 19217 : std::vector<CScript> ret;
955 [ + - ]: 19217 : CKeyID id = keys[0].GetID();
956 [ + - ]: 19217 : out.pubkeys.emplace(id, keys[0]);
957 [ + - + - ]: 19217 : ret.emplace_back(GetScriptForRawPubKey(keys[0])); // P2PK
958 [ + - + - : 38434 : ret.emplace_back(GetScriptForDestination(PKHash(id))); // P2PKH
+ - ]
959 [ + + ]: 19217 : if (keys[0].IsCompressed()) {
960 [ + - ]: 19189 : CScript p2wpkh = GetScriptForDestination(WitnessV0KeyHash(id));
961 [ + - + - ]: 19189 : out.scripts.emplace(CScriptID(p2wpkh), p2wpkh);
962 [ + - ]: 19189 : ret.emplace_back(p2wpkh);
963 [ + - + - : 38378 : ret.emplace_back(GetScriptForDestination(ScriptHash(p2wpkh))); // P2SH-P2WPKH
+ - ]
964 : 19189 : }
965 : 19217 : return ret;
966 : 0 : }
967 : : public:
968 [ + - + - ]: 499 : ComboDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "combo") {}
969 : 5 : bool IsSingleType() const final { return false; }
970 : 0 : std::unique_ptr<DescriptorImpl> Clone() const override
971 : : {
972 [ # # # # ]: 0 : return std::make_unique<ComboDescriptor>(m_pubkey_args.at(0)->Clone());
973 : : }
974 : : };
975 : :
976 : : /** A parsed multi(...) or sortedmulti(...) descriptor */
977 : : class MultisigDescriptor final : public DescriptorImpl
978 : : {
979 : : const int m_threshold;
980 : : const bool m_sorted;
981 : : protected:
982 : 1695 : std::string ToStringExtra() const override { return strprintf("%i", m_threshold); }
983 : 18713 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override {
984 [ + + ]: 18713 : if (m_sorted) {
985 : 2833 : std::vector<CPubKey> sorted_keys(keys);
986 : 2833 : std::sort(sorted_keys.begin(), sorted_keys.end());
987 [ + - + - ]: 5666 : return Vector(GetScriptForMultisig(m_threshold, sorted_keys));
988 : 2833 : }
989 [ + - ]: 31760 : return Vector(GetScriptForMultisig(m_threshold, keys));
990 : : }
991 : : public:
992 [ + + + - ]: 1868 : 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) {}
993 : 7 : bool IsSingleType() const final { return true; }
994 : :
995 : 234 : std::optional<int64_t> ScriptSize() const override {
996 : 234 : const auto n_keys = m_pubkey_args.size();
997 : 731 : auto op = [](int64_t acc, const std::unique_ptr<PubkeyProvider>& pk) { return acc + 1 + pk->GetSize();};
998 : 234 : const auto pubkeys_size{std::accumulate(m_pubkey_args.begin(), m_pubkey_args.end(), int64_t{0}, op)};
999 [ - + + - ]: 468 : return 1 + BuildScript(n_keys).size() + BuildScript(m_threshold).size() + pubkeys_size;
1000 : : }
1001 : :
1002 : 241 : std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
1003 [ + + ]: 227 : const auto sig_size = use_max_sig ? 72 : 71;
1004 : 241 : return (1 + (1 + sig_size) * m_threshold);
1005 : : }
1006 : :
1007 : 14 : std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
1008 [ + + ]: 14 : return *MaxSatSize(use_max_sig) * WITNESS_SCALE_FACTOR;
1009 : : }
1010 : :
1011 : 219 : std::optional<int64_t> MaxSatisfactionElems() const override { return 1 + m_threshold; }
1012 : :
1013 : 0 : std::unique_ptr<DescriptorImpl> Clone() const override
1014 : : {
1015 : 0 : std::vector<std::unique_ptr<PubkeyProvider>> providers;
1016 [ # # ]: 0 : providers.reserve(m_pubkey_args.size());
1017 [ # # ]: 0 : std::transform(m_pubkey_args.begin(), m_pubkey_args.end(), providers.begin(), [](const std::unique_ptr<PubkeyProvider>& p) { return p->Clone(); });
1018 [ # # # # ]: 0 : return std::make_unique<MultisigDescriptor>(m_threshold, std::move(providers), m_sorted);
1019 : 0 : }
1020 : : };
1021 : :
1022 : : /** A parsed (sorted)multi_a(...) descriptor. Always uses x-only pubkeys. */
1023 : : class MultiADescriptor final : public DescriptorImpl
1024 : : {
1025 : : const int m_threshold;
1026 : : const bool m_sorted;
1027 : : protected:
1028 : 798 : std::string ToStringExtra() const override { return strprintf("%i", m_threshold); }
1029 : 6950 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript>, FlatSigningProvider&) const override {
1030 : 6950 : CScript ret;
1031 : 6950 : std::vector<XOnlyPubKey> xkeys;
1032 [ + - ]: 6950 : xkeys.reserve(keys.size());
1033 [ + - + + ]: 999840 : for (const auto& key : keys) xkeys.emplace_back(key);
1034 [ + + ]: 6950 : if (m_sorted) std::sort(xkeys.begin(), xkeys.end());
1035 [ + - + - ]: 6950 : ret << ToByteVector(xkeys[0]) << OP_CHECKSIG;
1036 [ + + ]: 992890 : for (size_t i = 1; i < keys.size(); ++i) {
1037 [ + - + - ]: 1971880 : ret << ToByteVector(xkeys[i]) << OP_CHECKSIGADD;
1038 : : }
1039 [ + - + - ]: 6950 : ret << m_threshold << OP_NUMEQUAL;
1040 [ + - ]: 6950 : return Vector(std::move(ret));
1041 : 6950 : }
1042 : : public:
1043 [ + + + - ]: 1778 : 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) {}
1044 : 0 : bool IsSingleType() const final { return true; }
1045 : :
1046 : 0 : std::optional<int64_t> ScriptSize() const override {
1047 : 0 : const auto n_keys = m_pubkey_args.size();
1048 [ # # ]: 0 : return (1 + 32 + 1) * n_keys + BuildScript(m_threshold).size() + 1;
1049 : : }
1050 : :
1051 : 0 : std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
1052 : 0 : return (1 + 65) * m_threshold + (m_pubkey_args.size() - m_threshold);
1053 : : }
1054 : :
1055 : 0 : std::optional<int64_t> MaxSatisfactionElems() const override { return m_pubkey_args.size(); }
1056 : :
1057 : 0 : std::unique_ptr<DescriptorImpl> Clone() const override
1058 : : {
1059 : 0 : std::vector<std::unique_ptr<PubkeyProvider>> providers;
1060 [ # # ]: 0 : providers.reserve(m_pubkey_args.size());
1061 [ # # ]: 0 : for (const auto& arg : m_pubkey_args) {
1062 [ # # ]: 0 : providers.push_back(arg->Clone());
1063 : : }
1064 [ # # # # ]: 0 : return std::make_unique<MultiADescriptor>(m_threshold, std::move(providers), m_sorted);
1065 : 0 : }
1066 : : };
1067 : :
1068 : : /** A parsed sh(...) descriptor. */
1069 : : class SHDescriptor final : public DescriptorImpl
1070 : : {
1071 : : protected:
1072 : 118011 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, std::span<const CScript> scripts, FlatSigningProvider& out) const override
1073 : : {
1074 [ + - + - ]: 236022 : auto ret = Vector(GetScriptForDestination(ScriptHash(scripts[0])));
1075 [ + - + - : 118011 : if (ret.size()) out.scripts.emplace(CScriptID(scripts[0]), scripts[0]);
+ - ]
1076 : 118011 : return ret;
1077 : 0 : }
1078 : :
1079 [ + + ]: 24123 : bool IsSegwit() const { return m_subdescriptor_args[0]->GetOutputType() == OutputType::BECH32; }
1080 : :
1081 : : public:
1082 [ + - ]: 37963 : SHDescriptor(std::unique_ptr<DescriptorImpl> desc) : DescriptorImpl({}, std::move(desc), "sh") {}
1083 : :
1084 : 14431 : std::optional<OutputType> GetOutputType() const override
1085 : : {
1086 [ - + ]: 14431 : assert(m_subdescriptor_args.size() == 1);
1087 [ + + ]: 14431 : if (IsSegwit()) return OutputType::P2SH_SEGWIT;
1088 : 195 : return OutputType::LEGACY;
1089 : : }
1090 : 1567 : bool IsSingleType() const final { return true; }
1091 : :
1092 : 24 : std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 20 + 1; }
1093 : :
1094 : 9692 : std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
1095 [ + - ]: 9692 : if (const auto sat_size = m_subdescriptor_args[0]->MaxSatSize(use_max_sig)) {
1096 [ + - ]: 9692 : if (const auto subscript_size = m_subdescriptor_args[0]->ScriptSize()) {
1097 : : // The subscript is never witness data.
1098 : 9692 : const auto subscript_weight = (1 + *subscript_size) * WITNESS_SCALE_FACTOR;
1099 : : // The weight depends on whether the inner descriptor is satisfied using the witness stack.
1100 [ + + ]: 9692 : if (IsSegwit()) return subscript_weight + *sat_size;
1101 : 58 : return subscript_weight + *sat_size * WITNESS_SCALE_FACTOR;
1102 : : }
1103 : : }
1104 : 0 : return {};
1105 : : }
1106 : :
1107 : 9668 : std::optional<int64_t> MaxSatisfactionElems() const override {
1108 [ + - ]: 9668 : if (const auto sub_elems = m_subdescriptor_args[0]->MaxSatisfactionElems()) return 1 + *sub_elems;
1109 : 0 : return {};
1110 : : }
1111 : :
1112 : 0 : std::unique_ptr<DescriptorImpl> Clone() const override
1113 : : {
1114 [ # # # # ]: 0 : return std::make_unique<SHDescriptor>(m_subdescriptor_args.at(0)->Clone());
1115 : : }
1116 : : };
1117 : :
1118 : : /** A parsed wsh(...) descriptor. */
1119 : : class WSHDescriptor final : public DescriptorImpl
1120 : : {
1121 : : protected:
1122 : 17111 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, std::span<const CScript> scripts, FlatSigningProvider& out) const override
1123 : : {
1124 [ + - + - ]: 34222 : auto ret = Vector(GetScriptForDestination(WitnessV0ScriptHash(scripts[0])));
1125 [ + - + - : 17111 : if (ret.size()) out.scripts.emplace(CScriptID(scripts[0]), scripts[0]);
+ - ]
1126 : 17111 : return ret;
1127 : 0 : }
1128 : : public:
1129 [ + - ]: 1105 : WSHDescriptor(std::unique_ptr<DescriptorImpl> desc) : DescriptorImpl({}, std::move(desc), "wsh") {}
1130 : 921 : std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32; }
1131 : 410 : bool IsSingleType() const final { return true; }
1132 : :
1133 : 84 : std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
1134 : :
1135 : 406 : std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
1136 [ + - ]: 406 : if (const auto sat_size = m_subdescriptor_args[0]->MaxSatSize(use_max_sig)) {
1137 [ + - ]: 406 : if (const auto subscript_size = m_subdescriptor_args[0]->ScriptSize()) {
1138 [ + + ]: 473 : return GetSizeOfCompactSize(*subscript_size) + *subscript_size + *sat_size;
1139 : : }
1140 : : }
1141 : 0 : return {};
1142 : : }
1143 : :
1144 : 340 : std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
1145 : 340 : return MaxSatSize(use_max_sig);
1146 : : }
1147 : :
1148 : 380 : std::optional<int64_t> MaxSatisfactionElems() const override {
1149 [ + - ]: 380 : if (const auto sub_elems = m_subdescriptor_args[0]->MaxSatisfactionElems()) return 1 + *sub_elems;
1150 : 0 : return {};
1151 : : }
1152 : :
1153 : 0 : std::unique_ptr<DescriptorImpl> Clone() const override
1154 : : {
1155 [ # # # # ]: 0 : return std::make_unique<WSHDescriptor>(m_subdescriptor_args.at(0)->Clone());
1156 : : }
1157 : : };
1158 : :
1159 : : /** A parsed tr(...) descriptor. */
1160 : : class TRDescriptor final : public DescriptorImpl
1161 : : {
1162 : : std::vector<int> m_depths;
1163 : : protected:
1164 : 128161 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript> scripts, FlatSigningProvider& out) const override
1165 : : {
1166 [ - + ]: 128161 : TaprootBuilder builder;
1167 [ - + ]: 128161 : assert(m_depths.size() == scripts.size());
1168 [ + + ]: 162602 : for (size_t pos = 0; pos < m_depths.size(); ++pos) {
1169 [ + + + - ]: 68882 : builder.Add(m_depths[pos], scripts[pos], TAPROOT_LEAF_TAPSCRIPT);
1170 : : }
1171 [ - + ]: 128161 : if (!builder.IsComplete()) return {};
1172 [ - + ]: 128161 : assert(keys.size() == 1);
1173 : 128161 : XOnlyPubKey xpk(keys[0]);
1174 [ + - - + ]: 128161 : if (!xpk.IsFullyValid()) return {};
1175 [ + - ]: 128161 : builder.Finalize(xpk);
1176 [ + - ]: 128161 : WitnessV1Taproot output = builder.GetOutput();
1177 [ + - + - ]: 128161 : out.tr_trees[output] = builder;
1178 [ + - + - ]: 128161 : out.pubkeys.emplace(keys[0].GetID(), keys[0]);
1179 [ + - + - ]: 256322 : return Vector(GetScriptForDestination(output));
1180 : 128161 : }
1181 : 7269 : bool ToStringSubScriptHelper(const SigningProvider* arg, std::string& ret, const StringType type, const DescriptorCache* cache = nullptr) const override
1182 : : {
1183 [ + + ]: 7269 : if (m_depths.empty()) return true;
1184 : 1692 : std::vector<bool> path;
1185 [ + + ]: 5919 : for (size_t pos = 0; pos < m_depths.size(); ++pos) {
1186 [ + + + - ]: 4227 : if (pos) ret += ',';
1187 [ + + ]: 8454 : while ((int)path.size() <= m_depths[pos]) {
1188 [ + + + - ]: 4227 : if (path.size()) ret += '{';
1189 [ + - ]: 4227 : path.push_back(false);
1190 : : }
1191 [ + - ]: 4227 : std::string tmp;
1192 [ + - - + ]: 4227 : if (!m_subdescriptor_args[pos]->ToStringHelper(arg, tmp, type, cache)) return false;
1193 [ + - ]: 4227 : ret += tmp;
1194 [ + - + + ]: 6762 : while (!path.empty() && path.back()) {
1195 [ + - + - ]: 2535 : if (path.size() > 1) ret += '}';
1196 : 2535 : path.pop_back();
1197 : : }
1198 [ + - ]: 4227 : if (!path.empty()) path.back() = true;
1199 : 4227 : }
1200 : : return true;
1201 : 1692 : }
1202 : : public:
1203 : 6751 : TRDescriptor(std::unique_ptr<PubkeyProvider> internal_key, std::vector<std::unique_ptr<DescriptorImpl>> descs, std::vector<int> depths) :
1204 [ + - + - : 6751 : DescriptorImpl(Vector(std::move(internal_key)), std::move(descs), "tr"), m_depths(std::move(depths))
- + ]
1205 : : {
1206 [ - + ]: 6751 : assert(m_subdescriptor_args.size() == m_depths.size());
1207 : 6751 : }
1208 : 9434 : std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32M; }
1209 : 1642 : bool IsSingleType() const final { return true; }
1210 : :
1211 : 21 : std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
1212 : :
1213 : 4387 : std::optional<int64_t> MaxSatisfactionWeight(bool) const override {
1214 : : // FIXME: We assume keypath spend, which can lead to very large underestimations.
1215 : 4387 : return 1 + 65;
1216 : : }
1217 : :
1218 : 4366 : std::optional<int64_t> MaxSatisfactionElems() const override {
1219 : : // FIXME: See above, we assume keypath spend.
1220 : 4366 : return 1;
1221 : : }
1222 : :
1223 : 0 : std::unique_ptr<DescriptorImpl> Clone() const override
1224 : : {
1225 : 0 : std::vector<std::unique_ptr<DescriptorImpl>> subdescs;
1226 [ # # ]: 0 : subdescs.reserve(m_subdescriptor_args.size());
1227 [ # # ]: 0 : std::transform(m_subdescriptor_args.begin(), m_subdescriptor_args.end(), subdescs.begin(), [](const std::unique_ptr<DescriptorImpl>& d) { return d->Clone(); });
1228 [ # # # # : 0 : return std::make_unique<TRDescriptor>(m_pubkey_args.at(0)->Clone(), std::move(subdescs), m_depths);
# # # # ]
1229 : 0 : }
1230 : : };
1231 : :
1232 : : /* We instantiate Miniscript here with a simple integer as key type.
1233 : : * The value of these key integers are an index in the
1234 : : * DescriptorImpl::m_pubkey_args vector.
1235 : : */
1236 : :
1237 : : /**
1238 : : * The context for converting a Miniscript descriptor into a Script.
1239 : : */
1240 : : class ScriptMaker {
1241 : : //! Keys contained in the Miniscript (the evaluation of DescriptorImpl::m_pubkey_args).
1242 : : const std::vector<CPubKey>& m_keys;
1243 : : //! The script context we're operating within (Tapscript or P2WSH).
1244 : : const miniscript::MiniscriptContext m_script_ctx;
1245 : :
1246 : : //! Get the ripemd160(sha256()) hash of this key.
1247 : : //! Any key that is valid in a descriptor serializes as 32 bytes within a Tapscript context. So we
1248 : : //! must not hash the sign-bit byte in this case.
1249 : 450 : uint160 GetHash160(uint32_t key) const {
1250 [ + + ]: 450 : if (miniscript::IsTapscript(m_script_ctx)) {
1251 : 179 : return Hash160(XOnlyPubKey{m_keys[key]});
1252 : : }
1253 : 271 : return m_keys[key].GetID();
1254 : : }
1255 : :
1256 : : public:
1257 : 1293 : ScriptMaker(const std::vector<CPubKey>& keys LIFETIMEBOUND, const miniscript::MiniscriptContext script_ctx) : m_keys(keys), m_script_ctx{script_ctx} {}
1258 : :
1259 : 2654 : std::vector<unsigned char> ToPKBytes(uint32_t key) const {
1260 : : // In Tapscript keys always serialize as x-only, whether an x-only key was used in the descriptor or not.
1261 [ + + ]: 2654 : if (!miniscript::IsTapscript(m_script_ctx)) {
1262 : 1901 : return {m_keys[key].begin(), m_keys[key].end()};
1263 : : }
1264 : 753 : const XOnlyPubKey xonly_pubkey{m_keys[key]};
1265 : 753 : return {xonly_pubkey.begin(), xonly_pubkey.end()};
1266 : : }
1267 : :
1268 : 450 : std::vector<unsigned char> ToPKHBytes(uint32_t key) const {
1269 : 450 : auto id = GetHash160(key);
1270 : 450 : return {id.begin(), id.end()};
1271 : : }
1272 : : };
1273 : :
1274 : : /**
1275 : : * The context for converting a Miniscript descriptor to its textual form.
1276 : : */
1277 : : class StringMaker {
1278 : : //! To convert private keys for private descriptors.
1279 : : const SigningProvider* m_arg;
1280 : : //! Keys contained in the Miniscript (a reference to DescriptorImpl::m_pubkey_args).
1281 : : const std::vector<std::unique_ptr<PubkeyProvider>>& m_pubkeys;
1282 : : //! Whether to serialize keys as private or public.
1283 : : bool m_private;
1284 : :
1285 : : public:
1286 : 816 : StringMaker(const SigningProvider* arg LIFETIMEBOUND, const std::vector<std::unique_ptr<PubkeyProvider>>& pubkeys LIFETIMEBOUND, bool priv)
1287 : 816 : : m_arg(arg), m_pubkeys(pubkeys), m_private(priv) {}
1288 : :
1289 : 4515 : std::optional<std::string> ToString(uint32_t key) const
1290 : : {
1291 [ + + ]: 4515 : std::string ret;
1292 [ + + ]: 4515 : if (m_private) {
1293 [ + - + + ]: 133 : if (!m_pubkeys[key]->ToPrivateString(*m_arg, ret)) return {};
1294 : : } else {
1295 [ + - ]: 4382 : ret = m_pubkeys[key]->ToString();
1296 : : }
1297 : 4482 : return ret;
1298 : 4515 : }
1299 : : };
1300 : :
1301 : : class MiniscriptDescriptor final : public DescriptorImpl
1302 : : {
1303 : : private:
1304 : : miniscript::NodeRef<uint32_t> m_node;
1305 : :
1306 : : protected:
1307 : 1293 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript> scripts,
1308 : : FlatSigningProvider& provider) const override
1309 : : {
1310 : 1293 : const auto script_ctx{m_node->GetMsCtx()};
1311 [ + + ]: 4397 : for (const auto& key : keys) {
1312 [ + + ]: 3104 : if (miniscript::IsTapscript(script_ctx)) {
1313 : 932 : provider.pubkeys.emplace(Hash160(XOnlyPubKey{key}), key);
1314 : : } else {
1315 : 2172 : provider.pubkeys.emplace(key.GetID(), key);
1316 : : }
1317 : : }
1318 [ + - ]: 2586 : return Vector(m_node->ToScript(ScriptMaker(keys, script_ctx)));
1319 : : }
1320 : :
1321 : : public:
1322 : 693 : MiniscriptDescriptor(std::vector<std::unique_ptr<PubkeyProvider>> providers, miniscript::NodeRef<uint32_t> node)
1323 [ + - ]: 693 : : DescriptorImpl(std::move(providers), "?"), m_node(std::move(node)) {}
1324 : :
1325 : 816 : bool ToStringHelper(const SigningProvider* arg, std::string& out, const StringType type,
1326 : : const DescriptorCache* cache = nullptr) const override
1327 : : {
1328 [ + + ]: 816 : if (const auto res = m_node->ToString(StringMaker(arg, m_pubkey_args, type == StringType::PRIVATE))) {
1329 [ + - ]: 783 : out = *res;
1330 : 783 : return true;
1331 : 783 : }
1332 : 33 : return false;
1333 : : }
1334 : :
1335 : 352 : bool IsSolvable() const override { return true; }
1336 : 0 : bool IsSingleType() const final { return true; }
1337 : :
1338 : 171 : std::optional<int64_t> ScriptSize() const override { return m_node->ScriptSize(); }
1339 : :
1340 : 171 : std::optional<int64_t> MaxSatSize(bool) const override {
1341 : : // For Miniscript we always assume high-R ECDSA signatures.
1342 [ + - ]: 171 : return m_node->GetWitnessSize();
1343 : : }
1344 : :
1345 : 155 : std::optional<int64_t> MaxSatisfactionElems() const override {
1346 [ + - ]: 155 : return m_node->GetStackSize();
1347 : : }
1348 : :
1349 : 5 : std::unique_ptr<DescriptorImpl> Clone() const override
1350 : : {
1351 : 5 : std::vector<std::unique_ptr<PubkeyProvider>> providers;
1352 [ + - ]: 5 : providers.reserve(m_pubkey_args.size());
1353 [ + + ]: 10 : for (const auto& arg : m_pubkey_args) {
1354 [ + - ]: 10 : providers.push_back(arg->Clone());
1355 : : }
1356 [ + - + - : 10 : return std::make_unique<MiniscriptDescriptor>(std::move(providers), m_node->Clone());
- + ]
1357 : 5 : }
1358 : : };
1359 : :
1360 : : /** A parsed rawtr(...) descriptor. */
1361 : : class RawTRDescriptor final : public DescriptorImpl
1362 : : {
1363 : : protected:
1364 : 1088 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, std::span<const CScript> scripts, FlatSigningProvider& out) const override
1365 : : {
1366 [ - + ]: 1088 : assert(keys.size() == 1);
1367 : 1088 : XOnlyPubKey xpk(keys[0]);
1368 [ - + ]: 1088 : if (!xpk.IsFullyValid()) return {};
1369 [ + - ]: 1088 : WitnessV1Taproot output{xpk};
1370 [ + - + - ]: 2176 : return Vector(GetScriptForDestination(output));
1371 : : }
1372 : : public:
1373 [ + - + - ]: 15556 : RawTRDescriptor(std::unique_ptr<PubkeyProvider> output_key) : DescriptorImpl(Vector(std::move(output_key)), "rawtr") {}
1374 : 179 : std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32M; }
1375 : 62 : bool IsSingleType() const final { return true; }
1376 : :
1377 : 3 : std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
1378 : :
1379 : 120 : std::optional<int64_t> MaxSatisfactionWeight(bool) const override {
1380 : : // We can't know whether there is a script path, so assume key path spend.
1381 : 120 : return 1 + 65;
1382 : : }
1383 : :
1384 : 117 : std::optional<int64_t> MaxSatisfactionElems() const override {
1385 : : // See above, we assume keypath spend.
1386 : 117 : return 1;
1387 : : }
1388 : :
1389 : 0 : std::unique_ptr<DescriptorImpl> Clone() const override
1390 : : {
1391 [ # # # # ]: 0 : return std::make_unique<RawTRDescriptor>(m_pubkey_args.at(0)->Clone());
1392 : : }
1393 : : };
1394 : :
1395 : : ////////////////////////////////////////////////////////////////////////////
1396 : : // Parser //
1397 : : ////////////////////////////////////////////////////////////////////////////
1398 : :
1399 : : enum class ParseScriptContext {
1400 : : TOP, //!< Top-level context (script goes directly in scriptPubKey)
1401 : : P2SH, //!< Inside sh() (script becomes P2SH redeemScript)
1402 : : P2WPKH, //!< Inside wpkh() (no script, pubkey only)
1403 : : P2WSH, //!< Inside wsh() (script becomes v0 witness script)
1404 : : P2TR, //!< Inside tr() (either internal key, or BIP342 script leaf)
1405 : : };
1406 : :
1407 : 23325 : std::optional<uint32_t> ParseKeyPathNum(std::span<const char> elem, bool& apostrophe, std::string& error)
1408 : : {
1409 : 23325 : bool hardened = false;
1410 [ + + ]: 23325 : if (elem.size() > 0) {
1411 [ + + ]: 23319 : const char last = elem[elem.size() - 1];
1412 [ + + ]: 23319 : if (last == '\'' || last == 'h') {
1413 : 16819 : elem = elem.first(elem.size() - 1);
1414 : 16819 : hardened = true;
1415 : 16819 : apostrophe = last == '\'';
1416 : : }
1417 : : }
1418 : 23325 : uint32_t p;
1419 [ + - + + ]: 23325 : if (!ParseUInt32(std::string(elem.begin(), elem.end()), &p)) {
1420 [ + - ]: 12 : error = strprintf("Key path value '%s' is not a valid uint32", std::string(elem.begin(), elem.end()));
1421 : 12 : return std::nullopt;
1422 [ + + ]: 23313 : } else if (p > 0x7FFFFFFFUL) {
1423 : 2 : error = strprintf("Key path value %u is out of range", p);
1424 : 2 : return std::nullopt;
1425 : : }
1426 : :
1427 : 23311 : return std::make_optional<uint32_t>(p | (((uint32_t)hardened) << 31));
1428 : : }
1429 : :
1430 : : /**
1431 : : * Parse a key path, being passed a split list of elements (the first element is ignored because it is always the key).
1432 : : *
1433 : : * @param[in] split BIP32 path string, using either ' or h for hardened derivation
1434 : : * @param[out] out Vector of parsed key paths
1435 : : * @param[out] apostrophe only updated if hardened derivation is found
1436 : : * @param[out] error parsing error message
1437 : : * @param[in] allow_multipath Allows the parsed path to use the multipath specifier
1438 : : * @returns false if parsing failed
1439 : : **/
1440 : 11469 : [[nodiscard]] bool ParseKeyPath(const std::vector<std::span<const char>>& split, std::vector<KeyPath>& out, bool& apostrophe, std::string& error, bool allow_multipath)
1441 : : {
1442 : 11469 : KeyPath path;
1443 : 11469 : std::optional<size_t> multipath_segment_index;
1444 : 11469 : std::vector<uint32_t> multipath_values;
1445 : 11469 : std::unordered_set<uint32_t> seen_multipath;
1446 : :
1447 [ + + ]: 34548 : for (size_t i = 1; i < split.size(); ++i) {
1448 [ + - ]: 23103 : const std::span<const char>& elem = split[i];
1449 : :
1450 : : // Check if element contain multipath specifier
1451 [ + - + + : 23103 : if (!elem.empty() && elem.front() == '<' && elem.back() == '>') {
+ + ]
1452 [ + + ]: 160 : if (!allow_multipath) {
1453 [ + - + - ]: 4 : error = strprintf("Key path value '%s' specifies multipath in a section where multipath is not allowed", std::string(elem.begin(), elem.end()));
1454 : 2 : return false;
1455 : : }
1456 [ + + ]: 158 : if (multipath_segment_index) {
1457 [ + - ]: 11469 : error = "Multiple multipath key path specifiers found";
1458 : : return false;
1459 : : }
1460 : :
1461 : : // Parse each possible value
1462 [ + - ]: 156 : std::vector<std::span<const char>> nums = Split(std::span(elem.begin()+1, elem.end()-1), ";");
1463 [ + + ]: 156 : if (nums.size() < 2) {
1464 [ + - ]: 12 : error = "Multipath key path specifiers must have at least two items";
1465 : : return false;
1466 : : }
1467 : :
1468 [ + + ]: 526 : for (const auto& num : nums) {
1469 [ + - ]: 382 : const auto& op_num = ParseKeyPathNum(num, apostrophe, error);
1470 [ + + ]: 382 : if (!op_num) return false;
1471 [ + - + + ]: 376 : auto [_, inserted] = seen_multipath.insert(*op_num);
1472 [ + + ]: 376 : if (!inserted) {
1473 [ + - ]: 2 : error = strprintf("Duplicated key path value %u in multipath specifier", *op_num);
1474 : 2 : return false;
1475 : : }
1476 [ + - ]: 374 : multipath_values.emplace_back(*op_num);
1477 : : }
1478 : :
1479 [ + - ]: 144 : path.emplace_back(); // Placeholder for multipath segment
1480 : 144 : multipath_segment_index = path.size()-1;
1481 : 156 : } else {
1482 [ + - ]: 22943 : const auto& op_num = ParseKeyPathNum(elem, apostrophe, error);
1483 [ + + ]: 22943 : if (!op_num) return false;
1484 [ + - ]: 22935 : path.emplace_back(*op_num);
1485 : : }
1486 : : }
1487 : :
1488 [ + + ]: 11445 : if (!multipath_segment_index) {
1489 [ + - ]: 11303 : out.emplace_back(std::move(path));
1490 : : } else {
1491 : : // Replace the multipath placeholder with each value while generating paths
1492 [ + + ]: 504 : for (size_t i = 0; i < multipath_values.size(); i++) {
1493 [ + - ]: 362 : KeyPath branch_path = path;
1494 [ + - ]: 362 : branch_path[*multipath_segment_index] = multipath_values[i];
1495 [ + - ]: 362 : out.emplace_back(std::move(branch_path));
1496 : 362 : }
1497 : : }
1498 : : return true;
1499 : 11469 : }
1500 : :
1501 : : /** Parse a public key that excludes origin information. */
1502 : 26770 : 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)
1503 : : {
1504 : 26770 : std::vector<std::unique_ptr<PubkeyProvider>> ret;
1505 : 26770 : bool permit_uncompressed = ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH;
1506 [ + - ]: 26770 : auto split = Split(sp, '/');
1507 [ + - + + ]: 53540 : std::string str(split[0].begin(), split[0].end());
1508 [ + + ]: 26770 : if (str.size() == 0) {
1509 [ + - ]: 2 : error = "No key provided";
1510 : 2 : return {};
1511 : : }
1512 [ + + + + ]: 26768 : if (IsSpace(str.front()) || IsSpace(str.back())) {
1513 [ + - ]: 10 : error = strprintf("Key '%s' is invalid due to whitespace", str);
1514 : 10 : return {};
1515 : : }
1516 [ + + ]: 26758 : if (split.size() == 1) {
1517 [ + - + + ]: 20152 : if (IsHex(str)) {
1518 [ + - ]: 19621 : std::vector<unsigned char> data = ParseHex(str);
1519 : 19621 : CPubKey pubkey(data);
1520 [ + + + + ]: 19621 : if (pubkey.IsValid() && !pubkey.IsValidNonHybrid()) {
1521 [ + - ]: 4 : error = "Hybrid public keys are not allowed";
1522 : 4 : return {};
1523 : : }
1524 [ + - + + ]: 19617 : if (pubkey.IsFullyValid()) {
1525 [ + + + + ]: 1079 : if (permit_uncompressed || pubkey.IsCompressed()) {
1526 [ + - + - ]: 1075 : ret.emplace_back(std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, false));
1527 : 1075 : return ret;
1528 : : } else {
1529 [ + - ]: 4 : error = "Uncompressed keys are not allowed";
1530 : 4 : return {};
1531 : : }
1532 [ + - + + ]: 18538 : } else if (data.size() == 32 && ctx == ParseScriptContext::P2TR) {
1533 : 18537 : unsigned char fullkey[33] = {0x02};
1534 : 18537 : std::copy(data.begin(), data.end(), fullkey + 1);
1535 : 18537 : pubkey.Set(std::begin(fullkey), std::end(fullkey));
1536 [ + - + - ]: 18537 : if (pubkey.IsFullyValid()) {
1537 [ + - + - ]: 18537 : ret.emplace_back(std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, true));
1538 : 18537 : return ret;
1539 : : }
1540 : : }
1541 [ + - ]: 1 : error = strprintf("Pubkey '%s' is invalid", str);
1542 : 1 : return {};
1543 : 19621 : }
1544 [ + - ]: 531 : CKey key = DecodeSecret(str);
1545 [ + + ]: 531 : if (key.IsValid()) {
1546 [ + + + + ]: 434 : if (permit_uncompressed || key.IsCompressed()) {
1547 [ + - ]: 429 : CPubKey pubkey = key.GetPubKey();
1548 [ + - + - ]: 429 : out.keys.emplace(pubkey.GetID(), key);
1549 [ + - + - ]: 429 : ret.emplace_back(std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, ctx == ParseScriptContext::P2TR));
1550 : 429 : return ret;
1551 : : } else {
1552 [ + - ]: 5 : error = "Uncompressed keys are not allowed";
1553 : 5 : return {};
1554 : : }
1555 : : }
1556 : 531 : }
1557 [ + - ]: 6703 : CExtKey extkey = DecodeExtKey(str);
1558 [ + - ]: 6703 : CExtPubKey extpubkey = DecodeExtPubKey(str);
1559 [ + + + + ]: 6703 : if (!extkey.key.IsValid() && !extpubkey.pubkey.IsValid()) {
1560 [ + - ]: 3 : error = strprintf("key '%s' is not valid", str);
1561 : 3 : return {};
1562 : : }
1563 : 6700 : std::vector<KeyPath> paths;
1564 : 6700 : DeriveType type = DeriveType::NO;
1565 [ + + ]: 6700 : if (std::ranges::equal(split.back(), std::span{"*"}.first(1))) {
1566 : 6348 : split.pop_back();
1567 : 6348 : type = DeriveType::UNHARDENED;
1568 [ + + + + ]: 352 : } else if (std::ranges::equal(split.back(), std::span{"*'"}.first(2)) || std::ranges::equal(split.back(), std::span{"*h"}.first(2))) {
1569 : 147 : apostrophe = std::ranges::equal(split.back(), std::span{"*'"}.first(2));
1570 : 147 : split.pop_back();
1571 : 147 : type = DeriveType::HARDENED;
1572 : : }
1573 [ + - + + ]: 6700 : if (!ParseKeyPath(split, paths, apostrophe, error, /*allow_multipath=*/true)) return {};
1574 [ + + ]: 6678 : if (extkey.key.IsValid()) {
1575 [ + - ]: 626 : extpubkey = extkey.Neuter();
1576 [ + - + - ]: 626 : out.keys.emplace(extpubkey.pubkey.GetID(), extkey.key);
1577 : : }
1578 [ + + ]: 13576 : for (auto& path : paths) {
1579 [ + - + - ]: 13796 : ret.emplace_back(std::make_unique<BIP32PubkeyProvider>(key_exp_index, extpubkey, std::move(path), type, apostrophe));
1580 : : }
1581 : 6678 : return ret;
1582 : 40173 : }
1583 : :
1584 : : /** Parse a public key including origin information (if enabled). */
1585 : 26786 : 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)
1586 : : {
1587 : 26786 : std::vector<std::unique_ptr<PubkeyProvider>> ret;
1588 [ + - ]: 26786 : auto origin_split = Split(sp, ']');
1589 [ + + ]: 26786 : if (origin_split.size() > 2) {
1590 [ + - ]: 4 : error = "Multiple ']' characters found for a single pubkey";
1591 : 4 : return {};
1592 : : }
1593 : : // This is set if either the origin or path suffix contains a hardened derivation.
1594 : 26782 : bool apostrophe = false;
1595 [ + + ]: 26782 : if (origin_split.size() == 1) {
1596 [ + - ]: 22003 : return ParsePubkeyInner(key_exp_index, origin_split[0], ctx, out, apostrophe, error);
1597 : : }
1598 [ + - + + ]: 4779 : if (origin_split[0].empty() || origin_split[0][0] != '[') {
1599 : 6 : error = strprintf("Key origin start '[ character expected but not found, got '%c' instead",
1600 [ + - + - ]: 2 : origin_split[0].empty() ? /** empty, implies split char */ ']' : origin_split[0][0]);
1601 : 2 : return {};
1602 : : }
1603 [ + - ]: 4777 : auto slash_split = Split(origin_split[0].subspan(1), '/');
1604 [ + + ]: 4777 : if (slash_split[0].size() != 8) {
1605 [ + - ]: 6 : error = strprintf("Fingerprint is not 4 bytes (%u characters instead of 8 characters)", slash_split[0].size());
1606 : 6 : return {};
1607 : : }
1608 [ + - + - ]: 9542 : std::string fpr_hex = std::string(slash_split[0].begin(), slash_split[0].end());
1609 [ + - + + ]: 4771 : if (!IsHex(fpr_hex)) {
1610 [ + - ]: 2 : error = strprintf("Fingerprint '%s' is not hex", fpr_hex);
1611 : 2 : return {};
1612 : : }
1613 [ + - ]: 4769 : auto fpr_bytes = ParseHex(fpr_hex);
1614 [ - + ]: 4769 : KeyOriginInfo info;
1615 : 4769 : static_assert(sizeof(info.fingerprint) == 4, "Fingerprint must be 4 bytes");
1616 [ - + ]: 4769 : assert(fpr_bytes.size() == 4);
1617 : 4769 : std::copy(fpr_bytes.begin(), fpr_bytes.end(), info.fingerprint);
1618 : 4769 : std::vector<KeyPath> path;
1619 [ + - + + ]: 4769 : if (!ParseKeyPath(slash_split, path, apostrophe, error, /*allow_multipath=*/false)) return {};
1620 [ + - + - ]: 4767 : info.path = path.at(0);
1621 [ + - ]: 4767 : auto providers = ParsePubkeyInner(key_exp_index, origin_split[1], ctx, out, apostrophe, error);
1622 [ + + ]: 4767 : if (providers.empty()) return {};
1623 [ + - ]: 4765 : ret.reserve(providers.size());
1624 [ + + ]: 9545 : for (auto& prov : providers) {
1625 [ + - + - ]: 9560 : ret.emplace_back(std::make_unique<OriginPubkeyProvider>(key_exp_index, info, std::move(prov), apostrophe));
1626 : : }
1627 : 4765 : return ret;
1628 : 41103 : }
1629 : :
1630 : 316877 : std::unique_ptr<PubkeyProvider> InferPubkey(const CPubKey& pubkey, ParseScriptContext ctx, const SigningProvider& provider)
1631 : : {
1632 : : // Key cannot be hybrid
1633 [ + + ]: 316877 : if (!pubkey.IsValidNonHybrid()) {
1634 : 7 : return nullptr;
1635 : : }
1636 : : // Uncompressed is only allowed in TOP and P2SH contexts
1637 [ + + + + ]: 316870 : if (ctx != ParseScriptContext::TOP && ctx != ParseScriptContext::P2SH && !pubkey.IsCompressed()) {
1638 : 5 : return nullptr;
1639 : : }
1640 : 316865 : std::unique_ptr<PubkeyProvider> key_provider = std::make_unique<ConstPubkeyProvider>(0, pubkey, false);
1641 [ + - ]: 316865 : KeyOriginInfo info;
1642 [ + - + - : 316865 : if (provider.GetKeyOrigin(pubkey.GetID(), info)) {
+ + ]
1643 [ + - - + ]: 315709 : return std::make_unique<OriginPubkeyProvider>(0, std::move(info), std::move(key_provider), /*apostrophe=*/false);
1644 : : }
1645 : 1156 : return key_provider;
1646 : 316865 : }
1647 : :
1648 : 129352 : std::unique_ptr<PubkeyProvider> InferXOnlyPubkey(const XOnlyPubKey& xkey, ParseScriptContext ctx, const SigningProvider& provider)
1649 : : {
1650 : 129352 : CPubKey pubkey{xkey.GetEvenCorrespondingCPubKey()};
1651 : 129352 : std::unique_ptr<PubkeyProvider> key_provider = std::make_unique<ConstPubkeyProvider>(0, pubkey, true);
1652 [ + - ]: 129352 : KeyOriginInfo info;
1653 [ + - + + ]: 129352 : if (provider.GetKeyOriginByXOnly(xkey, info)) {
1654 [ + - - + ]: 113979 : return std::make_unique<OriginPubkeyProvider>(0, std::move(info), std::move(key_provider), /*apostrophe=*/false);
1655 : : }
1656 : 15373 : return key_provider;
1657 : 129352 : }
1658 : :
1659 : : /**
1660 : : * The context for parsing a Miniscript descriptor (either from Script or from its textual representation).
1661 : : */
1662 : 1052 : struct KeyParser {
1663 : : //! The Key type is an index in DescriptorImpl::m_pubkey_args
1664 : : using Key = uint32_t;
1665 : : //! Must not be nullptr if parsing from string.
1666 : : FlatSigningProvider* m_out;
1667 : : //! Must not be nullptr if parsing from Script.
1668 : : const SigningProvider* m_in;
1669 : : //! List of multipath expanded keys contained in the Miniscript.
1670 : : mutable std::vector<std::vector<std::unique_ptr<PubkeyProvider>>> m_keys;
1671 : : //! Used to detect key parsing errors within a Miniscript.
1672 : : mutable std::string m_key_parsing_error;
1673 : : //! The script context we're operating within (Tapscript or P2WSH).
1674 : : const miniscript::MiniscriptContext m_script_ctx;
1675 : : //! The number of keys that were parsed before starting to parse this Miniscript descriptor.
1676 : : uint32_t m_offset;
1677 : :
1678 : 1052 : KeyParser(FlatSigningProvider* out LIFETIMEBOUND, const SigningProvider* in LIFETIMEBOUND,
1679 : : miniscript::MiniscriptContext ctx, uint32_t offset = 0)
1680 : 1052 : : m_out(out), m_in(in), m_script_ctx(ctx), m_offset(offset) {}
1681 : :
1682 : 4636 : bool KeyCompare(const Key& a, const Key& b) const {
1683 : 4636 : return *m_keys.at(a).at(0) < *m_keys.at(b).at(0);
1684 : : }
1685 : :
1686 : 1907 : ParseScriptContext ParseContext() const {
1687 [ + - + ]: 1907 : switch (m_script_ctx) {
1688 : : case miniscript::MiniscriptContext::P2WSH: return ParseScriptContext::P2WSH;
1689 : 458 : case miniscript::MiniscriptContext::TAPSCRIPT: return ParseScriptContext::P2TR;
1690 : : }
1691 : 0 : assert(false);
1692 : : }
1693 : :
1694 : 418 : template<typename I> std::optional<Key> FromString(I begin, I end) const
1695 : : {
1696 [ - + ]: 418 : assert(m_out);
1697 : 418 : Key key = m_keys.size();
1698 : 418 : auto pk = ParsePubkey(m_offset + key, {&*begin, &*end}, ParseContext(), *m_out, m_key_parsing_error);
1699 [ + + ]: 418 : if (pk.empty()) return {};
1700 [ + - ]: 416 : m_keys.emplace_back(std::move(pk));
1701 : 416 : return key;
1702 : 418 : }
1703 : :
1704 : 30 : std::optional<std::string> ToString(const Key& key) const
1705 : : {
1706 : 30 : return m_keys.at(key).at(0)->ToString();
1707 : : }
1708 : :
1709 : 1180 : template<typename I> std::optional<Key> FromPKBytes(I begin, I end) const
1710 : : {
1711 [ - + ]: 1180 : assert(m_in);
1712 : 1180 : Key key = m_keys.size();
1713 [ + + + - ]: 1180 : if (miniscript::IsTapscript(m_script_ctx) && end - begin == 32) {
1714 : 222 : XOnlyPubKey pubkey;
1715 : 222 : std::copy(begin, end, pubkey.begin());
1716 [ + - ]: 222 : if (auto pubkey_provider = InferXOnlyPubkey(pubkey, ParseContext(), *m_in)) {
1717 [ + - ]: 222 : m_keys.emplace_back();
1718 [ + - ]: 222 : m_keys.back().push_back(std::move(pubkey_provider));
1719 : 222 : return key;
1720 : : }
1721 [ + - ]: 958 : } else if (!miniscript::IsTapscript(m_script_ctx)) {
1722 : 958 : CPubKey pubkey(begin, end);
1723 [ + + ]: 958 : if (auto pubkey_provider = InferPubkey(pubkey, ParseContext(), *m_in)) {
1724 [ + - ]: 956 : m_keys.emplace_back();
1725 [ + - ]: 956 : m_keys.back().push_back(std::move(pubkey_provider));
1726 : 956 : return key;
1727 : : }
1728 : : }
1729 : 2 : return {};
1730 : : }
1731 : :
1732 [ - + ]: 309 : template<typename I> std::optional<Key> FromPKHBytes(I begin, I end) const
1733 : : {
1734 [ - + ]: 309 : assert(end - begin == 20);
1735 [ - + ]: 309 : assert(m_in);
1736 : 309 : uint160 hash;
1737 : 309 : std::copy(begin, end, hash.begin());
1738 : 309 : CKeyID keyid(hash);
1739 : 309 : CPubKey pubkey;
1740 [ + - ]: 309 : if (m_in->GetPubKey(keyid, pubkey)) {
1741 [ + + ]: 309 : if (auto pubkey_provider = InferPubkey(pubkey, ParseContext(), *m_in)) {
1742 [ + - ]: 307 : Key key = m_keys.size();
1743 [ + - ]: 307 : m_keys.emplace_back();
1744 [ + - ]: 307 : m_keys.back().push_back(std::move(pubkey_provider));
1745 : 307 : return key;
1746 : : }
1747 : : }
1748 : 2 : return {};
1749 : : }
1750 : :
1751 : 997040 : miniscript::MiniscriptContext MsContext() const {
1752 [ + - + - : 997040 : return m_script_ctx;
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
- - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- - - + -
+ - + - +
- + - + -
+ - + - +
- + - - -
+ - + - -
- - - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + + +
- + - ]
1753 : : }
1754 : : };
1755 : :
1756 : : /** Parse a script in a particular context. */
1757 : : // NOLINTNEXTLINE(misc-no-recursion)
1758 : 11988 : std::vector<std::unique_ptr<DescriptorImpl>> ParseScript(uint32_t& key_exp_index, std::span<const char>& sp, ParseScriptContext ctx, FlatSigningProvider& out, std::string& error)
1759 : : {
1760 : 11988 : using namespace script;
1761 : 11988 : Assume(ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH || ctx == ParseScriptContext::P2TR);
1762 : 11988 : std::vector<std::unique_ptr<DescriptorImpl>> ret;
1763 [ + - ]: 11988 : auto expr = Expr(sp);
1764 [ + - + - : 11988 : if (Func("pk", expr)) {
+ + ]
1765 [ + - ]: 605 : auto pubkeys = ParsePubkey(key_exp_index, expr, ctx, out, error);
1766 [ + + ]: 605 : if (pubkeys.empty()) {
1767 [ + - ]: 8 : error = strprintf("pk(): %s", error);
1768 : 8 : return {};
1769 : : }
1770 : 597 : ++key_exp_index;
1771 [ + + ]: 1277 : for (auto& pubkey : pubkeys) {
1772 [ + - + - ]: 1360 : ret.emplace_back(std::make_unique<PKDescriptor>(std::move(pubkey), ctx == ParseScriptContext::P2TR));
1773 : : }
1774 : 597 : return ret;
1775 : 605 : }
1776 [ + + + - : 22565 : if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH) && Func("pkh", expr)) {
+ - + + +
+ ]
1777 [ + - ]: 1443 : auto pubkeys = ParsePubkey(key_exp_index, expr, ctx, out, error);
1778 [ + + ]: 1443 : if (pubkeys.empty()) {
1779 [ + - ]: 15 : error = strprintf("pkh(): %s", error);
1780 : 15 : return {};
1781 : : }
1782 : 1428 : ++key_exp_index;
1783 [ + + ]: 2876 : for (auto& pubkey : pubkeys) {
1784 [ + - + - ]: 2896 : ret.emplace_back(std::make_unique<PKHDescriptor>(std::move(pubkey)));
1785 : : }
1786 : 1428 : return ret;
1787 : 1443 : }
1788 [ + + + - : 17835 : if (ctx == ParseScriptContext::TOP && Func("combo", expr)) {
+ - + + +
+ ]
1789 [ + - ]: 502 : auto pubkeys = ParsePubkey(key_exp_index, expr, ctx, out, error);
1790 [ + + ]: 502 : if (pubkeys.empty()) {
1791 [ + - ]: 3 : error = strprintf("combo(): %s", error);
1792 : 3 : return {};
1793 : : }
1794 : 499 : ++key_exp_index;
1795 [ + + ]: 998 : for (auto& pubkey : pubkeys) {
1796 [ + - + - ]: 998 : ret.emplace_back(std::make_unique<ComboDescriptor>(std::move(pubkey)));
1797 : : }
1798 : 499 : return ret;
1799 [ + - + - : 9940 : } else if (Func("combo", expr)) {
+ + ]
1800 [ + - ]: 2 : error = "Can only have combo() at top level";
1801 : 2 : return {};
1802 : : }
1803 [ + - + - ]: 9436 : const bool multi = Func("multi", expr);
1804 [ + + + - : 18623 : const bool sortedmulti = !multi && Func("sortedmulti", expr);
+ - + + ]
1805 [ + + + - : 18599 : const bool multi_a = !(multi || sortedmulti) && Func("multi_a", expr);
+ - + + ]
1806 [ + + + + : 18509 : const bool sortedmulti_a = !(multi || sortedmulti || multi_a) && Func("sortedmulti_a", expr);
+ - + - +
+ ]
1807 [ + + + + : 9436 : if (((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH) && (multi || sortedmulti)) ||
+ + + + ]
1808 [ + + + + ]: 201 : (ctx == ParseScriptContext::P2TR && (multi_a || sortedmulti_a))) {
1809 [ + - ]: 405 : auto threshold = Expr(expr);
1810 : 405 : uint32_t thres;
1811 : 405 : std::vector<std::vector<std::unique_ptr<PubkeyProvider>>> providers; // List of multipath expanded pubkeys
1812 [ + - + - : 810 : if (!ParseUInt32(std::string(threshold.begin(), threshold.end()), &thres)) {
+ + ]
1813 [ + - + - ]: 4 : error = strprintf("Multi threshold '%s' is not valid", std::string(threshold.begin(), threshold.end()));
1814 : 2 : return {};
1815 : : }
1816 : 403 : size_t script_size = 0;
1817 : 403 : size_t max_providers_len = 0;
1818 [ + + ]: 19560 : while (expr.size()) {
1819 [ + - + - : 19171 : if (!Const(",", expr)) {
- + ]
1820 [ # # ]: 0 : error = strprintf("Multi: expected ',', got '%c'", expr[0]);
1821 : 0 : return {};
1822 : : }
1823 [ + - ]: 19171 : auto arg = Expr(expr);
1824 [ + - ]: 19171 : auto pks = ParsePubkey(key_exp_index, arg, ctx, out, error);
1825 [ + + ]: 19171 : if (pks.empty()) {
1826 [ + - ]: 14 : error = strprintf("Multi: %s", error);
1827 : 14 : return {};
1828 : : }
1829 [ + - + - ]: 19157 : script_size += pks.at(0)->GetSize() + 1;
1830 [ + + ]: 19157 : max_providers_len = std::max(max_providers_len, pks.size());
1831 [ + - ]: 19157 : providers.emplace_back(std::move(pks));
1832 : 19157 : key_exp_index++;
1833 : 19171 : }
1834 [ + + + + : 389 : if ((multi || sortedmulti) && (providers.empty() || providers.size() > MAX_PUBKEYS_PER_MULTISIG)) {
+ - - + ]
1835 [ # # ]: 0 : error = strprintf("Cannot have %u keys in multisig; must have between 1 and %d keys, inclusive", providers.size(), MAX_PUBKEYS_PER_MULTISIG);
1836 : 0 : return {};
1837 [ + + + + : 389 : } else if ((multi_a || sortedmulti_a) && (providers.empty() || providers.size() > MAX_PUBKEYS_PER_MULTI_A)) {
+ - - + ]
1838 [ # # ]: 0 : error = strprintf("Cannot have %u keys in multi_a; must have between 1 and %d keys, inclusive", providers.size(), MAX_PUBKEYS_PER_MULTI_A);
1839 : 0 : return {};
1840 [ + + ]: 389 : } else if (thres < 1) {
1841 [ + - ]: 2 : error = strprintf("Multisig threshold cannot be %d, must be at least 1", thres);
1842 : 2 : return {};
1843 [ + + ]: 387 : } else if (thres > providers.size()) {
1844 [ + - ]: 2 : error = strprintf("Multisig threshold cannot be larger than the number of keys; threshold is %d but only %u keys specified", thres, providers.size());
1845 : 2 : return {};
1846 : : }
1847 [ + + ]: 385 : if (ctx == ParseScriptContext::TOP) {
1848 [ + + ]: 24 : if (providers.size() > 3) {
1849 [ + - ]: 2 : error = strprintf("Cannot have %u pubkeys in bare multisig; only at most 3 pubkeys", providers.size());
1850 : 2 : return {};
1851 : : }
1852 : : }
1853 [ + + ]: 383 : if (ctx == ParseScriptContext::P2SH) {
1854 : : // This limits the maximum number of compressed pubkeys to 15.
1855 [ + + ]: 81 : if (script_size + 3 > MAX_SCRIPT_ELEMENT_SIZE) {
1856 [ + - ]: 4 : error = strprintf("P2SH script is too large, %d bytes is larger than %d bytes", script_size + 3, MAX_SCRIPT_ELEMENT_SIZE);
1857 : 4 : return {};
1858 : : }
1859 : : }
1860 : :
1861 : : // Make sure all vecs are of the same length, or exactly length 1
1862 : : // For length 1 vectors, clone key providers until vector is the same length
1863 [ + + ]: 19451 : for (auto& vec : providers) {
1864 [ + + ]: 19074 : if (vec.size() == 1) {
1865 [ + + ]: 19060 : for (size_t i = 1; i < max_providers_len; ++i) {
1866 [ + - + - : 18 : vec.emplace_back(vec.at(0)->Clone());
+ - ]
1867 : : }
1868 [ + + ]: 32 : } else if (vec.size() != max_providers_len) {
1869 [ + - ]: 2 : error = strprintf("multi(): Multipath derivation paths have mismatched lengths");
1870 : 2 : return {};
1871 : : }
1872 : : }
1873 : :
1874 : : // Build the final descriptors vector
1875 [ + + ]: 775 : for (size_t i = 0; i < max_providers_len; ++i) {
1876 : : // Build final pubkeys vectors by retrieving the i'th subscript for each vector in subscripts
1877 : 398 : std::vector<std::unique_ptr<PubkeyProvider>> pubs;
1878 [ + - ]: 398 : pubs.reserve(providers.size());
1879 [ + + ]: 19522 : for (auto& pub : providers) {
1880 [ + - + - ]: 19124 : pubs.emplace_back(std::move(pub.at(i)));
1881 : : }
1882 [ + + + + ]: 398 : if (multi || sortedmulti) {
1883 [ + - + - ]: 532 : ret.emplace_back(std::make_unique<MultisigDescriptor>(thres, std::move(pubs), sortedmulti));
1884 : : } else {
1885 [ + - + - ]: 264 : ret.emplace_back(std::make_unique<MultiADescriptor>(thres, std::move(pubs), sortedmulti_a));
1886 : : }
1887 : 398 : }
1888 : 377 : return ret;
1889 [ + - - + ]: 9436 : } else if (multi || sortedmulti) {
1890 [ # # ]: 0 : error = "Can only have multi/sortedmulti at top level, in sh(), or in wsh()";
1891 : 0 : return {};
1892 [ + - - + ]: 9031 : } else if (multi_a || sortedmulti_a) {
1893 [ # # ]: 0 : error = "Can only have multi_a/sortedmulti_a inside tr()";
1894 : 0 : return {};
1895 : : }
1896 [ + + + - : 17897 : if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH) && Func("wpkh", expr)) {
+ - + + +
+ ]
1897 [ + - ]: 2983 : auto pubkeys = ParsePubkey(key_exp_index, expr, ParseScriptContext::P2WPKH, out, error);
1898 [ + + ]: 2983 : if (pubkeys.empty()) {
1899 [ + - ]: 23 : error = strprintf("wpkh(): %s", error);
1900 : 23 : return {};
1901 : : }
1902 : 2960 : key_exp_index++;
1903 [ + + ]: 5937 : for (auto& pubkey : pubkeys) {
1904 [ + - + - ]: 5954 : ret.emplace_back(std::make_unique<WPKHDescriptor>(std::move(pubkey)));
1905 : : }
1906 : 2960 : return ret;
1907 [ + - + - : 9031 : } else if (Func("wpkh", expr)) {
+ + ]
1908 [ + - ]: 3 : error = "Can only have wpkh() at top level or inside sh()";
1909 : 3 : return {};
1910 : : }
1911 [ + + + - : 11850 : if (ctx == ParseScriptContext::TOP && Func("sh", expr)) {
+ - + + +
+ ]
1912 [ + - ]: 1607 : auto descs = ParseScript(key_exp_index, expr, ParseScriptContext::P2SH, out, error);
1913 [ + + + - ]: 1607 : if (descs.empty() || expr.size()) return {};
1914 : 1587 : std::vector<std::unique_ptr<DescriptorImpl>> ret;
1915 [ + - ]: 1587 : ret.reserve(descs.size());
1916 [ + + ]: 3193 : for (auto& desc : descs) {
1917 [ + - + - : 1606 : ret.push_back(std::make_unique<SHDescriptor>(std::move(desc)));
- + ]
1918 : : }
1919 : 1587 : return ret;
1920 [ + - + - : 6045 : } else if (Func("sh", expr)) {
+ + ]
1921 [ + - ]: 6 : error = "Can only have sh() at top level";
1922 : 6 : return {};
1923 : : }
1924 [ + + + - : 8705 : if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH) && Func("wsh", expr)) {
+ - + + +
+ ]
1925 [ + - ]: 287 : auto descs = ParseScript(key_exp_index, expr, ParseScriptContext::P2WSH, out, error);
1926 [ + + + - ]: 287 : if (descs.empty() || expr.size()) return {};
1927 [ + + ]: 493 : for (auto& desc : descs) {
1928 [ + - + - ]: 500 : ret.emplace_back(std::make_unique<WSHDescriptor>(std::move(desc)));
1929 : : }
1930 : 243 : return ret;
1931 [ + - + - : 4432 : } else if (Func("wsh", expr)) {
+ + ]
1932 [ + - ]: 3 : error = "Can only have wsh() at top level or inside sh()";
1933 : 3 : return {};
1934 : : }
1935 [ + + + - : 8123 : if (ctx == ParseScriptContext::TOP && Func("addr", expr)) {
+ - + + +
+ ]
1936 [ + - + - ]: 194 : CTxDestination dest = DecodeDestination(std::string(expr.begin(), expr.end()));
1937 [ + - + + ]: 97 : if (!IsValidDestination(dest)) {
1938 [ + - ]: 3 : error = "Address is not valid";
1939 : 3 : return {};
1940 : : }
1941 [ + - + - ]: 94 : ret.emplace_back(std::make_unique<AddressDescriptor>(std::move(dest)));
1942 : 94 : return ret;
1943 [ + - + - : 4142 : } else if (Func("addr", expr)) {
- + ]
1944 [ # # ]: 0 : error = "Can only have addr() at top level";
1945 : 0 : return {};
1946 : : }
1947 [ + + + - : 7929 : if (ctx == ParseScriptContext::TOP && Func("tr", expr)) {
+ - + + +
+ ]
1948 [ + - ]: 1631 : auto arg = Expr(expr);
1949 [ + - ]: 1631 : auto internal_keys = ParsePubkey(key_exp_index, arg, ParseScriptContext::P2TR, out, error);
1950 [ + + ]: 1631 : if (internal_keys.empty()) {
1951 [ + - ]: 2 : error = strprintf("tr(): %s", error);
1952 : 2 : return {};
1953 : : }
1954 [ + + ]: 1629 : size_t max_providers_len = internal_keys.size();
1955 : 1629 : ++key_exp_index;
1956 : 1629 : std::vector<std::vector<std::unique_ptr<DescriptorImpl>>> subscripts; //!< list of multipath expanded script subexpressions
1957 : 1629 : std::vector<int> depths; //!< depth in the tree of each subexpression (same length subscripts)
1958 [ + + ]: 1629 : if (expr.size()) {
1959 [ + - + - : 310 : if (!Const(",", expr)) {
- + ]
1960 [ # # ]: 0 : error = strprintf("tr: expected ',', got '%c'", expr[0]);
1961 : 0 : return {};
1962 : : }
1963 : : /** The path from the top of the tree to what we're currently processing.
1964 : : * branches[i] == false: left branch in the i'th step from the top; true: right branch.
1965 : : */
1966 : 310 : std::vector<bool> branches;
1967 : : // Loop over all provided scripts. In every iteration exactly one script will be processed.
1968 : : // Use a do-loop because inside this if-branch we expect at least one script.
1969 : : do {
1970 : : // First process all open braces.
1971 [ + - + - : 1204 : while (Const("{", expr)) {
+ + ]
1972 [ + - ]: 458 : branches.push_back(false); // new left branch
1973 [ - + ]: 458 : if (branches.size() > TAPROOT_CONTROL_MAX_NODE_COUNT) {
1974 [ # # ]: 0 : error = strprintf("tr() supports at most %i nesting levels", TAPROOT_CONTROL_MAX_NODE_COUNT);
1975 : 0 : return {};
1976 : : }
1977 : : }
1978 : : // Process the actual script expression.
1979 [ + - ]: 746 : auto sarg = Expr(expr);
1980 [ + - + - ]: 746 : subscripts.emplace_back(ParseScript(key_exp_index, sarg, ParseScriptContext::P2TR, out, error));
1981 [ + + ]: 746 : if (subscripts.back().empty()) return {};
1982 [ + + ]: 744 : max_providers_len = std::max(max_providers_len, subscripts.back().size());
1983 [ + - ]: 744 : depths.push_back(branches.size());
1984 : : // Process closing braces; one is expected for every right branch we were in.
1985 [ + + + + ]: 1180 : while (branches.size() && branches.back()) {
1986 [ + - - + : 436 : if (!Const("}", expr)) {
+ - ]
1987 [ # # ]: 0 : error = strprintf("tr(): expected '}' after script expression");
1988 : 0 : return {};
1989 : : }
1990 : 436 : branches.pop_back(); // move up one level after encountering '}'
1991 : : }
1992 : : // If after that, we're at the end of a left branch, expect a comma.
1993 [ + + + - ]: 744 : if (branches.size() && !branches.back()) {
1994 [ + - + - : 436 : if (!Const(",", expr)) {
- + ]
1995 [ # # ]: 0 : error = strprintf("tr(): expected ',' after script expression");
1996 : 0 : return {};
1997 : : }
1998 : 436 : branches.back() = true; // And now we're in a right branch.
1999 : : }
2000 [ + + ]: 744 : } while (branches.size());
2001 : : // After we've explored a whole tree, we must be at the end of the expression.
2002 [ - + ]: 308 : if (expr.size()) {
2003 [ # # ]: 0 : error = strprintf("tr(): expected ')' after script expression");
2004 : 0 : return {};
2005 : : }
2006 : 310 : }
2007 [ + - - + ]: 1627 : assert(TaprootBuilder::ValidDepths(depths));
2008 : :
2009 : : // Make sure all vecs are of the same length, or exactly length 1
2010 : : // For length 1 vectors, clone subdescs until vector is the same length
2011 [ + + ]: 2365 : for (auto& vec : subscripts) {
2012 [ + + ]: 742 : if (vec.size() == 1) {
2013 [ + + ]: 704 : for (size_t i = 1; i < max_providers_len; ++i) {
2014 [ + - + - : 5 : vec.emplace_back(vec.at(0)->Clone());
+ - ]
2015 : : }
2016 [ + + ]: 43 : } else if (vec.size() != max_providers_len) {
2017 [ + - ]: 4 : error = strprintf("tr(): Multipath subscripts have mismatched lengths");
2018 : 4 : return {};
2019 : : }
2020 : : }
2021 : :
2022 [ + + + + ]: 1623 : if (internal_keys.size() > 1 && internal_keys.size() != max_providers_len) {
2023 [ + - ]: 2 : error = strprintf("tr(): Multipath internal key mismatches multipath subscripts lengths");
2024 : 2 : return {};
2025 : : }
2026 : :
2027 [ + + ]: 1640 : while (internal_keys.size() < max_providers_len) {
2028 [ + - + - : 19 : internal_keys.emplace_back(internal_keys.at(0)->Clone());
+ - ]
2029 : : }
2030 : :
2031 : : // Build the final descriptors vector
2032 [ + + ]: 3280 : for (size_t i = 0; i < max_providers_len; ++i) {
2033 : : // Build final subscripts vectors by retrieving the i'th subscript for each vector in subscripts
2034 : 1659 : std::vector<std::unique_ptr<DescriptorImpl>> this_subs;
2035 [ + - ]: 1659 : this_subs.reserve(subscripts.size());
2036 [ + + ]: 2457 : for (auto& subs : subscripts) {
2037 [ + - + - ]: 798 : this_subs.emplace_back(std::move(subs.at(i)));
2038 : : }
2039 [ + - + - : 1659 : ret.emplace_back(std::make_unique<TRDescriptor>(std::move(internal_keys.at(i)), std::move(this_subs), depths));
+ - ]
2040 : 1659 : }
2041 : 1621 : return ret;
2042 : :
2043 : :
2044 [ + - + - : 4045 : } else if (Func("tr", expr)) {
- + ]
2045 [ # # ]: 0 : error = "Can only have tr at top level";
2046 : 0 : return {};
2047 : : }
2048 [ + + + - : 4667 : if (ctx == ParseScriptContext::TOP && Func("rawtr", expr)) {
+ - + + +
+ ]
2049 [ + - ]: 34 : auto arg = Expr(expr);
2050 [ + + ]: 34 : if (expr.size()) {
2051 [ + - ]: 1 : error = strprintf("rawtr(): only one key expected.");
2052 : 1 : return {};
2053 : : }
2054 [ + - ]: 33 : auto output_keys = ParsePubkey(key_exp_index, arg, ParseScriptContext::P2TR, out, error);
2055 [ - + ]: 33 : if (output_keys.empty()) {
2056 [ # # ]: 0 : error = strprintf("rawtr(): %s", error);
2057 : 0 : return {};
2058 : : }
2059 : 33 : ++key_exp_index;
2060 [ + + ]: 66 : for (auto& pubkey : output_keys) {
2061 [ + - + - ]: 66 : ret.emplace_back(std::make_unique<RawTRDescriptor>(std::move(pubkey)));
2062 : : }
2063 : 33 : return ret;
2064 [ + - + - : 2413 : } else if (Func("rawtr", expr)) {
- + ]
2065 [ # # ]: 0 : error = "Can only have rawtr at top level";
2066 : 0 : return {};
2067 : : }
2068 [ + + + - : 4599 : if (ctx == ParseScriptContext::TOP && Func("raw", expr)) {
+ - + + +
+ ]
2069 [ + - + - ]: 3770 : std::string str(expr.begin(), expr.end());
2070 [ + - + + ]: 1885 : if (!IsHex(str)) {
2071 [ + - ]: 2 : error = "Raw script is not hex";
2072 : 2 : return {};
2073 : : }
2074 [ + - ]: 1883 : auto bytes = ParseHex(str);
2075 [ + - + - ]: 3766 : ret.emplace_back(std::make_unique<RawDescriptor>(CScript(bytes.begin(), bytes.end())));
2076 : 1883 : return ret;
2077 [ + - + - : 4263 : } else if (Func("raw", expr)) {
- + ]
2078 [ # # ]: 0 : error = "Can only have raw() at top level";
2079 : 0 : return {};
2080 : : }
2081 : : // Process miniscript expressions.
2082 : 495 : {
2083 : 495 : const auto script_ctx{ctx == ParseScriptContext::P2WSH ? miniscript::MiniscriptContext::P2WSH : miniscript::MiniscriptContext::TAPSCRIPT};
2084 [ + - ]: 495 : KeyParser parser(/*out = */&out, /* in = */nullptr, /* ctx = */script_ctx, key_exp_index);
2085 [ + - + - ]: 990 : auto node = miniscript::FromString(std::string(expr.begin(), expr.end()), parser);
2086 [ + + ]: 495 : if (parser.m_key_parsing_error != "") {
2087 : 2 : error = std::move(parser.m_key_parsing_error);
2088 : 2 : return {};
2089 : : }
2090 [ + + ]: 493 : if (node) {
2091 [ + + ]: 153 : if (ctx != ParseScriptContext::P2WSH && ctx != ParseScriptContext::P2TR) {
2092 [ + - ]: 3 : error = "Miniscript expressions can only be used in wsh or tr.";
2093 : 3 : return {};
2094 : : }
2095 [ + + + + ]: 150 : if (!node->IsSane() || node->IsNotSatisfiable()) {
2096 : : // Try to find the first insane sub for better error reporting.
2097 [ + - ]: 14 : auto insane_node = node.get();
2098 [ + - + + ]: 14 : if (const auto sub = node->FindInsaneSub()) insane_node = sub;
2099 [ + - + - : 28 : if (const auto str = insane_node->ToString(parser)) error = *str;
+ - ]
2100 [ + + ]: 14 : if (!insane_node->IsValid()) {
2101 [ + - ]: 4 : error += " is invalid";
2102 [ + + ]: 10 : } else if (!node->IsSane()) {
2103 [ + - ]: 9 : error += " is not sane";
2104 [ + + ]: 9 : if (!insane_node->IsNonMalleable()) {
2105 [ + - ]: 2 : error += ": malleable witnesses exist";
2106 [ + + + + ]: 7 : } else if (insane_node == node.get() && !insane_node->NeedsSignature()) {
2107 [ + - ]: 3 : error += ": witnesses without signature exist";
2108 [ + + ]: 4 : } else if (!insane_node->CheckTimeLocksMix()) {
2109 [ + - ]: 2 : error += ": contains mixes of timelocks expressed in blocks and seconds";
2110 [ + - ]: 2 : } else if (!insane_node->CheckDuplicateKey()) {
2111 [ + - ]: 2 : error += ": contains duplicate public keys";
2112 [ # # ]: 0 : } else if (!insane_node->ValidSatisfactions()) {
2113 [ # # ]: 0 : error += ": needs witnesses that may exceed resource limits";
2114 : : }
2115 : : } else {
2116 [ + - ]: 1 : error += " is not satisfiable";
2117 : : }
2118 : 14 : return {};
2119 : : }
2120 : : // A signature check is required for a miniscript to be sane. Therefore no sane miniscript
2121 : : // may have an empty list of public keys.
2122 [ + - ]: 136 : CHECK_NONFATAL(!parser.m_keys.empty());
2123 : 136 : key_exp_index += parser.m_keys.size();
2124 : : // Make sure all vecs are of the same length, or exactly length 1
2125 : : // For length 1 vectors, clone subdescs until vector is the same length
2126 : 136 : size_t num_multipath = std::max_element(parser.m_keys.begin(), parser.m_keys.end(),
2127 : 242 : [](const std::vector<std::unique_ptr<PubkeyProvider>>& a, const std::vector<std::unique_ptr<PubkeyProvider>>& b) {
2128 [ + - ]: 242 : return a.size() < b.size();
2129 : 136 : })->size();
2130 : :
2131 [ + + ]: 512 : for (auto& vec : parser.m_keys) {
2132 [ + + ]: 378 : if (vec.size() == 1) {
2133 [ - + ]: 359 : for (size_t i = 1; i < num_multipath; ++i) {
2134 [ # # # # : 0 : vec.emplace_back(vec.at(0)->Clone());
# # ]
2135 : : }
2136 [ + + ]: 19 : } else if (vec.size() != num_multipath) {
2137 [ + - ]: 2 : error = strprintf("Miniscript: Multipath derivation paths have mismatched lengths");
2138 : 2 : return {};
2139 : : }
2140 : : }
2141 : :
2142 : : // Build the final descriptors vector
2143 [ + + ]: 278 : for (size_t i = 0; i < num_multipath; ++i) {
2144 : : // Build final pubkeys vectors by retrieving the i'th subscript for each vector in subscripts
2145 : 144 : std::vector<std::unique_ptr<PubkeyProvider>> pubs;
2146 [ + - ]: 144 : pubs.reserve(parser.m_keys.size());
2147 [ + + ]: 533 : for (auto& pub : parser.m_keys) {
2148 [ + - + - ]: 389 : pubs.emplace_back(std::move(pub.at(i)));
2149 : : }
2150 [ + - + - : 288 : ret.emplace_back(std::make_unique<MiniscriptDescriptor>(std::move(pubs), node->Clone()));
+ - ]
2151 : 144 : }
2152 : 134 : return ret;
2153 : : }
2154 : 650 : }
2155 [ + + ]: 340 : if (ctx == ParseScriptContext::P2SH) {
2156 [ + - ]: 2 : error = "A function is needed within P2SH";
2157 : 2 : return {};
2158 [ + + ]: 338 : } else if (ctx == ParseScriptContext::P2WSH) {
2159 [ + - ]: 2 : error = "A function is needed within P2WSH";
2160 : 2 : return {};
2161 : : }
2162 [ + - + - ]: 672 : error = strprintf("'%s' is not a valid descriptor function", std::string(expr.begin(), expr.end()));
2163 : 336 : return {};
2164 : 11988 : }
2165 : :
2166 : 950 : std::unique_ptr<DescriptorImpl> InferMultiA(const CScript& script, ParseScriptContext ctx, const SigningProvider& provider)
2167 : : {
2168 : 950 : auto match = MatchMultiA(script);
2169 [ + + ]: 950 : if (!match) return {};
2170 : 778 : std::vector<std::unique_ptr<PubkeyProvider>> keys;
2171 [ + - ]: 778 : keys.reserve(match->second.size());
2172 [ + + ]: 106226 : for (const auto keyspan : match->second) {
2173 [ - + ]: 105448 : if (keyspan.size() != 32) return {};
2174 [ + - ]: 105448 : auto key = InferXOnlyPubkey(XOnlyPubKey{keyspan}, ctx, provider);
2175 [ - + ]: 105448 : if (!key) return {};
2176 [ + - ]: 105448 : keys.push_back(std::move(key));
2177 : 105448 : }
2178 [ + - - + ]: 778 : return std::make_unique<MultiADescriptor>(match->first, std::move(keys));
2179 : 1728 : }
2180 : :
2181 : : // NOLINTNEXTLINE(misc-no-recursion)
2182 : 381407 : std::unique_ptr<DescriptorImpl> InferScript(const CScript& script, ParseScriptContext ctx, const SigningProvider& provider)
2183 : : {
2184 [ + + + + : 381407 : if (ctx == ParseScriptContext::P2TR && script.size() == 34 && script[0] == 32 && script[33] == OP_CHECKSIG) {
+ + + - -
+ ]
2185 : 3067 : XOnlyPubKey key{std::span{script}.subspan(1, 32)};
2186 [ + - - + ]: 3067 : return std::make_unique<PKDescriptor>(InferXOnlyPubkey(key, ctx, provider), true);
2187 : : }
2188 : :
2189 [ + + ]: 378340 : if (ctx == ParseScriptContext::P2TR) {
2190 : 950 : auto ret = InferMultiA(script, ctx, provider);
2191 [ + + ]: 950 : if (ret) return ret;
2192 : 950 : }
2193 : :
2194 : 377562 : std::vector<std::vector<unsigned char>> data;
2195 [ + - ]: 377562 : TxoutType txntype = Solver(script, data);
2196 : :
2197 [ + + + - ]: 377562 : if (txntype == TxoutType::PUBKEY && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
2198 : 18506 : CPubKey pubkey(data[0]);
2199 [ + - + + ]: 18506 : if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
2200 [ + - - + ]: 18504 : return std::make_unique<PKDescriptor>(std::move(pubkey_provider));
2201 : 18506 : }
2202 : : }
2203 [ + + + + ]: 359058 : if (txntype == TxoutType::PUBKEYHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
2204 : 102951 : uint160 hash(data[0]);
2205 [ + - ]: 102951 : CKeyID keyid(hash);
2206 [ + - ]: 102951 : CPubKey pubkey;
2207 [ + - + + ]: 102951 : if (provider.GetPubKey(keyid, pubkey)) {
2208 [ + - + + ]: 102698 : if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
2209 [ + - - + ]: 102694 : return std::make_unique<PKHDescriptor>(std::move(pubkey_provider));
2210 : 102698 : }
2211 : : }
2212 : : }
2213 [ + + ]: 256364 : if (txntype == TxoutType::WITNESS_V0_KEYHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH)) {
2214 : 192876 : uint160 hash(data[0]);
2215 [ + - ]: 192876 : CKeyID keyid(hash);
2216 [ + - ]: 192876 : CPubKey pubkey;
2217 [ + - + + ]: 192876 : if (provider.GetPubKey(keyid, pubkey)) {
2218 [ + - + + ]: 191626 : if (auto pubkey_provider = InferPubkey(pubkey, ParseScriptContext::P2WPKH, provider)) {
2219 [ + - - + ]: 191624 : return std::make_unique<WPKHDescriptor>(std::move(pubkey_provider));
2220 : 191626 : }
2221 : : }
2222 : : }
2223 [ + + + - ]: 64740 : if (txntype == TxoutType::MULTISIG && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
2224 : 680 : bool ok = true;
2225 : 680 : std::vector<std::unique_ptr<PubkeyProvider>> providers;
2226 [ + + ]: 3460 : for (size_t i = 1; i + 1 < data.size(); ++i) {
2227 : 2780 : CPubKey pubkey(data[i]);
2228 [ + - + - ]: 2780 : if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
2229 [ + - ]: 2780 : providers.push_back(std::move(pubkey_provider));
2230 : : } else {
2231 : 0 : ok = false;
2232 : 0 : break;
2233 : 2780 : }
2234 : : }
2235 [ + - - + ]: 680 : if (ok) return std::make_unique<MultisigDescriptor>((int)data[0][0], std::move(providers));
2236 : 680 : }
2237 [ + + ]: 64060 : if (txntype == TxoutType::SCRIPTHASH && ctx == ParseScriptContext::TOP) {
2238 : 36642 : uint160 hash(data[0]);
2239 [ + - ]: 36642 : CScriptID scriptid(hash);
2240 : 36642 : CScript subscript;
2241 [ + - + + ]: 36642 : if (provider.GetCScript(scriptid, subscript)) {
2242 [ + - ]: 36369 : auto sub = InferScript(subscript, ParseScriptContext::P2SH, provider);
2243 [ + + + - : 36369 : if (sub) return std::make_unique<SHDescriptor>(std::move(sub));
- + ]
2244 : 36369 : }
2245 : 36642 : }
2246 [ + + ]: 27703 : if (txntype == TxoutType::WITNESS_V0_SCRIPTHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH)) {
2247 [ + - ]: 3234 : CScriptID scriptid{RIPEMD160(data[0])};
2248 : 3234 : CScript subscript;
2249 [ + - + + ]: 3234 : if (provider.GetCScript(scriptid, subscript)) {
2250 [ + - ]: 868 : auto sub = InferScript(subscript, ParseScriptContext::P2WSH, provider);
2251 [ + + + - : 868 : if (sub) return std::make_unique<WSHDescriptor>(std::move(sub));
- + ]
2252 : 868 : }
2253 : 3234 : }
2254 [ + + ]: 26848 : if (txntype == TxoutType::WITNESS_V1_TAPROOT && ctx == ParseScriptContext::TOP) {
2255 : : // Extract x-only pubkey from output.
2256 : 20615 : XOnlyPubKey pubkey;
2257 : 20615 : std::copy(data[0].begin(), data[0].end(), pubkey.begin());
2258 : : // Request spending data.
2259 [ + - ]: 20615 : TaprootSpendData tap;
2260 [ + - + + ]: 20615 : if (provider.GetTaprootSpendData(pubkey, tap)) {
2261 : : // If found, convert it back to tree form.
2262 [ + - ]: 5092 : auto tree = InferTaprootTree(tap, pubkey);
2263 [ + - ]: 5092 : if (tree) {
2264 : : // If that works, try to infer subdescriptors for all leaves.
2265 : 5092 : bool ok = true;
2266 : 5092 : std::vector<std::unique_ptr<DescriptorImpl>> subscripts; //!< list of script subexpressions
2267 : 5092 : std::vector<int> depths; //!< depth in the tree of each subexpression (same length subscripts)
2268 [ + - + + ]: 9109 : for (const auto& [depth, script, leaf_ver] : *tree) {
2269 : 4017 : std::unique_ptr<DescriptorImpl> subdesc;
2270 [ + - ]: 4017 : if (leaf_ver == TAPROOT_LEAF_TAPSCRIPT) {
2271 [ + - ]: 8034 : subdesc = InferScript(CScript(script.begin(), script.end()), ParseScriptContext::P2TR, provider);
2272 : : }
2273 [ - + ]: 4017 : if (!subdesc) {
2274 : 0 : ok = false;
2275 : 0 : break;
2276 : : } else {
2277 [ + - ]: 4017 : subscripts.push_back(std::move(subdesc));
2278 [ + - ]: 4017 : depths.push_back(depth);
2279 : : }
2280 : 4017 : }
2281 : 0 : if (ok) {
2282 [ + - ]: 5092 : auto key = InferXOnlyPubkey(tap.internal_key, ParseScriptContext::P2TR, provider);
2283 [ + - - + ]: 5092 : return std::make_unique<TRDescriptor>(std::move(key), std::move(subscripts), std::move(depths));
2284 : 5092 : }
2285 : 5092 : }
2286 : 5092 : }
2287 : : // If the above doesn't work, construct a rawtr() descriptor with just the encoded x-only pubkey.
2288 [ + - + - ]: 15523 : if (pubkey.IsFullyValid()) {
2289 [ + - ]: 15523 : auto key = InferXOnlyPubkey(pubkey, ParseScriptContext::P2TR, provider);
2290 [ + - ]: 15523 : if (key) {
2291 [ + - - + ]: 15523 : return std::make_unique<RawTRDescriptor>(std::move(key));
2292 : : }
2293 : 15523 : }
2294 : 20615 : }
2295 : :
2296 [ + + ]: 6233 : if (ctx == ParseScriptContext::P2WSH || ctx == ParseScriptContext::P2TR) {
2297 : 557 : const auto script_ctx{ctx == ParseScriptContext::P2WSH ? miniscript::MiniscriptContext::P2WSH : miniscript::MiniscriptContext::TAPSCRIPT};
2298 [ + - ]: 557 : KeyParser parser(/* out = */nullptr, /* in = */&provider, /* ctx = */script_ctx);
2299 [ + - ]: 557 : auto node = miniscript::FromScript(script, parser);
2300 [ + + - + ]: 557 : if (node && node->IsSane()) {
2301 : 544 : std::vector<std::unique_ptr<PubkeyProvider>> keys;
2302 [ + - ]: 544 : keys.reserve(parser.m_keys.size());
2303 [ + + ]: 2027 : for (auto& key : parser.m_keys) {
2304 [ + - + - ]: 1483 : keys.emplace_back(std::move(key.at(0)));
2305 : : }
2306 [ + - - + ]: 544 : return std::make_unique<MiniscriptDescriptor>(std::move(keys), std::move(node));
2307 : 544 : }
2308 : 1114 : }
2309 : :
2310 : : // The following descriptors are all top-level only descriptors.
2311 : : // So if we are not at the top level, return early.
2312 [ + + ]: 5689 : if (ctx != ParseScriptContext::TOP) return nullptr;
2313 : :
2314 : 5664 : CTxDestination dest;
2315 [ + - + + ]: 5664 : if (ExtractDestination(script, dest)) {
2316 [ + - + - ]: 4199 : if (GetScriptForDestination(dest) == script) {
2317 [ + - - + ]: 4199 : return std::make_unique<AddressDescriptor>(std::move(dest));
2318 : : }
2319 : : }
2320 : :
2321 [ + - - + ]: 1465 : return std::make_unique<RawDescriptor>(script);
2322 : 377562 : }
2323 : :
2324 : :
2325 : : } // namespace
2326 : :
2327 : : /** Check a descriptor checksum, and update desc to be the checksum-less part. */
2328 : 9656 : bool CheckChecksum(std::span<const char>& sp, bool require_checksum, std::string& error, std::string* out_checksum = nullptr)
2329 : : {
2330 : 9656 : auto check_split = Split(sp, '#');
2331 [ + + ]: 9656 : if (check_split.size() > 2) {
2332 [ + - ]: 2 : error = "Multiple '#' symbols";
2333 : : return false;
2334 : : }
2335 [ + + + + ]: 9654 : if (check_split.size() == 1 && require_checksum){
2336 [ + - ]: 9656 : error = "Missing checksum";
2337 : : return false;
2338 : : }
2339 [ + + ]: 9647 : if (check_split.size() == 2) {
2340 [ + + ]: 5588 : if (check_split[1].size() != 8) {
2341 [ + - ]: 6 : error = strprintf("Expected 8 character checksum, not %u characters", check_split[1].size());
2342 : 6 : return false;
2343 : : }
2344 : : }
2345 [ + - ]: 9641 : auto checksum = DescriptorChecksum(check_split[0]);
2346 [ + + ]: 9641 : if (checksum.empty()) {
2347 [ + - ]: 9641 : error = "Invalid characters in payload";
2348 : : return false;
2349 : : }
2350 [ + + ]: 9640 : if (check_split.size() == 2) {
2351 [ + + ]: 5581 : if (!std::equal(checksum.begin(), checksum.end(), check_split[1].begin())) {
2352 [ + - + - ]: 22 : error = strprintf("Provided checksum '%s' does not match computed checksum '%s'", std::string(check_split[1].begin(), check_split[1].end()), checksum);
2353 : 11 : return false;
2354 : : }
2355 : : }
2356 [ + + ]: 9629 : if (out_checksum) *out_checksum = std::move(checksum);
2357 : 9629 : sp = check_split[0];
2358 : 9629 : return true;
2359 : 19297 : }
2360 : :
2361 : 9371 : std::vector<std::unique_ptr<Descriptor>> Parse(const std::string& descriptor, FlatSigningProvider& out, std::string& error, bool require_checksum)
2362 : : {
2363 : 9371 : std::span<const char> sp{descriptor};
2364 [ + + ]: 9371 : if (!CheckChecksum(sp, require_checksum, error)) return {};
2365 : 9348 : uint32_t key_exp_index = 0;
2366 : 9348 : auto ret = ParseScript(key_exp_index, sp, ParseScriptContext::TOP, out, error);
2367 [ + - + + ]: 9348 : if (sp.size() == 0 && !ret.empty()) {
2368 : 8882 : std::vector<std::unique_ptr<Descriptor>> descs;
2369 [ + - ]: 8882 : descs.reserve(ret.size());
2370 [ + + ]: 17870 : for (auto& r : ret) {
2371 [ + - ]: 8988 : descs.emplace_back(std::unique_ptr<Descriptor>(std::move(r)));
2372 : : }
2373 : 8882 : return descs;
2374 : 8882 : }
2375 : 466 : return {};
2376 : 9348 : }
2377 : :
2378 : 285 : std::string GetDescriptorChecksum(const std::string& descriptor)
2379 : : {
2380 [ + - ]: 285 : std::string ret;
2381 : 285 : std::string error;
2382 [ + - ]: 285 : std::span<const char> sp{descriptor};
2383 [ + - + + : 285 : if (!CheckChecksum(sp, false, error, &ret)) return "";
+ - ]
2384 : 281 : return ret;
2385 : 285 : }
2386 : :
2387 : 340153 : std::unique_ptr<Descriptor> InferDescriptor(const CScript& script, const SigningProvider& provider)
2388 : : {
2389 : 340153 : return InferScript(script, ParseScriptContext::TOP, provider);
2390 : : }
2391 : :
2392 : 6266 : uint256 DescriptorID(const Descriptor& desc)
2393 : : {
2394 : 6266 : std::string desc_str = desc.ToString(/*compat_format=*/true);
2395 : 6266 : uint256 id;
2396 [ + - + - : 6266 : CSHA256().Write((unsigned char*)desc_str.data(), desc_str.size()).Finalize(id.begin());
+ - ]
2397 : 6266 : return id;
2398 : 6266 : }
2399 : :
2400 : 13912 : void DescriptorCache::CacheParentExtPubKey(uint32_t key_exp_pos, const CExtPubKey& xpub)
2401 : : {
2402 : 13912 : m_parent_xpubs[key_exp_pos] = xpub;
2403 : 13912 : }
2404 : :
2405 : 33025 : void DescriptorCache::CacheDerivedExtPubKey(uint32_t key_exp_pos, uint32_t der_index, const CExtPubKey& xpub)
2406 : : {
2407 : 33025 : auto& xpubs = m_derived_xpubs[key_exp_pos];
2408 : 33025 : xpubs[der_index] = xpub;
2409 : 33025 : }
2410 : :
2411 : 11146 : void DescriptorCache::CacheLastHardenedExtPubKey(uint32_t key_exp_pos, const CExtPubKey& xpub)
2412 : : {
2413 : 11146 : m_last_hardened_xpubs[key_exp_pos] = xpub;
2414 : 11146 : }
2415 : :
2416 : 660737 : bool DescriptorCache::GetCachedParentExtPubKey(uint32_t key_exp_pos, CExtPubKey& xpub) const
2417 : : {
2418 : 660737 : const auto& it = m_parent_xpubs.find(key_exp_pos);
2419 [ + + ]: 660737 : if (it == m_parent_xpubs.end()) return false;
2420 : 653676 : xpub = it->second;
2421 : 653676 : return true;
2422 : : }
2423 : :
2424 : 683357 : bool DescriptorCache::GetCachedDerivedExtPubKey(uint32_t key_exp_pos, uint32_t der_index, CExtPubKey& xpub) const
2425 : : {
2426 : 683357 : const auto& key_exp_it = m_derived_xpubs.find(key_exp_pos);
2427 [ + + ]: 683357 : if (key_exp_it == m_derived_xpubs.end()) return false;
2428 : 26223 : const auto& der_it = key_exp_it->second.find(der_index);
2429 [ + + ]: 26223 : if (der_it == key_exp_it->second.end()) return false;
2430 : 4362 : xpub = der_it->second;
2431 : 4362 : return true;
2432 : : }
2433 : :
2434 : 3952 : bool DescriptorCache::GetCachedLastHardenedExtPubKey(uint32_t key_exp_pos, CExtPubKey& xpub) const
2435 : : {
2436 : 3952 : const auto& it = m_last_hardened_xpubs.find(key_exp_pos);
2437 [ + + ]: 3952 : if (it == m_last_hardened_xpubs.end()) return false;
2438 : 942 : xpub = it->second;
2439 : 942 : return true;
2440 : : }
2441 : :
2442 : 438016 : DescriptorCache DescriptorCache::MergeAndDiff(const DescriptorCache& other)
2443 : : {
2444 : 438016 : DescriptorCache diff;
2445 [ + - + + ]: 441757 : for (const auto& parent_xpub_pair : other.GetCachedParentExtPubKeys()) {
2446 [ + - ]: 3741 : CExtPubKey xpub;
2447 [ + - + + ]: 3741 : if (GetCachedParentExtPubKey(parent_xpub_pair.first, xpub)) {
2448 [ - + ]: 12 : if (xpub != parent_xpub_pair.second) {
2449 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": New cached parent xpub does not match already cached parent xpub");
2450 : : }
2451 : 12 : continue;
2452 : : }
2453 [ + - ]: 3729 : CacheParentExtPubKey(parent_xpub_pair.first, parent_xpub_pair.second);
2454 [ + - ]: 3729 : diff.CacheParentExtPubKey(parent_xpub_pair.first, parent_xpub_pair.second);
2455 : 0 : }
2456 [ + - + + ]: 449002 : for (const auto& derived_xpub_map_pair : other.GetCachedDerivedExtPubKeys()) {
2457 [ + + ]: 21972 : for (const auto& derived_xpub_pair : derived_xpub_map_pair.second) {
2458 [ + - ]: 10986 : CExtPubKey xpub;
2459 [ + - + + ]: 10986 : if (GetCachedDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, xpub)) {
2460 [ - + ]: 44 : if (xpub != derived_xpub_pair.second) {
2461 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": New cached derived xpub does not match already cached derived xpub");
2462 : : }
2463 : 44 : continue;
2464 : : }
2465 [ + - ]: 10942 : CacheDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, derived_xpub_pair.second);
2466 [ + - ]: 10942 : diff.CacheDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, derived_xpub_pair.second);
2467 : : }
2468 : 0 : }
2469 [ + - + + ]: 441026 : for (const auto& lh_xpub_pair : other.GetCachedLastHardenedExtPubKeys()) {
2470 [ + - ]: 3010 : CExtPubKey xpub;
2471 [ + - - + ]: 3010 : if (GetCachedLastHardenedExtPubKey(lh_xpub_pair.first, xpub)) {
2472 [ # # ]: 0 : if (xpub != lh_xpub_pair.second) {
2473 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": New cached last hardened xpub does not match already cached last hardened xpub");
2474 : : }
2475 : 0 : continue;
2476 : : }
2477 [ + - ]: 3010 : CacheLastHardenedExtPubKey(lh_xpub_pair.first, lh_xpub_pair.second);
2478 [ + - ]: 3010 : diff.CacheLastHardenedExtPubKey(lh_xpub_pair.first, lh_xpub_pair.second);
2479 : 0 : }
2480 : 438016 : return diff;
2481 : 0 : }
2482 : :
2483 : 876620 : ExtPubKeyMap DescriptorCache::GetCachedParentExtPubKeys() const
2484 : : {
2485 : 876620 : return m_parent_xpubs;
2486 : : }
2487 : :
2488 : 876620 : std::unordered_map<uint32_t, ExtPubKeyMap> DescriptorCache::GetCachedDerivedExtPubKeys() const
2489 : : {
2490 : 876620 : return m_derived_xpubs;
2491 : : }
2492 : :
2493 : 877309 : ExtPubKeyMap DescriptorCache::GetCachedLastHardenedExtPubKeys() const
2494 : : {
2495 : 877309 : return m_last_hardened_xpubs;
2496 : : }
|