Coverage Report

Created: 2026-09-02 14:16

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