6#include <bitcoin-build-config.h>
36#include <unordered_map>
37#include <unordered_set>
64 std::list<RPCCommandExecutionInfo>::iterator
it;
81 std::set<intptr_t> setDone;
82 std::vector<std::pair<std::string, const CRPCCommand*> > vCommands;
86 vCommands.emplace_back(entry.second.front()->category + entry.first, entry.second.front());
87 std::ranges::sort(vCommands);
93 for (
const auto& [
_, pcmd] : vCommands) {
94 std::string strMethod = pcmd->name;
95 if ((strCommand !=
"" || pcmd->category ==
"hidden") && strMethod != strCommand)
101 if (setDone.insert(pcmd->unique_id).second)
102 pcmd->actor(jreq, unused_result,
true);
104 std::string strHelp{e.what()};
105 if (strCommand ==
"")
107 if (strHelp.find(
'\n') != std::string::npos)
108 strHelp = strHelp.substr(0, strHelp.find(
'\n'));
110 if (category != pcmd->category)
112 if (!category.empty())
114 category = pcmd->category;
115 strRet +=
"== " +
Capitalize(category) +
" ==\n";
118 strRet += strHelp +
"\n";
122 strRet =
strprintf(
"help: unknown command: %s\n", strCommand);
123 strRet = strRet.substr(0,strRet.size()-1);
131 "List all commands, or get help for a specified command.\n",
146 if (
command ==
"dump_all_command_conversions") {
158 static const std::string RESULT{CLIENT_NAME
" stopping"};
164 "Request a graceful shutdown of " CLIENT_NAME
".",
175 if (jsonRequest.params[0].isNum()) {
187 "Returns the total uptime of the server.\n",
207 "Returns details of the RPC server.\n",
233 entry.
pushKV(
"duration", Ticks<std::chrono::microseconds>(SteadyClock::now() - info.
start));
234 active_commands.
push_back(std::move(entry));
238 result.
pushKV(
"active_commands", std::move(active_commands));
242 result.
pushKV(
"logpath", std::move(log_path));
250UniValue OpenRPCArgSchema(
const RPCArg& arg,
bool include_hidden,
bool in_skip_type_check);
253UniValue MakeObject(std::initializer_list<std::pair<std::string, UniValue>> entries)
256 for (
const auto& [key, value] : entries) {
257 obj.pushKV(key, value);
262void PushUniqueSchema(
UniValue& schemas, std::unordered_set<std::string>& seen,
UniValue schema)
264 const std::string serialized{schema.
write()};
265 if (seen.insert(serialized).second) schemas.
push_back(std::move(schema));
269UniValue DedupArrayItemsSchema(std::span<const RPCArg> inner,
bool include_hidden,
bool in_skip_type_check)
272 if (inner.size() == 1)
return OpenRPCArgSchema(inner.front(), include_hidden, in_skip_type_check);
275 std::unordered_set<std::string> seen;
276 for (
const auto& item : inner) {
277 PushUniqueSchema(one_of, seen, OpenRPCArgSchema(item, include_hidden, in_skip_type_check));
280 if (one_of.size() == 1)
return one_of[0];
283 items.pushKV(in_skip_type_check ?
"anyOf" :
"oneOf", std::move(one_of));
288UniValue DedupArrayItemsSchema(std::span<const RPCResult> inner)
291 if (inner.size() == 1)
return OpenRPCResultSchema(inner.front());
294 std::unordered_set<std::string> seen;
295 for (
const auto& item : inner) {
296 PushUniqueSchema(one_of, seen, OpenRPCResultSchema(item));
299 if (one_of.size() == 1)
return one_of[0];
302 items.pushKV(
"oneOf", std::move(one_of));
310 if (type_label.empty())
return;
312 static const std::unordered_set<std::string> number_or_string{
316 if (number_or_string.contains(type_label)) {
318 one_of.push_back(MakeObject({{
"type",
"integer"}}));
319 one_of.push_back(MakeObject({{
"type",
"string"}}));
321 schema.
pushKV(
"oneOf", std::move(one_of));
323 schema.
pushKV(
"x-bitcoin-type-override", type_label);
338UniValue OpenRPCArgSchema(
const RPCArg& arg,
bool include_hidden,
bool in_skip_type_check)
342 ApplyTypeStrOverride(schema, arg);
345 items.pushKV(
"type",
"array");
346 items.pushKV(
"items", DedupArrayItemsSchema(arg.
m_inner, include_hidden,
true));
349 one_of.push_back(std::move(items));
350 one_of.push_back(MakeObject({{
"type",
"object"}}));
351 schema.
pushKV(
"oneOf", std::move(one_of));
353 ApplyArgFallback(schema, arg);
359 schema = MakeObject({{
"type",
"string"}});
362 schema = MakeObject({{
"type",
"string"}, {
"pattern",
"^[0-9a-fA-F]+$"}});
365 schema = MakeObject({{
"type",
"number"}});
368 schema = MakeObject({{
"type",
"boolean"}});
372 one_of.push_back(MakeObject({{
"type",
"number"}}));
373 one_of.push_back(MakeObject({{
"type",
"string"}}));
374 schema.
pushKV(
"oneOf", std::move(one_of));
379 items.push_back(MakeObject({{
"type",
"number"}}));
380 items.push_back(MakeObject({{
"type",
"number"}}));
382 range_schema.pushKV(
"type",
"array");
383 range_schema.pushKV(
"items", std::move(items));
384 range_schema.pushKV(
"additionalItems",
false);
385 range_schema.pushKV(
"minItems", 2);
386 range_schema.pushKV(
"maxItems", 2);
388 one_of.push_back(MakeObject({{
"type",
"number"}}));
389 one_of.push_back(std::move(range_schema));
390 schema.
pushKV(
"oneOf", std::move(one_of));
394 UniValue items{DedupArrayItemsSchema(arg.
m_inner, include_hidden, in_skip_type_check)};
395 schema.
pushKV(
"type",
"array");
396 schema.
pushKV(
"items", std::move(items));
403 for (
const auto& inner : arg.
m_inner) {
404 if (!include_hidden && inner.m_opts.hidden)
continue;
405 UniValue prop{OpenRPCArgSchema(inner, include_hidden, in_skip_type_check)};
406 if (!inner.m_description.empty()) prop.
pushKV(
"description", inner.m_description);
407 if (inner.m_opts.placeholder) prop.pushKV(
"x-bitcoin-placeholder",
true);
408 if (inner.m_opts.also_positional) prop.pushKV(
"x-bitcoin-also-positional",
true);
409 properties.pushKV(inner.GetFirstName(), std::move(prop));
410 if (!inner.IsOptional()) required.push_back(inner.GetFirstName());
412 schema.
pushKV(
"type",
"object");
413 schema.
pushKV(
"properties", std::move(properties));
414 schema.
pushKV(
"additionalProperties",
false);
415 if (!required.empty()) schema.
pushKV(
"required", std::move(required));
419 schema.
pushKV(
"type",
"object");
421 schema.
pushKV(
"additionalProperties", OpenRPCArgSchema(arg.
m_inner[0], include_hidden, in_skip_type_check));
422 if (!arg.
m_inner[0].m_description.empty()) {
426 schema.
pushKV(
"additionalProperties",
true);
431 ApplyTypeStrOverride(schema, arg);
432 ApplyArgFallback(schema, arg);
444 if (result.
m_key_name.empty())
return obj_schema;
447 one_of.push_back(std::move(obj_schema));
448 one_of.push_back(MakeObject({{
"const",
false}}));
450 schema.
pushKV(
"oneOf", std::move(one_of));
459 return MakeObject({{
"type",
"string"}});
461 return MakeObject({{
"type",
"number"}, {
"x-bitcoin-unit",
"amount"}});
463 return MakeObject({{
"type",
"string"}, {
"pattern",
"^[0-9a-fA-F]+$"}});
465 return MakeObject({{
"type",
"number"}});
468 schema.
pushKV(
"type",
"number");
469 schema.
pushKV(
"x-bitcoin-unit",
"unix-time");
473 return MakeObject({{
"type",
"boolean"}});
475 return MakeObject({{
"type",
"null"}});
479 schema.
pushKV(
"type",
"array");
480 schema.
pushKV(
"items", std::move(items));
485 for (
const auto& inner : result.
m_inner) {
486 items.push_back(OpenRPCResultSchema(inner));
489 schema.
pushKV(
"type",
"array");
490 schema.
pushKV(
"items", std::move(items));
491 schema.
pushKV(
"additionalItems",
false);
499 for (
const auto& inner : result.
m_inner) {
500 if (inner.m_key_name.empty())
continue;
501 UniValue prop{OpenRPCResultSchema(inner)};
502 if (!inner.m_description.empty()) prop.
pushKV(
"description", inner.m_description);
503 properties.pushKV(inner.m_key_name, std::move(prop));
504 if (!inner.m_optional) required.push_back(inner.m_key_name);
507 schema.
pushKV(
"type",
"object");
508 schema.
pushKV(
"properties", std::move(properties));
509 schema.
pushKV(
"additionalProperties",
false);
510 if (!required.empty()) schema.
pushKV(
"required", std::move(required));
515 schema.
pushKV(
"type",
"object");
517 schema.
pushKV(
"additionalProperties", OpenRPCResultSchema(result.
m_inner[0]));
556 {
RPCResult::Type::BOOL,
"x-bitcoin-placeholder",
true,
"Whether the parameter is retained only for compatibility."},
557 {
RPCResult::Type::BOOL,
"x-bitcoin-also-positional",
true,
"Whether the parameter can also be passed positionally."},
563 "\"x-bitcoin-unit\" property: \"amount\" which denotes a Bitcoin amount in BTC."},
568 {.skip_type_check =
true}};
575 "Returns an OpenRPC document for currently available RPC commands.\n",
586 const bool include_hidden{self.
Arg<
bool>(
"show_hidden")};
596 "Returns an OpenRPC schema as a description of this service.\n",
638 auto new_end = std::remove(it->second.begin(), it->second.end(), pcmd);
639 if (it->second.end() != new_end) {
640 it->second.erase(new_end, it->second.end());
641 if (it->second.empty()) {
658 static std::once_flag g_rpc_interrupt_flag;
660 std::call_once(g_rpc_interrupt_flag, []() {
669 static std::once_flag g_rpc_stop_flag;
672 std::call_once(g_rpc_stop_flag, [&]() {
692 rpcWarmupStatus = newStatus;
705 fRPCInWarmup =
false;
712 *outStatus = rpcWarmupStatus;
718 const std::vector<std::string> enabled_methods =
gArgs.
GetArgs(
"-deprecatedrpc");
720 return find(enabled_methods.begin(), enabled_methods.end(), method) != enabled_methods.end();
731 }
catch (
const std::exception& e) {
753 std::unordered_map<std::string, const UniValue*> argsIn;
754 for (
size_t i=0; i<
keys.size(); ++i) {
755 auto [
_, inserted] = argsIn.emplace(
keys[i], &
values[i]);
769 int initial_hole_size = 0;
770 const std::string* initial_param =
nullptr;
772 for (
const auto& [argNamePattern, named_only]: argNames) {
773 std::vector<std::string> vargNames =
SplitString(argNamePattern,
'|');
774 auto fr = argsIn.end();
775 for (
const std::string & argName : vargNames) {
776 fr = argsIn.find(argName);
777 if (fr != argsIn.end()) {
786 if (fr != argsIn.end()) {
787 if (options.exists(fr->first)) {
790 options.pushKVEnd(fr->first, *fr->second);
796 if (!options.empty() || fr != argsIn.end()) {
797 for (
int i = 0; i < hole; ++i) {
804 if (!initial_param) initial_param = &argNamePattern;
807 if (
out.params.empty()) initial_hole_size = hole;
813 if (fr != argsIn.end()) {
814 if (!options.empty()) {
817 out.params.push_back(*fr->second);
820 if (!options.empty()) {
821 out.params.push_back(std::move(options));
829 auto positional_args{argsIn.extract(
"args")};
830 if (positional_args && positional_args.mapped()->isArray()) {
831 if (initial_hole_size < (
int)positional_args.mapped()->size() && initial_param) {
836 out.params = *positional_args.mapped();
837 for (
size_t i{
out.params.size()}; i < named_args.size(); ++i) {
838 out.params.push_back(named_args[i]);
842 if (!argsIn.empty()) {
851 for (
const auto&
command : commands) {
887 return command.actor(request, result, last_handler);
891 }
catch (
const std::exception& e) {
898 std::vector<std::string> commandList;
900 for (
const auto& i :
mapCommands) commandList.emplace_back(i.first);
906 std::vector<std::string> method_names;
908 if (cmds.empty())
continue;
910 if ((!include_hidden &&
cmd->category ==
"hidden") || !
cmd->metadata_fn)
continue;
911 method_names.push_back(
name);
913 std::sort(method_names.begin(), method_names.end());
916 for (
const auto& method_name : method_names) {
921 for (
const auto& arg : helpman.GetArgs()) {
926 param.pushKV(
"schema", OpenRPCArgSchema(arg, include_hidden,
false));
929 if (names.size() > 1) {
931 for (
size_t i{1}; i < names.size(); ++i) aliases.push_back(names[i]);
932 param.pushKV(
"x-bitcoin-aliases", std::move(aliases));
937 params.push_back(std::move(param));
941 const auto& results{helpman.GetResults().m_results};
943 result_schema = OpenRPCResultSchema(results[0]);
944 }
else if (results.size() > 1) {
946 for (
const auto& r : results) {
948 UniValue schema{OpenRPCResultSchema(r)};
949 if (!r.m_cond.empty()) schema.
pushKV(
"description", r.m_cond);
950 one_of.push_back(std::move(schema));
952 if (one_of.size() == 1) {
953 result_schema = one_of[0];
954 }
else if (one_of.size() > 1) {
955 result_schema.pushKV(
"oneOf", std::move(one_of));
960 method.pushKV(
"name", method_name);
962 method.pushKV(
"params", std::move(params));
964 result.pushKV(
"name",
"result");
965 result.pushKV(
"schema", std::move(result_schema));
966 method.pushKV(
"result", std::move(result));
967 method.pushKV(
"x-bitcoin-category",
cmd->category);
968 methods.push_back(std::move(method));
971 std::string version{
"v" CLIENT_VERSION_STRING};
972 if (!CLIENT_VERSION_IS_RELEASE) version +=
"-dev";
975 info.pushKV(
"title", CLIENT_NAME
" JSON-RPC");
976 info.pushKV(
"version", version);
977 info.pushKV(
"description",
"Autogenerated from " CLIENT_NAME
" RPC metadata.");
980 doc.pushKV(
"openrpc",
"1.4.1");
981 doc.pushKV(
"info", std::move(info));
982 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.
auto Arg(std::string_view key) const
Helper to get a required or default-valued 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.
@ 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.
HelpElision print_elision
std::list< RPCCommandExecutionInfo > active_commands GUARDED_BY(mutex)
Overloaded helper for std::visit.
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)