Coverage Report

Created: 2026-09-14 20:36

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/src/rpc/node.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/register.h> // IWYU pragma: associated
9
10
#include <chainparams.h>
11
#include <index/base.h>
12
#include <index/blockfilterindex.h>
13
#include <index/coinstatsindex.h>
14
#include <index/txindex.h>
15
#include <index/txospenderindex.h>
16
#include <interfaces/chain.h>
17
#include <interfaces/echo.h>
18
#include <interfaces/init.h>
19
#include <interfaces/ipc.h>
20
#include <kernel/cs_main.h>
21
#include <logging.h>
22
#include <node/context.h>
23
#include <rpc/protocol.h>
24
#include <rpc/request.h>
25
#include <rpc/server.h>
26
#include <rpc/server_util.h>
27
#include <rpc/util.h>
28
#include <scheduler.h>
29
#include <support/lockedpool.h>
30
#include <sync.h>
31
#include <tinyformat.h>
32
#include <univalue.h>
33
#include <util/check.h>
34
#include <util/time.h>
35
#include <validationinterface.h>
36
37
#include <cstdint>
38
#include <cstdio>
39
#include <cstdlib>
40
#include <limits>
41
#include <memory>
42
#include <optional>
43
#include <stdexcept>
44
#include <string>
45
#include <utility>
46
#include <vector>
47
#ifdef HAVE_MALLOC_INFO
48
#include <malloc.h>
49
#endif
50
#include <string_view>
51
52
using node::NodeContext;
53
54
static RPCMethod setmocktime()
55
3.85k
{
56
3.85k
    return RPCMethod{
57
3.85k
        "setmocktime",
58
3.85k
        "Set the local time to given timestamp (-regtest only)\n",
59
3.85k
        {
60
3.85k
            {"timestamp", RPCArg::Type::NUM, RPCArg::Optional::NO, UNIX_EPOCH_TIME + "\n"
61
3.85k
             "Pass 0 to go back to using the system time."},
62
3.85k
        },
63
3.85k
        RPCResult{RPCResult::Type::NONE, "", ""},
64
3.85k
        RPCExamples{""},
65
3.85k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
66
3.85k
{
67
1.40k
    if (!Params().IsMockableChain()) {
68
0
        throw std::runtime_error("setmocktime is for regression testing (-regtest mode) only");
69
0
    }
70
71
    // For now, don't change mocktime if we're in the middle of validation, as
72
    // this could have an effect on mempool time-based eviction, as well as
73
    // IsCurrentForFeeEstimation() and IsInitialBlockDownload().
74
    // TODO: figure out the right way to synchronize around mocktime, and
75
    // ensure all call sites of GetTime() are accessing this safely.
76
1.40k
    LOCK(cs_main);
77
78
1.40k
    const int64_t time{request.params[0].getInt<int64_t>()};
79
    // block timestamps are uint32_t, so mocking time beyond that is meaningless for anything
80
    // consensus-related and can cause integer overflow/truncation issues in time arithmetic.
81
1.40k
    constexpr int64_t max_time{std::numeric_limits<uint32_t>::max()};
82
1.40k
    if (time < 0 || time > max_time) {
83
4
        throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Mocktime must be in the range [0, %s], not %s.", max_time, time));
84
4
    }
85
86
1.40k
    SetMockTime(std::chrono::seconds{time});
87
1.40k
    const NodeContext& node_context{EnsureAnyNodeContext(request.context)};
88
1.40k
    for (const auto& chain_client : node_context.chain_clients) {
89
191
        chain_client->setMockTime(time);
90
191
    }
91
92
1.40k
    return UniValue::VNULL;
93
1.40k
},
94
3.85k
    };
95
3.85k
}
96
97
static RPCMethod mockscheduler()
98
2.48k
{
99
2.48k
    return RPCMethod{
100
2.48k
        "mockscheduler",
101
2.48k
        "Bump the scheduler into the future (-regtest only)\n",
102
2.48k
        {
103
2.48k
            {"delta_time", RPCArg::Type::NUM, RPCArg::Optional::NO, "Number of seconds to forward the scheduler into the future." },
104
2.48k
        },
105
2.48k
        RPCResult{RPCResult::Type::NONE, "", ""},
106
2.48k
        RPCExamples{""},
107
2.48k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
108
2.48k
{
109
30
    if (!Params().IsMockableChain()) {
110
0
        throw std::runtime_error("mockscheduler is for regression testing (-regtest mode) only");
111
0
    }
112
113
30
    int64_t delta_seconds = request.params[0].getInt<int64_t>();
114
30
    if (delta_seconds <= 0 || delta_seconds > 3600) {
115
0
        throw std::runtime_error("delta_time must be between 1 and 3600 seconds (1 hr)");
116
0
    }
117
118
30
    const NodeContext& node_context{EnsureAnyNodeContext(request.context)};
119
30
    CHECK_NONFATAL(node_context.scheduler)->MockForward(std::chrono::seconds{delta_seconds});
120
30
    CHECK_NONFATAL(node_context.validation_signals)->SyncWithValidationInterfaceQueue();
121
30
    for (const auto& chain_client : node_context.chain_clients) {
122
25
        chain_client->schedulerMockForward(std::chrono::seconds(delta_seconds));
123
25
    }
124
125
30
    return UniValue::VNULL;
126
30
},
127
2.48k
    };
128
2.48k
}
129
130
static UniValue RPCLockedMemoryInfo()
131
1
{
132
1
    LockedPool::Stats stats = LockedPoolManager::Instance().stats();
133
1
    UniValue obj(UniValue::VOBJ);
134
1
    obj.pushKV("used", stats.used);
135
1
    obj.pushKV("free", stats.free);
136
1
    obj.pushKV("total", stats.total);
137
1
    obj.pushKV("locked", stats.locked);
138
1
    obj.pushKV("chunks_used", stats.chunks_used);
139
1
    obj.pushKV("chunks_free", stats.chunks_free);
140
1
    return obj;
141
1
}
142
143
#ifdef HAVE_MALLOC_INFO
144
static std::string RPCMallocInfo()
145
1
{
146
1
    char *ptr = nullptr;
147
1
    size_t size = 0;
148
1
    FILE *f = open_memstream(&ptr, &size);
149
1
    if (f) {
150
1
        malloc_info(0, f);
151
1
        fclose(f);
152
1
        if (ptr) {
153
1
            std::string rv(ptr, size);
154
1
            free(ptr);
155
1
            return rv;
156
1
        }
157
1
    }
158
0
    return "";
159
1
}
160
#endif
161
162
static RPCMethod getmemoryinfo()
163
2.46k
{
164
    /* Please, avoid using the word "pool" here in the RPC interface or help,
165
     * as users will undoubtedly confuse it with the other "memory pool"
166
     */
167
2.46k
    return RPCMethod{"getmemoryinfo",
168
2.46k
                "Returns an object containing information about memory usage.\n",
169
2.46k
                {
170
2.46k
                    {"mode", RPCArg::Type::STR, RPCArg::Default{"stats"}, "determines what kind of information is returned.\n"
171
2.46k
            "  - \"stats\" returns general statistics about memory usage in the daemon.\n"
172
2.46k
            "  - \"mallocinfo\" returns an XML string describing low-level heap state (only available if compiled with glibc)."},
173
2.46k
                },
174
2.46k
                {
175
2.46k
                    RPCResult{"mode \"stats\"",
176
2.46k
                        RPCResult::Type::OBJ, "", "",
177
2.46k
                        {
178
2.46k
                            {RPCResult::Type::OBJ, "locked", "Information about locked memory manager",
179
2.46k
                            {
180
2.46k
                                {RPCResult::Type::NUM, "used", "Number of bytes used"},
181
2.46k
                                {RPCResult::Type::NUM, "free", "Number of bytes available in current arenas"},
182
2.46k
                                {RPCResult::Type::NUM, "total", "Total number of bytes managed"},
183
2.46k
                                {RPCResult::Type::NUM, "locked", "Amount of bytes that succeeded locking. If this number is smaller than total, locking pages failed at some point and key data could be swapped to disk."},
184
2.46k
                                {RPCResult::Type::NUM, "chunks_used", "Number allocated chunks"},
185
2.46k
                                {RPCResult::Type::NUM, "chunks_free", "Number unused chunks"},
186
2.46k
                            }},
187
2.46k
                        }
188
2.46k
                    },
189
2.46k
                    RPCResult{"mode \"mallocinfo\"",
190
2.46k
                        RPCResult::Type::STR, "", "\"<malloc version=\"1\">...\""
191
2.46k
                    },
192
2.46k
                },
193
2.46k
                RPCExamples{
194
2.46k
                    HelpExampleCli("getmemoryinfo", "")
195
2.46k
            + HelpExampleRpc("getmemoryinfo", "")
196
2.46k
                },
197
2.46k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
198
2.46k
{
199
3
    auto mode{self.Arg<std::string_view>("mode")};
200
3
    if (mode == "stats") {
201
1
        UniValue obj(UniValue::VOBJ);
202
1
        obj.pushKV("locked", RPCLockedMemoryInfo());
203
1
        return obj;
204
2
    } else if (mode == "mallocinfo") {
205
1
#ifdef HAVE_MALLOC_INFO
206
1
        return RPCMallocInfo();
207
#else
208
        throw JSONRPCError(RPC_INVALID_PARAMETER, "mallocinfo mode not available");
209
#endif
210
1
    } else {
211
1
        throw JSONRPCError(RPC_INVALID_PARAMETER, tfm::format("unknown mode %s", mode));
212
1
    }
213
3
},
214
2.46k
    };
215
2.46k
}
216
217
6
static void EnableOrDisableLogCategories(UniValue cats, bool enable) {
218
6
    cats = cats.get_array();
219
12
    for (unsigned int i = 0; i < cats.size(); ++i) {
220
6
        std::string cat = cats[i].get_str();
221
222
6
        bool success;
223
6
        if (enable) {
224
4
            success = LogInstance().EnableCategory(cat);
225
4
        } else {
226
2
            success = LogInstance().DisableCategory(cat);
227
2
        }
228
229
6
        if (!success) {
230
0
            throw JSONRPCError(RPC_INVALID_PARAMETER, "unknown logging category " + cat);
231
0
        }
232
6
    }
233
6
}
234
235
static RPCMethod logging()
236
2.48k
{
237
2.48k
    return RPCMethod{"logging",
238
2.48k
            "Gets and sets the logging configuration.\n"
239
2.48k
            "When called without an argument, returns the list of categories with status that are currently being debug logged or not.\n"
240
2.48k
            "When called with arguments, adds or removes categories from debug logging and return the lists above.\n"
241
2.48k
            "The arguments are evaluated in order \"include\", \"exclude\".\n"
242
2.48k
            "If an item is both included and excluded, it will thus end up being excluded.\n"
243
2.48k
            "The valid logging categories are: " + LogInstance().LogCategoriesString() + "\n"
244
2.48k
            "In addition, the following are available as category names with special meanings:\n"
245
2.48k
            "  - \"all\",  \"1\" : represent all logging categories.\n"
246
2.48k
            ,
247
2.48k
                {
248
2.48k
                    {"include", RPCArg::Type::ARR, RPCArg::Optional::OMITTED, "The categories to add to debug logging",
249
2.48k
                        {
250
2.48k
                            {"include_category", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "the valid logging category"},
251
2.48k
                        }},
252
2.48k
                    {"exclude", RPCArg::Type::ARR, RPCArg::Optional::OMITTED, "The categories to remove from debug logging",
253
2.48k
                        {
254
2.48k
                            {"exclude_category", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "the valid logging category"},
255
2.48k
                        }},
256
2.48k
                },
257
2.48k
                RPCResult{
258
2.48k
                    RPCResult::Type::OBJ_DYN, "", "keys are the logging categories, and values indicates its status",
259
2.48k
                    {
260
2.48k
                        {RPCResult::Type::BOOL, "category", "if being debug logged or not. false:inactive, true:active"},
261
2.48k
                    }
262
2.48k
                },
263
2.48k
                RPCExamples{
264
2.48k
                    HelpExampleCli("logging", "\"[\\\"all\\\"]\" \"[\\\"http\\\"]\"")
265
2.48k
            + HelpExampleRpc("logging", "[\"all\"], [\"leveldb\"]")
266
2.48k
                },
267
2.48k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
268
2.48k
{
269
17
    if (request.params[0].isArray()) {
270
4
        EnableOrDisableLogCategories(request.params[0], true);
271
4
    }
272
17
    if (request.params[1].isArray()) {
273
2
        EnableOrDisableLogCategories(request.params[1], false);
274
2
    }
275
276
17
    UniValue result(UniValue::VOBJ);
277
510
    for (const auto& logCatActive : LogInstance().LogCategoriesList()) {
278
510
        result.pushKV(logCatActive.category, logCatActive.active);
279
510
    }
280
281
17
    return result;
282
17
},
283
2.48k
    };
284
2.48k
}
285
286
static RPCMethod echo(const std::string& name)
287
5.10k
{
288
5.10k
    return RPCMethod{
289
5.10k
        name,
290
5.10k
        "Simply echo back the input arguments. This command is for testing.\n"
291
5.10k
                "\nIt will return an internal bug report when arg9='trigger_internal_bug' is passed.\n"
292
5.10k
                "\nThe difference between echo and echojson is that echojson has argument conversion enabled in the client-side table in "
293
5.10k
                "bitcoin-cli and the GUI. There is no server-side difference.",
294
5.10k
        {
295
5.10k
            {"arg0", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
296
5.10k
            {"arg1", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
297
5.10k
            {"arg2", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
298
5.10k
            {"arg3", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
299
5.10k
            {"arg4", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
300
5.10k
            {"arg5", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
301
5.10k
            {"arg6", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
302
5.10k
            {"arg7", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
303
5.10k
            {"arg8", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
304
5.10k
            {"arg9", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
305
5.10k
        },
306
5.10k
                RPCResult{RPCResult::Type::ANY, "", "Returns whatever was passed in"},
307
5.10k
                RPCExamples{""},
308
5.10k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
309
5.10k
{
310
199
    if (request.params[9].isStr()) {
311
0
        CHECK_NONFATAL(request.params[9].get_str() != "trigger_internal_bug");
312
0
    }
313
314
199
    return request.params;
315
199
},
316
5.10k
    };
317
5.10k
}
318
319
2.64k
static RPCMethod echo() { return echo("echo"); }
320
2.46k
static RPCMethod echojson() { return echo("echojson"); }
321
322
static RPCMethod echoipc()
323
2.45k
{
324
2.45k
    return RPCMethod{
325
2.45k
        "echoipc",
326
2.45k
        "Echo back the input argument, passing it through a spawned process in a multiprocess build.\n"
327
2.45k
        "This command is for testing.\n",
328
2.45k
        {{"arg", RPCArg::Type::STR, RPCArg::Optional::NO, "The string to echo",}},
329
2.45k
        RPCResult{RPCResult::Type::STR, "echo", "The echoed string."},
330
2.45k
        RPCExamples{HelpExampleCli("echo", "\"Hello world\"") +
331
2.45k
                    HelpExampleRpc("echo", "\"Hello world\"")},
332
2.45k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue {
333
1
            interfaces::Init& local_init = *EnsureAnyNodeContext(request.context).init;
334
1
            std::unique_ptr<interfaces::Echo> echo;
335
1
            if (interfaces::Ipc* ipc = local_init.ipc()) {
336
                // Spawn a new bitcoin-node process and call makeEcho to get a
337
                // client pointer to a interfaces::Echo instance running in
338
                // that process. This is just for testing. A slightly more
339
                // realistic test spawning a different executable instead of
340
                // the same executable would add a new bitcoin-echo executable,
341
                // and spawn bitcoin-echo below instead of bitcoin-node. But
342
                // using bitcoin-node avoids the need to build and install a
343
                // new executable just for this one test.
344
0
                auto init = ipc->spawnProcess("bitcoin-node");
345
0
                echo = init->makeEcho();
346
0
                ipc->addCleanup(*echo, [init = init.release()] { delete init; });
347
1
            } else {
348
                // IPC support is not available because this is a bitcoind
349
                // process not a bitcoind-node process, so just create a local
350
                // interfaces::Echo object and return it so the `echoipc` RPC
351
                // method will work, and the python test calling `echoipc`
352
                // can expect the same result.
353
1
                echo = local_init.makeEcho();
354
1
            }
355
1
            return echo->echo(request.params[0].get_str());
356
1
        },
357
2.45k
    };
358
2.45k
}
359
360
static UniValue SummaryToJSON(const IndexSummary&& summary, std::string index_name)
361
157
{
362
157
    UniValue ret_summary(UniValue::VOBJ);
363
157
    if (!index_name.empty() && index_name != summary.name) return ret_summary;
364
365
139
    UniValue entry(UniValue::VOBJ);
366
139
    entry.pushKV("synced", summary.synced);
367
139
    entry.pushKV("best_block_height", summary.best_block_height);
368
139
    ret_summary.pushKV(summary.name, std::move(entry));
369
139
    return ret_summary;
370
157
}
371
372
static RPCMethod getindexinfo()
373
2.53k
{
374
2.53k
    return RPCMethod{
375
2.53k
        "getindexinfo",
376
2.53k
        "Returns the status of one or all available indices currently running in the node.\n",
377
2.53k
                {
378
2.53k
                    {"index_name", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "Filter results for an index with a specific name."},
379
2.53k
                },
380
2.53k
                RPCResult{
381
2.53k
                    RPCResult::Type::OBJ_DYN, "", "", {
382
2.53k
                        {
383
2.53k
                            RPCResult::Type::OBJ, "name", "The name of the index",
384
2.53k
                            {
385
2.53k
                                {RPCResult::Type::BOOL, "synced", "Whether the index is synced or not"},
386
2.53k
                                {RPCResult::Type::NUM, "best_block_height", "The block height to which the index is synced"},
387
2.53k
                            }
388
2.53k
                        },
389
2.53k
                    },
390
2.53k
                },
391
2.53k
                RPCExamples{
392
2.53k
                    HelpExampleCli("getindexinfo", "")
393
2.53k
                  + HelpExampleRpc("getindexinfo", "")
394
2.53k
                  + HelpExampleCli("getindexinfo", "txindex")
395
2.53k
                  + HelpExampleRpc("getindexinfo", R"("txindex")")
396
2.53k
                },
397
2.53k
                [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
398
2.53k
{
399
64
    UniValue result(UniValue::VOBJ);
400
64
    const std::string index_name{self.MaybeArg<std::string_view>("index_name").value_or("")};
401
402
64
    if (g_txindex) {
403
39
        result.pushKVs(SummaryToJSON(g_txindex->GetSummary(), index_name));
404
39
    }
405
406
64
    if (g_coin_stats_index) {
407
52
        result.pushKVs(SummaryToJSON(g_coin_stats_index->GetSummary(), index_name));
408
52
    }
409
410
64
    if (g_txospenderindex) {
411
25
        result.pushKVs(SummaryToJSON(g_txospenderindex->GetSummary(), index_name));
412
25
    }
413
414
64
    ForEachBlockFilterIndex([&result, &index_name](const BlockFilterIndex& index) {
415
41
        result.pushKVs(SummaryToJSON(index.GetSummary(), index_name));
416
41
    });
417
418
64
    return result;
419
64
},
420
2.53k
    };
421
2.53k
}
422
423
void RegisterNodeRPCCommands(CRPCTable& t)
424
1.36k
{
425
1.36k
    static const CRPCCommand commands[]{
426
1.36k
        {"control", &getmemoryinfo},
427
1.36k
        {"control", &logging},
428
1.36k
        {"util", &getindexinfo},
429
1.36k
        {"hidden", &setmocktime},
430
1.36k
        {"hidden", &mockscheduler},
431
1.36k
        {"hidden", &echo},
432
1.36k
        {"hidden", &echojson},
433
1.36k
        {"hidden", &echoipc},
434
1.36k
    };
435
10.8k
    for (const auto& c : commands) {
436
10.8k
        t.appendCommand(c.name, &c);
437
10.8k
    }
438
1.36k
}