Bitcoin Core 32.99.0
P2P Digital Currency
node.cpp
Go to the documentation of this file.
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>
14#include <index/txindex.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
53
55{
56 return RPCMethod{
57 "setmocktime",
58 "Set the local time to given timestamp (-regtest only)\n",
59 {
61 "Pass 0 to go back to using the system time."},
62 },
64 RPCExamples{""},
65 [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
66{
67 if (!Params().IsMockableChain()) {
68 throw std::runtime_error("setmocktime is for regression testing (-regtest mode) only");
69 }
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.
77
78 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 constexpr int64_t max_time{std::numeric_limits<uint32_t>::max()};
82 if (time < 0 || time > max_time) {
83 throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Mocktime must be in the range [0, %s], not %s.", max_time, time));
84 }
85
86 SetMockTime(std::chrono::seconds{time});
87 const NodeContext& node_context{EnsureAnyNodeContext(request.context)};
88 for (const auto& chain_client : node_context.chain_clients) {
89 chain_client->setMockTime(time);
90 }
91
92 return UniValue::VNULL;
93},
94 };
95}
96
98{
99 return RPCMethod{
100 "mockscheduler",
101 "Bump the scheduler into the future (-regtest only)\n",
102 {
103 {"delta_time", RPCArg::Type::NUM, RPCArg::Optional::NO, "Number of seconds to forward the scheduler into the future." },
104 },
106 RPCExamples{""},
107 [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
108{
109 if (!Params().IsMockableChain()) {
110 throw std::runtime_error("mockscheduler is for regression testing (-regtest mode) only");
111 }
112
113 int64_t delta_seconds = request.params[0].getInt<int64_t>();
114 if (delta_seconds <= 0 || delta_seconds > 3600) {
115 throw std::runtime_error("delta_time must be between 1 and 3600 seconds (1 hr)");
116 }
117
118 const NodeContext& node_context{EnsureAnyNodeContext(request.context)};
119 CHECK_NONFATAL(node_context.scheduler)->MockForward(std::chrono::seconds{delta_seconds});
120 CHECK_NONFATAL(node_context.validation_signals)->SyncWithValidationInterfaceQueue();
121 for (const auto& chain_client : node_context.chain_clients) {
122 chain_client->schedulerMockForward(std::chrono::seconds(delta_seconds));
123 }
124
125 return UniValue::VNULL;
126},
127 };
128}
129
131{
134 obj.pushKV("used", stats.used);
135 obj.pushKV("free", stats.free);
136 obj.pushKV("total", stats.total);
137 obj.pushKV("locked", stats.locked);
138 obj.pushKV("chunks_used", stats.chunks_used);
139 obj.pushKV("chunks_free", stats.chunks_free);
140 return obj;
141}
142
143#ifdef HAVE_MALLOC_INFO
144static std::string RPCMallocInfo()
145{
146 char *ptr = nullptr;
147 size_t size = 0;
148 FILE *f = open_memstream(&ptr, &size);
149 if (f) {
150 malloc_info(0, f);
151 fclose(f);
152 if (ptr) {
153 std::string rv(ptr, size);
154 free(ptr);
155 return rv;
156 }
157 }
158 return "";
159}
160#endif
161
163{
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 return RPCMethod{"getmemoryinfo",
168 "Returns an object containing information about memory usage.\n",
169 {
170 {"mode", RPCArg::Type::STR, RPCArg::Default{"stats"}, "determines what kind of information is returned.\n"
171 " - \"stats\" returns general statistics about memory usage in the daemon.\n"
172 " - \"mallocinfo\" returns an XML string describing low-level heap state (only available if compiled with glibc)."},
173 },
174 {
175 RPCResult{"mode \"stats\"",
176 RPCResult::Type::OBJ, "", "",
177 {
178 {RPCResult::Type::OBJ, "locked", "Information about locked memory manager",
179 {
180 {RPCResult::Type::NUM, "used", "Number of bytes used"},
181 {RPCResult::Type::NUM, "free", "Number of bytes available in current arenas"},
182 {RPCResult::Type::NUM, "total", "Total number of bytes managed"},
183 {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 {RPCResult::Type::NUM, "chunks_used", "Number allocated chunks"},
185 {RPCResult::Type::NUM, "chunks_free", "Number unused chunks"},
186 }},
187 }
188 },
189 RPCResult{"mode \"mallocinfo\"",
190 RPCResult::Type::STR, "", "\"<malloc version=\"1\">...\""
191 },
192 },
194 HelpExampleCli("getmemoryinfo", "")
195 + HelpExampleRpc("getmemoryinfo", "")
196 },
197 [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
198{
199 auto mode{self.Arg<std::string_view>("mode")};
200 if (mode == "stats") {
202 obj.pushKV("locked", RPCLockedMemoryInfo());
203 return obj;
204 } else if (mode == "mallocinfo") {
205#ifdef HAVE_MALLOC_INFO
206 return RPCMallocInfo();
207#else
208 throw JSONRPCError(RPC_INVALID_PARAMETER, "mallocinfo mode not available");
209#endif
210 } else {
211 throw JSONRPCError(RPC_INVALID_PARAMETER, tfm::format("unknown mode %s", mode));
212 }
213},
214 };
215}
216
217static void EnableOrDisableLogCategories(UniValue cats, bool enable) {
218 cats = cats.get_array();
219 for (unsigned int i = 0; i < cats.size(); ++i) {
220 std::string cat = cats[i].get_str();
221
222 bool success;
223 if (enable) {
224 success = LogInstance().EnableCategory(cat);
225 } else {
226 success = LogInstance().DisableCategory(cat);
227 }
228
229 if (!success) {
230 throw JSONRPCError(RPC_INVALID_PARAMETER, "unknown logging category " + cat);
231 }
232 }
233}
234
236{
237 return RPCMethod{"logging",
238 "Gets and sets the logging configuration.\n"
239 "When called without an argument, returns the list of categories with status that are currently being debug logged or not.\n"
240 "When called with arguments, adds or removes categories from debug logging and return the lists above.\n"
241 "The arguments are evaluated in order \"include\", \"exclude\".\n"
242 "If an item is both included and excluded, it will thus end up being excluded.\n"
243 "The valid logging categories are: " + LogInstance().LogCategoriesString() + "\n"
244 "In addition, the following are available as category names with special meanings:\n"
245 " - \"all\", \"1\" : represent all logging categories.\n"
246 ,
247 {
248 {"include", RPCArg::Type::ARR, RPCArg::Optional::OMITTED, "The categories to add to debug logging",
249 {
250 {"include_category", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "the valid logging category"},
251 }},
252 {"exclude", RPCArg::Type::ARR, RPCArg::Optional::OMITTED, "The categories to remove from debug logging",
253 {
254 {"exclude_category", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "the valid logging category"},
255 }},
256 },
257 RPCResult{
258 RPCResult::Type::OBJ_DYN, "", "keys are the logging categories, and values indicates its status",
259 {
260 {RPCResult::Type::BOOL, "category", "if being debug logged or not. false:inactive, true:active"},
261 }
262 },
264 HelpExampleCli("logging", "\"[\\\"all\\\"]\" \"[\\\"http\\\"]\"")
265 + HelpExampleRpc("logging", "[\"all\"], [\"leveldb\"]")
266 },
267 [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
268{
269 if (request.params[0].isArray()) {
270 EnableOrDisableLogCategories(request.params[0], true);
271 }
272 if (request.params[1].isArray()) {
273 EnableOrDisableLogCategories(request.params[1], false);
274 }
275
276 UniValue result(UniValue::VOBJ);
277 for (const auto& logCatActive : LogInstance().LogCategoriesList()) {
278 result.pushKV(logCatActive.category, logCatActive.active);
279 }
280
281 return result;
282},
283 };
284}
285
286static RPCMethod echo(const std::string& name)
287{
288 return RPCMethod{
289 name,
290 "Simply echo back the input arguments. This command is for testing.\n"
291 "\nIt will return an internal bug report when arg9='trigger_internal_bug' is passed.\n"
292 "\nThe difference between echo and echojson is that echojson has argument conversion enabled in the client-side table in "
293 "bitcoin-cli and the GUI. There is no server-side difference.",
294 {
305 },
306 RPCResult{RPCResult::Type::ANY, "", "Returns whatever was passed in"},
307 RPCExamples{""},
308 [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
309{
310 if (request.params[9].isStr()) {
311 CHECK_NONFATAL(request.params[9].get_str() != "trigger_internal_bug");
312 }
313
314 return request.params;
315},
316 };
317}
318
319static RPCMethod echo() { return echo("echo"); }
320static RPCMethod echojson() { return echo("echojson"); }
321
323{
324 return RPCMethod{
325 "echoipc",
326 "Echo back the input argument, passing it through a spawned process in a multiprocess build.\n"
327 "This command is for testing.\n",
328 {{"arg", RPCArg::Type::STR, RPCArg::Optional::NO, "The string to echo",}},
329 RPCResult{RPCResult::Type::STR, "echo", "The echoed string."},
330 RPCExamples{HelpExampleCli("echo", "\"Hello world\"") +
331 HelpExampleRpc("echo", "\"Hello world\"")},
332 [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue {
333 interfaces::Init& local_init = *EnsureAnyNodeContext(request.context).init;
334 std::unique_ptr<interfaces::Echo> echo;
335 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 auto init = ipc->spawnProcess("bitcoin-node");
345 echo = init->makeEcho();
346 ipc->addCleanup(*echo, [init = init.release()] { delete init; });
347 } 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 echo = local_init.makeEcho();
354 }
355 return echo->echo(request.params[0].get_str());
356 },
357 };
358}
359
360static UniValue SummaryToJSON(const IndexSummary&& summary, std::string index_name)
361{
362 UniValue ret_summary(UniValue::VOBJ);
363 if (!index_name.empty() && index_name != summary.name) return ret_summary;
364
366 entry.pushKV("synced", summary.synced);
367 entry.pushKV("best_block_height", summary.best_block_height);
368 ret_summary.pushKV(summary.name, std::move(entry));
369 return ret_summary;
370}
371
373{
374 return RPCMethod{
375 "getindexinfo",
376 "Returns the status of one or all available indices currently running in the node.\n",
377 {
378 {"index_name", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "Filter results for an index with a specific name."},
379 },
380 RPCResult{
381 RPCResult::Type::OBJ_DYN, "", "", {
382 {
383 RPCResult::Type::OBJ, "name", "The name of the index",
384 {
385 {RPCResult::Type::BOOL, "synced", "Whether the index is synced or not"},
386 {RPCResult::Type::NUM, "best_block_height", "The block height to which the index is synced"},
387 }
388 },
389 },
390 },
392 HelpExampleCli("getindexinfo", "")
393 + HelpExampleRpc("getindexinfo", "")
394 + HelpExampleCli("getindexinfo", "txindex")
395 + HelpExampleRpc("getindexinfo", R"("txindex")")
396 },
397 [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
398{
399 UniValue result(UniValue::VOBJ);
400 const std::string index_name{self.MaybeArg<std::string_view>("index_name").value_or("")};
401
402 if (g_txindex) {
403 result.pushKVs(SummaryToJSON(g_txindex->GetSummary(), index_name));
404 }
405
406 if (g_coin_stats_index) {
407 result.pushKVs(SummaryToJSON(g_coin_stats_index->GetSummary(), index_name));
408 }
409
410 if (g_txospenderindex) {
411 result.pushKVs(SummaryToJSON(g_txospenderindex->GetSummary(), index_name));
412 }
413
414 ForEachBlockFilterIndex([&result, &index_name](const BlockFilterIndex& index) {
415 result.pushKVs(SummaryToJSON(index.GetSummary(), index_name));
416 });
417
418 return result;
419},
420 };
421}
422
424{
425 static const CRPCCommand commands[]{
426 {"control", &getmemoryinfo},
427 {"control", &logging},
428 {"util", &getindexinfo},
429 {"hidden", &setmocktime},
430 {"hidden", &mockscheduler},
431 {"hidden", &echo},
432 {"hidden", &echojson},
433 {"hidden", &echoipc},
434 };
435 for (const auto& c : commands) {
436 t.appendCommand(c.name, &c);
437 }
438}
void ForEachBlockFilterIndex(std::function< void(BlockFilterIndex &)> fn)
Iterate over all running block filter indexes, invoking fn on each.
const CChainParams & Params()
Return the currently selected parameters.
#define CHECK_NONFATAL(condition)
Identity function.
Definition: check.h:112
void EnableCategory(LogFlags flag)
Definition: logging.cpp:128
std::string LogCategoriesString() const
Returns a string with the log categories in alphabetical order.
Definition: logging.h:266
void DisableCategory(LogFlags flag)
Definition: logging.cpp:142
IndexSummary GetSummary() const
Get a summary of the index and its state.
Definition: base.cpp:488
BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of bloc...
bool IsMockableChain() const
If this chain allows time to be mocked.
Definition: chainparams.h:100
RPC command dispatcher.
Definition: server.h:89
Stats stats() const
Get pool usage statistics.
Definition: lockedpool.cpp:321
static LockedPoolManager & Instance()
Return the current instance, or create it once.
Definition: lockedpool.cpp:404
auto MaybeArg(std::string_view key) const
Helper to get an optional request argument.
Definition: util.h:502
auto Arg(std::string_view key) const
Helper to get a required or default-valued request argument.
Definition: util.h:470
const std::string & get_str() const
@ VNULL
Definition: univalue.h:24
@ VOBJ
Definition: univalue.h:24
size_t size() const
Definition: univalue.h:71
void pushKVs(UniValue obj)
Definition: univalue.cpp:136
const UniValue & get_array() const
void pushKV(std::string key, UniValue val)
Definition: univalue.cpp:125
Initial interface created when a process is first started, and used to give and get access to other i...
Definition: init.h:39
virtual std::unique_ptr< Echo > makeEcho()
Definition: init.h:46
virtual Ipc * ipc()
Definition: init.h:48
Interface providing access to interprocess-communication (IPC) functionality.
Definition: ipc.h:52
std::unique_ptr< CoinStatsIndex > g_coin_stats_index
The global UTXO set hash object.
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:8
BCLog::Logger & LogInstance()
Definition: logging.cpp:26
Definition: basic.cpp:11
Definition: ipc.h:14
void format(std::ostream &out, FormatStringCheck< sizeof...(Args)> fmt, const Args &... args)
Format list of arguments to the stream according to given format string.
Definition: tinyformat.h:1079
void RegisterNodeRPCCommands(CRPCTable &t)
Definition: node.cpp:423
static void EnableOrDisableLogCategories(UniValue cats, bool enable)
Definition: node.cpp:217
static RPCMethod getmemoryinfo()
Definition: node.cpp:162
static UniValue RPCLockedMemoryInfo()
Definition: node.cpp:130
static RPCMethod echoipc()
Definition: node.cpp:322
static RPCMethod echo(const std::string &name)
Definition: node.cpp:286
static RPCMethod echojson()
Definition: node.cpp:320
static RPCMethod setmocktime()
Definition: node.cpp:54
static RPCMethod getindexinfo()
Definition: node.cpp:372
static RPCMethod logging()
Definition: node.cpp:235
static UniValue SummaryToJSON(const IndexSummary &&summary, std::string index_name)
Definition: node.cpp:360
static RPCMethod mockscheduler()
Definition: node.cpp:97
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:75
const char * name
Definition: rest.cpp:71
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
Definition: protocol.h:69
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:189
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:207
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency.
Definition: util.cpp:49
NodeContext & EnsureAnyNodeContext(const std::any &context)
Definition: server_util.cpp:28
Memory statistics.
Definition: lockedpool.h:146
@ OMITTED
Optional argument for which the default value is omitted from help text for one of two reasons:
@ NO
Required arg.
bool skip_type_check
Definition: util.h:169
@ ANY
Special type to disable type checks.
@ OBJ_DYN
Special dictionary with keys that are not literals.
NodeContext struct containing references to chain state and connection state.
Definition: context.h:59
interfaces::Init * init
Init interface for initializing current process and connecting to other processes.
Definition: context.h:64
#define LOCK(cs)
Definition: sync.h:268
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172
std::unique_ptr< TxIndex > g_txindex
The global transaction index, used in GetTransaction. May be null.
Definition: txindex.cpp:41
std::unique_ptr< TxoSpenderIndex > g_txospenderindex
The global txo spender index. May be null.
void SetMockTime(std::chrono::time_point< NodeClock, std::chrono::seconds > mock)
Definition: time.cpp:52