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