19#include <boost/signals2/signal.hpp>
26#include <unordered_map>
41static std::map<std::string, std::unique_ptr<RPCTimerBase>>
60 std::list<RPCCommandExecutionInfo>::iterator
it;
65 {method, SteadyClock::now()});
86 std::string commandName = request.
strMethod;
89 auto iter = commandsReadView->find(commandName);
90 if (iter != commandsReadView.end()) {
91 return iter->second.get()->Execute(request);
103 if (command !=
nullptr) {
104 const std::string &commandName = command->GetName();
106 std::make_pair(commandName, std::move(command)));
126 std::string category;
127 std::set<intptr_t> setDone;
128 std::vector<std::pair<std::string, const CRPCCommand *>> vCommands;
133 std::make_pair(entry.second.front()->category + entry.first,
134 entry.second.front()));
136 sort(vCommands.begin(), vCommands.end());
142 for (
const std::pair<std::string, const CRPCCommand *> &command :
145 std::string strMethod = pcmd->
name;
146 if ((strCommand !=
"" || pcmd->
category ==
"hidden") &&
147 strMethod != strCommand) {
154 if (setDone.insert(pcmd->
unique_id).second) {
155 pcmd->
actor(config, jreq, unused_result,
158 }
catch (
const std::exception &e) {
160 std::string strHelp = std::string(e.what());
161 if (strCommand ==
"") {
162 if (strHelp.find(
'\n') != std::string::npos) {
163 strHelp = strHelp.substr(0, strHelp.find(
'\n'));
167 if (!category.empty()) {
171 strRet +=
"== " +
Capitalize(category) +
" ==\n";
174 strRet += strHelp +
"\n";
178 strRet =
strprintf(
"help: unknown command: %s\n", strCommand);
181 strRet = strRet.substr(0, strRet.size() - 1);
188 "List all commands, or get help for a specified command.\n",
191 "The command to get help on"},
200 std::string strCommand;
201 if (jsonRequest.params.size() > 0) {
202 strCommand = jsonRequest.params[0].
get_str();
204 if (strCommand ==
"dump_all_command_conversions") {
215 static const std::string RESULT{PACKAGE_NAME
" stopping"};
221 "\nRequest a graceful shutdown of " PACKAGE_NAME
".",
227 "A string with the content '" + RESULT +
"'"},
234 if (jsonRequest.params[0].isNum()) {
236 jsonRequest.params[0].getInt<
int>()});
246 "Returns the total uptime of the server.\n",
249 "The number of seconds that the server has been running"},
261 "Returns details of the RPC server.\n",
269 "All active commands",
273 "Information about an active command",
276 "The name of the RPC command"},
278 "The running time in microseconds"},
282 "The complete file path to the debug log"},
296 int64_t{Ticks<std::chrono::microseconds>(
297 SteadyClock::now() - info.
start)});
298 active_commands.
push_back(std::move(entry));
302 result.
pushKV(
"active_commands", std::move(active_commands));
306 result.
pushKV(
"logpath", std::move(log_path));
318 {
"control",
help, },
319 {
"control",
stop, },
342 auto new_end = std::remove(it->second.begin(), it->second.end(), pcmd);
343 if (it->second.end() != new_end) {
344 it->second.erase(new_end, it->second.end());
358 static std::once_flag g_rpc_interrupt_flag;
361 std::call_once(g_rpc_interrupt_flag, []() {
369 static std::once_flag g_rpc_stop_flag;
373 std::call_once(g_rpc_stop_flag, []() {
393 rpcWarmupStatus = newStatus;
399 fRPCInWarmup =
false;
405 *outStatus = rpcWarmupStatus;
411 const std::string &method) {
412 const std::vector<std::string> enabled_methods =
413 args.
GetArgs(
"-deprecatedrpc");
415 return find(enabled_methods.begin(), enabled_methods.end(), method) !=
416 enabled_methods.end();
428 }
catch (
const UniValue &objError) {
430 }
catch (
const std::exception &e) {
441 for (
size_t i = 0; i < vReq.
size(); i++) {
445 return ret.
write() +
"\n";
454 const std::vector<std::pair<std::string, bool>> &argNames) {
461 std::unordered_map<std::string, const UniValue *> argsIn;
462 for (
size_t i = 0; i < keys.size(); ++i) {
463 auto [
_, inserted] = argsIn.emplace(keys[i], &values[i]);
466 "Parameter " + keys[i] +
467 " specified multiple times");
479 size_t initial_hole_size = 0;
480 const std::string *initial_param =
nullptr;
482 for (
const auto &[argNamePattern, named_only] : argNames) {
483 std::vector<std::string> vargNames =
SplitString(argNamePattern,
'|');
484 auto fr = argsIn.end();
485 for (
const std::string &argName : vargNames) {
486 fr = argsIn.find(argName);
487 if (fr != argsIn.end()) {
496 if (fr != argsIn.end()) {
497 if (options.exists(fr->first)) {
499 "Parameter " + fr->first +
500 " specified multiple times");
502 options.pushKVEnd(fr->first, *fr->second);
508 if (!options.empty() || fr != argsIn.end()) {
509 for (
size_t i = 0; i < hole; ++i) {
516 if (!initial_param) {
517 initial_param = &argNamePattern;
522 initial_hole_size = hole;
529 if (fr != argsIn.end()) {
530 if (!options.empty()) {
532 "Parameter " + fr->first +
533 " conflicts with parameter " +
534 options.getKeys().front());
539 if (!options.empty()) {
548 auto positional_args{argsIn.extract(
"args")};
549 if (positional_args && positional_args.mapped()->isArray()) {
550 if (initial_hole_size < positional_args.mapped()->size() &&
554 "Parameter " + *initial_param +
555 " specified twice both as positional and named argument");
559 out.
params = *positional_args.mapped();
560 for (
size_t i{out.
params.
size()}; i < named_args.size(); ++i) {
565 if (!argsIn.empty()) {
567 "Unknown named parameter " + argsIn.begin()->first);
574 const std::vector<const CRPCCommand *> &commands,
576 for (
const auto &command : commands) {
578 &command == &commands.back())) {
613 return command.
actor(
615 result, last_handler);
617 return command.
actor(config, request, result, last_handler);
621 }
catch (
const std::exception &e) {
627 std::vector<std::string> commandList;
630 commandList.emplace_back(i.first);
644 for (
const auto &values : result.
getValues()) {
672 "No timer handler registered for RPC");
675 deadlineTimers.erase(
name);
678 deadlineTimers.emplace(
679 name, std::unique_ptr<RPCTimerBase>(
#define CHECK_NONFATAL(condition)
Identity function.
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
std::vector< std::pair< std::string, bool > > argNames
List of method arguments and whether they are named-only.
std::map< std::string, std::vector< const CRPCCommand * > > mapCommands
bool removeCommand(const std::string &name, const CRPCCommand *pcmd)
std::string help(const Config &config, const std::string &name, const JSONRPCRequest &helpreq) const
std::vector< std::string > listCommands() const
Returns a list of registered commands.
UniValue execute(const Config &config, 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 Config &config, 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.
enum JSONRPCRequest::Mode mode
void parse(const UniValue &valRequest)
Class for registering and managing all RPC calls.
UniValue ExecuteCommand(const Config &config, const JSONRPCRequest &request) const
Attempts to execute an RPC command from the given request.
RWCollection< RPCCommandMap > commands
void RegisterCommand(std::unique_ptr< RPCCommand > command)
Register an RPC command.
virtual RPCTimerBase * NewTimer(std::function< void()> &func, int64_t millis)=0
Factory function for timers.
virtual const char * Name()=0
Implementation name.
ReadView getReadView() const
void push_back(UniValue val)
const std::string & get_str() const
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)
std::string u8string() const
BCLog::Logger & LogInstance()
#define LogPrint(category,...)
void OnStarted(std::function< void()> slot)
void OnStopped(std::function< void()> slot)
std::vector< std::string > SplitString(std::string_view str, char sep)
UniValue JSONRPCError(int code, const std::string &message)
void DeleteAuthCookie()
Delete RPC authentication cookie from disk.
UniValue JSONRPCReplyObj(const UniValue &result, const UniValue &error, const UniValue &id)
@ RPC_MISC_ERROR
General application defined errors std::exception thrown in command handling.
@ RPC_TYPE_ERROR
Unexpected type was passed as parameter.
@ RPC_CLIENT_NOT_CONNECTED
P2P client errors Bitcoin is not connected.
@ 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)
void RPCSetTimerInterfaceIfUnset(RPCTimerInterface *iface)
Set the factory function for timer, but only, if unset.
void SetRPCWarmupFinished()
Mark warmup as done.
bool IsDeprecatedRPCEnabled(const ArgsManager &args, const std::string &method)
static RPCHelpMan uptime()
std::chrono::steady_clock SteadyClock
void RPCUnsetTimerInterface(RPCTimerInterface *iface)
Unset factory function for timers.
static RPCHelpMan getrpcinfo()
void RPCRunLater(const std::string &name, std::function< void()> func, int64_t nSeconds)
Run func nSeconds from now.
bool RPCIsInWarmup(std::string *outStatus)
Returns the current warmup state.
static UniValue JSONRPCExecOne(const Config &config, RPCServer &rpcServer, JSONRPCRequest jreq, const UniValue &req)
static RPCTimerInterface * timerInterface
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...
static GlobalMutex g_deadline_timers_mutex
bool IsRPCRunning()
Query whether RPC is running.
static bool ExecuteCommands(const Config &config, const std::vector< const CRPCCommand * > &commands, const JSONRPCRequest &request, UniValue &result)
static struct CRPCSignals g_rpcSignals
static bool fRPCInWarmup GUARDED_BY(g_rpc_warmup_mutex)
static GlobalMutex g_rpc_warmup_mutex
static bool ExecuteCommand(const Config &config, const CRPCCommand &command, const JSONRPCRequest &request, UniValue &result, bool last_handler)
static RPCServerInfo g_rpc_server_info
static const CRPCCommand vRPCCommands[]
std::string JSONRPCExecBatch(const Config &config, RPCServer &rpcServer, const JSONRPCRequest &jreq, const UniValue &vReq)
void SetRPCWarmupStatus(const std::string &newStatus)
Set the RPC warmup status.
void RPCSetTimerInterface(RPCTimerInterface *iface)
Set the factory function for timers.
void RpcInterruptionPoint()
Throw JSONRPCError if RPC is not running.
void StartShutdown()
Request shutdown of the application.
boost::signals2::signal< void()> Started
boost::signals2::signal< void()> Stopped
std::string DefaultHint
Hint for default value.
@ OMITTED
Optional argument for which the default value is omitted from help text for one of two reasons:
bool hidden
For testing only.
RPCCommandExecution(const std::string &method)
std::list< RPCCommandExecutionInfo >::iterator it
SteadyClock::time_point start
@ ANY
Special type to disable type checks (for testing only)
std::list< RPCCommandExecutionInfo > active_commands GUARDED_BY(mutex)
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
void UninterruptibleSleep(const std::chrono::microseconds &n)
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
bilingual_str _(const char *psz)
Translation function.
const UniValue NullUniValue
std::string Capitalize(std::string str)
Capitalizes the first character of the given string.