Bitcoin Core  24.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>
15 #include <script/signingprovider.h>
16 #include <script/standard.h>
17 #include <tinyformat.h>
18 #include <univalue.h>
19 #include <util/check.h>
20 #include <util/strencodings.h>
21 
22 #include <cstdint>
23 #include <memory>
24 #include <optional>
25 #include <string>
26 #include <tuple>
27 #include <vector>
28 
30 {
31  return RPCHelpMan{
32  "validateaddress",
33  "\nReturn information about the given bitcoin address.\n",
34  {
35  {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The bitcoin address to validate"},
36  },
37  RPCResult{
38  RPCResult::Type::OBJ, "", "",
39  {
40  {RPCResult::Type::BOOL, "isvalid", "If the address is valid or not"},
41  {RPCResult::Type::STR, "address", /*optional=*/true, "The bitcoin address validated"},
42  {RPCResult::Type::STR_HEX, "scriptPubKey", /*optional=*/true, "The hex-encoded scriptPubKey generated by the address"},
43  {RPCResult::Type::BOOL, "isscript", /*optional=*/true, "If the key is a script"},
44  {RPCResult::Type::BOOL, "iswitness", /*optional=*/true, "If the address is a witness address"},
45  {RPCResult::Type::NUM, "witness_version", /*optional=*/true, "The version number of the witness program"},
46  {RPCResult::Type::STR_HEX, "witness_program", /*optional=*/true, "The hex value of the witness program"},
47  {RPCResult::Type::STR, "error", /*optional=*/true, "Error message, if any"},
48  {RPCResult::Type::ARR, "error_locations", /*optional=*/true, "Indices of likely error locations in address, if known (e.g. Bech32 errors)",
49  {
50  {RPCResult::Type::NUM, "index", "index of a potential error"},
51  }},
52  }
53  },
55  HelpExampleCli("validateaddress", "\"" + EXAMPLE_ADDRESS[0] + "\"") +
56  HelpExampleRpc("validateaddress", "\"" + EXAMPLE_ADDRESS[0] + "\"")
57  },
58  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
59  {
60  std::string error_msg;
61  std::vector<int> error_locations;
62  CTxDestination dest = DecodeDestination(request.params[0].get_str(), error_msg, &error_locations);
63  const bool isValid = IsValidDestination(dest);
64  CHECK_NONFATAL(isValid == error_msg.empty());
65 
67  ret.pushKV("isvalid", isValid);
68  if (isValid) {
69  std::string currentAddress = EncodeDestination(dest);
70  ret.pushKV("address", currentAddress);
71 
72  CScript scriptPubKey = GetScriptForDestination(dest);
73  ret.pushKV("scriptPubKey", HexStr(scriptPubKey));
74 
75  UniValue detail = DescribeAddress(dest);
76  ret.pushKVs(detail);
77  } else {
78  UniValue error_indices(UniValue::VARR);
79  for (int i : error_locations) error_indices.push_back(i);
80  ret.pushKV("error_locations", error_indices);
81  ret.pushKV("error", error_msg);
82  }
83 
84  return ret;
85  },
86  };
87 }
88 
90 {
91  return RPCHelpMan{"createmultisig",
92  "\nCreates a multi-signature address with n signature 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 n 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  },
114  RPCExamples{
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  for (unsigned int i = 0; i < keys.size(); ++i) {
128  if (IsHex(keys[i].get_str()) && (keys[i].get_str().length() == 66 || keys[i].get_str().length() == 130)) {
129  pubkeys.push_back(HexToPubKey(keys[i].get_str()));
130  } else {
131  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Invalid public key: %s\n.", keys[i].get_str()));
132  }
133  }
134 
135  // Get the output type
136  OutputType output_type = OutputType::LEGACY;
137  if (!request.params[2].isNull()) {
138  std::optional<OutputType> parsed = ParseOutputType(request.params[2].get_str());
139  if (!parsed) {
140  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Unknown address type '%s'", request.params[2].get_str()));
141  } else if (parsed.value() == OutputType::BECH32M) {
142  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "createmultisig cannot create bech32m multisig addresses");
143  }
144  output_type = parsed.value();
145  }
146 
147  // Construct using pay-to-script-hash:
148  FillableSigningProvider keystore;
149  CScript inner;
150  const CTxDestination dest = AddAndGetMultisigDestination(required, pubkeys, output_type, keystore, inner);
151 
152  // Make the descriptor
153  std::unique_ptr<Descriptor> descriptor = InferDescriptor(GetScriptForDestination(dest), keystore);
154 
155  UniValue result(UniValue::VOBJ);
156  result.pushKV("address", EncodeDestination(dest));
157  result.pushKV("redeemScript", HexStr(inner));
158  result.pushKV("descriptor", descriptor->ToString());
159 
160  UniValue warnings(UniValue::VARR);
161  if (descriptor->GetOutputType() != output_type) {
162  // Only warns if the user has explicitly chosen an address type we cannot generate
163  warnings.push_back("Unable to make chosen address type, please ensure no uncompressed public keys are present.");
164  }
165  if (!warnings.empty()) result.pushKV("warnings", warnings);
166 
167  return result;
168  },
169  };
170 }
171 
173 {
174  const std::string EXAMPLE_DESCRIPTOR = "wpkh([d34db33f/84h/0h/0h]0279be667ef9dcbbac55a06295Ce870b07029Bfcdb2dce28d959f2815b16f81798)";
175 
176  return RPCHelpMan{"getdescriptorinfo",
177  {"\nAnalyses a descriptor.\n"},
178  {
179  {"descriptor", RPCArg::Type::STR, RPCArg::Optional::NO, "The descriptor."},
180  },
181  RPCResult{
182  RPCResult::Type::OBJ, "", "",
183  {
184  {RPCResult::Type::STR, "descriptor", "The descriptor in canonical form, without private keys"},
185  {RPCResult::Type::STR, "checksum", "The checksum for the input descriptor"},
186  {RPCResult::Type::BOOL, "isrange", "Whether the descriptor is ranged"},
187  {RPCResult::Type::BOOL, "issolvable", "Whether the descriptor is solvable"},
188  {RPCResult::Type::BOOL, "hasprivatekeys", "Whether the input descriptor contained at least one private key"},
189  }
190  },
191  RPCExamples{
192  "Analyse a descriptor\n" +
193  HelpExampleCli("getdescriptorinfo", "\"" + EXAMPLE_DESCRIPTOR + "\"") +
194  HelpExampleRpc("getdescriptorinfo", "\"" + EXAMPLE_DESCRIPTOR + "\"")
195  },
196  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
197  {
198  RPCTypeCheck(request.params, {UniValue::VSTR});
199 
200  FlatSigningProvider provider;
201  std::string error;
202  auto desc = Parse(request.params[0].get_str(), provider, error);
203  if (!desc) {
205  }
206 
207  UniValue result(UniValue::VOBJ);
208  result.pushKV("descriptor", desc->ToString());
209  result.pushKV("checksum", GetDescriptorChecksum(request.params[0].get_str()));
210  result.pushKV("isrange", desc->IsRange());
211  result.pushKV("issolvable", desc->IsSolvable());
212  result.pushKV("hasprivatekeys", provider.keys.size() > 0);
213  return result;
214  },
215  };
216 }
217 
219 {
220  const std::string EXAMPLE_DESCRIPTOR = "wpkh([d34db33f/84h/0h/0h]xpub6DJ2dNUysrn5Vt36jH2KLBT2i1auw1tTSSomg8PhqNiUtx8QX2SvC9nrHu81fT41fvDUnhMjEzQgXnQjKEu3oaqMSzhSrHMxyyoEAmUHQbY/0/*)#cjjspncu";
221 
222  return RPCHelpMan{"deriveaddresses",
223  {"\nDerives one or more addresses corresponding to an output descriptor.\n"
224  "Examples of output descriptors are:\n"
225  " pkh(<pubkey>) P2PKH outputs for the given pubkey\n"
226  " wpkh(<pubkey>) Native segwit P2PKH outputs for the given pubkey\n"
227  " sh(multi(<n>,<pubkey>,<pubkey>,...)) P2SH-multisig outputs for the given threshold and pubkeys\n"
228  " raw(<hex script>) Outputs whose scriptPubKey equals the specified hex scripts\n"
229  "\nIn the above, <pubkey> either refers to a fixed public key in hexadecimal notation, or to an xpub/xprv optionally followed by one\n"
230  "or more path elements separated by \"/\", where \"h\" represents a hardened child key.\n"
231  "For more information on output descriptors, see the documentation in the doc/descriptors.md file.\n"},
232  {
233  {"descriptor", RPCArg::Type::STR, RPCArg::Optional::NO, "The descriptor."},
234  {"range", RPCArg::Type::RANGE, RPCArg::Optional::OMITTED_NAMED_ARG, "If a ranged descriptor is used, this specifies the end or the range (in [begin,end] notation) to derive."},
235  },
236  RPCResult{
237  RPCResult::Type::ARR, "", "",
238  {
239  {RPCResult::Type::STR, "address", "the derived addresses"},
240  }
241  },
242  RPCExamples{
243  "First three native segwit receive addresses\n" +
244  HelpExampleCli("deriveaddresses", "\"" + EXAMPLE_DESCRIPTOR + "\" \"[0,2]\"") +
245  HelpExampleRpc("deriveaddresses", "\"" + EXAMPLE_DESCRIPTOR + "\", \"[0,2]\"")
246  },
247  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
248  {
249  RPCTypeCheck(request.params, {UniValue::VSTR, UniValueType()}); // Range argument is checked later
250  const std::string desc_str = request.params[0].get_str();
251 
252  int64_t range_begin = 0;
253  int64_t range_end = 0;
254 
255  if (request.params.size() >= 2 && !request.params[1].isNull()) {
256  std::tie(range_begin, range_end) = ParseDescriptorRange(request.params[1]);
257  }
258 
259  FlatSigningProvider key_provider;
260  std::string error;
261  auto desc = Parse(desc_str, key_provider, error, /* require_checksum = */ true);
262  if (!desc) {
264  }
265 
266  if (!desc->IsRange() && request.params.size() > 1) {
267  throw JSONRPCError(RPC_INVALID_PARAMETER, "Range should not be specified for an un-ranged descriptor");
268  }
269 
270  if (desc->IsRange() && request.params.size() == 1) {
271  throw JSONRPCError(RPC_INVALID_PARAMETER, "Range must be specified for a ranged descriptor");
272  }
273 
274  UniValue addresses(UniValue::VARR);
275 
276  for (int i = range_begin; i <= range_end; ++i) {
277  FlatSigningProvider provider;
278  std::vector<CScript> scripts;
279  if (!desc->Expand(i, key_provider, scripts, provider)) {
280  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Cannot derive script without private keys");
281  }
282 
283  for (const CScript& script : scripts) {
284  CTxDestination dest;
285  if (!ExtractDestination(script, dest)) {
286  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Descriptor does not have a corresponding address");
287  }
288 
289  addresses.push_back(EncodeDestination(dest));
290  }
291  }
292 
293  // This should not be possible, but an assert seems overkill:
294  if (addresses.empty()) {
295  throw JSONRPCError(RPC_MISC_ERROR, "Unexpected empty result");
296  }
297 
298  return addresses;
299  },
300  };
301 }
302 
304 {
305  static const CRPCCommand commands[]{
306  {"util", &validateaddress},
307  {"util", &createmultisig},
308  {"util", &deriveaddresses},
309  {"util", &getdescriptorinfo},
310  };
311  for (const auto& c : commands) {
312  t.appendCommand(c.name, &c);
313  }
314 }
int ret
#define CHECK_NONFATAL(condition)
Identity function.
Definition: check.h:47
RPC command dispatcher.
Definition: server.h:126
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:411
Fillable signing provider that keeps keys in an address->secret map.
void push_back(UniValue val)
Definition: univalue.cpp:104
@ VOBJ
Definition: univalue.h:20
@ VARR
Definition: univalue.h:20
bool empty() const
Definition: univalue.h:68
Int getInt() const
Definition: univalue.h:142
const UniValue & get_array() const
void pushKV(std::string key, UniValue val)
Definition: univalue.cpp:126
std::string GetDescriptorChecksum(const std::string &descriptor)
Get the checksum for a descriptor.
std::unique_ptr< Descriptor > Parse(const std::string &descriptor, FlatSigningProvider &out, std::string &error, bool require_checksum)
Parse a descriptor string.
std::unique_ptr< Descriptor > InferDescriptor(const CScript &script, const SigningProvider &provider)
Find a descriptor for the specified script, using information from provider where possible.
CTxDestination DecodeDestination(const std::string &str, std::string &error_msg, std::vector< int > *error_locations)
Definition: key_io.cpp:281
std::string EncodeDestination(const CTxDestination &dest)
Definition: key_io.cpp:276
static RPCHelpMan getdescriptorinfo()
void RegisterOutputScriptRPCCommands(CRPCTable &t)
static RPCHelpMan deriveaddresses()
static RPCHelpMan createmultisig()
static RPCHelpMan validateaddress()
std::optional< OutputType > ParseOutputType(const std::string &type)
Definition: outputtype.cpp:25
OutputType
Definition: outputtype.h:17
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:56
@ RPC_MISC_ERROR
General application defined errors.
Definition: protocol.h:39
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
Definition: protocol.h:43
@ RPC_INVALID_ADDRESS_OR_KEY
Invalid address or key.
Definition: protocol.h:41
std::pair< int64_t, int64_t > ParseDescriptorRange(const UniValue &value)
Parse a JSON range specified as int64, or [int64, int64].
Definition: util.cpp:1041
void RPCTypeCheck(const UniValue &params, const std::list< UniValueType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.
Definition: util.cpp:33
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:166
CTxDestination AddAndGetMultisigDestination(const int required, const std::vector< CPubKey > &pubkeys, OutputType type, FillableSigningProvider &keystore, CScript &script_out)
Definition: util.cpp:236
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:184
CPubKey HexToPubKey(const std::string &hex_in)
Definition: util.cpp:202
const std::string EXAMPLE_ADDRESS[2]
Example bech32 addresses for the RPCExamples help documentation.
Definition: util.cpp:21
UniValue DescribeAddress(const CTxDestination &dest)
Definition: util.cpp:335
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
Definition: standard.cpp:237
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition: standard.cpp:356
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:334
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:149
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_NAMED_ARG
Optional arg that is a named argument and has a default value of null.
@ OMITTED
Optional argument with default value omitted because they are implicitly clear.
@ NO
Required arg.
@ STR_HEX
Special string with only hex chars.
bool error(const char *fmt, const Args &... args)
Definition: system.h:48
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
bool IsHex(std::string_view str)