Branch data Line data Source code
1 : : // Copyright (c) 2018-present The Bitcoin Core developers
2 : : // Distributed under the MIT software license, see the accompanying
3 : : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 : :
5 : : #ifndef BITCOIN_SCRIPT_DESCRIPTOR_H
6 : : #define BITCOIN_SCRIPT_DESCRIPTOR_H
7 : :
8 : : #include <outputtype.h>
9 : : #include <pubkey.h>
10 : : #include <uint256.h>
11 : : #include <util/expected.h>
12 : :
13 : : #include <cstddef>
14 : : #include <cstdint>
15 : : #include <memory>
16 : : #include <optional>
17 : : #include <set>
18 : : #include <string>
19 : : #include <string_view>
20 : : #include <unordered_map>
21 : : #include <vector>
22 : :
23 : : class CScript;
24 : : class SigningProvider;
25 : : struct FlatSigningProvider;
26 : :
27 : : using ExtPubKeyMap = std::unordered_map<uint32_t, CExtPubKey>;
28 : :
29 : : /** Cache for single descriptor's derived extended pubkeys */
30 : : class DescriptorCache {
31 : : private:
32 : : /** Map key expression index -> map of (key derivation index -> xpub) */
33 : : std::unordered_map<uint32_t, ExtPubKeyMap> m_derived_xpubs;
34 : : /** Map key expression index -> parent xpub */
35 : : ExtPubKeyMap m_parent_xpubs;
36 : : /** Map key expression index -> last hardened xpub */
37 : : ExtPubKeyMap m_last_hardened_xpubs;
38 : :
39 : : public:
40 : : /** Cache a parent xpub
41 : : *
42 : : * @param[in] key_exp_pos Position of the key expression within the descriptor
43 : : * @param[in] xpub The CExtPubKey to cache
44 : : */
45 : : void CacheParentExtPubKey(uint32_t key_exp_pos, const CExtPubKey& xpub);
46 : : /** Retrieve a cached parent xpub
47 : : *
48 : : * @param[in] key_exp_pos Position of the key expression within the descriptor
49 : : * @param[out] xpub The CExtPubKey to get from cache
50 : : */
51 : : bool GetCachedParentExtPubKey(uint32_t key_exp_pos, CExtPubKey& xpub) const;
52 : : /** Cache an xpub derived at an index
53 : : *
54 : : * @param[in] key_exp_pos Position of the key expression within the descriptor
55 : : * @param[in] der_index Derivation index of the xpub
56 : : * @param[in] xpub The CExtPubKey to cache
57 : : */
58 : : void CacheDerivedExtPubKey(uint32_t key_exp_pos, uint32_t der_index, const CExtPubKey& xpub);
59 : : /** Retrieve a cached xpub derived at an index
60 : : *
61 : : * @param[in] key_exp_pos Position of the key expression within the descriptor
62 : : * @param[in] der_index Derivation index of the xpub
63 : : * @param[out] xpub The CExtPubKey to get from cache
64 : : */
65 : : bool GetCachedDerivedExtPubKey(uint32_t key_exp_pos, uint32_t der_index, CExtPubKey& xpub) const;
66 : : /** Cache a last hardened xpub
67 : : *
68 : : * @param[in] key_exp_pos Position of the key expression within the descriptor
69 : : * @param[in] xpub The CExtPubKey to cache
70 : : */
71 : : void CacheLastHardenedExtPubKey(uint32_t key_exp_pos, const CExtPubKey& xpub);
72 : : /** Retrieve a cached last hardened xpub
73 : : *
74 : : * @param[in] key_exp_pos Position of the key expression within the descriptor
75 : : * @param[out] xpub The CExtPubKey to get from cache
76 : : */
77 : : bool GetCachedLastHardenedExtPubKey(uint32_t key_exp_pos, CExtPubKey& xpub) const;
78 : :
79 : : /** Retrieve all cached parent xpubs */
80 : : ExtPubKeyMap GetCachedParentExtPubKeys() const;
81 : : /** Retrieve all cached derived xpubs */
82 : : std::unordered_map<uint32_t, ExtPubKeyMap> GetCachedDerivedExtPubKeys() const;
83 : : /** Retrieve all cached last hardened xpubs */
84 : : ExtPubKeyMap GetCachedLastHardenedExtPubKeys() const;
85 : :
86 : : /** Combine another DescriptorCache into this one.
87 : : * Returns a cache containing the items from the other cache unknown to current cache
88 : : */
89 : : DescriptorCache MergeAndDiff(const DescriptorCache& other);
90 : : };
91 : :
92 : : /** \brief Interface for parsed descriptor objects.
93 : : *
94 : : * Descriptors are strings that describe a set of scriptPubKeys, together with
95 : : * all information necessary to solve them. By combining all information into
96 : : * one, they avoid the need to separately import keys and scripts.
97 : : *
98 : : * Descriptors may be ranged, which occurs when the public keys inside are
99 : : * specified in the form of HD chains (xpubs).
100 : : *
101 : : * Descriptors always represent public information - public keys and scripts -
102 : : * but in cases where private keys need to be conveyed along with a descriptor,
103 : : * they can be included inside by changing public keys to private keys (WIF
104 : : * format), and changing xpubs by xprvs.
105 : : *
106 : : * Reference documentation about the descriptor language can be found in
107 : : * doc/descriptors.md.
108 : : */
109 [ - + - + : 340057 : struct Descriptor {
- + ][ - +
- + - + ]
110 : 0 : virtual ~Descriptor() = default;
111 : :
112 : : /** Whether the expansion of this descriptor depends on the position. */
113 : : virtual bool IsRange() const = 0;
114 : :
115 : : /** Whether this descriptor has all information about signing ignoring lack of private keys.
116 : : * This is true for all descriptors except ones that use `raw` or `addr` constructions. */
117 : : virtual bool IsSolvable() const = 0;
118 : :
119 : : /** Convert the descriptor back to a string, undoing parsing. */
120 : : virtual std::string ToString(bool compat_format=false) const = 0;
121 : :
122 : : /** Convert the descriptor to the canonical string.
123 : : * The canonical string is the same as the public string but always uses h as the hardened indicator
124 : : */
125 : : virtual std::string ToCanonicalString() const = 0;
126 : :
127 : : /** Whether this descriptor will return at most one scriptPubKey or multiple (aka is or is not combo) */
128 : : virtual bool IsSingleType() const = 0;
129 : :
130 : : /** Whether the given provider has all private keys required by this descriptor.
131 : : * @return `false` if the descriptor doesn't have any keys or subdescriptors,
132 : : * or if the provider does not have all private keys required by
133 : : * the descriptor.
134 : : */
135 : : virtual bool HavePrivateKeys(const SigningProvider& provider) const = 0;
136 : :
137 : : /** Convert the descriptor to a private string. This uses public keys if the relevant private keys are not in the SigningProvider.
138 : : * If none of the relevant private keys are available, the output string in the "out" parameter will not contain any private key information,
139 : : * and this function will return "false".
140 : : * @param[in] provider The SigningProvider to query for private keys.
141 : : * @param[out] out The resulting descriptor string, containing private keys if available.
142 : : * @returns true if at least one private key available.
143 : : */
144 : : virtual bool ToPrivateString(const SigningProvider& provider, std::string& out) const = 0;
145 : :
146 : : /** Convert the descriptor to a normalized string. Normalized descriptors have the xpub at the last hardened step. This fails if the provided provider does not have the private keys to derive that xpub. */
147 : : virtual bool ToNormalizedString(const SigningProvider& provider, std::string& out, const DescriptorCache* cache = nullptr) const = 0;
148 : :
149 : : /** Whether the descriptor can be used to produce its address(es) without needing a cache or private keys. */
150 : : virtual bool CanSelfExpand() const = 0;
151 : :
152 : : /** Expand a descriptor at a specified position.
153 : : *
154 : : * @param[in] pos The position at which to expand the descriptor. If IsRange() is false, this is ignored.
155 : : * @param[in] provider The provider to query for private keys in case of hardened derivation.
156 : : * @param[out] output_scripts The expanded scriptPubKeys.
157 : : * @param[out] out Scripts and public keys necessary for solving the expanded scriptPubKeys (may be equal to `provider`).
158 : : * @param[out] write_cache Cache data necessary to evaluate the descriptor at this point without access to private keys.
159 : : */
160 : : virtual bool Expand(int pos, const SigningProvider& provider, std::vector<CScript>& output_scripts, FlatSigningProvider& out, DescriptorCache* write_cache = nullptr) const = 0;
161 : :
162 : : /** Expand a descriptor at a specified position using cached expansion data.
163 : : *
164 : : * @param[in] pos The position at which to expand the descriptor. If IsRange() is false, this is ignored.
165 : : * @param[in] read_cache Cached expansion data.
166 : : * @param[out] output_scripts The expanded scriptPubKeys.
167 : : * @param[out] out Scripts and public keys necessary for solving the expanded scriptPubKeys (may be equal to `provider`).
168 : : */
169 : : virtual bool ExpandFromCache(int pos, const DescriptorCache& read_cache, std::vector<CScript>& output_scripts, FlatSigningProvider& out) const = 0;
170 : :
171 : : /** Expand the private key for a descriptor at a specified position, if possible.
172 : : *
173 : : * @param[in] pos The position at which to expand the descriptor. If IsRange() is false, this is ignored.
174 : : * @param[in] provider The provider to query for the private keys.
175 : : * @param[out] out Any private keys available for the specified `pos`.
176 : : */
177 : : virtual void ExpandPrivate(int pos, const SigningProvider& provider, FlatSigningProvider& out) const = 0;
178 : :
179 : : /** @return The OutputType of the scriptPubKey(s) produced by this descriptor. Or nullopt if indeterminate (multiple or none) */
180 : : virtual std::optional<OutputType> GetOutputType() const = 0;
181 : :
182 : : /** Get the size of the scriptPubKey for this descriptor. */
183 : : virtual std::optional<int64_t> ScriptSize() const = 0;
184 : :
185 : : /** Get the maximum size of a satisfaction for this descriptor, in weight units.
186 : : *
187 : : * @param use_max_sig Whether to assume ECDSA signatures will have a high-r.
188 : : */
189 : : virtual std::optional<int64_t> MaxSatisfactionWeight(bool use_max_sig) const = 0;
190 : :
191 : : /** Get the maximum size number of stack elements for satisfying this descriptor. */
192 : : virtual std::optional<int64_t> MaxSatisfactionElems() const = 0;
193 : :
194 : : /** Return all (extended) public keys for this descriptor, including any from subdescriptors.
195 : : *
196 : : * @param[out] pubkeys Any public keys
197 : : * @param[out] ext_pubs Any extended public keys
198 : : */
199 : : virtual void GetPubKeys(std::set<CPubKey>& pubkeys, std::set<CExtPubKey>& ext_pubs) const = 0;
200 : :
201 : : /** Whether this descriptor produces any scripts with the Expand functions */
202 : : virtual bool HasScripts() const = 0;
203 : :
204 : : /** Semantic/safety warnings (includes subdescriptors). */
205 : : virtual std::vector<std::string> Warnings() const = 0;
206 : :
207 : : /** Get the maximum key expression index. Used only for tests */
208 : : virtual uint32_t GetMaxKeyExpr() const = 0;
209 : :
210 : : /** Get the number of key expressions in this descriptor. Used only for tests */
211 : : virtual size_t GetKeyCount() const = 0;
212 : : };
213 : :
214 : : /** Validate the numeric bounds of a descriptor key-expression range
215 : : * [low, high] (high inclusive). On success returns an Expected with no
216 : : * value; on failure returns the first violated invariant's user-facing
217 : : * message.
218 : : */
219 : : util::Expected<void, std::string> CheckDescriptorRangeBounds(int64_t low, int64_t high);
220 : :
221 : : /** Parse a `descriptor` string. Included private keys are put in `out`.
222 : : *
223 : : * If the descriptor has a checksum, it must be valid. If `require_checksum`
224 : : * is set, the checksum is mandatory - otherwise it is optional.
225 : : *
226 : : * If a parse error occurs, or the checksum is missing/invalid, or anything
227 : : * else is wrong, an empty vector is returned.
228 : : */
229 : : std::vector<std::unique_ptr<Descriptor>> Parse(std::string_view descriptor, FlatSigningProvider& out, std::string& error, bool require_checksum = false);
230 : :
231 : : /** Get the checksum for a `descriptor`.
232 : : *
233 : : * - If it already has one, and it is correct, return the checksum in the input.
234 : : * - If it already has one that is wrong, return "".
235 : : * - If it does not already have one, return the checksum that would need to be added.
236 : : */
237 : : std::string GetDescriptorChecksum(const std::string& descriptor);
238 : :
239 : : /** Find a descriptor for the specified `script`, using information from `provider` where possible.
240 : : *
241 : : * A non-ranged descriptor which only generates the specified script will be returned in all
242 : : * circumstances.
243 : : *
244 : : * For public keys with key origin information, this information will be preserved in the returned
245 : : * descriptor.
246 : : *
247 : : * - If all information for solving `script` is present in `provider`, a descriptor will be returned
248 : : * which is IsSolvable() and encapsulates said information.
249 : : * - Failing that, if `script` corresponds to a known address type, an "addr()" descriptor will be
250 : : * returned (which is not IsSolvable()).
251 : : * - Failing that, a "raw()" descriptor is returned.
252 : : */
253 : : std::unique_ptr<Descriptor> InferDescriptor(const CScript& script, const SigningProvider& provider);
254 : :
255 : : /** Hash of the COMPAT string representation of the descriptor that is not supposed to change over time.
256 : : * Due to the hash's usage in previous versions, the COMPAT string is computed with some quirks.
257 : : *
258 : : * The hash is the sha256 of the public descriptor using apostrophes as the hardened indicator, except inside of
259 : : * Miniscript expressions, where the public serialization is used as provided.
260 : : */
261 : : uint256 CompatDescriptorHash(const Descriptor& desc);
262 : :
263 : : #endif // BITCOIN_SCRIPT_DESCRIPTOR_H
|