22 "\"qrmzys48glkpevp2l4t24jtcltc9hyzx9cep2qffm4\"";
25 const std::list<UniValueType> &typesExpected,
29 if (params.
size() <= i) {
34 if (!(fAllowNull && v.
isNull())) {
52 const std::map<std::string, UniValueType> &typesExpected,
53 bool fAllowNull,
bool fStrict) {
54 for (
const auto &t : typesExpected) {
56 if (!fAllowNull && v.
isNull()) {
61 if (!(t.second.typeAny || v.
type() == t.second.type ||
62 (fAllowNull && v.
isNull()))) {
63 std::string err =
strprintf(
"Expected type %s for %s, got %s",
71 for (
const std::string &k : o.
getKeys()) {
72 if (typesExpected.count(k) == 0) {
73 std::string err =
strprintf(
"Unexpected key %s", k);
99 std::string strHex(v.
get_str());
100 if (64 != strHex.length()) {
103 strprintf(
"%s must be of length %d (not %d, for '%s')", strName, 64,
104 strHex.length(), strHex));
107 if (!
IsHex(strHex)) {
109 strName +
" must be hexadecimal string (not '" +
124 if (!
IsHex(strHex)) {
126 strName +
" must be hexadecimal string (not '" +
144 std::string ShellQuote(
const std::string &s) {
146 result.reserve(s.size() * 2);
147 for (
const char ch : s) {
154 return "'" + result +
"'";
163 std::string ShellQuoteIfNeeded(
const std::string &s) {
164 for (
const char ch : s) {
165 if (ch ==
' ' || ch ==
'\'' || ch ==
'"') {
166 return ShellQuote(s);
176 const std::string &args) {
177 return "> bitcoin-cli " + methodname +
" " + args +
"\n";
182 std::string result =
"> bitcoin-cli -named " + methodname;
183 for (
const auto &argpair : args) {
184 const auto &value = argpair.second.isStr() ? argpair.second.get_str()
185 : argpair.second.write();
186 result +=
" " + argpair.first +
"=" + ShellQuoteIfNeeded(value);
193 const std::string &args) {
194 return "> curl --user myusername --data-binary '{\"jsonrpc\": \"1.0\", "
195 "\"id\": \"curltest\", "
197 methodname +
"\", \"params\": [" + args +
198 "]}' -H 'content-type: text/plain;' http://127.0.0.1:8332/\n";
204 for (
const auto ¶m : args) {
205 params.
pushKV(param.first, param.second);
208 return "> curl --user myusername --data-binary '{\"jsonrpc\": \"1.0\", "
209 "\"id\": \"curltest\", "
211 methodname +
"\", \"params\": " + params.
write() +
212 "}' -H 'content-type: text/plain;' http://127.0.0.1:8332/\n";
217 if (!
IsHex(hex_in)) {
219 "Invalid public key: " + hex_in);
224 "Invalid public key: " + hex_in);
232 const std::string &addr_in) {
236 "Invalid address: " + addr_in);
241 strprintf(
"%s does not refer to a key", addr_in));
244 if (!keystore.
GetPubKey(key, vchPubKey)) {
247 strprintf(
"no full public key for address %s", addr_in));
251 "Wallet contains an invalid public key");
259 const std::vector<CPubKey> &pubkeys,
267 "a multisignature address must require at least one key to redeem");
269 if ((
int)pubkeys.size() < required) {
271 strprintf(
"not enough keys supplied (got %u keys, "
272 "but need at least %d to redeem)",
273 pubkeys.size(), required));
275 if (pubkeys.size() > 16) {
277 "Number of keys involved in the multisignature "
278 "address creation > 16\nReduce the number");
286 (
strprintf(
"redeemScript exceeds size limit: %d > %d",
291 for (
const CPubKey &pk : pubkeys) {
292 if (!pk.IsCompressed()) {
315 obj.
pushKV(
"isscript",
false);
321 obj.
pushKV(
"isscript",
true);
331 std::vector<std::string> ret;
332 using U = std::underlying_type<TxoutType>::type;
336 return Join(ret,
", ");
359 const std::string &err_string) {
360 if (err_string.length() > 0) {
373 Section(
const std::string &left,
const std::string &right)
395 void Push(
const RPCArg &arg,
const size_t current_indent = 5,
397 const auto indent = std::string(current_indent,
' ');
398 const auto indent_next = std::string(current_indent + 2,
' ');
414 if (arg.
m_type_str.size() != 0 && push_name) {
431 {indent + (push_name ?
"\"" + arg.
GetName() +
"\": " :
"") +
434 for (
const auto &arg_inner : arg.
m_inner) {
447 left += push_name ?
"\"" + arg.
GetName() +
"\": " :
"";
453 for (
const auto &arg_inner : arg.
m_inner) {
476 if (s.m_right.empty()) {
482 std::string left = s.m_left;
483 left.resize(pad,
' ');
489 size_t new_line_pos = s.m_right.find_first_of(
'\n');
491 right += s.m_right.substr(begin, new_line_pos - begin);
492 if (new_line_pos == std::string::npos) {
496 right +=
"\n" + std::string(pad,
' ');
497 begin = s.m_right.find_first_not_of(
' ', new_line_pos + 1);
498 if (begin == std::string::npos) {
501 new_line_pos = s.m_right.find_first_of(
'\n', begin + 1);
514 std::move(results),
std::move(examples), nullptr} {}
519 : m_name{
std::move(name_)}, m_fun{
std::move(fun)},
520 m_description{
std::move(description)}, m_args{
std::move(args)},
521 m_results{
std::move(results)}, m_examples{
std::move(examples)} {
522 std::set<std::string> named_args;
523 for (
const auto &arg :
m_args) {
524 std::vector<std::string> names =
SplitString(arg.m_names,
'|');
526 for (
const std::string &
name : names) {
530 if (arg.m_fallback.index() == 2) {
532 switch (std::get<RPCArg::Default>(arg.m_fallback).getType()) {
571 if (r.m_cond.empty()) {
572 result +=
"\nResult:\n";
574 result +=
"\nResult (" + r.m_cond +
"):\n";
577 r.ToSections(sections);
598 throw std::runtime_error(
ToString());
603 [ret](
const RPCResult &res) { return res.MatchesType(ret); }));
608 size_t num_required_args = 0;
609 for (
size_t n =
m_args.size(); n > 0; --n) {
610 if (!
m_args.at(n - 1).IsOptional()) {
611 num_required_args = n;
615 return num_required_args <= num_args && num_args <=
m_args.size();
619 std::vector<std::string> ret;
620 for (
const auto &arg :
m_args) {
621 ret.emplace_back(arg.m_names);
631 bool was_optional{
false};
632 for (
const auto &arg :
m_args) {
637 const bool optional = arg.IsOptional();
648 was_optional =
false;
650 ret += arg.ToString(
true);
662 for (
size_t i{0}; i <
m_args.size(); ++i) {
663 const auto &arg =
m_args.at(i);
670 ret +=
"\nArguments:\n";
676 arg.ToDescriptionString());
696 for (
int i{0}; i < int(
m_args.size()); ++i) {
697 const auto &arg =
m_args.at(i);
698 std::vector<std::string> arg_names =
SplitString(arg.m_names,
'|');
699 for (
const auto &arg_name : arg_names) {
703 map.push_back(arg_name);
746 ret +=
"numeric or string";
750 ret +=
"numeric or array";
759 ret +=
"json object";
770 ", optional, default=" + std::get<RPCArg::DefaultHint>(
m_fallback);
772 ret +=
", optional, default=" +
773 std::get<RPCArg::Default>(
m_fallback).write();
775 switch (std::get<RPCArg::Optional>(
m_fallback)) {
797 const int current_indent)
const {
799 const std::string indent(current_indent,
' ');
800 const std::string indent_next(current_indent + 2,
' ');
804 const std::string maybe_separator{outer_type !=
OuterType::NONE ?
"," :
""};
807 const std::string maybe_key{
811 const auto Description = [&](
const std::string &type) {
812 return "(" + type + (this->
m_optional ?
", optional" :
"") +
")" +
829 {indent +
"null" + maybe_separator, Description(
"json null")});
834 {indent + maybe_key +
"\"str\"" + maybe_separator,
835 Description(
"string")});
839 sections.
PushSection({indent + maybe_key +
"n" + maybe_separator,
840 Description(
"numeric")});
845 {indent + maybe_key +
"\"hex\"" + maybe_separator,
846 Description(
"string")});
850 sections.
PushSection({indent + maybe_key +
"n" + maybe_separator,
851 Description(
"numeric")});
855 sections.
PushSection({indent + maybe_key +
"xxx" + maybe_separator,
856 Description(
"numeric")});
861 {indent + maybe_key +
"true|false" + maybe_separator,
862 Description(
"boolean")});
868 {indent + maybe_key +
"[", Description(
"json array")});
869 for (
const auto &i :
m_inner) {
879 sections.
PushSection({indent +
"]" + maybe_separator,
""});
885 {indent + maybe_key +
"{}", Description(
"empty JSON object")});
890 {indent + maybe_key +
"{", Description(
"json object")});
891 for (
const auto &i :
m_inner) {
904 sections.
PushSection({indent +
"}" + maybe_separator,
""});
958 return res +
"\"str\"";
960 return res +
"\"hex\"";
964 return res +
"n or [n,n]";
966 return res +
"amount";
971 for (
const auto &i :
m_inner) {
972 res += i.ToString(oneline) +
",";
983 return res +
"unknown";
1008 return "{" + res +
"}";
1010 return "{" + res +
",...}";
1015 for (
const auto &i :
m_inner) {
1016 res += i.ToString(oneline) +
",";
1018 return "[" + res +
"...]";
1025 if (value.
isNum()) {
1035 "Range specified as [begin,end] must not have begin after end");
1040 "Range must be specified as end or as [begin,end]");
1048 "Range should be greater or equal than 0");
1050 if ((high >> 31) != 0) {
1053 if (high >= low + 1000000) {
1059 std::vector<CScript>
1062 std::string desc_str;
1063 std::pair<int64_t, int64_t> range = {0, 1000};
1064 if (scanobject.
isStr()) {
1065 desc_str = scanobject.
get_str();
1066 }
else if (scanobject.
isObject()) {
1068 if (desc_uni.isNull()) {
1071 "Descriptor needs to be provided in scan object");
1073 desc_str = desc_uni.get_str();
1075 if (!range_uni.isNull()) {
1081 "Scan object needs to be either a string or an object");
1085 auto desc =
Parse(desc_str, provider,
error);
1089 if (!desc->IsRange()) {
1093 std::vector<CScript> ret;
1094 for (
int i = range.first; i <= range.second; ++i) {
1095 std::vector<CScript> scripts;
1096 if (!desc->Expand(i, provider, scripts, provider)) {
1099 strprintf(
"Cannot derive script without private keys: '%s'",
1102 std::move(scripts.begin(), scripts.end(), std::back_inserter(ret));
1114 return servicesNames;
bool MoneyRange(const Amount nValue)
static constexpr Amount SATOSHI
#define CHECK_NONFATAL(condition)
Identity function.
#define NONFATAL_UNREACHABLE()
NONFATAL_UNREACHABLE() is a macro that is used to mark unreachable code.
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
A reference to a CKey: the Hash160 of its serialized public key.
An encapsulated public key.
bool IsFullyValid() const
fully validate whether this is a valid public key (more expensive than IsValid())
Serialized script, used inside transaction inputs and outputs.
UniValue operator()(const CNoDestination &dest) const
UniValue operator()(const ScriptHash &scriptID) const
UniValue operator()(const PKHash &keyID) const
Fillable signing provider that keeps keys in an address->secret map.
virtual bool GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const override
enum JSONRPCRequest::Mode mode
const RPCExamples m_examples
std::vector< std::string > GetArgNames() const
RPCHelpMan(std::string name, std::string description, std::vector< RPCArg > args, RPCResults results, RPCExamples examples)
const std::string m_description
bool IsValidNumArgs(size_t num_args) const
If the supplied number of args is neither too small nor too high.
std::function< UniValue(const RPCHelpMan &, const Config &config, const JSONRPCRequest &)> RPCMethodImpl
const RPCMethodImpl m_fun
const RPCResults m_results
UniValue HandleRequest(const Config &config, const JSONRPCRequest &request) const
const std::vector< RPCArg > m_args
std::string ToString() const
UniValue GetArgMap() const
Return the named args that need to be converted from string to another JSON type.
const std::string & get_str() const
const UniValue & find_value(std::string_view key) const
enum VType getType() const
int64_t get_int64() const
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
const std::string & getValStr() const
const std::vector< std::string > & getKeys() const
bool push_back(const UniValue &val)
bool pushKV(const std::string &key, const UniValue &val)
std::unique_ptr< Descriptor > Parse(const std::string &descriptor, FlatSigningProvider &out, std::string &error, bool require_checksum)
Parse a descriptor string.
bilingual_str TransactionErrorString(const TransactionError error)
CTxDestination DecodeDestination(const std::string &addr, const CChainParams ¶ms)
Implement std::hash so RCUPtr can be used as a key for maps or sets.
CTxDestination AddAndGetDestinationForScript(FillableSigningProvider &keystore, const CScript &script, OutputType type)
Get a destination of the requested type (if possible) to the specified script.
std::vector< std::string > serviceFlagsToStr(const uint64_t flags)
Convert service flags (a bitmask of NODE_*) to human readable strings.
ServiceFlags
nServices flags.
UniValue JSONRPCError(int code, const std::string &message)
RPCErrorCode
Bitcoin RPC error codes.
@ RPC_TRANSACTION_ALREADY_IN_CHAIN
@ RPC_TYPE_ERROR
Unexpected type was passed as parameter.
@ RPC_TRANSACTION_REJECTED
@ RPC_TRANSACTION_ERROR
Aliases for backward compatibility.
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
@ RPC_DESERIALIZATION_ERROR
Error parsing or validating structure in raw format.
@ RPC_INVALID_ADDRESS_OR_KEY
Invalid address or key.
@ RPC_CLIENT_P2P_DISABLED
No valid connection manager instance found.
std::pair< int64_t, int64_t > ParseDescriptorRange(const UniValue &value)
Parse a JSON range specified as int64, or [int64, int64].
std::vector< uint8_t > ParseHexV(const UniValue &v, std::string strName)
void RPCTypeCheck(const UniValue ¶ms, const std::list< UniValueType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
UniValue GetServicesNames(ServiceFlags services)
Returns, given services flags, a list of humanly readable (known) network services.
CTxDestination AddAndGetMultisigDestination(const int required, const std::vector< CPubKey > &pubkeys, OutputType type, FillableSigningProvider &keystore, CScript &script_out)
std::string HelpExampleRpcNamed(const std::string &methodname, const RPCArgList &args)
void RPCTypeCheckArgument(const UniValue &value, const UniValueType &typeExpected)
Type-check one argument; throws JSONRPCError if wrong type given.
UniValue JSONRPCTransactionError(TransactionError terr, const std::string &err_string)
Amount AmountFromValue(const UniValue &value)
RPCErrorCode RPCErrorFromTransactionError(TransactionError terr)
std::vector< uint8_t > ParseHexO(const UniValue &o, std::string strKey)
const std::string EXAMPLE_ADDRESS
Example CashAddr address used in multiple RPCExamples.
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 ...
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency.
std::string GetAllOutputTypes()
CPubKey HexToPubKey(const std::string &hex_in)
CPubKey AddrToPubKey(const CChainParams &chainparams, const FillableSigningProvider &keystore, const std::string &addr_in)
uint256 ParseHashO(const UniValue &o, std::string strKey)
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded values (throws error if not hex).
void RPCTypeCheckObj(const UniValue &o, const std::map< std::string, UniValueType > &typesExpected, bool fAllowNull, bool fStrict)
Check for expected keys/value types in an Object.
static std::pair< int64_t, int64_t > ParseRange(const UniValue &value)
std::string HelpExampleCliNamed(const std::string &methodname, const RPCArgList &args)
UniValue DescribeAddress(const CTxDestination &dest)
std::vector< std::pair< std::string, UniValue > > RPCArgList
OuterType
Serializing JSON objects depends on the outer type.
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
CKeyID GetKeyForDestination(const SigningProvider &store, const CTxDestination &dest)
Return the CKeyID of the key involved in a script (if there is a unique one).
CScript GetScriptForMultisig(int nRequired, const std::vector< CPubKey > &keys)
Generate a multisig script.
std::string GetTxnOutputType(TxoutType t)
Get the name of a TxoutType as a string.
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
std::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
bool ParseFixedPoint(const std::string &val, int decimals, int64_t *amount_out)
Parse number as fixed point according to JSON number syntax.
bool IsHex(const std::string &str)
Returns true if each character in str is a hex character, and has an even number of hex digits.
std::vector< uint8_t > ParseHex(const char *psz)
auto Join(const std::vector< T > &list, const BaseType &separator, UnaryOp unary_op) -> decltype(unary_op(list.at(0)))
Join a list of items.
std::vector< std::string > SplitString(std::string_view str, char sep)
static const Currency & get()
@ RANGE
Special type that is a NUM or [NUM,NUM].
@ OBJ_USER_KEYS
Special type where the user must set the keys e.g.
@ STR_HEX
Special type that is a STR with only hex chars.
@ AMOUNT
Special type representing a floating point amount (can be either NUM or STR)
const std::vector< RPCArg > m_inner
Only used for arrays or dicts.
const std::string m_names
The name of the arg (can be empty for inner args, can contain multiple aliases separated by | for nam...
const Fallback m_fallback
std::string ToString(bool oneline) const
Return the type string of the argument.
const std::string m_description
const std::vector< std::string > m_type_str
Should be empty unless it is supposed to override the auto-generated type strings.
std::string GetName() const
Return the name, throws when there are aliases.
std::string GetFirstName() const
Return the first of all aliases.
const std::string m_oneline_description
Should be empty unless it is supposed to override the auto-generated summary line.
std::string ToStringObj(bool oneline) const
Return the type string of the argument when it is in an object (dict).
std::string ToDescriptionString() const
Return the description string, including the argument type and whether the argument is required.
@ 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.
std::string ToDescriptionString() const
const std::string m_examples
const std::string m_description
void ToSections(Sections §ions, OuterType outer_type=OuterType::NONE, const int current_indent=0) const
Append the sections of the result.
@ ELISION
Special type to denote elision (...)
@ NUM_TIME
Special numeric to denote unix epoch time.
@ ANY
Special type to disable type checks (for testing only)
@ ARR_FIXED
Special array that has a fixed number of entries.
@ OBJ_DYN
Special dictionary with keys that are not literals.
@ STR_HEX
Special string with only hex chars.
@ STR_AMOUNT
Special string to represent a floating point amount.
@ OBJ_EMPTY
Special type to allow empty OBJ.
const std::vector< RPCResult > m_inner
Only used for arrays or dicts.
const std::string m_key_name
Only used for dicts.
bool MatchesType(const UniValue &result) const
Check whether the result JSON type matches.
std::string ToDescriptionString() const
Return the description string.
const std::vector< RPCResult > m_results
A pair of strings that can be aligned (through padding) with other Sections later on.
Section(const std::string &left, const std::string &right)
const std::string m_right
Keeps track of RPCArgs by transforming them into sections for the purpose of serializing everything t...
void PushSection(const Section &s)
std::vector< Section > m_sections
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::string ToString() const
Concatenate all sections with proper padding.
Wrapper for UniValue::VType, which includes typeAny: used to denote don't care type.
bool error(const char *fmt, const Args &...args)
uint256 uint256S(const char *str)
uint256 from const char *.
const char * uvTypeName(UniValue::VType t)