Branch data Line data Source code
1 : : // Copyright (c) 2010 Satoshi Nakamoto
2 : : // Copyright (c) 2009-2022 The Bitcoin Core developers
3 : : // Distributed under the MIT software license, see the accompanying
4 : : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 : :
6 : : #include <key_io.h>
7 : : #include <outputtype.h>
8 : : #include <pubkey.h>
9 : : #include <rpc/protocol.h>
10 : : #include <rpc/request.h>
11 : : #include <rpc/server.h>
12 : : #include <rpc/util.h>
13 : : #include <script/descriptor.h>
14 : : #include <script/script.h>
15 : : #include <script/signingprovider.h>
16 : : #include <tinyformat.h>
17 : : #include <univalue.h>
18 : : #include <util/check.h>
19 : : #include <util/strencodings.h>
20 : :
21 : : #include <cstdint>
22 : : #include <memory>
23 : : #include <optional>
24 : : #include <string>
25 : : #include <tuple>
26 : : #include <vector>
27 : :
28 : 2263 : static RPCHelpMan validateaddress()
29 : : {
30 : 2263 : return RPCHelpMan{
31 : : "validateaddress",
32 : : "\nReturn information about the given bitcoin address.\n",
33 : : {
34 [ + - ]: 2263 : {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The bitcoin address to validate"},
35 : : },
36 : 0 : RPCResult{
37 : : RPCResult::Type::OBJ, "", "",
38 : : {
39 : : {RPCResult::Type::BOOL, "isvalid", "If the address is valid or not"},
40 : : {RPCResult::Type::STR, "address", /*optional=*/true, "The bitcoin address validated"},
41 : : {RPCResult::Type::STR_HEX, "scriptPubKey", /*optional=*/true, "The hex-encoded output script generated by the address"},
42 : : {RPCResult::Type::BOOL, "isscript", /*optional=*/true, "If the key is a script"},
43 : : {RPCResult::Type::BOOL, "iswitness", /*optional=*/true, "If the address is a witness address"},
44 : : {RPCResult::Type::NUM, "witness_version", /*optional=*/true, "The version number of the witness program"},
45 : : {RPCResult::Type::STR_HEX, "witness_program", /*optional=*/true, "The hex value of the witness program"},
46 : : {RPCResult::Type::STR, "error", /*optional=*/true, "Error message, if any"},
47 : : {RPCResult::Type::ARR, "error_locations", /*optional=*/true, "Indices of likely error locations in address, if known (e.g. Bech32 errors)",
48 : : {
49 : : {RPCResult::Type::NUM, "index", "index of a potential error"},
50 : : }},
51 : : }
52 [ + - + - : 29419 : },
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
+ + + - -
- - ]
53 : 2263 : RPCExamples{
54 [ + - + - : 6789 : HelpExampleCli("validateaddress", "\"" + EXAMPLE_ADDRESS[0] + "\"") +
+ - ]
55 [ + - + - : 9052 : HelpExampleRpc("validateaddress", "\"" + EXAMPLE_ADDRESS[0] + "\"")
+ - + - ]
56 [ + - ]: 2263 : },
57 : 145 : [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
58 : : {
59 [ + - ]: 145 : std::string error_msg;
60 : 145 : std::vector<int> error_locations;
61 [ + - + - : 145 : CTxDestination dest = DecodeDestination(request.params[0].get_str(), error_msg, &error_locations);
+ - ]
62 [ + - ]: 145 : const bool isValid = IsValidDestination(dest);
63 [ + - ]: 145 : CHECK_NONFATAL(isValid == error_msg.empty());
64 : :
65 : 145 : UniValue ret(UniValue::VOBJ);
66 [ + - + - : 290 : ret.pushKV("isvalid", isValid);
+ - ]
67 [ + + ]: 145 : if (isValid) {
68 [ + - ]: 99 : std::string currentAddress = EncodeDestination(dest);
69 [ + - + - : 198 : ret.pushKV("address", currentAddress);
+ - ]
70 : :
71 [ + - ]: 99 : CScript scriptPubKey = GetScriptForDestination(dest);
72 [ + + + - : 297 : ret.pushKV("scriptPubKey", HexStr(scriptPubKey));
+ - + - +
- ]
73 : :
74 [ + - ]: 99 : UniValue detail = DescribeAddress(dest);
75 [ + - ]: 99 : ret.pushKVs(std::move(detail));
76 : 99 : } else {
77 : 46 : UniValue error_indices(UniValue::VARR);
78 [ + - + - : 75 : for (int i : error_locations) error_indices.push_back(i);
+ + ]
79 [ + - + - ]: 92 : ret.pushKV("error_locations", std::move(error_indices));
80 [ + - + - : 92 : ret.pushKV("error", error_msg);
+ - ]
81 : 46 : }
82 : :
83 : 145 : return ret;
84 : 145 : },
85 [ + - + - : 20367 : };
+ - + - +
- + - + +
- - ]
86 [ + - + - : 31682 : }
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - - - ]
87 : :
88 : 2237 : static RPCHelpMan createmultisig()
89 : : {
90 : 2237 : return RPCHelpMan{"createmultisig",
91 : : "\nCreates a multi-signature address with n signature of m keys required.\n"
92 : : "It returns a json object with the address and redeemScript.\n",
93 : : {
94 [ + - ]: 2237 : {"nrequired", RPCArg::Type::NUM, RPCArg::Optional::NO, "The number of required signatures out of the n keys."},
95 [ + - ]: 2237 : {"keys", RPCArg::Type::ARR, RPCArg::Optional::NO, "The hex-encoded public keys.",
96 : : {
97 [ + - ]: 2237 : {"key", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "The hex-encoded public key"},
98 : : }},
99 [ + - ]: 4474 : {"address_type", RPCArg::Type::STR, RPCArg::Default{"legacy"}, "The address type to use. Options are \"legacy\", \"p2sh-segwit\", and \"bech32\"."},
100 : : },
101 : 0 : RPCResult{
102 : : RPCResult::Type::OBJ, "", "",
103 : : {
104 : : {RPCResult::Type::STR, "address", "The value of the new multisig address."},
105 : : {RPCResult::Type::STR_HEX, "redeemScript", "The string value of the hex-encoded redemption script."},
106 : : {RPCResult::Type::STR, "descriptor", "The descriptor for this multisig"},
107 : : {RPCResult::Type::ARR, "warnings", /*optional=*/true, "Any warnings resulting from the creation of this multisig",
108 : : {
109 : : {RPCResult::Type::STR, "", ""},
110 : : }},
111 : : }
112 [ + - + - : 17896 : },
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
+ + + - -
- - ]
113 : 2237 : RPCExamples{
114 : : "\nCreate a multisig address from 2 public keys\n"
115 [ + - + - : 4474 : + HelpExampleCli("createmultisig", "2 \"[\\\"03789ed0bb717d88f7d321a368d905e7430207ebbd82bd342cf11ae157a7ace5fd\\\",\\\"03dbc6764b8884a92e871274b87583e6d5c2a58819473e17e107ef3f6aa5a61626\\\"]\"") +
+ - + - ]
116 : 2237 : "\nAs a JSON-RPC call\n"
117 [ + - + - : 8948 : + HelpExampleRpc("createmultisig", "2, [\"03789ed0bb717d88f7d321a368d905e7430207ebbd82bd342cf11ae157a7ace5fd\",\"03dbc6764b8884a92e871274b87583e6d5c2a58819473e17e107ef3f6aa5a61626\"]")
+ - + - ]
118 [ + - ]: 2237 : },
119 : 121 : [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
120 : : {
121 : 121 : int required = request.params[0].getInt<int>();
122 : :
123 : : // Get the public keys
124 : 121 : const UniValue& keys = request.params[1].get_array();
125 : 121 : std::vector<CPubKey> pubkeys;
126 [ + - ]: 121 : pubkeys.reserve(keys.size());
127 [ + + ]: 874 : for (unsigned int i = 0; i < keys.size(); ++i) {
128 [ + - + - : 1506 : pubkeys.push_back(HexToPubKey(keys[i].get_str()));
+ - ]
129 : : }
130 : :
131 : : // Get the output type
132 : 121 : OutputType output_type = OutputType::LEGACY;
133 [ + - + + ]: 121 : if (!request.params[2].isNull()) {
134 [ + - + - : 116 : std::optional<OutputType> parsed = ParseOutputType(request.params[2].get_str());
+ - ]
135 [ + + ]: 116 : if (!parsed) {
136 [ + - + - : 2 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Unknown address type '%s'", request.params[2].get_str()));
+ - + - ]
137 [ + + ]: 115 : } else if (parsed.value() == OutputType::BECH32M) {
138 [ + - + - ]: 2 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "createmultisig cannot create bech32m multisig addresses");
139 : : }
140 : : output_type = parsed.value();
141 : : }
142 : :
143 : 119 : FlatSigningProvider keystore;
144 : 119 : CScript inner;
145 [ + + ]: 119 : const CTxDestination dest = AddAndGetMultisigDestination(required, pubkeys, output_type, keystore, inner);
146 : :
147 : : // Make the descriptor
148 [ + - + - ]: 116 : std::unique_ptr<Descriptor> descriptor = InferDescriptor(GetScriptForDestination(dest), keystore);
149 : :
150 : 116 : UniValue result(UniValue::VOBJ);
151 [ + - + - : 232 : result.pushKV("address", EncodeDestination(dest));
+ - + - ]
152 [ + - + - : 348 : result.pushKV("redeemScript", HexStr(inner));
+ - + - +
- ]
153 [ + - + - : 232 : result.pushKV("descriptor", descriptor->ToString());
+ - + - ]
154 : :
155 : 116 : UniValue warnings(UniValue::VARR);
156 [ + - ]: 116 : if (descriptor->GetOutputType() != output_type) {
157 : : // Only warns if the user has explicitly chosen an address type we cannot generate
158 [ + - + - ]: 24 : warnings.push_back("Unable to make chosen address type, please ensure no uncompressed public keys are present.");
159 : : }
160 [ + - ]: 116 : PushWarnings(warnings, result);
161 : :
162 : 232 : return result;
163 : 119 : },
164 [ + - + - : 44740 : };
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + + +
+ - - -
- ]
165 [ + - + - : 33555 : }
+ - + - +
- + - + -
+ - + - +
- + - - -
- - ]
166 : :
167 : 2372 : static RPCHelpMan getdescriptorinfo()
168 : : {
169 : 2372 : const std::string EXAMPLE_DESCRIPTOR = "wpkh([d34db33f/84h/0h/0h]0279be667ef9dcbbac55a06295Ce870b07029Bfcdb2dce28d959f2815b16f81798)";
170 : :
171 [ + - ]: 2372 : return RPCHelpMan{"getdescriptorinfo",
172 : : {"\nAnalyses a descriptor.\n"},
173 : : {
174 [ + - ]: 2372 : {"descriptor", RPCArg::Type::STR, RPCArg::Optional::NO, "The descriptor."},
175 : : },
176 : 0 : RPCResult{
177 : : RPCResult::Type::OBJ, "", "",
178 : : {
179 : : {RPCResult::Type::STR, "descriptor", "The descriptor in canonical form, without private keys. For a multipath descriptor, only the first will be returned."},
180 : : {RPCResult::Type::ARR, "multipath_expansion", /*optional=*/true, "All descriptors produced by expanding multipath derivation elements. Only if the provided descriptor specifies multipath derivation elements.",
181 : : {
182 : : {RPCResult::Type::STR, "", ""},
183 : : }},
184 : : {RPCResult::Type::STR, "checksum", "The checksum for the input descriptor"},
185 : : {RPCResult::Type::BOOL, "isrange", "Whether the descriptor is ranged"},
186 : : {RPCResult::Type::BOOL, "issolvable", "Whether the descriptor is solvable"},
187 : : {RPCResult::Type::BOOL, "hasprivatekeys", "Whether the input descriptor contained at least one private key"},
188 : : }
189 [ + - + - : 23720 : },
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + + + +
- - - - ]
190 : 2372 : RPCExamples{
191 : 2372 : "Analyse a descriptor\n" +
192 [ + - + - : 9488 : HelpExampleCli("getdescriptorinfo", "\"" + EXAMPLE_DESCRIPTOR + "\"") +
+ - + - ]
193 [ + - + - : 9488 : HelpExampleRpc("getdescriptorinfo", "\"" + EXAMPLE_DESCRIPTOR + "\"")
+ - + - ]
194 [ + - ]: 2372 : },
195 : 254 : [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
196 : : {
197 : 254 : FlatSigningProvider provider;
198 [ + - ]: 254 : std::string error;
199 [ + - + - : 254 : auto descs = Parse(request.params[0].get_str(), provider, error);
+ - ]
200 [ + + ]: 254 : if (descs.empty()) {
201 [ + - ]: 1 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error);
202 : : }
203 : :
204 : 253 : UniValue result(UniValue::VOBJ);
205 [ + - + - : 506 : result.pushKV("descriptor", descs.at(0)->ToString());
+ - + - +
- ]
206 : :
207 [ + + ]: 253 : if (descs.size() > 1) {
208 : 4 : UniValue multipath_descs(UniValue::VARR);
209 [ + + ]: 12 : for (const auto& d : descs) {
210 [ + - + - : 8 : multipath_descs.push_back(d->ToString());
+ - ]
211 : : }
212 [ + - + - : 8 : result.pushKV("multipath_expansion", multipath_descs);
+ - ]
213 : 4 : }
214 : :
215 [ + - + - : 506 : result.pushKV("checksum", GetDescriptorChecksum(request.params[0].get_str()));
+ - + - +
- + - ]
216 [ + - + - : 506 : result.pushKV("isrange", descs.at(0)->IsRange());
+ - + - +
- ]
217 [ + - + - : 506 : result.pushKV("issolvable", descs.at(0)->IsSolvable());
+ - + - +
- ]
218 [ + - + - : 506 : result.pushKV("hasprivatekeys", provider.keys.size() > 0);
+ - ]
219 : 253 : return result;
220 : 255 : },
221 [ + - + - : 21348 : };
+ - + - +
- + - + -
+ + - - ]
222 [ + - + - : 28464 : }
+ - + - +
- + - + -
+ - + - +
- - - ]
223 : :
224 : 198 : static UniValue DeriveAddresses(const Descriptor* desc, int64_t range_begin, int64_t range_end, FlatSigningProvider& key_provider)
225 : : {
226 : 198 : UniValue addresses(UniValue::VARR);
227 : :
228 [ + + ]: 408 : for (int64_t i = range_begin; i <= range_end; ++i) {
229 : 216 : FlatSigningProvider provider;
230 : 216 : std::vector<CScript> scripts;
231 [ + - + + ]: 216 : if (!desc->Expand(i, key_provider, scripts, provider)) {
232 [ + - + - ]: 4 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Cannot derive script without private keys");
233 : : }
234 : :
235 [ + + ]: 430 : for (const CScript& script : scripts) {
236 : 220 : CTxDestination dest;
237 [ + - + + ]: 220 : if (!ExtractDestination(script, dest)) {
238 : : // ExtractDestination no longer returns true for P2PK since it doesn't have a corresponding address
239 : : // However combo will output P2PK and should just ignore that script
240 [ + + ]: 6 : if (scripts.size() > 1 && std::get_if<PubKeyDestination>(&dest)) {
241 : 2 : continue;
242 : : }
243 [ + - + - ]: 8 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Descriptor does not have a corresponding address");
244 : : }
245 : :
246 [ + - + - : 214 : addresses.push_back(EncodeDestination(dest));
+ - ]
247 : 220 : }
248 : 222 : }
249 : :
250 : : // This should not be possible, but an assert seems overkill:
251 [ - + ]: 192 : if (addresses.empty()) {
252 [ # # # # ]: 0 : throw JSONRPCError(RPC_MISC_ERROR, "Unexpected empty result");
253 : : }
254 : :
255 : 192 : return addresses;
256 : 6 : }
257 : :
258 : 2328 : static RPCHelpMan deriveaddresses()
259 : : {
260 : 2328 : const std::string EXAMPLE_DESCRIPTOR = "wpkh([d34db33f/84h/0h/0h]xpub6DJ2dNUysrn5Vt36jH2KLBT2i1auw1tTSSomg8PhqNiUtx8QX2SvC9nrHu81fT41fvDUnhMjEzQgXnQjKEu3oaqMSzhSrHMxyyoEAmUHQbY/0/*)#cjjspncu";
261 : :
262 [ + - ]: 2328 : return RPCHelpMan{"deriveaddresses",
263 : : {"\nDerives one or more addresses corresponding to an output descriptor.\n"
264 : : "Examples of output descriptors are:\n"
265 : : " pkh(<pubkey>) P2PKH outputs for the given pubkey\n"
266 : : " wpkh(<pubkey>) Native segwit P2PKH outputs for the given pubkey\n"
267 : : " sh(multi(<n>,<pubkey>,<pubkey>,...)) P2SH-multisig outputs for the given threshold and pubkeys\n"
268 : : " raw(<hex script>) Outputs whose output script equals the specified hex-encoded bytes\n"
269 : : " tr(<pubkey>,multi_a(<n>,<pubkey>,<pubkey>,...)) P2TR-multisig outputs for the given threshold and pubkeys\n"
270 : : "\nIn the above, <pubkey> either refers to a fixed public key in hexadecimal notation, or to an xpub/xprv optionally followed by one\n"
271 : : "or more path elements separated by \"/\", where \"h\" represents a hardened child key.\n"
272 : : "For more information on output descriptors, see the documentation in the doc/descriptors.md file.\n"},
273 : : {
274 [ + - ]: 2328 : {"descriptor", RPCArg::Type::STR, RPCArg::Optional::NO, "The descriptor."},
275 [ + - ]: 2328 : {"range", RPCArg::Type::RANGE, RPCArg::Optional::OMITTED, "If a ranged descriptor is used, this specifies the end or the range (in [begin,end] notation) to derive."},
276 : : },
277 : : {
278 : : RPCResult{"for single derivation descriptors",
279 : : RPCResult::Type::ARR, "", "",
280 : : {
281 : : {RPCResult::Type::STR, "address", "the derived addresses"},
282 : : }
283 [ + - + - : 6984 : },
+ - + - +
- + - + -
+ + - - ]
284 : : RPCResult{"for multipath descriptors",
285 : : RPCResult::Type::ARR, "", "The derived addresses for each of the multipath expansions of the descriptor, in multipath specifier order",
286 : : {
287 : : {
288 : : RPCResult::Type::ARR, "", "The derived addresses for a multipath descriptor expansion",
289 : : {
290 : : {RPCResult::Type::STR, "address", "the derived address"},
291 : : },
292 : : },
293 : : },
294 [ + - + - : 11640 : },
+ - + - +
- + - + -
+ - + - +
- + + + +
- - - - ]
295 : : },
296 : 2328 : RPCExamples{
297 : 2328 : "First three native segwit receive addresses\n" +
298 [ + - + - : 9312 : HelpExampleCli("deriveaddresses", "\"" + EXAMPLE_DESCRIPTOR + "\" \"[0,2]\"") +
+ - + - ]
299 [ + - + - : 6984 : HelpExampleRpc("deriveaddresses", "\"" + EXAMPLE_DESCRIPTOR + "\", \"[0,2]\"")
+ - ]
300 [ + - ]: 2328 : },
301 : 212 : [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
302 : : {
303 : 212 : const std::string desc_str = request.params[0].get_str();
304 : :
305 : 212 : int64_t range_begin = 0;
306 : 212 : int64_t range_end = 0;
307 : :
308 [ + + + - : 212 : if (request.params.size() >= 2 && !request.params[1].isNull()) {
+ - ]
309 [ + - + + ]: 86 : std::tie(range_begin, range_end) = ParseDescriptorRange(request.params[1]);
310 : : }
311 : :
312 : 204 : FlatSigningProvider key_provider;
313 [ + - ]: 204 : std::string error;
314 [ + - ]: 204 : auto descs = Parse(desc_str, key_provider, error, /* require_checksum = */ true);
315 [ + + ]: 204 : if (descs.empty()) {
316 [ + - ]: 4 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error);
317 : : }
318 [ + - ]: 200 : auto& desc = descs.at(0);
319 [ + - + + : 200 : if (!desc->IsRange() && request.params.size() > 1) {
+ + ]
320 [ + - + - ]: 4 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Range should not be specified for an un-ranged descriptor");
321 : : }
322 : :
323 [ + - + + : 198 : if (desc->IsRange() && request.params.size() == 1) {
+ + ]
324 [ + - + - ]: 4 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Range must be specified for a ranged descriptor");
325 : : }
326 : :
327 [ + + ]: 196 : UniValue addresses = DeriveAddresses(desc.get(), range_begin, range_end, key_provider);
328 : :
329 [ + + ]: 190 : if (descs.size() == 1) {
330 : 188 : return addresses;
331 : : }
332 : :
333 : 2 : UniValue ret(UniValue::VARR);
334 [ + - + - ]: 2 : ret.push_back(addresses);
335 [ + + ]: 4 : for (size_t i = 1; i < descs.size(); ++i) {
336 [ + - + - : 2 : ret.push_back(DeriveAddresses(descs.at(i).get(), range_begin, range_end, key_provider));
+ - ]
337 : : }
338 : 2 : return ret;
339 : 218 : },
340 [ + - + - : 34920 : };
+ - + - +
- + - + -
+ - + - +
- + + + +
- - - - ]
341 [ + - + - : 27936 : }
+ - + - +
- + - + -
+ - + - -
- - - ]
342 : :
343 : 1183 : void RegisterOutputScriptRPCCommands(CRPCTable& t)
344 : : {
345 : 1183 : static const CRPCCommand commands[]{
346 : : {"util", &validateaddress},
347 : : {"util", &createmultisig},
348 : : {"util", &deriveaddresses},
349 : : {"util", &getdescriptorinfo},
350 [ + + + - : 1183 : };
+ - + - +
- + - + -
+ - + - +
- - - ]
351 [ + + ]: 5915 : for (const auto& c : commands) {
352 : 4732 : t.appendCommand(c.name, &c);
353 : : }
354 : 1183 : }
|