Coverage Report

Created: 2026-07-14 18:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/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
51.3k
{
42
51.3k
    return RPCMethod{
43
51.3k
        "setmocktime",
44
51.3k
        "Set the local time to given timestamp (-regtest only)\n",
45
51.3k
        {
46
51.3k
            {"timestamp", RPCArg::Type::NUM, RPCArg::Optional::NO, UNIX_EPOCH_TIME + "\n"
47
51.3k
             "Pass 0 to go back to using the system time."},
48
51.3k
        },
49
51.3k
        RPCResult{RPCResult::Type::NONE, "", ""},
50
51.3k
        RPCExamples{""},
51
51.3k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
52
51.3k
{
53
51.2k
    if (!Params().IsMockableChain()) {
  Branch (53:9): [True: 0, False: 51.2k]
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
51.2k
    LOCK(cs_main);
63
64
51.2k
    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
51.2k
    constexpr int64_t max_time{std::numeric_limits<uint32_t>::max()};
68
51.2k
    if (time < 0 || time > max_time) {
  Branch (68:9): [True: 0, False: 51.2k]
  Branch (68:21): [True: 0, False: 51.2k]
69
0
        throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Mocktime must be in the range [0, %s], not %s.", max_time, time));
70
0
    }
71
72
51.2k
    SetMockTime(time);
73
51.2k
    const NodeContext& node_context{EnsureAnyNodeContext(request.context)};
74
51.2k
    for (const auto& chain_client : node_context.chain_clients) {
  Branch (74:35): [True: 51.2k, False: 51.2k]
75
51.2k
        chain_client->setMockTime(time);
76
51.2k
    }
77
78
51.2k
    return UniValue::VNULL;
79
51.2k
},
80
51.3k
    };
81
51.3k
}
82
83
static RPCMethod mockscheduler()
84
42.6k
{
85
42.6k
    return RPCMethod{
86
42.6k
        "mockscheduler",
87
42.6k
        "Bump the scheduler into the future (-regtest only)\n",
88
42.6k
        {
89
42.6k
            {"delta_time", RPCArg::Type::NUM, RPCArg::Optional::NO, "Number of seconds to forward the scheduler into the future." },
90
42.6k
        },
91
42.6k
        RPCResult{RPCResult::Type::NONE, "", ""},
92
42.6k
        RPCExamples{""},
93
42.6k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
94
42.6k
{
95
42.5k
    if (!Params().IsMockableChain()) {
  Branch (95:9): [True: 0, False: 42.5k]
96
0
        throw std::runtime_error("mockscheduler is for regression testing (-regtest mode) only");
97
0
    }
98
99
42.5k
    int64_t delta_seconds = request.params[0].getInt<int64_t>();
100
42.5k
    if (delta_seconds <= 0 || delta_seconds > 3600) {
  Branch (100:9): [True: 0, False: 42.5k]
  Branch (100:31): [True: 0, False: 42.5k]
101
0
        throw std::runtime_error("delta_time must be between 1 and 3600 seconds (1 hr)");
102
0
    }
103
104
42.5k
    const NodeContext& node_context{EnsureAnyNodeContext(request.context)};
105
42.5k
    CHECK_NONFATAL(node_context.scheduler)->MockForward(std::chrono::seconds{delta_seconds});
106
42.5k
    CHECK_NONFATAL(node_context.validation_signals)->SyncWithValidationInterfaceQueue();
107
43.1k
    for (const auto& chain_client : node_context.chain_clients) {
  Branch (107:35): [True: 43.1k, False: 42.5k]
108
43.1k
        chain_client->schedulerMockForward(std::chrono::seconds(delta_seconds));
109
43.1k
    }
110
111
42.5k
    return UniValue::VNULL;
112
42.5k
},
113
42.6k
    };
114
42.6k
}
115
116
static UniValue RPCLockedMemoryInfo()
117
0
{
118
0
    LockedPool::Stats stats = LockedPoolManager::Instance().stats();
119
0
    UniValue obj(UniValue::VOBJ);
120
0
    obj.pushKV("used", stats.used);
121
0
    obj.pushKV("free", stats.free);
122
0
    obj.pushKV("total", stats.total);
123
0
    obj.pushKV("locked", stats.locked);
124
0
    obj.pushKV("chunks_used", stats.chunks_used);
125
0
    obj.pushKV("chunks_free", stats.chunks_free);
126
0
    return obj;
127
0
}
128
129
#ifdef HAVE_MALLOC_INFO
130
static std::string RPCMallocInfo()
131
0
{
132
0
    char *ptr = nullptr;
133
0
    size_t size = 0;
134
0
    FILE *f = open_memstream(&ptr, &size);
135
0
    if (f) {
  Branch (135:9): [True: 0, False: 0]
136
0
        malloc_info(0, f);
137
0
        fclose(f);
138
0
        if (ptr) {
  Branch (138:13): [True: 0, False: 0]
139
0
            std::string rv(ptr, size);
140
0
            free(ptr);
141
0
            return rv;
142
0
        }
143
0
    }
144
0
    return "";
145
0
}
146
#endif
147
148
static RPCMethod getmemoryinfo()
149
54
{
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
54
    return RPCMethod{"getmemoryinfo",
154
54
                "Returns an object containing information about memory usage.\n",
155
54
                {
156
54
                    {"mode", RPCArg::Type::STR, RPCArg::Default{"stats"}, "determines what kind of information is returned.\n"
157
54
            "  - \"stats\" returns general statistics about memory usage in the daemon.\n"
158
54
            "  - \"mallocinfo\" returns an XML string describing low-level heap state (only available if compiled with glibc)."},
159
54
                },
160
54
                {
161
54
                    RPCResult{"mode \"stats\"",
162
54
                        RPCResult::Type::OBJ, "", "",
163
54
                        {
164
54
                            {RPCResult::Type::OBJ, "locked", "Information about locked memory manager",
165
54
                            {
166
54
                                {RPCResult::Type::NUM, "used", "Number of bytes used"},
167
54
                                {RPCResult::Type::NUM, "free", "Number of bytes available in current arenas"},
168
54
                                {RPCResult::Type::NUM, "total", "Total number of bytes managed"},
169
54
                                {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
54
                                {RPCResult::Type::NUM, "chunks_used", "Number allocated chunks"},
171
54
                                {RPCResult::Type::NUM, "chunks_free", "Number unused chunks"},
172
54
                            }},
173
54
                        }
174
54
                    },
175
54
                    RPCResult{"mode \"mallocinfo\"",
176
54
                        RPCResult::Type::STR, "", "\"<malloc version=\"1\">...\""
177
54
                    },
178
54
                },
179
54
                RPCExamples{
180
54
                    HelpExampleCli("getmemoryinfo", "")
181
54
            + HelpExampleRpc("getmemoryinfo", "")
182
54
                },
183
54
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
184
54
{
185
0
    auto mode{self.Arg<std::string_view>("mode")};
186
0
    if (mode == "stats") {
  Branch (186:9): [True: 0, False: 0]
187
0
        UniValue obj(UniValue::VOBJ);
188
0
        obj.pushKV("locked", RPCLockedMemoryInfo());
189
0
        return obj;
190
0
    } else if (mode == "mallocinfo") {
  Branch (190:16): [True: 0, False: 0]
191
0
#ifdef HAVE_MALLOC_INFO
192
0
        return RPCMallocInfo();
193
#else
194
        throw JSONRPCError(RPC_INVALID_PARAMETER, "mallocinfo mode not available");
195
#endif
196
0
    } else {
197
0
        throw JSONRPCError(RPC_INVALID_PARAMETER, tfm::format("unknown mode %s", mode));
198
0
    }
199
0
},
200
54
    };
201
54
}
202
203
0
static void EnableOrDisableLogCategories(UniValue cats, bool enable) {
204
0
    cats = cats.get_array();
205
0
    for (unsigned int i = 0; i < cats.size(); ++i) {
  Branch (205:30): [True: 0, False: 0]
206
0
        std::string cat = cats[i].get_str();
207
208
0
        bool success;
209
0
        if (enable) {
  Branch (209:13): [True: 0, False: 0]
210
0
            success = LogInstance().EnableCategory(cat);
211
0
        } else {
212
0
            success = LogInstance().DisableCategory(cat);
213
0
        }
214
215
0
        if (!success) {
  Branch (215:13): [True: 0, False: 0]
216
0
            throw JSONRPCError(RPC_INVALID_PARAMETER, "unknown logging category " + cat);
217
0
        }
218
0
    }
219
0
}
220
221
static RPCMethod logging()
222
54
{
223
54
    return RPCMethod{"logging",
224
54
            "Gets and sets the logging configuration.\n"
225
54
            "When called without an argument, returns the list of categories with status that are currently being debug logged or not.\n"
226
54
            "When called with arguments, adds or removes categories from debug logging and return the lists above.\n"
227
54
            "The arguments are evaluated in order \"include\", \"exclude\".\n"
228
54
            "If an item is both included and excluded, it will thus end up being excluded.\n"
229
54
            "The valid logging categories are: " + LogInstance().LogCategoriesString() + "\n"
230
54
            "In addition, the following are available as category names with special meanings:\n"
231
54
            "  - \"all\",  \"1\" : represent all logging categories.\n"
232
54
            ,
233
54
                {
234
54
                    {"include", RPCArg::Type::ARR, RPCArg::Optional::OMITTED, "The categories to add to debug logging",
235
54
                        {
236
54
                            {"include_category", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "the valid logging category"},
237
54
                        }},
238
54
                    {"exclude", RPCArg::Type::ARR, RPCArg::Optional::OMITTED, "The categories to remove from debug logging",
239
54
                        {
240
54
                            {"exclude_category", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "the valid logging category"},
241
54
                        }},
242
54
                },
243
54
                RPCResult{
244
54
                    RPCResult::Type::OBJ_DYN, "", "keys are the logging categories, and values indicates its status",
245
54
                    {
246
54
                        {RPCResult::Type::BOOL, "category", "if being debug logged or not. false:inactive, true:active"},
247
54
                    }
248
54
                },
249
54
                RPCExamples{
250
54
                    HelpExampleCli("logging", "\"[\\\"all\\\"]\" \"[\\\"http\\\"]\"")
251
54
            + HelpExampleRpc("logging", "[\"all\"], [\"leveldb\"]")
252
54
                },
253
54
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
254
54
{
255
0
    if (request.params[0].isArray()) {
  Branch (255:9): [True: 0, False: 0]
256
0
        EnableOrDisableLogCategories(request.params[0], true);
257
0
    }
258
0
    if (request.params[1].isArray()) {
  Branch (258:9): [True: 0, False: 0]
259
0
        EnableOrDisableLogCategories(request.params[1], false);
260
0
    }
261
262
0
    UniValue result(UniValue::VOBJ);
263
0
    for (const auto& logCatActive : LogInstance().LogCategoriesList()) {
  Branch (263:35): [True: 0, False: 0]
264
0
        result.pushKV(logCatActive.category, logCatActive.active);
265
0
    }
266
267
0
    return result;
268
0
},
269
54
    };
270
54
}
271
272
static RPCMethod echo(const std::string& name)
273
50.1k
{
274
50.1k
    return RPCMethod{
275
50.1k
        name,
276
50.1k
        "Simply echo back the input arguments. This command is for testing.\n"
277
50.1k
                "\nIt will return an internal bug report when arg9='trigger_internal_bug' is passed.\n"
278
50.1k
                "\nThe difference between echo and echojson is that echojson has argument conversion enabled in the client-side table in "
279
50.1k
                "bitcoin-cli and the GUI. There is no server-side difference.",
280
50.1k
        {
281
50.1k
            {"arg0", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
282
50.1k
            {"arg1", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
283
50.1k
            {"arg2", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
284
50.1k
            {"arg3", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
285
50.1k
            {"arg4", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
286
50.1k
            {"arg5", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
287
50.1k
            {"arg6", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
288
50.1k
            {"arg7", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
289
50.1k
            {"arg8", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
290
50.1k
            {"arg9", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
291
50.1k
        },
292
50.1k
                RPCResult{RPCResult::Type::ANY, "", "Returns whatever was passed in"},
293
50.1k
                RPCExamples{""},
294
50.1k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
295
50.1k
{
296
50.0k
    if (request.params[9].isStr()) {
  Branch (296:9): [True: 0, False: 50.0k]
297
0
        CHECK_NONFATAL(request.params[9].get_str() != "trigger_internal_bug");
298
0
    }
299
300
50.0k
    return request.params;
301
50.0k
},
302
50.1k
    };
303
50.1k
}
304
305
50.0k
static RPCMethod echo() { return echo("echo"); }
306
54
static RPCMethod echojson() { return echo("echojson"); }
307
308
static RPCMethod echoipc()
309
54
{
310
54
    return RPCMethod{
311
54
        "echoipc",
312
54
        "Echo back the input argument, passing it through a spawned process in a multiprocess build.\n"
313
54
        "This command is for testing.\n",
314
54
        {{"arg", RPCArg::Type::STR, RPCArg::Optional::NO, "The string to echo",}},
315
54
        RPCResult{RPCResult::Type::STR, "echo", "The echoed string."},
316
54
        RPCExamples{HelpExampleCli("echo", "\"Hello world\"") +
317
54
                    HelpExampleRpc("echo", "\"Hello world\"")},
318
54
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue {
319
0
            interfaces::Init& local_init = *EnsureAnyNodeContext(request.context).init;
320
0
            std::unique_ptr<interfaces::Echo> echo;
321
0
            if (interfaces::Ipc* ipc = local_init.ipc()) {
  Branch (321:34): [True: 0, False: 0]
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
0
            } 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
0
                echo = local_init.makeEcho();
340
0
            }
341
0
            return echo->echo(request.params[0].get_str());
342
0
        },
343
54
    };
344
54
}
345
346
static UniValue SummaryToJSON(const IndexSummary&& summary, std::string index_name)
347
0
{
348
0
    UniValue ret_summary(UniValue::VOBJ);
349
0
    if (!index_name.empty() && index_name != summary.name) return ret_summary;
  Branch (349:9): [True: 0, False: 0]
  Branch (349:32): [True: 0, False: 0]
350
351
0
    UniValue entry(UniValue::VOBJ);
352
0
    entry.pushKV("synced", summary.synced);
353
0
    entry.pushKV("best_block_height", summary.best_block_height);
354
0
    ret_summary.pushKV(summary.name, std::move(entry));
355
0
    return ret_summary;
356
0
}
357
358
static RPCMethod getindexinfo()
359
54
{
360
54
    return RPCMethod{
361
54
        "getindexinfo",
362
54
        "Returns the status of one or all available indices currently running in the node.\n",
363
54
                {
364
54
                    {"index_name", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "Filter results for an index with a specific name."},
365
54
                },
366
54
                RPCResult{
367
54
                    RPCResult::Type::OBJ_DYN, "", "", {
368
54
                        {
369
54
                            RPCResult::Type::OBJ, "name", "The name of the index",
370
54
                            {
371
54
                                {RPCResult::Type::BOOL, "synced", "Whether the index is synced or not"},
372
54
                                {RPCResult::Type::NUM, "best_block_height", "The block height to which the index is synced"},
373
54
                            }
374
54
                        },
375
54
                    },
376
54
                },
377
54
                RPCExamples{
378
54
                    HelpExampleCli("getindexinfo", "")
379
54
                  + HelpExampleRpc("getindexinfo", "")
380
54
                  + HelpExampleCli("getindexinfo", "txindex")
381
54
                  + HelpExampleRpc("getindexinfo", "txindex")
382
54
                },
383
54
                [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
384
54
{
385
0
    UniValue result(UniValue::VOBJ);
386
0
    const std::string index_name{self.MaybeArg<std::string_view>("index_name").value_or("")};
387
388
0
    if (g_txindex) {
  Branch (388:9): [True: 0, False: 0]
389
0
        result.pushKVs(SummaryToJSON(g_txindex->GetSummary(), index_name));
390
0
    }
391
392
0
    if (g_coin_stats_index) {
  Branch (392:9): [True: 0, False: 0]
393
0
        result.pushKVs(SummaryToJSON(g_coin_stats_index->GetSummary(), index_name));
394
0
    }
395
396
0
    if (g_txospenderindex) {
  Branch (396:9): [True: 0, False: 0]
397
0
        result.pushKVs(SummaryToJSON(g_txospenderindex->GetSummary(), index_name));
398
0
    }
399
400
0
    ForEachBlockFilterIndex([&result, &index_name](const BlockFilterIndex& index) {
401
0
        result.pushKVs(SummaryToJSON(index.GetSummary(), index_name));
402
0
    });
403
404
0
    return result;
405
0
},
406
54
    };
407
54
}
408
409
void RegisterNodeRPCCommands(CRPCTable& t)
410
27
{
411
27
    static const CRPCCommand commands[]{
412
27
        {"control", &getmemoryinfo},
413
27
        {"control", &logging},
414
27
        {"util", &getindexinfo},
415
27
        {"hidden", &setmocktime},
416
27
        {"hidden", &mockscheduler},
417
27
        {"hidden", &echo},
418
27
        {"hidden", &echojson},
419
27
        {"hidden", &echoipc},
420
27
    };
421
216
    for (const auto& c : commands) {
  Branch (421:24): [True: 216, False: 27]
422
216
        t.appendCommand(c.name, &c);
423
216
    }
424
27
}