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 <memory>
25 : : #include <numeric>
26 : : #include <optional>
27 : : #include <string>
28 : : #include <vector>
29 : :
30 : : using util::Split;
31 : :
32 : : namespace {
33 : :
34 : : ////////////////////////////////////////////////////////////////////////////
35 : : // Checksum //
36 : : ////////////////////////////////////////////////////////////////////////////
37 : :
38 : : // This section implements a checksum algorithm for descriptors with the
39 : : // following properties:
40 : : // * Mistakes in a descriptor string are measured in "symbol errors". The higher
41 : : // the number of symbol errors, the harder it is to detect:
42 : : // * An error substituting a character from 0123456789()[],'/*abcdefgh@:$%{} for
43 : : // another in that set always counts as 1 symbol error.
44 : : // * Note that hex encoded keys are covered by these characters. Xprvs and
45 : : // xpubs use other characters too, but already have their own checksum
46 : : // mechanism.
47 : : // * Function names like "multi()" use other characters, but mistakes in
48 : : // these would generally result in an unparsable descriptor.
49 : : // * A case error always counts as 1 symbol error.
50 : : // * Any other 1 character substitution error counts as 1 or 2 symbol errors.
51 : : // * Any 1 symbol error is always detected.
52 : : // * Any 2 or 3 symbol error in a descriptor of up to 49154 characters is always detected.
53 : : // * Any 4 symbol error in a descriptor of up to 507 characters is always detected.
54 : : // * Any 5 symbol error in a descriptor of up to 77 characters is always detected.
55 : : // * Is optimized to minimize the chance a 5 symbol error in a descriptor up to 387 characters is undetected
56 : : // * Random errors have a chance of 1 in 2**40 of being undetected.
57 : : //
58 : : // These properties are achieved by expanding every group of 3 (non checksum) characters into
59 : : // 4 GF(32) symbols, over which a cyclic code is defined.
60 : :
61 : : /*
62 : : * Interprets c as 8 groups of 5 bits which are the coefficients of a degree 8 polynomial over GF(32),
63 : : * multiplies that polynomial by x, computes its remainder modulo a generator, and adds the constant term val.
64 : : *
65 : : * 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}.
66 : : * It is chosen to define an cyclic error detecting code which is selected by:
67 : : * - Starting from all BCH codes over GF(32) of degree 8 and below, which by construction guarantee detecting
68 : : * 3 errors in windows up to 19000 symbols.
69 : : * - Taking all those generators, and for degree 7 ones, extend them to degree 8 by adding all degree-1 factors.
70 : : * - Selecting just the set of generators that guarantee detecting 4 errors in a window of length 512.
71 : : * - Selecting one of those with best worst-case behavior for 5 errors in windows of length up to 512.
72 : : *
73 : : * The generator and the constants to implement it can be verified using this Sage code:
74 : : * B = GF(2) # Binary field
75 : : * BP.<b> = B[] # Polynomials over the binary field
76 : : * F_mod = b**5 + b**3 + 1
77 : : * F.<f> = GF(32, modulus=F_mod, repr='int') # GF(32) definition
78 : : * FP.<x> = F[] # Polynomials over GF(32)
79 : : * E_mod = x**3 + x + F.fetch_int(8)
80 : : * E.<e> = F.extension(E_mod) # Extension field definition
81 : : * alpha = e**2743 # Choice of an element in extension field
82 : : * for p in divisors(E.order() - 1): # Verify alpha has order 32767.
83 : : * assert((alpha**p == 1) == (p % 32767 == 0))
84 : : * G = lcm([(alpha**i).minpoly() for i in [1056,1057,1058]] + [x + 1])
85 : : * print(G) # Print out the generator
86 : : * for i in [1,2,4,8,16]: # Print out {1,2,4,8,16}*(G mod x^8), packed in hex integers.
87 : : * v = 0
88 : : * for coef in reversed((F.fetch_int(i)*(G % x**8)).coefficients(sparse=True)):
89 : : * v = v*32 + coef.integer_representation()
90 : : * print("0x%x" % v)
91 : : */
92 : 279409176 : uint64_t PolyMod(uint64_t c, int val)
93 : : {
94 : 279409176 : uint8_t c0 = c >> 35;
95 : 279409176 : c = ((c & 0x7ffffffff) << 5) ^ val;
96 [ + + ]: 279409176 : if (c0 & 1) c ^= 0xf5dee51989;
97 [ + + ]: 279409176 : if (c0 & 2) c ^= 0xa9fdca3312;
98 [ + + ]: 279409176 : if (c0 & 4) c ^= 0x1bab10e32d;
99 [ + + ]: 279409176 : if (c0 & 8) c ^= 0x3706b1677a;
100 [ + + ]: 279409176 : if (c0 & 16) c ^= 0x644d626ffd;
101 : 279409176 : return c;
102 : : }
103 : :
104 : 284196 : std::string DescriptorChecksum(const Span<const char>& span)
105 : : {
106 : : /** A character set designed such that:
107 : : * - The most common 'unprotected' descriptor characters (hex, keypaths) are in the first group of 32.
108 : : * - Case errors cause an offset that's a multiple of 32.
109 : : * - As many alphabetic characters are in the same group (while following the above restrictions).
110 : : *
111 : : * If p(x) gives the position of a character c in this character set, every group of 3 characters
112 : : * (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).
113 : : * This means that changes that only affect the lower 5 bits of the position, or only the higher 2 bits, will just
114 : : * affect a single symbol.
115 : : *
116 : : * As a result, within-group-of-32 errors count as 1 symbol, as do cross-group errors that don't affect
117 : : * the position within the groups.
118 : : */
119 : 284196 : static const std::string INPUT_CHARSET =
120 : : "0123456789()[],'/*abcdefgh@:$%{}"
121 : : "IJKLMNOPQRSTUVWXYZ&+-.;<=>?!^_|~"
122 [ + + + - : 284740 : "ijklmnopqrstuvwxyzABCDEFGH`#\"\\ ";
+ - ]
123 : :
124 : : /** The character set for the checksum itself (same as bech32). */
125 [ + + + - : 284740 : static const std::string CHECKSUM_CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
+ - ]
126 : :
127 : 284196 : uint64_t c = 1;
128 : 284196 : int cls = 0;
129 : 284196 : int clscount = 0;
130 [ + + ]: 208059771 : for (auto ch : span) {
131 : 207775576 : auto pos = INPUT_CHARSET.find(ch);
132 [ + + ]: 207775576 : if (pos == std::string::npos) return "";
133 : 207775575 : c = PolyMod(c, pos & 31); // Emit a symbol for the position inside the group, for every character.
134 : 207775575 : cls = cls * 3 + (pos >> 5); // Accumulate the group numbers
135 [ + + ]: 207775575 : if (++clscount == 3) {
136 : : // Emit an extra symbol representing the group numbers, for every 3 characters.
137 : 69145504 : c = PolyMod(c, cls);
138 : 69145504 : cls = 0;
139 : 69145504 : clscount = 0;
140 : : }
141 : : }
142 [ + + ]: 284195 : if (clscount > 0) c = PolyMod(c, cls);
143 [ + + ]: 2557755 : for (int j = 0; j < 8; ++j) c = PolyMod(c, 0); // Shift further to determine the checksum.
144 : 284195 : c ^= 1; // Prevent appending zeroes from not affecting the checksum.
145 : :
146 : 284195 : std::string ret(8, ' ');
147 [ + + ]: 2557755 : for (int j = 0; j < 8; ++j) ret[j] = CHECKSUM_CHARSET[(c >> (5 * (7 - j))) & 31];
148 : 284195 : return ret;
149 : 284195 : }
150 : :
151 [ + - + - ]: 550010 : std::string AddChecksum(const std::string& str) { return str + "#" + DescriptorChecksum(str); }
152 : :
153 : : ////////////////////////////////////////////////////////////////////////////
154 : : // Internal representation //
155 : : ////////////////////////////////////////////////////////////////////////////
156 : :
157 : : typedef std::vector<uint32_t> KeyPath;
158 : :
159 : : /** Interface for public key objects in descriptors. */
160 : : struct PubkeyProvider
161 : : {
162 : : protected:
163 : : //! Index of this key expression in the descriptor
164 : : //! E.g. If this PubkeyProvider is key1 in multi(2, key1, key2, key3), then m_expr_index = 0
165 : : uint32_t m_expr_index;
166 : :
167 : : public:
168 : 1499321 : explicit PubkeyProvider(uint32_t exp_index) : m_expr_index(exp_index) {}
169 : :
170 : 0 : virtual ~PubkeyProvider() = default;
171 : :
172 : : /** Compare two public keys represented by this provider.
173 : : * Used by the Miniscript descriptors to check for duplicate keys in the script.
174 : : */
175 : 3784 : bool operator<(PubkeyProvider& other) const {
176 [ + - ]: 3784 : CPubKey a, b;
177 : 3784 : SigningProvider dummy;
178 [ + - ]: 3784 : KeyOriginInfo dummy_info;
179 : :
180 [ + - ]: 3784 : GetPubKey(0, dummy, a, dummy_info);
181 [ + - ]: 3784 : other.GetPubKey(0, dummy, b, dummy_info);
182 : :
183 : 3784 : return a < b;
184 : 3784 : }
185 : :
186 : : /** Derive a public key.
187 : : * read_cache is the cache to read keys from (if not nullptr)
188 : : * write_cache is the cache to write keys to (if not nullptr)
189 : : * Caches are not exclusive but this is not tested. Currently we use them exclusively
190 : : */
191 : : virtual bool GetPubKey(int pos, const SigningProvider& arg, CPubKey& key, KeyOriginInfo& info, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const = 0;
192 : :
193 : : /** Whether this represent multiple public keys at different positions. */
194 : : virtual bool IsRange() const = 0;
195 : :
196 : : /** Get the size of the generated public key(s) in bytes (33 or 65). */
197 : : virtual size_t GetSize() const = 0;
198 : :
199 : : enum class StringType {
200 : : PUBLIC,
201 : : COMPAT // string calculation that mustn't change over time to stay compatible with previous software versions
202 : : };
203 : :
204 : : /** Get the descriptor string form. */
205 : : virtual std::string ToString(StringType type=StringType::PUBLIC) const = 0;
206 : :
207 : : /** Get the descriptor string form including private data (if available in arg). */
208 : : virtual bool ToPrivateString(const SigningProvider& arg, std::string& out) const = 0;
209 : :
210 : : /** Get the descriptor string form with the xpub at the last hardened derivation,
211 : : * and always use h for hardened derivation.
212 : : */
213 : : virtual bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache = nullptr) const = 0;
214 : :
215 : : /** Derive a private key, if private data is available in arg. */
216 : : virtual bool GetPrivKey(int pos, const SigningProvider& arg, CKey& key) const = 0;
217 : :
218 : : /** Return the non-extended public key for this PubkeyProvider, if it has one. */
219 : : virtual std::optional<CPubKey> GetRootPubKey() const = 0;
220 : : /** Return the extended public key for this PubkeyProvider, if it has one. */
221 : : virtual std::optional<CExtPubKey> GetRootExtPubKey() const = 0;
222 : : };
223 : :
224 : : class OriginPubkeyProvider final : public PubkeyProvider
225 : : {
226 : : KeyOriginInfo m_origin;
227 : : std::unique_ptr<PubkeyProvider> m_provider;
228 : : bool m_apostrophe;
229 : :
230 : 122907 : std::string OriginString(StringType type, bool normalized=false) const
231 : : {
232 : : // If StringType==COMPAT, always use the apostrophe to stay compatible with previous versions
233 [ + + + + : 122907 : bool use_apostrophe = (!normalized && m_apostrophe) || type == StringType::COMPAT;
+ + ]
234 [ + - + - ]: 245814 : return HexStr(m_origin.fingerprint) + FormatHDKeypath(m_origin.path, use_apostrophe);
235 : : }
236 : :
237 : : public:
238 : 730571 : 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) {}
239 : 118171 : bool GetPubKey(int pos, const SigningProvider& arg, CPubKey& key, KeyOriginInfo& info, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
240 : : {
241 [ + + ]: 118171 : if (!m_provider->GetPubKey(pos, arg, key, info, read_cache, write_cache)) return false;
242 : 118111 : std::copy(std::begin(m_origin.fingerprint), std::end(m_origin.fingerprint), info.fingerprint);
243 : 118111 : info.path.insert(info.path.begin(), m_origin.path.begin(), m_origin.path.end());
244 : 118111 : return true;
245 : : }
246 : 10173 : bool IsRange() const override { return m_provider->IsRange(); }
247 : 133035 : size_t GetSize() const override { return m_provider->GetSize(); }
248 [ + - + - : 368403 : std::string ToString(StringType type) const override { return "[" + OriginString(type) + "]" + m_provider->ToString(type); }
+ - ]
249 : 68 : bool ToPrivateString(const SigningProvider& arg, std::string& ret) const override
250 : : {
251 [ + - ]: 68 : std::string sub;
252 [ + - + + ]: 68 : if (!m_provider->ToPrivateString(arg, sub)) return false;
253 [ + - + - : 72 : ret = "[" + OriginString(StringType::PUBLIC) + "]" + std::move(sub);
+ - ]
254 : 36 : return true;
255 : 68 : }
256 : 70 : bool ToNormalizedString(const SigningProvider& arg, std::string& ret, const DescriptorCache* cache) const override
257 : : {
258 [ + - ]: 70 : std::string sub;
259 [ + - + - ]: 70 : if (!m_provider->ToNormalizedString(arg, sub, cache)) return false;
260 : : // If m_provider is a BIP32PubkeyProvider, we may get a string formatted like a OriginPubkeyProvider
261 : : // In that case, we need to strip out the leading square bracket and fingerprint from the substring,
262 : : // and append that to our own origin string.
263 [ + + ]: 70 : if (sub[0] == '[') {
264 [ + - ]: 4 : sub = sub.substr(9);
265 [ + - + - : 4 : ret = "[" + OriginString(StringType::PUBLIC, /*normalized=*/true) + std::move(sub);
+ - ]
266 : : } else {
267 [ + - + - : 132 : ret = "[" + OriginString(StringType::PUBLIC, /*normalized=*/true) + "]" + std::move(sub);
+ - ]
268 : : }
269 : : return true;
270 : 70 : }
271 : 137 : bool GetPrivKey(int pos, const SigningProvider& arg, CKey& key) const override
272 : : {
273 : 137 : return m_provider->GetPrivKey(pos, arg, key);
274 : : }
275 : 0 : std::optional<CPubKey> GetRootPubKey() const override
276 : : {
277 : 0 : return m_provider->GetRootPubKey();
278 : : }
279 : 0 : std::optional<CExtPubKey> GetRootExtPubKey() const override
280 : : {
281 : 0 : return m_provider->GetRootExtPubKey();
282 : : }
283 : : };
284 : :
285 : : /** An object representing a parsed constant public key in a descriptor. */
286 : 0 : class ConstPubkeyProvider final : public PubkeyProvider
287 : : {
288 : : CPubKey m_pubkey;
289 : : bool m_xonly;
290 : :
291 : : public:
292 : 762517 : ConstPubkeyProvider(uint32_t exp_index, const CPubKey& pubkey, bool xonly) : PubkeyProvider(exp_index), m_pubkey(pubkey), m_xonly(xonly) {}
293 : 1068618 : bool GetPubKey(int pos, const SigningProvider& arg, CPubKey& key, KeyOriginInfo& info, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
294 : : {
295 : 1068618 : key = m_pubkey;
296 [ + + ]: 1068618 : info.path.clear();
297 : 1068618 : CKeyID keyid = m_pubkey.GetID();
298 : 1068618 : std::copy(keyid.begin(), keyid.begin() + sizeof(info.fingerprint), info.fingerprint);
299 : 1068618 : return true;
300 : : }
301 : 27556 : bool IsRange() const override { return false; }
302 : 147748 : size_t GetSize() const override { return m_pubkey.size(); }
303 [ + + + - ]: 401056 : std::string ToString(StringType type) const override { return m_xonly ? HexStr(m_pubkey).substr(2) : HexStr(m_pubkey); }
304 : 252 : bool ToPrivateString(const SigningProvider& arg, std::string& ret) const override
305 : : {
306 : 252 : CKey key;
307 [ + + ]: 252 : if (m_xonly) {
308 [ + - + - : 48 : for (const auto& keyid : XOnlyPubKey(m_pubkey).GetKeyIDs()) {
+ + ]
309 [ + - ]: 40 : arg.GetKey(keyid, key);
310 [ + + ]: 40 : if (key.IsValid()) break;
311 : 20 : }
312 : : } else {
313 [ + - + - ]: 232 : arg.GetKey(m_pubkey.GetID(), key);
314 : : }
315 [ + + ]: 252 : if (!key.IsValid()) return false;
316 [ + - ]: 185 : ret = EncodeSecret(key);
317 : 185 : return true;
318 : 252 : }
319 : 4316 : bool ToNormalizedString(const SigningProvider& arg, std::string& ret, const DescriptorCache* cache) const override
320 : : {
321 : 4316 : ret = ToString(StringType::PUBLIC);
322 : 4316 : return true;
323 : : }
324 : 41277 : bool GetPrivKey(int pos, const SigningProvider& arg, CKey& key) const override
325 : : {
326 : 41277 : return arg.GetKey(m_pubkey.GetID(), key);
327 : : }
328 : 9 : std::optional<CPubKey> GetRootPubKey() const override
329 : : {
330 : 9 : return m_pubkey;
331 : : }
332 : 9 : std::optional<CExtPubKey> GetRootExtPubKey() const override
333 : : {
334 : 9 : return std::nullopt;
335 : : }
336 : : };
337 : :
338 : : enum class DeriveType {
339 : : NO,
340 : : UNHARDENED,
341 : : HARDENED,
342 : : };
343 : :
344 : : /** An object representing a parsed extended public key in a descriptor. */
345 : : class BIP32PubkeyProvider final : public PubkeyProvider
346 : : {
347 : : // Root xpub, path, and final derivation step type being used, if any
348 : : CExtPubKey m_root_extkey;
349 : : KeyPath m_path;
350 : : DeriveType m_derive;
351 : : // Whether ' or h is used in harded derivation
352 : : bool m_apostrophe;
353 : :
354 : 32809 : bool GetExtKey(const SigningProvider& arg, CExtKey& ret) const
355 : : {
356 : 32809 : CKey key;
357 [ + - + - : 32809 : if (!arg.GetKey(m_root_extkey.pubkey.GetID(), key)) return false;
+ + ]
358 : 31366 : ret.nDepth = m_root_extkey.nDepth;
359 : 31366 : std::copy(m_root_extkey.vchFingerprint, m_root_extkey.vchFingerprint + sizeof(ret.vchFingerprint), ret.vchFingerprint);
360 : 31366 : ret.nChild = m_root_extkey.nChild;
361 : 31366 : ret.chaincode = m_root_extkey.chaincode;
362 [ + - ]: 31366 : ret.key = key;
363 : : return true;
364 : 32809 : }
365 : :
366 : : // Derives the last xprv
367 : 32552 : bool GetDerivedExtKey(const SigningProvider& arg, CExtKey& xprv, CExtKey& last_hardened) const
368 : : {
369 [ + + ]: 32552 : if (!GetExtKey(arg, xprv)) return false;
370 [ + + ]: 98184 : for (auto entry : m_path) {
371 [ + - ]: 66998 : if (!xprv.Derive(xprv, entry)) return false;
372 [ + + ]: 66998 : if (entry >> 31) {
373 : 52689 : last_hardened = xprv;
374 : : }
375 : : }
376 : : return true;
377 : : }
378 : :
379 : 35708 : bool IsHardened() const
380 : : {
381 [ + + ]: 35708 : if (m_derive == DeriveType::HARDENED) return true;
382 [ + + ]: 34382 : for (auto entry : m_path) {
383 [ + + ]: 23309 : if (entry >> 31) return true;
384 : : }
385 : : return false;
386 : : }
387 : :
388 : : public:
389 : 6233 : 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) {}
390 : 215089 : bool IsRange() const override { return m_derive != DeriveType::NO; }
391 : 505 : size_t GetSize() const override { return 33; }
392 : 702169 : 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
393 : : {
394 : : // Info of parent of the to be derived pubkey
395 [ + - ]: 702169 : KeyOriginInfo parent_info;
396 [ + - ]: 702169 : CKeyID keyid = m_root_extkey.pubkey.GetID();
397 : 702169 : std::copy(keyid.begin(), keyid.begin() + sizeof(parent_info.fingerprint), parent_info.fingerprint);
398 [ + - ]: 702169 : parent_info.path = m_path;
399 : :
400 : : // Info of the derived key itself which is copied out upon successful completion
401 [ + - ]: 702169 : KeyOriginInfo final_info_out_tmp = parent_info;
402 [ + + + - ]: 702169 : if (m_derive == DeriveType::UNHARDENED) final_info_out_tmp.path.push_back((uint32_t)pos);
403 [ + + + - ]: 702169 : if (m_derive == DeriveType::HARDENED) final_info_out_tmp.path.push_back(((uint32_t)pos) | 0x80000000L);
404 : :
405 : : // Derive keys or fetch them from cache
406 : 702169 : CExtPubKey final_extkey = m_root_extkey;
407 : 702169 : CExtPubKey parent_extkey = m_root_extkey;
408 [ + + ]: 702169 : CExtPubKey last_hardened_extkey;
409 : 702169 : bool der = true;
410 [ + + ]: 702169 : if (read_cache) {
411 [ + + ]: 666461 : if (!read_cache->GetCachedDerivedExtPubKey(m_expr_index, pos, final_extkey)) {
412 [ + + ]: 662177 : if (m_derive == DeriveType::HARDENED) return false;
413 : : // Try to get the derivation parent
414 [ + + ]: 651129 : if (!read_cache->GetCachedParentExtPubKey(m_expr_index, parent_extkey)) return false;
415 : 647931 : final_extkey = parent_extkey;
416 [ + + + - ]: 647931 : if (m_derive == DeriveType::UNHARDENED) der = parent_extkey.Derive(final_extkey, pos);
417 : : }
418 [ + + ]: 35708 : } else if (IsHardened()) {
419 [ + - ]: 24635 : CExtKey xprv;
420 : 24635 : CExtKey lh_xprv;
421 [ + - + + ]: 24635 : if (!GetDerivedExtKey(arg, xprv, lh_xprv)) return false;
422 [ + - ]: 24524 : parent_extkey = xprv.Neuter();
423 [ + + + - ]: 24524 : if (m_derive == DeriveType::UNHARDENED) der = xprv.Derive(xprv, pos);
424 [ + + + - ]: 24524 : if (m_derive == DeriveType::HARDENED) der = xprv.Derive(xprv, pos | 0x80000000UL);
425 [ + - ]: 24524 : final_extkey = xprv.Neuter();
426 [ + + ]: 24524 : if (lh_xprv.key.IsValid()) {
427 [ + - ]: 21499 : last_hardened_extkey = lh_xprv.Neuter();
428 : : }
429 : 24635 : } else {
430 [ + + ]: 26866 : for (auto entry : m_path) {
431 [ + - + - ]: 15793 : if (!parent_extkey.Derive(parent_extkey, entry)) return false;
432 : : }
433 : 11073 : final_extkey = parent_extkey;
434 [ + + + - ]: 11073 : if (m_derive == DeriveType::UNHARDENED) der = parent_extkey.Derive(final_extkey, pos);
435 [ - + ]: 11073 : assert(m_derive != DeriveType::HARDENED);
436 : : }
437 [ + - ]: 682939 : if (!der) return false;
438 : :
439 [ + - ]: 687812 : final_info_out = final_info_out_tmp;
440 : 687812 : key_out = final_extkey.pubkey;
441 : :
442 [ + + ]: 687812 : if (write_cache) {
443 : : // Only cache parent if there is any unhardened derivation
444 [ + + ]: 14914 : if (m_derive != DeriveType::HARDENED) {
445 [ + - ]: 3921 : write_cache->CacheParentExtPubKey(m_expr_index, parent_extkey);
446 : : // Cache last hardened xpub if we have it
447 [ + + ]: 3921 : if (last_hardened_extkey.pubkey.IsValid()) {
448 [ + - ]: 2930 : write_cache->CacheLastHardenedExtPubKey(m_expr_index, last_hardened_extkey);
449 : : }
450 [ + - ]: 10993 : } else if (final_info_out.path.size() > 0) {
451 [ + - ]: 10993 : write_cache->CacheDerivedExtPubKey(m_expr_index, pos, final_extkey);
452 : : }
453 : : }
454 : :
455 : : return true;
456 : 702169 : }
457 : 122860 : std::string ToString(StringType type, bool normalized) const
458 : : {
459 : : // If StringType==COMPAT, always use the apostrophe to stay compatible with previous versions
460 [ + + + + : 122860 : const bool use_apostrophe = (!normalized && m_apostrophe) || type == StringType::COMPAT;
+ + ]
461 [ + - + - ]: 245720 : std::string ret = EncodeExtPubKey(m_root_extkey) + FormatHDKeypath(m_path, /*apostrophe=*/use_apostrophe);
462 [ + + ]: 122860 : if (IsRange()) {
463 [ + - ]: 121609 : ret += "/*";
464 [ + + + + ]: 121609 : if (m_derive == DeriveType::HARDENED) ret += use_apostrophe ? '\'' : 'h';
465 : : }
466 : 122860 : return ret;
467 : 0 : }
468 : 122838 : std::string ToString(StringType type=StringType::PUBLIC) const override
469 : : {
470 : 122588 : return ToString(type, /*normalized=*/false);
471 : : }
472 : 257 : bool ToPrivateString(const SigningProvider& arg, std::string& out) const override
473 : : {
474 [ + - ]: 257 : CExtKey key;
475 [ + - + + ]: 257 : if (!GetExtKey(arg, key)) return false;
476 [ + - + - : 180 : out = EncodeExtKey(key) + FormatHDKeypath(m_path, /*apostrophe=*/m_apostrophe);
+ - ]
477 [ + + ]: 180 : if (IsRange()) {
478 [ + - ]: 78 : out += "/*";
479 [ + + + + ]: 265 : if (m_derive == DeriveType::HARDENED) out += m_apostrophe ? '\'' : 'h';
480 : : }
481 : : return true;
482 : 257 : }
483 : 1158 : bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache) const override
484 : : {
485 [ + + ]: 1158 : if (m_derive == DeriveType::HARDENED) {
486 : 22 : out = ToString(StringType::PUBLIC, /*normalized=*/true);
487 : :
488 : 22 : return true;
489 : : }
490 : : // Step backwards to find the last hardened step in the path
491 : 1136 : int i = (int)m_path.size() - 1;
492 [ + + ]: 2088 : for (; i >= 0; --i) {
493 [ + + ]: 1838 : if (m_path.at(i) >> 31) {
494 : : break;
495 : : }
496 : : }
497 : : // Either no derivation or all unhardened derivation
498 [ + + ]: 1136 : if (i == -1) {
499 : 250 : out = ToString();
500 : 250 : return true;
501 : : }
502 : : // Get the path to the last hardened stup
503 : 886 : KeyOriginInfo origin;
504 : 886 : int k = 0;
505 [ + + ]: 3520 : for (; k <= i; ++k) {
506 : : // Add to the path
507 [ + - + - ]: 2634 : origin.path.push_back(m_path.at(k));
508 : : }
509 : : // Build the remaining path
510 : 886 : KeyPath end_path;
511 [ + + ]: 1777 : for (; k < (int)m_path.size(); ++k) {
512 [ + - + - ]: 891 : end_path.push_back(m_path.at(k));
513 : : }
514 : : // Get the fingerprint
515 [ + - ]: 886 : CKeyID id = m_root_extkey.pubkey.GetID();
516 : 886 : std::copy(id.begin(), id.begin() + 4, origin.fingerprint);
517 : :
518 [ + + ]: 886 : CExtPubKey xpub;
519 [ + + ]: 886 : CExtKey lh_xprv;
520 : : // If we have the cache, just get the parent xpub
521 [ + + ]: 886 : if (cache != nullptr) {
522 : 870 : cache->GetCachedLastHardenedExtPubKey(m_expr_index, xpub);
523 : : }
524 [ + + ]: 886 : if (!xpub.pubkey.IsValid()) {
525 : : // Cache miss, or nor cache, or need privkey
526 [ + - ]: 16 : CExtKey xprv;
527 [ + - - + ]: 16 : if (!GetDerivedExtKey(arg, xprv, lh_xprv)) return false;
528 [ + - ]: 16 : xpub = lh_xprv.Neuter();
529 : 16 : }
530 [ - + ]: 886 : assert(xpub.pubkey.IsValid());
531 : :
532 : : // Build the string
533 [ + - + - : 1772 : std::string origin_str = HexStr(origin.fingerprint) + FormatHDKeypath(origin.path);
+ - ]
534 [ + - + - : 1772 : out = "[" + origin_str + "]" + EncodeExtPubKey(xpub) + FormatHDKeypath(end_path);
+ - + - +
- ]
535 [ + + ]: 886 : if (IsRange()) {
536 [ + - ]: 874 : out += "/*";
537 [ - + ]: 874 : assert(m_derive == DeriveType::UNHARDENED);
538 : : }
539 : 886 : return true;
540 : 1772 : }
541 : 7901 : bool GetPrivKey(int pos, const SigningProvider& arg, CKey& key) const override
542 : : {
543 [ + - ]: 7901 : CExtKey extkey;
544 : 7901 : CExtKey dummy;
545 [ + - + + ]: 7901 : if (!GetDerivedExtKey(arg, extkey, dummy)) return false;
546 [ + + + - : 6646 : if (m_derive == DeriveType::UNHARDENED && !extkey.Derive(extkey, pos)) return false;
+ - ]
547 [ + + + - : 6646 : if (m_derive == DeriveType::HARDENED && !extkey.Derive(extkey, pos | 0x80000000UL)) return false;
+ - ]
548 [ + - ]: 6646 : key = extkey.key;
549 : : return true;
550 : 7901 : }
551 : 248 : std::optional<CPubKey> GetRootPubKey() const override
552 : : {
553 : 248 : return std::nullopt;
554 : : }
555 : 248 : std::optional<CExtPubKey> GetRootExtPubKey() const override
556 : : {
557 : 248 : return m_root_extkey;
558 : : }
559 : : };
560 : :
561 : : /** Base class for all Descriptor implementations. */
562 : : class DescriptorImpl : public Descriptor
563 : : {
564 : : protected:
565 : : //! Public key arguments for this descriptor (size 1 for PK, PKH, WPKH; any size for WSH and Multisig).
566 : : const std::vector<std::unique_ptr<PubkeyProvider>> m_pubkey_args;
567 : : //! The string name of the descriptor function.
568 : : const std::string m_name;
569 : :
570 : : //! The sub-descriptor arguments (empty for everything but SH and WSH).
571 : : //! In doc/descriptors.m this is referred to as SCRIPT expressions sh(SCRIPT)
572 : : //! and wsh(SCRIPT), and distinct from KEY expressions and ADDR expressions.
573 : : //! Subdescriptors can only ever generate a single script.
574 : : const std::vector<std::unique_ptr<DescriptorImpl>> m_subdescriptor_args;
575 : :
576 : : //! Return a serialization of anything except pubkey and script arguments, to be prepended to those.
577 : 316364 : virtual std::string ToStringExtra() const { return ""; }
578 : :
579 : : /** A helper function to construct the scripts for this descriptor.
580 : : *
581 : : * This function is invoked once by ExpandHelper.
582 : : *
583 : : * @param pubkeys The evaluations of the m_pubkey_args field.
584 : : * @param scripts The evaluations of m_subdescriptor_args (one for each m_subdescriptor_args element).
585 : : * @param out A FlatSigningProvider to put scripts or public keys in that are necessary to the solver.
586 : : * The origin info of the provided pubkeys is automatically added.
587 : : * @return A vector with scriptPubKeys for this descriptor.
588 : : */
589 : : virtual std::vector<CScript> MakeScripts(const std::vector<CPubKey>& pubkeys, Span<const CScript> scripts, FlatSigningProvider& out) const = 0;
590 : :
591 : : public:
592 [ + - ]: 639501 : DescriptorImpl(std::vector<std::unique_ptr<PubkeyProvider>> pubkeys, const std::string& name) : m_pubkey_args(std::move(pubkeys)), m_name(name), m_subdescriptor_args() {}
593 [ + - + - ]: 58000 : 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))) {}
594 [ + - ]: 6009 : 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)) {}
595 : :
596 : : enum class StringType
597 : : {
598 : : PUBLIC,
599 : : PRIVATE,
600 : : NORMALIZED,
601 : : COMPAT, // string calculation that mustn't change over time to stay compatible with previous software versions
602 : : };
603 : :
604 : : // NOLINTNEXTLINE(misc-no-recursion)
605 : 20524 : bool IsSolvable() const override
606 : : {
607 [ + + ]: 22414 : for (const auto& arg : m_subdescriptor_args) {
608 [ + - ]: 1890 : if (!arg->IsSolvable()) return false;
609 : : }
610 : : return true;
611 : : }
612 : :
613 : : // NOLINTNEXTLINE(misc-no-recursion)
614 : 116886 : bool IsRange() const final
615 : : {
616 [ + + ]: 144693 : for (const auto& pubkey : m_pubkey_args) {
617 [ + + ]: 118719 : if (pubkey->IsRange()) return true;
618 : : }
619 [ + + ]: 28241 : for (const auto& arg : m_subdescriptor_args) {
620 [ + + ]: 9891 : if (arg->IsRange()) return true;
621 : : }
622 : : return false;
623 : : }
624 : :
625 : : // NOLINTNEXTLINE(misc-no-recursion)
626 : 319061 : virtual bool ToStringSubScriptHelper(const SigningProvider* arg, std::string& ret, const StringType type, const DescriptorCache* cache = nullptr) const
627 : : {
628 : 319061 : size_t pos = 0;
629 [ + + ]: 366718 : for (const auto& scriptarg : m_subdescriptor_args) {
630 [ - + ]: 47746 : if (pos++) ret += ",";
631 [ + - ]: 47746 : std::string tmp;
632 [ + - + + ]: 47746 : if (!scriptarg->ToStringHelper(arg, tmp, type, cache)) return false;
633 [ + - ]: 95314 : ret += tmp;
634 : 47746 : }
635 : : return true;
636 : : }
637 : :
638 : : // NOLINTNEXTLINE(misc-no-recursion)
639 : 326140 : virtual bool ToStringHelper(const SigningProvider* arg, std::string& out, const StringType type, const DescriptorCache* cache = nullptr) const
640 : : {
641 : 326140 : std::string extra = ToStringExtra();
642 [ + + ]: 326140 : size_t pos = extra.size() > 0 ? 1 : 0;
643 [ + - + - ]: 326140 : std::string ret = m_name + "(" + extra;
644 [ + + ]: 717662 : for (const auto& pubkey : m_pubkey_args) {
645 [ + + + - ]: 391638 : if (pos++) ret += ",";
646 [ + + + + : 391638 : std::string tmp;
- ]
647 [ + + + + : 391638 : switch (type) {
- ]
648 : 5474 : case StringType::NORMALIZED:
649 [ + - + - ]: 5474 : if (!pubkey->ToNormalizedString(*arg, tmp, cache)) return false;
650 : : break;
651 : 417 : case StringType::PRIVATE:
652 [ + - + + ]: 417 : if (!pubkey->ToPrivateString(*arg, tmp)) return false;
653 : : break;
654 : 370152 : case StringType::PUBLIC:
655 [ + - ]: 370152 : tmp = pubkey->ToString();
656 : 370152 : break;
657 : 15595 : case StringType::COMPAT:
658 [ + - ]: 15595 : tmp = pubkey->ToString(PubkeyProvider::StringType::COMPAT);
659 : 15595 : break;
660 : : }
661 [ + - ]: 783044 : ret += tmp;
662 : 391638 : }
663 [ + - ]: 652048 : std::string subscript;
664 [ + - + + ]: 326024 : if (!ToStringSubScriptHelper(arg, subscript, type, cache)) return false;
665 [ + + + + : 325935 : if (pos && subscript.size()) ret += ',';
+ - ]
666 [ + - ]: 651870 : out = std::move(ret) + std::move(subscript) + ")";
667 : 325935 : return true;
668 : 326140 : }
669 : :
670 : 273514 : std::string ToString(bool compat_format) const final
671 : : {
672 [ + + ]: 273514 : std::string ret;
673 [ + + + - ]: 541136 : ToStringHelper(nullptr, ret, compat_format ? StringType::COMPAT : StringType::PUBLIC);
674 [ + - ]: 273514 : return AddChecksum(ret);
675 : 273514 : }
676 : :
677 : 322 : bool ToPrivateString(const SigningProvider& arg, std::string& out) const override
678 : : {
679 : 322 : bool ret = ToStringHelper(&arg, out, StringType::PRIVATE);
680 : 322 : out = AddChecksum(out);
681 : 322 : return ret;
682 : : }
683 : :
684 : 1169 : bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache) const override final
685 : : {
686 : 1169 : bool ret = ToStringHelper(&arg, out, StringType::NORMALIZED, cache);
687 : 1169 : out = AddChecksum(out);
688 : 1169 : return ret;
689 : : }
690 : :
691 : : // NOLINTNEXTLINE(misc-no-recursion)
692 : 824787 : bool ExpandHelper(int pos, const SigningProvider& arg, const DescriptorCache* read_cache, std::vector<CScript>& output_scripts, FlatSigningProvider& out, DescriptorCache* write_cache) const
693 : : {
694 : 824787 : std::vector<std::pair<CPubKey, KeyOriginInfo>> entries;
695 [ + - ]: 824787 : entries.reserve(m_pubkey_args.size());
696 : :
697 : : // Construct temporary data in `entries`, `subscripts`, and `subprovider` to avoid producing output in case of failure.
698 [ + + ]: 2573649 : for (const auto& p : m_pubkey_args) {
699 [ + - ]: 1763219 : entries.emplace_back();
700 [ + - + + ]: 1763219 : if (!p->GetPubKey(pos, arg, entries.back().first, entries.back().second, read_cache, write_cache)) return false;
701 : : }
702 : 810430 : std::vector<CScript> subscripts;
703 : 810430 : FlatSigningProvider subprovider;
704 [ + + ]: 984585 : for (const auto& subarg : m_subdescriptor_args) {
705 : 175293 : std::vector<CScript> outscripts;
706 [ + - + + ]: 175293 : if (!subarg->ExpandHelper(pos, arg, read_cache, outscripts, subprovider, write_cache)) return false;
707 [ - + ]: 174155 : assert(outscripts.size() == 1);
708 [ + - ]: 174155 : subscripts.emplace_back(std::move(outscripts[0]));
709 : 175293 : }
710 [ + - ]: 809292 : out.Merge(std::move(subprovider));
711 : :
712 : 809292 : std::vector<CPubKey> pubkeys;
713 [ + - ]: 809292 : pubkeys.reserve(entries.size());
714 [ + + ]: 2558090 : for (auto& entry : entries) {
715 [ + - ]: 1748798 : pubkeys.push_back(entry.first);
716 [ + - + - ]: 3497596 : out.origins.emplace(entry.first.GetID(), std::make_pair<CPubKey, KeyOriginInfo>(CPubKey(entry.first), std::move(entry.second)));
717 : : }
718 : :
719 [ + - ]: 1618584 : output_scripts = MakeScripts(pubkeys, Span{subscripts}, out);
720 : 809292 : return true;
721 : 824787 : }
722 : :
723 : 96032 : bool Expand(int pos, const SigningProvider& provider, std::vector<CScript>& output_scripts, FlatSigningProvider& out, DescriptorCache* write_cache = nullptr) const final
724 : : {
725 : 96032 : return ExpandHelper(pos, provider, nullptr, output_scripts, out, write_cache);
726 : : }
727 : :
728 : 553462 : bool ExpandFromCache(int pos, const DescriptorCache& read_cache, std::vector<CScript>& output_scripts, FlatSigningProvider& out) const final
729 : : {
730 : 553462 : return ExpandHelper(pos, DUMMY_SIGNING_PROVIDER, &read_cache, output_scripts, out, nullptr);
731 : : }
732 : :
733 : : // NOLINTNEXTLINE(misc-no-recursion)
734 : 14177 : void ExpandPrivate(int pos, const SigningProvider& provider, FlatSigningProvider& out) const final
735 : : {
736 [ + + ]: 63355 : for (const auto& p : m_pubkey_args) {
737 : 49178 : CKey key;
738 [ + - + + ]: 49178 : if (!p->GetPrivKey(pos, provider, key)) continue;
739 [ + - + - : 11884 : out.keys.emplace(key.GetPubKey().GetID(), key);
+ - ]
740 : 49178 : }
741 [ + + ]: 16528 : for (const auto& arg : m_subdescriptor_args) {
742 : 2351 : arg->ExpandPrivate(pos, provider, out);
743 : : }
744 : 14177 : }
745 : :
746 : 1648 : std::optional<OutputType> GetOutputType() const override { return std::nullopt; }
747 : :
748 : 0 : std::optional<int64_t> ScriptSize() const override { return {}; }
749 : :
750 : : /** A helper for MaxSatisfactionWeight.
751 : : *
752 : : * @param use_max_sig Whether to assume ECDSA signatures will have a high-r.
753 : : * @return The maximum size of the satisfaction in raw bytes (with no witness meaning).
754 : : */
755 : 0 : virtual std::optional<int64_t> MaxSatSize(bool use_max_sig) const { return {}; }
756 : :
757 : 300 : std::optional<int64_t> MaxSatisfactionWeight(bool) const override { return {}; }
758 : :
759 : 4 : std::optional<int64_t> MaxSatisfactionElems() const override { return {}; }
760 : :
761 : : // NOLINTNEXTLINE(misc-no-recursion)
762 : 313 : void GetPubKeys(std::set<CPubKey>& pubkeys, std::set<CExtPubKey>& ext_pubs) const override
763 : : {
764 [ + + ]: 570 : for (const auto& p : m_pubkey_args) {
765 : 257 : std::optional<CPubKey> pub = p->GetRootPubKey();
766 [ + + ]: 257 : if (pub) pubkeys.insert(*pub);
767 : 257 : std::optional<CExtPubKey> ext_pub = p->GetRootExtPubKey();
768 [ + + ]: 257 : if (ext_pub) ext_pubs.insert(*ext_pub);
769 : : }
770 [ + + ]: 371 : for (const auto& arg : m_subdescriptor_args) {
771 : 58 : arg->GetPubKeys(pubkeys, ext_pubs);
772 : : }
773 : 313 : }
774 : : };
775 : :
776 : : /** A parsed addr(A) descriptor. */
777 : : class AddressDescriptor final : public DescriptorImpl
778 : : {
779 : : const CTxDestination m_destination;
780 : : protected:
781 : 4700 : std::string ToStringExtra() const override { return EncodeDestination(m_destination); }
782 [ + - ]: 4036 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, Span<const CScript>, FlatSigningProvider&) const override { return Vector(GetScriptForDestination(m_destination)); }
783 : : public:
784 [ + - ]: 6789 : AddressDescriptor(CTxDestination destination) : DescriptorImpl({}, "addr"), m_destination(std::move(destination)) {}
785 : 25 : bool IsSolvable() const final { return false; }
786 : :
787 : 69 : std::optional<OutputType> GetOutputType() const override
788 : : {
789 : 69 : return OutputTypeFromDestination(m_destination);
790 : : }
791 : 0 : bool IsSingleType() const final { return true; }
792 : 10 : bool ToPrivateString(const SigningProvider& arg, std::string& out) const final { return false; }
793 : :
794 [ # # ]: 0 : std::optional<int64_t> ScriptSize() const override { return GetScriptForDestination(m_destination).size(); }
795 : : };
796 : :
797 : : /** A parsed raw(H) descriptor. */
798 : : class RawDescriptor final : public DescriptorImpl
799 : : {
800 : : const CScript m_script;
801 : : protected:
802 [ + + ]: 3046 : std::string ToStringExtra() const override { return HexStr(m_script); }
803 : 1762 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, Span<const CScript>, FlatSigningProvider&) const override { return Vector(m_script); }
804 : : public:
805 [ + - ]: 3236 : RawDescriptor(CScript script) : DescriptorImpl({}, "raw"), m_script(std::move(script)) {}
806 : 0 : bool IsSolvable() const final { return false; }
807 : :
808 : 2 : std::optional<OutputType> GetOutputType() const override
809 : : {
810 : 2 : CTxDestination dest;
811 [ + - ]: 2 : ExtractDestination(m_script, dest);
812 [ + - ]: 2 : return OutputTypeFromDestination(dest);
813 : 2 : }
814 : 0 : bool IsSingleType() const final { return true; }
815 : 1 : bool ToPrivateString(const SigningProvider& arg, std::string& out) const final { return false; }
816 : :
817 [ # # ]: 0 : std::optional<int64_t> ScriptSize() const override { return m_script.size(); }
818 : : };
819 : :
820 : : /** A parsed pk(P) descriptor. */
821 : : class PKDescriptor final : public DescriptorImpl
822 : : {
823 : : private:
824 : : const bool m_xonly;
825 : : protected:
826 : 27508 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript>, FlatSigningProvider&) const override
827 : : {
828 [ + + ]: 27508 : if (m_xonly) {
829 [ + - + - : 26664 : CScript script = CScript() << ToByteVector(XOnlyPubKey(keys[0])) << OP_CHECKSIG;
+ - ]
830 [ + - ]: 26664 : return Vector(std::move(script));
831 : 26664 : } else {
832 [ + - ]: 1688 : return Vector(GetScriptForRawPubKey(keys[0]));
833 : : }
834 : : }
835 : : public:
836 [ + - + - ]: 23463 : PKDescriptor(std::unique_ptr<PubkeyProvider> prov, bool xonly = false) : DescriptorImpl(Vector(std::move(prov)), "pk"), m_xonly(xonly) {}
837 : 4 : bool IsSingleType() const final { return true; }
838 : :
839 : 314 : std::optional<int64_t> ScriptSize() const override {
840 [ + - ]: 314 : return 1 + (m_xonly ? 32 : m_pubkey_args[0]->GetSize()) + 1;
841 : : }
842 : :
843 : 522 : std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
844 [ + + ]: 311 : const auto ecdsa_sig_size = use_max_sig ? 72 : 71;
845 [ + - + - ]: 522 : return 1 + (m_xonly ? 65 : ecdsa_sig_size);
846 : : }
847 : :
848 : 211 : std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
849 [ + + ]: 211 : return *MaxSatSize(use_max_sig) * WITNESS_SCALE_FACTOR;
850 : : }
851 : :
852 : 516 : std::optional<int64_t> MaxSatisfactionElems() const override { return 1; }
853 : : };
854 : :
855 : : /** A parsed pkh(P) descriptor. */
856 : : class PKHDescriptor final : public DescriptorImpl
857 : : {
858 : : protected:
859 : 160850 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript>, FlatSigningProvider& out) const override
860 : : {
861 : 160850 : CKeyID id = keys[0].GetID();
862 : 160850 : out.pubkeys.emplace(id, keys[0]);
863 [ + - + - ]: 321700 : return Vector(GetScriptForDestination(PKHash(id)));
864 : : }
865 : : public:
866 [ + - + - ]: 211519 : PKHDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "pkh") {}
867 : 155972 : std::optional<OutputType> GetOutputType() const override { return OutputType::LEGACY; }
868 : 16539 : bool IsSingleType() const final { return true; }
869 : :
870 : 417 : std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 1 + 20 + 1 + 1; }
871 : :
872 : 126362 : std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
873 [ + + ]: 126362 : const auto sig_size = use_max_sig ? 72 : 71;
874 : 126362 : return 1 + sig_size + 1 + m_pubkey_args[0]->GetSize();
875 : : }
876 : :
877 : 125952 : std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
878 : 125952 : return *MaxSatSize(use_max_sig) * WITNESS_SCALE_FACTOR;
879 : : }
880 : :
881 : 126352 : std::optional<int64_t> MaxSatisfactionElems() const override { return 2; }
882 : : };
883 : :
884 : : /** A parsed wpkh(P) descriptor. */
885 : : class WPKHDescriptor final : public DescriptorImpl
886 : : {
887 : : protected:
888 : 302330 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript>, FlatSigningProvider& out) const override
889 : : {
890 : 302330 : CKeyID id = keys[0].GetID();
891 : 302330 : out.pubkeys.emplace(id, keys[0]);
892 [ + - + - ]: 604660 : return Vector(GetScriptForDestination(WitnessV0KeyHash(id)));
893 : : }
894 : : public:
895 [ + - + - ]: 372956 : WPKHDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "wpkh") {}
896 : 306400 : std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32; }
897 : 26637 : bool IsSingleType() const final { return true; }
898 : :
899 : 17061 : std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 20; }
900 : :
901 : 262689 : std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
902 [ + + ]: 17058 : const auto sig_size = use_max_sig ? 72 : 71;
903 : 262689 : return (1 + sig_size + 1 + 33);
904 : : }
905 : :
906 : 245631 : std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
907 [ + + ]: 245631 : return MaxSatSize(use_max_sig);
908 : : }
909 : :
910 : 262683 : std::optional<int64_t> MaxSatisfactionElems() const override { return 2; }
911 : : };
912 : :
913 : : /** A parsed combo(P) descriptor. */
914 : : class ComboDescriptor final : public DescriptorImpl
915 : : {
916 : : protected:
917 : 19146 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript>, FlatSigningProvider& out) const override
918 : : {
919 : 19146 : std::vector<CScript> ret;
920 [ + - ]: 19146 : CKeyID id = keys[0].GetID();
921 [ + - ]: 19146 : out.pubkeys.emplace(id, keys[0]);
922 [ + - + - ]: 19146 : ret.emplace_back(GetScriptForRawPubKey(keys[0])); // P2PK
923 [ + - + - : 38292 : ret.emplace_back(GetScriptForDestination(PKHash(id))); // P2PKH
+ - ]
924 [ + + ]: 19146 : if (keys[0].IsCompressed()) {
925 [ + - ]: 19121 : CScript p2wpkh = GetScriptForDestination(WitnessV0KeyHash(id));
926 [ + - + - ]: 19121 : out.scripts.emplace(CScriptID(p2wpkh), p2wpkh);
927 [ + - ]: 19121 : ret.emplace_back(p2wpkh);
928 [ + - + - : 38242 : ret.emplace_back(GetScriptForDestination(ScriptHash(p2wpkh))); // P2SH-P2WPKH
+ - ]
929 : 19121 : }
930 : 19146 : return ret;
931 : 0 : }
932 : : public:
933 [ + - + - ]: 461 : ComboDescriptor(std::unique_ptr<PubkeyProvider> prov) : DescriptorImpl(Vector(std::move(prov)), "combo") {}
934 : 5 : bool IsSingleType() const final { return false; }
935 : : };
936 : :
937 : : /** A parsed multi(...) or sortedmulti(...) descriptor */
938 : : class MultisigDescriptor final : public DescriptorImpl
939 : : {
940 : : const int m_threshold;
941 : : const bool m_sorted;
942 : : protected:
943 : 2755 : std::string ToStringExtra() const override { return strprintf("%i", m_threshold); }
944 : 19804 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript>, FlatSigningProvider&) const override {
945 [ + + ]: 19804 : if (m_sorted) {
946 : 2833 : std::vector<CPubKey> sorted_keys(keys);
947 : 2833 : std::sort(sorted_keys.begin(), sorted_keys.end());
948 [ + - + - ]: 5666 : return Vector(GetScriptForMultisig(m_threshold, sorted_keys));
949 : 2833 : }
950 [ + - ]: 33942 : return Vector(GetScriptForMultisig(m_threshold, keys));
951 : : }
952 : : public:
953 [ + + + - ]: 8664 : 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) {}
954 : 5 : bool IsSingleType() const final { return true; }
955 : :
956 : 1144 : std::optional<int64_t> ScriptSize() const override {
957 : 1144 : const auto n_keys = m_pubkey_args.size();
958 : 2256 : auto op = [](int64_t acc, const std::unique_ptr<PubkeyProvider>& pk) { return acc + 1 + pk->GetSize();};
959 : 1144 : const auto pubkeys_size{std::accumulate(m_pubkey_args.begin(), m_pubkey_args.end(), int64_t{0}, op)};
960 [ - + + - ]: 2288 : return 1 + BuildScript(n_keys).size() + BuildScript(m_threshold).size() + pubkeys_size;
961 : : }
962 : :
963 : 1311 : std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
964 [ + + ]: 1139 : const auto sig_size = use_max_sig ? 72 : 71;
965 : 1311 : return (1 + (1 + sig_size) * m_threshold);
966 : : }
967 : :
968 : 172 : std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
969 [ + + ]: 172 : return *MaxSatSize(use_max_sig) * WITNESS_SCALE_FACTOR;
970 : : }
971 : :
972 : 1294 : std::optional<int64_t> MaxSatisfactionElems() const override { return 1 + m_threshold; }
973 : : };
974 : :
975 : : /** A parsed (sorted)multi_a(...) descriptor. Always uses x-only pubkeys. */
976 : : class MultiADescriptor final : public DescriptorImpl
977 : : {
978 : : const int m_threshold;
979 : : const bool m_sorted;
980 : : protected:
981 : 798 : std::string ToStringExtra() const override { return strprintf("%i", m_threshold); }
982 : 6950 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript>, FlatSigningProvider&) const override {
983 : 6950 : CScript ret;
984 : 6950 : std::vector<XOnlyPubKey> xkeys;
985 [ + - ]: 6950 : xkeys.reserve(keys.size());
986 [ + - + + ]: 999840 : for (const auto& key : keys) xkeys.emplace_back(key);
987 [ + + ]: 6950 : if (m_sorted) std::sort(xkeys.begin(), xkeys.end());
988 [ + - + - ]: 6950 : ret << ToByteVector(xkeys[0]) << OP_CHECKSIG;
989 [ + + ]: 992890 : for (size_t i = 1; i < keys.size(); ++i) {
990 [ + - + - ]: 1971880 : ret << ToByteVector(xkeys[i]) << OP_CHECKSIGADD;
991 : : }
992 [ + - + - ]: 6950 : ret << m_threshold << OP_NUMEQUAL;
993 [ + - ]: 6950 : return Vector(std::move(ret));
994 : 6950 : }
995 : : public:
996 [ + + + - ]: 1790 : 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) {}
997 : 0 : bool IsSingleType() const final { return true; }
998 : :
999 : 0 : std::optional<int64_t> ScriptSize() const override {
1000 : 0 : const auto n_keys = m_pubkey_args.size();
1001 [ # # ]: 0 : return (1 + 32 + 1) * n_keys + BuildScript(m_threshold).size() + 1;
1002 : : }
1003 : :
1004 : 0 : std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
1005 : 0 : return (1 + 65) * m_threshold + (m_pubkey_args.size() - m_threshold);
1006 : : }
1007 : :
1008 : 0 : std::optional<int64_t> MaxSatisfactionElems() const override { return m_pubkey_args.size(); }
1009 : : };
1010 : :
1011 : : /** A parsed sh(...) descriptor. */
1012 : : class SHDescriptor final : public DescriptorImpl
1013 : : {
1014 : : protected:
1015 : 122295 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, Span<const CScript> scripts, FlatSigningProvider& out) const override
1016 : : {
1017 [ + - + - ]: 244590 : auto ret = Vector(GetScriptForDestination(ScriptHash(scripts[0])));
1018 [ + - + - : 122295 : if (ret.size()) out.scripts.emplace(CScriptID(scripts[0]), scripts[0]);
+ - ]
1019 : 122295 : return ret;
1020 : 0 : }
1021 : :
1022 [ + + ]: 41538 : bool IsSegwit() const { return m_subdescriptor_args[0]->GetOutputType() == OutputType::BECH32; }
1023 : :
1024 : : public:
1025 [ + - ]: 53902 : SHDescriptor(std::unique_ptr<DescriptorImpl> desc) : DescriptorImpl({}, std::move(desc), "sh") {}
1026 : :
1027 : 23319 : std::optional<OutputType> GetOutputType() const override
1028 : : {
1029 [ - + ]: 23319 : assert(m_subdescriptor_args.size() == 1);
1030 [ + + ]: 23319 : if (IsSegwit()) return OutputType::P2SH_SEGWIT;
1031 : 815 : return OutputType::LEGACY;
1032 : : }
1033 : 1560 : bool IsSingleType() const final { return true; }
1034 : :
1035 : 19 : std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 20 + 1; }
1036 : :
1037 : 18219 : std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
1038 [ + - ]: 18219 : if (const auto sat_size = m_subdescriptor_args[0]->MaxSatSize(use_max_sig)) {
1039 [ + - ]: 18219 : if (const auto subscript_size = m_subdescriptor_args[0]->ScriptSize()) {
1040 : : // The subscript is never witness data.
1041 : 18219 : const auto subscript_weight = (1 + *subscript_size) * WITNESS_SCALE_FACTOR;
1042 : : // The weight depends on whether the inner descriptor is satisfied using the witness stack.
1043 [ + + ]: 18219 : if (IsSegwit()) return subscript_weight + *sat_size;
1044 : 627 : return subscript_weight + *sat_size * WITNESS_SCALE_FACTOR;
1045 : : }
1046 : : }
1047 : 0 : return {};
1048 : : }
1049 : :
1050 : 18200 : std::optional<int64_t> MaxSatisfactionElems() const override {
1051 [ + - ]: 18200 : if (const auto sub_elems = m_subdescriptor_args[0]->MaxSatisfactionElems()) return 1 + *sub_elems;
1052 : 0 : return {};
1053 : : }
1054 : : };
1055 : :
1056 : : /** A parsed wsh(...) descriptor. */
1057 : : class WSHDescriptor final : public DescriptorImpl
1058 : : {
1059 : : protected:
1060 : 17901 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>&, Span<const CScript> scripts, FlatSigningProvider& out) const override
1061 : : {
1062 [ + - + - ]: 35802 : auto ret = Vector(GetScriptForDestination(WitnessV0ScriptHash(scripts[0])));
1063 [ + - + - : 17901 : if (ret.size()) out.scripts.emplace(CScriptID(scripts[0]), scripts[0]);
+ - ]
1064 : 17901 : return ret;
1065 : 0 : }
1066 : : public:
1067 [ + - ]: 4098 : WSHDescriptor(std::unique_ptr<DescriptorImpl> desc) : DescriptorImpl({}, std::move(desc), "wsh") {}
1068 : 2409 : std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32; }
1069 : 395 : bool IsSingleType() const final { return true; }
1070 : :
1071 : 550 : std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
1072 : :
1073 : 1357 : std::optional<int64_t> MaxSatSize(bool use_max_sig) const override {
1074 [ + - ]: 1357 : if (const auto sat_size = m_subdescriptor_args[0]->MaxSatSize(use_max_sig)) {
1075 [ + - ]: 1357 : if (const auto subscript_size = m_subdescriptor_args[0]->ScriptSize()) {
1076 [ + + ]: 1412 : return GetSizeOfCompactSize(*subscript_size) + *subscript_size + *sat_size;
1077 : : }
1078 : : }
1079 : 0 : return {};
1080 : : }
1081 : :
1082 : 823 : std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const override {
1083 : 823 : return MaxSatSize(use_max_sig);
1084 : : }
1085 : :
1086 : 1333 : std::optional<int64_t> MaxSatisfactionElems() const override {
1087 [ + - ]: 1333 : if (const auto sub_elems = m_subdescriptor_args[0]->MaxSatisfactionElems()) return 1 + *sub_elems;
1088 : 0 : return {};
1089 : : }
1090 : : };
1091 : :
1092 : : /** A parsed tr(...) descriptor. */
1093 : : class TRDescriptor final : public DescriptorImpl
1094 : : {
1095 : : std::vector<int> m_depths;
1096 : : protected:
1097 : 126778 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript> scripts, FlatSigningProvider& out) const override
1098 : : {
1099 [ - + ]: 126778 : TaprootBuilder builder;
1100 [ - + ]: 126778 : assert(m_depths.size() == scripts.size());
1101 [ + + ]: 160728 : for (size_t pos = 0; pos < m_depths.size(); ++pos) {
1102 [ + + + - ]: 67900 : builder.Add(m_depths[pos], scripts[pos], TAPROOT_LEAF_TAPSCRIPT);
1103 : : }
1104 [ - + ]: 126778 : if (!builder.IsComplete()) return {};
1105 [ - + ]: 126778 : assert(keys.size() == 1);
1106 [ + - ]: 126778 : XOnlyPubKey xpk(keys[0]);
1107 [ + - - + ]: 126778 : if (!xpk.IsFullyValid()) return {};
1108 [ + - ]: 126778 : builder.Finalize(xpk);
1109 [ + - ]: 126778 : WitnessV1Taproot output = builder.GetOutput();
1110 [ + - + - ]: 126778 : out.tr_trees[output] = builder;
1111 [ + - + - ]: 126778 : out.pubkeys.emplace(keys[0].GetID(), keys[0]);
1112 [ + - + - ]: 253556 : return Vector(GetScriptForDestination(output));
1113 : 126778 : }
1114 : 6963 : bool ToStringSubScriptHelper(const SigningProvider* arg, std::string& ret, const StringType type, const DescriptorCache* cache = nullptr) const override
1115 : : {
1116 [ + + ]: 6963 : if (m_depths.empty()) return true;
1117 : 1621 : std::vector<bool> path;
1118 [ + + ]: 5739 : for (size_t pos = 0; pos < m_depths.size(); ++pos) {
1119 [ + + + - ]: 4118 : if (pos) ret += ',';
1120 [ + + ]: 8236 : while ((int)path.size() <= m_depths[pos]) {
1121 [ + + + - ]: 4118 : if (path.size()) ret += '{';
1122 [ + - ]: 4118 : path.push_back(false);
1123 : : }
1124 [ + - ]: 4118 : std::string tmp;
1125 [ + - - + ]: 4118 : if (!m_subdescriptor_args[pos]->ToStringHelper(arg, tmp, type, cache)) return false;
1126 [ + - ]: 4118 : ret += tmp;
1127 [ + - + + ]: 6615 : while (!path.empty() && path.back()) {
1128 [ + - + - ]: 2497 : if (path.size() > 1) ret += '}';
1129 : 2497 : path.pop_back();
1130 : : }
1131 [ + - ]: 4118 : if (!path.empty()) path.back() = true;
1132 : 4118 : }
1133 : : return true;
1134 : 1621 : }
1135 : : public:
1136 : 6009 : TRDescriptor(std::unique_ptr<PubkeyProvider> internal_key, std::vector<std::unique_ptr<DescriptorImpl>> descs, std::vector<int> depths) :
1137 [ + - + - : 6009 : DescriptorImpl(Vector(std::move(internal_key)), std::move(descs), "tr"), m_depths(std::move(depths))
- + ]
1138 : : {
1139 [ - + ]: 6009 : assert(m_subdescriptor_args.size() == m_depths.size());
1140 : 6009 : }
1141 : 8890 : std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32M; }
1142 : 1616 : bool IsSingleType() const final { return true; }
1143 : :
1144 : 11 : std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
1145 : :
1146 : 3885 : std::optional<int64_t> MaxSatisfactionWeight(bool) const override {
1147 : : // FIXME: We assume keypath spend, which can lead to very large underestimations.
1148 : 3885 : return 1 + 65;
1149 : : }
1150 : :
1151 : 3874 : std::optional<int64_t> MaxSatisfactionElems() const override {
1152 : : // FIXME: See above, we assume keypath spend.
1153 : 3874 : return 1;
1154 : : }
1155 : : };
1156 : :
1157 : : /* We instantiate Miniscript here with a simple integer as key type.
1158 : : * The value of these key integers are an index in the
1159 : : * DescriptorImpl::m_pubkey_args vector.
1160 : : */
1161 : :
1162 : : /**
1163 : : * The context for converting a Miniscript descriptor into a Script.
1164 : : */
1165 : : class ScriptMaker {
1166 : : //! Keys contained in the Miniscript (the evaluation of DescriptorImpl::m_pubkey_args).
1167 : : const std::vector<CPubKey>& m_keys;
1168 : : //! The script context we're operating within (Tapscript or P2WSH).
1169 : : const miniscript::MiniscriptContext m_script_ctx;
1170 : :
1171 : : //! Get the ripemd160(sha256()) hash of this key.
1172 : : //! Any key that is valid in a descriptor serializes as 32 bytes within a Tapscript context. So we
1173 : : //! must not hash the sign-bit byte in this case.
1174 : 389 : uint160 GetHash160(uint32_t key) const {
1175 [ + + ]: 389 : if (miniscript::IsTapscript(m_script_ctx)) {
1176 : 179 : return Hash160(XOnlyPubKey{m_keys[key]});
1177 : : }
1178 : 210 : return m_keys[key].GetID();
1179 : : }
1180 : :
1181 : : public:
1182 : 880 : ScriptMaker(const std::vector<CPubKey>& keys LIFETIMEBOUND, const miniscript::MiniscriptContext script_ctx) : m_keys(keys), m_script_ctx{script_ctx} {}
1183 : :
1184 : 1583 : std::vector<unsigned char> ToPKBytes(uint32_t key) const {
1185 : : // In Tapscript keys always serialize as x-only, whether an x-only key was used in the descriptor or not.
1186 [ + + ]: 1583 : if (!miniscript::IsTapscript(m_script_ctx)) {
1187 : 952 : return {m_keys[key].begin(), m_keys[key].end()};
1188 : : }
1189 : 631 : const XOnlyPubKey xonly_pubkey{m_keys[key]};
1190 : 631 : return {xonly_pubkey.begin(), xonly_pubkey.end()};
1191 : : }
1192 : :
1193 : 389 : std::vector<unsigned char> ToPKHBytes(uint32_t key) const {
1194 : 389 : auto id = GetHash160(key);
1195 : 389 : return {id.begin(), id.end()};
1196 : : }
1197 : : };
1198 : :
1199 : : /**
1200 : : * The context for converting a Miniscript descriptor to its textual form.
1201 : : */
1202 : : class StringMaker {
1203 : : //! To convert private keys for private descriptors.
1204 : : const SigningProvider* m_arg;
1205 : : //! Keys contained in the Miniscript (a reference to DescriptorImpl::m_pubkey_args).
1206 : : const std::vector<std::unique_ptr<PubkeyProvider>>& m_pubkeys;
1207 : : //! Whether to serialize keys as private or public.
1208 : : bool m_private;
1209 : :
1210 : : public:
1211 : 729 : StringMaker(const SigningProvider* arg LIFETIMEBOUND, const std::vector<std::unique_ptr<PubkeyProvider>>& pubkeys LIFETIMEBOUND, bool priv)
1212 : 729 : : m_arg(arg), m_pubkeys(pubkeys), m_private(priv) {}
1213 : :
1214 : 4134 : std::optional<std::string> ToString(uint32_t key) const
1215 : : {
1216 [ + + ]: 4134 : std::string ret;
1217 [ + + ]: 4134 : if (m_private) {
1218 [ + - + + ]: 92 : if (!m_pubkeys[key]->ToPrivateString(*m_arg, ret)) return {};
1219 : : } else {
1220 [ + - ]: 4042 : ret = m_pubkeys[key]->ToString();
1221 : : }
1222 : 4106 : return ret;
1223 : 4134 : }
1224 : : };
1225 : :
1226 : : class MiniscriptDescriptor final : public DescriptorImpl
1227 : : {
1228 : : private:
1229 : : miniscript::NodeRef<uint32_t> m_node;
1230 : :
1231 : : protected:
1232 : 880 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript> scripts,
1233 : : FlatSigningProvider& provider) const override
1234 : : {
1235 : 880 : const auto script_ctx{m_node->GetMsCtx()};
1236 [ + + ]: 2852 : for (const auto& key : keys) {
1237 [ + + ]: 1972 : if (miniscript::IsTapscript(script_ctx)) {
1238 : 810 : provider.pubkeys.emplace(Hash160(XOnlyPubKey{key}), key);
1239 : : } else {
1240 : 1162 : provider.pubkeys.emplace(key.GetID(), key);
1241 : : }
1242 : : }
1243 [ + - ]: 1760 : return Vector(m_node->ToScript(ScriptMaker(keys, script_ctx)));
1244 : : }
1245 : :
1246 : : public:
1247 : 525 : MiniscriptDescriptor(std::vector<std::unique_ptr<PubkeyProvider>> providers, miniscript::NodeRef<uint32_t> node)
1248 [ + - ]: 525 : : DescriptorImpl(std::move(providers), "?"), m_node(std::move(node)) {}
1249 : :
1250 : 729 : bool ToStringHelper(const SigningProvider* arg, std::string& out, const StringType type,
1251 : : const DescriptorCache* cache = nullptr) const override
1252 : : {
1253 [ + + ]: 729 : if (const auto res = m_node->ToString(StringMaker(arg, m_pubkey_args, type == StringType::PRIVATE))) {
1254 [ + - ]: 701 : out = *res;
1255 : 701 : return true;
1256 : 701 : }
1257 : 28 : return false;
1258 : : }
1259 : :
1260 : 270 : bool IsSolvable() const override { return true; }
1261 : 0 : bool IsSingleType() const final { return true; }
1262 : :
1263 : 124 : std::optional<int64_t> ScriptSize() const override { return m_node->ScriptSize(); }
1264 : :
1265 : 124 : std::optional<int64_t> MaxSatSize(bool) const override {
1266 : : // For Miniscript we always assume high-R ECDSA signatures.
1267 [ + - ]: 124 : return m_node->GetWitnessSize();
1268 : : }
1269 : :
1270 : 110 : std::optional<int64_t> MaxSatisfactionElems() const override {
1271 [ + - ]: 110 : return m_node->GetStackSize();
1272 : : }
1273 : : };
1274 : :
1275 : : /** A parsed rawtr(...) descriptor. */
1276 : : class RawTRDescriptor final : public DescriptorImpl
1277 : : {
1278 : : protected:
1279 : 1070 : std::vector<CScript> MakeScripts(const std::vector<CPubKey>& keys, Span<const CScript> scripts, FlatSigningProvider& out) const override
1280 : : {
1281 [ - + ]: 1070 : assert(keys.size() == 1);
1282 : 1070 : XOnlyPubKey xpk(keys[0]);
1283 [ - + ]: 1070 : if (!xpk.IsFullyValid()) return {};
1284 [ + - ]: 1070 : WitnessV1Taproot output{xpk};
1285 [ + - + - ]: 2140 : return Vector(GetScriptForDestination(output));
1286 : : }
1287 : : public:
1288 [ + - + - ]: 15292 : RawTRDescriptor(std::unique_ptr<PubkeyProvider> output_key) : DescriptorImpl(Vector(std::move(output_key)), "rawtr") {}
1289 : 177 : std::optional<OutputType> GetOutputType() const override { return OutputType::BECH32M; }
1290 : 62 : bool IsSingleType() const final { return true; }
1291 : :
1292 : 3 : std::optional<int64_t> ScriptSize() const override { return 1 + 1 + 32; }
1293 : :
1294 : 118 : std::optional<int64_t> MaxSatisfactionWeight(bool) const override {
1295 : : // We can't know whether there is a script path, so assume key path spend.
1296 : 118 : return 1 + 65;
1297 : : }
1298 : :
1299 : 115 : std::optional<int64_t> MaxSatisfactionElems() const override {
1300 : : // See above, we assume keypath spend.
1301 : 115 : return 1;
1302 : : }
1303 : : };
1304 : :
1305 : : ////////////////////////////////////////////////////////////////////////////
1306 : : // Parser //
1307 : : ////////////////////////////////////////////////////////////////////////////
1308 : :
1309 : : enum class ParseScriptContext {
1310 : : TOP, //!< Top-level context (script goes directly in scriptPubKey)
1311 : : P2SH, //!< Inside sh() (script becomes P2SH redeemScript)
1312 : : P2WPKH, //!< Inside wpkh() (no script, pubkey only)
1313 : : P2WSH, //!< Inside wsh() (script becomes v0 witness script)
1314 : : P2TR, //!< Inside tr() (either internal key, or BIP342 script leaf)
1315 : : };
1316 : :
1317 : : /**
1318 : : * Parse a key path, being passed a split list of elements (the first element is ignored).
1319 : : *
1320 : : * @param[in] split BIP32 path string, using either ' or h for hardened derivation
1321 : : * @param[out] out the key path
1322 : : * @param[out] apostrophe only updated if hardened derivation is found
1323 : : * @param[out] error parsing error message
1324 : : * @returns false if parsing failed
1325 : : **/
1326 : 11296 : [[nodiscard]] bool ParseKeyPath(const std::vector<Span<const char>>& split, KeyPath& out, bool& apostrophe, std::string& error)
1327 : : {
1328 [ + + ]: 34009 : for (size_t i = 1; i < split.size(); ++i) {
1329 [ + - ]: 22717 : Span<const char> elem = split[i];
1330 : 22717 : bool hardened = false;
1331 [ + - ]: 22717 : if (elem.size() > 0) {
1332 [ + + ]: 22717 : const char last = elem[elem.size() - 1];
1333 [ + + ]: 22717 : if (last == '\'' || last == 'h') {
1334 : 17022 : elem = elem.first(elem.size() - 1);
1335 : 17022 : hardened = true;
1336 : 17022 : apostrophe = last == '\'';
1337 : : }
1338 : : }
1339 : 22717 : uint32_t p;
1340 [ + - + + ]: 22717 : if (!ParseUInt32(std::string(elem.begin(), elem.end()), &p)) {
1341 [ + - ]: 2 : error = strprintf("Key path value '%s' is not a valid uint32", std::string(elem.begin(), elem.end()));
1342 : 2 : return false;
1343 [ + + ]: 22715 : } else if (p > 0x7FFFFFFFUL) {
1344 : 2 : error = strprintf("Key path value %u is out of range", p);
1345 : 2 : return false;
1346 : : }
1347 : 22713 : out.push_back(p | (((uint32_t)hardened) << 31));
1348 : : }
1349 : : return true;
1350 : : }
1351 : :
1352 : : /** Parse a public key that excludes origin information. */
1353 : 26570 : std::unique_ptr<PubkeyProvider> ParsePubkeyInner(uint32_t key_exp_index, const Span<const char>& sp, ParseScriptContext ctx, FlatSigningProvider& out, bool& apostrophe, std::string& error)
1354 : : {
1355 : 26570 : bool permit_uncompressed = ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH;
1356 : 26570 : auto split = Split(sp, '/');
1357 [ + - + + ]: 53140 : std::string str(split[0].begin(), split[0].end());
1358 [ + + ]: 26570 : if (str.size() == 0) {
1359 [ + - ]: 2 : error = "No key provided";
1360 : 2 : return nullptr;
1361 : : }
1362 [ + + ]: 26568 : if (split.size() == 1) {
1363 [ + - + + ]: 20415 : if (IsHex(str)) {
1364 [ + - ]: 19868 : std::vector<unsigned char> data = ParseHex(str);
1365 : 19868 : CPubKey pubkey(data);
1366 [ + + + + ]: 19868 : if (pubkey.IsValid() && !pubkey.IsValidNonHybrid()) {
1367 [ + - ]: 4 : error = "Hybrid public keys are not allowed";
1368 : 4 : return nullptr;
1369 : : }
1370 [ + - + + ]: 19864 : if (pubkey.IsFullyValid()) {
1371 [ + + + + ]: 1336 : if (permit_uncompressed || pubkey.IsCompressed()) {
1372 [ + - ]: 1332 : return std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, false);
1373 : : } else {
1374 [ + - ]: 4 : error = "Uncompressed keys are not allowed";
1375 : 4 : return nullptr;
1376 : : }
1377 [ + - + + ]: 18528 : } else if (data.size() == 32 && ctx == ParseScriptContext::P2TR) {
1378 : 18527 : unsigned char fullkey[33] = {0x02};
1379 : 18527 : std::copy(data.begin(), data.end(), fullkey + 1);
1380 : 18527 : pubkey.Set(std::begin(fullkey), std::end(fullkey));
1381 [ + - + - ]: 18527 : if (pubkey.IsFullyValid()) {
1382 [ + - ]: 18527 : return std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, true);
1383 : : }
1384 : : }
1385 [ + - ]: 1 : error = strprintf("Pubkey '%s' is invalid", str);
1386 : 1 : return nullptr;
1387 : 19868 : }
1388 [ + - ]: 547 : CKey key = DecodeSecret(str);
1389 [ + + ]: 547 : if (key.IsValid()) {
1390 [ + + + + ]: 460 : if (permit_uncompressed || key.IsCompressed()) {
1391 [ + - ]: 455 : CPubKey pubkey = key.GetPubKey();
1392 [ + - + - ]: 455 : out.keys.emplace(pubkey.GetID(), key);
1393 [ + - ]: 455 : return std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, ctx == ParseScriptContext::P2TR);
1394 : : } else {
1395 [ + - ]: 5 : error = "Uncompressed keys are not allowed";
1396 : 5 : return nullptr;
1397 : : }
1398 : : }
1399 : 547 : }
1400 [ + - ]: 6240 : CExtKey extkey = DecodeExtKey(str);
1401 [ + - ]: 6240 : CExtPubKey extpubkey = DecodeExtPubKey(str);
1402 [ + + + + ]: 6240 : if (!extkey.key.IsValid() && !extpubkey.pubkey.IsValid()) {
1403 [ + - ]: 3 : error = strprintf("key '%s' is not valid", str);
1404 : 3 : return nullptr;
1405 : : }
1406 : 6237 : KeyPath path;
1407 : 6237 : DeriveType type = DeriveType::NO;
1408 [ + + ]: 6237 : if (split.back() == Span{"*"}.first(1)) {
1409 : 5939 : split.pop_back();
1410 : 5939 : type = DeriveType::UNHARDENED;
1411 [ + + + + ]: 298 : } else if (split.back() == Span{"*'"}.first(2) || split.back() == Span{"*h"}.first(2)) {
1412 : 133 : apostrophe = split.back() == Span{"*'"}.first(2);
1413 : 133 : split.pop_back();
1414 : 133 : type = DeriveType::HARDENED;
1415 : : }
1416 [ + - + + ]: 6237 : if (!ParseKeyPath(split, path, apostrophe, error)) return nullptr;
1417 [ + + ]: 6233 : if (extkey.key.IsValid()) {
1418 [ + - ]: 562 : extpubkey = extkey.Neuter();
1419 [ + - + - ]: 562 : out.keys.emplace(extpubkey.pubkey.GetID(), extkey.key);
1420 : : }
1421 [ + - - + ]: 6233 : return std::make_unique<BIP32PubkeyProvider>(key_exp_index, extpubkey, std::move(path), type, apostrophe);
1422 : 39047 : }
1423 : :
1424 : : /** Parse a public key including origin information (if enabled). */
1425 : 26584 : std::unique_ptr<PubkeyProvider> ParsePubkey(uint32_t key_exp_index, const Span<const char>& sp, ParseScriptContext ctx, FlatSigningProvider& out, std::string& error)
1426 : : {
1427 : 26584 : auto origin_split = Split(sp, ']');
1428 [ + + ]: 26584 : if (origin_split.size() > 2) {
1429 [ + - ]: 4 : error = "Multiple ']' characters found for a single pubkey";
1430 : 4 : return nullptr;
1431 : : }
1432 : : // This is set if either the origin or path suffix contains a hardened derivation.
1433 : 26580 : bool apostrophe = false;
1434 [ + + ]: 26580 : if (origin_split.size() == 1) {
1435 [ + - ]: 21511 : return ParsePubkeyInner(key_exp_index, origin_split[0], ctx, out, apostrophe, error);
1436 : : }
1437 [ + - + + ]: 5069 : if (origin_split[0].empty() || origin_split[0][0] != '[') {
1438 : 6 : error = strprintf("Key origin start '[ character expected but not found, got '%c' instead",
1439 [ + - + - ]: 2 : origin_split[0].empty() ? /** empty, implies split char */ ']' : origin_split[0][0]);
1440 : 2 : return nullptr;
1441 : : }
1442 [ + - ]: 5067 : auto slash_split = Split(origin_split[0].subspan(1), '/');
1443 [ + + ]: 5067 : if (slash_split[0].size() != 8) {
1444 [ + - ]: 6 : error = strprintf("Fingerprint is not 4 bytes (%u characters instead of 8 characters)", slash_split[0].size());
1445 : 6 : return nullptr;
1446 : : }
1447 [ + - + - ]: 10122 : std::string fpr_hex = std::string(slash_split[0].begin(), slash_split[0].end());
1448 [ + - + + ]: 5061 : if (!IsHex(fpr_hex)) {
1449 [ + - ]: 2 : error = strprintf("Fingerprint '%s' is not hex", fpr_hex);
1450 : 2 : return nullptr;
1451 : : }
1452 [ + - ]: 5059 : auto fpr_bytes = ParseHex(fpr_hex);
1453 [ - + ]: 5059 : KeyOriginInfo info;
1454 : 5059 : static_assert(sizeof(info.fingerprint) == 4, "Fingerprint must be 4 bytes");
1455 [ - + ]: 5059 : assert(fpr_bytes.size() == 4);
1456 : 5059 : std::copy(fpr_bytes.begin(), fpr_bytes.end(), info.fingerprint);
1457 [ + - - + ]: 5059 : if (!ParseKeyPath(slash_split, info.path, apostrophe, error)) return nullptr;
1458 [ + - ]: 5059 : auto provider = ParsePubkeyInner(key_exp_index, origin_split[1], ctx, out, apostrophe, error);
1459 [ + + ]: 5059 : if (!provider) return nullptr;
1460 [ + - - + ]: 5057 : return std::make_unique<OriginPubkeyProvider>(key_exp_index, std::move(info), std::move(provider), apostrophe);
1461 : 46830 : }
1462 : :
1463 : 610865 : std::unique_ptr<PubkeyProvider> InferPubkey(const CPubKey& pubkey, ParseScriptContext ctx, const SigningProvider& provider)
1464 : : {
1465 : : // Key cannot be hybrid
1466 [ + + ]: 610865 : if (!pubkey.IsValidNonHybrid()) {
1467 : 6 : return nullptr;
1468 : : }
1469 : : // Uncompressed is only allowed in TOP and P2SH contexts
1470 [ + + + + ]: 610859 : if (ctx != ParseScriptContext::TOP && ctx != ParseScriptContext::P2SH && !pubkey.IsCompressed()) {
1471 : 802 : return nullptr;
1472 : : }
1473 : 610057 : std::unique_ptr<PubkeyProvider> key_provider = std::make_unique<ConstPubkeyProvider>(0, pubkey, false);
1474 [ + - ]: 610057 : KeyOriginInfo info;
1475 [ + - + - : 610057 : if (provider.GetKeyOrigin(pubkey.GetID(), info)) {
+ + ]
1476 [ + - - + ]: 608492 : return std::make_unique<OriginPubkeyProvider>(0, std::move(info), std::move(key_provider), /*apostrophe=*/false);
1477 : : }
1478 : 1565 : return key_provider;
1479 : 610057 : }
1480 : :
1481 : 132146 : std::unique_ptr<PubkeyProvider> InferXOnlyPubkey(const XOnlyPubKey& xkey, ParseScriptContext ctx, const SigningProvider& provider)
1482 : : {
1483 : 132146 : CPubKey pubkey{xkey.GetEvenCorrespondingCPubKey()};
1484 : 132146 : std::unique_ptr<PubkeyProvider> key_provider = std::make_unique<ConstPubkeyProvider>(0, pubkey, true);
1485 [ + - ]: 132146 : KeyOriginInfo info;
1486 [ + - + + ]: 132146 : if (provider.GetKeyOriginByXOnly(xkey, info)) {
1487 [ + - - + ]: 117022 : return std::make_unique<OriginPubkeyProvider>(0, std::move(info), std::move(key_provider), /*apostrophe=*/false);
1488 : : }
1489 : 15124 : return key_provider;
1490 : 132146 : }
1491 : :
1492 : : /**
1493 : : * The context for parsing a Miniscript descriptor (either from Script or from its textual representation).
1494 : : */
1495 : 1231 : struct KeyParser {
1496 : : //! The Key type is an index in DescriptorImpl::m_pubkey_args
1497 : : using Key = uint32_t;
1498 : : //! Must not be nullptr if parsing from string.
1499 : : FlatSigningProvider* m_out;
1500 : : //! Must not be nullptr if parsing from Script.
1501 : : const SigningProvider* m_in;
1502 : : //! List of keys contained in the Miniscript.
1503 : : mutable std::vector<std::unique_ptr<PubkeyProvider>> m_keys;
1504 : : //! Used to detect key parsing errors within a Miniscript.
1505 : : mutable std::string m_key_parsing_error;
1506 : : //! The script context we're operating within (Tapscript or P2WSH).
1507 : : const miniscript::MiniscriptContext m_script_ctx;
1508 : : //! The number of keys that were parsed before starting to parse this Miniscript descriptor.
1509 : : uint32_t m_offset;
1510 : :
1511 : 1231 : KeyParser(FlatSigningProvider* out LIFETIMEBOUND, const SigningProvider* in LIFETIMEBOUND,
1512 : : miniscript::MiniscriptContext ctx, uint32_t offset = 0)
1513 : 1231 : : m_out(out), m_in(in), m_script_ctx(ctx), m_offset(offset) {}
1514 : :
1515 : 3784 : bool KeyCompare(const Key& a, const Key& b) const {
1516 : 3784 : return *m_keys.at(a) < *m_keys.at(b);
1517 : : }
1518 : :
1519 : 1729 : ParseScriptContext ParseContext() const {
1520 [ + - + ]: 1729 : switch (m_script_ctx) {
1521 : : case miniscript::MiniscriptContext::P2WSH: return ParseScriptContext::P2WSH;
1522 : 400 : case miniscript::MiniscriptContext::TAPSCRIPT: return ParseScriptContext::P2TR;
1523 : : }
1524 : 0 : assert(false);
1525 : : }
1526 : :
1527 : 367 : template<typename I> std::optional<Key> FromString(I begin, I end) const
1528 : : {
1529 [ - + ]: 367 : assert(m_out);
1530 : 367 : Key key = m_keys.size();
1531 [ + + ]: 367 : auto pk = ParsePubkey(m_offset + key, {&*begin, &*end}, ParseContext(), *m_out, m_key_parsing_error);
1532 [ + + ]: 367 : if (!pk) return {};
1533 [ + - ]: 365 : m_keys.push_back(std::move(pk));
1534 : 365 : return key;
1535 : 367 : }
1536 : :
1537 : 30 : std::optional<std::string> ToString(const Key& key) const
1538 : : {
1539 : 30 : return m_keys.at(key)->ToString();
1540 : : }
1541 : :
1542 : 974 : template<typename I> std::optional<Key> FromPKBytes(I begin, I end) const
1543 : : {
1544 [ - + ]: 974 : assert(m_in);
1545 : 974 : Key key = m_keys.size();
1546 [ + + + - ]: 974 : if (miniscript::IsTapscript(m_script_ctx) && end - begin == 32) {
1547 : 174 : XOnlyPubKey pubkey;
1548 : 174 : std::copy(begin, end, pubkey.begin());
1549 [ + - ]: 174 : if (auto pubkey_provider = InferPubkey(pubkey.GetEvenCorrespondingCPubKey(), ParseContext(), *m_in)) {
1550 [ + - ]: 174 : m_keys.push_back(std::move(pubkey_provider));
1551 : 174 : return key;
1552 : : }
1553 [ + - ]: 800 : } else if (!miniscript::IsTapscript(m_script_ctx)) {
1554 : 800 : CPubKey pubkey(begin, end);
1555 [ + - ]: 800 : if (auto pubkey_provider = InferPubkey(pubkey, ParseContext(), *m_in)) {
1556 [ + - ]: 800 : m_keys.push_back(std::move(pubkey_provider));
1557 : 800 : return key;
1558 : : }
1559 : : }
1560 : 0 : return {};
1561 : : }
1562 : :
1563 [ - + ]: 449 : template<typename I> std::optional<Key> FromPKHBytes(I begin, I end) const
1564 : : {
1565 [ - + ]: 449 : assert(end - begin == 20);
1566 [ - + ]: 449 : assert(m_in);
1567 : 449 : uint160 hash;
1568 : 449 : std::copy(begin, end, hash.begin());
1569 : 449 : CKeyID keyid(hash);
1570 : 449 : CPubKey pubkey;
1571 [ + + ]: 449 : if (m_in->GetPubKey(keyid, pubkey)) {
1572 [ + + ]: 388 : if (auto pubkey_provider = InferPubkey(pubkey, ParseContext(), *m_in)) {
1573 [ + - ]: 244 : Key key = m_keys.size();
1574 [ + - ]: 244 : m_keys.push_back(std::move(pubkey_provider));
1575 : 244 : return key;
1576 : : }
1577 : : }
1578 : 205 : return {};
1579 : : }
1580 : :
1581 : 995559 : miniscript::MiniscriptContext MsContext() const {
1582 [ + - + - : 995559 : return m_script_ctx;
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
- - + - +
- + - + -
+ - + - +
- + - + -
- - + - +
- + - + -
+ - + - +
- - - + -
+ - + - +
- + - + -
+ - + - +
- + - - -
+ - + - -
- - - - -
- - + - +
- + - + -
+ - + - +
- + - + -
+ - + + +
- + - ]
1583 : : }
1584 : : };
1585 : :
1586 : : /** Parse a script in a particular context. */
1587 : : // NOLINTNEXTLINE(misc-no-recursion)
1588 : 11360 : std::unique_ptr<DescriptorImpl> ParseScript(uint32_t& key_exp_index, Span<const char>& sp, ParseScriptContext ctx, FlatSigningProvider& out, std::string& error)
1589 : : {
1590 : 11360 : using namespace script;
1591 : :
1592 : 11360 : auto expr = Expr(sp);
1593 [ + - + + ]: 11360 : if (Func("pk", expr)) {
1594 : 535 : auto pubkey = ParsePubkey(key_exp_index, expr, ctx, out, error);
1595 [ + + ]: 535 : if (!pubkey) {
1596 [ + - ]: 3 : error = strprintf("pk(): %s", error);
1597 : 3 : return nullptr;
1598 : : }
1599 : 532 : ++key_exp_index;
1600 [ + - - + ]: 532 : return std::make_unique<PKDescriptor>(std::move(pubkey), ctx == ParseScriptContext::P2TR);
1601 : 535 : }
1602 [ + + + - : 21459 : if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH) && Func("pkh", expr)) {
+ + + + ]
1603 : 1386 : auto pubkey = ParsePubkey(key_exp_index, expr, ctx, out, error);
1604 [ + + ]: 1386 : if (!pubkey) {
1605 [ + - ]: 9 : error = strprintf("pkh(): %s", error);
1606 : 9 : return nullptr;
1607 : : }
1608 : 1377 : ++key_exp_index;
1609 [ + - - + ]: 1377 : return std::make_unique<PKHDescriptor>(std::move(pubkey));
1610 [ + + + - : 20073 : } else if (ctx != ParseScriptContext::P2TR && Func("pkh", expr)) {
- + - + ]
1611 : : // Under Taproot, always the Miniscript parser deal with it.
1612 : 0 : error = "Can only have pkh at top level, in sh(), wsh(), or in tr()";
1613 : 0 : return nullptr;
1614 : : }
1615 [ + + + - : 16713 : if (ctx == ParseScriptContext::TOP && Func("combo", expr)) {
+ + + + ]
1616 : 464 : auto pubkey = ParsePubkey(key_exp_index, expr, ctx, out, error);
1617 [ + + ]: 464 : if (!pubkey) {
1618 [ + - ]: 3 : error = strprintf("combo(): %s", error);
1619 : 3 : return nullptr;
1620 : : }
1621 : 461 : ++key_exp_index;
1622 [ + - - + ]: 461 : return std::make_unique<ComboDescriptor>(std::move(pubkey));
1623 [ + - + + ]: 9439 : } else if (Func("combo", expr)) {
1624 : 2 : error = "Can only have combo() at top level";
1625 : 2 : return nullptr;
1626 : : }
1627 [ + - ]: 8973 : const bool multi = Func("multi", expr);
1628 [ + + + - : 17605 : const bool sortedmulti = !multi && Func("sortedmulti", expr);
+ + ]
1629 [ + + + - : 17581 : const bool multi_a = !(multi || sortedmulti) && Func("multi_a", expr);
+ + ]
1630 [ + + + + : 17491 : const bool sortedmulti_a = !(multi || sortedmulti || multi_a) && Func("sortedmulti_a", expr);
+ - + + ]
1631 [ + + + + : 8973 : if (((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH) && (multi || sortedmulti)) ||
+ + + + ]
1632 [ + + + + ]: 191 : (ctx == ParseScriptContext::P2TR && (multi_a || sortedmulti_a))) {
1633 : 497 : auto threshold = Expr(expr);
1634 : 497 : uint32_t thres;
1635 : 497 : std::vector<std::unique_ptr<PubkeyProvider>> providers;
1636 [ + - + - : 994 : if (!ParseUInt32(std::string(threshold.begin(), threshold.end()), &thres)) {
+ + ]
1637 [ + - + - ]: 4 : error = strprintf("Multi threshold '%s' is not valid", std::string(threshold.begin(), threshold.end()));
1638 : 2 : return nullptr;
1639 : : }
1640 : : size_t script_size = 0;
1641 [ + + ]: 19816 : while (expr.size()) {
1642 [ + - + - : 19332 : if (!Const(",", expr)) {
- + ]
1643 [ # # ]: 0 : error = strprintf("Multi: expected ',', got '%c'", expr[0]);
1644 : 0 : return nullptr;
1645 : : }
1646 [ + - ]: 19332 : auto arg = Expr(expr);
1647 [ + - ]: 19332 : auto pk = ParsePubkey(key_exp_index, arg, ctx, out, error);
1648 [ + + ]: 19332 : if (!pk) {
1649 [ + - ]: 11 : error = strprintf("Multi: %s", error);
1650 : 11 : return nullptr;
1651 : : }
1652 [ + - ]: 19321 : script_size += pk->GetSize() + 1;
1653 [ + - ]: 19321 : providers.emplace_back(std::move(pk));
1654 : 19321 : key_exp_index++;
1655 : 19332 : }
1656 [ + + + + : 484 : if ((multi || sortedmulti) && (providers.empty() || providers.size() > MAX_PUBKEYS_PER_MULTISIG)) {
+ - - + ]
1657 [ # # ]: 0 : error = strprintf("Cannot have %u keys in multisig; must have between 1 and %d keys, inclusive", providers.size(), MAX_PUBKEYS_PER_MULTISIG);
1658 : 0 : return nullptr;
1659 [ + + + + : 484 : } else if ((multi_a || sortedmulti_a) && (providers.empty() || providers.size() > MAX_PUBKEYS_PER_MULTI_A)) {
+ - - + ]
1660 [ # # ]: 0 : error = strprintf("Cannot have %u keys in multi_a; must have between 1 and %d keys, inclusive", providers.size(), MAX_PUBKEYS_PER_MULTI_A);
1661 : 0 : return nullptr;
1662 [ + + ]: 484 : } else if (thres < 1) {
1663 [ + - ]: 2 : error = strprintf("Multisig threshold cannot be %d, must be at least 1", thres);
1664 : 2 : return nullptr;
1665 [ + + ]: 482 : } else if (thres > providers.size()) {
1666 [ + - ]: 2 : error = strprintf("Multisig threshold cannot be larger than the number of keys; threshold is %d but only %u keys specified", thres, providers.size());
1667 : 2 : return nullptr;
1668 : : }
1669 [ + + ]: 480 : if (ctx == ParseScriptContext::TOP) {
1670 [ + + ]: 20 : if (providers.size() > 3) {
1671 [ + - ]: 2 : error = strprintf("Cannot have %u pubkeys in bare multisig; only at most 3 pubkeys", providers.size());
1672 : 2 : return nullptr;
1673 : : }
1674 : : }
1675 [ + + ]: 478 : if (ctx == ParseScriptContext::P2SH) {
1676 : : // This limits the maximum number of compressed pubkeys to 15.
1677 [ + + ]: 94 : if (script_size + 3 > MAX_SCRIPT_ELEMENT_SIZE) {
1678 [ + - ]: 4 : error = strprintf("P2SH script is too large, %d bytes is larger than %d bytes", script_size + 3, MAX_SCRIPT_ELEMENT_SIZE);
1679 : 4 : return nullptr;
1680 : : }
1681 : : }
1682 [ + + + + ]: 474 : if (multi || sortedmulti) {
1683 [ + - - + ]: 342 : return std::make_unique<MultisigDescriptor>(thres, std::move(providers), sortedmulti);
1684 : : } else {
1685 [ + - - + ]: 132 : return std::make_unique<MultiADescriptor>(thres, std::move(providers), sortedmulti_a);
1686 : : }
1687 [ + - - + ]: 8973 : } else if (multi || sortedmulti) {
1688 : 0 : error = "Can only have multi/sortedmulti at top level, in sh(), or in wsh()";
1689 : 0 : return nullptr;
1690 [ + - - + ]: 8476 : } else if (multi_a || sortedmulti_a) {
1691 : 0 : error = "Can only have multi_a/sortedmulti_a inside tr()";
1692 : 0 : return nullptr;
1693 : : }
1694 [ + + + - : 16815 : if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH) && Func("wpkh", expr)) {
+ + + + ]
1695 : 2942 : auto pubkey = ParsePubkey(key_exp_index, expr, ParseScriptContext::P2WPKH, out, error);
1696 [ + + ]: 2942 : if (!pubkey) {
1697 [ + - ]: 7 : error = strprintf("wpkh(): %s", error);
1698 : 7 : return nullptr;
1699 : : }
1700 : 2935 : key_exp_index++;
1701 [ + - - + ]: 2935 : return std::make_unique<WPKHDescriptor>(std::move(pubkey));
1702 [ + - + + ]: 8476 : } else if (Func("wpkh", expr)) {
1703 : 3 : error = "Can only have wpkh() at top level or inside sh()";
1704 : 3 : return nullptr;
1705 : : }
1706 [ + + + - : 10786 : if (ctx == ParseScriptContext::TOP && Func("sh", expr)) {
+ + + + ]
1707 : 1666 : auto desc = ParseScript(key_exp_index, expr, ParseScriptContext::P2SH, out, error);
1708 [ + + + - ]: 1666 : if (!desc || expr.size()) return nullptr;
1709 [ + - - + ]: 1648 : return std::make_unique<SHDescriptor>(std::move(desc));
1710 [ + - + + ]: 5531 : } else if (Func("sh", expr)) {
1711 : 6 : error = "Can only have sh() at top level";
1712 : 6 : return nullptr;
1713 : : }
1714 [ + + + - : 7587 : if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH) && Func("wsh", expr)) {
+ + + + ]
1715 : 355 : auto desc = ParseScript(key_exp_index, expr, ParseScriptContext::P2WSH, out, error);
1716 [ + + + - ]: 355 : if (!desc || expr.size()) return nullptr;
1717 [ + - - + ]: 315 : return std::make_unique<WSHDescriptor>(std::move(desc));
1718 [ + - + + ]: 3859 : } else if (Func("wsh", expr)) {
1719 : 3 : error = "Can only have wsh() at top level or inside sh()";
1720 : 3 : return nullptr;
1721 : : }
1722 [ + + + - : 6869 : if (ctx == ParseScriptContext::TOP && Func("addr", expr)) {
+ + + + ]
1723 [ + - ]: 62 : CTxDestination dest = DecodeDestination(std::string(expr.begin(), expr.end()));
1724 [ + - + + ]: 62 : if (!IsValidDestination(dest)) {
1725 [ + - ]: 3 : error = "Address is not valid";
1726 : 3 : return nullptr;
1727 : : }
1728 [ + - - + ]: 59 : return std::make_unique<AddressDescriptor>(std::move(dest));
1729 [ + - - + ]: 3501 : } else if (Func("addr", expr)) {
1730 : 0 : error = "Can only have addr() at top level";
1731 : 0 : return nullptr;
1732 : : }
1733 [ + + + - : 6745 : if (ctx == ParseScriptContext::TOP && Func("tr", expr)) {
+ + + + ]
1734 : 1534 : auto arg = Expr(expr);
1735 : 1534 : auto internal_key = ParsePubkey(key_exp_index, arg, ParseScriptContext::P2TR, out, error);
1736 [ + + ]: 1534 : if (!internal_key) {
1737 [ + - ]: 2 : error = strprintf("tr(): %s", error);
1738 : 2 : return nullptr;
1739 : : }
1740 : 1532 : ++key_exp_index;
1741 : 1532 : std::vector<std::unique_ptr<DescriptorImpl>> subscripts; //!< list of script subexpressions
1742 : 1532 : std::vector<int> depths; //!< depth in the tree of each subexpression (same length subscripts)
1743 [ + + ]: 1532 : if (expr.size()) {
1744 [ + - + - : 277 : if (!Const(",", expr)) {
- + ]
1745 [ # # ]: 0 : error = strprintf("tr: expected ',', got '%c'", expr[0]);
1746 : 0 : return nullptr;
1747 : : }
1748 : : /** The path from the top of the tree to what we're currently processing.
1749 : : * branches[i] == false: left branch in the i'th step from the top; true: right branch.
1750 : : */
1751 : 277 : std::vector<bool> branches;
1752 : : // Loop over all provided scripts. In every iteration exactly one script will be processed.
1753 : : // Use a do-loop because inside this if-branch we expect at least one script.
1754 : : do {
1755 : : // First process all open braces.
1756 [ + - + - : 1131 : while (Const("{", expr)) {
+ + ]
1757 [ + - ]: 438 : branches.push_back(false); // new left branch
1758 [ - + ]: 438 : if (branches.size() > TAPROOT_CONTROL_MAX_NODE_COUNT) {
1759 [ # # ]: 0 : error = strprintf("tr() supports at most %i nesting levels", TAPROOT_CONTROL_MAX_NODE_COUNT);
1760 : 0 : return nullptr;
1761 : : }
1762 : : }
1763 : : // Process the actual script expression.
1764 [ + - ]: 693 : auto sarg = Expr(expr);
1765 [ + - + - ]: 693 : subscripts.emplace_back(ParseScript(key_exp_index, sarg, ParseScriptContext::P2TR, out, error));
1766 [ + + ]: 693 : if (!subscripts.back()) return nullptr;
1767 [ + - ]: 691 : depths.push_back(branches.size());
1768 : : // Process closing braces; one is expected for every right branch we were in.
1769 [ + + + + ]: 1107 : while (branches.size() && branches.back()) {
1770 [ + - - + : 416 : if (!Const("}", expr)) {
+ - ]
1771 [ # # ]: 0 : error = strprintf("tr(): expected '}' after script expression");
1772 : 0 : return nullptr;
1773 : : }
1774 : 416 : branches.pop_back(); // move up one level after encountering '}'
1775 : : }
1776 : : // If after that, we're at the end of a left branch, expect a comma.
1777 [ + + + - ]: 691 : if (branches.size() && !branches.back()) {
1778 [ + - + - : 416 : if (!Const(",", expr)) {
- + ]
1779 [ # # ]: 0 : error = strprintf("tr(): expected ',' after script expression");
1780 : 0 : return nullptr;
1781 : : }
1782 : 416 : branches.back() = true; // And now we're in a right branch.
1783 : : }
1784 [ + + ]: 691 : } while (branches.size());
1785 : : // After we've explored a whole tree, we must be at the end of the expression.
1786 [ - + ]: 275 : if (expr.size()) {
1787 [ # # ]: 0 : error = strprintf("tr(): expected ')' after script expression");
1788 : 0 : return nullptr;
1789 : : }
1790 : 277 : }
1791 [ + - - + ]: 1530 : assert(TaprootBuilder::ValidDepths(depths));
1792 [ + - - + ]: 1530 : return std::make_unique<TRDescriptor>(std::move(internal_key), std::move(subscripts), std::move(depths));
1793 [ + - - + ]: 3439 : } else if (Func("tr", expr)) {
1794 : 0 : error = "Can only have tr at top level";
1795 : 0 : return nullptr;
1796 : : }
1797 [ + + + - : 3677 : if (ctx == ParseScriptContext::TOP && Func("rawtr", expr)) {
+ + + + ]
1798 : 25 : auto arg = Expr(expr);
1799 [ + + ]: 25 : if (expr.size()) {
1800 : 1 : error = strprintf("rawtr(): only one key expected.");
1801 : 1 : return nullptr;
1802 : : }
1803 : 24 : auto output_key = ParsePubkey(key_exp_index, arg, ParseScriptContext::P2TR, out, error);
1804 [ - + ]: 24 : if (!output_key) return nullptr;
1805 : 24 : ++key_exp_index;
1806 [ + - - + ]: 24 : return std::make_unique<RawTRDescriptor>(std::move(output_key));
1807 [ + - - + ]: 1904 : } else if (Func("rawtr", expr)) {
1808 : 0 : error = "Can only have rawtr at top level";
1809 : 0 : return nullptr;
1810 : : }
1811 [ + + + - : 3627 : if (ctx == ParseScriptContext::TOP && Func("raw", expr)) {
+ + + + ]
1812 [ + - ]: 1722 : std::string str(expr.begin(), expr.end());
1813 [ + - + + ]: 1722 : if (!IsHex(str)) {
1814 [ + - ]: 2 : error = "Raw script is not hex";
1815 : 2 : return nullptr;
1816 : : }
1817 [ + - ]: 1720 : auto bytes = ParseHex(str);
1818 [ + - - + ]: 1720 : return std::make_unique<RawDescriptor>(CScript(bytes.begin(), bytes.end()));
1819 [ + - - + ]: 3600 : } else if (Func("raw", expr)) {
1820 : 0 : error = "Can only have raw() at top level";
1821 : 0 : return nullptr;
1822 : : }
1823 : : // Process miniscript expressions.
1824 : 158 : {
1825 : 158 : const auto script_ctx{ctx == ParseScriptContext::P2WSH ? miniscript::MiniscriptContext::P2WSH : miniscript::MiniscriptContext::TAPSCRIPT};
1826 [ + - ]: 158 : KeyParser parser(/*out = */&out, /* in = */nullptr, /* ctx = */script_ctx, key_exp_index);
1827 [ + - + - ]: 316 : auto node = miniscript::FromString(std::string(expr.begin(), expr.end()), parser);
1828 [ + + ]: 158 : if (parser.m_key_parsing_error != "") {
1829 : 2 : error = std::move(parser.m_key_parsing_error);
1830 : 2 : return nullptr;
1831 : : }
1832 [ + + ]: 156 : if (node) {
1833 [ + + ]: 125 : if (ctx != ParseScriptContext::P2WSH && ctx != ParseScriptContext::P2TR) {
1834 [ + - ]: 3 : error = "Miniscript expressions can only be used in wsh or tr.";
1835 : 3 : return nullptr;
1836 : : }
1837 [ + + + + ]: 122 : if (!node->IsSane() || node->IsNotSatisfiable()) {
1838 : : // Try to find the first insane sub for better error reporting.
1839 : 14 : auto insane_node = node.get();
1840 [ + - + + ]: 14 : if (const auto sub = node->FindInsaneSub()) insane_node = sub;
1841 [ + - + - : 28 : if (const auto str = insane_node->ToString(parser)) error = *str;
+ - ]
1842 [ + + ]: 14 : if (!insane_node->IsValid()) {
1843 [ + - ]: 4 : error += " is invalid";
1844 [ + + ]: 10 : } else if (!node->IsSane()) {
1845 [ + - ]: 9 : error += " is not sane";
1846 [ + + ]: 9 : if (!insane_node->IsNonMalleable()) {
1847 [ + - ]: 2 : error += ": malleable witnesses exist";
1848 [ + + + + ]: 7 : } else if (insane_node == node.get() && !insane_node->NeedsSignature()) {
1849 [ + - ]: 3 : error += ": witnesses without signature exist";
1850 [ + + ]: 4 : } else if (!insane_node->CheckTimeLocksMix()) {
1851 [ + - ]: 2 : error += ": contains mixes of timelocks expressed in blocks and seconds";
1852 [ + - ]: 2 : } else if (!insane_node->CheckDuplicateKey()) {
1853 [ + - ]: 2 : error += ": contains duplicate public keys";
1854 [ # # ]: 0 : } else if (!insane_node->ValidSatisfactions()) {
1855 [ # # ]: 0 : error += ": needs witnesses that may exceed resource limits";
1856 : : }
1857 : : } else {
1858 [ + - ]: 1 : error += " is not satisfiable";
1859 : : }
1860 : 14 : return nullptr;
1861 : : }
1862 : : // A signature check is required for a miniscript to be sane. Therefore no sane miniscript
1863 : : // may have an empty list of public keys.
1864 [ + - ]: 108 : CHECK_NONFATAL(!parser.m_keys.empty());
1865 [ + - ]: 108 : key_exp_index += parser.m_keys.size();
1866 [ + - - + ]: 108 : return std::make_unique<MiniscriptDescriptor>(std::move(parser.m_keys), std::move(node));
1867 : : }
1868 : 285 : }
1869 [ + + ]: 31 : if (ctx == ParseScriptContext::P2SH) {
1870 : 2 : error = "A function is needed within P2SH";
1871 : 2 : return nullptr;
1872 [ + + ]: 29 : } else if (ctx == ParseScriptContext::P2WSH) {
1873 : 2 : error = "A function is needed within P2WSH";
1874 : 2 : return nullptr;
1875 : : }
1876 [ + - ]: 27 : error = strprintf("'%s' is not a valid descriptor function", std::string(expr.begin(), expr.end()));
1877 : 27 : return nullptr;
1878 : : }
1879 : :
1880 : 908 : std::unique_ptr<DescriptorImpl> InferMultiA(const CScript& script, ParseScriptContext ctx, const SigningProvider& provider)
1881 : : {
1882 : 908 : auto match = MatchMultiA(script);
1883 [ + + ]: 908 : if (!match) return {};
1884 : 784 : std::vector<std::unique_ptr<PubkeyProvider>> keys;
1885 [ + - ]: 784 : keys.reserve(match->second.size());
1886 [ + + ]: 110226 : for (const auto keyspan : match->second) {
1887 [ - + ]: 109442 : if (keyspan.size() != 32) return {};
1888 [ + - + - ]: 109442 : auto key = InferXOnlyPubkey(XOnlyPubKey{keyspan}, ctx, provider);
1889 [ - + ]: 109442 : if (!key) return {};
1890 [ + - ]: 109442 : keys.push_back(std::move(key));
1891 : 109442 : }
1892 [ + - - + ]: 784 : return std::make_unique<MultiADescriptor>(match->first, std::move(keys));
1893 : 1692 : }
1894 : :
1895 : : // NOLINTNEXTLINE(misc-no-recursion)
1896 : 693311 : std::unique_ptr<DescriptorImpl> InferScript(const CScript& script, ParseScriptContext ctx, const SigningProvider& provider)
1897 : : {
1898 [ + + + + : 693311 : if (ctx == ParseScriptContext::P2TR && script.size() == 34 && script[0] == 32 && script[33] == OP_CHECKSIG) {
+ + + - -
+ ]
1899 : 2957 : XOnlyPubKey key{Span{script}.subspan(1, 32)};
1900 [ + - - + ]: 2957 : return std::make_unique<PKDescriptor>(InferXOnlyPubkey(key, ctx, provider), true);
1901 : : }
1902 : :
1903 [ + + ]: 690354 : if (ctx == ParseScriptContext::P2TR) {
1904 : 908 : auto ret = InferMultiA(script, ctx, provider);
1905 [ + + ]: 908 : if (ret) return ret;
1906 : 908 : }
1907 : :
1908 : 689570 : std::vector<std::vector<unsigned char>> data;
1909 [ + - ]: 689570 : TxoutType txntype = Solver(script, data);
1910 : :
1911 [ + + + - ]: 689570 : if (txntype == TxoutType::PUBKEY && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
1912 : 20120 : CPubKey pubkey(data[0]);
1913 [ + - + + ]: 20120 : if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
1914 [ + - - + ]: 19974 : return std::make_unique<PKDescriptor>(std::move(pubkey_provider));
1915 : 20120 : }
1916 : : }
1917 [ + + + + ]: 669596 : if (txntype == TxoutType::PUBKEYHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
1918 : 211051 : uint160 hash(data[0]);
1919 [ + - ]: 211051 : CKeyID keyid(hash);
1920 [ + - ]: 211051 : CPubKey pubkey;
1921 [ + - + + ]: 211051 : if (provider.GetPubKey(keyid, pubkey)) {
1922 [ + - + + ]: 210289 : if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
1923 [ + - - + ]: 210142 : return std::make_unique<PKHDescriptor>(std::move(pubkey_provider));
1924 : 210289 : }
1925 : : }
1926 : : }
1927 [ + + ]: 459454 : if (txntype == TxoutType::WITNESS_V0_KEYHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH)) {
1928 : 372665 : uint160 hash(data[0]);
1929 [ + - ]: 372665 : CKeyID keyid(hash);
1930 [ + - ]: 372665 : CPubKey pubkey;
1931 [ + - + + ]: 372665 : if (provider.GetPubKey(keyid, pubkey)) {
1932 [ + - + + ]: 370153 : if (auto pubkey_provider = InferPubkey(pubkey, ParseScriptContext::P2WPKH, provider)) {
1933 [ + - - + ]: 370021 : return std::make_unique<WPKHDescriptor>(std::move(pubkey_provider));
1934 : 370153 : }
1935 : : }
1936 : : }
1937 [ + + + - ]: 89433 : if (txntype == TxoutType::MULTISIG && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
1938 : 4241 : bool ok = true;
1939 : 4241 : std::vector<std::unique_ptr<PubkeyProvider>> providers;
1940 [ + + ]: 12943 : for (size_t i = 1; i + 1 < data.size(); ++i) {
1941 : 8941 : CPubKey pubkey(data[i]);
1942 [ + - + + ]: 8941 : if (auto pubkey_provider = InferPubkey(pubkey, ctx, provider)) {
1943 [ + - ]: 8702 : providers.push_back(std::move(pubkey_provider));
1944 : : } else {
1945 : 239 : ok = false;
1946 : 239 : break;
1947 : 8941 : }
1948 : : }
1949 [ + - - + ]: 4002 : if (ok) return std::make_unique<MultisigDescriptor>((int)data[0][0], std::move(providers));
1950 : 4241 : }
1951 [ + + ]: 85431 : if (txntype == TxoutType::SCRIPTHASH && ctx == ParseScriptContext::TOP) {
1952 : 53492 : uint160 hash(data[0]);
1953 [ + - ]: 53492 : CScriptID scriptid(hash);
1954 : 53492 : CScript subscript;
1955 [ + - + + ]: 53492 : if (provider.GetCScript(scriptid, subscript)) {
1956 [ + - ]: 52582 : auto sub = InferScript(subscript, ParseScriptContext::P2SH, provider);
1957 [ + + + - : 52582 : if (sub) return std::make_unique<SHDescriptor>(std::move(sub));
- + ]
1958 : 52582 : }
1959 : 53492 : }
1960 [ + + ]: 33177 : if (txntype == TxoutType::WITNESS_V0_SCRIPTHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH)) {
1961 [ + - ]: 6232 : CScriptID scriptid{RIPEMD160(data[0])};
1962 : 6232 : CScript subscript;
1963 [ + - + + ]: 6232 : if (provider.GetCScript(scriptid, subscript)) {
1964 [ + - ]: 4439 : auto sub = InferScript(subscript, ParseScriptContext::P2WSH, provider);
1965 [ + + + - : 4439 : if (sub) return std::make_unique<WSHDescriptor>(std::move(sub));
- + ]
1966 : 4439 : }
1967 : 6232 : }
1968 [ + + ]: 29394 : if (txntype == TxoutType::WITNESS_V1_TAPROOT && ctx == ParseScriptContext::TOP) {
1969 : : // Extract x-only pubkey from output.
1970 : 19747 : XOnlyPubKey pubkey;
1971 : 19747 : std::copy(data[0].begin(), data[0].end(), pubkey.begin());
1972 : : // Request spending data.
1973 [ + - ]: 19747 : TaprootSpendData tap;
1974 [ + - + + ]: 19747 : if (provider.GetTaprootSpendData(pubkey, tap)) {
1975 : : // If found, convert it back to tree form.
1976 [ + - ]: 4479 : auto tree = InferTaprootTree(tap, pubkey);
1977 [ + - ]: 4479 : if (tree) {
1978 : : // If that works, try to infer subdescriptors for all leaves.
1979 : 4479 : bool ok = true;
1980 : 4479 : std::vector<std::unique_ptr<DescriptorImpl>> subscripts; //!< list of script subexpressions
1981 : 4479 : std::vector<int> depths; //!< depth in the tree of each subexpression (same length subscripts)
1982 [ + - + + ]: 8344 : for (const auto& [depth, script, leaf_ver] : *tree) {
1983 : 3865 : std::unique_ptr<DescriptorImpl> subdesc;
1984 [ + - ]: 3865 : if (leaf_ver == TAPROOT_LEAF_TAPSCRIPT) {
1985 [ + - ]: 7730 : subdesc = InferScript(CScript(script.begin(), script.end()), ParseScriptContext::P2TR, provider);
1986 : : }
1987 [ - + ]: 3865 : if (!subdesc) {
1988 : 0 : ok = false;
1989 : 0 : break;
1990 : : } else {
1991 [ + - ]: 3865 : subscripts.push_back(std::move(subdesc));
1992 [ + - ]: 3865 : depths.push_back(depth);
1993 : : }
1994 : 3865 : }
1995 : 0 : if (ok) {
1996 [ + - ]: 4479 : auto key = InferXOnlyPubkey(tap.internal_key, ParseScriptContext::P2TR, provider);
1997 [ + - - + ]: 4479 : return std::make_unique<TRDescriptor>(std::move(key), std::move(subscripts), std::move(depths));
1998 : 4479 : }
1999 : 4479 : }
2000 : 4479 : }
2001 : : // If the above doesn't work, construct a rawtr() descriptor with just the encoded x-only pubkey.
2002 [ + - + - ]: 15268 : if (pubkey.IsFullyValid()) {
2003 [ + - ]: 15268 : auto key = InferXOnlyPubkey(pubkey, ParseScriptContext::P2TR, provider);
2004 [ + - ]: 15268 : if (key) {
2005 [ + - - + ]: 15268 : return std::make_unique<RawTRDescriptor>(std::move(key));
2006 : : }
2007 : 15268 : }
2008 : 19747 : }
2009 : :
2010 [ + + ]: 9647 : if (ctx == ParseScriptContext::P2WSH || ctx == ParseScriptContext::P2TR) {
2011 : 1073 : const auto script_ctx{ctx == ParseScriptContext::P2WSH ? miniscript::MiniscriptContext::P2WSH : miniscript::MiniscriptContext::TAPSCRIPT};
2012 [ + - ]: 1073 : KeyParser parser(/* out = */nullptr, /* in = */&provider, /* ctx = */script_ctx);
2013 [ + - ]: 1073 : auto node = miniscript::FromScript(script, parser);
2014 [ + + + + ]: 1073 : if (node && node->IsSane()) {
2015 [ + - - + : 417 : return std::make_unique<MiniscriptDescriptor>(std::move(parser.m_keys), std::move(node));
- + ]
2016 : : }
2017 : 2146 : }
2018 : :
2019 : : // The following descriptors are all top-level only descriptors.
2020 : : // So if we are not at the top level, return early.
2021 [ + + ]: 9230 : if (ctx != ParseScriptContext::TOP) return nullptr;
2022 : :
2023 : 8246 : CTxDestination dest;
2024 [ + - + + ]: 8246 : if (ExtractDestination(script, dest)) {
2025 [ + - + - ]: 6730 : if (GetScriptForDestination(dest) == script) {
2026 [ + - - + ]: 6730 : return std::make_unique<AddressDescriptor>(std::move(dest));
2027 : : }
2028 : : }
2029 : :
2030 [ + - - + ]: 1516 : return std::make_unique<RawDescriptor>(script);
2031 : 689570 : }
2032 : :
2033 : :
2034 : : } // namespace
2035 : :
2036 : : /** Check a descriptor checksum, and update desc to be the checksum-less part. */
2037 : 9208 : bool CheckChecksum(Span<const char>& sp, bool require_checksum, std::string& error, std::string* out_checksum = nullptr)
2038 : : {
2039 : 9208 : auto check_split = Split(sp, '#');
2040 [ + + ]: 9208 : if (check_split.size() > 2) {
2041 [ + - ]: 2 : error = "Multiple '#' symbols";
2042 : : return false;
2043 : : }
2044 [ + + + + ]: 9206 : if (check_split.size() == 1 && require_checksum){
2045 [ + - ]: 9208 : error = "Missing checksum";
2046 : : return false;
2047 : : }
2048 [ + + ]: 9197 : if (check_split.size() == 2) {
2049 [ + + ]: 5467 : if (check_split[1].size() != 8) {
2050 [ + - ]: 6 : error = strprintf("Expected 8 character checksum, not %u characters", check_split[1].size());
2051 : 6 : return false;
2052 : : }
2053 : : }
2054 [ + - ]: 9191 : auto checksum = DescriptorChecksum(check_split[0]);
2055 [ + + ]: 9191 : if (checksum.empty()) {
2056 [ + - ]: 9191 : error = "Invalid characters in payload";
2057 : : return false;
2058 : : }
2059 [ + + ]: 9190 : if (check_split.size() == 2) {
2060 [ + + ]: 5460 : if (!std::equal(checksum.begin(), checksum.end(), check_split[1].begin())) {
2061 [ + - + - ]: 22 : error = strprintf("Provided checksum '%s' does not match computed checksum '%s'", std::string(check_split[1].begin(), check_split[1].end()), checksum);
2062 : 11 : return false;
2063 : : }
2064 : : }
2065 [ + + ]: 9179 : if (out_checksum) *out_checksum = std::move(checksum);
2066 : 9179 : sp = check_split[0];
2067 : 9179 : return true;
2068 : 18399 : }
2069 : :
2070 : 8671 : std::unique_ptr<Descriptor> Parse(const std::string& descriptor, FlatSigningProvider& out, std::string& error, bool require_checksum)
2071 : : {
2072 : 8671 : Span<const char> sp{descriptor};
2073 [ + + ]: 8671 : if (!CheckChecksum(sp, require_checksum, error)) return nullptr;
2074 : 8646 : uint32_t key_exp_index = 0;
2075 : 8646 : auto ret = ParseScript(key_exp_index, sp, ParseScriptContext::TOP, out, error);
2076 [ + - + + ]: 8646 : if (sp.size() == 0 && ret) return std::unique_ptr<Descriptor>(std::move(ret));
2077 : 117 : return nullptr;
2078 : 8646 : }
2079 : :
2080 : 537 : std::string GetDescriptorChecksum(const std::string& descriptor)
2081 : : {
2082 [ + - ]: 537 : std::string ret;
2083 : 537 : std::string error;
2084 [ + - ]: 537 : Span<const char> sp{descriptor};
2085 [ + - + + : 537 : if (!CheckChecksum(sp, false, error, &ret)) return "";
+ - ]
2086 : 533 : return ret;
2087 : 537 : }
2088 : :
2089 : 632425 : std::unique_ptr<Descriptor> InferDescriptor(const CScript& script, const SigningProvider& provider)
2090 : : {
2091 : 632425 : return InferScript(script, ParseScriptContext::TOP, provider);
2092 : : }
2093 : :
2094 : 5894 : uint256 DescriptorID(const Descriptor& desc)
2095 : : {
2096 : 5894 : std::string desc_str = desc.ToString(/*compat_format=*/true);
2097 : 5894 : uint256 id;
2098 [ + - + - : 5894 : CSHA256().Write((unsigned char*)desc_str.data(), desc_str.size()).Finalize(id.begin());
+ - ]
2099 : 5894 : return id;
2100 : 5894 : }
2101 : :
2102 : 13052 : void DescriptorCache::CacheParentExtPubKey(uint32_t key_exp_pos, const CExtPubKey& xpub)
2103 : : {
2104 : 13052 : m_parent_xpubs[key_exp_pos] = xpub;
2105 : 13052 : }
2106 : :
2107 : 32966 : void DescriptorCache::CacheDerivedExtPubKey(uint32_t key_exp_pos, uint32_t der_index, const CExtPubKey& xpub)
2108 : : {
2109 : 32966 : auto& xpubs = m_derived_xpubs[key_exp_pos];
2110 : 32966 : xpubs[der_index] = xpub;
2111 : 32966 : }
2112 : :
2113 : 10628 : void DescriptorCache::CacheLastHardenedExtPubKey(uint32_t key_exp_pos, const CExtPubKey& xpub)
2114 : : {
2115 : 10628 : m_last_hardened_xpubs[key_exp_pos] = xpub;
2116 : 10628 : }
2117 : :
2118 : 654730 : bool DescriptorCache::GetCachedParentExtPubKey(uint32_t key_exp_pos, CExtPubKey& xpub) const
2119 : : {
2120 : 654730 : const auto& it = m_parent_xpubs.find(key_exp_pos);
2121 [ + + ]: 654730 : if (it == m_parent_xpubs.end()) return false;
2122 : 647943 : xpub = it->second;
2123 : 647943 : return true;
2124 : : }
2125 : :
2126 : 677430 : bool DescriptorCache::GetCachedDerivedExtPubKey(uint32_t key_exp_pos, uint32_t der_index, CExtPubKey& xpub) const
2127 : : {
2128 : 677430 : const auto& key_exp_it = m_derived_xpubs.find(key_exp_pos);
2129 [ + + ]: 677430 : if (key_exp_it == m_derived_xpubs.end()) return false;
2130 : 26179 : const auto& der_it = key_exp_it->second.find(der_index);
2131 [ + + ]: 26179 : if (der_it == key_exp_it->second.end()) return false;
2132 : 4320 : xpub = der_it->second;
2133 : 4320 : return true;
2134 : : }
2135 : :
2136 : 3752 : bool DescriptorCache::GetCachedLastHardenedExtPubKey(uint32_t key_exp_pos, CExtPubKey& xpub) const
2137 : : {
2138 : 3752 : const auto& it = m_last_hardened_xpubs.find(key_exp_pos);
2139 [ + + ]: 3752 : if (it == m_last_hardened_xpubs.end()) return false;
2140 : 870 : xpub = it->second;
2141 : 870 : return true;
2142 : : }
2143 : :
2144 : 433545 : DescriptorCache DescriptorCache::MergeAndDiff(const DescriptorCache& other)
2145 : : {
2146 : 433545 : DescriptorCache diff;
2147 [ + - + + ]: 437146 : for (const auto& parent_xpub_pair : other.GetCachedParentExtPubKeys()) {
2148 : 3601 : CExtPubKey xpub;
2149 [ + + ]: 3601 : if (GetCachedParentExtPubKey(parent_xpub_pair.first, xpub)) {
2150 [ - + ]: 12 : if (xpub != parent_xpub_pair.second) {
2151 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": New cached parent xpub does not match already cached parent xpub");
2152 : : }
2153 : 12 : continue;
2154 : : }
2155 [ + - ]: 3589 : CacheParentExtPubKey(parent_xpub_pair.first, parent_xpub_pair.second);
2156 [ + - ]: 3589 : diff.CacheParentExtPubKey(parent_xpub_pair.first, parent_xpub_pair.second);
2157 : 0 : }
2158 [ + - + + ]: 444514 : for (const auto& derived_xpub_map_pair : other.GetCachedDerivedExtPubKeys()) {
2159 [ + + ]: 21938 : for (const auto& derived_xpub_pair : derived_xpub_map_pair.second) {
2160 : 10969 : CExtPubKey xpub;
2161 [ + + ]: 10969 : if (GetCachedDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, xpub)) {
2162 [ - + ]: 36 : if (xpub != derived_xpub_pair.second) {
2163 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": New cached derived xpub does not match already cached derived xpub");
2164 : : }
2165 : 36 : continue;
2166 : : }
2167 [ + - ]: 10933 : CacheDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, derived_xpub_pair.second);
2168 [ + - ]: 10933 : diff.CacheDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, derived_xpub_pair.second);
2169 : : }
2170 : 0 : }
2171 [ + - + + ]: 436427 : for (const auto& lh_xpub_pair : other.GetCachedLastHardenedExtPubKeys()) {
2172 : 2882 : CExtPubKey xpub;
2173 [ - + ]: 2882 : if (GetCachedLastHardenedExtPubKey(lh_xpub_pair.first, xpub)) {
2174 [ # # ]: 0 : if (xpub != lh_xpub_pair.second) {
2175 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": New cached last hardened xpub does not match already cached last hardened xpub");
2176 : : }
2177 : 0 : continue;
2178 : : }
2179 [ + - ]: 2882 : CacheLastHardenedExtPubKey(lh_xpub_pair.first, lh_xpub_pair.second);
2180 [ + - ]: 2882 : diff.CacheLastHardenedExtPubKey(lh_xpub_pair.first, lh_xpub_pair.second);
2181 : 0 : }
2182 : 433545 : return diff;
2183 : 0 : }
2184 : :
2185 : 867510 : ExtPubKeyMap DescriptorCache::GetCachedParentExtPubKeys() const
2186 : : {
2187 : 867510 : return m_parent_xpubs;
2188 : : }
2189 : :
2190 : 867510 : std::unordered_map<uint32_t, ExtPubKeyMap> DescriptorCache::GetCachedDerivedExtPubKeys() const
2191 : : {
2192 : 867510 : return m_derived_xpubs;
2193 : : }
2194 : :
2195 : 868236 : ExtPubKeyMap DescriptorCache::GetCachedLastHardenedExtPubKeys() const
2196 : : {
2197 : 868236 : return m_last_hardened_xpubs;
2198 : : }
|