Branch data Line data Source code
1 : : // Copyright (c) 2018-2022 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 : 731669893 : uint64_t PolyMod(uint64_t c, int val)
94 : : {
95 : 731669893 : uint8_t c0 = c >> 35;
96 : 731669893 : c = ((c & 0x7ffffffff) << 5) ^ val;
97 [ + + ]: 731669893 : if (c0 & 1) c ^= 0xf5dee51989;
98 [ + + ]: 731669893 : if (c0 & 2) c ^= 0xa9fdca3312;
99 [ + + ]: 731669893 : if (c0 & 4) c ^= 0x1bab10e32d;
100 [ + + ]: 731669893 : if (c0 & 8) c ^= 0x3706b1677a;
101 [ + + ]: 731669893 : if (c0 & 16) c ^= 0x644d626ffd;
102 : 1463339786 : return c;
103 : 731669893 : }
104 : :
105 : 3575773 : std::string DescriptorChecksum(const 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 [ + + - + ]: 3575782 : static const std::string INPUT_CHARSET =
121 [ + - ]: 9 : "0123456789()[],'/*abcdefgh@:$%{}"
122 : : "IJKLMNOPQRSTUVWXYZ&+-.;<=>?!^_|~"
123 : : "ijklmnopqrstuvwxyzABCDEFGH`#\"\\ ";
124 : :
125 : : /** The character set for the checksum itself (same as bech32). */
126 [ + + - + : 3575773 : static const std::string CHECKSUM_CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
+ - ]
127 : :
128 : 3575773 : uint64_t c = 1;
129 : 3575773 : int cls = 0;
130 : 3575773 : int clscount = 0;
131 [ + + + + ]: 529474155 : for (auto ch : span) {
132 : 525898382 : auto pos = INPUT_CHARSET.find(ch);
133 [ + + - + ]: 525898382 : if (pos == std::string::npos) return "";
134 : 525893700 : c = PolyMod(c, pos & 31); // Emit a symbol for the position inside the group, for every character.
135 : 525893700 : cls = cls * 3 + (pos >> 5); // Accumulate the group numbers
136 [ + + ]: 525893700 : if (++clscount == 3) {
137 : : // Emit an extra symbol representing the group numbers, for every 3 characters.
138 : 173874640 : c = PolyMod(c, cls);
139 : 173874640 : cls = 0;
140 : 173874640 : clscount = 0;
141 : 173874640 : }
142 [ + + + + ]: 525898382 : }
143 [ + + ]: 3571091 : if (clscount > 0) c = PolyMod(c, cls);
144 [ + + ]: 32139819 : for (int j = 0; j < 8; ++j) c = PolyMod(c, 0); // Shift further to determine the checksum.
145 : 3571091 : c ^= 1; // Prevent appending zeroes from not affecting the checksum.
146 : :
147 [ + - ]: 3571091 : std::string ret(8, ' ');
148 [ + + + - ]: 32139819 : for (int j = 0; j < 8; ++j) ret[j] = CHECKSUM_CHARSET[(c >> (5 * (7 - j))) & 31];
149 : 3571091 : return ret;
150 [ + - ]: 7146864 : }
151 : :
152 [ + - + - : 3518860 : 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 : 15445888 : explicit PubkeyProvider(uint32_t exp_index) : m_expr_index(exp_index) {}
170 : :
171 : 15445888 : 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 : 174145 : bool operator<(PubkeyProvider& other) const {
177 : 174145 : CPubKey a, b;
178 : 174145 : SigningProvider dummy;
179 : 174145 : KeyOriginInfo dummy_info;
180 : :
181 [ + - ]: 174145 : GetPubKey(0, dummy, a, dummy_info);
182 [ + - ]: 174145 : other.GetPubKey(0, dummy, b, dummy_info);
183 : :
184 : 174145 : return a < b;
185 : 174145 : }
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 : 2219431 : 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 [ + + + + ]: 2219431 : bool use_apostrophe = (!normalized && m_apostrophe) || type == StringType::COMPAT;
238 [ + - + - ]: 2219431 : return HexStr(m_origin.fingerprint) + FormatHDKeypath(m_origin.path, use_apostrophe);
239 : 2219431 : }
240 : :
241 : : public:
242 : 7574880 : 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 : 2126218 : bool GetPubKey(int pos, const SigningProvider& arg, CPubKey& key, KeyOriginInfo& info, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
244 : : {
245 [ + + ]: 2126218 : if (!m_provider->GetPubKey(pos, arg, key, info, read_cache, write_cache)) return false;
246 : 2094805 : std::copy(std::begin(m_origin.fingerprint), std::end(m_origin.fingerprint), info.fingerprint);
247 : 2094805 : info.path.insert(info.path.begin(), m_origin.path.begin(), m_origin.path.end());
248 : 2094805 : return true;
249 : 2126218 : }
250 : 2190836 : bool IsRange() const override { return m_provider->IsRange(); }
251 : 881997 : size_t GetSize() const override { return m_provider->GetSize(); }
252 [ + - + - : 2211973 : std::string ToString(StringType type) const override { return "[" + OriginString(type) + "]" + m_provider->ToString(type); }
+ - + - ]
253 : 1694 : bool ToPrivateString(const SigningProvider& arg, std::string& ret) const override
254 : : {
255 : 1694 : std::string sub;
256 [ + - + + ]: 1694 : if (!m_provider->ToPrivateString(arg, sub)) return false;
257 [ + - + - : 1654 : ret = "[" + OriginString(StringType::PUBLIC) + "]" + std::move(sub);
+ - + - ]
258 : 1654 : return true;
259 : 1694 : }
260 : 5811 : bool ToNormalizedString(const SigningProvider& arg, std::string& ret, const DescriptorCache* cache) const override
261 : : {
262 : 5811 : std::string sub;
263 [ + - + + ]: 5811 : 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 [ + + ]: 5804 : if (sub[0] == '[') {
268 [ + - ]: 2903 : sub = sub.substr(9);
269 [ + - + - : 2903 : ret = "[" + OriginString(StringType::PUBLIC, /*normalized=*/true) + std::move(sub);
+ - ]
270 : 2903 : } else {
271 [ + - + - : 2901 : ret = "[" + OriginString(StringType::PUBLIC, /*normalized=*/true) + "]" + std::move(sub);
+ - + - ]
272 : : }
273 : 5804 : return true;
274 : 5811 : }
275 : 6071 : bool GetPrivKey(int pos, const SigningProvider& arg, CKey& key) const override
276 : : {
277 : 6071 : 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 : 0 : }
291 : : };
292 : :
293 : : /** An object representing a parsed constant public key in a descriptor. */
294 : : class ConstPubkeyProvider final : public PubkeyProvider
295 : : {
296 : : CPubKey m_pubkey;
297 : : bool m_xonly;
298 : :
299 : : public:
300 : 7716388 : ConstPubkeyProvider(uint32_t exp_index, const CPubKey& pubkey, bool xonly) : PubkeyProvider(exp_index), m_pubkey(pubkey), m_xonly(xonly) {}
301 : 282491 : bool GetPubKey(int pos, const SigningProvider& arg, CPubKey& key, KeyOriginInfo& info, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
302 : : {
303 : 282491 : key = m_pubkey;
304 : 282491 : info.path.clear();
305 : 282491 : CKeyID keyid = m_pubkey.GetID();
306 : 282491 : std::copy(keyid.begin(), keyid.begin() + sizeof(info.fingerprint), info.fingerprint);
307 : 282491 : return true;
308 : 282491 : }
309 : 68241 : bool IsRange() const override { return false; }
310 : 932893 : size_t GetSize() const override { return m_pubkey.size(); }
311 [ + + + - : 209459 : std::string ToString(StringType type) const override { return m_xonly ? HexStr(m_pubkey).substr(2) : HexStr(m_pubkey); }
+ - + - +
+ + + # #
# # ]
312 : 4286 : bool ToPrivateString(const SigningProvider& arg, std::string& ret) const override
313 : : {
314 : 4286 : CKey key;
315 [ + + ]: 4286 : if (m_xonly) {
316 [ + - + - : 8561 : for (const auto& keyid : XOnlyPubKey(m_pubkey).GetKeyIDs()) {
+ + ]
317 [ + - ]: 5656 : arg.GetKey(keyid, key);
318 [ + - + + ]: 5656 : if (key.IsValid()) break;
319 [ + + ]: 5656 : }
320 : 2905 : } else {
321 [ + - + - ]: 1381 : arg.GetKey(m_pubkey.GetID(), key);
322 : : }
323 [ + - + + ]: 4286 : if (!key.IsValid()) return false;
324 [ + - ]: 2869 : ret = EncodeSecret(key);
325 : 2869 : return true;
326 : 4286 : }
327 : 46765 : bool ToNormalizedString(const SigningProvider& arg, std::string& ret, const DescriptorCache* cache) const override
328 : : {
329 : 46765 : ret = ToString(StringType::PUBLIC);
330 : 46765 : return true;
331 : : }
332 : 48657 : bool GetPrivKey(int pos, const SigningProvider& arg, CKey& key) const override
333 : : {
334 : 48657 : return arg.GetKey(m_pubkey.GetID(), key);
335 : : }
336 : 0 : std::optional<CPubKey> GetRootPubKey() const override
337 : : {
338 : 0 : return m_pubkey;
339 : : }
340 : 0 : std::optional<CExtPubKey> GetRootExtPubKey() const override
341 : : {
342 : 0 : return std::nullopt;
343 : : }
344 : 0 : std::unique_ptr<PubkeyProvider> Clone() const override
345 : : {
346 : 0 : return std::make_unique<ConstPubkeyProvider>(m_expr_index, m_pubkey, m_xonly);
347 : : }
348 : : };
349 : :
350 : : enum class DeriveType {
351 : : NO,
352 : : UNHARDENED,
353 : : HARDENED,
354 : : };
355 : :
356 : : /** An object representing a parsed extended public key in a descriptor. */
357 : : class BIP32PubkeyProvider final : public PubkeyProvider
358 : : {
359 : : // Root xpub, path, and final derivation step type being used, if any
360 : : CExtPubKey m_root_extkey;
361 : : KeyPath m_path;
362 : : DeriveType m_derive;
363 : : // Whether ' or h is used in harded derivation
364 : : bool m_apostrophe;
365 : :
366 : 155008 : bool GetExtKey(const SigningProvider& arg, CExtKey& ret) const
367 : : {
368 : 155008 : CKey key;
369 [ + - + - : 155008 : if (!arg.GetKey(m_root_extkey.pubkey.GetID(), key)) return false;
+ + ]
370 : 118849 : ret.nDepth = m_root_extkey.nDepth;
371 [ + - ]: 118849 : std::copy(m_root_extkey.vchFingerprint, m_root_extkey.vchFingerprint + sizeof(ret.vchFingerprint), ret.vchFingerprint);
372 : 118849 : ret.nChild = m_root_extkey.nChild;
373 : 118849 : ret.chaincode = m_root_extkey.chaincode;
374 [ + - ]: 118849 : ret.key = key;
375 : 118849 : return true;
376 : 155008 : }
377 : :
378 : : // Derives the last xprv
379 : 139307 : bool GetDerivedExtKey(const SigningProvider& arg, CExtKey& xprv, CExtKey& last_hardened) const
380 : : {
381 [ + + ]: 139307 : if (!GetExtKey(arg, xprv)) return false;
382 [ + + - - : 208041 : for (auto entry : m_path) {
+ ]
383 [ + - ]: 104174 : if (!xprv.Derive(xprv, entry)) return false;
384 [ + + ]: 104174 : if (entry >> 31) {
385 : 29760 : last_hardened = xprv;
386 : 29760 : }
387 [ - + ]: 104174 : }
388 : 103867 : return true;
389 : 139307 : }
390 : :
391 : 296706 : bool IsHardened() const
392 : : {
393 [ + + ]: 296706 : if (m_derive == DeriveType::HARDENED) return true;
394 [ + + - + : 548208 : for (auto entry : m_path) {
+ ]
395 [ + + ]: 265461 : if (entry >> 31) return true;
396 [ + + ]: 265461 : }
397 : 261498 : return false;
398 : 296706 : }
399 : :
400 : : public:
401 : 154620 : 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) {}
402 : 4710107 : bool IsRange() const override { return m_derive != DeriveType::NO; }
403 : 105472 : size_t GetSize() const override { return 33; }
404 : 2446220 : 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
405 : : {
406 : : // Info of parent of the to be derived pubkey
407 : 2446220 : KeyOriginInfo parent_info;
408 [ + - ]: 2446220 : CKeyID keyid = m_root_extkey.pubkey.GetID();
409 [ + - ]: 2446220 : std::copy(keyid.begin(), keyid.begin() + sizeof(parent_info.fingerprint), parent_info.fingerprint);
410 [ + - ]: 2446220 : parent_info.path = m_path;
411 : :
412 : : // Info of the derived key itself which is copied out upon successful completion
413 [ + - ]: 2446220 : KeyOriginInfo final_info_out_tmp = parent_info;
414 [ + + + - ]: 2446220 : if (m_derive == DeriveType::UNHARDENED) final_info_out_tmp.path.push_back((uint32_t)pos);
415 [ + + + - ]: 2446220 : if (m_derive == DeriveType::HARDENED) final_info_out_tmp.path.push_back(((uint32_t)pos) | 0x80000000L);
416 : :
417 : : // Derive keys or fetch them from cache
418 : 2446220 : CExtPubKey final_extkey = m_root_extkey;
419 : 2446220 : CExtPubKey parent_extkey = m_root_extkey;
420 [ + - ]: 2446220 : CExtPubKey last_hardened_extkey;
421 : 2446220 : bool der = true;
422 [ + + ]: 2446220 : if (read_cache) {
423 [ + - + + ]: 2149514 : if (!read_cache->GetCachedDerivedExtPubKey(m_expr_index, pos, final_extkey)) {
424 [ + + ]: 2142469 : if (m_derive == DeriveType::HARDENED) return false;
425 : : // Try to get the derivation parent
426 [ + - + + ]: 2139947 : if (!read_cache->GetCachedParentExtPubKey(m_expr_index, parent_extkey)) return false;
427 : 2111123 : final_extkey = parent_extkey;
428 [ + + + - ]: 2111123 : if (m_derive == DeriveType::UNHARDENED) der = parent_extkey.Derive(final_extkey, pos);
429 : 2111123 : }
430 [ + - + + ]: 2414874 : } else if (IsHardened()) {
431 [ + - ]: 35208 : CExtKey xprv;
432 [ + - ]: 35208 : CExtKey lh_xprv;
433 [ + - + + ]: 35208 : if (!GetDerivedExtKey(arg, xprv, lh_xprv)) return false;
434 [ + - ]: 17540 : parent_extkey = xprv.Neuter();
435 [ + + + - ]: 17540 : if (m_derive == DeriveType::UNHARDENED) der = xprv.Derive(xprv, pos);
436 [ + + + - ]: 17540 : if (m_derive == DeriveType::HARDENED) der = xprv.Derive(xprv, pos | 0x80000000UL);
437 [ + - ]: 17540 : final_extkey = xprv.Neuter();
438 [ + + ]: 17540 : if (lh_xprv.key.IsValid()) {
439 [ + - ]: 9293 : last_hardened_extkey = lh_xprv.Neuter();
440 : 9293 : }
441 [ + + ]: 35208 : } else {
442 [ + + - + ]: 503029 : for (auto entry : m_path) {
443 [ + - + - ]: 241531 : if (!parent_extkey.Derive(parent_extkey, entry)) return false;
444 [ - + ]: 241531 : }
445 : 261498 : final_extkey = parent_extkey;
446 [ + + + - ]: 261498 : if (m_derive == DeriveType::UNHARDENED) der = parent_extkey.Derive(final_extkey, pos);
447 [ + - ]: 261498 : assert(m_derive != DeriveType::HARDENED);
448 : : }
449 [ + - ]: 2397206 : if (!der) return false;
450 : :
451 [ + - ]: 2397206 : final_info_out = final_info_out_tmp;
452 : 2397206 : key_out = final_extkey.pubkey;
453 : :
454 [ + + ]: 2397206 : if (write_cache) {
455 : : // Only cache parent if there is any unhardened derivation
456 [ + + ]: 123331 : if (m_derive != DeriveType::HARDENED) {
457 [ + - ]: 114940 : write_cache->CacheParentExtPubKey(m_expr_index, parent_extkey);
458 : : // Cache last hardened xpub if we have it
459 [ + - + + ]: 114940 : if (last_hardened_extkey.pubkey.IsValid()) {
460 [ + - ]: 9149 : write_cache->CacheLastHardenedExtPubKey(m_expr_index, last_hardened_extkey);
461 : 9149 : }
462 [ + - ]: 123331 : } else if (final_info_out.path.size() > 0) {
463 [ + - ]: 8391 : write_cache->CacheDerivedExtPubKey(m_expr_index, pos, final_extkey);
464 : 8391 : }
465 : 123331 : }
466 : :
467 : 2397206 : return true;
468 : 2446220 : }
469 : 2417075 : std::string ToString(StringType type, bool normalized) const
470 : : {
471 : : // If StringType==COMPAT, always use the apostrophe to stay compatible with previous versions
472 [ + + + + ]: 2417075 : const bool use_apostrophe = (!normalized && m_apostrophe) || type == StringType::COMPAT;
473 [ + - + - ]: 2417075 : std::string ret = EncodeExtPubKey(m_root_extkey) + FormatHDKeypath(m_path, /*apostrophe=*/use_apostrophe);
474 [ + + ]: 2417075 : if (IsRange()) {
475 [ + - ]: 2237435 : ret += "/*";
476 [ + + + - ]: 2237435 : if (m_derive == DeriveType::HARDENED) ret += use_apostrophe ? '\'' : 'h';
477 : 2237435 : }
478 : 2417075 : return ret;
479 [ + - ]: 2417075 : }
480 : 2410562 : std::string ToString(StringType type=StringType::PUBLIC) const override
481 : : {
482 : 2410562 : return ToString(type, /*normalized=*/false);
483 : : }
484 : 15701 : bool ToPrivateString(const SigningProvider& arg, std::string& out) const override
485 : : {
486 : 15701 : CExtKey key;
487 [ + - + + ]: 15701 : if (!GetExtKey(arg, key)) return false;
488 [ + - + - : 14982 : out = EncodeExtKey(key) + FormatHDKeypath(m_path, /*apostrophe=*/m_apostrophe);
+ - ]
489 [ + + ]: 14982 : if (IsRange()) {
490 [ + - ]: 2529 : out += "/*";
491 [ + + + - ]: 2529 : if (m_derive == DeriveType::HARDENED) out += m_apostrophe ? '\'' : 'h';
492 : 2529 : }
493 : 14982 : return true;
494 : 15701 : }
495 : 89604 : bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache) const override
496 : : {
497 [ + + ]: 89604 : if (m_derive == DeriveType::HARDENED) {
498 : 6513 : out = ToString(StringType::PUBLIC, /*normalized=*/true);
499 : :
500 : 6513 : return true;
501 : : }
502 : : // Step backwards to find the last hardened step in the path
503 : 83091 : int i = (int)m_path.size() - 1;
504 [ + + ]: 152235 : for (; i >= 0; --i) {
505 [ + + ]: 78045 : if (m_path.at(i) >> 31) {
506 : 8901 : break;
507 : : }
508 : 69144 : }
509 : : // Either no derivation or all unhardened derivation
510 [ + + ]: 83091 : if (i == -1) {
511 : 74190 : out = ToString();
512 : 74190 : return true;
513 : : }
514 : : // Get the path to the last hardened stup
515 : 8901 : KeyOriginInfo origin;
516 : 8901 : int k = 0;
517 [ + + ]: 19389 : for (; k <= i; ++k) {
518 : : // Add to the path
519 [ + - + - ]: 10488 : origin.path.push_back(m_path.at(k));
520 : 10488 : }
521 : : // Build the remaining path
522 : 8901 : KeyPath end_path;
523 [ + + ]: 12287 : for (; k < (int)m_path.size(); ++k) {
524 [ + - + - ]: 3386 : end_path.push_back(m_path.at(k));
525 : 3386 : }
526 : : // Get the fingerprint
527 [ + - ]: 8901 : CKeyID id = m_root_extkey.pubkey.GetID();
528 [ + - ]: 8901 : std::copy(id.begin(), id.begin() + 4, origin.fingerprint);
529 : :
530 [ + - ]: 8901 : CExtPubKey xpub;
531 [ + - ]: 8901 : CExtKey lh_xprv;
532 : : // If we have the cache, just get the parent xpub
533 [ + + ]: 8901 : if (cache != nullptr) {
534 [ + - ]: 61 : cache->GetCachedLastHardenedExtPubKey(m_expr_index, xpub);
535 : 61 : }
536 [ + - + + ]: 8901 : if (!xpub.pubkey.IsValid()) {
537 : : // Cache miss, or nor cache, or need privkey
538 [ + - ]: 8857 : CExtKey xprv;
539 [ + - + + ]: 8857 : if (!GetDerivedExtKey(arg, xprv, lh_xprv)) return false;
540 [ + - ]: 8759 : xpub = lh_xprv.Neuter();
541 [ + + ]: 8857 : }
542 [ + - + - ]: 8803 : assert(xpub.pubkey.IsValid());
543 : :
544 : : // Build the string
545 [ + - + - : 8803 : std::string origin_str = HexStr(origin.fingerprint) + FormatHDKeypath(origin.path);
+ - ]
546 [ + - + - : 8803 : out = "[" + origin_str + "]" + EncodeExtPubKey(xpub) + FormatHDKeypath(end_path);
+ - + - +
- + - ]
547 [ + + ]: 8803 : if (IsRange()) {
548 [ + - ]: 82 : out += "/*";
549 [ + - ]: 82 : assert(m_derive == DeriveType::UNHARDENED);
550 : 82 : }
551 : 8803 : return true;
552 : 89604 : }
553 : 95242 : bool GetPrivKey(int pos, const SigningProvider& arg, CKey& key) const override
554 : : {
555 : 95242 : CExtKey extkey;
556 [ + - ]: 95242 : CExtKey dummy;
557 [ + - + + ]: 95242 : if (!GetDerivedExtKey(arg, extkey, dummy)) return false;
558 [ + + + - : 77568 : if (m_derive == DeriveType::UNHARDENED && !extkey.Derive(extkey, pos)) return false;
+ - ]
559 [ + + + - : 77568 : if (m_derive == DeriveType::HARDENED && !extkey.Derive(extkey, pos | 0x80000000UL)) return false;
+ - ]
560 [ + - ]: 77568 : key = extkey.key;
561 : 77568 : return true;
562 : 95242 : }
563 : 0 : std::optional<CPubKey> GetRootPubKey() const override
564 : : {
565 : 0 : return std::nullopt;
566 : : }
567 : 0 : std::optional<CExtPubKey> GetRootExtPubKey() const override
568 : : {
569 : 0 : return m_root_extkey;
570 : : }
571 : 0 : std::unique_ptr<PubkeyProvider> Clone() const override
572 : : {
573 : 0 : return std::make_unique<BIP32PubkeyProvider>(m_expr_index, m_root_extkey, m_path, m_derive, m_apostrophe);
574 : : }
575 : : };
576 : :
577 : : /** Base class for all Descriptor implementations. */
578 : : class DescriptorImpl : public Descriptor
579 : : {
580 : : protected:
581 : : //! Public key arguments for this descriptor (size 1 for PK, PKH, WPKH; any size for WSH and Multisig).
582 : : const std::vector<std::unique_ptr<PubkeyProvider>> m_pubkey_args;
583 : : //! The string name of the descriptor function.
584 : : const std::string m_name;
585 : :
586 : : //! The sub-descriptor arguments (empty for everything but SH and WSH).
587 : : //! In doc/descriptors.m this is referred to as SCRIPT expressions sh(SCRIPT)
588 : : //! and wsh(SCRIPT), and distinct from KEY expressions and ADDR expressions.
589 : : //! Subdescriptors can only ever generate a single script.
590 : : const std::vector<std::unique_ptr<DescriptorImpl>> m_subdescriptor_args;
591 : :
592 : : //! Return a serialization of anything except pubkey and script arguments, to be prepended to those.
593 [ + - ]: 3487255 : virtual std::string ToStringExtra() const { return ""; }
594 : :
595 : : /** A helper function to construct the scripts for this descriptor.
596 : : *
597 : : * This function is invoked once by ExpandHelper.
598 : : *
599 : : * @param pubkeys The evaluations of the m_pubkey_args field.
600 : : * @param scripts The evaluations of m_subdescriptor_args (one for each m_subdescriptor_args element).
601 : : * @param out A FlatSigningProvider to put scripts or public keys in that are necessary to the solver.
602 : : * The origin info of the provided pubkeys is automatically added.
603 : : * @return A vector with scriptPubKeys for this descriptor.
604 : : */
605 : : virtual std::vector<CScript> MakeScripts(const std::vector<CPubKey>& pubkeys, Span<const CScript> scripts, FlatSigningProvider& out) const = 0;
606 : :
607 : : public:
608 [ + - ]: 8092003 : DescriptorImpl(std::vector<std::unique_ptr<PubkeyProvider>> pubkeys, const std::string& name) : m_pubkey_args(std::move(pubkeys)), m_name(name), m_subdescriptor_args() {}
609 [ + - + - ]: 5622171 : 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))) {}
610 [ + - ]: 639861 : 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)) {}
611 : :
612 : : enum class StringType
613 : : {
614 : : PUBLIC,
615 : : PRIVATE,
616 : : NORMALIZED,
617 : : COMPAT, // string calculation that mustn't change over time to stay compatible with previous software versions
618 : : };
619 : :
620 : : // NOLINTNEXTLINE(misc-no-recursion)
621 : 5714 : bool IsSolvable() const override
622 : : {
623 [ + + - - : 9960 : for (const auto& arg : m_subdescriptor_args) {
+ ]
624 [ + - ]: 4246 : if (!arg->IsSolvable()) return false;
625 [ - + ]: 4246 : }
626 : 5714 : return true;
627 : 5714 : }
628 : :
629 : : // NOLINTNEXTLINE(misc-no-recursion)
630 : 3437564 : bool IsRange() const final
631 : : {
632 [ + + + + ]: 5775052 : for (const auto& pubkey : m_pubkey_args) {
633 [ + + ]: 2337488 : if (pubkey->IsRange()) return true;
634 [ + + ]: 2337488 : }
635 [ + + + + ]: 2465238 : for (const auto& arg : m_subdescriptor_args) {
636 [ + + ]: 1221145 : if (arg->IsRange()) return true;
637 [ + + ]: 1221145 : }
638 : 33074 : return false;
639 : 3437564 : }
640 : :
641 : : // NOLINTNEXTLINE(misc-no-recursion)
642 : 4292855 : virtual bool ToStringSubScriptHelper(const SigningProvider* arg, std::string& ret, const StringType type, const DescriptorCache* cache = nullptr) const
643 : : {
644 : 4292855 : size_t pos = 0;
645 [ + + + + ]: 5519232 : for (const auto& scriptarg : m_subdescriptor_args) {
646 [ + - ]: 1226377 : if (pos++) ret += ",";
647 : 1226377 : std::string tmp;
648 [ + - + + ]: 1226377 : if (!scriptarg->ToStringHelper(arg, tmp, type, cache)) return false;
649 [ + - ]: 1225342 : ret += tmp;
650 [ + + + + ]: 1226377 : }
651 : 4291820 : return true;
652 : 4292855 : }
653 : :
654 : : // NOLINTNEXTLINE(misc-no-recursion)
655 : 4744447 : virtual bool ToStringHelper(const SigningProvider* arg, std::string& out, const StringType type, const DescriptorCache* cache = nullptr) const
656 : : {
657 : 4744447 : std::string extra = ToStringExtra();
658 : 4744447 : size_t pos = extra.size() > 0 ? 1 : 0;
659 [ + - + - ]: 4744447 : std::string ret = m_name + "(" + extra;
660 [ + + + + ]: 7352881 : for (const auto& pubkey : m_pubkey_args) {
661 [ + + + - ]: 2608434 : if (pos++) ret += ",";
662 : 2608434 : std::string tmp;
663 [ + + - + : 2608434 : switch (type) {
+ ]
664 : : case StringType::NORMALIZED:
665 [ + - + + ]: 136369 : if (!pubkey->ToNormalizedString(*arg, tmp, cache)) return false;
666 : 136271 : break;
667 : : case StringType::PRIVATE:
668 [ + - + + ]: 17923 : if (!pubkey->ToPrivateString(*arg, tmp)) return false;
669 : 16434 : break;
670 : : case StringType::PUBLIC:
671 [ - + ]: 2419617 : tmp = pubkey->ToString();
672 : 2419617 : break;
673 : : case StringType::COMPAT:
674 [ - + ]: 34525 : tmp = pubkey->ToString(PubkeyProvider::StringType::COMPAT);
675 : 34525 : break;
676 : : }
677 [ + - ]: 2606847 : ret += tmp;
678 [ + + + + ]: 2608434 : }
679 : 4742860 : std::string subscript;
680 [ + - + + ]: 4742860 : if (!ToStringSubScriptHelper(arg, subscript, type, cache)) return false;
681 [ + + + + : 4741508 : if (pos && subscript.size()) ret += ',';
+ - ]
682 [ + - + - ]: 4741508 : out = std::move(ret) + std::move(subscript) + ")";
683 : 4741508 : return true;
684 : 4744447 : }
685 : :
686 : 3510978 : std::string ToString(bool compat_format) const final
687 : : {
688 : 3510978 : std::string ret;
689 [ + - ]: 3510978 : ToStringHelper(nullptr, ret, compat_format ? StringType::COMPAT : StringType::PUBLIC);
690 [ + - ]: 3510978 : return AddChecksum(ret);
691 : 3510978 : }
692 : :
693 : 2937 : bool ToPrivateString(const SigningProvider& arg, std::string& out) const override
694 : : {
695 : 2937 : bool ret = ToStringHelper(&arg, out, StringType::PRIVATE);
696 : 2937 : out = AddChecksum(out);
697 : 5874 : return ret;
698 : 2937 : }
699 : :
700 : 4945 : bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache) const override final
701 : : {
702 : 4945 : bool ret = ToStringHelper(&arg, out, StringType::NORMALIZED, cache);
703 : 4945 : out = AddChecksum(out);
704 : 9890 : return ret;
705 : 4945 : }
706 : :
707 : : // NOLINTNEXTLINE(misc-no-recursion)
708 : 3254435 : bool ExpandHelper(int pos, const SigningProvider& arg, const DescriptorCache* read_cache, std::vector<CScript>& output_scripts, FlatSigningProvider& out, DescriptorCache* write_cache) const
709 : : {
710 : 3254435 : std::vector<std::pair<CPubKey, KeyOriginInfo>> entries;
711 [ + - ]: 3254435 : entries.reserve(m_pubkey_args.size());
712 : :
713 : : // Construct temporary data in `entries`, `subscripts`, and `subprovider` to avoid producing output in case of failure.
714 [ + + + + ]: 5634856 : for (const auto& p : m_pubkey_args) {
715 [ + - ]: 2380421 : entries.emplace_back();
716 [ + - + + ]: 2380421 : if (!p->GetPubKey(pos, arg, entries.back().first, entries.back().second, read_cache, write_cache)) return false;
717 [ + + ]: 2380421 : }
718 : 3222433 : std::vector<CScript> subscripts;
719 : 3222433 : FlatSigningProvider subprovider;
720 [ + + + + ]: 4380463 : for (const auto& subarg : m_subdescriptor_args) {
721 : 1158030 : std::vector<CScript> outscripts;
722 [ + - + + ]: 1158030 : if (!subarg->ExpandHelper(pos, arg, read_cache, outscripts, subprovider, write_cache)) return false;
723 [ + - ]: 1150008 : assert(outscripts.size() == 1);
724 [ + - ]: 1150008 : subscripts.emplace_back(std::move(outscripts[0]));
725 [ + + + + ]: 1158030 : }
726 [ + - ]: 3214411 : out.Merge(std::move(subprovider));
727 : :
728 : 3214411 : std::vector<CPubKey> pubkeys;
729 [ + - ]: 3214411 : pubkeys.reserve(entries.size());
730 [ + + ]: 5551882 : for (auto& entry : entries) {
731 [ - + ]: 2337471 : pubkeys.push_back(entry.first);
732 [ - + - + : 2337471 : out.origins.emplace(entry.first.GetID(), std::make_pair<CPubKey, KeyOriginInfo>(CPubKey(entry.first), std::move(entry.second)));
+ - ]
733 : 2337471 : }
734 : :
735 [ + - + - ]: 3214411 : output_scripts = MakeScripts(pubkeys, Span{subscripts}, out);
736 : 3214411 : return true;
737 : 3254435 : }
738 : :
739 : 35004 : bool Expand(int pos, const SigningProvider& provider, std::vector<CScript>& output_scripts, FlatSigningProvider& out, DescriptorCache* write_cache = nullptr) const final
740 : : {
741 : 35004 : return ExpandHelper(pos, provider, nullptr, output_scripts, out, write_cache);
742 : : }
743 : :
744 : 2061401 : bool ExpandFromCache(int pos, const DescriptorCache& read_cache, std::vector<CScript>& output_scripts, FlatSigningProvider& out) const final
745 : : {
746 : 2061401 : return ExpandHelper(pos, DUMMY_SIGNING_PROVIDER, &read_cache, output_scripts, out, nullptr);
747 : : }
748 : :
749 : : // NOLINTNEXTLINE(misc-no-recursion)
750 : 8740 : void ExpandPrivate(int pos, const SigningProvider& provider, FlatSigningProvider& out) const final
751 : : {
752 [ + + ]: 152639 : for (const auto& p : m_pubkey_args) {
753 : 143899 : CKey key;
754 [ + - + + ]: 143899 : if (!p->GetPrivKey(pos, provider, key)) continue;
755 [ + - + - : 108273 : out.keys.emplace(key.GetPubKey().GetID(), key);
+ - ]
756 [ + + - + : 143899 : }
+ ]
757 [ + + ]: 12966 : for (const auto& arg : m_subdescriptor_args) {
758 : 4226 : arg->ExpandPrivate(pos, provider, out);
759 : 4226 : }
760 : 8740 : }
761 : :
762 : 2275 : std::optional<OutputType> GetOutputType() const override { return std::nullopt; }
763 : :
764 : 0 : std::optional<int64_t> ScriptSize() const override { return {}; }
765 : :
766 : : /** A helper for MaxSatisfactionWeight.
767 : : *
768 : : * @param use_max_sig Whether to assume ECDSA signatures will have a high-r.
769 : : * @return The maximum size of the satisfaction in raw bytes (with no witness meaning).
770 : : */
771 : 0 : virtual std::optional<int64_t> MaxSatSize(bool use_max_sig) const { return {}; }
772 : :
773 : 794 : std::optional<int64_t> MaxSatisfactionWeight(bool) const override { return {}; }
774 : :
775 : 397 : std::optional<int64_t> MaxSatisfactionElems() const override { return {}; }
776 : :
777 : : // NOLINTNEXTLINE(misc-no-recursion)
778 : 0 : void GetPubKeys(std::set<CPubKey>& pubkeys, std::set<CExtPubKey>& ext_pubs) const override
779 : : {
780 [ # # ]: 0 : for (const auto& p : m_pubkey_args) {
781 : 0 : std::optional<CPubKey> pub = p->GetRootPubKey();
782 [ # # ]: 0 : if (pub) pubkeys.insert(*pub);
783 : 0 : std::optional<CExtPubKey> ext_pub = p->GetRootExtPubKey();
784 [ # # ]: 0 : if (ext_pub) ext_pubs.insert(*ext_pub);
785 : 0 : }
786 [ # # ]: 0 : for (const auto& arg : m_subdescriptor_args) {
787 : 0 : arg->GetPubKeys(pubkeys, ext_pubs);
788 : 0 : }
789 : 0 : }
790 : :
791 : : virtual std::unique_ptr<DescriptorImpl> Clone() const = 0;
792 : : };
793 : :
794 : : /** A parsed addr(A) descriptor. */
795 : : class AddressDescriptor final : public DescriptorImpl
796 : : {
797 : : const CTxDestination m_destination;
798 : : protected:
799 : 260472 : std::string ToStringExtra() const override { return EncodeDestination(m_destination); }
800 [ # # ]: 0 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, Span<const CScript>, FlatSigningProvider&) const override { return Vector(GetScriptForDestination(m_destination)); }
801 : : public:
802 [ + - + - ]: 260648 : AddressDescriptor(CTxDestination destination) : DescriptorImpl({}, "addr"), m_destination(std::move(destination)) {}
803 : 0 : bool IsSolvable() const final { return false; }
804 : :
805 : 0 : std::optional<OutputType> GetOutputType() const override
806 : : {
807 : 0 : return OutputTypeFromDestination(m_destination);
808 : : }
809 : 0 : bool IsSingleType() const final { return true; }
810 : 0 : bool ToPrivateString(const SigningProvider& arg, std::string& out) const final { return false; }
811 : :
812 [ # # ]: 0 : std::optional<int64_t> ScriptSize() const override { return GetScriptForDestination(m_destination).size(); }
813 : 0 : std::unique_ptr<DescriptorImpl> Clone() const override
814 : : {
815 : 0 : return std::make_unique<AddressDescriptor>(m_destination);
816 : : }
817 : : };
818 : :
819 : : /** A parsed raw(H) descriptor. */
820 : : class RawDescriptor final : public DescriptorImpl
821 : : {
822 : : const CScript m_script;
823 : : protected:
824 : 971996 : std::string ToStringExtra() const override { return HexStr(m_script); }
825 : 3836 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, Span<const CScript>, FlatSigningProvider&) const override { return Vector(m_script); }
826 : : public:
827 [ + - + - ]: 967209 : RawDescriptor(CScript script) : DescriptorImpl({}, "raw"), m_script(std::move(script)) {}
828 : 383 : bool IsSolvable() const final { return false; }
829 : :
830 : 1578 : std::optional<OutputType> GetOutputType() const override
831 : : {
832 : 1578 : CTxDestination dest;
833 [ + - ]: 1578 : ExtractDestination(m_script, dest);
834 [ + - ]: 1578 : return OutputTypeFromDestination(dest);
835 : 1578 : }
836 : 2698 : bool IsSingleType() const final { return true; }
837 : 630 : bool ToPrivateString(const SigningProvider& arg, std::string& out) const final { return false; }
838 : :
839 : 379 : std::optional<int64_t> ScriptSize() const override { return m_script.size(); }
840 : :
841 : 0 : std::unique_ptr<DescriptorImpl> Clone() const override
842 : : {
843 : 0 : return std::make_unique<RawDescriptor>(m_script);
844 : : }
845 : : };
846 : :
847 : : /** A parsed pk(P) descriptor. */
848 : : class PKDescriptor final : public DescriptorImpl
849 : : {
850 : : private:
851 : : const bool m_xonly;
852 : : protected:
853 : 8294 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript>, FlatSigningProvider&) const override
854 : : {
855 [ + + ]: 8294 : if (m_xonly) {
856 [ + - + - : 3766 : CScript script = CScript() << ToByteVector(XOnlyPubKey(keys[0])) << OP_CHECKSIG;
+ - + - +
- ]
857 [ + - ]: 3766 : return Vector(std::move(script));
858 : 3766 : } else {
859 [ + - ]: 4528 : return Vector(GetScriptForRawPubKey(keys[0]));
860 : : }
861 : 8294 : }
862 : : public:
863 [ + - + - ]: 30971 : PKDescriptor(std::unique_ptr<PubkeyProvider> prov, bool xonly = false) : DescriptorImpl(Vector(std::move(prov)), "pk"), m_xonly(xonly) {}
864 : 154 : bool IsSingleType() const final { return true; }
865 : :
866 : 70 : std::optional<int64_t> ScriptSize() const override {
867 [ - + ]: 70 : return 1 + (m_xonly ? 32 : m_pubkey_args[0]->GetSize()) + 1;
868 : : }
869 : :
870 : 126 : std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
871 : 126 : const auto ecdsa_sig_size = use_max_sig ? 72 : 71;
872 [ - + ]: 126 : return 1 + (m_xonly ? 65 : ecdsa_sig_size);
873 : 126 : }
874 : :
875 : 102 : std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
876 : 102 : return *MaxSatSize(use_max_sig) * WITNESS_SCALE_FACTOR;
877 : : }
878 : :
879 : 63 : std::optional<int64_t> MaxSatisfactionElems() const override { return 1; }
880 : :
881 : 0 : std::unique_ptr<DescriptorImpl> Clone() const override
882 : : {
883 [ # # ]: 0 : return std::make_unique<PKDescriptor>(m_pubkey_args.at(0)->Clone(), m_xonly);
884 : 0 : }
885 : : };
886 : :
887 : : /** A parsed pkh(P) descriptor. */
888 : : class PKHDescriptor final : public DescriptorImpl
889 : : {
890 : : protected:
891 : 415052 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript>, FlatSigningProvider& out) const override
892 : : {
893 : 415052 : CKeyID id = keys[0].GetID();
894 : 415052 : out.pubkeys.emplace(id, keys[0]);
895 [ + - + - ]: 415052 : return Vector(GetScriptForDestination(PKHash(id)));
896 : 415052 : }
897 : : public:
898 [ + - + - ]: 948679 : PKHDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "pkh") {}
899 : 1106926 : std::optional<OutputType> GetOutputType() const override { return OutputType::LEGACY; }
900 : 324222 : bool IsSingleType() const final { return true; }
901 : :
902 : 39 : std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 1 + 20 + 1 + 1; }
903 : :
904 : 873033 : std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
905 : 873033 : const auto sig_size = use_max_sig ? 72 : 71;
906 : 873033 : return 1 + sig_size + 1 + m_pubkey_args[0]->GetSize();
907 : 873033 : }
908 : :
909 : 873001 : std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
910 : 873001 : return *MaxSatSize(use_max_sig) * WITNESS_SCALE_FACTOR;
911 : : }
912 : :
913 : 873009 : std::optional<int64_t> MaxSatisfactionElems() const override { return 2; }
914 : :
915 : 0 : std::unique_ptr<DescriptorImpl> Clone() const override
916 : : {
917 [ # # ]: 0 : return std::make_unique<PKHDescriptor>(m_pubkey_args.at(0)->Clone());
918 : 0 : }
919 : : };
920 : :
921 : : /** A parsed wpkh(P) descriptor. */
922 : : class WPKHDescriptor final : public DescriptorImpl
923 : : {
924 : : protected:
925 : 1209044 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript>, FlatSigningProvider& out) const override
926 : : {
927 : 1209044 : CKeyID id = keys[0].GetID();
928 : 1209044 : out.pubkeys.emplace(id, keys[0]);
929 [ + - + - ]: 1209044 : return Vector(GetScriptForDestination(WitnessV0KeyHash(id)));
930 : 1209044 : }
931 : : public:
932 [ + - + - ]: 5847487 : WPKHDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "wpkh") {}
933 : 11868819 : std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32; }
934 : 56321 : bool IsSingleType() const final { return true; }
935 : :
936 : 5577806 : std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 20; }
937 : :
938 : 5799540 : std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
939 : 5799540 : const auto sig_size = use_max_sig ? 72 : 71;
940 : 5799540 : return (1 + sig_size + 1 + 33);
941 : 5799540 : }
942 : :
943 : 221741 : std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
944 : 221741 : return MaxSatSize(use_max_sig);
945 : : }
946 : :
947 : 5799525 : std::optional<int64_t> MaxSatisfactionElems() const override { return 2; }
948 : :
949 : 0 : std::unique_ptr<DescriptorImpl> Clone() const override
950 : : {
951 [ # # ]: 0 : return std::make_unique<WPKHDescriptor>(m_pubkey_args.at(0)->Clone());
952 : 0 : }
953 : : };
954 : :
955 : : /** A parsed combo(P) descriptor. */
956 : : class ComboDescriptor final : public DescriptorImpl
957 : : {
958 : : protected:
959 : 1297 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript>, FlatSigningProvider& out) const override
960 : : {
961 : 1297 : std::vector<CScript> ret;
962 [ + - ]: 1297 : CKeyID id = keys[0].GetID();
963 [ + - ]: 1297 : out.pubkeys.emplace(id, keys[0]);
964 [ + - + - ]: 1297 : ret.emplace_back(GetScriptForRawPubKey(keys[0])); // P2PK
965 [ + - + - : 1297 : ret.emplace_back(GetScriptForDestination(PKHash(id))); // P2PKH
+ - ]
966 [ + + ]: 1297 : if (keys[0].IsCompressed()) {
967 [ + - + - ]: 1240 : CScript p2wpkh = GetScriptForDestination(WitnessV0KeyHash(id));
968 [ + - + - ]: 1240 : out.scripts.emplace(CScriptID(p2wpkh), p2wpkh);
969 [ + - ]: 1240 : ret.emplace_back(p2wpkh);
970 [ + - + - : 1240 : ret.emplace_back(GetScriptForDestination(ScriptHash(p2wpkh))); // P2SH-P2WPKH
+ - ]
971 : 1240 : }
972 : 1297 : return ret;
973 [ + - ]: 1297 : }
974 : : public:
975 [ + - + - ]: 740 : ComboDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "combo") {}
976 : 210 : bool IsSingleType() const final { return false; }
977 : 0 : std::unique_ptr<DescriptorImpl> Clone() const override
978 : : {
979 [ # # ]: 0 : return std::make_unique<ComboDescriptor>(m_pubkey_args.at(0)->Clone());
980 : 0 : }
981 : : };
982 : :
983 : : /** A parsed multi(...) or sortedmulti(...) descriptor */
984 : : class MultisigDescriptor final : public DescriptorImpl
985 : : {
986 : : const int m_threshold;
987 : : const bool m_sorted;
988 : : protected:
989 : 22527 : std::string ToStringExtra() const override { return strprintf("%i", m_threshold); }
990 : 2196 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript>, FlatSigningProvider&) const override {
991 [ + + ]: 2196 : if (m_sorted) {
992 : 853 : std::vector<CPubKey> sorted_keys(keys);
993 [ + - ]: 853 : std::sort(sorted_keys.begin(), sorted_keys.end());
994 [ + - + - ]: 853 : return Vector(GetScriptForMultisig(m_threshold, sorted_keys));
995 : 853 : }
996 [ + - ]: 1343 : return Vector(GetScriptForMultisig(m_threshold, keys));
997 : 2196 : }
998 : : public:
999 [ + - + - ]: 20898 : 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) {}
1000 : 510 : bool IsSingleType() const final { return true; }
1001 : :
1002 : 1170 : std::optional<int64_t> ScriptSize() const override {
1003 : 1170 : const auto n_keys = m_pubkey_args.size();
1004 : 14061 : auto op = [](int64_t acc, const std::unique_ptr<PubkeyProvider>& pk) { return acc + 1 + pk->GetSize();};
1005 : 1170 : const auto pubkeys_size{std::accumulate(m_pubkey_args.begin(), m_pubkey_args.end(), int64_t{0}, op)};
1006 [ + - + - : 1170 : return 1 + BuildScript(n_keys).size() + BuildScript(m_threshold).size() + pubkeys_size;
+ - ]
1007 : 1170 : }
1008 : :
1009 : 1254 : std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
1010 : 1254 : const auto sig_size = use_max_sig ? 72 : 71;
1011 : 1254 : return (1 + (1 + sig_size) * m_threshold);
1012 : 1254 : }
1013 : :
1014 : 156 : std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
1015 : 156 : return *MaxSatSize(use_max_sig) * WITNESS_SCALE_FACTOR;
1016 : : }
1017 : :
1018 : 627 : std::optional<int64_t> MaxSatisfactionElems() const override { return 1 + m_threshold; }
1019 : :
1020 : 0 : std::unique_ptr<DescriptorImpl> Clone() const override
1021 : : {
1022 : 0 : std::vector<std::unique_ptr<PubkeyProvider>> providers;
1023 [ # # ]: 0 : providers.reserve(m_pubkey_args.size());
1024 [ # # ]: 0 : std::transform(m_pubkey_args.begin(), m_pubkey_args.end(), providers.begin(), [](const std::unique_ptr<PubkeyProvider>& p) { return p->Clone(); });
1025 [ # # ]: 0 : return std::make_unique<MultisigDescriptor>(m_threshold, std::move(providers), m_sorted);
1026 : 0 : }
1027 : : };
1028 : :
1029 : : /** A parsed (sorted)multi_a(...) descriptor. Always uses x-only pubkeys. */
1030 : : class MultiADescriptor final : public DescriptorImpl
1031 : : {
1032 : : const int m_threshold;
1033 : : const bool m_sorted;
1034 : : protected:
1035 : 2197 : std::string ToStringExtra() const override { return strprintf("%i", m_threshold); }
1036 : 1878 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript>, FlatSigningProvider&) const override {
1037 : 1878 : CScript ret;
1038 : 1878 : std::vector<XOnlyPubKey> xkeys;
1039 [ + - ]: 1878 : xkeys.reserve(keys.size());
1040 [ + + + - ]: 243724 : for (const auto& key : keys) xkeys.emplace_back(key);
1041 [ + + + - ]: 1878 : if (m_sorted) std::sort(xkeys.begin(), xkeys.end());
1042 [ + - + - : 1878 : ret << ToByteVector(xkeys[0]) << OP_CHECKSIG;
+ - ]
1043 [ + + ]: 241846 : for (size_t i = 1; i < keys.size(); ++i) {
1044 [ + - + - : 239968 : ret << ToByteVector(xkeys[i]) << OP_CHECKSIGADD;
+ - ]
1045 : 239968 : }
1046 [ + - + - ]: 1878 : ret << m_threshold << OP_NUMEQUAL;
1047 [ + - ]: 1878 : return Vector(std::move(ret));
1048 : 1878 : }
1049 : : public:
1050 [ + - + - ]: 2506 : 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) {}
1051 : 0 : bool IsSingleType() const final { return true; }
1052 : :
1053 : 0 : std::optional<int64_t> ScriptSize() const override {
1054 : 0 : const auto n_keys = m_pubkey_args.size();
1055 [ # # ]: 0 : return (1 + 32 + 1) * n_keys + BuildScript(m_threshold).size() + 1;
1056 : 0 : }
1057 : :
1058 : 0 : std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
1059 : 0 : return (1 + 65) * m_threshold + (m_pubkey_args.size() - m_threshold);
1060 : : }
1061 : :
1062 : 0 : std::optional<int64_t> MaxSatisfactionElems() const override { return m_pubkey_args.size(); }
1063 : :
1064 : 0 : std::unique_ptr<DescriptorImpl> Clone() const override
1065 : : {
1066 : 0 : std::vector<std::unique_ptr<PubkeyProvider>> providers;
1067 [ # # ]: 0 : providers.reserve(m_pubkey_args.size());
1068 [ # # ]: 0 : for (const auto& arg : m_pubkey_args) {
1069 [ # # # # ]: 0 : providers.push_back(arg->Clone());
1070 : 0 : }
1071 [ # # ]: 0 : return std::make_unique<MultiADescriptor>(m_threshold, std::move(providers), m_sorted);
1072 : 0 : }
1073 : : };
1074 : :
1075 : : /** A parsed sh(...) descriptor. */
1076 : : class SHDescriptor final : public DescriptorImpl
1077 : : {
1078 : : protected:
1079 : 1138025 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, Span<const CScript> scripts, FlatSigningProvider& out) const override
1080 : : {
1081 [ + - + - ]: 1138025 : auto ret = Vector(GetScriptForDestination(ScriptHash(scripts[0])));
1082 [ - + + - : 1138025 : if (ret.size()) out.scripts.emplace(CScriptID(scripts[0]), scripts[0]);
+ - ]
1083 : 1138025 : return ret;
1084 [ + - ]: 1138025 : }
1085 : :
1086 : 11616163 : bool IsSegwit() const { return m_subdescriptor_args[0]->GetOutputType() == OutputType::BECH32; }
1087 : :
1088 : : public:
1089 [ + - + - ]: 5618644 : SHDescriptor(std::unique_ptr<DescriptorImpl> desc) : DescriptorImpl({}, std::move(desc), "sh") {}
1090 : :
1091 : 6037430 : std::optional<OutputType> GetOutputType() const override
1092 : : {
1093 [ + - ]: 6037430 : assert(m_subdescriptor_args.size() == 1);
1094 [ + + ]: 6037430 : if (IsSegwit()) return OutputType::P2SH_SEGWIT;
1095 : 1056 : return OutputType::LEGACY;
1096 : 6037430 : }
1097 : 845415 : bool IsSingleType() const final { return true; }
1098 : :
1099 : 457 : std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 20 + 1; }
1100 : :
1101 : 5578733 : std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
1102 [ - + - + : 11157466 : if (const auto sat_size = m_subdescriptor_args[0]->MaxSatSize(use_max_sig)) {
- ]
1103 [ + - + - ]: 11157466 : if (const auto subscript_size = m_subdescriptor_args[0]->ScriptSize()) {
1104 : : // The subscript is never witness data.
1105 : 5578733 : const auto subscript_weight = (1 + *subscript_size) * WITNESS_SCALE_FACTOR;
1106 : : // The weight depends on whether the inner descriptor is satisfied using the witness stack.
1107 [ + + ]: 5578733 : if (IsSegwit()) return subscript_weight + *sat_size;
1108 : 626 : return subscript_weight + *sat_size * WITNESS_SCALE_FACTOR;
1109 : 5578733 : }
1110 : 0 : }
1111 : 0 : return {};
1112 : 5578733 : }
1113 : :
1114 : 5578260 : std::optional<int64_t> MaxSatisfactionElems() const override {
1115 [ + - - + : 5578260 : if (const auto sub_elems = m_subdescriptor_args[0]->MaxSatisfactionElems()) return 1 + *sub_elems;
- ]
1116 : 0 : return {};
1117 : 5578260 : }
1118 : :
1119 : 0 : std::unique_ptr<DescriptorImpl> Clone() const override
1120 : : {
1121 [ # # ]: 0 : return std::make_unique<SHDescriptor>(m_subdescriptor_args.at(0)->Clone());
1122 : 0 : }
1123 : : };
1124 : :
1125 : : /** A parsed wsh(...) descriptor. */
1126 : : class WSHDescriptor final : public DescriptorImpl
1127 : : {
1128 : : protected:
1129 : 5115 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, Span<const CScript> scripts, FlatSigningProvider& out) const override
1130 : : {
1131 [ + - + - ]: 5115 : auto ret = Vector(GetScriptForDestination(WitnessV0ScriptHash(scripts[0])));
1132 [ - + + - : 5115 : if (ret.size()) out.scripts.emplace(CScriptID(scripts[0]), scripts[0]);
+ - ]
1133 : 5115 : return ret;
1134 [ + - ]: 5115 : }
1135 : : public:
1136 [ + - + - ]: 3527 : WSHDescriptor(std::unique_ptr<DescriptorImpl> desc) : DescriptorImpl({}, std::move(desc), "wsh") {}
1137 : 3849 : std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32; }
1138 : 4096 : bool IsSingleType() const final { return true; }
1139 : :
1140 : 1108 : std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
1141 : :
1142 : 1936 : std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
1143 [ - + - + : 3872 : if (const auto sat_size = m_subdescriptor_args[0]->MaxSatSize(use_max_sig)) {
- ]
1144 [ + - + - ]: 3872 : if (const auto subscript_size = m_subdescriptor_args[0]->ScriptSize()) {
1145 : 1936 : return GetSizeOfCompactSize(*subscript_size) + *subscript_size + *sat_size;
1146 : : }
1147 : 0 : }
1148 : 0 : return {};
1149 : 1936 : }
1150 : :
1151 : 1628 : std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
1152 : 1628 : return MaxSatSize(use_max_sig);
1153 : : }
1154 : :
1155 : 968 : std::optional<int64_t> MaxSatisfactionElems() const override {
1156 [ + - - + : 968 : if (const auto sub_elems = m_subdescriptor_args[0]->MaxSatisfactionElems()) return 1 + *sub_elems;
- ]
1157 : 0 : return {};
1158 : 968 : }
1159 : :
1160 : 0 : std::unique_ptr<DescriptorImpl> Clone() const override
1161 : : {
1162 [ # # ]: 0 : return std::make_unique<WSHDescriptor>(m_subdescriptor_args.at(0)->Clone());
1163 : 0 : }
1164 : : };
1165 : :
1166 : : /** A parsed tr(...) descriptor. */
1167 : : class TRDescriptor final : public DescriptorImpl
1168 : : {
1169 : : std::vector<int> m_depths;
1170 : : protected:
1171 : 423802 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript> scripts, FlatSigningProvider& out) const override
1172 : : {
1173 : 423802 : TaprootBuilder builder;
1174 [ + - ]: 423802 : assert(m_depths.size() == scripts.size());
1175 [ + + ]: 430670 : for (size_t pos = 0; pos < m_depths.size(); ++pos) {
1176 [ + - + - ]: 6868 : builder.Add(m_depths[pos], scripts[pos], TAPROOT_LEAF_TAPSCRIPT);
1177 : 6868 : }
1178 [ + - + - ]: 423802 : if (!builder.IsComplete()) return {};
1179 [ + - ]: 423802 : assert(keys.size() == 1);
1180 [ + - ]: 423802 : XOnlyPubKey xpk(keys[0]);
1181 [ + - + - ]: 423802 : if (!xpk.IsFullyValid()) return {};
1182 [ + - ]: 423802 : builder.Finalize(xpk);
1183 [ + - ]: 423802 : WitnessV1Taproot output = builder.GetOutput();
1184 [ + - + - ]: 423802 : out.tr_trees[output] = builder;
1185 [ + - + - ]: 423802 : out.pubkeys.emplace(keys[0].GetID(), keys[0]);
1186 [ + - + - ]: 423802 : return Vector(GetScriptForDestination(output));
1187 : 423802 : }
1188 : 450005 : bool ToStringSubScriptHelper(const SigningProvider* arg, std::string& ret, const StringType type, const DescriptorCache* cache = nullptr) const override
1189 : : {
1190 [ + + ]: 450005 : if (m_depths.empty()) return true;
1191 : 3246 : std::vector<bool> path;
1192 [ + + + + ]: 10174 : for (size_t pos = 0; pos < m_depths.size(); ++pos) {
1193 [ + + + - ]: 6928 : if (pos) ret += ',';
1194 [ + + ]: 13856 : while ((int)path.size() <= m_depths[pos]) {
1195 [ + + + - ]: 6928 : if (path.size()) ret += '{';
1196 [ + - ]: 6928 : path.push_back(false);
1197 : : }
1198 : 6928 : std::string tmp;
1199 [ + - + + ]: 6928 : if (!m_subdescriptor_args[pos]->ToStringHelper(arg, tmp, type, cache)) return false;
1200 [ + - ]: 6611 : ret += tmp;
1201 [ - + - + : 10293 : while (!path.empty() && path.back()) {
+ + ]
1202 [ + - + - ]: 3682 : if (path.size() > 1) ret += '}';
1203 [ + - ]: 3682 : path.pop_back();
1204 : : }
1205 [ - + + - ]: 6611 : if (!path.empty()) path.back() = true;
1206 [ + + ]: 6928 : }
1207 : 2929 : return true;
1208 : 450005 : }
1209 : : public:
1210 : 639861 : TRDescriptor(std::unique_ptr<PubkeyProvider> internal_key, std::vector<std::unique_ptr<DescriptorImpl>> descs, std::vector<int> depths) :
1211 [ + - + - ]: 639861 : DescriptorImpl(Vector(std::move(internal_key)), std::move(descs), "tr"), m_depths(std::move(depths))
1212 : 639861 : {
1213 [ + - ]: 639861 : assert(m_subdescriptor_args.size() == m_depths.size());
1214 : 639861 : }
1215 : 804607 : std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32M; }
1216 : 340355 : bool IsSingleType() const final { return true; }
1217 : :
1218 : 1058 : std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
1219 : :
1220 : 618397 : std::optional<int64_t> MaxSatisfactionWeight(bool) const override {
1221 : : // FIXME: We assume keypath spend, which can lead to very large underestimations.
1222 : 618397 : return 1 + 65;
1223 : : }
1224 : :
1225 : 617280 : std::optional<int64_t> MaxSatisfactionElems() const override {
1226 : : // FIXME: See above, we assume keypath spend.
1227 : 617280 : return 1;
1228 : : }
1229 : :
1230 : 0 : std::unique_ptr<DescriptorImpl> Clone() const override
1231 : : {
1232 : 0 : std::vector<std::unique_ptr<DescriptorImpl>> subdescs;
1233 [ # # ]: 0 : subdescs.reserve(m_subdescriptor_args.size());
1234 [ # # ]: 0 : std::transform(m_subdescriptor_args.begin(), m_subdescriptor_args.end(), subdescs.begin(), [](const std::unique_ptr<DescriptorImpl>& d) { return d->Clone(); });
1235 [ # # # # : 0 : return std::make_unique<TRDescriptor>(m_pubkey_args.at(0)->Clone(), std::move(subdescs), m_depths);
# # ]
1236 : 0 : }
1237 : : };
1238 : :
1239 : : /* We instantiate Miniscript here with a simple integer as key type.
1240 : : * The value of these key integers are an index in the
1241 : : * DescriptorImpl::m_pubkey_args vector.
1242 : : */
1243 : :
1244 : : /**
1245 : : * The context for converting a Miniscript descriptor into a Script.
1246 : : */
1247 : : class ScriptMaker {
1248 : : //! Keys contained in the Miniscript (the evaluation of DescriptorImpl::m_pubkey_args).
1249 : : const std::vector<CPubKey>& m_keys;
1250 : : //! The script context we're operating within (Tapscript or P2WSH).
1251 : : const miniscript::MiniscriptContext m_script_ctx;
1252 : :
1253 : : //! Get the ripemd160(sha256()) hash of this key.
1254 : : //! Any key that is valid in a descriptor serializes as 32 bytes within a Tapscript context. So we
1255 : : //! must not hash the sign-bit byte in this case.
1256 : 1388 : uint160 GetHash160(uint32_t key) const {
1257 [ + + ]: 1388 : if (miniscript::IsTapscript(m_script_ctx)) {
1258 : 580 : return Hash160(XOnlyPubKey{m_keys[key]});
1259 : : }
1260 : 808 : return m_keys[key].GetID();
1261 : 1388 : }
1262 : :
1263 : : public:
1264 : 5574 : ScriptMaker(const std::vector<CPubKey>& keys LIFETIMEBOUND, const miniscript::MiniscriptContext script_ctx) : m_keys(keys), m_script_ctx{script_ctx} {}
1265 : :
1266 : 17089 : std::vector<unsigned char> ToPKBytes(uint32_t key) const {
1267 : : // In Tapscript keys always serialize as x-only, whether an x-only key was used in the descriptor or not.
1268 [ + + ]: 17089 : if (!miniscript::IsTapscript(m_script_ctx)) {
1269 [ + - ]: 14355 : return {m_keys[key].begin(), m_keys[key].end()};
1270 : : }
1271 : 2734 : const XOnlyPubKey xonly_pubkey{m_keys[key]};
1272 [ + - ]: 2734 : return {xonly_pubkey.begin(), xonly_pubkey.end()};
1273 : 17089 : }
1274 : :
1275 : 1388 : std::vector<unsigned char> ToPKHBytes(uint32_t key) const {
1276 : 1388 : auto id = GetHash160(key);
1277 [ + - ]: 1388 : return {id.begin(), id.end()};
1278 : 1388 : }
1279 : : };
1280 : :
1281 : : /**
1282 : : * The context for converting a Miniscript descriptor to its textual form.
1283 : : */
1284 : : class StringMaker {
1285 : : //! To convert private keys for private descriptors.
1286 : : const SigningProvider* m_arg;
1287 : : //! Keys contained in the Miniscript (a reference to DescriptorImpl::m_pubkey_args).
1288 : : const std::vector<std::unique_ptr<PubkeyProvider>>& m_pubkeys;
1289 : : //! Whether to serialize keys as private or public.
1290 : : bool m_private;
1291 : :
1292 : : public:
1293 : 7718 : StringMaker(const SigningProvider* arg LIFETIMEBOUND, const std::vector<std::unique_ptr<PubkeyProvider>>& pubkeys LIFETIMEBOUND, bool priv)
1294 : 7718 : : m_arg(arg), m_pubkeys(pubkeys), m_private(priv) {}
1295 : :
1296 : 26067 : std::optional<std::string> ToString(uint32_t key) const
1297 : : {
1298 : 26067 : std::string ret;
1299 [ + + ]: 26067 : if (m_private) {
1300 [ + - + + ]: 2064 : if (!m_pubkeys[key]->ToPrivateString(*m_arg, ret)) return {};
1301 : 1417 : } else {
1302 [ + - ]: 24003 : ret = m_pubkeys[key]->ToString();
1303 : : }
1304 : 25420 : return ret;
1305 : 26067 : }
1306 : : };
1307 : :
1308 : : class MiniscriptDescriptor final : public DescriptorImpl
1309 : : {
1310 : : private:
1311 : : miniscript::NodeRef<uint32_t> m_node;
1312 : :
1313 : : protected:
1314 : 5574 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript> scripts,
1315 : : FlatSigningProvider& provider) const override
1316 : : {
1317 : 5574 : const auto script_ctx{m_node->GetMsCtx()};
1318 [ + + ]: 24051 : for (const auto& key : keys) {
1319 [ + + ]: 18477 : if (miniscript::IsTapscript(script_ctx)) {
1320 : 3314 : provider.pubkeys.emplace(Hash160(XOnlyPubKey{key}), key);
1321 : 3314 : } else {
1322 : 15163 : provider.pubkeys.emplace(key.GetID(), key);
1323 : : }
1324 : 18477 : }
1325 [ + - ]: 5574 : return Vector(m_node->ToScript(ScriptMaker(keys, script_ctx)));
1326 : 5574 : }
1327 : :
1328 : : public:
1329 : 5365 : MiniscriptDescriptor(std::vector<std::unique_ptr<PubkeyProvider>> providers, miniscript::NodeRef<uint32_t> node)
1330 [ + - + - ]: 5365 : : DescriptorImpl(std::move(providers), "?"), m_node(std::move(node)) {}
1331 : :
1332 : 7718 : bool ToStringHelper(const SigningProvider* arg, std::string& out, const StringType type,
1333 : : const DescriptorCache* cache = nullptr) const override
1334 : : {
1335 [ + + - + : 14789 : if (const auto res = m_node->ToString(StringMaker(arg, m_pubkey_args, type == StringType::PRIVATE))) {
+ ]
1336 [ + - ]: 7071 : out = *res;
1337 : 7071 : return true;
1338 : : }
1339 : 647 : return false;
1340 : 7718 : }
1341 : :
1342 : 1134 : bool IsSolvable() const override { return true; }
1343 : 0 : bool IsSingleType() const final { return true; }
1344 : :
1345 : 1408 : std::optional<int64_t> ScriptSize() const override { return m_node->ScriptSize(); }
1346 : :
1347 : 1408 : std::optional<int64_t> MaxSatSize(bool) const override {
1348 : : // For Miniscript we always assume high-R ECDSA signatures.
1349 : 1408 : return m_node->GetWitnessSize();
1350 : : }
1351 : :
1352 : 704 : std::optional<int64_t> MaxSatisfactionElems() const override {
1353 : 704 : return m_node->GetStackSize();
1354 : : }
1355 : :
1356 : 0 : std::unique_ptr<DescriptorImpl> Clone() const override
1357 : : {
1358 : 0 : std::vector<std::unique_ptr<PubkeyProvider>> providers;
1359 [ # # ]: 0 : providers.reserve(m_pubkey_args.size());
1360 [ # # ]: 0 : for (const auto& arg : m_pubkey_args) {
1361 [ # # # # ]: 0 : providers.push_back(arg->Clone());
1362 : 0 : }
1363 [ # # # # ]: 0 : return std::make_unique<MiniscriptDescriptor>(std::move(providers), miniscript::MakeNodeRef<uint32_t>(*m_node));
1364 : 0 : }
1365 : : };
1366 : :
1367 : : /** A parsed rawtr(...) descriptor. */
1368 : : class RawTRDescriptor final : public DescriptorImpl
1369 : : {
1370 : : protected:
1371 : 298 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript> scripts, FlatSigningProvider& out) const override
1372 : : {
1373 [ + - ]: 298 : assert(keys.size() == 1);
1374 : 298 : XOnlyPubKey xpk(keys[0]);
1375 [ + - ]: 298 : if (!xpk.IsFullyValid()) return {};
1376 : 298 : WitnessV1Taproot output{xpk};
1377 [ + - + - ]: 298 : return Vector(GetScriptForDestination(output));
1378 : 298 : }
1379 : : public:
1380 [ + - + - ]: 7500 : RawTRDescriptor(std::unique_ptr<PubkeyProvider> output_key) : DescriptorImpl(Vector(std::move(output_key)), "rawtr") {}
1381 : 122 : std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32M; }
1382 : 174 : bool IsSingleType() const final { return true; }
1383 : :
1384 : 8 : std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
1385 : :
1386 : 18 : std::optional<int64_t> MaxSatisfactionWeight(bool) const override {
1387 : : // We can't know whether there is a script path, so assume key path spend.
1388 : 18 : return 1 + 65;
1389 : : }
1390 : :
1391 : 9 : std::optional<int64_t> MaxSatisfactionElems() const override {
1392 : : // See above, we assume keypath spend.
1393 : 9 : return 1;
1394 : : }
1395 : :
1396 : 0 : std::unique_ptr<DescriptorImpl> Clone() const override
1397 : : {
1398 [ # # ]: 0 : return std::make_unique<RawTRDescriptor>(m_pubkey_args.at(0)->Clone());
1399 : 0 : }
1400 : : };
1401 : :
1402 : : ////////////////////////////////////////////////////////////////////////////
1403 : : // Parser //
1404 : : ////////////////////////////////////////////////////////////////////////////
1405 : :
1406 : : enum class ParseScriptContext {
1407 : : TOP, //!< Top-level context (script goes directly in scriptPubKey)
1408 : : P2SH, //!< Inside sh() (script becomes P2SH redeemScript)
1409 : : P2WPKH, //!< Inside wpkh() (no script, pubkey only)
1410 : : P2WSH, //!< Inside wsh() (script becomes v0 witness script)
1411 : : P2TR, //!< Inside tr() (either internal key, or BIP342 script leaf)
1412 : : };
1413 : :
1414 : 265341 : std::optional<uint32_t> ParseKeyPathNum(Span<const char> elem, bool& apostrophe, std::string& error)
1415 : : {
1416 : 265341 : bool hardened = false;
1417 [ + + ]: 265341 : if (elem.size() > 0) {
1418 : 265327 : const char last = elem[elem.size() - 1];
1419 [ + + + + ]: 265327 : if (last == '\'' || last == 'h') {
1420 : 93726 : elem = elem.first(elem.size() - 1);
1421 : 93726 : hardened = true;
1422 : 93726 : apostrophe = last == '\'';
1423 : 93726 : }
1424 : 265327 : }
1425 : 265341 : uint32_t p;
1426 [ + - + - : 265341 : if (!ParseUInt32(std::string(elem.begin(), elem.end()), &p)) {
+ + ]
1427 [ + - + - ]: 173 : error = strprintf("Key path value '%s' is not a valid uint32", std::string(elem.begin(), elem.end()));
1428 : 173 : return std::nullopt;
1429 [ + + ]: 265168 : } else if (p > 0x7FFFFFFFUL) {
1430 : 19 : error = strprintf("Key path value %u is out of range", p);
1431 : 19 : return std::nullopt;
1432 : : }
1433 : :
1434 : 265149 : return std::make_optional<uint32_t>(p | (((uint32_t)hardened) << 31));
1435 : 265341 : }
1436 : :
1437 : : /**
1438 : : * Parse a key path, being passed a split list of elements (the first element is ignored because it is always the key).
1439 : : *
1440 : : * @param[in] split BIP32 path string, using either ' or h for hardened derivation
1441 : : * @param[out] out Vector of parsed key paths
1442 : : * @param[out] apostrophe only updated if hardened derivation is found
1443 : : * @param[out] error parsing error message
1444 : : * @param[in] allow_multipath Allows the parsed path to use the multipath specifier
1445 : : * @returns false if parsing failed
1446 : : **/
1447 : 191189 : [[nodiscard]] bool ParseKeyPath(const std::vector<Span<const char>>& split, std::vector<KeyPath>& out, bool& apostrophe, std::string& error, bool allow_multipath)
1448 : : {
1449 : 191189 : KeyPath path;
1450 : 191189 : std::optional<size_t> multipath_segment_index;
1451 : 191189 : std::vector<uint32_t> multipath_values;
1452 : 191189 : std::unordered_set<uint32_t> seen_multipath;
1453 : :
1454 [ + + + + ]: 456530 : for (size_t i = 1; i < split.size(); ++i) {
1455 : 265341 : const Span<const char>& elem = split[i];
1456 : :
1457 : : // Check if element contain multipath specifier
1458 [ + + - + : 265341 : if (!elem.empty() && elem.front() == '<' && elem.back() == '>') {
# # ]
1459 [ # # ]: 0 : if (!allow_multipath) {
1460 [ # # # # ]: 0 : error = strprintf("Key path value '%s' specifies multipath in a section where multipath is not allowed", std::string(elem.begin(), elem.end()));
1461 : 0 : return false;
1462 : : }
1463 [ # # ]: 0 : if (multipath_segment_index) {
1464 [ # # ]: 0 : error = "Multiple multipath key path specifiers found";
1465 : 0 : return false;
1466 : : }
1467 : :
1468 : : // Parse each possible value
1469 [ # # ]: 0 : std::vector<Span<const char>> nums = Split(Span(elem.begin()+1, elem.end()-1), ";");
1470 [ # # ]: 0 : if (nums.size() < 2) {
1471 [ # # ]: 0 : error = "Multipath key path specifiers must have at least two items";
1472 : 0 : return false;
1473 : : }
1474 : :
1475 [ # # # # ]: 0 : for (const auto& num : nums) {
1476 [ # # ]: 0 : const auto& op_num = ParseKeyPathNum(num, apostrophe, error);
1477 [ # # ]: 0 : if (!op_num) return false;
1478 [ # # ]: 0 : auto [_, inserted] = seen_multipath.insert(*op_num);
1479 [ # # ]: 0 : if (!inserted) {
1480 [ # # ]: 0 : error = strprintf("Duplicated key path value %u in multipath specifier", *op_num);
1481 : 0 : return false;
1482 : : }
1483 [ # # ]: 0 : multipath_values.emplace_back(*op_num);
1484 [ # # # # ]: 0 : }
1485 : :
1486 [ # # ]: 0 : path.emplace_back(); // Placeholder for multipath segment
1487 : 0 : multipath_segment_index = path.size()-1;
1488 [ # # ]: 0 : } else {
1489 [ - + ]: 265341 : const auto& op_num = ParseKeyPathNum(elem, apostrophe, error);
1490 [ + + ]: 265341 : if (!op_num) return false;
1491 [ - + ]: 265149 : path.emplace_back(*op_num);
1492 [ + + ]: 265341 : }
1493 [ + + ]: 265341 : }
1494 : :
1495 [ - + ]: 190997 : if (!multipath_segment_index) {
1496 [ + - ]: 190997 : out.emplace_back(std::move(path));
1497 : 190997 : } else {
1498 : : // Replace the multipath placeholder with each value while generating paths
1499 [ # # ]: 0 : for (size_t i = 0; i < multipath_values.size(); i++) {
1500 [ # # ]: 0 : KeyPath branch_path = path;
1501 : 0 : branch_path[*multipath_segment_index] = multipath_values[i];
1502 [ # # ]: 0 : out.emplace_back(std::move(branch_path));
1503 : 0 : }
1504 : : }
1505 : 190997 : return true;
1506 : 191189 : }
1507 : :
1508 : : /** Parse a public key that excludes origin information. */
1509 : 244857 : std::vector<std::unique_ptr<PubkeyProvider>> ParsePubkeyInner(uint32_t key_exp_index, const Span<const char>& sp, ParseScriptContext ctx, FlatSigningProvider& out, bool& apostrophe, std::string& error)
1510 : : {
1511 : 244857 : std::vector<std::unique_ptr<PubkeyProvider>> ret;
1512 [ + + ]: 244857 : bool permit_uncompressed = ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH;
1513 [ + - ]: 244857 : auto split = Split(sp, '/');
1514 [ + - ]: 244857 : std::string str(split[0].begin(), split[0].end());
1515 [ + + ]: 244857 : if (str.size() == 0) {
1516 [ + - ]: 69 : error = "No key provided";
1517 : 69 : return {};
1518 : : }
1519 [ + + ]: 244788 : if (split.size() == 1) {
1520 [ + - + + ]: 123071 : if (IsHex(str)) {
1521 [ + - ]: 53629 : std::vector<unsigned char> data = ParseHex(str);
1522 [ + - + - ]: 53629 : CPubKey pubkey(data);
1523 [ + - + + : 53629 : if (pubkey.IsValid() && !pubkey.IsValidNonHybrid()) {
+ + ]
1524 [ + - ]: 11 : error = "Hybrid public keys are not allowed";
1525 : 11 : return {};
1526 : : }
1527 [ + - + + ]: 53618 : if (pubkey.IsFullyValid()) {
1528 [ + + + - : 33911 : if (permit_uncompressed || pubkey.IsCompressed()) {
+ + ]
1529 [ + - + - ]: 33907 : ret.emplace_back(std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, false));
1530 : 33907 : return ret;
1531 : : } else {
1532 [ + - ]: 4 : error = "Uncompressed keys are not allowed";
1533 : 4 : return {};
1534 : : }
1535 [ + + + + ]: 19707 : } else if (data.size() == 32 && ctx == ParseScriptContext::P2TR) {
1536 : 19582 : unsigned char fullkey[33] = {0x02};
1537 [ + - ]: 19582 : std::copy(data.begin(), data.end(), fullkey + 1);
1538 [ + - ]: 19582 : pubkey.Set(std::begin(fullkey), std::end(fullkey));
1539 [ + - + + ]: 19582 : if (pubkey.IsFullyValid()) {
1540 [ + - + - ]: 19562 : ret.emplace_back(std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, true));
1541 : 19562 : return ret;
1542 : : }
1543 [ + + ]: 19582 : }
1544 [ + - ]: 145 : error = strprintf("Pubkey '%s' is invalid", str);
1545 : 145 : return {};
1546 : 53629 : }
1547 [ + - ]: 69442 : CKey key = DecodeSecret(str);
1548 [ + - + + ]: 69442 : if (key.IsValid()) {
1549 [ + + + - : 35992 : if (permit_uncompressed || key.IsCompressed()) {
- + ]
1550 [ + - ]: 35992 : CPubKey pubkey = key.GetPubKey();
1551 [ + - + - ]: 35992 : out.keys.emplace(pubkey.GetID(), key);
1552 [ + - + - ]: 35992 : ret.emplace_back(std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, ctx == ParseScriptContext::P2TR));
1553 : 35992 : return ret;
1554 : 35992 : } else {
1555 [ # # ]: 0 : error = "Uncompressed keys are not allowed";
1556 : 0 : return {};
1557 : : }
1558 : : }
1559 [ + + ]: 69442 : }
1560 [ + - ]: 155167 : CExtKey extkey = DecodeExtKey(str);
1561 [ + - ]: 155167 : CExtPubKey extpubkey = DecodeExtPubKey(str);
1562 [ + - + + : 155167 : if (!extkey.key.IsValid() && !extpubkey.pubkey.IsValid()) {
+ - + + ]
1563 [ + - ]: 457 : error = strprintf("key '%s' is not valid", str);
1564 : 457 : return {};
1565 : : }
1566 : 154710 : std::vector<KeyPath> paths;
1567 : 154710 : DeriveType type = DeriveType::NO;
1568 [ + - + + ]: 154710 : if (std::ranges::equal(split.back(), Span{"*"}.first(1))) {
1569 : 34767 : split.pop_back();
1570 : 34767 : type = DeriveType::UNHARDENED;
1571 [ + - + + : 154710 : } else if (std::ranges::equal(split.back(), Span{"*'"}.first(2)) || std::ranges::equal(split.back(), Span{"*h"}.first(2))) {
+ - + + ]
1572 [ + - ]: 8975 : apostrophe = std::ranges::equal(split.back(), Span{"*'"}.first(2));
1573 : 8975 : split.pop_back();
1574 : 8975 : type = DeriveType::HARDENED;
1575 : 8975 : }
1576 [ + - + + ]: 154710 : if (!ParseKeyPath(split, paths, apostrophe, error, /*allow_multipath=*/true)) return {};
1577 [ + - + + ]: 154620 : if (extkey.key.IsValid()) {
1578 [ + - ]: 131140 : extpubkey = extkey.Neuter();
1579 [ + - + - ]: 131140 : out.keys.emplace(extpubkey.pubkey.GetID(), extkey.key);
1580 : 131140 : }
1581 [ + + ]: 309240 : for (auto& path : paths) {
1582 [ + - + - ]: 154620 : ret.emplace_back(std::make_unique<BIP32PubkeyProvider>(key_exp_index, extpubkey, std::move(path), type, apostrophe));
1583 : 154620 : }
1584 : 154620 : return ret;
1585 : 244857 : }
1586 : :
1587 : : /** Parse a public key including origin information (if enabled). */
1588 : 245060 : std::vector<std::unique_ptr<PubkeyProvider>> ParsePubkey(uint32_t key_exp_index, const Span<const char>& sp, ParseScriptContext ctx, FlatSigningProvider& out, std::string& error)
1589 : : {
1590 : 245060 : std::vector<std::unique_ptr<PubkeyProvider>> ret;
1591 [ + - ]: 245060 : auto origin_split = Split(sp, ']');
1592 [ + + ]: 245060 : if (origin_split.size() > 2) {
1593 [ + - ]: 29 : error = "Multiple ']' characters found for a single pubkey";
1594 : 29 : return {};
1595 : : }
1596 : : // This is set if either the origin or path suffix contains a hardened derivation.
1597 : 245031 : bool apostrophe = false;
1598 [ + + ]: 245031 : if (origin_split.size() == 1) {
1599 [ + - ]: 208480 : return ParsePubkeyInner(key_exp_index, origin_split[0], ctx, out, apostrophe, error);
1600 : : }
1601 [ + + + + ]: 36551 : if (origin_split[0].empty() || origin_split[0][0] != '[') {
1602 [ + - ]: 58 : error = strprintf("Key origin start '[ character expected but not found, got '%c' instead",
1603 [ + + ]: 29 : origin_split[0].empty() ? /** empty, implies split char */ ']' : origin_split[0][0]);
1604 : 29 : return {};
1605 : : }
1606 [ + - ]: 36522 : auto slash_split = Split(origin_split[0].subspan(1), '/');
1607 [ + + ]: 36522 : if (slash_split[0].size() != 8) {
1608 [ + - ]: 26 : error = strprintf("Fingerprint is not 4 bytes (%u characters instead of 8 characters)", slash_split[0].size());
1609 : 26 : return {};
1610 : : }
1611 [ + - ]: 36496 : std::string fpr_hex = std::string(slash_split[0].begin(), slash_split[0].end());
1612 [ + - + + ]: 36496 : if (!IsHex(fpr_hex)) {
1613 [ + - ]: 17 : error = strprintf("Fingerprint '%s' is not hex", fpr_hex);
1614 : 17 : return {};
1615 : : }
1616 [ + - ]: 36479 : auto fpr_bytes = ParseHex(fpr_hex);
1617 : 36479 : KeyOriginInfo info;
1618 : : static_assert(sizeof(info.fingerprint) == 4, "Fingerprint must be 4 bytes");
1619 [ + - ]: 36479 : assert(fpr_bytes.size() == 4);
1620 [ + - ]: 36479 : std::copy(fpr_bytes.begin(), fpr_bytes.end(), info.fingerprint);
1621 : 36479 : std::vector<KeyPath> path;
1622 [ + - + + ]: 36479 : if (!ParseKeyPath(slash_split, path, apostrophe, error, /*allow_multipath=*/false)) return {};
1623 [ + - + - ]: 36377 : info.path = path.at(0);
1624 [ + - ]: 36377 : auto providers = ParsePubkeyInner(key_exp_index, origin_split[1], ctx, out, apostrophe, error);
1625 [ + + ]: 36377 : if (providers.empty()) return {};
1626 [ + - ]: 36300 : ret.reserve(providers.size());
1627 [ + + ]: 72600 : for (auto& prov : providers) {
1628 [ + - + - ]: 36300 : ret.emplace_back(std::make_unique<OriginPubkeyProvider>(key_exp_index, info, std::move(prov), apostrophe));
1629 : 36300 : }
1630 : 36300 : return ret;
1631 : 245060 : }
1632 : :
1633 : 6868948 : std::unique_ptr<PubkeyProvider> InferPubkey(const CPubKey& pubkey, ParseScriptContext ctx, const SigningProvider& provider)
1634 : : {
1635 : : // Key cannot be hybrid
1636 [ + + ]: 6868948 : if (!pubkey.IsValidNonHybrid()) {
1637 : 2496 : return nullptr;
1638 : : }
1639 : : // Uncompressed is only allowed in TOP and P2SH contexts
1640 [ + + + + : 6866452 : if (ctx != ParseScriptContext::TOP && ctx != ParseScriptContext::P2SH && !pubkey.IsCompressed()) {
+ - ]
1641 : 0 : return nullptr;
1642 : : }
1643 : 6866452 : std::unique_ptr<PubkeyProvider> key_provider = std::make_unique<ConstPubkeyProvider>(0, pubkey, false);
1644 : 6866452 : KeyOriginInfo info;
1645 [ + - + - : 6866452 : if (provider.GetKeyOrigin(pubkey.GetID(), info)) {
+ + ]
1646 [ + - ]: 6785492 : return std::make_unique<OriginPubkeyProvider>(0, std::move(info), std::move(key_provider), /*apostrophe=*/false);
1647 : : }
1648 : 80960 : return key_provider;
1649 : 6868948 : }
1650 : :
1651 : 760475 : std::unique_ptr<PubkeyProvider> InferXOnlyPubkey(const XOnlyPubKey& xkey, ParseScriptContext ctx, const SigningProvider& provider)
1652 : : {
1653 : 760475 : CPubKey pubkey{xkey.GetEvenCorrespondingCPubKey()};
1654 : 760475 : std::unique_ptr<PubkeyProvider> key_provider = std::make_unique<ConstPubkeyProvider>(0, pubkey, true);
1655 : 760475 : KeyOriginInfo info;
1656 [ + - + + ]: 760475 : if (provider.GetKeyOriginByXOnly(xkey, info)) {
1657 [ + - ]: 753088 : return std::make_unique<OriginPubkeyProvider>(0, std::move(info), std::move(key_provider), /*apostrophe=*/false);
1658 : : }
1659 : 7387 : return key_provider;
1660 : 760475 : }
1661 : :
1662 : : /**
1663 : : * The context for parsing a Miniscript descriptor (either from Script or from its textual representation).
1664 : : */
1665 : : struct KeyParser {
1666 : : //! The Key type is an index in DescriptorImpl::m_pubkey_args
1667 : : using Key = uint32_t;
1668 : : //! Must not be nullptr if parsing from string.
1669 : : FlatSigningProvider* m_out;
1670 : : //! Must not be nullptr if parsing from Script.
1671 : : const SigningProvider* m_in;
1672 : : //! List of multipath expanded keys contained in the Miniscript.
1673 : : mutable std::vector<std::vector<std::unique_ptr<PubkeyProvider>>> m_keys;
1674 : : //! Used to detect key parsing errors within a Miniscript.
1675 : : mutable std::string m_key_parsing_error;
1676 : : //! The script context we're operating within (Tapscript or P2WSH).
1677 : : const miniscript::MiniscriptContext m_script_ctx;
1678 : : //! The number of keys that were parsed before starting to parse this Miniscript descriptor.
1679 : : uint32_t m_offset;
1680 : :
1681 : 27994 : KeyParser(FlatSigningProvider* out LIFETIMEBOUND, const SigningProvider* in LIFETIMEBOUND,
1682 : : miniscript::MiniscriptContext ctx, uint32_t offset = 0)
1683 : 27994 : : m_out(out), m_in(in), m_script_ctx(ctx), m_offset(offset) {}
1684 : :
1685 : 174145 : bool KeyCompare(const Key& a, const Key& b) const {
1686 : 174145 : return *m_keys.at(a).at(0) < *m_keys.at(b).at(0);
1687 : : }
1688 : :
1689 : 56508 : ParseScriptContext ParseContext() const {
1690 [ + - + ]: 56508 : switch (m_script_ctx) {
1691 : 34345 : case miniscript::MiniscriptContext::P2WSH: return ParseScriptContext::P2WSH;
1692 : 22163 : case miniscript::MiniscriptContext::TAPSCRIPT: return ParseScriptContext::P2TR;
1693 : : }
1694 : 0 : assert(false);
1695 : 56508 : }
1696 : :
1697 : 52067 : template<typename I> std::optional<Key> FromString(I begin, I end) const
1698 : : {
1699 [ + - ]: 52067 : assert(m_out);
1700 : 52067 : Key key = m_keys.size();
1701 : 52067 : auto pk = ParsePubkey(m_offset + key, {&*begin, &*end}, ParseContext(), *m_out, m_key_parsing_error);
1702 [ + + ]: 52067 : if (pk.empty()) return {};
1703 [ + - ]: 51779 : m_keys.emplace_back(std::move(pk));
1704 : 51779 : return key;
1705 : 52067 : }
1706 : :
1707 : 20921 : std::optional<std::string> ToString(const Key& key) const
1708 : : {
1709 : 20921 : return m_keys.at(key).at(0)->ToString();
1710 : : }
1711 : :
1712 : 4234 : template<typename I> std::optional<Key> FromPKBytes(I begin, I end) const
1713 : : {
1714 [ + - ]: 4234 : assert(m_in);
1715 : 4234 : Key key = m_keys.size();
1716 [ + + - + ]: 4234 : if (miniscript::IsTapscript(m_script_ctx) && end - begin == 32) {
1717 : 1319 : XOnlyPubKey pubkey;
1718 : 1319 : std::copy(begin, end, pubkey.begin());
1719 [ + - - + ]: 2638 : if (auto pubkey_provider = InferPubkey(pubkey.GetEvenCorrespondingCPubKey(), ParseContext(), *m_in)) {
1720 [ + - ]: 1319 : m_keys.emplace_back();
1721 [ + - ]: 1319 : m_keys.back().push_back(std::move(pubkey_provider));
1722 : 1319 : return key;
1723 : : }
1724 [ - + - + ]: 4234 : } else if (!miniscript::IsTapscript(m_script_ctx)) {
1725 : 2915 : CPubKey pubkey(begin, end);
1726 [ + + + + ]: 5813 : if (auto pubkey_provider = InferPubkey(pubkey, ParseContext(), *m_in)) {
1727 [ + - ]: 2898 : m_keys.emplace_back();
1728 [ + - ]: 2898 : m_keys.back().push_back(std::move(pubkey_provider));
1729 : 2898 : return key;
1730 : : }
1731 [ + + ]: 2915 : }
1732 : 17 : return {};
1733 : 4234 : }
1734 : :
1735 : 207 : template<typename I> std::optional<Key> FromPKHBytes(I begin, I end) const
1736 : : {
1737 [ + - ]: 207 : assert(end - begin == 20);
1738 [ + - ]: 207 : assert(m_in);
1739 : 207 : uint160 hash;
1740 : 207 : std::copy(begin, end, hash.begin());
1741 : 207 : CKeyID keyid(hash);
1742 : 207 : CPubKey pubkey;
1743 [ - + ]: 207 : if (m_in->GetPubKey(keyid, pubkey)) {
1744 [ + - + - ]: 414 : if (auto pubkey_provider = InferPubkey(pubkey, ParseContext(), *m_in)) {
1745 : 207 : Key key = m_keys.size();
1746 [ + - ]: 207 : m_keys.emplace_back();
1747 [ + - ]: 207 : m_keys.back().push_back(std::move(pubkey_provider));
1748 : 207 : return key;
1749 : 207 : }
1750 : 0 : }
1751 : 0 : return {};
1752 : 207 : }
1753 : :
1754 : 7503110 : miniscript::MiniscriptContext MsContext() const {
1755 : 7503110 : return m_script_ctx;
1756 : : }
1757 : : };
1758 : :
1759 : : /** Parse a script in a particular context. */
1760 : : // NOLINTNEXTLINE(misc-no-recursion)
1761 : 74910 : std::vector<std::unique_ptr<DescriptorImpl>> ParseScript(uint32_t& key_exp_index, Span<const char>& sp, ParseScriptContext ctx, FlatSigningProvider& out, std::string& error)
1762 : : {
1763 : : using namespace script;
1764 : :
1765 : 74910 : std::vector<std::unique_ptr<DescriptorImpl>> ret;
1766 [ + - ]: 74910 : auto expr = Expr(sp);
1767 [ + - + - : 74910 : if (Func("pk", expr)) {
+ + ]
1768 [ + - ]: 9305 : auto pubkeys = ParsePubkey(key_exp_index, expr, ctx, out, error);
1769 [ + + ]: 9305 : if (pubkeys.empty()) {
1770 [ + - ]: 290 : error = strprintf("pk(): %s", error);
1771 : 290 : return {};
1772 : : }
1773 : 9015 : ++key_exp_index;
1774 [ + + ]: 18030 : for (auto& pubkey : pubkeys) {
1775 [ + - + - ]: 9015 : ret.emplace_back(std::make_unique<PKDescriptor>(std::move(pubkey), ctx == ParseScriptContext::P2TR));
1776 : 9015 : }
1777 : 9015 : return ret;
1778 : 9305 : }
1779 [ + + + + : 124837 : if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH) && Func("pkh", expr)) {
+ + + - +
- + + + +
+ + + + +
+ # # # #
# # # # ]
1780 [ + - ]: 7376 : auto pubkeys = ParsePubkey(key_exp_index, expr, ctx, out, error);
1781 [ + + ]: 7376 : if (pubkeys.empty()) {
1782 [ + - ]: 41 : error = strprintf("pkh(): %s", error);
1783 : 41 : return {};
1784 : : }
1785 : 7335 : ++key_exp_index;
1786 [ + + ]: 14670 : for (auto& pubkey : pubkeys) {
1787 [ + - + - ]: 7335 : ret.emplace_back(std::make_unique<PKHDescriptor>(std::move(pubkey)));
1788 : 7335 : }
1789 : 7335 : return ret;
1790 [ + + + - : 117461 : } else if (ctx != ParseScriptContext::P2TR && Func("pkh", expr)) {
+ - + + +
+ + + + +
- + # # #
# # # #
# ]
1791 : : // Under Taproot, always the Miniscript parser deal with it.
1792 [ # # ]: 0 : error = "Can only have pkh at top level, in sh(), wsh(), or in tr()";
1793 : 0 : return {};
1794 : : }
1795 [ + + + - : 97512 : if (ctx == ParseScriptContext::TOP && Func("combo", expr)) {
+ - + + +
+ + + + +
+ + # # #
# # # #
# ]
1796 [ + - ]: 761 : auto pubkeys = ParsePubkey(key_exp_index, expr, ctx, out, error);
1797 [ + + ]: 761 : if (pubkeys.empty()) {
1798 [ + - ]: 21 : error = strprintf("combo(): %s", error);
1799 : 21 : return {};
1800 : : }
1801 : 740 : ++key_exp_index;
1802 [ + + ]: 1480 : for (auto& pubkey : pubkeys) {
1803 [ + - + - ]: 740 : ret.emplace_back(std::make_unique<ComboDescriptor>(std::move(pubkey)));
1804 : 740 : }
1805 : 740 : return ret;
1806 [ + - + - : 58229 : } else if (Func("combo", expr)) {
+ + ]
1807 [ + - ]: 8 : error = "Can only have combo() at top level";
1808 : 8 : return {};
1809 : : }
1810 [ + - + - ]: 57460 : const bool multi = Func("multi", expr);
1811 [ + + + - : 111651 : const bool sortedmulti = !multi && Func("sortedmulti", expr);
+ - + + +
+ + + + +
# # # # #
# # # ]
1812 [ + + + + : 111062 : const bool multi_a = !(multi || sortedmulti) && Func("multi_a", expr);
+ - + - +
+ + + + +
+ + # # #
# # # #
# ]
1813 [ + + + + : 110079 : const bool sortedmulti_a = !(multi || sortedmulti || multi_a) && Func("sortedmulti_a", expr);
+ + + - +
- + + + +
+ + + + #
# # # # #
# # ]
1814 [ + + + + : 60886 : if (((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH) && (multi || sortedmulti)) ||
+ + + + ]
1815 [ + + + + ]: 56378 : (ctx == ParseScriptContext::P2TR && (multi_a || sortedmulti_a))) {
1816 [ + - ]: 18654 : auto threshold = Expr(expr);
1817 : 3322 : uint32_t thres;
1818 : 3322 : std::vector<std::vector<std::unique_ptr<PubkeyProvider>>> providers; // List of multipath expanded pubkeys
1819 [ + - + - : 3322 : if (!ParseUInt32(std::string(threshold.begin(), threshold.end()), &thres)) {
+ + ]
1820 [ + - + - ]: 114 : error = strprintf("Multi threshold '%s' is not valid", std::string(threshold.begin(), threshold.end()));
1821 : 114 : return {};
1822 : : }
1823 : 3208 : size_t script_size = 0;
1824 : 3208 : size_t max_providers_len = 0;
1825 [ + + ]: 155579 : while (expr.size()) {
1826 [ + - - + : 152614 : if (!Const(",", expr)) {
+ + ]
1827 [ + - ]: 10 : error = strprintf("Multi: expected ',', got '%c'", expr[0]);
1828 : 10 : return {};
1829 : : }
1830 [ - + ]: 152604 : auto arg = Expr(expr);
1831 [ - + ]: 152604 : auto pks = ParsePubkey(key_exp_index, arg, ctx, out, error);
1832 [ + + ]: 152604 : if (pks.empty()) {
1833 [ - + ]: 233 : error = strprintf("Multi: %s", error);
1834 : 233 : return {};
1835 : : }
1836 [ + - + - ]: 152371 : script_size += pks.at(0)->GetSize() + 1;
1837 : 152371 : max_providers_len = std::max(max_providers_len, pks.size());
1838 [ + - ]: 152371 : providers.emplace_back(std::move(pks));
1839 : 152371 : key_exp_index++;
1840 [ + + ]: 152604 : }
1841 [ + + + + : 2965 : if ((multi || sortedmulti) && (providers.empty() || providers.size() > MAX_PUBKEYS_PER_MULTISIG)) {
+ + ]
1842 [ + - ]: 3071 : error = strprintf("Cannot have %u keys in multisig; must have between 1 and %d keys, inclusive", providers.size(), MAX_PUBKEYS_PER_MULTISIG);
1843 : 27 : return {};
1844 [ + + + + : 4424 : } else if ((multi_a || sortedmulti_a) && (providers.empty() || providers.size() > MAX_PUBKEYS_PER_MULTI_A)) {
+ + ]
1845 [ + - ]: 3171 : error = strprintf("Cannot have %u keys in multi_a; must have between 1 and %d keys, inclusive", providers.size(), MAX_PUBKEYS_PER_MULTI_A);
1846 : 7 : return {};
1847 [ + + ]: 3127 : } else if (thres < 1) {
1848 [ + - ]: 14 : error = strprintf("Multisig threshold cannot be %d, must be at least 1", thres);
1849 : 14 : return {};
1850 [ + + ]: 3113 : } else if (thres > providers.size()) {
1851 [ + - ]: 20 : error = strprintf("Multisig threshold cannot be larger than the number of keys; threshold is %d but only %u keys specified", thres, providers.size());
1852 : 20 : return {};
1853 : : }
1854 [ + + ]: 3093 : if (ctx == ParseScriptContext::TOP) {
1855 [ + + ]: 683 : if (providers.size() > 3) {
1856 [ + - ]: 23 : error = strprintf("Cannot have %u pubkeys in bare multisig; only at most 3 pubkeys", providers.size());
1857 : 23 : return {};
1858 : : }
1859 : 660 : }
1860 [ + + ]: 3070 : if (ctx == ParseScriptContext::P2SH) {
1861 : : // This limits the maximum number of compressed pubkeys to 15.
1862 [ + + ]: 400 : if (script_size + 3 > MAX_SCRIPT_ELEMENT_SIZE) {
1863 [ + - ]: 9 : error = strprintf("P2SH script is too large, %d bytes is larger than %d bytes", script_size + 3, MAX_SCRIPT_ELEMENT_SIZE);
1864 : 9 : return {};
1865 : : }
1866 : 391 : }
1867 : :
1868 : : // Make sure all vecs are of the same length, or exactly length 1
1869 : : // For length 1 vectors, clone key providers until vector is the same length
1870 [ + + - + ]: 145984 : for (auto& vec : providers) {
1871 [ + - ]: 142923 : if (vec.size() == 1) {
1872 [ - + ]: 142923 : for (size_t i = 1; i < max_providers_len; ++i) {
1873 [ # # # # : 0 : vec.emplace_back(vec.at(0)->Clone());
# # ]
1874 : 0 : }
1875 [ # # ]: 142923 : } else if (vec.size() != max_providers_len) {
1876 [ # # ]: 0 : error = strprintf("multi(): Multipath derivation paths have mismatched lengths");
1877 : 0 : return {};
1878 : : }
1879 [ - + ]: 142923 : }
1880 : :
1881 : : // Build the final descriptors vector
1882 [ + + ]: 6122 : for (size_t i = 0; i < max_providers_len; ++i) {
1883 : : // Build final pubkeys vectors by retrieving the i'th subscript for each vector in subscripts
1884 : 3061 : std::vector<std::unique_ptr<PubkeyProvider>> pubs;
1885 [ + - ]: 3061 : pubs.reserve(providers.size());
1886 [ + + ]: 145984 : for (auto& pub : providers) {
1887 [ + - + - ]: 142923 : pubs.emplace_back(std::move(pub.at(i)));
1888 : 142923 : }
1889 [ + + + + ]: 3061 : if (multi || sortedmulti) {
1890 [ - + + - ]: 1474 : ret.emplace_back(std::make_unique<MultisigDescriptor>(thres, std::move(pubs), sortedmulti));
1891 : 1474 : } else {
1892 [ - + - + ]: 1587 : ret.emplace_back(std::make_unique<MultiADescriptor>(thres, std::move(pubs), sortedmulti_a));
1893 : : }
1894 : 3061 : }
1895 : 3061 : return ret;
1896 [ + + + + ]: 55492 : } else if (multi || sortedmulti) {
1897 [ + - ]: 11 : error = "Can only have multi/sortedmulti at top level, in sh(), or in wsh()";
1898 : 11 : return {};
1899 [ + + + + ]: 51963 : } else if (multi_a || sortedmulti_a) {
1900 [ + - ]: 11 : error = "Can only have multi_a/sortedmulti_a inside tr()";
1901 : 11 : return {};
1902 : : }
1903 [ + + + + : 96424 : if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH) && Func("wpkh", expr)) {
+ - + - +
+ + + + +
+ + + + #
# # # # #
# # ]
1904 [ + - ]: 13067 : auto pubkeys = ParsePubkey(key_exp_index, expr, ParseScriptContext::P2WPKH, out, error);
1905 [ + + ]: 13067 : if (pubkeys.empty()) {
1906 [ + - ]: 20 : error = strprintf("wpkh(): %s", error);
1907 : 20 : return {};
1908 : : }
1909 : 13047 : key_exp_index++;
1910 [ + + ]: 26094 : for (auto& pubkey : pubkeys) {
1911 [ + - + - ]: 13047 : ret.emplace_back(std::make_unique<WPKHDescriptor>(std::move(pubkey)));
1912 : 13047 : }
1913 : 13047 : return ret;
1914 [ + - + - : 51952 : } else if (Func("wpkh", expr)) {
+ + ]
1915 [ + - ]: 6 : error = "Can only have wpkh() at top level or inside sh()";
1916 : 6 : return {};
1917 : : }
1918 [ + + + - : 69837 : if (ctx == ParseScriptContext::TOP && Func("sh", expr)) {
+ - + + +
+ + + + +
+ + # # #
# # # #
# ]
1919 [ + - ]: 7557 : auto descs = ParseScript(key_exp_index, expr, ParseScriptContext::P2SH, out, error);
1920 [ + + + + ]: 7557 : if (descs.empty() || expr.size()) return {};
1921 : 7254 : std::vector<std::unique_ptr<DescriptorImpl>> ret;
1922 [ + - ]: 7254 : ret.reserve(descs.size());
1923 [ + + ]: 14508 : for (auto& desc : descs) {
1924 [ + - + - ]: 7254 : ret.push_back(std::make_unique<SHDescriptor>(std::move(desc)));
1925 : 7254 : }
1926 : 7254 : return ret;
1927 [ + - + - : 46133 : } else if (Func("sh", expr)) {
+ - + + ]
1928 [ + - ]: 6 : error = "Can only have sh() at top level";
1929 : 6 : return {};
1930 : : }
1931 [ + + + + : 55158 : if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH) && Func("wsh", expr)) {
+ - + - +
+ + + + +
+ + + + #
# # # # #
# # ]
1932 [ + - ]: 5250 : auto descs = ParseScript(key_exp_index, expr, ParseScriptContext::P2WSH, out, error);
1933 [ + + + + ]: 5250 : if (descs.empty() || expr.size()) return {};
1934 [ + + ]: 4696 : for (auto& desc : descs) {
1935 [ + - + - ]: 2348 : ret.emplace_back(std::make_unique<WSHDescriptor>(std::move(desc)));
1936 : 2348 : }
1937 : 2348 : return ret;
1938 [ + - + - : 31316 : } else if (Func("wsh", expr)) {
+ + ]
1939 [ + - ]: 5 : error = "Can only have wsh() at top level or inside sh()";
1940 : 5 : return {};
1941 : : }
1942 [ + + + - : 44546 : if (ctx == ParseScriptContext::TOP && Func("addr", expr)) {
+ - + + +
+ + + + +
+ + # # #
# # # #
# ]
1943 [ + - + - ]: 975 : CTxDestination dest = DecodeDestination(std::string(expr.begin(), expr.end()));
1944 [ + - + - ]: 975 : if (!IsValidDestination(dest)) {
1945 [ + - ]: 975 : error = "Address is not valid";
1946 : 975 : return {};
1947 : : }
1948 [ # # # # ]: 0 : ret.emplace_back(std::make_unique<AddressDescriptor>(std::move(dest)));
1949 : 0 : return ret;
1950 [ + - + - : 26061 : } else if (Func("addr", expr)) {
+ + ]
1951 [ + - ]: 8 : error = "Can only have addr() at top level";
1952 : 8 : return {};
1953 : : }
1954 [ + + + - : 42588 : if (ctx == ParseScriptContext::TOP && Func("tr", expr)) {
+ - + + +
+ + + + +
+ + # # #
# # # #
# ]
1955 [ + - ]: 9765 : auto arg = Expr(expr);
1956 [ + - ]: 9765 : auto internal_keys = ParsePubkey(key_exp_index, arg, ParseScriptContext::P2TR, out, error);
1957 [ + + ]: 9765 : if (internal_keys.empty()) {
1958 [ + - ]: 76 : error = strprintf("tr(): %s", error);
1959 : 76 : return {};
1960 : : }
1961 : 9689 : size_t max_providers_len = internal_keys.size();
1962 : 9689 : ++key_exp_index;
1963 : 9689 : std::vector<std::vector<std::unique_ptr<DescriptorImpl>>> subscripts; //!< list of multipath expanded script subexpressions
1964 : 9689 : std::vector<int> depths; //!< depth in the tree of each subexpression (same length subscripts)
1965 [ + + ]: 9689 : if (expr.size()) {
1966 [ + - + - : 2154 : if (!Const(",", expr)) {
+ + ]
1967 [ + - ]: 6 : error = strprintf("tr: expected ',', got '%c'", expr[0]);
1968 : 6 : return {};
1969 : : }
1970 : : /** The path from the top of the tree to what we're currently processing.
1971 : : * branches[i] == false: left branch in the i'th step from the top; true: right branch.
1972 : : */
1973 : 2148 : std::vector<bool> branches;
1974 : : // Loop over all provided scripts. In every iteration exactly one script will be processed.
1975 : : // Use a do-loop because inside this if-branch we expect at least one script.
1976 : 2148 : do {
1977 : : // First process all open braces.
1978 [ + - + - : 21312 : while (Const("{", expr)) {
+ + ]
1979 [ + - ]: 12279 : branches.push_back(false); // new left branch
1980 [ + + ]: 12279 : if (branches.size() > TAPROOT_CONTROL_MAX_NODE_COUNT) {
1981 [ + - ]: 11 : error = strprintf("tr() supports at most %i nesting levels", TAPROOT_CONTROL_MAX_NODE_COUNT);
1982 : 11 : return {};
1983 : : }
1984 : : }
1985 : : // Process the actual script expression.
1986 [ + - ]: 9033 : auto sarg = Expr(expr);
1987 [ + - + - ]: 9033 : subscripts.emplace_back(ParseScript(key_exp_index, sarg, ParseScriptContext::P2TR, out, error));
1988 [ + + ]: 9033 : if (subscripts.back().empty()) return {};
1989 : 8331 : max_providers_len = std::max(max_providers_len, subscripts.back().size());
1990 [ + - ]: 8331 : depths.push_back(branches.size());
1991 : : // Process closing braces; one is expected for every right branch we were in.
1992 [ + + + - : 11379 : while (branches.size() && branches.back()) {
+ + ]
1993 [ + - + - : 3082 : if (!Const("}", expr)) {
+ + ]
1994 [ + - ]: 34 : error = strprintf("tr(): expected '}' after script expression");
1995 : 34 : return {};
1996 : : }
1997 [ + - ]: 3048 : branches.pop_back(); // move up one level after encountering '}'
1998 : : }
1999 : : // If after that, we're at the end of a left branch, expect a comma.
2000 [ + + + - : 8297 : if (branches.size() && !branches.back()) {
+ + ]
2001 [ + - + - : 6921 : if (!Const(",", expr)) {
+ + ]
2002 [ + - ]: 25 : error = strprintf("tr(): expected ',' after script expression");
2003 : 25 : return {};
2004 : : }
2005 [ + - ]: 6896 : branches.back() = true; // And now we're in a right branch.
2006 : 6896 : }
2007 [ + + + + ]: 9033 : } while (branches.size());
2008 : : // After we've explored a whole tree, we must be at the end of the expression.
2009 [ + + ]: 1376 : if (expr.size()) {
2010 [ + - ]: 11 : error = strprintf("tr(): expected ')' after script expression");
2011 : 11 : return {};
2012 : : }
2013 [ + + ]: 2148 : }
2014 [ + - + - ]: 8900 : assert(TaprootBuilder::ValidDepths(depths));
2015 : :
2016 : : // Make sure all vecs are of the same length, or exactly length 1
2017 : : // For length 1 vectors, clone subdescs until vector is the same length
2018 [ + + - + ]: 12757 : for (auto& vec : subscripts) {
2019 [ + - ]: 3857 : if (vec.size() == 1) {
2020 [ - + ]: 3857 : for (size_t i = 1; i < max_providers_len; ++i) {
2021 [ # # # # : 0 : vec.emplace_back(vec.at(0)->Clone());
# # ]
2022 : 0 : }
2023 [ # # ]: 3857 : } else if (vec.size() != max_providers_len) {
2024 [ # # ]: 0 : error = strprintf("tr(): Multipath subscripts have mismatched lengths");
2025 : 0 : return {};
2026 : : }
2027 [ - + ]: 3857 : }
2028 : :
2029 [ - + # # ]: 8900 : if (internal_keys.size() > 1 && internal_keys.size() != max_providers_len) {
2030 [ # # ]: 0 : error = strprintf("tr(): Multipath internal key mismatches multipath subscripts lengths");
2031 : 0 : return {};
2032 : : }
2033 : :
2034 [ - + ]: 8900 : while (internal_keys.size() < max_providers_len) {
2035 [ # # # # : 0 : internal_keys.emplace_back(internal_keys.at(0)->Clone());
# # ]
2036 : : }
2037 : :
2038 : : // Build the final descriptors vector
2039 [ + + ]: 17800 : for (size_t i = 0; i < max_providers_len; ++i) {
2040 : : // Build final subscripts vectors by retrieving the i'th subscript for each vector in subscripts
2041 : 8900 : std::vector<std::unique_ptr<DescriptorImpl>> this_subs;
2042 [ + - ]: 8900 : this_subs.reserve(subscripts.size());
2043 [ + + ]: 12757 : for (auto& subs : subscripts) {
2044 [ + - + - ]: 3857 : this_subs.emplace_back(std::move(subs.at(i)));
2045 : 3857 : }
2046 [ + - + - : 8900 : ret.emplace_back(std::make_unique<TRDescriptor>(std::move(internal_keys.at(i)), std::move(this_subs), depths));
+ - ]
2047 : 8900 : }
2048 : 8900 : return ret;
2049 : :
2050 : :
2051 [ + - + - : 25078 : } else if (Func("tr", expr)) {
+ + ]
2052 [ + - ]: 10 : error = "Can only have tr at top level";
2053 : 10 : return {};
2054 : : }
2055 [ + + + - : 23048 : if (ctx == ParseScriptContext::TOP && Func("rawtr", expr)) {
+ - + + +
+ + + + +
+ + # # #
# # # #
# ]
2056 [ + - ]: 121 : auto arg = Expr(expr);
2057 [ + + ]: 121 : if (expr.size()) {
2058 [ + - ]: 6 : error = strprintf("rawtr(): only one key expected.");
2059 : 6 : return {};
2060 : : }
2061 [ + - ]: 115 : auto output_keys = ParsePubkey(key_exp_index, arg, ParseScriptContext::P2TR, out, error);
2062 [ + + ]: 115 : if (output_keys.empty()) {
2063 [ + - ]: 10 : error = strprintf("rawtr(): %s", error);
2064 : 10 : return {};
2065 : : }
2066 : 105 : ++key_exp_index;
2067 [ + + ]: 210 : for (auto& pubkey : output_keys) {
2068 [ + - + - ]: 105 : ret.emplace_back(std::make_unique<RawTRDescriptor>(std::move(pubkey)));
2069 : 105 : }
2070 : 105 : return ret;
2071 [ + - + - : 15303 : } else if (Func("rawtr", expr)) {
+ + ]
2072 [ + - ]: 6 : error = "Can only have rawtr at top level";
2073 : 6 : return {};
2074 : : }
2075 [ + + + - : 22800 : if (ctx == ParseScriptContext::TOP && Func("raw", expr)) {
+ - + + +
+ + + + +
+ + # # #
# # # #
# ]
2076 [ + - ]: 3163 : std::string str(expr.begin(), expr.end());
2077 [ + - + + ]: 3163 : if (!IsHex(str)) {
2078 [ + - ]: 32 : error = "Raw script is not hex";
2079 : 32 : return {};
2080 : : }
2081 [ + - ]: 3131 : auto bytes = ParseHex(str);
2082 [ + - + - : 3131 : ret.emplace_back(std::make_unique<RawDescriptor>(CScript(bytes.begin(), bytes.end())));
+ - ]
2083 : 3131 : return ret;
2084 [ + - + - : 15176 : } else if (Func("raw", expr)) {
+ + ]
2085 [ + - ]: 6 : error = "Can only have raw() at top level";
2086 : 6 : return {};
2087 : : }
2088 : : // Process miniscript expressions.
2089 : : {
2090 : 12007 : const auto script_ctx{ctx == ParseScriptContext::P2WSH ? miniscript::MiniscriptContext::P2WSH : miniscript::MiniscriptContext::TAPSCRIPT};
2091 [ + - ]: 12007 : KeyParser parser(/*out = */&out, /* in = */nullptr, /* ctx = */script_ctx, key_exp_index);
2092 [ + - + - ]: 12007 : auto node = miniscript::FromString(std::string(expr.begin(), expr.end()), parser);
2093 [ + - + + ]: 12007 : if (parser.m_key_parsing_error != "") {
2094 : 288 : error = std::move(parser.m_key_parsing_error);
2095 : 288 : return {};
2096 : : }
2097 [ + + ]: 11719 : if (node) {
2098 [ + + + + ]: 7888 : if (ctx != ParseScriptContext::P2WSH && ctx != ParseScriptContext::P2TR) {
2099 [ + - ]: 1161 : error = "Miniscript expressions can only be used in wsh or tr.";
2100 : 1161 : return {};
2101 : : }
2102 [ + - + + : 6727 : if (!node->IsSane() || node->IsNotSatisfiable()) {
+ - + + ]
2103 : : // Try to find the first insane sub for better error reporting.
2104 : 2670 : auto insane_node = node.get();
2105 [ + - + + ]: 2670 : if (const auto sub = node->FindInsaneSub()) insane_node = sub;
2106 [ + - - + : 2670 : if (const auto str = insane_node->ToString(parser)) error = *str;
+ - ]
2107 [ + - + + ]: 2670 : if (!insane_node->IsValid()) {
2108 [ + - ]: 1577 : error += " is invalid";
2109 [ + - + + ]: 2670 : } else if (!node->IsSane()) {
2110 [ + - ]: 870 : error += " is not sane";
2111 [ + - + + ]: 870 : if (!insane_node->IsNonMalleable()) {
2112 [ + - ]: 172 : error += ": malleable witnesses exist";
2113 [ + + + - : 870 : } else if (insane_node == node.get() && !insane_node->NeedsSignature()) {
+ + ]
2114 [ + - ]: 127 : error += ": witnesses without signature exist";
2115 [ + - + + ]: 698 : } else if (!insane_node->CheckTimeLocksMix()) {
2116 [ + - ]: 49 : error += ": contains mixes of timelocks expressed in blocks and seconds";
2117 [ + - + + ]: 571 : } else if (!insane_node->CheckDuplicateKey()) {
2118 [ + - ]: 403 : error += ": contains duplicate public keys";
2119 [ + - + + ]: 522 : } else if (!insane_node->ValidSatisfactions()) {
2120 [ + - ]: 66 : error += ": needs witnesses that may exceed resource limits";
2121 : 66 : }
2122 : 870 : } else {
2123 [ + - ]: 223 : error += " is not satisfiable";
2124 : : }
2125 : 2670 : return {};
2126 : 2670 : }
2127 : : // A signature check is required for a miniscript to be sane. Therefore no sane miniscript
2128 : : // may have an empty list of public keys.
2129 [ + - ]: 4057 : CHECK_NONFATAL(!parser.m_keys.empty());
2130 : 4057 : key_exp_index += parser.m_keys.size();
2131 : : // Make sure all vecs are of the same length, or exactly length 1
2132 : : // For length 1 vectors, clone subdescs until vector is the same length
2133 [ + - ]: 4057 : size_t num_multipath = std::max_element(parser.m_keys.begin(), parser.m_keys.end(),
2134 : 5260 : [](const std::vector<std::unique_ptr<PubkeyProvider>>& a, const std::vector<std::unique_ptr<PubkeyProvider>>& b) {
2135 : 5260 : return a.size() < b.size();
2136 : 4057 : })->size();
2137 : :
2138 [ + + - + ]: 13374 : for (auto& vec : parser.m_keys) {
2139 [ + - ]: 9317 : if (vec.size() == 1) {
2140 [ - + ]: 9317 : for (size_t i = 1; i < num_multipath; ++i) {
2141 [ # # # # : 0 : vec.emplace_back(vec.at(0)->Clone());
# # ]
2142 : 0 : }
2143 [ # # ]: 9317 : } else if (vec.size() != num_multipath) {
2144 [ # # ]: 0 : error = strprintf("Miniscript: Multipath derivation paths have mismatched lengths");
2145 : 0 : return {};
2146 : : }
2147 [ - + ]: 9317 : }
2148 : :
2149 : : // Build the final descriptors vector
2150 [ + + ]: 8114 : for (size_t i = 0; i < num_multipath; ++i) {
2151 : : // Build final pubkeys vectors by retrieving the i'th subscript for each vector in subscripts
2152 : 4057 : std::vector<std::unique_ptr<PubkeyProvider>> pubs;
2153 [ + - ]: 4057 : pubs.reserve(parser.m_keys.size());
2154 [ + + ]: 13374 : for (auto& pub : parser.m_keys) {
2155 [ + - + - ]: 9317 : pubs.emplace_back(std::move(pub.at(i)));
2156 : 9317 : }
2157 [ + - + - ]: 4057 : ret.emplace_back(std::make_unique<MiniscriptDescriptor>(std::move(pubs), node));
2158 : 4057 : }
2159 : 4057 : return ret;
2160 : 4057 : }
2161 [ + + ]: 12007 : }
2162 [ + + ]: 3831 : if (ctx == ParseScriptContext::P2SH) {
2163 [ + - ]: 65 : error = "A function is needed within P2SH";
2164 : 65 : return {};
2165 [ + + ]: 3766 : } else if (ctx == ParseScriptContext::P2WSH) {
2166 [ + - ]: 403 : error = "A function is needed within P2WSH";
2167 : 403 : return {};
2168 : : }
2169 [ + - + - ]: 3363 : error = strprintf("'%s' is not a valid descriptor function", std::string(expr.begin(), expr.end()));
2170 : 3363 : return {};
2171 : 72942 : }
2172 : :
2173 : 1308 : std::unique_ptr<DescriptorImpl> InferMultiA(const CScript& script, ParseScriptContext ctx, const SigningProvider& provider)
2174 : : {
2175 : 1308 : auto match = MatchMultiA(script);
2176 [ + + ]: 1308 : if (!match) return {};
2177 : 919 : std::vector<std::unique_ptr<PubkeyProvider>> keys;
2178 [ + - ]: 919 : keys.reserve(match->second.size());
2179 [ + + - + ]: 121806 : for (const auto keyspan : match->second) {
2180 [ - + ]: 120887 : if (keyspan.size() != 32) return {};
2181 [ + - + - ]: 120887 : auto key = InferXOnlyPubkey(XOnlyPubKey{keyspan}, ctx, provider);
2182 [ + - ]: 120887 : if (!key) return {};
2183 [ - + ]: 120887 : keys.push_back(std::move(key));
2184 [ - + - + ]: 120887 : }
2185 [ + - ]: 919 : return std::make_unique<MultiADescriptor>(match->first, std::move(keys));
2186 : 1308 : }
2187 : :
2188 : : // NOLINTNEXTLINE(misc-no-recursion)
2189 : 14295724 : std::unique_ptr<DescriptorImpl> InferScript(const CScript& script, ParseScriptContext ctx, const SigningProvider& provider)
2190 : : {
2191 [ + + + + : 14295724 : if (ctx == ParseScriptContext::P2TR && script.size() == 34 && script[0] == 32 && script[33] == OP_CHECKSIG) {
+ + - + ]
2192 : 1232 : XOnlyPubKey key{Span{script}.subspan(1, 32)};
2193 [ + - ]: 1232 : return std::make_unique<PKDescriptor>(InferXOnlyPubkey(key, ctx, provider), true);
2194 : 1232 : }
2195 : :
2196 [ + + ]: 14294492 : if (ctx == ParseScriptContext::P2TR) {
2197 : 1308 : auto ret = InferMultiA(script, ctx, provider);
2198 [ + + ]: 1308 : if (ret) return ret;
2199 [ + + ]: 1697 : }
2200 : :
2201 : 14293573 : std::vector<std::vector<unsigned char>> data;
2202 [ + - ]: 14293573 : TxoutType txntype = Solver(script, data);
2203 : :
2204 [ + + + + : 14293573 : if (txntype == TxoutType::PUBKEY && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
+ + + - ]
2205 [ + - + - ]: 22528 : CPubKey pubkey(data[0]);
2206 [ + - + + : 43252 : if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
+ + ]
2207 [ + - ]: 20724 : return std::make_unique<PKDescriptor>(std::move(pubkey_provider));
2208 : : }
2209 [ + + ]: 22528 : }
2210 [ + + + + : 14272849 : if (txntype == TxoutType::PUBKEYHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
+ + + + ]
2211 [ + - + - ]: 961018 : uint160 hash(data[0]);
2212 [ + - ]: 961018 : CKeyID keyid(hash);
2213 [ + - ]: 961018 : CPubKey pubkey;
2214 [ + - + + ]: 961018 : if (provider.GetPubKey(keyid, pubkey)) {
2215 [ + - + - : 1882688 : if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
+ - ]
2216 [ + - ]: 941344 : return std::make_unique<PKHDescriptor>(std::move(pubkey_provider));
2217 : : }
2218 : 0 : }
2219 [ + + ]: 961018 : }
2220 [ + + + + : 13331505 : if (txntype == TxoutType::WITNESS_V0_KEYHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH)) {
+ - ]
2221 [ + - + - ]: 5888376 : uint160 hash(data[0]);
2222 [ + - ]: 5888376 : CKeyID keyid(hash);
2223 [ + - ]: 5888376 : CPubKey pubkey;
2224 [ + - + + ]: 5888376 : if (provider.GetPubKey(keyid, pubkey)) {
2225 [ + - + - : 11668880 : if (auto pubkey_provider = InferPubkey(pubkey, ParseScriptContext::P2WPKH, provider)) {
+ - ]
2226 [ + - ]: 5834440 : return std::make_unique<WPKHDescriptor>(std::move(pubkey_provider));
2227 : : }
2228 : 0 : }
2229 [ + + ]: 5888376 : }
2230 [ + + + + : 7497065 : if (txntype == TxoutType::MULTISIG && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
+ + + - ]
2231 : 20099 : bool ok = true;
2232 : 20099 : std::vector<std::unique_ptr<PubkeyProvider>> providers;
2233 [ + + ]: 86294 : for (size_t i = 1; i + 1 < data.size(); ++i) {
2234 [ + - + - ]: 66195 : CPubKey pubkey(data[i]);
2235 [ + - + + : 132390 : if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
+ + ]
2236 [ + - ]: 65520 : providers.push_back(std::move(pubkey_provider));
2237 : 65520 : } else {
2238 : 675 : ok = false;
2239 : 675 : break;
2240 : : }
2241 [ + + ]: 66195 : }
2242 [ + + + - ]: 20099 : if (ok) return std::make_unique<MultisigDescriptor>((int)data[0][0], std::move(providers));
2243 [ + + ]: 20099 : }
2244 [ + + - + ]: 7477641 : if (txntype == TxoutType::SCRIPTHASH && ctx == ParseScriptContext::TOP) {
2245 [ + - + - ]: 5718926 : uint160 hash(data[0]);
2246 [ + - ]: 5718926 : CScriptID scriptid(hash);
2247 : 5718926 : CScript subscript;
2248 [ + - + + ]: 5718926 : if (provider.GetCScript(scriptid, subscript)) {
2249 [ + - ]: 5611390 : auto sub = InferScript(subscript, ParseScriptContext::P2SH, provider);
2250 [ + - + - ]: 5611390 : if (sub) return std::make_unique<SHDescriptor>(std::move(sub));
2251 [ + - ]: 5611390 : }
2252 [ + + ]: 5718926 : }
2253 [ + + + + : 1866251 : if (txntype == TxoutType::WITNESS_V0_SCRIPTHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH)) {
+ - ]
2254 [ + - + - : 53400 : CScriptID scriptid{RIPEMD160(data[0])};
+ - ]
2255 : 53400 : CScript subscript;
2256 [ + - + + ]: 53400 : if (provider.GetCScript(scriptid, subscript)) {
2257 [ + - ]: 1859 : auto sub = InferScript(subscript, ParseScriptContext::P2WSH, provider);
2258 [ + + + - ]: 1859 : if (sub) return std::make_unique<WSHDescriptor>(std::move(sub));
2259 [ + + ]: 1859 : }
2260 [ + + ]: 53400 : }
2261 [ + + - + ]: 1865072 : if (txntype == TxoutType::WITNESS_V1_TAPROOT && ctx == ParseScriptContext::TOP) {
2262 : : // Extract x-only pubkey from output.
2263 [ + - ]: 642717 : XOnlyPubKey pubkey;
2264 [ + - + - ]: 642717 : std::copy(data[0].begin(), data[0].end(), pubkey.begin());
2265 : : // Request spending data.
2266 [ + - ]: 642717 : TaprootSpendData tap;
2267 [ + - + + ]: 642717 : if (provider.GetTaprootSpendData(pubkey, tap)) {
2268 : : // If found, convert it back to tree form.
2269 [ + - ]: 630984 : auto tree = InferTaprootTree(tap, pubkey);
2270 [ + + ]: 630984 : if (tree) {
2271 : : // If that works, try to infer subdescriptors for all leaves.
2272 : 630963 : bool ok = true;
2273 : 630963 : std::vector<std::unique_ptr<DescriptorImpl>> subscripts; //!< list of script subexpressions
2274 : 630963 : std::vector<int> depths; //!< depth in the tree of each subexpression (same length subscripts)
2275 [ + + ]: 636041 : for (const auto& [depth, script, leaf_ver] : *tree) {
2276 : 2540 : std::unique_ptr<DescriptorImpl> subdesc;
2277 [ - + ]: 2540 : if (leaf_ver == TAPROOT_LEAF_TAPSCRIPT) {
2278 [ + - + - : 7620 : subdesc = InferScript(CScript(script.begin(), script.end()), ParseScriptContext::P2TR, provider);
+ - - + ]
2279 : 2540 : }
2280 [ + + ]: 2540 : if (!subdesc) {
2281 : 2 : ok = false;
2282 : 2 : break;
2283 : : } else {
2284 [ + - ]: 2538 : subscripts.push_back(std::move(subdesc));
2285 [ + - ]: 2538 : depths.push_back(depth);
2286 : : }
2287 [ + + + + ]: 2540 : }
2288 [ + + ]: 630963 : if (ok) {
2289 [ + - ]: 630961 : auto key = InferXOnlyPubkey(tap.internal_key, ParseScriptContext::P2TR, provider);
2290 [ + - ]: 630961 : return std::make_unique<TRDescriptor>(std::move(key), std::move(subscripts), std::move(depths));
2291 : 630961 : }
2292 [ + + ]: 630963 : }
2293 [ + + ]: 630984 : }
2294 : : // If the above doesn't work, construct a rawtr() descriptor with just the encoded x-only pubkey.
2295 [ + - + + ]: 11756 : if (pubkey.IsFullyValid()) {
2296 [ + - ]: 7395 : auto key = InferXOnlyPubkey(pubkey, ParseScriptContext::P2TR, provider);
2297 [ + - ]: 7395 : if (key) {
2298 [ + - ]: 7395 : return std::make_unique<RawTRDescriptor>(std::move(key));
2299 : : }
2300 [ + - ]: 7395 : }
2301 [ + + ]: 642717 : }
2302 : :
2303 [ + + + + ]: 1226716 : if (ctx == ParseScriptContext::P2WSH || ctx == ParseScriptContext::P2TR) {
2304 : 1990 : const auto script_ctx{ctx == ParseScriptContext::P2WSH ? miniscript::MiniscriptContext::P2WSH : miniscript::MiniscriptContext::TAPSCRIPT};
2305 [ + - ]: 1990 : KeyParser parser(/* out = */nullptr, /* in = */&provider, /* ctx = */script_ctx);
2306 [ + - ]: 1990 : auto node = miniscript::FromScript(script, parser);
2307 [ + + + - : 1990 : if (node && node->IsSane()) {
+ + ]
2308 : 1308 : std::vector<std::unique_ptr<PubkeyProvider>> keys;
2309 [ + - ]: 1308 : keys.reserve(parser.m_keys.size());
2310 [ + + ]: 5269 : for (auto& key : parser.m_keys) {
2311 [ + - + - ]: 3961 : keys.emplace_back(std::move(key.at(0)));
2312 : 3961 : }
2313 [ + - ]: 1308 : return std::make_unique<MiniscriptDescriptor>(std::move(keys), std::move(node));
2314 : 1308 : }
2315 [ + + ]: 1990 : }
2316 : :
2317 : : // The following descriptors are all top-level only descriptors.
2318 : : // So if we are not at the top level, return early.
2319 [ + + ]: 1225408 : if (ctx != ParseScriptContext::TOP) return nullptr;
2320 : :
2321 : 1224726 : CTxDestination dest;
2322 [ + - + + ]: 1224726 : if (ExtractDestination(script, dest)) {
2323 [ + - + - : 260648 : if (GetScriptForDestination(dest) == script) {
+ - ]
2324 [ + - ]: 260648 : return std::make_unique<AddressDescriptor>(std::move(dest));
2325 : : }
2326 : 0 : }
2327 : :
2328 [ + - ]: 964078 : return std::make_unique<RawDescriptor>(script);
2329 : 14295724 : }
2330 : :
2331 : :
2332 : : } // namespace
2333 : :
2334 : : /** Check a descriptor checksum, and update desc to be the checksum-less part. */
2335 : 61091 : bool CheckChecksum(Span<const char>& sp, bool require_checksum, std::string& error, std::string* out_checksum = nullptr)
2336 : : {
2337 : 61091 : auto check_split = Split(sp, '#');
2338 [ + + ]: 61091 : if (check_split.size() > 2) {
2339 [ + - ]: 281 : error = "Multiple '#' symbols";
2340 : 281 : return false;
2341 : : }
2342 [ + + + + ]: 60810 : if (check_split.size() == 1 && require_checksum){
2343 [ + - ]: 3508 : error = "Missing checksum";
2344 : 3508 : return false;
2345 : : }
2346 [ + + ]: 57302 : if (check_split.size() == 2) {
2347 [ + + ]: 477 : if (check_split[1].size() != 8) {
2348 [ + - ]: 389 : error = strprintf("Expected 8 character checksum, not %u characters", check_split[1].size());
2349 : 389 : return false;
2350 : : }
2351 : 88 : }
2352 [ + - ]: 56913 : auto checksum = DescriptorChecksum(check_split[0]);
2353 [ + + ]: 56913 : if (checksum.empty()) {
2354 [ + - ]: 4682 : error = "Invalid characters in payload";
2355 : 4682 : return false;
2356 : : }
2357 [ + + ]: 52231 : if (check_split.size() == 2) {
2358 [ + - + + ]: 72 : if (!std::equal(checksum.begin(), checksum.end(), check_split[1].begin())) {
2359 [ + - + - ]: 36 : error = strprintf("Provided checksum '%s' does not match computed checksum '%s'", std::string(check_split[1].begin(), check_split[1].end()), checksum);
2360 : 36 : return false;
2361 : : }
2362 : 36 : }
2363 [ + + ]: 52195 : if (out_checksum) *out_checksum = std::move(checksum);
2364 : 52195 : sp = check_split[0];
2365 : 52195 : return true;
2366 : 61091 : }
2367 : :
2368 : 59755 : std::vector<std::unique_ptr<Descriptor>> Parse(const std::string& descriptor, FlatSigningProvider& out, std::string& error, bool require_checksum)
2369 : : {
2370 : 59755 : Span<const char> sp{descriptor};
2371 [ + + ]: 59755 : if (!CheckChecksum(sp, require_checksum, error)) return {};
2372 : 51102 : uint32_t key_exp_index = 0;
2373 : 51102 : auto ret = ParseScript(key_exp_index, sp, ParseScriptContext::TOP, out, error);
2374 [ + + + + ]: 51102 : if (sp.size() == 0 && !ret.empty()) {
2375 : 40929 : std::vector<std::unique_ptr<Descriptor>> descs;
2376 [ + - ]: 40929 : descs.reserve(ret.size());
2377 [ + + ]: 81858 : for (auto& r : ret) {
2378 [ + - ]: 40929 : descs.emplace_back(std::unique_ptr<Descriptor>(std::move(r)));
2379 : 40929 : }
2380 : 40929 : return descs;
2381 [ + - ]: 40929 : }
2382 : 10173 : return {};
2383 : 59755 : }
2384 : :
2385 : 1336 : std::string GetDescriptorChecksum(const std::string& descriptor)
2386 : : {
2387 : 1336 : std::string ret;
2388 : 1336 : std::string error;
2389 [ + - ]: 1336 : Span<const char> sp{descriptor};
2390 [ + - + + : 1336 : if (!CheckChecksum(sp, false, error, &ret)) return "";
+ - ]
2391 : 1093 : return ret;
2392 : 1336 : }
2393 : :
2394 : 8679935 : std::unique_ptr<Descriptor> InferDescriptor(const CScript& script, const SigningProvider& provider)
2395 : : {
2396 : 8679935 : return InferScript(script, ParseScriptContext::TOP, provider);
2397 : : }
2398 : :
2399 : 37047 : uint256 DescriptorID(const Descriptor& desc)
2400 : : {
2401 : 37047 : std::string desc_str = desc.ToString(/*compat_format=*/true);
2402 [ + - ]: 37047 : uint256 id;
2403 [ + - + - : 37047 : CSHA256().Write((unsigned char*)desc_str.data(), desc_str.size()).Finalize(id.begin());
+ - + - ]
2404 : : return id;
2405 : 37047 : }
2406 : :
2407 : 231390 : void DescriptorCache::CacheParentExtPubKey(uint32_t key_exp_pos, const CExtPubKey& xpub)
2408 : : {
2409 : 231390 : m_parent_xpubs[key_exp_pos] = xpub;
2410 : 231390 : }
2411 : :
2412 : 21658 : void DescriptorCache::CacheDerivedExtPubKey(uint32_t key_exp_pos, uint32_t der_index, const CExtPubKey& xpub)
2413 : : {
2414 : 21658 : auto& xpubs = m_derived_xpubs[key_exp_pos];
2415 : 21658 : xpubs[der_index] = xpub;
2416 : 21658 : }
2417 : :
2418 : 9887 : void DescriptorCache::CacheLastHardenedExtPubKey(uint32_t key_exp_pos, const CExtPubKey& xpub)
2419 : : {
2420 : 9887 : m_last_hardened_xpubs[key_exp_pos] = xpub;
2421 : 9887 : }
2422 : :
2423 : 2286183 : bool DescriptorCache::GetCachedParentExtPubKey(uint32_t key_exp_pos, CExtPubKey& xpub) const
2424 : : {
2425 : 2286183 : const auto& it = m_parent_xpubs.find(key_exp_pos);
2426 [ + + ]: 2286183 : if (it == m_parent_xpubs.end()) return false;
2427 : 2214737 : xpub = it->second;
2428 : 2214737 : return true;
2429 : 2286183 : }
2430 : :
2431 : 2169004 : bool DescriptorCache::GetCachedDerivedExtPubKey(uint32_t key_exp_pos, uint32_t der_index, CExtPubKey& xpub) const
2432 : : {
2433 : 2169004 : const auto& key_exp_it = m_derived_xpubs.find(key_exp_pos);
2434 [ + + ]: 2169004 : if (key_exp_it == m_derived_xpubs.end()) return false;
2435 : 24556 : const auto& der_it = key_exp_it->second.find(der_index);
2436 [ + + ]: 24556 : if (der_it == key_exp_it->second.end()) return false;
2437 : 20809 : xpub = der_it->second;
2438 : 20809 : return true;
2439 : 2169004 : }
2440 : :
2441 : 457 : bool DescriptorCache::GetCachedLastHardenedExtPubKey(uint32_t key_exp_pos, CExtPubKey& xpub) const
2442 : : {
2443 : 457 : const auto& it = m_last_hardened_xpubs.find(key_exp_pos);
2444 [ + + ]: 457 : if (it == m_last_hardened_xpubs.end()) return false;
2445 : 71 : xpub = it->second;
2446 : 71 : return true;
2447 : 457 : }
2448 : :
2449 : 782301 : DescriptorCache DescriptorCache::MergeAndDiff(const DescriptorCache& other)
2450 : : {
2451 : 782301 : DescriptorCache diff;
2452 [ + - + + ]: 812549 : for (const auto& parent_xpub_pair : other.GetCachedParentExtPubKeys()) {
2453 [ + - ]: 30248 : CExtPubKey xpub;
2454 [ + - + + ]: 30248 : if (GetCachedParentExtPubKey(parent_xpub_pair.first, xpub)) {
2455 [ + - + - ]: 1020 : if (xpub != parent_xpub_pair.second) {
2456 [ # # # # : 0 : throw std::runtime_error(std::string(__func__) + ": New cached parent xpub does not match already cached parent xpub");
# # # # ]
2457 : : }
2458 : 1020 : continue;
2459 : : }
2460 [ + - ]: 29228 : CacheParentExtPubKey(parent_xpub_pair.first, parent_xpub_pair.second);
2461 [ + - ]: 29228 : diff.CacheParentExtPubKey(parent_xpub_pair.first, parent_xpub_pair.second);
2462 [ + + + + ]: 30248 : }
2463 [ + - + + ]: 784649 : for (const auto& derived_xpub_map_pair : other.GetCachedDerivedExtPubKeys()) {
2464 [ + + ]: 4696 : for (const auto& derived_xpub_pair : derived_xpub_map_pair.second) {
2465 [ + - ]: 2348 : CExtPubKey xpub;
2466 [ + - - + ]: 2348 : if (GetCachedDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, xpub)) {
2467 [ # # # # ]: 0 : if (xpub != derived_xpub_pair.second) {
2468 [ # # # # : 0 : throw std::runtime_error(std::string(__func__) + ": New cached derived xpub does not match already cached derived xpub");
# # # # ]
2469 : : }
2470 : 0 : continue;
2471 : : }
2472 [ + - ]: 2348 : CacheDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, derived_xpub_pair.second);
2473 [ + - ]: 2348 : diff.CacheDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, derived_xpub_pair.second);
2474 [ - + - + ]: 2348 : }
2475 : 2348 : }
2476 [ + - + + ]: 782697 : for (const auto& lh_xpub_pair : other.GetCachedLastHardenedExtPubKeys()) {
2477 [ + - ]: 396 : CExtPubKey xpub;
2478 [ + - + + ]: 396 : if (GetCachedLastHardenedExtPubKey(lh_xpub_pair.first, xpub)) {
2479 [ + - + - ]: 27 : if (xpub != lh_xpub_pair.second) {
2480 [ # # # # : 0 : throw std::runtime_error(std::string(__func__) + ": New cached last hardened xpub does not match already cached last hardened xpub");
# # # # ]
2481 : : }
2482 : 27 : continue;
2483 : : }
2484 [ + - ]: 369 : CacheLastHardenedExtPubKey(lh_xpub_pair.first, lh_xpub_pair.second);
2485 [ + - ]: 369 : diff.CacheLastHardenedExtPubKey(lh_xpub_pair.first, lh_xpub_pair.second);
2486 [ + + + + ]: 396 : }
2487 : 782301 : return diff;
2488 [ + - ]: 782301 : }
2489 : :
2490 : 1631262 : ExtPubKeyMap DescriptorCache::GetCachedParentExtPubKeys() const
2491 : : {
2492 : 1631262 : return m_parent_xpubs;
2493 : : }
2494 : :
2495 : 1631262 : std::unordered_map<uint32_t, ExtPubKeyMap> DescriptorCache::GetCachedDerivedExtPubKeys() const
2496 : : {
2497 : 1631262 : return m_derived_xpubs;
2498 : : }
2499 : :
2500 : 1564602 : ExtPubKeyMap DescriptorCache::GetCachedLastHardenedExtPubKeys() const
2501 : : {
2502 : 1564602 : return m_last_hardened_xpubs;
2503 : : }
|