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