6#include <bitcoin-build-config.h>
22#include <validation.h>
31#include <unordered_set>
32#include <unordered_map>
59 std::list<RPCCommandExecutionInfo>::iterator
it;
76 std::set<intptr_t> setDone;
77 std::vector<std::pair<std::string, const CRPCCommand*> > vCommands;
81 vCommands.emplace_back(entry.second.front()->category + entry.first, entry.second.front());
82 std::ranges::sort(vCommands);
88 for (
const auto& [
_, pcmd] : vCommands) {
89 std::string strMethod = pcmd->name;
90 if ((strCommand !=
"" || pcmd->category ==
"hidden") && strMethod != strCommand)
96 if (setDone.insert(pcmd->unique_id).second)
97 pcmd->actor(jreq, unused_result,
true);
99 std::string strHelp{e.what()};
100 if (strCommand ==
"")
102 if (strHelp.find(
'\n') != std::string::npos)
103 strHelp = strHelp.substr(0, strHelp.find(
'\n'));
105 if (category != pcmd->category)
107 if (!category.empty())
109 category = pcmd->category;
110 strRet +=
"== " +
Capitalize(category) +
" ==\n";
113 strRet += strHelp +
"\n";
117 strRet =
strprintf(
"help: unknown command: %s\n", strCommand);
118 strRet = strRet.substr(0,strRet.size()-1);
126 "List all commands, or get help for a specified command.\n",
138 if (
command ==
"dump_all_command_conversions") {
150 static const std::string RESULT{CLIENT_NAME
" stopping"};
156 "Request a graceful shutdown of " CLIENT_NAME
".",
167 if (jsonRequest.params[0].isNum()) {
179 "Returns the total uptime of the server.\n",
199 "Returns details of the RPC server.\n",
225 entry.
pushKV(
"duration", Ticks<std::chrono::microseconds>(SteadyClock::now() - info.
start));
226 active_commands.
push_back(std::move(entry));
230 result.
pushKV(
"active_commands", std::move(active_commands));
234 result.
pushKV(
"logpath", std::move(log_path));
245UniValue MakeObject(std::initializer_list<std::pair<std::string, UniValue>> entries)
248 for (
const auto& [key, value] : entries) {
249 obj.pushKV(key, value);
254void PushUniqueSchema(
UniValue& schemas, std::unordered_set<std::string>& seen,
UniValue schema)
256 const std::string serialized{schema.
write()};
257 if (seen.insert(serialized).second) schemas.
push_back(std::move(schema));
261UniValue DedupArrayItemsSchema(std::span<const RPCArg> inner,
bool include_hidden)
264 if (inner.size() == 1)
return OpenRPCArgSchema(inner.front(), include_hidden);
267 std::unordered_set<std::string> seen;
268 for (
const auto& item : inner) {
269 PushUniqueSchema(one_of, seen, OpenRPCArgSchema(item, include_hidden));
272 if (one_of.size() == 1)
return one_of[0];
275 items.pushKV(
"oneOf", std::move(one_of));
280UniValue DedupArrayItemsSchema(std::span<const RPCResult> inner)
283 if (inner.size() == 1)
return OpenRPCResultSchema(inner.front());
286 std::unordered_set<std::string> seen;
287 for (
const auto& item : inner) {
288 PushUniqueSchema(one_of, seen, OpenRPCResultSchema(item));
291 if (one_of.size() == 1)
return one_of[0];
294 items.pushKV(
"oneOf", std::move(one_of));
302 if (type_label.empty())
return;
304 static const std::unordered_set<std::string> number_or_string{
308 if (number_or_string.contains(type_label)) {
310 one_of.push_back(MakeObject({{
"type",
"number"}}));
311 one_of.push_back(MakeObject({{
"type",
"string"}}));
313 schema.
pushKV(
"oneOf", std::move(one_of));
315 schema.
pushKV(
"x-bitcoin-type-override", type_label);
321 if (
const auto* def = std::get_if<RPCArg::Default>(&arg.
m_fallback)) {
322 schema.
pushKV(
"default", *def);
323 }
else if (
const auto* hint = std::get_if<RPCArg::DefaultHint>(&arg.
m_fallback)) {
324 schema.
pushKV(
"x-bitcoin-default-hint", *hint);
333 ApplyTypeStrOverride(schema, arg);
336 one_of.push_back(MakeObject({{
"type",
"array"}}));
337 one_of.push_back(MakeObject({{
"type",
"object"}}));
338 schema.
pushKV(
"oneOf", std::move(one_of));
340 ApplyArgFallback(schema, arg);
346 schema = MakeObject({{
"type",
"string"}});
349 schema = MakeObject({{
"type",
"string"}, {
"pattern",
"^[0-9a-fA-F]+$"}});
352 schema = MakeObject({{
"type",
"number"}});
355 schema = MakeObject({{
"type",
"boolean"}});
359 one_of.push_back(MakeObject({{
"type",
"number"}}));
360 one_of.push_back(MakeObject({{
"type",
"string"}}));
361 schema.
pushKV(
"oneOf", std::move(one_of));
366 items.push_back(MakeObject({{
"type",
"number"}}));
367 items.push_back(MakeObject({{
"type",
"number"}}));
369 range_schema.pushKV(
"type",
"array");
370 range_schema.pushKV(
"items", std::move(items));
371 range_schema.pushKV(
"additionalItems",
false);
372 range_schema.pushKV(
"minItems", 2);
373 range_schema.pushKV(
"maxItems", 2);
375 one_of.push_back(MakeObject({{
"type",
"number"}}));
376 one_of.push_back(std::move(range_schema));
377 schema.
pushKV(
"oneOf", std::move(one_of));
382 schema.
pushKV(
"type",
"array");
383 schema.
pushKV(
"items", std::move(items));
390 for (
const auto& inner : arg.
m_inner) {
391 if (!include_hidden && inner.m_opts.hidden)
continue;
392 UniValue prop{OpenRPCArgSchema(inner, include_hidden)};
393 if (!inner.m_description.empty()) prop.
pushKV(
"description", inner.m_description);
394 if (inner.m_opts.placeholder) prop.pushKV(
"x-bitcoin-placeholder",
true);
395 if (inner.m_opts.also_positional) prop.pushKV(
"x-bitcoin-also-positional",
true);
396 properties.pushKV(inner.GetFirstName(), std::move(prop));
397 if (!inner.IsOptional()) required.push_back(inner.GetFirstName());
399 schema.
pushKV(
"type",
"object");
400 schema.
pushKV(
"properties", std::move(properties));
401 schema.
pushKV(
"additionalProperties",
false);
402 if (!required.empty()) schema.
pushKV(
"required", std::move(required));
406 schema.
pushKV(
"type",
"object");
408 schema.
pushKV(
"additionalProperties", OpenRPCArgSchema(arg.
m_inner[0], include_hidden));
410 schema.
pushKV(
"additionalProperties",
true);
415 ApplyTypeStrOverride(schema, arg);
416 ApplyArgFallback(schema, arg);
428 if (result.
m_key_name.empty())
return obj_schema;
431 one_of.push_back(std::move(obj_schema));
432 one_of.push_back(MakeObject({{
"const",
false}}));
434 schema.
pushKV(
"oneOf", std::move(one_of));
443 return MakeObject({{
"type",
"string"}});
445 return MakeObject({{
"type",
"number"}, {
"x-bitcoin-unit",
"amount"}});
447 return MakeObject({{
"type",
"string"}, {
"pattern",
"^[0-9a-fA-F]+$"}});
449 return MakeObject({{
"type",
"number"}});
452 schema.
pushKV(
"type",
"number");
453 schema.
pushKV(
"x-bitcoin-unit",
"unix-time");
457 return MakeObject({{
"type",
"boolean"}});
459 return MakeObject({{
"type",
"null"}});
463 schema.
pushKV(
"type",
"array");
464 schema.
pushKV(
"items", std::move(items));
469 for (
const auto& inner : result.
m_inner) {
470 items.push_back(OpenRPCResultSchema(inner));
473 schema.
pushKV(
"type",
"array");
474 schema.
pushKV(
"items", std::move(items));
475 schema.
pushKV(
"additionalItems",
false);
483 for (
const auto& inner : result.
m_inner) {
484 if (inner.m_key_name.empty())
continue;
485 UniValue prop{OpenRPCResultSchema(inner)};
486 if (!inner.m_description.empty()) prop.
pushKV(
"description", inner.m_description);
487 properties.pushKV(inner.m_key_name, std::move(prop));
488 if (!inner.m_optional) required.push_back(inner.m_key_name);
491 schema.
pushKV(
"type",
"object");
492 schema.
pushKV(
"properties", std::move(properties));
493 schema.
pushKV(
"additionalProperties",
false);
494 if (!required.empty()) schema.
pushKV(
"required", std::move(required));
499 schema.
pushKV(
"type",
"object");
501 schema.
pushKV(
"additionalProperties", OpenRPCResultSchema(result.
m_inner[0]));
540 {
RPCResult::Type::BOOL,
"x-bitcoin-placeholder",
true,
"Whether the parameter is retained only for compatibility."},
541 {
RPCResult::Type::BOOL,
"x-bitcoin-also-positional",
true,
"Whether the parameter can also be passed positionally."},
551 {.skip_type_check =
true}};
558 "Returns an OpenRPC document for currently available RPC commands.\n",
569 const bool include_hidden{!request.params[0].
isNull() && request.params[0].get_bool()};
579 "Returns an OpenRPC schema as a description of this service.\n",
621 auto new_end = std::remove(it->second.begin(), it->second.end(), pcmd);
622 if (it->second.end() != new_end) {
623 it->second.erase(new_end, it->second.end());
624 if (it->second.empty()) {
641 static std::once_flag g_rpc_interrupt_flag;
643 std::call_once(g_rpc_interrupt_flag, []() {
652 static std::once_flag g_rpc_stop_flag;
655 std::call_once(g_rpc_stop_flag, [&]() {
675 rpcWarmupStatus = newStatus;
688 fRPCInWarmup =
false;
695 *outStatus = rpcWarmupStatus;
701 const std::vector<std::string> enabled_methods =
gArgs.
GetArgs(
"-deprecatedrpc");
703 return find(enabled_methods.begin(), enabled_methods.end(), method) != enabled_methods.end();
714 }
catch (
const std::exception& e) {
736 std::unordered_map<std::string, const UniValue*> argsIn;
737 for (
size_t i=0; i<
keys.size(); ++i) {
738 auto [
_, inserted] = argsIn.emplace(
keys[i], &
values[i]);
752 int initial_hole_size = 0;
753 const std::string* initial_param =
nullptr;
755 for (
const auto& [argNamePattern, named_only]: argNames) {
756 std::vector<std::string> vargNames =
SplitString(argNamePattern,
'|');
757 auto fr = argsIn.end();
758 for (
const std::string & argName : vargNames) {
759 fr = argsIn.find(argName);
760 if (fr != argsIn.end()) {
769 if (fr != argsIn.end()) {
770 if (options.exists(fr->first)) {
773 options.pushKVEnd(fr->first, *fr->second);
779 if (!options.empty() || fr != argsIn.end()) {
780 for (
int i = 0; i < hole; ++i) {
787 if (!initial_param) initial_param = &argNamePattern;
790 if (
out.params.empty()) initial_hole_size = hole;
796 if (fr != argsIn.end()) {
797 if (!options.empty()) {
800 out.params.push_back(*fr->second);
803 if (!options.empty()) {
804 out.params.push_back(std::move(options));
812 auto positional_args{argsIn.extract(
"args")};
813 if (positional_args && positional_args.mapped()->isArray()) {
814 if (initial_hole_size < (
int)positional_args.mapped()->size() && initial_param) {
819 out.params = *positional_args.mapped();
820 for (
size_t i{
out.params.size()}; i < named_args.size(); ++i) {
821 out.params.push_back(named_args[i]);
825 if (!argsIn.empty()) {
834 for (
const auto&
command : commands) {
870 return command.actor(request, result, last_handler);
874 }
catch (
const std::exception& e) {
881 std::vector<std::string> commandList;
883 for (
const auto& i :
mapCommands) commandList.emplace_back(i.first);
889 std::vector<std::string> method_names;
891 if (cmds.empty())
continue;
893 if ((!include_hidden &&
cmd->category ==
"hidden") || !
cmd->metadata_fn)
continue;
894 method_names.push_back(
name);
896 std::sort(method_names.begin(), method_names.end());
899 for (
const auto& method_name : method_names) {
904 for (
const auto& arg : helpman.GetArgs()) {
909 param.pushKV(
"schema", OpenRPCArgSchema(arg, include_hidden));
912 if (names.size() > 1) {
914 for (
size_t i{1}; i < names.size(); ++i) aliases.push_back(names[i]);
915 param.pushKV(
"x-bitcoin-aliases", std::move(aliases));
920 params.push_back(std::move(param));
924 const auto& results{helpman.GetResults().m_results};
926 result_schema = OpenRPCResultSchema(results[0]);
927 }
else if (results.size() > 1) {
929 for (
const auto& r : results) {
931 UniValue schema{OpenRPCResultSchema(r)};
932 if (!r.m_cond.empty()) schema.
pushKV(
"description", r.m_cond);
933 one_of.push_back(std::move(schema));
935 if (one_of.size() == 1) {
936 result_schema = one_of[0];
937 }
else if (one_of.size() > 1) {
938 result_schema.pushKV(
"oneOf", std::move(one_of));
943 method.pushKV(
"name", method_name);
945 method.pushKV(
"params", std::move(params));
947 result.pushKV(
"name",
"result");
948 result.pushKV(
"schema", std::move(result_schema));
949 method.pushKV(
"result", std::move(result));
950 method.pushKV(
"x-bitcoin-category",
cmd->category);
951 methods.push_back(std::move(method));
954 std::string version{
"v" CLIENT_VERSION_STRING};
955 if (!CLIENT_VERSION_IS_RELEASE) version +=
"-dev";
958 info.pushKV(
"title",
"Bitcoin Core JSON-RPC");
959 info.pushKV(
"version", version);
960 info.pushKV(
"description",
"Autogenerated from Bitcoin Core RPC metadata.");
963 doc.pushKV(
"openrpc",
"1.4.1");
964 doc.pushKV(
"info", std::move(info));
965 doc.pushKV(
"methods", std::move(methods));
#define CHECK_NONFATAL(condition)
Identity function.
#define NONFATAL_UNREACHABLE()
NONFATAL_UNREACHABLE() is a macro that is used to mark unreachable code.
std::vector< std::string > GetArgs(const std::string &strArg) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Return a vector of strings of the given argument.
std::map< std::string, std::vector< const CRPCCommand * > > mapCommands
bool removeCommand(const std::string &name, const CRPCCommand *pcmd)
std::string help(std::string_view name, const JSONRPCRequest &helpreq) const
std::vector< std::string > listCommands() const
Returns a list of registered commands.
UniValue buildOpenRPCDoc(bool include_hidden=false) const
Return a complete OpenRPC 1.4.1 document for registered commands.
UniValue execute(const JSONRPCRequest &request) const
Execute a method.
void appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
UniValue dumpArgMap(const JSONRPCRequest &request) const
Return all named arguments that need to be converted by the client from string to another JSON type.
Different type to mark Mutex at global scope.
JSONRPCVersion m_json_version
enum JSONRPCRequest::Mode mode
std::optional< UniValue > id
auto MaybeArg(std::string_view key) const
Helper to get an optional request argument.
void push_back(UniValue val)
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
const std::vector< UniValue > & getValues() const
const std::vector< std::string > & getKeys() const
void pushKV(std::string key, UniValue val)
SteadyClock::duration GetUptime()
Monotonic uptime (not affected by system time changes).
#define LogDebug(category,...)
BCLog::Logger & LogInstance()
std::vector< std::string > SplitString(std::string_view str, char sep)
std::string TrimString(std::string_view str, std::string_view pattern=" \f\n\r\t\v")
UniValue JSONRPCError(int code, const std::string &message)
UniValue JSONRPCReplyObj(UniValue result, UniValue error, std::optional< UniValue > id, JSONRPCVersion jsonrpc_version)
void DeleteAuthCookie()
Delete RPC authentication cookie from disk.
@ RPC_MISC_ERROR
General application defined errors.
@ RPC_TYPE_ERROR
Unexpected type was passed as parameter.
@ RPC_CLIENT_NOT_CONNECTED
P2P client errors.
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
@ RPC_IN_WARMUP
Client still warming up.
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
static const int64_t values[]
A selection of numbers that do not trigger int64_t overflow when added/subtracted.
bool IsDeprecatedRPCEnabled(const std::string &method)
void SetRPCWarmupFinished()
static bool ExecuteCommands(const std::vector< const CRPCCommand * > &commands, const JSONRPCRequest &request, UniValue &result)
static RPCResult OpenRPCDocResult()
bool RPCIsInWarmup(std::string *outStatus)
static bool ExecuteCommand(const CRPCCommand &command, const JSONRPCRequest &request, UniValue &result, bool last_handler)
static std::atomic< bool > g_rpc_running
static JSONRPCRequest transformNamedArguments(const JSONRPCRequest &in, const std::vector< std::pair< std::string, bool > > &argNames)
Process named arguments into a vector of positional arguments, based on the passed-in specification f...
bool IsRPCRunning()
Query whether RPC is running.
void SetRPCWarmupStarting()
static RPCMethod getrpcinfo()
UniValue JSONRPCExec(const JSONRPCRequest &jreq, bool catch_errors)
static RPCMethod getopenrpcinfo()
static bool fRPCInWarmup GUARDED_BY(g_rpc_warmup_mutex)
static GlobalMutex g_rpc_warmup_mutex
static RPCMethod uptime()
static RPCServerInfo g_rpc_server_info
static RPCMethod rpc_discover()
static const CRPCCommand vRPCCommands[]
void SetRPCWarmupStatus(const std::string &newStatus)
Set the RPC warmup status.
void RpcInterruptionPoint()
Throw JSONRPCError if RPC is not running.
NodeContext & EnsureAnyNodeContext(const std::any &context)
@ RANGE
Special type that is a NUM or [NUM,NUM].
@ OBJ_USER_KEYS
Special type where the user must set the keys e.g. to define multiple addresses; as opposed to e....
@ 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)
@ OBJ_NAMED_PARAMS
Special type that behaves almost exactly like OBJ, defining an options object with a list of pre-defi...
const std::vector< RPCArg > m_inner
Only used for arrays or dicts.
const RPCArgOptions m_opts
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
const std::string m_description
std::string DefaultHint
Hint for default value.
std::string GetFirstName() const
Return the first of all aliases.
@ OMITTED
Optional argument for which the default value is omitted from help text for one of two reasons:
bool hidden
For testing only.
std::vector< std::string > type_str
Should be empty unless it is supposed to override the auto-generated type strings....
bool also_positional
If set allows a named-parameter field in an OBJ_NAMED_PARAM options object to have the same name as a...
bool placeholder
If set, the argument is retained only for compatibility and should generally be omitted.
RPCCommandExecution(const std::string &method)
std::list< RPCCommandExecutionInfo >::iterator it
SteadyClock::time_point start
@ 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.
const std::vector< RPCResult > m_inner
Only used for arrays or dicts.
const RPCResultOptions m_opts
const std::string m_key_name
Only used for dicts.
std::list< RPCCommandExecutionInfo > active_commands GUARDED_BY(mutex)
std::vector< uint16_t > keys
consteval auto _(util::TranslatedLiteral str)
const UniValue NullUniValue
std::string Capitalize(std::string str)
Capitalizes the first character of the given string.
void UninterruptibleSleep(const std::chrono::microseconds &n)
constexpr int64_t TicksSeconds(Duration d)