17 #include <boost/algorithm/string/classification.hpp> 18 #include <boost/algorithm/string/split.hpp> 19 #include <boost/variant/static_visitor.hpp> 23 "\"qrmzys48glkpevp2l4t24jtcltc9hyzx9cep2qffm4\"";
26 const std::list<UniValueType> &typesExpected,
30 if (params.
size() <= i) {
35 if (!(fAllowNull && v.
isNull())) {
53 const std::map<std::string, UniValueType> &typesExpected,
54 bool fAllowNull,
bool fStrict) {
55 for (
const auto &t : typesExpected) {
57 if (!fAllowNull && v.
isNull()) {
62 if (!(t.second.typeAny || v.
type() == t.second.type ||
63 (fAllowNull && v.
isNull()))) {
64 std::string err =
strprintf(
"Expected type %s for %s, got %s",
72 for (
const std::string &k : o.
getKeys()) {
73 if (typesExpected.count(k) == 0) {
74 std::string err =
strprintf(
"Unexpected key %s", k);
100 std::string strHex(v.
get_str());
101 if (64 != strHex.length()) {
104 strprintf(
"%s must be of length %d (not %d, for '%s')", strName, 64,
105 strHex.length(), strHex));
108 if (!
IsHex(strHex)) {
110 strName +
" must be hexadecimal string (not '" +
125 if (!
IsHex(strHex)) {
127 strName +
" must be hexadecimal string (not '" +
139 const std::string &args) {
140 return "> bitcoin-cli " + methodname +
" " + args +
"\n";
144 const std::string &args) {
145 return "> curl --user myusername --data-binary '{\"jsonrpc\": \"1.0\", " 146 "\"id\": \"curltest\", " 148 methodname +
"\", \"params\": [" + args +
149 "]}' -H 'content-type: text/plain;' http://127.0.0.1:8332/\n";
154 if (!
IsHex(hex_in)) {
156 "Invalid public key: " + hex_in);
161 "Invalid public key: " + hex_in);
169 const std::string &addr_in) {
173 "Invalid address: " + addr_in);
178 strprintf(
"%s does not refer to a key", addr_in));
181 if (!keystore.
GetPubKey(key, vchPubKey)) {
184 strprintf(
"no full public key for address %s", addr_in));
188 "Wallet contains an invalid public key");
196 const std::vector<CPubKey> &pubkeys,
204 "a multisignature address must require at least one key to redeem");
206 if ((
int)pubkeys.size() < required) {
208 strprintf(
"not enough keys supplied (got %u keys, " 209 "but need at least %d to redeem)",
210 pubkeys.size(), required));
212 if (pubkeys.size() > 16) {
214 "Number of keys involved in the multisignature " 215 "address creation > 16\nReduce the number");
223 (
strprintf(
"redeemScript exceeds size limit: %d > %d",
228 for (
const CPubKey &pk : pubkeys) {
229 if (!pk.IsCompressed()) {
252 obj.
pushKV(
"isscript",
false);
258 obj.
pushKV(
"isscript",
true);
287 const std::string &err_string) {
288 if (err_string.length() > 0) {
301 Section(
const std::string &left,
const std::string &right)
302 : m_left{left}, m_right{right} {}
316 m_max_pad = std::max(m_max_pad, s.
m_left.size());
317 m_sections.push_back(s);
323 void Push(
const RPCArg &arg,
const size_t current_indent = 5,
325 const auto indent = std::string(current_indent,
' ');
326 const auto indent_next = std::string(current_indent + 2,
' ');
342 if (arg.
m_type_str.size() != 0 && push_name) {
359 {indent + (push_name ?
"\"" + arg.
GetName() +
"\": " :
"") +
362 for (
const auto &arg_inner : arg.
m_inner) {
366 PushSection({indent_next +
"...",
""});
375 left += push_name ?
"\"" + arg.
GetName() +
"\": " :
"";
380 PushSection({left, right});
381 for (
const auto &arg_inner : arg.
m_inner) {
384 PushSection({indent_next +
"...",
""});
400 const size_t pad = m_max_pad + 4;
401 for (
const auto &s : m_sections) {
402 if (s.m_right.empty()) {
408 std::string left = s.m_left;
409 left.resize(pad,
' ');
415 size_t new_line_pos = s.m_right.find_first_of(
'\n');
417 right += s.m_right.substr(begin, new_line_pos - begin);
418 if (new_line_pos == std::string::npos) {
422 right +=
"\n" + std::string(pad,
' ');
423 begin = s.m_right.find_first_not_of(
' ', new_line_pos + 1);
424 if (begin == std::string::npos) {
427 new_line_pos = s.m_right.find_first_of(
'\n', begin + 1);
439 : m_name{std::move(name_)},
m_description{std::move(description)},
442 std::set<std::string> named_args;
443 for (
const auto &arg :
m_args) {
444 std::vector<std::string> names;
445 boost::split(names, arg.m_names, boost::is_any_of(
"|"));
447 for (
const std::string &
name : names) {
456 if (r.m_cond.empty()) {
457 result +=
"\nResult:\n";
459 result +=
"\nResult (" + r.m_cond +
"):\n";
462 r.ToSections(sections);
473 size_t num_required_args = 0;
474 for (
size_t n =
m_args.size(); n > 0; --n) {
475 if (!
m_args.at(n - 1).IsOptional()) {
476 num_required_args = n;
480 return num_required_args <= num_args && num_args <=
m_args.size();
487 bool was_optional{
false};
488 for (
const auto &arg :
m_args) {
489 const bool optional = arg.IsOptional();
500 was_optional =
false;
502 ret += arg.ToString(
true);
514 for (
size_t i{0}; i < m_args.size(); ++i) {
515 const auto &arg = m_args.at(i);
518 ret +=
"\nArguments:\n";
524 arg.ToDescriptionString());
543 return m_names.substr(0, m_names.find(
"|"));
552 if (m_fallback.which() == 1) {
562 if (m_type_str.size() != 0) {
563 ret += m_type_str.at(1);
576 ret +=
"numeric or string";
580 ret +=
"numeric or array";
588 case Type::OBJ_USER_KEYS: {
589 ret +=
"json object";
600 if (m_fallback.which() == 1) {
601 ret +=
", optional, default=" + boost::get<std::string>(m_fallback);
603 switch (boost::get<RPCArg::Optional>(m_fallback)) {
627 const int current_indent)
const {
629 const std::string indent(current_indent,
' ');
630 const std::string indent_next(current_indent + 2,
' ');
634 const std::string maybe_separator{outer_type !=
OuterType::NONE ?
"," :
""};
637 const std::string maybe_key{
638 outer_type ==
OuterType::OBJ ?
"\"" + this->m_key_name +
"\" : " :
""};
641 const auto Description = [&](
const std::string &type) {
642 return "(" + type + (this->m_optional ?
", optional" :
"") +
")" +
647 case Type::ELISION: {
655 {indent +
"null" + maybe_separator, Description(
"json null")});
660 {indent + maybe_key +
"\"str\"" + maybe_separator,
661 Description(
"string")});
664 case Type::STR_AMOUNT: {
665 sections.
PushSection({indent + maybe_key +
"n" + maybe_separator,
666 Description(
"numeric")});
669 case Type::STR_HEX: {
671 {indent + maybe_key +
"\"hex\"" + maybe_separator,
672 Description(
"string")});
676 sections.
PushSection({indent + maybe_key +
"n" + maybe_separator,
677 Description(
"numeric")});
680 case Type::NUM_TIME: {
681 sections.
PushSection({indent + maybe_key +
"xxx" + maybe_separator,
682 Description(
"numeric")});
687 {indent + maybe_key +
"true|false" + maybe_separator,
688 Description(
"boolean")});
691 case Type::ARR_FIXED:
694 {indent + maybe_key +
"[", Description(
"json array")});
695 for (
const auto &i : m_inner) {
699 if (m_type == Type::ARR && m_inner.back().m_type != Type::ELISION) {
705 sections.
PushSection({indent +
"]" + maybe_separator,
""});
711 {indent + maybe_key +
"{", Description(
"json object")});
712 for (
const auto &i : m_inner) {
716 if (m_type == Type::OBJ_DYN &&
717 m_inner.back().m_type != Type::ELISION) {
725 sections.
PushSection({indent +
"}" + maybe_separator,
""});
738 res += GetFirstName();
746 return res +
"\"str\"";
748 return res +
"\"hex\"";
752 return res +
"n or [n,n]";
754 return res +
"amount";
759 for (
const auto &i : m_inner) {
760 res += i.ToString(oneline) +
",";
764 case Type::OBJ_USER_KEYS:
774 if (oneline && !m_oneline_description.empty()) {
775 return m_oneline_description;
781 return "\"" + GetFirstName() +
"\"";
787 return GetFirstName();
790 case Type::OBJ_USER_KEYS: {
791 const std::string res =
Join(m_inner,
",", [&](
const RPCArg &i) {
794 if (m_type == Type::OBJ) {
795 return "{" + res +
"}";
797 return "{" + res +
",...}";
802 for (
const auto &i : m_inner) {
803 res += i.ToString(oneline) +
",";
805 return "[" + res +
"...]";
824 "Range specified as [begin,end] must not have begin after end");
829 "Range must be specified as end or as [begin,end]");
837 "Range should be greater or equal than 0");
839 if ((high >> 31) != 0) {
842 if (high >= low + 1000000) {
851 std::string desc_str;
852 std::pair<int64_t, int64_t> range = {0, 1000};
853 if (scanobject.
isStr()) {
854 desc_str = scanobject.
get_str();
860 "Descriptor needs to be provided in scan object");
864 if (!range_uni.
isNull()) {
870 "Scan object needs to be either a string or an object");
874 auto desc =
Parse(desc_str, provider, error);
878 if (!desc->IsRange()) {
882 std::vector<CScript> ret;
883 for (
int i = range.first; i <= range.second; ++i) {
884 std::vector<CScript> scripts;
885 if (!desc->Expand(i, provider, scripts, provider)) {
888 strprintf(
"Cannot derive script without private keys: '%s'",
891 std::move(scripts.begin(), scripts.end(), std::back_inserter(ret));
903 return servicesNames;
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 ...
virtual bool GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const override
Aliases for backward compatibility.
std::vector< uint8_t > ParseHexO(const UniValue &o, std::string strKey)
ServiceFlags
nServices flags.
std::string ToDescriptionString() const
Return the description string.
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.
RPCErrorCode RPCErrorFromTransactionError(TransactionError terr)
Keeps track of RPCArgs by transforming them into sections for the purpose of serializing everything t...
auto Join(const std::vector< T > &list, const BaseType &separator, UnaryOp unary_op) -> decltype(unary_op(list.at(0)))
Join a list of items.
static std::pair< int64_t, int64_t > ParseRange(const UniValue &value)
UniValue GetServicesNames(ServiceFlags services)
Returns, given services flags, a list of humanly readable (known) network services.
const std::string EXAMPLE_ADDRESS
Example CashAddr address used in multiple RPCExamples.
void ToSections(Sections §ions, OuterType outer_type=OuterType::NONE, const int current_indent=0) const
Append the sections of the result.
#define CHECK_NONFATAL(condition)
Throw a NonFatalCheckError when the condition evaluates to false.
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
std::string ToDescriptionString() const
const std::string m_right
CPubKey HexToPubKey(const std::string &hex_in)
UniValue DescribeAddress(const CTxDestination &dest)
const RPCExamples m_examples
const std::string & get_str() const
static constexpr Amount SATOSHI
CKeyID GetKeyForDestination(const SigningProvider &store, const CTxDestination &dest)
Return the CKeyID of the key involved in a script (if there is a unique one).
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
int64_t get_int64() const
std::vector< uint8_t > ParseHexV(const UniValue &v, std::string strName)
bool IsValidNumArgs(size_t num_args) const
If the supplied number of args is neither too small nor too high.
const std::vector< std::string > & getKeys() const
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
const std::string & getValStr() const
std::string ToString() const
bool ParseFixedPoint(const std::string &val, int decimals, int64_t *amount_out)
Parse number as fixed point according to JSON number syntax.
const std::vector< RPCArg > m_inner
Only used for arrays or dicts.
Invalid, missing or duplicate parameter.
const UniValue & find_value(const UniValue &obj, const std::string &name)
const std::string m_description
std::pair< int64_t, int64_t > ParseDescriptorRange(const UniValue &value)
Parse a JSON range specified as int64, or [int64, int64].
CTxDestination AddAndGetMultisigDestination(const int required, const std::vector< CPubKey > &pubkeys, OutputType type, FillableSigningProvider &keystore, CScript &script_out)
bool MoneyRange(const Amount nValue)
void RPCTypeCheckArgument(const UniValue &value, const UniValueType &typeExpected)
Type-check one argument; throws JSONRPCError if wrong type given.
std::unique_ptr< Descriptor > Parse(const std::string &descriptor, FlatSigningProvider &out, std::string &error, bool require_checksum)
Parse a descriptor string.
Special type that is a STR with only hex chars.
std::string GetName() const
Return the name, throws when there are aliases.
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
const char * uvTypeName(UniValue::VType t)
UniValue operator()(const PKHash &keyID) const
uint256 ParseHashO(const UniValue &o, std::string strKey)
UniValue JSONRPCError(int code, const std::string &message)
bool push_back(const UniValue &val)
UniValue operator()(const CNoDestination &dest) const
UniValue operator()(const ScriptHash &scriptID) const
bool IsFullyValid() const
fully validate whether this is a valid public key (more expensive than IsValid()) ...
std::vector< std::string > serviceFlagsToStr(const uint64_t flags)
Convert service flags (a bitmask of NODE_*) to human readable strings.
uint256 uint256S(const char *str)
uint256 from const char *.
An encapsulated public key.
Fillable signing provider that keeps keys in an address->secret map.
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...
Unexpected type was passed as parameter.
Special type where the user must set the keys e.g.
Amount AmountFromValue(const UniValue &value)
bool pushKV(const std::string &key, const UniValue &val)
std::string GetFirstName() const
Return the first of all aliases.
const std::vector< RPCArg > m_args
CTxDestination DecodeDestination(const std::string &addr, const CChainParams ¶ms)
CPubKey AddrToPubKey(const CChainParams &chainparams, const FillableSigningProvider &keystore, const std::string &addr_in)
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
CTxDestination AddAndGetDestinationForScript(FillableSigningProvider &keystore, const CScript &script, OutputType type)
Get a destination of the requested type (if possible) to the specified script.
Optional arg that is a named argument and has a default value of null.
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded values (throws error if not hex).
const std::vector< std::string > m_type_str
Should be empty unless it is supposed to override the auto-generated type strings.
const RPCResults m_results
Special type that is a NUM or [NUM,NUM].
OuterType
Serializing JSON objects depends on the outer type.
RPCHelpMan(std::string name, std::string description, std::vector< RPCArg > args, RPCResults results, RPCExamples examples)
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...
std::vector< Section > m_sections
Serialized script, used inside transaction inputs and outputs.
Section(const std::string &left, const std::string &right)
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< uint8_t > ParseHex(const char *psz)
A reference to a CKey: the Hash160 of its serialized public key.
Special type representing a floating point amount (can be either NUM or STR)
CScript GetScriptForMultisig(int nRequired, const std::vector< CPubKey > &keys)
Generate a multisig script.
No valid connection manager instance found.
void PushSection(const Section &s)
UniValue JSONRPCTransactionError(TransactionError terr, const std::string &err_string)
RPCErrorCode
Bitcoin RPC error codes.
std::string ToString() const
Concatenate all sections with proper padding.
bilingual_str TransactionErrorString(const TransactionError error)
std::string ToString(bool oneline) const
Return the type string of the argument.
A pair of strings that can be aligned (through padding) with other Sections later on...
bool error(const char *fmt, const Args &... args)
Wrapper for UniValue::VType, which includes typeAny: used to denote don't care type.
boost::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
Error parsing or validating structure in raw format.
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency...
void RPCTypeCheck(const UniValue ¶ms, const std::list< UniValueType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.
std::string ToStringObj(bool oneline) const
Return the type string of the argument when it is in an object (dict).