19#include <boost/signals2/signal.hpp>
26#include <unordered_map>
39static std::map<std::string, std::unique_ptr<RPCTimerBase>>
58 std::list<RPCCommandExecutionInfo>::iterator
it;
63 {method, SteadyClock::now()});
84 std::string commandName = request.
strMethod;
87 auto iter = commandsReadView->find(commandName);
88 if (iter != commandsReadView.end()) {
89 return iter->second.get()->Execute(request);
101 if (command !=
nullptr) {
102 const std::string &commandName = command->GetName();
104 std::make_pair(commandName, std::move(command)));
124 std::string category;
125 std::set<intptr_t> setDone;
126 std::vector<std::pair<std::string, const CRPCCommand *>> vCommands;
130 std::make_pair(entry.second.front()->category + entry.first,
131 entry.second.front()));
133 sort(vCommands.begin(), vCommands.end());
139 for (
const std::pair<std::string, const CRPCCommand *> &command :
142 std::string strMethod = pcmd->
name;
143 if ((strCommand !=
"" || pcmd->
category ==
"hidden") &&
144 strMethod != strCommand) {
151 if (setDone.insert(pcmd->
unique_id).second) {
152 pcmd->
actor(config, jreq, unused_result,
155 }
catch (
const std::exception &e) {
157 std::string strHelp = std::string(e.what());
158 if (strCommand ==
"") {
159 if (strHelp.find(
'\n') != std::string::npos) {
160 strHelp = strHelp.substr(0, strHelp.find(
'\n'));
164 if (!category.empty()) {
168 strRet +=
"== " +
Capitalize(category) +
" ==\n";
171 strRet += strHelp +
"\n";
175 strRet =
strprintf(
"help: unknown command: %s\n", strCommand);
178 strRet = strRet.substr(0, strRet.size() - 1);
185 "List all commands, or get help for a specified command.\n",
188 "The command to get help on"},
197 std::string strCommand;
198 if (jsonRequest.params.size() > 0) {
199 strCommand = jsonRequest.params[0].
get_str();
201 if (strCommand ==
"dump_all_command_conversions") {
212 static const std::string RESULT{PACKAGE_NAME
" stopping"};
218 "\nRequest a graceful shutdown of " PACKAGE_NAME
".",
224 "A string with the content '" + RESULT +
"'"},
231 if (jsonRequest.params[0].isNum()) {
233 jsonRequest.params[0].getInt<
int>()});
243 "Returns the total uptime of the server.\n",
246 "The number of seconds that the server has been running"},
258 "Returns details of the RPC server.\n",
266 "All active commands",
270 "Information about an active command",
273 "The name of the RPC command"},
275 "The running time in microseconds"},
279 "The complete file path to the debug log"},
293 int64_t{Ticks<std::chrono::microseconds>(
294 SteadyClock::now() - info.
start)});
299 result.
pushKV(
"active_commands", active_commands);
303 result.
pushKV(
"logpath", log_path);
315 {
"control",
help, },
316 {
"control",
stop, },
339 auto new_end = std::remove(it->second.begin(), it->second.end(), pcmd);
340 if (it->second.end() != new_end) {
341 it->second.erase(new_end, it->second.end());
355 static std::once_flag g_rpc_interrupt_flag;
358 std::call_once(g_rpc_interrupt_flag, []() {
366 static std::once_flag g_rpc_stop_flag;
370 std::call_once(g_rpc_stop_flag, []() {
390 rpcWarmupStatus = newStatus;
396 fRPCInWarmup =
false;
402 *outStatus = rpcWarmupStatus;
408 const std::string &method) {
409 const std::vector<std::string> enabled_methods =
410 args.
GetArgs(
"-deprecatedrpc");
412 return find(enabled_methods.begin(), enabled_methods.end(), method) !=
413 enabled_methods.end();
425 }
catch (
const UniValue &objError) {
427 }
catch (
const std::exception &e) {
438 for (
size_t i = 0; i < vReq.
size(); i++) {
442 return ret.
write() +
"\n";
451 const std::vector<std::pair<std::string, bool>> &argNames) {
458 std::unordered_map<std::string, const UniValue *> argsIn;
459 for (
size_t i = 0; i < keys.size(); ++i) {
460 auto [
_, inserted] = argsIn.emplace(keys[i], &values[i]);
463 "Parameter " + keys[i] +
464 " specified multiple times");
476 size_t initial_hole_size = 0;
477 const std::string *initial_param =
nullptr;
479 for (
const auto &[argNamePattern, named_only] : argNames) {
480 std::vector<std::string> vargNames =
SplitString(argNamePattern,
'|');
481 auto fr = argsIn.end();
482 for (
const std::string &argName : vargNames) {
483 fr = argsIn.find(argName);
484 if (fr != argsIn.end()) {
493 if (fr != argsIn.end()) {
494 if (options.exists(fr->first)) {
496 "Parameter " + fr->first +
497 " specified multiple times");
499 options.pushKVEnd(fr->first, *fr->second);
505 if (!options.empty() || fr != argsIn.end()) {
506 for (
size_t i = 0; i < hole; ++i) {
513 if (!initial_param) {
514 initial_param = &argNamePattern;
519 initial_hole_size = hole;
526 if (fr != argsIn.end()) {
527 if (!options.empty()) {
529 "Parameter " + fr->first +
530 " conflicts with parameter " +
531 options.getKeys().front());
536 if (!options.empty()) {
545 auto positional_args{argsIn.extract(
"args")};
546 if (positional_args && positional_args.mapped()->isArray()) {
547 if (initial_hole_size < positional_args.mapped()->size() &&
551 "Parameter " + *initial_param +
552 " specified twice both as positional and named argument");
556 out.
params = *positional_args.mapped();
557 for (
size_t i{out.
params.
size()}; i < named_args.size(); ++i) {
562 if (!argsIn.empty()) {
564 "Unknown named parameter " + argsIn.begin()->first);
571 const std::vector<const CRPCCommand *> &commands,
573 for (
const auto &command : commands) {
575 &command == &commands.back())) {
610 return command.
actor(
612 result, last_handler);
614 return command.
actor(config, request, result, last_handler);
618 }
catch (
const std::exception &e) {
624 std::vector<std::string> commandList;
626 commandList.emplace_back(i.first);
640 for (
const auto &values : result.
getValues()) {
668 "No timer handler registered for RPC");
671 deadlineTimers.erase(
name);
674 deadlineTimers.emplace(
675 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)
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)
int RPCSerializationFlags()
Retrieves any serialization flags requested in command line argument.
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.
std::vector< std::string > SplitString(std::string_view str, char sep)
boost::signals2::signal< void()> Started
boost::signals2::signal< void()> Stopped
std::string DefaultHint
Hint for default value.
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.