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