Branch data Line data Source code
1 : : // Copyright (c) 2010 Satoshi Nakamoto
2 : : // Copyright (c) 2009-2022 The Bitcoin Core developers
3 : : // Distributed under the MIT software license, see the accompanying
4 : : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 : :
6 : : #include <rpc/server.h>
7 : :
8 : : #include <common/args.h>
9 : : #include <common/system.h>
10 : : #include <logging.h>
11 : : #include <node/context.h>
12 : : #include <rpc/server_util.h>
13 : : #include <rpc/util.h>
14 : : #include <sync.h>
15 : : #include <util/signalinterrupt.h>
16 : : #include <util/strencodings.h>
17 : : #include <util/string.h>
18 : : #include <util/time.h>
19 : :
20 : : #include <boost/signals2/signal.hpp>
21 : :
22 : : #include <cassert>
23 : : #include <chrono>
24 : : #include <memory>
25 : : #include <mutex>
26 : : #include <unordered_map>
27 : 2 :
28 : : static GlobalMutex g_rpc_warmup_mutex;
29 : : static std::atomic<bool> g_rpc_running{false};
30 : : static bool fRPCInWarmup GUARDED_BY(g_rpc_warmup_mutex) = true;
31 [ + - ]: 2 : static std::string rpcWarmupStatus GUARDED_BY(g_rpc_warmup_mutex) = "RPC server started";
32 : : /* Timer-creating functions */
33 : : static RPCTimerInterface* timerInterface = nullptr;
34 : : /* Map of name to timer. */
35 : : static GlobalMutex g_deadline_timers_mutex;
36 : 2 : static std::map<std::string, std::unique_ptr<RPCTimerBase> > deadlineTimers GUARDED_BY(g_deadline_timers_mutex);
37 : : static bool ExecuteCommand(const CRPCCommand& command, const JSONRPCRequest& request, UniValue& result, bool last_handler);
38 : :
39 : 0 : struct RPCCommandExecutionInfo
40 : : {
41 : : std::string method;
42 : : SteadyClock::time_point start;
43 : : };
44 : :
45 : 0 : struct RPCServerInfo
46 : : {
47 : : Mutex mutex;
48 : : std::list<RPCCommandExecutionInfo> active_commands GUARDED_BY(mutex);
49 : : };
50 : :
51 : 2 : static RPCServerInfo g_rpc_server_info;
52 : :
53 : : struct RPCCommandExecution
54 : : {
55 : : std::list<RPCCommandExecutionInfo>::iterator it;
56 : 0 : explicit RPCCommandExecution(const std::string& method)
57 : : {
58 : 0 : LOCK(g_rpc_server_info.mutex);
59 [ # # ][ # # ]: 0 : it = g_rpc_server_info.active_commands.insert(g_rpc_server_info.active_commands.end(), {method, SteadyClock::now()});
60 : 0 : }
61 : 0 : ~RPCCommandExecution()
62 : : {
63 [ # # ]: 0 : LOCK(g_rpc_server_info.mutex);
64 : 0 : g_rpc_server_info.active_commands.erase(it);
65 : 0 : }
66 : : };
67 : :
68 : 2 : static struct CRPCSignals
69 : : {
70 : : boost::signals2::signal<void ()> Started;
71 : : boost::signals2::signal<void ()> Stopped;
72 : 2 : } g_rpcSignals;
73 : :
74 : 0 : void RPCServer::OnStarted(std::function<void ()> slot)
75 : : {
76 [ # # ]: 0 : g_rpcSignals.Started.connect(slot);
77 : 0 : }
78 : :
79 : 0 : void RPCServer::OnStopped(std::function<void ()> slot)
80 : : {
81 [ # # ]: 0 : g_rpcSignals.Stopped.connect(slot);
82 : 0 : }
83 : :
84 : 0 : std::string CRPCTable::help(const std::string& strCommand, const JSONRPCRequest& helpreq) const
85 : : {
86 : 0 : std::string strRet;
87 : 0 : std::string category;
88 : 0 : std::set<intptr_t> setDone;
89 : 0 : std::vector<std::pair<std::string, const CRPCCommand*> > vCommands;
90 [ # # ]: 0 : vCommands.reserve(mapCommands.size());
91 : :
92 [ # # ]: 0 : for (const auto& entry : mapCommands)
93 [ # # ][ # # ]: 0 : vCommands.emplace_back(entry.second.front()->category + entry.first, entry.second.front());
94 [ # # ]: 0 : sort(vCommands.begin(), vCommands.end());
95 : :
96 [ # # ]: 0 : JSONRPCRequest jreq = helpreq;
97 : 0 : jreq.mode = JSONRPCRequest::GET_HELP;
98 [ # # ]: 2 : jreq.params = UniValue();
99 : :
100 [ # # ]: 0 : for (const std::pair<std::string, const CRPCCommand*>& command : vCommands)
101 : : {
102 : 0 : const CRPCCommand *pcmd = command.second;
103 [ # # ]: 0 : std::string strMethod = pcmd->name;
104 [ # # ][ # # ]: 0 : if ((strCommand != "" || pcmd->category == "hidden") && strMethod != strCommand)
[ # # ][ # # ]
105 : 0 : continue;
106 [ # # ]: 2 : jreq.strMethod = strMethod;
107 : : try
108 : : {
109 [ # # ]: 0 : UniValue unused_result;
110 [ # # ][ # # ]: 0 : if (setDone.insert(pcmd->unique_id).second)
111 [ # # ]: 0 : pcmd->actor(jreq, unused_result, /*last_handler=*/true);
112 [ # # ]: 0 : }
113 : : catch (const std::exception& e)
114 : : {
115 : : // Help text is returned in an exception
116 [ # # ]: 0 : std::string strHelp = std::string(e.what());
117 [ # # ][ # # ]: 0 : if (strCommand == "")
118 : : {
119 [ # # ]: 0 : if (strHelp.find('\n') != std::string::npos)
120 [ # # ]: 0 : strHelp = strHelp.substr(0, strHelp.find('\n'));
121 : :
122 [ # # ]: 0 : if (category != pcmd->category)
123 : : {
124 [ # # ]: 0 : if (!category.empty())
125 [ # # ]: 0 : strRet += "\n";
126 [ # # ]: 0 : category = pcmd->category;
127 [ # # ][ # # ]: 0 : strRet += "== " + Capitalize(category) + " ==\n";
[ # # ][ # # ]
[ # # ]
128 : 0 : }
129 : 0 : }
130 [ # # ][ # # ]: 0 : strRet += strHelp + "\n";
131 [ # # ][ # # ]: 0 : }
132 [ # # # ]: 0 : }
133 [ # # ][ # # ]: 0 : if (strRet == "")
134 [ # # ]: 0 : strRet = strprintf("help: unknown command: %s\n", strCommand);
135 [ # # ]: 0 : strRet = strRet.substr(0,strRet.size()-1);
136 : 0 : return strRet;
137 [ # # ]: 0 : }
138 : :
139 : 4 : static RPCHelpMan help()
140 : : {
141 [ + - ][ - + ]: 8 : return RPCHelpMan{"help",
[ # # ][ # # ]
142 [ + - ]: 4 : "\nList all commands, or get help for a specified command.\n",
143 [ + - ]: 8 : {
144 [ + - ][ + - ]: 4 : {"command", RPCArg::Type::STR, RPCArg::DefaultHint{"all commands"}, "The command to get help on"},
[ + - ][ + - ]
145 : : },
146 [ + - ]: 16 : {
147 [ + - ][ + - ]: 8 : RPCResult{RPCResult::Type::STR, "", "The help text"},
[ + - ]
148 [ + - ][ + - ]: 4 : RPCResult{RPCResult::Type::ANY, "", ""},
[ + - ]
149 : : },
150 [ + - ][ + - ]: 4 : RPCExamples{""},
151 : 4 : [&](const RPCHelpMan& self, const JSONRPCRequest& jsonRequest) -> UniValue
152 : : {
153 : 0 : std::string strCommand;
154 [ # # ][ # # ]: 0 : if (jsonRequest.params.size() > 0) {
155 [ # # ][ # # ]: 0 : strCommand = jsonRequest.params[0].get_str();
[ # # ]
156 : 0 : }
157 [ # # ]: 0 : if (strCommand == "dump_all_command_conversions") {
158 : : // Used for testing only, undocumented
159 [ # # ]: 0 : return tableRPC.dumpArgMap(jsonRequest);
160 : : }
161 : :
162 [ # # ][ # # ]: 0 : return tableRPC.help(strCommand, jsonRequest);
163 : 0 : },
164 : : };
165 : 0 : }
166 : :
167 : 4 : static RPCHelpMan stop()
168 : : {
169 [ + + ][ - + ]: 4 : static const std::string RESULT{PACKAGE_NAME " stopping"};
[ + - ]
170 [ + - ][ + - ]: 8 : return RPCHelpMan{"stop",
[ # # ]
171 : : // Also accept the hidden 'wait' integer argument (milliseconds)
172 : : // For instance, 'stop 1000' makes the call wait 1 second before returning
173 : : // to the client (intended for testing)
174 [ + - ]: 4 : "\nRequest a graceful shutdown of " PACKAGE_NAME ".",
175 [ + - ]: 8 : {
176 [ + - ][ + - ]: 4 : {"wait", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "how long to wait in ms", RPCArgOptions{.hidden=true}},
[ + - ][ + - ]
[ + - ]
177 : : },
178 [ + - ][ + - ]: 4 : RPCResult{RPCResult::Type::STR, "", "A string with the content '" + RESULT + "'"},
[ + - ][ + - ]
[ + - ]
179 [ + - ][ + - ]: 4 : RPCExamples{""},
180 : 4 : [&](const RPCHelpMan& self, const JSONRPCRequest& jsonRequest) -> UniValue
181 : : {
182 : : // Event loop will exit after current HTTP requests have been handled, so
183 : : // this reply will get back to the client.
184 : 0 : CHECK_NONFATAL((*CHECK_NONFATAL(EnsureAnyNodeContext(jsonRequest.context).shutdown))());
185 [ # # ]: 0 : if (jsonRequest.params[0].isNum()) {
186 : 0 : UninterruptibleSleep(std::chrono::milliseconds{jsonRequest.params[0].getInt<int>()});
187 : 0 : }
188 : 0 : return RESULT;
189 : : },
190 : : };
191 : 0 : }
192 : :
193 : 4 : static RPCHelpMan uptime()
194 : : {
195 [ + - ][ - + ]: 8 : return RPCHelpMan{"uptime",
196 [ + - ]: 4 : "\nReturns the total uptime of the server.\n",
197 : 4 : {},
198 [ + - ][ + - ]: 4 : RPCResult{
199 [ + - ][ + - ]: 4 : RPCResult::Type::NUM, "", "The number of seconds that the server has been running"
200 : : },
201 [ + - ]: 4 : RPCExamples{
202 [ + - ][ + - ]: 4 : HelpExampleCli("uptime", "")
[ + - ]
203 [ + - ][ + - ]: 4 : + HelpExampleRpc("uptime", "")
[ + - ][ + - ]
204 : : },
205 : 4 : [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
206 : : {
207 : 0 : return GetTime() - GetStartupTime();
208 : : }
209 : : };
210 : 0 : }
211 : :
212 : 4 : static RPCHelpMan getrpcinfo()
213 : : {
214 [ + - ][ + - ]: 8 : return RPCHelpMan{"getrpcinfo",
[ # # ][ # # ]
[ # # ]
215 [ + - ]: 4 : "\nReturns details of the RPC server.\n",
216 : 4 : {},
217 [ + - ][ + - ]: 4 : RPCResult{
218 [ + - ][ + - ]: 4 : RPCResult::Type::OBJ, "", "",
219 [ + - ]: 12 : {
220 [ + - ][ + - ]: 8 : {RPCResult::Type::ARR, "active_commands", "All active commands",
[ + - ]
221 [ + - ]: 8 : {
222 [ + - ][ + - ]: 8 : {RPCResult::Type::OBJ, "", "Information about an active command",
[ + - ]
223 [ + - ]: 12 : {
224 [ + - ][ + - ]: 4 : {RPCResult::Type::STR, "method", "The name of the RPC command"},
[ + - ]
225 [ + - ][ + - ]: 4 : {RPCResult::Type::NUM, "duration", "The running time in microseconds"},
[ + - ]
226 : : }},
227 : : }},
228 [ + - ][ + - ]: 4 : {RPCResult::Type::STR, "logpath", "The complete file path to the debug log"},
[ + - ]
229 : : }
230 : : },
231 [ + - ]: 4 : RPCExamples{
232 [ + - ][ + - ]: 4 : HelpExampleCli("getrpcinfo", "")
[ + - ]
233 [ + - ][ + - ]: 4 : + HelpExampleRpc("getrpcinfo", "")},
[ + - ][ + - ]
234 : 4 : [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
235 : : {
236 : 0 : LOCK(g_rpc_server_info.mutex);
237 [ # # ]: 0 : UniValue active_commands(UniValue::VARR);
238 [ # # ]: 0 : for (const RPCCommandExecutionInfo& info : g_rpc_server_info.active_commands) {
239 [ # # ]: 0 : UniValue entry(UniValue::VOBJ);
240 [ # # ][ # # ]: 0 : entry.pushKV("method", info.method);
[ # # ]
241 [ # # ][ # # ]: 0 : entry.pushKV("duration", int64_t{Ticks<std::chrono::microseconds>(SteadyClock::now() - info.start)});
[ # # ][ # # ]
[ # # ]
242 [ # # ][ # # ]: 0 : active_commands.push_back(entry);
243 : 0 : }
244 : :
245 [ # # ]: 0 : UniValue result(UniValue::VOBJ);
246 [ # # ][ # # ]: 0 : result.pushKV("active_commands", active_commands);
[ # # ]
247 : :
248 [ # # ][ # # ]: 0 : const std::string path = LogInstance().m_file_path.utf8string();
249 [ # # ][ # # ]: 0 : UniValue log_path(UniValue::VSTR, path);
250 [ # # ][ # # ]: 0 : result.pushKV("logpath", log_path);
[ # # ]
251 : :
252 : 0 : return result;
253 [ # # ]: 0 : }
254 : : };
255 : 0 : }
256 : :
257 [ # # ]: 10 : static const CRPCCommand vRPCCommands[]{
258 : : /* Overall control/query calls */
259 [ + - ][ + - ]: 2 : {"control", &getrpcinfo},
260 [ + - ][ + - ]: 2 : {"control", &help},
261 [ + - ][ + - ]: 2 : {"control", &stop},
262 [ + - ][ - + ]: 2 : {"control", &uptime},
263 : : };
264 : :
265 : 2 : CRPCTable::CRPCTable()
266 : : {
267 [ + + ]: 10 : for (const auto& c : vRPCCommands) {
268 [ + - ]: 8 : appendCommand(c.name, &c);
269 : : }
270 : 2 : }
271 : :
272 : 8 : void CRPCTable::appendCommand(const std::string& name, const CRPCCommand* pcmd)
273 : : {
274 : 8 : CHECK_NONFATAL(!IsRPCRunning()); // Only add commands before rpc is running
275 : :
276 : 8 : mapCommands[name].push_back(pcmd);
277 : 8 : }
278 : :
279 : 0 : bool CRPCTable::removeCommand(const std::string& name, const CRPCCommand* pcmd)
280 : : {
281 : 0 : auto it = mapCommands.find(name);
282 [ # # ]: 0 : if (it != mapCommands.end()) {
283 : 0 : auto new_end = std::remove(it->second.begin(), it->second.end(), pcmd);
284 [ # # ]: 0 : if (it->second.end() != new_end) {
285 : 0 : it->second.erase(new_end, it->second.end());
286 : 0 : return true;
287 : : }
288 : 0 : }
289 : 0 : return false;
290 : 0 : }
291 : :
292 : 0 : void StartRPC()
293 : : {
294 [ # # ][ # # ]: 0 : LogPrint(BCLog::RPC, "Starting RPC\n");
[ # # ][ # # ]
295 : 0 : g_rpc_running = true;
296 : 0 : g_rpcSignals.Started();
297 : 0 : }
298 : :
299 : 0 : void InterruptRPC()
300 : : {
301 : : static std::once_flag g_rpc_interrupt_flag;
302 : : // This function could be called twice if the GUI has been started with -server=1.
303 : 0 : std::call_once(g_rpc_interrupt_flag, []() {
304 [ # # ][ # # ]: 0 : LogPrint(BCLog::RPC, "Interrupting RPC\n");
[ # # ][ # # ]
305 : : // Interrupt e.g. running longpolls
306 : 0 : g_rpc_running = false;
307 : 0 : });
308 : 0 : }
309 : :
310 : 0 : void StopRPC()
311 : : {
312 : : static std::once_flag g_rpc_stop_flag;
313 : : // This function could be called twice if the GUI has been started with -server=1.
314 [ # # ]: 0 : assert(!g_rpc_running);
315 : 0 : std::call_once(g_rpc_stop_flag, []() {
316 [ # # ][ # # ]: 0 : LogPrint(BCLog::RPC, "Stopping RPC\n");
[ # # ][ # # ]
317 : 0 : WITH_LOCK(g_deadline_timers_mutex, deadlineTimers.clear());
318 : 0 : DeleteAuthCookie();
319 : 0 : g_rpcSignals.Stopped();
320 : 0 : });
321 : 0 : }
322 : :
323 : 8 : bool IsRPCRunning()
324 : : {
325 : 8 : return g_rpc_running;
326 : : }
327 : :
328 : 0 : void RpcInterruptionPoint()
329 : : {
330 [ # # ][ # # ]: 0 : if (!IsRPCRunning()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down");
[ # # ][ # # ]
[ # # ]
331 : 0 : }
332 : :
333 : 0 : void SetRPCWarmupStatus(const std::string& newStatus)
334 : : {
335 : 0 : LOCK(g_rpc_warmup_mutex);
336 [ # # ]: 0 : rpcWarmupStatus = newStatus;
337 : 0 : }
338 : :
339 : 0 : void SetRPCWarmupFinished()
340 : : {
341 : 0 : LOCK(g_rpc_warmup_mutex);
342 [ # # ]: 0 : assert(fRPCInWarmup);
343 : 0 : fRPCInWarmup = false;
344 : 0 : }
345 : :
346 : 0 : bool RPCIsInWarmup(std::string *outStatus)
347 : : {
348 : 0 : LOCK(g_rpc_warmup_mutex);
349 [ # # ]: 0 : if (outStatus)
350 [ # # ]: 0 : *outStatus = rpcWarmupStatus;
351 : 0 : return fRPCInWarmup;
352 : 0 : }
353 : :
354 : 0 : bool IsDeprecatedRPCEnabled(const std::string& method)
355 : : {
356 [ # # ][ # # ]: 0 : const std::vector<std::string> enabled_methods = gArgs.GetArgs("-deprecatedrpc");
357 : :
358 [ # # ]: 0 : return find(enabled_methods.begin(), enabled_methods.end(), method) != enabled_methods.end();
359 : 0 : }
360 : :
361 : 0 : static UniValue JSONRPCExecOne(JSONRPCRequest jreq, const UniValue& req)
362 : : {
363 [ # # ]: 0 : UniValue rpc_result(UniValue::VOBJ);
364 : :
365 : : try {
366 [ # # ]: 0 : jreq.parse(req);
367 : :
368 [ # # ]: 0 : UniValue result = tableRPC.execute(jreq);
369 [ # # ]: 0 : rpc_result = JSONRPCReplyObj(result, NullUniValue, jreq.id);
370 [ # # ][ # # ]: 0 : }
371 : : catch (const UniValue& objError)
372 : : {
373 [ # # ]: 0 : rpc_result = JSONRPCReplyObj(NullUniValue, objError, jreq.id);
374 [ # # ][ # # ]: 0 : }
375 : : catch (const std::exception& e)
376 : : {
377 [ # # ]: 0 : rpc_result = JSONRPCReplyObj(NullUniValue,
378 [ # # ][ # # ]: 0 : JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
379 [ # # ][ # # ]: 0 : }
380 : :
381 : 0 : return rpc_result;
382 [ # # ]: 0 : }
383 : :
384 : 0 : std::string JSONRPCExecBatch(const JSONRPCRequest& jreq, const UniValue& vReq)
385 : : {
386 [ # # ]: 0 : UniValue ret(UniValue::VARR);
387 [ # # ][ # # ]: 0 : for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
388 [ # # ][ # # ]: 0 : ret.push_back(JSONRPCExecOne(jreq, vReq[reqIdx]));
[ # # ][ # # ]
389 : :
390 [ # # ][ # # ]: 0 : return ret.write() + "\n";
391 : 0 : }
392 : :
393 : : /**
394 : : * Process named arguments into a vector of positional arguments, based on the
395 : : * passed-in specification for the RPC call's arguments.
396 : : */
397 : 0 : static inline JSONRPCRequest transformNamedArguments(const JSONRPCRequest& in, const std::vector<std::pair<std::string, bool>>& argNames)
398 : : {
399 : 0 : JSONRPCRequest out = in;
400 [ # # ]: 0 : out.params = UniValue(UniValue::VARR);
401 : : // Build a map of parameters, and remove ones that have been processed, so that we can throw a focused error if
402 : : // there is an unknown one.
403 [ # # ]: 0 : const std::vector<std::string>& keys = in.params.getKeys();
404 [ # # ]: 0 : const std::vector<UniValue>& values = in.params.getValues();
405 : 0 : std::unordered_map<std::string, const UniValue*> argsIn;
406 [ # # ]: 0 : for (size_t i=0; i<keys.size(); ++i) {
407 [ # # ]: 0 : auto [_, inserted] = argsIn.emplace(keys[i], &values[i]);
408 [ # # ]: 0 : if (!inserted) {
409 [ # # ][ # # ]: 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Parameter " + keys[i] + " specified multiple times");
[ # # ][ # # ]
410 : : }
411 : 0 : }
412 : : // Process expected parameters. If any parameters were left unspecified in
413 : : // the request before a parameter that was specified, null values need to be
414 : : // inserted at the unspecified parameter positions, and the "hole" variable
415 : : // below tracks the number of null values that need to be inserted.
416 : : // The "initial_hole_size" variable stores the size of the initial hole,
417 : : // i.e. how many initial positional arguments were left unspecified. This is
418 : : // used after the for-loop to add initial positional arguments from the
419 : : // "args" parameter, if present.
420 : 0 : int hole = 0;
421 : 0 : int initial_hole_size = 0;
422 : 0 : const std::string* initial_param = nullptr;
423 [ # # ]: 0 : UniValue options{UniValue::VOBJ};
424 [ # # ]: 0 : for (const auto& [argNamePattern, named_only]: argNames) {
425 [ # # ]: 0 : std::vector<std::string> vargNames = SplitString(argNamePattern, '|');
426 : 0 : auto fr = argsIn.end();
427 [ # # ]: 0 : for (const std::string & argName : vargNames) {
428 [ # # ]: 0 : fr = argsIn.find(argName);
429 [ # # ]: 0 : if (fr != argsIn.end()) {
430 : 0 : break;
431 : : }
432 : : }
433 : :
434 : : // Handle named-only parameters by pushing them into a temporary options
435 : : // object, and then pushing the accumulated options as the next
436 : : // positional argument.
437 [ # # ]: 0 : if (named_only) {
438 [ # # ]: 0 : if (fr != argsIn.end()) {
439 [ # # ][ # # ]: 0 : if (options.exists(fr->first)) {
440 [ # # ][ # # ]: 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Parameter " + fr->first + " specified multiple times");
[ # # ][ # # ]
441 : : }
442 [ # # ][ # # ]: 0 : options.pushKVEnd(fr->first, *fr->second);
[ # # ]
443 [ # # ]: 0 : argsIn.erase(fr);
444 : 0 : }
445 : 0 : continue;
446 : : }
447 : :
448 [ # # ][ # # ]: 0 : if (!options.empty() || fr != argsIn.end()) {
[ # # ]
449 [ # # ]: 0 : for (int i = 0; i < hole; ++i) {
450 : : // Fill hole between specified parameters with JSON nulls,
451 : : // but not at the end (for backwards compatibility with calls
452 : : // that act based on number of specified parameters).
453 [ # # ][ # # ]: 0 : out.params.push_back(UniValue());
454 : 0 : }
455 : 0 : hole = 0;
456 [ # # ]: 0 : if (!initial_param) initial_param = &argNamePattern;
457 : 0 : } else {
458 : 0 : hole += 1;
459 [ # # ][ # # ]: 0 : if (out.params.empty()) initial_hole_size = hole;
460 : : }
461 : :
462 : : // If named input parameter "fr" is present, push it onto out.params. If
463 : : // options are present, push them onto out.params. If both are present,
464 : : // throw an error.
465 [ # # ]: 0 : if (fr != argsIn.end()) {
466 [ # # ][ # # ]: 0 : if (!options.empty()) {
467 [ # # ][ # # ]: 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Parameter " + fr->first + " conflicts with parameter " + options.getKeys().front());
[ # # ][ # # ]
[ # # ][ # # ]
468 : : }
469 [ # # ][ # # ]: 0 : out.params.push_back(*fr->second);
470 [ # # ]: 0 : argsIn.erase(fr);
471 : 0 : }
472 [ # # ][ # # ]: 0 : if (!options.empty()) {
473 [ # # ]: 0 : out.params.push_back(std::move(options));
474 [ # # ]: 0 : options = UniValue{UniValue::VOBJ};
475 : 0 : }
476 [ # # ]: 0 : }
477 : : // If leftover "args" param was found, use it as a source of positional
478 : : // arguments and add named arguments after. This is a convenience for
479 : : // clients that want to pass a combination of named and positional
480 : : // arguments as described in doc/JSON-RPC-interface.md#parameter-passing
481 [ # # ][ # # ]: 0 : auto positional_args{argsIn.extract("args")};
482 [ # # ][ # # ]: 0 : if (positional_args && positional_args.mapped()->isArray()) {
[ # # ]
483 [ # # ][ # # ]: 0 : if (initial_hole_size < (int)positional_args.mapped()->size() && initial_param) {
484 [ # # ][ # # ]: 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Parameter " + *initial_param + " specified twice both as positional and named argument");
[ # # ][ # # ]
485 : : }
486 : : // Assign positional_args to out.params and append named_args after.
487 : 0 : UniValue named_args{std::move(out.params)};
488 [ # # ]: 0 : out.params = *positional_args.mapped();
489 [ # # ]: 0 : for (size_t i{out.params.size()}; i < named_args.size(); ++i) {
490 [ # # ][ # # ]: 0 : out.params.push_back(named_args[i]);
[ # # ]
491 : 0 : }
492 : 0 : }
493 : : // If there are still arguments in the argsIn map, this is an error.
494 [ # # ]: 0 : if (!argsIn.empty()) {
495 [ # # ][ # # ]: 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Unknown named parameter " + argsIn.begin()->first);
[ # # ]
496 : : }
497 : : // Return request with named arguments transformed to positional arguments
498 : 0 : return out;
499 [ # # ]: 0 : }
500 : :
501 : 0 : static bool ExecuteCommands(const std::vector<const CRPCCommand*>& commands, const JSONRPCRequest& request, UniValue& result)
502 : : {
503 [ # # ]: 0 : for (const auto& command : commands) {
504 [ # # ]: 0 : if (ExecuteCommand(*command, request, result, &command == &commands.back())) {
505 : 0 : return true;
506 : : }
507 : : }
508 : 0 : return false;
509 : 0 : }
510 : :
511 : 0 : UniValue CRPCTable::execute(const JSONRPCRequest &request) const
512 : : {
513 : : // Return immediately if in warmup
514 : : {
515 : 0 : LOCK(g_rpc_warmup_mutex);
516 [ # # ]: 0 : if (fRPCInWarmup)
517 [ # # ]: 0 : throw JSONRPCError(RPC_IN_WARMUP, rpcWarmupStatus);
518 : 0 : }
519 : :
520 : : // Find method
521 : 0 : auto it = mapCommands.find(request.strMethod);
522 [ # # ]: 0 : if (it != mapCommands.end()) {
523 : 0 : UniValue result;
524 [ # # ][ # # ]: 0 : if (ExecuteCommands(it->second, request, result)) {
525 : 0 : return result;
526 : : }
527 [ # # ]: 0 : }
528 [ # # ][ # # ]: 0 : throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
[ # # ]
529 : 0 : }
530 : :
531 : 0 : static bool ExecuteCommand(const CRPCCommand& command, const JSONRPCRequest& request, UniValue& result, bool last_handler)
532 : : {
533 : : try {
534 [ # # ]: 0 : RPCCommandExecution execution(request.strMethod);
535 : : // Execute, convert arguments to array if necessary
536 [ # # ][ # # ]: 0 : if (request.params.isObject()) {
537 [ # # ][ # # ]: 0 : return command.actor(transformNamedArguments(request, command.argNames), result, last_handler);
538 : : } else {
539 [ # # ]: 0 : return command.actor(request, result, last_handler);
540 : : }
541 [ # # ][ # # ]: 0 : } catch (const UniValue::type_error& e) {
542 [ # # ][ # # ]: 0 : throw JSONRPCError(RPC_TYPE_ERROR, e.what());
[ # # ]
543 [ # # ]: 0 : } catch (const std::exception& e) {
544 [ # # ][ # # ]: 0 : throw JSONRPCError(RPC_MISC_ERROR, e.what());
[ # # ]
545 [ # # ]: 0 : }
546 : 0 : }
547 : :
548 : 0 : std::vector<std::string> CRPCTable::listCommands() const
549 : : {
550 : 0 : std::vector<std::string> commandList;
551 [ # # ]: 0 : commandList.reserve(mapCommands.size());
552 [ # # ][ # # ]: 0 : for (const auto& i : mapCommands) commandList.emplace_back(i.first);
553 : 0 : return commandList;
554 [ # # ]: 0 : }
555 : :
556 : 0 : UniValue CRPCTable::dumpArgMap(const JSONRPCRequest& args_request) const
557 : : {
558 : 0 : JSONRPCRequest request = args_request;
559 : 0 : request.mode = JSONRPCRequest::GET_ARGS;
560 : :
561 [ # # ]: 0 : UniValue ret{UniValue::VARR};
562 [ # # ]: 0 : for (const auto& cmd : mapCommands) {
563 [ # # ]: 0 : UniValue result;
564 [ # # ][ # # ]: 0 : if (ExecuteCommands(cmd.second, request, result)) {
565 [ # # ][ # # ]: 0 : for (const auto& values : result.getValues()) {
566 [ # # ][ # # ]: 0 : ret.push_back(values);
567 : : }
568 : 0 : }
569 : 0 : }
570 : 0 : return ret;
571 [ # # ]: 0 : }
572 : :
573 : 0 : void RPCSetTimerInterfaceIfUnset(RPCTimerInterface *iface)
574 : : {
575 [ # # ]: 0 : if (!timerInterface)
576 : 0 : timerInterface = iface;
577 : 0 : }
578 : :
579 : 0 : void RPCSetTimerInterface(RPCTimerInterface *iface)
580 : : {
581 : 0 : timerInterface = iface;
582 : 0 : }
583 : :
584 : 0 : void RPCUnsetTimerInterface(RPCTimerInterface *iface)
585 : : {
586 [ # # ]: 0 : if (timerInterface == iface)
587 : 0 : timerInterface = nullptr;
588 : 0 : }
589 : :
590 : 0 : void RPCRunLater(const std::string& name, std::function<void()> func, int64_t nSeconds)
591 : : {
592 [ # # ]: 0 : if (!timerInterface)
593 [ # # ][ # # ]: 0 : throw JSONRPCError(RPC_INTERNAL_ERROR, "No timer handler registered for RPC");
[ # # ][ # # ]
594 : 0 : LOCK(g_deadline_timers_mutex);
595 [ # # ]: 0 : deadlineTimers.erase(name);
596 [ # # ][ # # ]: 0 : LogPrint(BCLog::RPC, "queue run of timer %s in %i seconds (using %s)\n", name, nSeconds, timerInterface->Name());
[ # # ][ # # ]
[ # # ][ # # ]
597 [ # # ][ # # ]: 0 : deadlineTimers.emplace(name, std::unique_ptr<RPCTimerBase>(timerInterface->NewTimer(func, nSeconds*1000)));
598 : 0 : }
599 : :
600 : 0 : bool RPCSerializationWithoutWitness()
601 : : {
602 [ # # ][ # # ]: 0 : return (gArgs.GetIntArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) == 0);
603 : 0 : }
604 : :
605 : 2 : CRPCTable tableRPC;
|