Coverage Report

Created: 2026-11-13 17:38

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