|
Bitcoin Core
22.99.0
P2P Digital Currency
|
Go to the documentation of this file.
17 #include <boost/algorithm/string/classification.hpp>
18 #include <boost/algorithm/string/split.hpp>
21 const std::string
EXAMPLE_ADDRESS[2] = {
"bc1q09vm5lfy0j5reeulh4x5752q25uqqvz34hufdl",
"bc1q02ad21edsxd23d32dfgqqsz4vv4nmtfzuklhy3"};
24 const std::list<UniValueType>& typesExpected,
29 if (params.
size() <= i)
33 if (!(fAllowNull && v.
isNull())) {
48 const std::map<std::string, UniValueType>& typesExpected,
52 for (
const auto& t : typesExpected) {
54 if (!fAllowNull && v.
isNull())
57 if (!(t.second.typeAny || v.
type() == t.second.type || (fAllowNull && v.
isNull()))) {
58 std::string err =
strprintf(
"Expected type %s for %s, got %s",
66 for (
const std::string& k : o.
getKeys())
68 if (typesExpected.count(k) == 0)
70 std::string err =
strprintf(
"Unexpected key %s", k);
91 std::string strHex(v.
get_str());
92 if (64 != strHex.length())
123 std::string ShellQuote(
const std::string& s)
126 result.reserve(s.size() * 2);
127 for (
const char ch: s) {
134 return "'" + result +
"'";
142 std::string ShellQuoteIfNeeded(
const std::string& s)
144 for (
const char ch: s) {
145 if (ch ==
' ' || ch ==
'\'' || ch ==
'"') {
146 return ShellQuote(s);
155 std::string
HelpExampleCli(
const std::string& methodname,
const std::string& args)
157 return "> bitcoin-cli " + methodname +
" " + args +
"\n";
162 std::string result =
"> bitcoin-cli -named " + methodname;
163 for (
const auto& argpair: args) {
164 const auto& value = argpair.second.isStr()
165 ? argpair.second.get_str()
166 : argpair.second.write();
167 result +=
" " + argpair.first +
"=" + ShellQuoteIfNeeded(value);
173 std::string
HelpExampleRpc(
const std::string& methodname,
const std::string& args)
175 return "> curl --user myusername --data-binary '{\"jsonrpc\": \"1.0\", \"id\": \"curltest\", "
176 "\"method\": \"" + methodname +
"\", \"params\": [" + args +
"]}' -H 'content-type: text/plain;' http://127.0.0.1:8332/\n";
182 for (
const auto& param: args) {
183 params.
pushKV(param.first, param.second);
186 return "> curl --user myusername --data-binary '{\"jsonrpc\": \"1.0\", \"id\": \"curltest\", "
187 "\"method\": \"" + methodname +
"\", \"params\": " + params.
write() +
"}' -H 'content-type: text/plain;' http://127.0.0.1:8332/\n";
193 if (!
IsHex(hex_in)) {
215 if (!keystore.
GetPubKey(key, vchPubKey)) {
231 if ((
int)pubkeys.size() < required) {
241 for (
const CPubKey& pk : pubkeys) {
242 if (!pk.IsCompressed()) {
271 obj.
pushKV(
"isscript",
false);
272 obj.
pushKV(
"iswitness",
false);
279 obj.
pushKV(
"isscript",
true);
280 obj.
pushKV(
"iswitness",
false);
287 obj.
pushKV(
"isscript",
false);
288 obj.
pushKV(
"iswitness",
true);
289 obj.
pushKV(
"witness_version", 0);
297 obj.
pushKV(
"isscript",
true);
298 obj.
pushKV(
"iswitness",
true);
299 obj.
pushKV(
"witness_version", 0);
307 obj.
pushKV(
"isscript",
true);
308 obj.
pushKV(
"iswitness",
true);
309 obj.
pushKV(
"witness_version", 1);
317 obj.
pushKV(
"iswitness",
true);
318 obj.
pushKV(
"witness_version", (
int)
id.version);
331 const int target{value.
get_int()};
332 const unsigned int unsigned_target{
static_cast<unsigned int>(target)};
333 if (target < 1 || unsigned_target > max_target) {
336 return unsigned_target;
360 if (err_string.length() > 0) {
372 Section(
const std::string& left,
const std::string& right)
397 const auto indent = std::string(current_indent,
' ');
398 const auto indent_next = std::string(current_indent + 2,
' ');
410 if (arg.
m_type_str.size() != 0 && push_name) {
422 PushSection({indent + (push_name ?
"\"" + arg.
GetName() +
"\": " :
"") +
"{", right});
423 for (
const auto& arg_inner : arg.
m_inner) {
434 left += push_name ?
"\"" + arg.
GetName() +
"\": " :
"";
438 for (
const auto& arg_inner : arg.
m_inner) {
459 if (s.m_right.empty()) {
465 std::string left = s.m_left;
466 left.resize(pad,
' ');
472 size_t new_line_pos = s.m_right.find_first_of(
'\n');
474 right += s.m_right.substr(begin, new_line_pos - begin);
475 if (new_line_pos == std::string::npos) {
478 right +=
"\n" + std::string(pad,
' ');
479 begin = s.m_right.find_first_not_of(
' ', new_line_pos + 1);
480 if (begin == std::string::npos) {
483 new_line_pos = s.m_right.find_first_of(
'\n', begin + 1);
493 :
RPCHelpMan{std::move(
name), std::move(description), std::move(args), std::move(results), std::move(examples),
nullptr} {}
496 : m_name{std::move(
name)},
497 m_fun{std::move(fun)},
498 m_description{std::move(description)},
499 m_args{std::move(args)},
500 m_results{std::move(results)},
501 m_examples{std::move(examples)}
503 std::set<std::string> named_args;
504 for (
const auto& arg : m_args) {
505 std::vector<std::string> names;
506 boost::split(names, arg.m_names, boost::is_any_of(
"|"));
508 for (
const std::string&
name : names) {
512 if (arg.m_fallback.index() == 2) {
514 switch (std::get<RPCArg::Default>(arg.m_fallback).getType()) {
546 if (r.m_cond.empty()) {
547 result +=
"\nResult:\n";
549 result +=
"\nResult (" + r.m_cond +
"):\n";
552 r.ToSections(sections);
573 throw std::runtime_error(
ToString());
582 size_t num_required_args = 0;
583 for (
size_t n =
m_args.size(); n > 0; --n) {
584 if (!
m_args.at(n - 1).IsOptional()) {
585 num_required_args = n;
589 return num_required_args <= num_args && num_args <=
m_args.size();
594 std::vector<std::string> ret;
595 for (
const auto& arg :
m_args) {
596 ret.emplace_back(arg.m_names);
607 bool was_optional{
false};
608 for (
const auto& arg :
m_args) {
609 if (arg.m_hidden)
break;
610 const bool optional = arg.IsOptional();
613 if (!was_optional) ret +=
"( ";
616 if (was_optional) ret +=
") ";
617 was_optional =
false;
619 ret += arg.ToString(
true);
621 if (was_optional) ret +=
" )";
629 for (
size_t i{0}; i <
m_args.size(); ++i) {
630 const auto& arg =
m_args.at(i);
631 if (arg.m_hidden)
break;
633 if (i == 0) ret +=
"\nArguments:\n";
636 sections.
m_sections.emplace_back(::
ToString(i + 1) +
". " + arg.GetFirstName(), arg.ToDescriptionString());
656 for (
int i{0}; i < int(
m_args.size()); ++i) {
657 const auto& arg =
m_args.at(i);
658 std::vector<std::string> arg_names;
659 boost::split(arg_names, arg.m_names, boost::is_any_of(
"|"));
660 for (
const auto& arg_name : arg_names) {
664 map.push_back(arg_name);
711 ret +=
"numeric or string";
715 ret +=
"numeric or array";
724 ret +=
"json object";
734 ret +=
", optional, default=" + std::get<RPCArg::DefaultHint>(
m_fallback);
736 ret +=
", optional, default=" + std::get<RPCArg::Default>(
m_fallback).write();
738 switch (std::get<RPCArg::Optional>(
m_fallback)) {
761 const std::string indent(current_indent,
' ');
762 const std::string indent_next(current_indent + 2,
' ');
765 const std::string maybe_separator{outer_type !=
OuterType::NONE ?
"," :
""};
768 const std::string maybe_key{
774 const auto Description = [&](
const std::string& type) {
775 return "(" + type + (this->
m_optional ?
", optional" :
"") +
")" +
789 sections.
PushSection({indent +
"null" + maybe_separator, Description(
"json null")});
793 sections.
PushSection({indent + maybe_key +
"\"str\"" + maybe_separator, Description(
"string")});
797 sections.
PushSection({indent + maybe_key +
"n" + maybe_separator, Description(
"numeric")});
801 sections.
PushSection({indent + maybe_key +
"\"hex\"" + maybe_separator, Description(
"string")});
805 sections.
PushSection({indent + maybe_key +
"n" + maybe_separator, Description(
"numeric")});
809 sections.
PushSection({indent + maybe_key +
"xxx" + maybe_separator, Description(
"numeric")});
813 sections.
PushSection({indent + maybe_key +
"true|false" + maybe_separator, Description(
"boolean")});
818 sections.
PushSection({indent + maybe_key +
"[", Description(
"json array")});
819 for (
const auto& i :
m_inner) {
829 sections.
PushSection({indent +
"]" + maybe_separator,
""});
834 sections.
PushSection({indent + maybe_key +
"{", Description(
"json object")});
835 for (
const auto& i :
m_inner) {
846 sections.
PushSection({indent +
"}" + maybe_separator,
""});
901 return res +
"\"str\"";
903 return res +
"\"hex\"";
907 return res +
"n or [n,n]";
909 return res +
"amount";
914 for (
const auto& i :
m_inner) {
915 res += i.ToString(oneline) +
",";
945 return "{" + res +
"}";
947 return "{" + res +
",...}";
952 for (
const auto& i :
m_inner) {
953 res += i.ToString(oneline) +
",";
955 return "[" + res +
"...]";
982 if ((high >> 31) != 0) {
985 if (high >= low + 1000000) {
993 std::string desc_str;
994 std::pair<int64_t, int64_t> range = {0, 1000};
995 if (scanobject.
isStr()) {
996 desc_str = scanobject.
get_str();
1000 desc_str = desc_uni.
get_str();
1002 if (!range_uni.
isNull()) {
1010 auto desc =
Parse(desc_str, provider,
error);
1014 if (!desc->IsRange()) {
1018 std::vector<CScript> ret;
1019 for (
int i = range.first; i <= range.second; ++i) {
1020 std::vector<CScript> scripts;
1021 if (!desc->Expand(i, provider, scripts, provider)) {
1024 std::move(scripts.begin(), scripts.end(), std::back_inserter(ret));
1037 return servicesNames;
UniValue operator()(const WitnessV0ScriptHash &id) const
const RPCMethodImpl m_fun
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency.
@ ELISION
Special type to denote elision (...)
std::unique_ptr< Descriptor > Parse(const std::string &descriptor, FlatSigningProvider &out, std::string &error, bool require_checksum)
Parse a descriptor string.
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded Values (throws error if not hex).
std::string HelpExampleRpcNamed(const std::string &methodname, const RPCArgList &args)
CPubKey HexToPubKey(const std::string &hex_in)
UniValue operator()(const WitnessV0KeyHash &id) const
std::string ToStringObj(bool oneline) const
Return the type string of the argument when it is in an object (dict).
std::vector< unsigned char > ParseHex(const char *psz)
CTxDestination subtype to encode any future Witness version.
const std::string m_oneline_description
Should be empty unless it is supposed to override the auto-generated summary line.
uint256 ParseHashO(const UniValue &o, std::string strKey)
UniValue DescribeAddress(const CTxDestination &dest)
bool ParseFixedPoint(const std::string &val, int decimals, int64_t *amount_out)
Parse number as fixed point according to JSON number syntax.
CPubKey AddrToPubKey(const FillableSigningProvider &keystore, const std::string &addr_in)
#define CHECK_NONFATAL(condition)
Throw a NonFatalCheckError when the condition evaluates to false.
const std::string EXAMPLE_ADDRESS[2]
Example bech32 addresses for the RPCExamples help documentation.
const RPCResults m_results
bilingual_str TransactionErrorString(const TransactionError err)
@ RPC_CLIENT_P2P_DISABLED
No valid connection manager instance found.
RPCErrorCode RPCErrorFromTransactionError(TransactionError terr)
@ RPC_TRANSACTION_REJECTED
UniValue operator()(const CNoDestination &dest) const
Fillable signing provider that keeps keys in an address->secret map.
CTxDestination AddAndGetDestinationForScript(FillableSigningProvider &keystore, const CScript &script, OutputType type)
Get a destination of the requested type (if possible) to the specified script.
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
bool IsHex(const std::string &str)
std::function< UniValue(const RPCHelpMan &, const JSONRPCRequest &)> RPCMethodImpl
std::vector< std::string > serviceFlagsToStr(uint64_t flags)
Convert service flags (a bitmask of NODE_*) to human readable strings.
const Fallback m_fallback
bool MoneyRange(const CAmount &nValue)
const std::string m_key_name
Only used for dicts.
std::vector< unsigned char > ParseHexV(const UniValue &v, std::string strName)
ServiceFlags
nServices flags
A reference to a CKey: the Hash160 of its serialized public key.
const std::string m_examples
std::vector< unsigned char > ParseHexO(const UniValue &o, std::string strKey)
const std::vector< RPCArg > m_inner
Only used for arrays or dicts.
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
@ OBJ_USER_KEYS
Special type where the user must set the keys e.g. to define multiple addresses; as opposed to e....
const std::string m_right
enum VType getType() const
void RPCTypeCheckArgument(const UniValue &value, const UniValueType &typeExpected)
Type-check one argument; throws JSONRPCError if wrong type given.
const std::vector< RPCResult > m_inner
Only used for arrays or dicts.
bool pushKV(const std::string &key, const UniValue &val)
UniValue operator()(const PKHash &keyID) const
const std::vector< RPCArg > m_args
@ RPC_TRANSACTION_ALREADY_IN_CHAIN
OuterType
Serializing JSON objects depends on the outer type.
void ToSections(Sections §ions, OuterType outer_type=OuterType::NONE, const int current_indent=0) const
Append the sections of the result.
@ ARR_FIXED
Special array that has a fixed number of entries.
A Span is an object that can refer to a contiguous sequence of objects.
const RPCExamples m_examples
UniValue GetArgMap() const
Return the named args that need to be converted from string to another JSON type.
const std::string & get_str() const
@ RPC_DESERIALIZATION_ERROR
Error parsing or validating structure in raw format.
Wrapper for UniValue::VType, which includes typeAny: Used to denote don't care type.
Section(const std::string &left, const std::string &right)
std::string ToString() const
int64_t get_int64() const
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
bool IsValidNumArgs(size_t num_args) const
If the supplied number of args is neither too small nor too high.
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
@ OMITTED_NAMED_ARG
Optional arg that is a named argument and has a default value of null.
virtual bool GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const override
void RPCTypeCheckObj(const UniValue &o, const std::map< std::string, UniValueType > &typesExpected, bool fAllowNull, bool fStrict)
@ STR_HEX
Special type that is a STR with only hex chars.
UniValue HandleRequest(const JSONRPCRequest &request) const
CScript GetScriptForMultisig(int nRequired, const std::vector< CPubKey > &keys)
Generate a multisig script.
const std::string m_description
std::string ToDescriptionString() const
Return the description string.
const std::string m_description
static std::pair< int64_t, int64_t > ParseRange(const UniValue &value)
Keeps track of RPCArgs by transforming them into sections for the purpose of serializing everything t...
@ STR_HEX
Special string with only hex chars.
int64_t CAmount
Amount in satoshis (Can be negative)
CKeyID GetKeyForDestination(const SigningProvider &store, const CTxDestination &dest)
Return the CKeyID of the key involved in a script (if there is a unique one).
enum JSONRPCRequest::Mode mode
bool MatchesType(const UniValue &result) const
Check whether the result JSON type matches.
const std::vector< std::string > & getKeys() const
const char * uvTypeName(UniValue::VType t)
std::vector< Section > m_sections
RPCHelpMan(std::string name, std::string description, std::vector< RPCArg > args, RPCResults results, RPCExamples examples)
std::string ToDescriptionString() const
uint256 uint256S(const char *str)
UniValue operator()(const ScriptHash &scriptID) const
@ NUM_TIME
Special numeric to denote unix epoch time.
const std::string m_names
The name of the arg (can be empty for inner args, can contain multiple aliases separated by | for nam...
CTxDestination DecodeDestination(const std::string &str, std::string &error_msg)
std::string GetName() const
Return the name, throws when there are aliases.
@ ANY
Special type to disable type checks (for testing only)
Serialized script, used inside transaction inputs and outputs.
const std::vector< std::string > m_type_str
Should be empty unless it is supposed to override the auto-generated type strings....
@ RANGE
Special type that is a NUM or [NUM,NUM].
UniValue operator()(const WitnessUnknown &id) const
std::string GetFirstName() const
Return the first of all aliases.
std::vector< std::string > GetArgNames() const
@ RPC_INVALID_ADDRESS_OR_KEY
Invalid address or key.
CAmount AmountFromValue(const UniValue &value, int decimals)
Validate and return a CAmount from a UniValue number or string.
unsigned int ParseConfirmTarget(const UniValue &value, unsigned int max_target)
Parse a confirm target option and raise an RPC error if it is invalid.
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
const std::string & getValStr() const
auto Join(const std::vector< T > &list, const BaseType &separator, UnaryOp unary_op) -> decltype(unary_op(list.at(0)))
Join a list of items.
CTxDestination AddAndGetMultisigDestination(const int required, const std::vector< CPubKey > &pubkeys, OutputType type, FillableSigningProvider &keystore, CScript &script_out)
UniValue operator()(const WitnessV1Taproot &tap) const
An encapsulated public key.
void PushSection(const Section &s)
void Push(const RPCArg &arg, const size_t current_indent=5, const OuterType outer_type=OuterType::NONE)
Recursive helper to translate an RPCArg into sections.
std::vector< std::pair< std::string, UniValue > > RPCArgList
std::string ToString() const
Concatenate all sections with proper padding.
UniValue JSONRPCError(int code, const std::string &message)
RPCErrorCode
Bitcoin RPC error codes.
const std::vector< RPCResult > m_results
@ OMITTED
Optional argument with default value omitted because they are implicitly clear.
std::string ToDescriptionString() const
Return the description string, including the argument type and whether the argument is required.
bool push_back(const UniValue &val)
bool IsFullyValid() const
fully validate whether this is a valid public key (more expensive than IsValid())
std::string HelpExampleCliNamed(const std::string &methodname, const RPCArgList &args)
@ OBJ_DYN
Special dictionary with keys that are not literals.
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
@ AMOUNT
Special type representing a floating point amount (can be either NUM or STR)
std::string ToString(bool oneline) const
Return the type string of the argument.
const UniValue & find_value(const UniValue &obj, const std::string &name)
@ RPC_TYPE_ERROR
Unexpected type was passed as parameter.
bool error(const char *fmt, const Args &... args)
@ STR_AMOUNT
Special string to represent a floating point amount.
UniValue GetServicesNames(ServiceFlags services)
Returns, given services flags, a list of humanly readable (known) network services.
std::vector< CScript > EvalDescriptorStringOrObject(const UniValue &scanobject, FlatSigningProvider &provider)
Evaluate a descriptor given as a string, or as a {"desc":...,"range":...} object, with default range ...
void RPCTypeCheck(const UniValue ¶ms, const std::list< UniValueType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
const std::string m_description
UniValue JSONRPCTransactionError(TransactionError terr, const std::string &err_string)
static const int MAX_PUBKEYS_PER_MULTISIG
@ RPC_TRANSACTION_ERROR
Aliases for backward compatibility.
A pair of strings that can be aligned (through padding) with other Sections later on.
std::pair< int64_t, int64_t > ParseDescriptorRange(const UniValue &value)
Parse a JSON range specified as int64, or [int64, int64].
std::string HelpExampleCli(const std::string &methodname, const std::string &args)