Bitcoin Core 31.99.0
P2P Digital Currency
server.cpp
Go to the documentation of this file.
1// Copyright (c) 2010 Satoshi Nakamoto
2// Copyright (c) 2009-present 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 <bitcoin-build-config.h> // IWYU pragma: keep
7
8#include <rpc/server.h>
9
10#include <common/args.h>
11#include <common/system.h>
12#include <logging.h>
13#include <node/context.h>
15#include <rpc/server_util.h>
16#include <rpc/util.h>
17#include <sync.h>
19#include <util/strencodings.h>
20#include <util/string.h>
21#include <util/time.h>
22#include <validation.h>
23
24#include <algorithm>
25#include <cassert>
26#include <chrono>
27#include <memory>
28#include <mutex>
29#include <span>
30#include <string_view>
31#include <unordered_set>
32#include <unordered_map>
33#include <variant>
34
36
38static std::atomic<bool> g_rpc_running{false};
39static bool fRPCInWarmup GUARDED_BY(g_rpc_warmup_mutex) = true;
40static std::string rpcWarmupStatus GUARDED_BY(g_rpc_warmup_mutex) = "RPC server started";
41static bool ExecuteCommand(const CRPCCommand& command, const JSONRPCRequest& request, UniValue& result, bool last_handler);
42
44{
45 std::string method;
46 SteadyClock::time_point start;
47};
48
50{
52 std::list<RPCCommandExecutionInfo> active_commands GUARDED_BY(mutex);
53};
54
56
58{
59 std::list<RPCCommandExecutionInfo>::iterator it;
60 explicit RPCCommandExecution(const std::string& method)
61 {
63 it = g_rpc_server_info.active_commands.insert(g_rpc_server_info.active_commands.end(), {method, SteadyClock::now()});
64 }
66 {
68 g_rpc_server_info.active_commands.erase(it);
69 }
70};
71
72std::string CRPCTable::help(std::string_view strCommand, const JSONRPCRequest& helpreq) const
73{
74 std::string strRet;
75 std::string category;
76 std::set<intptr_t> setDone;
77 std::vector<std::pair<std::string, const CRPCCommand*> > vCommands;
78 vCommands.reserve(mapCommands.size());
79
80 for (const auto& entry : mapCommands)
81 vCommands.emplace_back(entry.second.front()->category + entry.first, entry.second.front());
82 std::ranges::sort(vCommands);
83
84 JSONRPCRequest jreq = helpreq;
86 jreq.params = UniValue();
87
88 for (const auto& [_, pcmd] : vCommands) {
89 std::string strMethod = pcmd->name;
90 if ((strCommand != "" || pcmd->category == "hidden") && strMethod != strCommand)
91 continue;
92 jreq.strMethod = strMethod;
93 try
94 {
95 UniValue unused_result;
96 if (setDone.insert(pcmd->unique_id).second)
97 pcmd->actor(jreq, unused_result, /*last_handler=*/true);
98 } catch (const HelpResult& e) {
99 std::string strHelp{e.what()};
100 if (strCommand == "")
101 {
102 if (strHelp.find('\n') != std::string::npos)
103 strHelp = strHelp.substr(0, strHelp.find('\n'));
104
105 if (category != pcmd->category)
106 {
107 if (!category.empty())
108 strRet += "\n";
109 category = pcmd->category;
110 strRet += "== " + Capitalize(category) + " ==\n";
111 }
112 }
113 strRet += strHelp + "\n";
114 }
115 }
116 if (strRet == "")
117 strRet = strprintf("help: unknown command: %s\n", strCommand);
118 strRet = strRet.substr(0,strRet.size()-1);
119 return strRet;
120}
121
123{
124 return RPCMethod{
125 "help",
126 "List all commands, or get help for a specified command.\n",
127 {
128 {"command", RPCArg::Type::STR, RPCArg::DefaultHint{"all commands"}, "The command to get help on"},
129 },
130 {
131 RPCResult{RPCResult::Type::STR, "", "The help text"},
133 },
134 RPCExamples{""},
135 [](const RPCMethod& self, const JSONRPCRequest& jsonRequest) -> UniValue
136{
137 auto command{self.MaybeArg<std::string_view>("command")};
138 if (command == "dump_all_command_conversions") {
139 // Used for testing only, undocumented
140 return tableRPC.dumpArgMap(jsonRequest);
141 }
142
143 return tableRPC.help(command.value_or(""), jsonRequest);
144},
145 };
146}
147
149{
150 static const std::string RESULT{CLIENT_NAME " stopping"};
151 return RPCMethod{
152 "stop",
153 // Also accept the hidden 'wait' integer argument (milliseconds)
154 // For instance, 'stop 1000' makes the call wait 1 second before returning
155 // to the client (intended for testing)
156 "Request a graceful shutdown of " CLIENT_NAME ".",
157 {
158 {"wait", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "how long to wait in ms", RPCArgOptions{.hidden=true}},
159 },
160 RPCResult{RPCResult::Type::STR, "", "A string with the content '" + RESULT + "'"},
161 RPCExamples{""},
162 [](const RPCMethod& self, const JSONRPCRequest& jsonRequest) -> UniValue
163{
164 // Event loop will exit after current HTTP requests have been handled, so
165 // this reply will get back to the client.
166 CHECK_NONFATAL((CHECK_NONFATAL(EnsureAnyNodeContext(jsonRequest.context).shutdown_request))());
167 if (jsonRequest.params[0].isNum()) {
168 UninterruptibleSleep(std::chrono::milliseconds{jsonRequest.params[0].getInt<int>()});
169 }
170 return RESULT;
171},
172 };
173}
174
176{
177 return RPCMethod{
178 "uptime",
179 "Returns the total uptime of the server.\n",
180 {},
181 RPCResult{
182 RPCResult::Type::NUM, "", "The number of seconds that the server has been running"
183 },
185 HelpExampleCli("uptime", "")
186 + HelpExampleRpc("uptime", "")
187 },
188 [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
189{
190 return TicksSeconds(GetUptime());
191}
192 };
193}
194
196{
197 return RPCMethod{
198 "getrpcinfo",
199 "Returns details of the RPC server.\n",
200 {},
201 RPCResult{
202 RPCResult::Type::OBJ, "", "",
203 {
204 {RPCResult::Type::ARR, "active_commands", "All active commands",
205 {
206 {RPCResult::Type::OBJ, "", "Information about an active command",
207 {
208 {RPCResult::Type::STR, "method", "The name of the RPC command"},
209 {RPCResult::Type::NUM, "duration", "The running time in microseconds"},
210 }},
211 }},
212 {RPCResult::Type::STR, "logpath", "The complete file path to the debug log"},
213 }
214 },
216 HelpExampleCli("getrpcinfo", "")
217 + HelpExampleRpc("getrpcinfo", "")},
218 [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
219{
221 UniValue active_commands(UniValue::VARR);
222 for (const RPCCommandExecutionInfo& info : g_rpc_server_info.active_commands) {
224 entry.pushKV("method", info.method);
225 entry.pushKV("duration", Ticks<std::chrono::microseconds>(SteadyClock::now() - info.start));
226 active_commands.push_back(std::move(entry));
227 }
228
229 UniValue result(UniValue::VOBJ);
230 result.pushKV("active_commands", std::move(active_commands));
231
232 const std::string path = LogInstance().m_file_path.utf8string();
233 UniValue log_path(UniValue::VSTR, path);
234 result.pushKV("logpath", std::move(log_path));
235
236 return result;
237}
238 };
239}
240
241namespace {
242UniValue OpenRPCArgSchema(const RPCArg& arg, bool include_hidden);
243UniValue OpenRPCResultSchema(const RPCResult& result);
244
245UniValue MakeObject(std::initializer_list<std::pair<std::string, UniValue>> entries)
246{
248 for (const auto& [key, value] : entries) {
249 obj.pushKV(key, value);
250 }
251 return obj;
252}
253
254void PushUniqueSchema(UniValue& schemas, std::unordered_set<std::string>& seen, UniValue schema)
255{
256 const std::string serialized{schema.write()};
257 if (seen.insert(serialized).second) schemas.push_back(std::move(schema));
258}
259
260// NOLINTNEXTLINE(misc-no-recursion)
261UniValue DedupArrayItemsSchema(std::span<const RPCArg> inner, bool include_hidden)
262{
263 if (inner.empty()) return UniValue{UniValue::VOBJ};
264 if (inner.size() == 1) return OpenRPCArgSchema(inner.front(), include_hidden);
265
266 UniValue one_of{UniValue::VARR};
267 std::unordered_set<std::string> seen;
268 for (const auto& item : inner) {
269 PushUniqueSchema(one_of, seen, OpenRPCArgSchema(item, include_hidden));
270 }
271
272 if (one_of.size() == 1) return one_of[0];
273
275 items.pushKV("oneOf", std::move(one_of));
276 return items;
277}
278
279// NOLINTNEXTLINE(misc-no-recursion)
280UniValue DedupArrayItemsSchema(std::span<const RPCResult> inner)
281{
282 if (inner.empty()) return UniValue{UniValue::VOBJ};
283 if (inner.size() == 1) return OpenRPCResultSchema(inner.front());
284
285 UniValue one_of{UniValue::VARR};
286 std::unordered_set<std::string> seen;
287 for (const auto& item : inner) {
288 PushUniqueSchema(one_of, seen, OpenRPCResultSchema(item));
289 }
290
291 if (one_of.size() == 1) return one_of[0];
292
294 items.pushKV("oneOf", std::move(one_of));
295 return items;
296}
297
298void ApplyTypeStrOverride(UniValue& schema, const RPCArg& arg)
299{
300 if (arg.m_opts.type_str.size() != 2) return;
301 const std::string& type_label{arg.m_opts.type_str[1]};
302 if (type_label.empty()) return;
303
304 static const std::unordered_set<std::string> number_or_string{
305 "integer / string",
306 "string or numeric",
307 };
308 if (number_or_string.contains(type_label)) {
309 UniValue one_of{UniValue::VARR};
310 one_of.push_back(MakeObject({{"type", "number"}}));
311 one_of.push_back(MakeObject({{"type", "string"}}));
312 schema = UniValue{UniValue::VOBJ};
313 schema.pushKV("oneOf", std::move(one_of));
314 } else {
315 schema.pushKV("x-bitcoin-type-override", type_label);
316 }
317}
318
319void ApplyArgFallback(UniValue& schema, const RPCArg& arg)
320{
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);
325 }
326}
327
328// NOLINTNEXTLINE(misc-no-recursion)
329UniValue OpenRPCArgSchema(const RPCArg& arg, bool include_hidden)
330{
331 UniValue schema{UniValue::VOBJ};
332 if (arg.m_opts.skip_type_check) {
333 ApplyTypeStrOverride(schema, arg);
334 if (schema.empty() && arg.m_type == RPCArg::Type::ARR) {
335 UniValue one_of{UniValue::VARR};
336 one_of.push_back(MakeObject({{"type", "array"}}));
337 one_of.push_back(MakeObject({{"type", "object"}}));
338 schema.pushKV("oneOf", std::move(one_of));
339 }
340 ApplyArgFallback(schema, arg);
341 return schema;
342 }
343
344 switch (arg.m_type) {
346 schema = MakeObject({{"type", "string"}});
347 break;
349 schema = MakeObject({{"type", "string"}, {"pattern", "^[0-9a-fA-F]+$"}});
350 break;
352 schema = MakeObject({{"type", "number"}});
353 break;
355 schema = MakeObject({{"type", "boolean"}});
356 break;
358 UniValue one_of{UniValue::VARR};
359 one_of.push_back(MakeObject({{"type", "number"}}));
360 one_of.push_back(MakeObject({{"type", "string"}}));
361 schema.pushKV("oneOf", std::move(one_of));
362 break;
363 }
364 case RPCArg::Type::RANGE: {
366 items.push_back(MakeObject({{"type", "number"}}));
367 items.push_back(MakeObject({{"type", "number"}}));
368 UniValue range_schema{UniValue::VOBJ};
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);
374 UniValue one_of{UniValue::VARR};
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));
378 break;
379 }
380 case RPCArg::Type::ARR: {
381 UniValue items{DedupArrayItemsSchema(arg.m_inner, include_hidden)};
382 schema.pushKV("type", "array");
383 schema.pushKV("items", std::move(items));
384 break;
385 }
388 UniValue properties{UniValue::VOBJ};
389 UniValue required{UniValue::VARR};
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());
398 }
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));
403 break;
404 }
406 schema.pushKV("type", "object");
407 if (!arg.m_inner.empty()) {
408 schema.pushKV("additionalProperties", OpenRPCArgSchema(arg.m_inner[0], include_hidden));
409 } else {
410 schema.pushKV("additionalProperties", true);
411 }
412 break;
413 }
414 } // no default case, so the compiler can warn about missing cases
415 ApplyTypeStrOverride(schema, arg);
416 ApplyArgFallback(schema, arg);
417 return schema;
418}
419
420// NOLINTNEXTLINE(misc-no-recursion)
421UniValue OpenRPCResultSchema(const RPCResult& result)
422{
423 if (result.m_opts.skip_type_check) {
424 RPCResultOptions opts{result.m_opts};
425 opts.skip_type_check = false;
426 if (result.m_type == RPCResult::Type::OBJ) {
427 UniValue obj_schema{OpenRPCResultSchema(RPCResult{result, std::move(opts)})};
428 if (result.m_key_name.empty()) return obj_schema;
429
430 UniValue one_of{UniValue::VARR};
431 one_of.push_back(std::move(obj_schema));
432 one_of.push_back(MakeObject({{"const", false}}));
433 UniValue schema{UniValue::VOBJ};
434 schema.pushKV("oneOf", std::move(one_of));
435 return schema;
436 }
437 if (result.m_type == RPCResult::Type::ARR) return OpenRPCResultSchema(RPCResult{result, std::move(opts)});
438 return UniValue{UniValue::VOBJ};
439 }
440
441 switch (result.m_type) {
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"}});
451 UniValue schema{UniValue::VOBJ};
452 schema.pushKV("type", "number");
453 schema.pushKV("x-bitcoin-unit", "unix-time");
454 return schema;
455 }
457 return MakeObject({{"type", "boolean"}});
459 return MakeObject({{"type", "null"}});
461 UniValue items{DedupArrayItemsSchema(result.m_inner)};
462 UniValue schema{UniValue::VOBJ};
463 schema.pushKV("type", "array");
464 schema.pushKV("items", std::move(items));
465 return schema;
466 }
469 for (const auto& inner : result.m_inner) {
470 items.push_back(OpenRPCResultSchema(inner));
471 }
472 UniValue schema{UniValue::VOBJ};
473 schema.pushKV("type", "array");
474 schema.pushKV("items", std::move(items));
475 schema.pushKV("additionalItems", false);
476 schema.pushKV("minItems", uint64_t(result.m_inner.size()));
477 schema.pushKV("maxItems", uint64_t(result.m_inner.size()));
478 return schema;
479 }
481 UniValue properties{UniValue::VOBJ};
482 UniValue required{UniValue::VARR};
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);
489 }
490 UniValue schema{UniValue::VOBJ};
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));
495 return schema;
496 }
498 UniValue schema{UniValue::VOBJ};
499 schema.pushKV("type", "object");
500 if (!result.m_inner.empty()) {
501 schema.pushKV("additionalProperties", OpenRPCResultSchema(result.m_inner[0]));
502 } else {
503 schema.pushKV("additionalProperties", UniValue{UniValue::VOBJ});
504 }
505 return schema;
506 }
508 return UniValue{UniValue::VOBJ};
509 } // no default case, so the compiler can warn about missing cases
511}
512} // namespace
513
515{
516 return RPCResult{
517 RPCResult::Type::OBJ, "", "",
518 {
519 {RPCResult::Type::STR, "openrpc", "OpenRPC specification version."},
520 {RPCResult::Type::OBJ, "info", "Metadata about this JSON-RPC interface.",
521 {
522 {RPCResult::Type::STR, "title", "API title."},
523 {RPCResult::Type::STR, "version", "Bitcoin Core version string."},
524 {RPCResult::Type::STR, "description", "API description."},
525 }},
526 {RPCResult::Type::ARR, "methods", "Documented RPC methods.",
527 {{RPCResult::Type::OBJ, "", "An RPC method description object.",
528 {
529 {RPCResult::Type::STR, "name", "Method name."},
530 {RPCResult::Type::STR, "description", "Method description."},
531 {RPCResult::Type::ARR, "params", "Method parameters.",
532 {{RPCResult::Type::OBJ, "", "A parameter.",
533 {
534 {RPCResult::Type::STR, "name", "Parameter name."},
535 {RPCResult::Type::BOOL, "required", "Whether the parameter is required."},
536 {RPCResult::Type::ANY, "schema", "JSON Schema for the parameter."},
537 {RPCResult::Type::STR, "description", /*optional=*/true, "Parameter description."},
538 {RPCResult::Type::ARR, "x-bitcoin-aliases", /*optional=*/true, "Alternative parameter names.",
539 {{RPCResult::Type::STR, "", "An alias."}}},
540 {RPCResult::Type::BOOL, "x-bitcoin-placeholder", /*optional=*/true, "Whether the parameter is retained only for compatibility."},
541 {RPCResult::Type::BOOL, "x-bitcoin-also-positional", /*optional=*/true, "Whether the parameter can also be passed positionally."},
542 }}}},
543 {RPCResult::Type::OBJ, "result", "Method result.",
544 {
545 {RPCResult::Type::STR, "name", "Result name."},
546 {RPCResult::Type::ANY, "schema", "JSON Schema for the result."},
547 }},
548 {RPCResult::Type::STR, "x-bitcoin-category", "RPC category."},
549 }}}},
550 },
551 {.skip_type_check = true}};
552}
553
555{
556 return RPCMethod{
557 "getopenrpcinfo",
558 "Returns an OpenRPC document for currently available RPC commands.\n",
559 {
560 {"show_hidden", RPCArg::Type::BOOL, RPCArg::Default{false}, "Also include hidden RPC commands and arguments."},
561 },
564 HelpExampleCli("getopenrpcinfo", "")
565 + HelpExampleRpc("getopenrpcinfo", "")
566 },
567 [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
568{
569 const bool include_hidden{!request.params[0].isNull() && request.params[0].get_bool()};
570 return tableRPC.buildOpenRPCDoc(include_hidden);
571},
572 };
573}
574
576{
577 return RPCMethod{
578 "rpc.discover",
579 "Returns an OpenRPC schema as a description of this service.\n",
580 {},
583 HelpExampleCli("rpc.discover", "")
584 + HelpExampleRpc("rpc.discover", "")
585 },
586 [](const RPCMethod&, const JSONRPCRequest&) -> UniValue
587{
588 return tableRPC.buildOpenRPCDoc(/*include_hidden=*/false);
589},
590 };
591}
592
594 /* Overall control/query calls */
595 {"control", &getopenrpcinfo},
596 {"control", &rpc_discover},
597 {"control", &getrpcinfo},
598 {"control", &help},
599 {"control", &stop},
600 {"control", &uptime},
601};
602
604{
605 for (const auto& c : vRPCCommands) {
606 appendCommand(c.name, &c);
607 }
608}
609
610void CRPCTable::appendCommand(const std::string& name, const CRPCCommand* pcmd)
611{
612 CHECK_NONFATAL(!IsRPCRunning()); // Only add commands before rpc is running
613
614 mapCommands[name].push_back(pcmd);
615}
616
617bool CRPCTable::removeCommand(const std::string& name, const CRPCCommand* pcmd)
618{
619 auto it = mapCommands.find(name);
620 if (it != mapCommands.end()) {
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()) {
625 mapCommands.erase(it);
626 }
627 return true;
628 }
629 }
630 return false;
631}
632
634{
635 LogDebug(BCLog::RPC, "Starting RPC\n");
636 g_rpc_running = true;
637}
638
640{
641 static std::once_flag g_rpc_interrupt_flag;
642 // This function could be called twice if the GUI has been started with -server=1.
643 std::call_once(g_rpc_interrupt_flag, []() {
644 LogDebug(BCLog::RPC, "Interrupting RPC\n");
645 // Interrupt e.g. running longpolls
646 g_rpc_running = false;
647 });
648}
649
651{
652 static std::once_flag g_rpc_stop_flag;
653 // This function could be called twice if the GUI has been started with -server=1.
655 std::call_once(g_rpc_stop_flag, [&]() {
656 LogDebug(BCLog::RPC, "Stopping RPC\n");
658 LogDebug(BCLog::RPC, "RPC stopped.\n");
659 });
660}
661
663{
664 return g_rpc_running;
665}
666
668{
669 if (!IsRPCRunning()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down");
670}
671
672void SetRPCWarmupStatus(const std::string& newStatus)
673{
675 rpcWarmupStatus = newStatus;
676}
677
679{
681 fRPCInWarmup = true;
682}
683
685{
687 assert(fRPCInWarmup);
688 fRPCInWarmup = false;
689}
690
691bool RPCIsInWarmup(std::string *outStatus)
692{
694 if (outStatus)
695 *outStatus = rpcWarmupStatus;
696 return fRPCInWarmup;
697}
698
699bool IsDeprecatedRPCEnabled(const std::string& method)
700{
701 const std::vector<std::string> enabled_methods = gArgs.GetArgs("-deprecatedrpc");
702
703 return find(enabled_methods.begin(), enabled_methods.end(), method) != enabled_methods.end();
704}
705
706UniValue JSONRPCExec(const JSONRPCRequest& jreq, bool catch_errors)
707{
708 UniValue result;
709 if (catch_errors) {
710 try {
711 result = tableRPC.execute(jreq);
712 } catch (UniValue& e) {
713 return JSONRPCReplyObj(NullUniValue, std::move(e), jreq.id, jreq.m_json_version);
714 } catch (const std::exception& e) {
716 }
717 } else {
718 result = tableRPC.execute(jreq);
719 }
720
721 return JSONRPCReplyObj(std::move(result), NullUniValue, jreq.id, jreq.m_json_version);
722}
723
728static inline JSONRPCRequest transformNamedArguments(const JSONRPCRequest& in, const std::vector<std::pair<std::string, bool>>& argNames)
729{
730 JSONRPCRequest out = in;
731 out.params = UniValue(UniValue::VARR);
732 // Build a map of parameters, and remove ones that have been processed, so that we can throw a focused error if
733 // there is an unknown one.
734 const std::vector<std::string>& keys = in.params.getKeys();
735 const std::vector<UniValue>& values = in.params.getValues();
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]);
739 if (!inserted) {
740 throw JSONRPCError(RPC_INVALID_PARAMETER, "Parameter " + keys[i] + " specified multiple times");
741 }
742 }
743 // Process expected parameters. If any parameters were left unspecified in
744 // the request before a parameter that was specified, null values need to be
745 // inserted at the unspecified parameter positions, and the "hole" variable
746 // below tracks the number of null values that need to be inserted.
747 // The "initial_hole_size" variable stores the size of the initial hole,
748 // i.e. how many initial positional arguments were left unspecified. This is
749 // used after the for-loop to add initial positional arguments from the
750 // "args" parameter, if present.
751 int hole = 0;
752 int initial_hole_size = 0;
753 const std::string* initial_param = nullptr;
754 UniValue options{UniValue::VOBJ};
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()) {
761 break;
762 }
763 }
764
765 // Handle named-only parameters by pushing them into a temporary options
766 // object, and then pushing the accumulated options as the next
767 // positional argument.
768 if (named_only) {
769 if (fr != argsIn.end()) {
770 if (options.exists(fr->first)) {
771 throw JSONRPCError(RPC_INVALID_PARAMETER, "Parameter " + fr->first + " specified multiple times");
772 }
773 options.pushKVEnd(fr->first, *fr->second);
774 argsIn.erase(fr);
775 }
776 continue;
777 }
778
779 if (!options.empty() || fr != argsIn.end()) {
780 for (int i = 0; i < hole; ++i) {
781 // Fill hole between specified parameters with JSON nulls,
782 // but not at the end (for backwards compatibility with calls
783 // that act based on number of specified parameters).
784 out.params.push_back(UniValue());
785 }
786 hole = 0;
787 if (!initial_param) initial_param = &argNamePattern;
788 } else {
789 hole += 1;
790 if (out.params.empty()) initial_hole_size = hole;
791 }
792
793 // If named input parameter "fr" is present, push it onto out.params. If
794 // options are present, push them onto out.params. If both are present,
795 // throw an error.
796 if (fr != argsIn.end()) {
797 if (!options.empty()) {
798 throw JSONRPCError(RPC_INVALID_PARAMETER, "Parameter " + fr->first + " conflicts with parameter " + options.getKeys().front());
799 }
800 out.params.push_back(*fr->second);
801 argsIn.erase(fr);
802 }
803 if (!options.empty()) {
804 out.params.push_back(std::move(options));
805 options = UniValue{UniValue::VOBJ};
806 }
807 }
808 // If leftover "args" param was found, use it as a source of positional
809 // arguments and add named arguments after. This is a convenience for
810 // clients that want to pass a combination of named and positional
811 // arguments as described in doc/JSON-RPC-interface.md#parameter-passing
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) {
815 throw JSONRPCError(RPC_INVALID_PARAMETER, "Parameter " + *initial_param + " specified twice both as positional and named argument");
816 }
817 // Assign positional_args to out.params and append named_args after.
818 UniValue named_args{std::move(out.params)};
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]);
822 }
823 }
824 // If there are still arguments in the argsIn map, this is an error.
825 if (!argsIn.empty()) {
826 throw JSONRPCError(RPC_INVALID_PARAMETER, "Unknown named parameter " + argsIn.begin()->first);
827 }
828 // Return request with named arguments transformed to positional arguments
829 return out;
830}
831
832static bool ExecuteCommands(const std::vector<const CRPCCommand*>& commands, const JSONRPCRequest& request, UniValue& result)
833{
834 for (const auto& command : commands) {
835 if (ExecuteCommand(*command, request, result, &command == &commands.back())) {
836 return true;
837 }
838 }
839 return false;
840}
841
843{
844 // Return immediately if in warmup
845 {
847 if (fRPCInWarmup)
848 throw JSONRPCError(RPC_IN_WARMUP, rpcWarmupStatus);
849 }
850
851 // Find method
852 auto it = mapCommands.find(request.strMethod);
853 if (it != mapCommands.end()) {
854 UniValue result;
855 if (ExecuteCommands(it->second, request, result)) {
856 return result;
857 }
858 }
859 throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
860}
861
862static bool ExecuteCommand(const CRPCCommand& command, const JSONRPCRequest& request, UniValue& result, bool last_handler)
863{
864 try {
865 RPCCommandExecution execution(request.strMethod);
866 // Execute, convert arguments to array if necessary
867 if (request.params.isObject()) {
868 return command.actor(transformNamedArguments(request, command.argNames), result, last_handler);
869 } else {
870 return command.actor(request, result, last_handler);
871 }
872 } catch (const UniValue::type_error& e) {
873 throw JSONRPCError(RPC_TYPE_ERROR, e.what());
874 } catch (const std::exception& e) {
875 throw JSONRPCError(RPC_MISC_ERROR, e.what());
876 }
877}
878
879std::vector<std::string> CRPCTable::listCommands() const
880{
881 std::vector<std::string> commandList;
882 commandList.reserve(mapCommands.size());
883 for (const auto& i : mapCommands) commandList.emplace_back(i.first);
884 return commandList;
885}
886
887UniValue CRPCTable::buildOpenRPCDoc(bool include_hidden) const
888{
889 std::vector<std::string> method_names;
890 for (const auto& [name, cmds] : mapCommands) {
891 if (cmds.empty()) continue;
892 const CRPCCommand* cmd{cmds.front()};
893 if ((!include_hidden && cmd->category == "hidden") || !cmd->metadata_fn) continue;
894 method_names.push_back(name);
895 }
896 std::sort(method_names.begin(), method_names.end());
897
898 UniValue methods{UniValue::VARR};
899 for (const auto& method_name : method_names) {
900 const CRPCCommand* cmd{mapCommands.at(method_name).front()};
901 RPCMethod helpman{cmd->metadata_fn()};
902
903 UniValue params{UniValue::VARR};
904 for (const auto& arg : helpman.GetArgs()) {
905 if (!include_hidden && arg.m_opts.hidden) continue;
907 param.pushKV("name", arg.GetFirstName());
908 param.pushKV("required", !arg.IsOptional());
909 param.pushKV("schema", OpenRPCArgSchema(arg, include_hidden));
910
911 std::vector<std::string> names{SplitString(arg.m_names, '|')};
912 if (names.size() > 1) {
913 UniValue aliases{UniValue::VARR};
914 for (size_t i{1}; i < names.size(); ++i) aliases.push_back(names[i]);
915 param.pushKV("x-bitcoin-aliases", std::move(aliases));
916 }
917 if (arg.m_opts.placeholder) param.pushKV("x-bitcoin-placeholder", true);
918 if (arg.m_opts.also_positional) param.pushKV("x-bitcoin-also-positional", true);
919 if (!arg.m_description.empty()) param.pushKV("description", arg.m_description);
920 params.push_back(std::move(param));
921 }
922
923 UniValue result_schema{UniValue::VOBJ};
924 const auto& results{helpman.GetResults().m_results};
925 if (results.size() == 1 && results[0].m_type != RPCResult::Type::ANY) {
926 result_schema = OpenRPCResultSchema(results[0]);
927 } else if (results.size() > 1) {
928 UniValue one_of{UniValue::VARR};
929 for (const auto& r : results) {
930 if (r.m_type == RPCResult::Type::ANY) continue;
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));
934 }
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));
939 }
940 }
941
942 UniValue method{UniValue::VOBJ};
943 method.pushKV("name", method_name);
944 method.pushKV("description", util::TrimString(helpman.GetDescription()));
945 method.pushKV("params", std::move(params));
946 UniValue result{UniValue::VOBJ};
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));
952 }
953
954 std::string version{"v" CLIENT_VERSION_STRING};
955 if (!CLIENT_VERSION_IS_RELEASE) version += "-dev";
956
958 info.pushKV("title", "Bitcoin Core JSON-RPC");
959 info.pushKV("version", version);
960 info.pushKV("description", "Autogenerated from Bitcoin Core RPC metadata.");
961
963 doc.pushKV("openrpc", "1.4.1");
964 doc.pushKV("info", std::move(info));
965 doc.pushKV("methods", std::move(methods));
966 return doc;
967}
968
970{
971 JSONRPCRequest request = args_request;
973
975 for (const auto& cmd : mapCommands) {
976 UniValue result;
977 if (ExecuteCommands(cmd.second, request, result)) {
978 for (const auto& values : result.getValues()) {
979 ret.push_back(values);
980 }
981 }
982 }
983 return ret;
984}
985
ArgsManager gArgs
Definition: args.cpp:40
int ret
const auto cmd
const auto command
#define CHECK_NONFATAL(condition)
Identity function.
Definition: check.h:112
#define NONFATAL_UNREACHABLE()
NONFATAL_UNREACHABLE() is a macro that is used to mark unreachable code.
Definition: check.h:133
std::vector< std::string > GetArgs(const std::string &strArg) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Return a vector of strings of the given argument.
Definition: args.cpp:424
fs::path m_file_path
Definition: logging.h:177
RPC command dispatcher.
Definition: server.h:90
CRPCTable()
Definition: server.cpp:603
std::map< std::string, std::vector< const CRPCCommand * > > mapCommands
Definition: server.h:92
bool removeCommand(const std::string &name, const CRPCCommand *pcmd)
Definition: server.cpp:617
std::string help(std::string_view name, const JSONRPCRequest &helpreq) const
Definition: server.cpp:72
std::vector< std::string > listCommands() const
Returns a list of registered commands.
Definition: server.cpp:879
UniValue buildOpenRPCDoc(bool include_hidden=false) const
Return a complete OpenRPC 1.4.1 document for registered commands.
Definition: server.cpp:887
UniValue execute(const JSONRPCRequest &request) const
Execute a method.
Definition: server.cpp:842
void appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
Definition: server.cpp:610
UniValue dumpArgMap(const JSONRPCRequest &request) const
Return all named arguments that need to be converted by the client from string to another JSON type.
Definition: server.cpp:969
Different type to mark Mutex at global scope.
Definition: sync.h:142
UniValue params
Definition: request.h:57
std::string strMethod
Definition: request.h:56
JSONRPCVersion m_json_version
Definition: request.h:63
enum JSONRPCRequest::Mode mode
std::optional< UniValue > id
Definition: request.h:55
auto MaybeArg(std::string_view key) const
Helper to get an optional request argument.
Definition: util.h:503
void push_back(UniValue val)
Definition: univalue.cpp:103
@ VOBJ
Definition: univalue.h:24
@ VSTR
Definition: univalue.h:24
@ VARR
Definition: univalue.h:24
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
bool isNull() const
Definition: univalue.h:81
const std::vector< UniValue > & getValues() const
const std::vector< std::string > & getKeys() const
bool empty() const
Definition: univalue.h:69
void pushKV(std::string key, UniValue val)
Definition: univalue.cpp:125
bool isObject() const
Definition: univalue.h:88
SteadyClock::duration GetUptime()
Monotonic uptime (not affected by system time changes).
Definition: system.cpp:134
#define LogDebug(category,...)
Definition: log.h:143
BCLog::Logger & LogInstance()
Definition: logging.cpp:26
@ RPC
Definition: categories.h:23
std::vector< std::string > SplitString(std::string_view str, char sep)
Definition: string.h:152
std::string TrimString(std::string_view str, std::string_view pattern=" \f\n\r\t\v")
Definition: string.h:172
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:70
UniValue JSONRPCReplyObj(UniValue result, UniValue error, std::optional< UniValue > id, JSONRPCVersion jsonrpc_version)
Definition: request.cpp:51
void DeleteAuthCookie()
Delete RPC authentication cookie from disk.
Definition: request.cpp:164
const char * name
Definition: rest.cpp:50
@ RPC_MISC_ERROR
General application defined errors.
Definition: protocol.h:63
@ RPC_METHOD_NOT_FOUND
Definition: protocol.h:55
@ RPC_TYPE_ERROR
Unexpected type was passed as parameter.
Definition: protocol.h:64
@ RPC_CLIENT_NOT_CONNECTED
P2P client errors.
Definition: protocol.h:82
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
Definition: protocol.h:67
@ RPC_IN_WARMUP
Client still warming up.
Definition: protocol.h:73
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:183
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:201
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)
Definition: server.cpp:699
void SetRPCWarmupFinished()
Definition: server.cpp:684
static RPCMethod stop()
Definition: server.cpp:148
void StartRPC()
Definition: server.cpp:633
static bool ExecuteCommands(const std::vector< const CRPCCommand * > &commands, const JSONRPCRequest &request, UniValue &result)
Definition: server.cpp:832
static RPCResult OpenRPCDocResult()
Definition: server.cpp:514
bool RPCIsInWarmup(std::string *outStatus)
Definition: server.cpp:691
static bool ExecuteCommand(const CRPCCommand &command, const JSONRPCRequest &request, UniValue &result, bool last_handler)
Definition: server.cpp:862
void StopRPC()
Definition: server.cpp:650
static std::atomic< bool > g_rpc_running
Definition: server.cpp:38
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...
Definition: server.cpp:728
bool IsRPCRunning()
Query whether RPC is running.
Definition: server.cpp:662
void SetRPCWarmupStarting()
Definition: server.cpp:678
static RPCMethod help()
Definition: server.cpp:122
void InterruptRPC()
Definition: server.cpp:639
static RPCMethod getrpcinfo()
Definition: server.cpp:195
UniValue JSONRPCExec(const JSONRPCRequest &jreq, bool catch_errors)
Definition: server.cpp:706
static RPCMethod getopenrpcinfo()
Definition: server.cpp:554
static bool fRPCInWarmup GUARDED_BY(g_rpc_warmup_mutex)
static GlobalMutex g_rpc_warmup_mutex
Definition: server.cpp:37
static RPCMethod uptime()
Definition: server.cpp:175
static RPCServerInfo g_rpc_server_info
Definition: server.cpp:55
static RPCMethod rpc_discover()
Definition: server.cpp:575
static const CRPCCommand vRPCCommands[]
Definition: server.cpp:593
void SetRPCWarmupStatus(const std::string &newStatus)
Set the RPC warmup status.
Definition: server.cpp:672
CRPCTable tableRPC
Definition: server.cpp:986
void RpcInterruptionPoint()
Throw JSONRPCError if RPC is not running.
Definition: server.cpp:667
NodeContext & EnsureAnyNodeContext(const std::any &context)
Definition: server_util.cpp:25
Definition: util.h:187
@ 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.
Definition: util.h:228
const RPCArgOptions m_opts
Definition: util.h:231
const std::string m_names
The name of the arg (can be empty for inner args, can contain multiple aliases separated by | for nam...
Definition: util.h:226
const Fallback m_fallback
Definition: util.h:229
const std::string m_description
Definition: util.h:230
std::string DefaultHint
Hint for default value.
Definition: util.h:221
bool IsOptional() const
Definition: util.cpp:925
const Type m_type
Definition: util.h:227
std::string GetFirstName() const
Return the first of all aliases.
Definition: util.cpp:914
@ OMITTED
Optional argument for which the default value is omitted from help text for one of two reasons:
bool hidden
For testing only.
Definition: util.h:174
std::vector< std::string > type_str
Should be empty unless it is supposed to override the auto-generated type strings....
Definition: util.h:172
bool also_positional
If set allows a named-parameter field in an OBJ_NAMED_PARAM options object to have the same name as a...
Definition: util.h:175
bool placeholder
If set, the argument is retained only for compatibility and should generally be omitted.
Definition: util.h:173
bool skip_type_check
Definition: util.h:170
RPCCommandExecution(const std::string &method)
Definition: server.cpp:60
std::list< RPCCommandExecutionInfo >::iterator it
Definition: server.cpp:59
SteadyClock::time_point start
Definition: server.cpp:46
std::string method
Definition: server.cpp:45
@ 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.
Definition: util.h:326
const RPCResultOptions m_opts
Definition: util.h:328
const std::string m_key_name
Only used for dicts.
Definition: util.h:325
const Type m_type
Definition: util.h:324
bool skip_type_check
Definition: util.h:303
std::list< RPCCommandExecutionInfo > active_commands GUARDED_BY(mutex)
Mutex mutex
Definition: server.cpp:51
#define LOCK(cs)
Definition: sync.h:268
std::vector< uint16_t > keys
Definition: dbwrapper.cpp:376
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172
consteval auto _(util::TranslatedLiteral str)
Definition: translation.h:79
const UniValue NullUniValue
Definition: univalue.cpp:15
std::string Capitalize(std::string str)
Capitalizes the first character of the given string.
void UninterruptibleSleep(const std::chrono::microseconds &n)
Definition: time.cpp:30
constexpr int64_t TicksSeconds(Duration d)
Definition: time.h:88
assert(!tx.IsCoinBase())