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