Bitcoin Core 32.99.0
P2P Digital Currency
output_script.cpp
Go to the documentation of this file.
1// Copyright (c) 2010 Satoshi Nakamoto
2// Copyright (c) 2009-present 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 <rpc/register.h> // IWYU pragma: associated
7
8#include <addresstype.h>
9#include <crypto/hex_base.h>
10#include <key.h>
11#include <key_io.h>
12#include <outputtype.h>
13#include <pubkey.h>
14#include <rpc/protocol.h>
15#include <rpc/request.h>
16#include <rpc/server.h>
17#include <rpc/util.h>
18#include <script/descriptor.h>
19#include <script/script.h>
21#include <tinyformat.h>
22#include <univalue.h>
23#include <util/check.h>
24
25#include <cstddef>
26#include <cstdint>
27#include <map>
28#include <memory>
29#include <optional>
30#include <span>
31#include <string>
32#include <string_view>
33#include <tuple>
34#include <utility>
35#include <variant>
36#include <vector>
37
39{
40 return RPCMethod{
41 "validateaddress",
42 "Return information about the given bitcoin address.\n",
43 {
44 {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The bitcoin address to validate"},
45 },
48 {
49 {RPCResult::Type::BOOL, "isvalid", "If the address is valid or not"},
50 {RPCResult::Type::STR, "address", /*optional=*/true, "The bitcoin address validated"},
51 {RPCResult::Type::STR_HEX, "scriptPubKey", /*optional=*/true, "The hex-encoded output script generated by the address"},
52 {RPCResult::Type::BOOL, "isscript", /*optional=*/true, "If the key is a script"},
53 {RPCResult::Type::BOOL, "iswitness", /*optional=*/true, "If the address is a witness address"},
54 {RPCResult::Type::NUM, "witness_version", /*optional=*/true, "The version number of the witness program"},
55 {RPCResult::Type::STR_HEX, "witness_program", /*optional=*/true, "The hex value of the witness program"},
56 {RPCResult::Type::STR, "error", /*optional=*/true, "Error message, if any"},
57 {RPCResult::Type::ARR, "error_locations", /*optional=*/true, "Indices of likely error locations in address, if known (e.g. Bech32 errors)",
58 {
59 {RPCResult::Type::NUM, "index", "index of a potential error"},
60 }},
61 }
62 },
64 HelpExampleCli("validateaddress", "\"" + EXAMPLE_ADDRESS[0] + "\"") +
65 HelpExampleRpc("validateaddress", "\"" + EXAMPLE_ADDRESS[0] + "\"")
66 },
67 [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
68 {
69 std::string error_msg;
70 std::vector<int> error_locations;
71 CTxDestination dest = DecodeDestination(request.params[0].get_str(), error_msg, &error_locations);
72 const bool isValid = IsValidDestination(dest);
73 CHECK_NONFATAL(isValid == error_msg.empty());
74
76 ret.pushKV("isvalid", isValid);
77 if (isValid) {
78 std::string currentAddress = EncodeDestination(dest);
79 ret.pushKV("address", currentAddress);
80
81 CScript scriptPubKey = GetScriptForDestination(dest);
82 ret.pushKV("scriptPubKey", HexStr(scriptPubKey));
83
85 ret.pushKVs(std::move(detail));
86 } else {
87 UniValue error_indices(UniValue::VARR);
88 for (int i : error_locations) error_indices.push_back(i);
89 ret.pushKV("error_locations", std::move(error_indices));
90 ret.pushKV("error", error_msg);
91 }
92
93 return ret;
94 },
95 };
96}
97
99{
100 return RPCMethod{
101 "createmultisig",
102 "Creates a multi-signature address with n signatures of m keys required.\n"
103 "It returns a json object with the address and redeemScript.\n",
104 {
105 {"nrequired", RPCArg::Type::NUM, RPCArg::Optional::NO, "The number of required signatures out of the m keys."},
106 {"keys", RPCArg::Type::ARR, RPCArg::Optional::NO, "The hex-encoded public keys.",
107 {
108 {"key", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "The hex-encoded public key"},
109 }},
110 {"address_type", RPCArg::Type::STR, RPCArg::Default{"legacy"}, "The address type to use. Options are \"legacy\", \"p2sh-segwit\", and \"bech32\"."},
111 },
112 RPCResult{
113 RPCResult::Type::OBJ, "", "",
114 {
115 {RPCResult::Type::STR, "address", "The value of the new multisig address."},
116 {RPCResult::Type::STR_HEX, "redeemScript", "The string value of the hex-encoded redemption script."},
117 {RPCResult::Type::STR, "descriptor", "The descriptor for this multisig"},
118 {RPCResult::Type::ARR, "warnings", /*optional=*/true, "Any warnings resulting from the creation of this multisig",
119 {
120 {RPCResult::Type::STR, "", ""},
121 }},
122 }
123 },
125 "\nCreate a multisig address from 2 public keys\n"
126 + HelpExampleCli("createmultisig", "2 \"[\\\"03789ed0bb717d88f7d321a368d905e7430207ebbd82bd342cf11ae157a7ace5fd\\\",\\\"03dbc6764b8884a92e871274b87583e6d5c2a58819473e17e107ef3f6aa5a61626\\\"]\"") +
127 "\nAs a JSON-RPC call\n"
128 + HelpExampleRpc("createmultisig", "2, [\"03789ed0bb717d88f7d321a368d905e7430207ebbd82bd342cf11ae157a7ace5fd\",\"03dbc6764b8884a92e871274b87583e6d5c2a58819473e17e107ef3f6aa5a61626\"]")
129 },
130 [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
131 {
132 int required = request.params[0].getInt<int>();
133
134 // Get the public keys
135 const UniValue& keys = request.params[1].get_array();
136 std::vector<CPubKey> pubkeys;
137 pubkeys.reserve(keys.size());
138 for (unsigned int i = 0; i < keys.size(); ++i) {
139 pubkeys.push_back(HexToPubKey(keys[i].get_str()));
140 }
141
142 // Get the output type
143 auto address_type{self.Arg<std::string_view>("address_type")};
144 auto output_type{ParseOutputType(address_type)};
145 if (!output_type) {
146 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, tfm::format("Unknown address type '%s'", address_type));
147 } else if (output_type.value() == OutputType::BECH32M) {
148 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "createmultisig cannot create bech32m multisig addresses");
149 }
150
151 FlatSigningProvider keystore;
152 CScript inner;
153 const CTxDestination dest = AddAndGetMultisigDestination(required, pubkeys, output_type.value(), keystore, inner);
154
155 // Make the descriptor
156 std::unique_ptr<Descriptor> descriptor = InferDescriptor(GetScriptForDestination(dest), keystore);
157
158 UniValue result(UniValue::VOBJ);
159 result.pushKV("address", EncodeDestination(dest));
160 result.pushKV("redeemScript", HexStr(inner));
161 result.pushKV("descriptor", descriptor->ToString());
162
163 UniValue warnings(UniValue::VARR);
164 if (descriptor->GetOutputType() != output_type.value()) {
165 // Only warns if the user has explicitly chosen an address type we cannot generate
166 warnings.push_back("Unable to make chosen address type, please ensure no uncompressed public keys are present.");
167 }
168 PushWarnings(warnings, result);
169
170 return result;
171 },
172 };
173}
174
176{
177 const std::string EXAMPLE_DESCRIPTOR = "wpkh([d34db33f/84h/0h/0h]0279be667ef9dcbbac55a06295Ce870b07029Bfcdb2dce28d959f2815b16f81798)";
178
179 return RPCMethod{
180 "getdescriptorinfo",
181 "Analyses a descriptor.\n",
182 {
183 {"descriptor", RPCArg::Type::STR, RPCArg::Optional::NO, "The descriptor."},
184 },
185 RPCResult{
186 RPCResult::Type::OBJ, "", "",
187 {
188 {RPCResult::Type::STR, "descriptor", "The descriptor, without private keys. For a multipath descriptor, only the first will be returned."},
189 {RPCResult::Type::ARR, "multipath_expansion", /*optional=*/true, "All descriptors produced by expanding multipath derivation elements. Only if the provided descriptor specifies multipath derivation elements.",
190 {
191 {RPCResult::Type::STR, "", ""},
192 }},
193 {RPCResult::Type::STR, "checksum", "The checksum for the input descriptor"},
194 {RPCResult::Type::BOOL, "isrange", "Whether the descriptor is ranged"},
195 {RPCResult::Type::BOOL, "issolvable", "Whether the descriptor is solvable"},
196 {RPCResult::Type::BOOL, "hasprivatekeys", "Whether the input descriptor contained at least one private key"},
197 }
198 },
200 "Analyse a descriptor\n" +
201 HelpExampleCli("getdescriptorinfo", "\"" + EXAMPLE_DESCRIPTOR + "\"") +
202 HelpExampleRpc("getdescriptorinfo", "\"" + EXAMPLE_DESCRIPTOR + "\"")
203 },
204 [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
205 {
207 std::string error;
208 auto descs = Parse(self.Arg<std::string_view>("descriptor"), provider, error);
209 if (descs.empty()) {
211 }
212
213 UniValue result(UniValue::VOBJ);
214 result.pushKV("descriptor", descs.at(0)->ToString());
215
216 if (descs.size() > 1) {
217 UniValue multipath_descs(UniValue::VARR);
218 for (const auto& d : descs) {
219 multipath_descs.push_back(d->ToString());
220 }
221 result.pushKV("multipath_expansion", multipath_descs);
222 }
223
224 result.pushKV("checksum", GetDescriptorChecksum(request.params[0].get_str()));
225 result.pushKV("isrange", descs.at(0)->IsRange());
226 result.pushKV("issolvable", descs.at(0)->IsSolvable());
227 result.pushKV("hasprivatekeys", provider.keys.size() > 0);
228 return result;
229 },
230 };
231}
232
233static UniValue DeriveAddresses(const Descriptor* desc, int64_t range_begin, int64_t range_end, FlatSigningProvider& key_provider)
234{
235 UniValue addresses(UniValue::VARR);
236
237 for (int64_t i = range_begin; i <= range_end; ++i) {
239 std::vector<CScript> scripts;
240 if (!desc->Expand(i, key_provider, scripts, provider)) {
241 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Cannot derive script without private keys");
242 }
243
244 for (const CScript& script : scripts) {
245 CTxDestination dest;
246 if (!ExtractDestination(script, dest)) {
247 // ExtractDestination no longer returns true for P2PK since it doesn't have a corresponding address
248 // However combo will output P2PK and should just ignore that script
249 if (scripts.size() > 1 && std::get_if<PubKeyDestination>(&dest)) {
250 continue;
251 }
252 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Descriptor does not have a corresponding address");
253 }
254
255 addresses.push_back(EncodeDestination(dest));
256 }
257 }
258
259 // This should not be possible, but an assert seems overkill:
260 if (addresses.empty()) {
261 throw JSONRPCError(RPC_MISC_ERROR, "Unexpected empty result");
262 }
263
264 return addresses;
265}
266
268{
269 const std::string EXAMPLE_DESCRIPTOR = "wpkh([d34db33f/84h/0h/0h]xpub6DJ2dNUysrn5Vt36jH2KLBT2i1auw1tTSSomg8PhqNiUtx8QX2SvC9nrHu81fT41fvDUnhMjEzQgXnQjKEu3oaqMSzhSrHMxyyoEAmUHQbY/0/*)#cjjspncu";
270
271 return RPCMethod{
272 "deriveaddresses",
273 "Derives one or more addresses corresponding to an output descriptor.\n"
274 "Examples of output descriptors are:\n"
275 " pkh(<pubkey>) P2PKH outputs for the given pubkey\n"
276 " wpkh(<pubkey>) Native segwit P2PKH outputs for the given pubkey\n"
277 " sh(multi(<n>,<pubkey>,<pubkey>,...)) P2SH-multisig outputs for the given threshold and pubkeys\n"
278 " raw(<hex script>) Outputs whose output script equals the specified hex-encoded bytes\n"
279 " tr(<pubkey>,multi_a(<n>,<pubkey>,<pubkey>,...)) P2TR-multisig outputs for the given threshold and pubkeys\n"
280 "\nIn the above, <pubkey> either refers to a fixed public key in hexadecimal notation, or to an xpub/xprv optionally followed by one\n"
281 "or more path elements separated by \"/\", where \"h\" represents a hardened child key.\n"
282 "For more information on output descriptors, see the documentation in the doc/descriptors.md file.\n",
283 {
284 {"descriptor", RPCArg::Type::STR, RPCArg::Optional::NO, "The descriptor."},
285 {"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."},
286 },
287 {
288 RPCResult{"for single derivation descriptors",
289 RPCResult::Type::ARR, "", "",
290 {
291 {RPCResult::Type::STR, "address", "the derived addresses"},
292 }
293 },
294 RPCResult{"for multipath descriptors",
295 RPCResult::Type::ARR, "", "The derived addresses for each of the multipath expansions of the descriptor, in multipath specifier order",
296 {
297 {
298 RPCResult::Type::ARR, "", "The derived addresses for a multipath descriptor expansion",
299 {
300 {RPCResult::Type::STR, "address", "the derived address"},
301 },
302 },
303 },
304 },
305 },
307 "First three native segwit receive addresses\n" +
308 HelpExampleCli("deriveaddresses", "\"" + EXAMPLE_DESCRIPTOR + "\" \"[0,2]\"") +
309 HelpExampleRpc("deriveaddresses", "\"" + EXAMPLE_DESCRIPTOR + "\", \"[0,2]\"")
310 },
311 [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
312 {
313 auto desc_str{self.Arg<std::string_view>("descriptor")};
314
315 int64_t range_begin = 0;
316 int64_t range_end = 0;
317
318 const UniValue* range = self.MaybeArg<UniValue>("range");
319 if (range) {
320 std::tie(range_begin, range_end) = ParseDescriptorRange(*range);
321 }
322
323 FlatSigningProvider key_provider;
324 std::string error;
325 auto descs = Parse(desc_str, key_provider, error, /* require_checksum = */ true);
326 if (descs.empty()) {
328 }
329 auto& desc = descs.at(0);
330 if (!desc->IsRange() && range) {
331 throw JSONRPCError(RPC_INVALID_PARAMETER, "Range should not be specified for an un-ranged descriptor");
332 }
333
334 if (desc->IsRange() && !range) {
335 throw JSONRPCError(RPC_INVALID_PARAMETER, "Range must be specified for a ranged descriptor");
336 }
337
338 UniValue addresses = DeriveAddresses(desc.get(), range_begin, range_end, key_provider);
339
340 if (descs.size() == 1) {
341 return addresses;
342 }
343
345 ret.push_back(addresses);
346 for (size_t i = 1; i < descs.size(); ++i) {
347 ret.push_back(DeriveAddresses(descs.at(i).get(), range_begin, range_end, key_provider));
348 }
349 return ret;
350 },
351 };
352}
353
355{
356 static const CRPCCommand commands[]{
357 {"util", &validateaddress},
358 {"util", &createmultisig},
359 {"util", &deriveaddresses},
360 {"util", &getdescriptorinfo},
361 };
362 for (const auto& c : commands) {
363 t.appendCommand(c.name, &c);
364 }
365}
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a scriptPubKey for the destination.
Definition: addresstype.cpp:49
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination corresponds to one with an address.
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
std::variant< CNoDestination, PubKeyDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, PayToAnchor, WitnessUnknown > CTxDestination
A txout script categorized into standard templates.
Definition: addresstype.h:143
int ret
#define CHECK_NONFATAL(condition)
Identity function.
Definition: check.h:112
RPC command dispatcher.
Definition: server.h:89
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:406
auto MaybeArg(std::string_view key) const
Helper to get an optional request argument.
Definition: util.h:502
auto Arg(std::string_view key) const
Helper to get a required or default-valued request argument.
Definition: util.h:470
void push_back(UniValue val)
Definition: univalue.cpp:103
@ VOBJ
Definition: univalue.h:24
@ VARR
Definition: univalue.h:24
bool empty() const
Definition: univalue.h:69
Int getInt() const
Definition: univalue.h:143
void pushKV(std::string key, UniValue val)
Definition: univalue.cpp:125
static UniValue Parse(std::string_view raw, ParamFormat format=ParamFormat::JSON)
Parse string to UniValue or throw runtime_error if string contains invalid JSON.
Definition: client.cpp:408
std::string HexStr(const std::span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: hex_base.cpp:30
CTxDestination DecodeDestination(const std::string &str, std::string &error_msg, std::vector< int > *error_locations)
Definition: key_io.cpp:300
std::string EncodeDestination(const CTxDestination &dest)
Definition: key_io.cpp:295
void format(std::ostream &out, FormatStringCheck< sizeof...(Args)> fmt, const Args &... args)
Format list of arguments to the stream according to given format string.
Definition: tinyformat.h:1079
static RPCMethod deriveaddresses()
static RPCMethod getdescriptorinfo()
static RPCMethod createmultisig()
void RegisterOutputScriptRPCCommands(CRPCTable &t)
static UniValue DeriveAddresses(const Descriptor *desc, int64_t range_begin, int64_t range_end, FlatSigningProvider &key_provider)
static RPCMethod validateaddress()
std::optional< OutputType > ParseOutputType(std::string_view type)
Definition: outputtype.cpp:23
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:75
@ RPC_MISC_ERROR
General application defined errors.
Definition: protocol.h:65
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
Definition: protocol.h:69
@ RPC_INVALID_ADDRESS_OR_KEY
Invalid address or key.
Definition: protocol.h:67
std::pair< int64_t, int64_t > ParseDescriptorRange(const UniValue &value)
Parse a JSON range specified as int64, or [int64, int64].
Definition: util.cpp:1328
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:188
void PushWarnings(const UniValue &warnings, UniValue &obj)
Push warning messages to an RPC "warnings" field as a JSON array of strings.
Definition: util.cpp:1407
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:206
CPubKey HexToPubKey(const std::string &hex_in)
Definition: util.cpp:224
const std::string EXAMPLE_ADDRESS[2]
Example bech32 addresses for the RPCExamples help documentation.
Definition: util.cpp:49
CTxDestination AddAndGetMultisigDestination(const int required, const std::vector< CPubKey > &pubkeys, OutputType type, FlatSigningProvider &keystore, CScript &script_out)
Definition: util.cpp:240
UniValue DescribeAddress(const CTxDestination &dest)
Definition: util.cpp:352
std::unique_ptr< Descriptor > InferDescriptor(const CScript &script, const SigningProvider &provider)
Find a descriptor for the specified script, using information from provider where possible.
std::string GetDescriptorChecksum(const std::string &descriptor)
Get the checksum for a descriptor.
Interface for parsed descriptor objects.
Definition: descriptor.h:108
virtual bool Expand(int pos, const SigningProvider &provider, std::vector< CScript > &output_scripts, FlatSigningProvider &out, DescriptorCache *write_cache=nullptr) const =0
Expand a descriptor at a specified position.
@ RANGE
Special type that is a NUM or [NUM,NUM].
@ STR_HEX
Special type that is a STR with only hex chars.
@ OMITTED
Optional argument for which the default value is omitted from help text for one of two reasons:
@ NO
Required arg.
@ STR_HEX
Special string with only hex chars.
std::vector< uint16_t > keys
Definition: dbwrapper.cpp:376
FuzzedDataProvider provider
Definition: dbwrapper.cpp:366