Coverage Report

Created: 2026-10-07 13:27

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.94k
{
56
3.94k
    return RPCMethod{
57
3.94k
        "setmocktime",
58
3.94k
        "Set the local time to given timestamp (-regtest only)\n",
59
3.94k
        {
60
3.94k
            {"timestamp", RPCArg::Type::NUM, RPCArg::Optional::NO, UNIX_EPOCH_TIME + "\n"
61
3.94k
             "Pass 0 to go back to using the system time."},
62
3.94k
        },
63
3.94k
        RPCResult{RPCResult::Type::NONE, "", ""},
64
3.94k
        RPCExamples{""},
65
3.94k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
66
3.94k
{
67
1.41k
    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.41k
    LOCK(cs_main);
77
78
1.41k
    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.41k
    constexpr int64_t max_time{std::numeric_limits<uint32_t>::max()};
82
1.41k
    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.41k
    SetMockTime(std::chrono::seconds{time});
87
1.41k
    const NodeContext& node_context{EnsureAnyNodeContext(request.context)};
88
1.41k
    for (const auto& chain_client : node_context.chain_clients) {
89
191
        chain_client->setMockTime(time);
90
191
    }
91
92
1.41k
    return UniValue::VNULL;
93
1.41k
},
94
3.94k
    };
95
3.94k
}
96
97
static RPCMethod mockscheduler()
98
2.55k
{
99
2.55k
    return RPCMethod{
100
2.55k
        "mockscheduler",
101
2.55k
        "Bump the scheduler into the future (-regtest only)\n",
102
2.55k
        {
103
2.55k
            {"delta_time", RPCArg::Type::NUM, RPCArg::Optional::NO, "Number of seconds to forward the scheduler into the future." },
104
2.55k
        },
105
2.55k
        RPCResult{RPCResult::Type::NONE, "", ""},
106
2.55k
        RPCExamples{""},
107
2.55k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
108
2.55k
{
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.55k
    };
128
2.55k
}
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.53k
{
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.53k
    return RPCMethod{"getmemoryinfo",
168
2.53k
                "Returns an object containing information about memory usage.\n",
169
2.53k
                {
170
2.53k
                    {"mode", RPCArg::Type::STR, RPCArg::Default{"stats"}, "determines what kind of information is returned.\n"
171
2.53k
            "  - \"stats\" returns general statistics about memory usage in the daemon.\n"
172
2.53k
            "  - \"mallocinfo\" returns an XML string describing low-level heap state (only available if compiled with glibc)."},
173
2.53k
                },
174
2.53k
                {
175
2.53k
                    RPCResult{"mode \"stats\"",
176
2.53k
                        RPCResult::Type::OBJ, "", "",
177
2.53k
                        {
178
2.53k
                            {RPCResult::Type::OBJ, "locked", "Information about locked memory manager",
179
2.53k
                            {
180
2.53k
                                {RPCResult::Type::NUM, "used", "Number of bytes used"},
181
2.53k
                                {RPCResult::Type::NUM, "free", "Number of bytes available in current arenas"},
182
2.53k
                                {RPCResult::Type::NUM, "total", "Total number of bytes managed"},
183
2.53k
                                {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.53k
                                {RPCResult::Type::NUM, "chunks_used", "Number allocated chunks"},
185
2.53k
                                {RPCResult::Type::NUM, "chunks_free", "Number unused chunks"},
186
2.53k
                            }},
187
2.53k
                        }
188
2.53k
                    },
189
2.53k
                    RPCResult{"mode \"mallocinfo\"",
190
2.53k
                        RPCResult::Type::STR, "", "\"<malloc version=\"1\">...\""
191
2.53k
                    },
192
2.53k
                },
193
2.53k
                RPCExamples{
194
2.53k
                    HelpExampleCli("getmemoryinfo", "")
195
2.53k
            + HelpExampleRpc("getmemoryinfo", "")
196
2.53k
                },
197
2.53k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
198
2.53k
{
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.53k
    };
215
2.53k
}
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.55k
{
237
2.55k
    return RPCMethod{"logging",
238
2.55k
            "Gets and sets the logging configuration.\n"
239
2.55k
            "When called without an argument, returns the list of categories with status that are currently being debug logged or not.\n"
240
2.55k
            "When called with arguments, adds or removes categories from debug logging and return the lists above.\n"
241
2.55k
            "The arguments are evaluated in order \"include\", \"exclude\".\n"
242
2.55k
            "If an item is both included and excluded, it will thus end up being excluded.\n"
243
2.55k
            "The valid logging categories are: " + LogInstance().LogCategoriesString() + "\n"
244
2.55k
            "In addition, the following are available as category names with special meanings:\n"
245
2.55k
            "  - \"all\",  \"1\" : represent all logging categories.\n"
246
2.55k
            ,
247
2.55k
                {
248
2.55k
                    {"include", RPCArg::Type::ARR, RPCArg::Optional::OMITTED, "The categories to add to debug logging",
249
2.55k
                        {
250
2.55k
                            {"include_category", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "the valid logging category"},
251
2.55k
                        }},
252
2.55k
                    {"exclude", RPCArg::Type::ARR, RPCArg::Optional::OMITTED, "The categories to remove from debug logging",
253
2.55k
                        {
254
2.55k
                            {"exclude_category", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "the valid logging category"},
255
2.55k
                        }},
256
2.55k
                },
257
2.55k
                RPCResult{
258
2.55k
                    RPCResult::Type::OBJ_DYN, "", "keys are the logging categories, and values indicates its status",
259
2.55k
                    {
260
2.55k
                        {RPCResult::Type::BOOL, "category", "if being debug logged or not. false:inactive, true:active"},
261
2.55k
                    }
262
2.55k
                },
263
2.55k
                RPCExamples{
264
2.55k
                    HelpExampleCli("logging", "\"[\\\"all\\\"]\" \"[\\\"http\\\"]\"")
265
2.55k
            + HelpExampleRpc("logging", "[\"all\"], [\"leveldb\"]")
266
2.55k
                },
267
2.55k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
268
2.55k
{
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
527
    for (const auto& logCatActive : LogInstance().LogCategoriesList()) {
278
527
        result.pushKV(logCatActive.category, logCatActive.active);
279
527
    }
280
281
17
    return result;
282
17
},
283
2.55k
    };
284
2.55k
}
285
286
static RPCMethod echo(const std::string& name)
287
5.18k
{
288
5.18k
    return RPCMethod{
289
5.18k
        name,
290
5.18k
        "Simply echo back the input arguments. This command is for testing.\n"
291
5.18k
                "\nIt will return an internal bug report when arg9='trigger_internal_bug' is passed.\n"
292
5.18k
                "\nThe difference between echo and echojson is that echojson has argument conversion enabled in the client-side table in "
293
5.18k
                "bitcoin-cli and the GUI. There is no server-side difference.",
294
5.18k
        {
295
5.18k
            {"arg0", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
296
5.18k
            {"arg1", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
297
5.18k
            {"arg2", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
298
5.18k
            {"arg3", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
299
5.18k
            {"arg4", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
300
5.18k
            {"arg5", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
301
5.18k
            {"arg6", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
302
5.18k
            {"arg7", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
303
5.18k
            {"arg8", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
304
5.18k
            {"arg9", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
305
5.18k
        },
306
5.18k
                RPCResult{RPCResult::Type::ANY, "", "Returns whatever was passed in"},
307
5.18k
                RPCExamples{""},
308
5.18k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
309
5.18k
{
310
137
    if (request.params[9].isStr()) {
311
0
        CHECK_NONFATAL(request.params[9].get_str() != "trigger_internal_bug");
312
0
    }
313
314
137
    return request.params;
315
137
},
316
5.18k
    };
317
5.18k
}
318
319
2.65k
static RPCMethod echo() { return echo("echo"); }
320
2.53k
static RPCMethod echojson() { return echo("echojson"); }
321
322
static RPCMethod echoipc()
323
2.52k
{
324
2.52k
    return RPCMethod{
325
2.52k
        "echoipc",
326
2.52k
        "Echo back the input argument, passing it through a spawned process in a multiprocess build.\n"
327
2.52k
        "This command is for testing.\n",
328
2.52k
        {{"arg", RPCArg::Type::STR, RPCArg::Optional::NO, "The string to echo",}},
329
2.52k
        RPCResult{RPCResult::Type::STR, "echo", "The echoed string."},
330
2.52k
        RPCExamples{HelpExampleCli("echo", "\"Hello world\"") +
331
2.52k
                    HelpExampleRpc("echo", "\"Hello world\"")},
332
2.52k
        [](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.52k
    };
358
2.52k
}
359
360
static UniValue SummaryToJSON(const IndexSummary&& summary, std::string index_name)
361
145
{
362
145
    UniValue ret_summary(UniValue::VOBJ);
363
145
    if (!index_name.empty() && index_name != summary.name) return ret_summary;
364
365
127
    UniValue entry(UniValue::VOBJ);
366
127
    entry.pushKV("synced", summary.synced);
367
127
    entry.pushKV("best_block_height", summary.best_block_height);
368
127
    ret_summary.pushKV(summary.name, std::move(entry));
369
127
    return ret_summary;
370
145
}
371
372
static RPCMethod getindexinfo()
373
2.59k
{
374
2.59k
    return RPCMethod{
375
2.59k
        "getindexinfo",
376
2.59k
        "Returns the status of one or all available indices currently running in the node.\n",
377
2.59k
                {
378
2.59k
                    {"index_name", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "Filter results for an index with a specific name."},
379
2.59k
                },
380
2.59k
                RPCResult{
381
2.59k
                    RPCResult::Type::OBJ_DYN, "", "", {
382
2.59k
                        {
383
2.59k
                            RPCResult::Type::OBJ, "name", "The name of the index",
384
2.59k
                            {
385
2.59k
                                {RPCResult::Type::BOOL, "synced", "Whether the index is synced or not"},
386
2.59k
                                {RPCResult::Type::NUM, "best_block_height", "The block height to which the index is synced"},
387
2.59k
                            }
388
2.59k
                        },
389
2.59k
                    },
390
2.59k
                },
391
2.59k
                RPCExamples{
392
2.59k
                    HelpExampleCli("getindexinfo", "")
393
2.59k
                  + HelpExampleRpc("getindexinfo", "")
394
2.59k
                  + HelpExampleCli("getindexinfo", "txindex")
395
2.59k
                  + HelpExampleRpc("getindexinfo", R"("txindex")")
396
2.59k
                },
397
2.59k
                [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
398
2.59k
{
399
61
    UniValue result(UniValue::VOBJ);
400
61
    const std::string index_name{self.MaybeArg<std::string_view>("index_name").value_or("")};
401
402
61
    if (g_txindex) {
403
36
        result.pushKVs(SummaryToJSON(g_txindex->GetSummary(), index_name));
404
36
    }
405
406
61
    if (g_coin_stats_index) {
407
49
        result.pushKVs(SummaryToJSON(g_coin_stats_index->GetSummary(), index_name));
408
49
    }
409
410
61
    if (g_txospenderindex) {
411
22
        result.pushKVs(SummaryToJSON(g_txospenderindex->GetSummary(), index_name));
412
22
    }
413
414
61
    ForEachBlockFilterIndex([&result, &index_name](const BlockFilterIndex& index) {
415
38
        result.pushKVs(SummaryToJSON(index.GetSummary(), index_name));
416
38
    });
417
418
61
    return result;
419
61
},
420
2.59k
    };
421
2.59k
}
422
423
void RegisterNodeRPCCommands(CRPCTable& t)
424
1.40k
{
425
1.40k
    static const CRPCCommand commands[]{
426
1.40k
        {"control", &getmemoryinfo},
427
1.40k
        {"control", &logging},
428
1.40k
        {"util", &getindexinfo},
429
1.40k
        {"hidden", &setmocktime},
430
1.40k
        {"hidden", &mockscheduler},
431
1.40k
        {"hidden", &echo},
432
1.40k
        {"hidden", &echojson},
433
1.40k
        {"hidden", &echoipc},
434
1.40k
    };
435
11.2k
    for (const auto& c : commands) {
436
11.2k
        t.appendCommand(c.name, &c);
437
11.2k
    }
438
1.40k
}