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 : 2721 : static RPCHelpMan validateaddress()
29 : : {
30 : 2721 : return RPCHelpMan{
31 : : "validateaddress",
32 : : "\nReturn information about the given bitcoin address.\n",
33 : : {
34 [ + - ]: 2721 : {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The bitcoin address to validate"},
35 : : },
36 [ + - + - : 32652 : 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 scriptPubKey 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 [ + - + - : 29931 : },
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - ]
53 [ + - ]: 5442 : RPCExamples{
54 [ + - + - : 8163 : HelpExampleCli("validateaddress", "\"" + EXAMPLE_ADDRESS[0] + "\"") +
+ - + - ]
55 [ + - + - : 8163 : HelpExampleRpc("validateaddress", "\"" + EXAMPLE_ADDRESS[0] + "\"")
+ - ]
56 : : },
57 : 304 : [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
58 : : {
59 [ + - ]: 304 : std::string error_msg;
60 : 304 : std::vector<int> error_locations;
61 [ + - + - : 304 : CTxDestination dest = DecodeDestination(request.params[0].get_str(), error_msg, &error_locations);
+ - ]
62 [ + - ]: 304 : const bool isValid = IsValidDestination(dest);
63 [ + - ]: 304 : CHECK_NONFATAL(isValid == error_msg.empty());
64 : :
65 : 304 : UniValue ret(UniValue::VOBJ);
66 [ + - + - : 608 : ret.pushKV("isvalid", isValid);
+ - ]
67 [ + + ]: 304 : if (isValid) {
68 [ + - ]: 258 : std::string currentAddress = EncodeDestination(dest);
69 [ + - + - : 516 : ret.pushKV("address", currentAddress);
+ - ]
70 : :
71 [ + - ]: 258 : CScript scriptPubKey = GetScriptForDestination(dest);
72 [ + + + - : 774 : ret.pushKV("scriptPubKey", HexStr(scriptPubKey));
+ - + - +
- ]
73 : :
74 [ + - ]: 258 : UniValue detail = DescribeAddress(dest);
75 [ + - ]: 258 : ret.pushKVs(std::move(detail));
76 : 258 : } 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 : 304 : return ret;
84 : 304 : },
85 [ + - + - : 24489 : };
+ - + - +
- + + -
- ]
86 [ + - + - : 38094 : }
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + + - -
- - ]
87 : :
88 : 2548 : static RPCHelpMan createmultisig()
89 : : {
90 : 2548 : 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 [ + - ]: 2548 : {"nrequired", RPCArg::Type::NUM, RPCArg::Optional::NO, "The number of required signatures out of the n keys."},
95 [ + - ]: 2548 : {"keys", RPCArg::Type::ARR, RPCArg::Optional::NO, "The hex-encoded public keys.",
96 : : {
97 [ + - ]: 2548 : {"key", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "The hex-encoded public key"},
98 : : }},
99 [ + - ]: 5096 : {"address_type", RPCArg::Type::STR, RPCArg::Default{"legacy"}, "The address type to use. Options are \"legacy\", \"p2sh-segwit\", and \"bech32\"."},
100 : : },
101 [ + - + - : 17836 : 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 [ + - + - : 15288 : },
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - ]
113 [ + - ]: 5096 : RPCExamples{
114 : : "\nCreate a multisig address from 2 public keys\n"
115 [ + - + - : 5096 : + HelpExampleCli("createmultisig", "2 \"[\\\"03789ed0bb717d88f7d321a368d905e7430207ebbd82bd342cf11ae157a7ace5fd\\\",\\\"03dbc6764b8884a92e871274b87583e6d5c2a58819473e17e107ef3f6aa5a61626\\\"]\"") +
+ - + - ]
116 : : "\nAs a JSON-RPC call\n"
117 [ + - + - : 10192 : + HelpExampleRpc("createmultisig", "2, [\"03789ed0bb717d88f7d321a368d905e7430207ebbd82bd342cf11ae157a7ace5fd\",\"03dbc6764b8884a92e871274b87583e6d5c2a58819473e17e107ef3f6aa5a61626\"]")
+ - + - ]
118 : : },
119 : 133 : [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
120 : : {
121 : 133 : int required = request.params[0].getInt<int>();
122 : :
123 : : // Get the public keys
124 : 133 : const UniValue& keys = request.params[1].get_array();
125 : 133 : std::vector<CPubKey> pubkeys;
126 [ + + ]: 903 : for (unsigned int i = 0; i < keys.size(); ++i) {
127 [ + - + - : 1542 : pubkeys.push_back(HexToPubKey(keys[i].get_str()));
+ + ]
128 : : }
129 : :
130 : : // Get the output type
131 : 131 : OutputType output_type = OutputType::LEGACY;
132 [ + - + + ]: 131 : if (!request.params[2].isNull()) {
133 [ + - + - : 122 : std::optional<OutputType> parsed = ParseOutputType(request.params[2].get_str());
+ - ]
134 [ + + ]: 122 : if (!parsed) {
135 [ + - + - : 2 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Unknown address type '%s'", request.params[2].get_str()));
+ - + - ]
136 [ + + ]: 121 : } else if (parsed.value() == OutputType::BECH32M) {
137 [ + - + - ]: 2 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "createmultisig cannot create bech32m multisig addresses");
138 : : }
139 : : output_type = parsed.value();
140 : : }
141 : :
142 : 129 : FlatSigningProvider keystore;
143 [ + + ]: 129 : CScript inner;
144 [ + + ]: 129 : const CTxDestination dest = AddAndGetMultisigDestination(required, pubkeys, output_type, keystore, inner);
145 : :
146 : : // Make the descriptor
147 [ + - + - ]: 126 : std::unique_ptr<Descriptor> descriptor = InferDescriptor(GetScriptForDestination(dest), keystore);
148 : :
149 : 126 : UniValue result(UniValue::VOBJ);
150 [ + - + - : 252 : result.pushKV("address", EncodeDestination(dest));
+ - + - ]
151 [ + - + - : 378 : result.pushKV("redeemScript", HexStr(inner));
+ - + - +
- ]
152 [ + - + - : 252 : result.pushKV("descriptor", descriptor->ToString());
+ - + - ]
153 : :
154 : 126 : UniValue warnings(UniValue::VARR);
155 [ + - ]: 126 : if (descriptor->GetOutputType() != output_type) {
156 : : // Only warns if the user has explicitly chosen an address type we cannot generate
157 [ + - + - ]: 24 : warnings.push_back("Unable to make chosen address type, please ensure no uncompressed public keys are present.");
158 : : }
159 [ + - ]: 126 : PushWarnings(warnings, result);
160 : :
161 : 126 : return result;
162 : 136 : },
163 [ + - + - : 40768 : };
+ - + - +
- + - + -
+ - + - +
+ - - ]
164 [ + - + - : 43316 : }
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ + + + -
- - - - -
- - ]
165 : :
166 : 2925 : static RPCHelpMan getdescriptorinfo()
167 : : {
168 : 2925 : const std::string EXAMPLE_DESCRIPTOR = "wpkh([d34db33f/84h/0h/0h]0279be667ef9dcbbac55a06295Ce870b07029Bfcdb2dce28d959f2815b16f81798)";
169 : :
170 [ + - ]: 2925 : return RPCHelpMan{"getdescriptorinfo",
171 : : {"\nAnalyses a descriptor.\n"},
172 : : {
173 [ + - ]: 2925 : {"descriptor", RPCArg::Type::STR, RPCArg::Optional::NO, "The descriptor."},
174 : : },
175 [ + - + - : 23400 : RPCResult{
+ + - - ]
176 : : RPCResult::Type::OBJ, "", "",
177 : : {
178 : : {RPCResult::Type::STR, "descriptor", "The descriptor in canonical form, without private keys"},
179 : : {RPCResult::Type::STR, "checksum", "The checksum for the input descriptor"},
180 : : {RPCResult::Type::BOOL, "isrange", "Whether the descriptor is ranged"},
181 : : {RPCResult::Type::BOOL, "issolvable", "Whether the descriptor is solvable"},
182 : : {RPCResult::Type::BOOL, "hasprivatekeys", "Whether the input descriptor contained at least one private key"},
183 : : }
184 [ + - + - : 17550 : },
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - +
- ]
185 [ + - ]: 5850 : RPCExamples{
186 [ + - ]: 5850 : "Analyse a descriptor\n" +
187 [ + - + - : 14625 : HelpExampleCli("getdescriptorinfo", "\"" + EXAMPLE_DESCRIPTOR + "\"") +
+ - + - ]
188 [ + - + - : 8775 : HelpExampleRpc("getdescriptorinfo", "\"" + EXAMPLE_DESCRIPTOR + "\"")
+ - ]
189 : : },
190 : 508 : [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
191 : : {
192 : 508 : FlatSigningProvider provider;
193 [ + - ]: 508 : std::string error;
194 [ + - + - : 508 : auto desc = Parse(request.params[0].get_str(), provider, error);
+ - ]
195 [ + + ]: 508 : if (!desc) {
196 [ + - ]: 1 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error);
197 : : }
198 : :
199 : 507 : UniValue result(UniValue::VOBJ);
200 [ + - + - : 1014 : result.pushKV("descriptor", desc->ToString());
+ - + - ]
201 [ + - + - : 1014 : result.pushKV("checksum", GetDescriptorChecksum(request.params[0].get_str()));
+ - + - +
- + - ]
202 [ + - + - : 1014 : result.pushKV("isrange", desc->IsRange());
+ - + - ]
203 [ + - + - : 1014 : result.pushKV("issolvable", desc->IsSolvable());
+ - + - ]
204 [ + - + - : 1014 : result.pushKV("hasprivatekeys", provider.keys.size() > 0);
+ - ]
205 : 507 : return result;
206 : 509 : },
207 [ + - + - : 26325 : };
+ - + - +
- + - + +
- - ]
208 [ + - + - : 29250 : }
+ - + - +
- + - + -
+ - + - -
- ]
209 : :
210 : 2641 : static RPCHelpMan deriveaddresses()
211 : : {
212 : 2641 : const std::string EXAMPLE_DESCRIPTOR = "wpkh([d34db33f/84h/0h/0h]xpub6DJ2dNUysrn5Vt36jH2KLBT2i1auw1tTSSomg8PhqNiUtx8QX2SvC9nrHu81fT41fvDUnhMjEzQgXnQjKEu3oaqMSzhSrHMxyyoEAmUHQbY/0/*)#cjjspncu";
213 : :
214 [ + - ]: 2641 : return RPCHelpMan{"deriveaddresses",
215 : : {"\nDerives one or more addresses corresponding to an output descriptor.\n"
216 : : "Examples of output descriptors are:\n"
217 : : " pkh(<pubkey>) P2PKH outputs for the given pubkey\n"
218 : : " wpkh(<pubkey>) Native segwit P2PKH outputs for the given pubkey\n"
219 : : " sh(multi(<n>,<pubkey>,<pubkey>,...)) P2SH-multisig outputs for the given threshold and pubkeys\n"
220 : : " raw(<hex script>) Outputs whose scriptPubKey equals the specified hex scripts\n"
221 : : " tr(<pubkey>,multi_a(<n>,<pubkey>,<pubkey>,...)) P2TR-multisig outputs for the given threshold and pubkeys\n"
222 : : "\nIn the above, <pubkey> either refers to a fixed public key in hexadecimal notation, or to an xpub/xprv optionally followed by one\n"
223 : : "or more path elements separated by \"/\", where \"h\" represents a hardened child key.\n"
224 : : "For more information on output descriptors, see the documentation in the doc/descriptors.md file.\n"},
225 : : {
226 [ + - ]: 2641 : {"descriptor", RPCArg::Type::STR, RPCArg::Optional::NO, "The descriptor."},
227 [ + - ]: 2641 : {"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."},
228 : : },
229 [ + - + - : 10564 : RPCResult{
+ + - - ]
230 : : RPCResult::Type::ARR, "", "",
231 : : {
232 : : {RPCResult::Type::STR, "address", "the derived addresses"},
233 : : }
234 [ + - + - : 5282 : },
+ - + - +
- ]
235 [ + - ]: 5282 : RPCExamples{
236 [ + - ]: 5282 : "First three native segwit receive addresses\n" +
237 [ + - + - : 13205 : HelpExampleCli("deriveaddresses", "\"" + EXAMPLE_DESCRIPTOR + "\" \"[0,2]\"") +
+ - + - ]
238 [ + - + - : 7923 : HelpExampleRpc("deriveaddresses", "\"" + EXAMPLE_DESCRIPTOR + "\", \"[0,2]\"")
+ - ]
239 : : },
240 : 226 : [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
241 : : {
242 : 226 : const std::string desc_str = request.params[0].get_str();
243 : :
244 : 226 : int64_t range_begin = 0;
245 : 226 : int64_t range_end = 0;
246 : :
247 [ + + + - : 226 : if (request.params.size() >= 2 && !request.params[1].isNull()) {
+ - ]
248 [ + - + + ]: 84 : std::tie(range_begin, range_end) = ParseDescriptorRange(request.params[1]);
249 : : }
250 : :
251 : 218 : FlatSigningProvider key_provider;
252 [ + - ]: 218 : std::string error;
253 [ + - ]: 218 : auto desc = Parse(desc_str, key_provider, error, /* require_checksum = */ true);
254 [ + + ]: 218 : if (!desc) {
255 [ + - ]: 4 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error);
256 : : }
257 : :
258 [ + - + + : 214 : if (!desc->IsRange() && request.params.size() > 1) {
+ + ]
259 [ + - + - ]: 4 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Range should not be specified for an un-ranged descriptor");
260 : : }
261 : :
262 [ + - + + : 212 : if (desc->IsRange() && request.params.size() == 1) {
+ + ]
263 [ + - + - ]: 4 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Range must be specified for a ranged descriptor");
264 : : }
265 : :
266 : 210 : UniValue addresses(UniValue::VARR);
267 : :
268 [ + + ]: 428 : for (int64_t i = range_begin; i <= range_end; ++i) {
269 : 224 : FlatSigningProvider provider;
270 : 224 : std::vector<CScript> scripts;
271 [ + - + + ]: 224 : if (!desc->Expand(i, key_provider, scripts, provider)) {
272 [ + - + - ]: 4 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Cannot derive script without private keys");
273 : : }
274 : :
275 [ + + ]: 446 : for (const CScript& script : scripts) {
276 [ + - ]: 228 : CTxDestination dest;
277 [ + - + + ]: 228 : if (!ExtractDestination(script, dest)) {
278 : : // ExtractDestination no longer returns true for P2PK since it doesn't have a corresponding address
279 : : // However combo will output P2PK and should just ignore that script
280 [ + + ]: 6 : if (scripts.size() > 1 && std::get_if<PubKeyDestination>(&dest)) {
281 : 2 : continue;
282 : : }
283 [ + - + - ]: 8 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Descriptor does not have a corresponding address");
284 : : }
285 : :
286 [ + - + - : 222 : addresses.push_back(EncodeDestination(dest));
+ - ]
287 : 228 : }
288 : 230 : }
289 : :
290 : : // This should not be possible, but an assert seems overkill:
291 [ - + ]: 204 : if (addresses.empty()) {
292 [ # # # # ]: 0 : throw JSONRPCError(RPC_MISC_ERROR, "Unexpected empty result");
293 : : }
294 : :
295 : 408 : return addresses;
296 : 238 : },
297 [ + - + - : 29051 : };
+ - + - +
- + - + -
+ + - - ]
298 [ + - + - : 21128 : }
+ - + - +
- + - + -
- - ]
299 : :
300 : 1325 : void RegisterOutputScriptRPCCommands(CRPCTable& t)
301 : : {
302 : 1325 : static const CRPCCommand commands[]{
303 : : {"util", &validateaddress},
304 : : {"util", &createmultisig},
305 : : {"util", &deriveaddresses},
306 : : {"util", &getdescriptorinfo},
307 [ + + + - : 1325 : };
+ - + - +
- + - + -
+ - + - +
- - - ]
308 [ + + ]: 6625 : for (const auto& c : commands) {
309 : 5300 : t.appendCommand(c.name, &c);
310 : : }
311 : 1325 : }
|