Bitcoin Core  24.99.0
P2P Digital Currency
node.cpp
Go to the documentation of this file.
1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2021 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 <chainparams.h>
7 #include <httpserver.h>
9 #include <index/coinstatsindex.h>
10 #include <index/txindex.h>
11 #include <interfaces/chain.h>
12 #include <interfaces/echo.h>
13 #include <interfaces/init.h>
14 #include <interfaces/ipc.h>
15 #include <node/context.h>
16 #include <rpc/server.h>
17 #include <rpc/server_util.h>
18 #include <rpc/util.h>
19 #include <scheduler.h>
20 #include <univalue.h>
21 #include <util/check.h>
22 #include <util/syscall_sandbox.h>
23 #include <util/system.h>
24 
25 #include <stdint.h>
26 #ifdef HAVE_MALLOC_INFO
27 #include <malloc.h>
28 #endif
29 
30 using node::NodeContext;
31 
33 {
34  return RPCHelpMan{"setmocktime",
35  "\nSet the local time to given timestamp (-regtest only)\n",
36  {
38  "Pass 0 to go back to using the system time."},
39  },
41  RPCExamples{""},
42  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
43 {
44  if (!Params().IsMockableChain()) {
45  throw std::runtime_error("setmocktime is for regression testing (-regtest mode) only");
46  }
47 
48  // For now, don't change mocktime if we're in the middle of validation, as
49  // this could have an effect on mempool time-based eviction, as well as
50  // IsCurrentForFeeEstimation() and IsInitialBlockDownload().
51  // TODO: figure out the right way to synchronize around mocktime, and
52  // ensure all call sites of GetTime() are accessing this safely.
53  LOCK(cs_main);
54 
55  RPCTypeCheck(request.params, {UniValue::VNUM});
56  const int64_t time{request.params[0].getInt<int64_t>()};
57  if (time < 0) {
58  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Mocktime cannot be negative: %s.", time));
59  }
60  SetMockTime(time);
61  auto node_context = util::AnyPtr<NodeContext>(request.context);
62  if (node_context) {
63  for (const auto& chain_client : node_context->chain_clients) {
64  chain_client->setMockTime(time);
65  }
66  }
67 
68  return UniValue::VNULL;
69 },
70  };
71 }
72 
73 #if defined(USE_SYSCALL_SANDBOX)
74 static RPCHelpMan invokedisallowedsyscall()
75 {
76  return RPCHelpMan{
77  "invokedisallowedsyscall",
78  "\nInvoke a disallowed syscall to trigger a syscall sandbox violation. Used for testing purposes.\n",
79  {},
82  HelpExampleCli("invokedisallowedsyscall", "") + HelpExampleRpc("invokedisallowedsyscall", "")},
83  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue {
84  if (!Params().IsTestChain()) {
85  throw std::runtime_error("invokedisallowedsyscall is used for testing only.");
86  }
87  TestDisallowedSandboxCall();
88  return UniValue::VNULL;
89  },
90  };
91 }
92 #endif // USE_SYSCALL_SANDBOX
93 
95 {
96  return RPCHelpMan{"mockscheduler",
97  "\nBump the scheduler into the future (-regtest only)\n",
98  {
99  {"delta_time", RPCArg::Type::NUM, RPCArg::Optional::NO, "Number of seconds to forward the scheduler into the future." },
100  },
102  RPCExamples{""},
103  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
104 {
105  if (!Params().IsMockableChain()) {
106  throw std::runtime_error("mockscheduler is for regression testing (-regtest mode) only");
107  }
108 
109  // check params are valid values
110  RPCTypeCheck(request.params, {UniValue::VNUM});
111  int64_t delta_seconds = request.params[0].getInt<int64_t>();
112  if (delta_seconds <= 0 || delta_seconds > 3600) {
113  throw std::runtime_error("delta_time must be between 1 and 3600 seconds (1 hr)");
114  }
115 
116  auto node_context = CHECK_NONFATAL(util::AnyPtr<NodeContext>(request.context));
117  // protect against null pointer dereference
118  CHECK_NONFATAL(node_context->scheduler);
119  node_context->scheduler->MockForward(std::chrono::seconds(delta_seconds));
120 
121  return UniValue::VNULL;
122 },
123  };
124 }
125 
127 {
130  obj.pushKV("used", uint64_t(stats.used));
131  obj.pushKV("free", uint64_t(stats.free));
132  obj.pushKV("total", uint64_t(stats.total));
133  obj.pushKV("locked", uint64_t(stats.locked));
134  obj.pushKV("chunks_used", uint64_t(stats.chunks_used));
135  obj.pushKV("chunks_free", uint64_t(stats.chunks_free));
136  return obj;
137 }
138 
139 #ifdef HAVE_MALLOC_INFO
140 static std::string RPCMallocInfo()
141 {
142  char *ptr = nullptr;
143  size_t size = 0;
144  FILE *f = open_memstream(&ptr, &size);
145  if (f) {
146  malloc_info(0, f);
147  fclose(f);
148  if (ptr) {
149  std::string rv(ptr, size);
150  free(ptr);
151  return rv;
152  }
153  }
154  return "";
155 }
156 #endif
157 
159 {
160  /* Please, avoid using the word "pool" here in the RPC interface or help,
161  * as users will undoubtedly confuse it with the other "memory pool"
162  */
163  return RPCHelpMan{"getmemoryinfo",
164  "Returns an object containing information about memory usage.\n",
165  {
166  {"mode", RPCArg::Type::STR, RPCArg::Default{"stats"}, "determines what kind of information is returned.\n"
167  " - \"stats\" returns general statistics about memory usage in the daemon.\n"
168  " - \"mallocinfo\" returns an XML string describing low-level heap state (only available if compiled with glibc 2.10+)."},
169  },
170  {
171  RPCResult{"mode \"stats\"",
172  RPCResult::Type::OBJ, "", "",
173  {
174  {RPCResult::Type::OBJ, "locked", "Information about locked memory manager",
175  {
176  {RPCResult::Type::NUM, "used", "Number of bytes used"},
177  {RPCResult::Type::NUM, "free", "Number of bytes available in current arenas"},
178  {RPCResult::Type::NUM, "total", "Total number of bytes managed"},
179  {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."},
180  {RPCResult::Type::NUM, "chunks_used", "Number allocated chunks"},
181  {RPCResult::Type::NUM, "chunks_free", "Number unused chunks"},
182  }},
183  }
184  },
185  RPCResult{"mode \"mallocinfo\"",
186  RPCResult::Type::STR, "", "\"<malloc version=\"1\">...\""
187  },
188  },
189  RPCExamples{
190  HelpExampleCli("getmemoryinfo", "")
191  + HelpExampleRpc("getmemoryinfo", "")
192  },
193  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
194 {
195  std::string mode = request.params[0].isNull() ? "stats" : request.params[0].get_str();
196  if (mode == "stats") {
198  obj.pushKV("locked", RPCLockedMemoryInfo());
199  return obj;
200  } else if (mode == "mallocinfo") {
201 #ifdef HAVE_MALLOC_INFO
202  return RPCMallocInfo();
203 #else
204  throw JSONRPCError(RPC_INVALID_PARAMETER, "mallocinfo mode not available");
205 #endif
206  } else {
207  throw JSONRPCError(RPC_INVALID_PARAMETER, "unknown mode " + mode);
208  }
209 },
210  };
211 }
212 
213 static void EnableOrDisableLogCategories(UniValue cats, bool enable) {
214  cats = cats.get_array();
215  for (unsigned int i = 0; i < cats.size(); ++i) {
216  std::string cat = cats[i].get_str();
217 
218  bool success;
219  if (enable) {
220  success = LogInstance().EnableCategory(cat);
221  } else {
222  success = LogInstance().DisableCategory(cat);
223  }
224 
225  if (!success) {
226  throw JSONRPCError(RPC_INVALID_PARAMETER, "unknown logging category " + cat);
227  }
228  }
229 }
230 
232 {
233  return RPCHelpMan{"logging",
234  "Gets and sets the logging configuration.\n"
235  "When called without an argument, returns the list of categories with status that are currently being debug logged or not.\n"
236  "When called with arguments, adds or removes categories from debug logging and return the lists above.\n"
237  "The arguments are evaluated in order \"include\", \"exclude\".\n"
238  "If an item is both included and excluded, it will thus end up being excluded.\n"
239  "The valid logging categories are: " + LogInstance().LogCategoriesString() + "\n"
240  "In addition, the following are available as category names with special meanings:\n"
241  " - \"all\", \"1\" : represent all logging categories.\n"
242  " - \"none\", \"0\" : even if other logging categories are specified, ignore all of them.\n"
243  ,
244  {
245  {"include", RPCArg::Type::ARR, RPCArg::Optional::OMITTED_NAMED_ARG, "The categories to add to debug logging",
246  {
247  {"include_category", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "the valid logging category"},
248  }},
249  {"exclude", RPCArg::Type::ARR, RPCArg::Optional::OMITTED_NAMED_ARG, "The categories to remove from debug logging",
250  {
251  {"exclude_category", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "the valid logging category"},
252  }},
253  },
254  RPCResult{
255  RPCResult::Type::OBJ_DYN, "", "keys are the logging categories, and values indicates its status",
256  {
257  {RPCResult::Type::BOOL, "category", "if being debug logged or not. false:inactive, true:active"},
258  }
259  },
260  RPCExamples{
261  HelpExampleCli("logging", "\"[\\\"all\\\"]\" \"[\\\"http\\\"]\"")
262  + HelpExampleRpc("logging", "[\"all\"], [\"libevent\"]")
263  },
264  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
265 {
266  uint32_t original_log_categories = LogInstance().GetCategoryMask();
267  if (request.params[0].isArray()) {
268  EnableOrDisableLogCategories(request.params[0], true);
269  }
270  if (request.params[1].isArray()) {
271  EnableOrDisableLogCategories(request.params[1], false);
272  }
273  uint32_t updated_log_categories = LogInstance().GetCategoryMask();
274  uint32_t changed_log_categories = original_log_categories ^ updated_log_categories;
275 
276  // Update libevent logging if BCLog::LIBEVENT has changed.
277  if (changed_log_categories & BCLog::LIBEVENT) {
279  }
280 
281  UniValue result(UniValue::VOBJ);
282  for (const auto& logCatActive : LogInstance().LogCategoriesList()) {
283  result.pushKV(logCatActive.category, logCatActive.active);
284  }
285 
286  return result;
287 },
288  };
289 }
290 
291 static RPCHelpMan echo(const std::string& name)
292 {
293  return RPCHelpMan{name,
294  "\nSimply echo back the input arguments. This command is for testing.\n"
295  "\nIt will return an internal bug report when arg9='trigger_internal_bug' is passed.\n"
296  "\nThe difference between echo and echojson is that echojson has argument conversion enabled in the client-side table in "
297  "bitcoin-cli and the GUI. There is no server-side difference.",
298  {
309  },
310  RPCResult{RPCResult::Type::ANY, "", "Returns whatever was passed in"},
311  RPCExamples{""},
312  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
313 {
314  if (request.params[9].isStr()) {
315  CHECK_NONFATAL(request.params[9].get_str() != "trigger_internal_bug");
316  }
317 
318  return request.params;
319 },
320  };
321 }
322 
323 static RPCHelpMan echo() { return echo("echo"); }
324 static RPCHelpMan echojson() { return echo("echojson"); }
325 
327 {
328  return RPCHelpMan{
329  "echoipc",
330  "\nEcho back the input argument, passing it through a spawned process in a multiprocess build.\n"
331  "This command is for testing.\n",
332  {{"arg", RPCArg::Type::STR, RPCArg::Optional::NO, "The string to echo",}},
333  RPCResult{RPCResult::Type::STR, "echo", "The echoed string."},
334  RPCExamples{HelpExampleCli("echo", "\"Hello world\"") +
335  HelpExampleRpc("echo", "\"Hello world\"")},
336  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue {
337  interfaces::Init& local_init = *EnsureAnyNodeContext(request.context).init;
338  std::unique_ptr<interfaces::Echo> echo;
339  if (interfaces::Ipc* ipc = local_init.ipc()) {
340  // Spawn a new bitcoin-node process and call makeEcho to get a
341  // client pointer to a interfaces::Echo instance running in
342  // that process. This is just for testing. A slightly more
343  // realistic test spawning a different executable instead of
344  // the same executable would add a new bitcoin-echo executable,
345  // and spawn bitcoin-echo below instead of bitcoin-node. But
346  // using bitcoin-node avoids the need to build and install a
347  // new executable just for this one test.
348  auto init = ipc->spawnProcess("bitcoin-node");
349  echo = init->makeEcho();
350  ipc->addCleanup(*echo, [init = init.release()] { delete init; });
351  } else {
352  // IPC support is not available because this is a bitcoind
353  // process not a bitcoind-node process, so just create a local
354  // interfaces::Echo object and return it so the `echoipc` RPC
355  // method will work, and the python test calling `echoipc`
356  // can expect the same result.
357  echo = local_init.makeEcho();
358  }
359  return echo->echo(request.params[0].get_str());
360  },
361  };
362 }
363 
364 static UniValue SummaryToJSON(const IndexSummary&& summary, std::string index_name)
365 {
366  UniValue ret_summary(UniValue::VOBJ);
367  if (!index_name.empty() && index_name != summary.name) return ret_summary;
368 
369  UniValue entry(UniValue::VOBJ);
370  entry.pushKV("synced", summary.synced);
371  entry.pushKV("best_block_height", summary.best_block_height);
372  ret_summary.pushKV(summary.name, entry);
373  return ret_summary;
374 }
375 
377 {
378  return RPCHelpMan{"getindexinfo",
379  "\nReturns the status of one or all available indices currently running in the node.\n",
380  {
381  {"index_name", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, "Filter results for an index with a specific name."},
382  },
383  RPCResult{
384  RPCResult::Type::OBJ_DYN, "", "", {
385  {
386  RPCResult::Type::OBJ, "name", "The name of the index",
387  {
388  {RPCResult::Type::BOOL, "synced", "Whether the index is synced or not"},
389  {RPCResult::Type::NUM, "best_block_height", "The block height to which the index is synced"},
390  }
391  },
392  },
393  },
394  RPCExamples{
395  HelpExampleCli("getindexinfo", "")
396  + HelpExampleRpc("getindexinfo", "")
397  + HelpExampleCli("getindexinfo", "txindex")
398  + HelpExampleRpc("getindexinfo", "txindex")
399  },
400  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
401 {
402  UniValue result(UniValue::VOBJ);
403  const std::string index_name = request.params[0].isNull() ? "" : request.params[0].get_str();
404 
405  if (g_txindex) {
406  result.pushKVs(SummaryToJSON(g_txindex->GetSummary(), index_name));
407  }
408 
409  if (g_coin_stats_index) {
410  result.pushKVs(SummaryToJSON(g_coin_stats_index->GetSummary(), index_name));
411  }
412 
413  ForEachBlockFilterIndex([&result, &index_name](const BlockFilterIndex& index) {
414  result.pushKVs(SummaryToJSON(index.GetSummary(), index_name));
415  });
416 
417  return result;
418 },
419  };
420 }
421 
423 {
424  static const CRPCCommand commands[]{
425  {"control", &getmemoryinfo},
426  {"control", &logging},
427  {"util", &getindexinfo},
428  {"hidden", &setmocktime},
429  {"hidden", &mockscheduler},
430  {"hidden", &echo},
431  {"hidden", &echojson},
432  {"hidden", &echoipc},
433 #if defined(USE_SYSCALL_SANDBOX)
434  {"hidden", &invokedisallowedsyscall},
435 #endif // USE_SYSCALL_SANDBOX
436  };
437  for (const auto& c : commands) {
438  t.appendCommand(c.name, &c);
439  }
440 }
void ForEachBlockFilterIndex(std::function< void(BlockFilterIndex &)> fn)
Iterate over all running block filter indexes, invoking fn on each.
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: validation.cpp:121
const CChainParams & Params()
Return the currently selected parameters.
#define CHECK_NONFATAL(condition)
Identity function.
Definition: check.h:47
void EnableCategory(LogFlags flag)
Definition: logging.cpp:96
uint32_t GetCategoryMask() const
Definition: logging.h:172
std::string LogCategoriesString() const
Returns a string with the log categories in alphabetical order.
Definition: logging.h:185
void DisableCategory(LogFlags flag)
Definition: logging.cpp:109
IndexSummary GetSummary() const
Get a summary of the index and its state.
Definition: base.cpp:405
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:103
bool IsTestChain() const
If this chain is exclusively used for testing.
Definition: chainparams.h:101
RPC command dispatcher.
Definition: server.h:126
Stats stats() const
Get pool usage statistics.
Definition: lockedpool.cpp:323
static LockedPoolManager & Instance()
Return the current instance, or create it once.
Definition: lockedpool.h:222
const std::string & get_str() const
@ VNULL
Definition: univalue.h:20
@ VOBJ
Definition: univalue.h:20
bool isNull() const
Definition: univalue.h:79
size_t size() const
Definition: univalue.h:70
void pushKVs(UniValue obj)
Definition: univalue.cpp:137
const UniValue & get_array() const
void pushKV(std::string key, UniValue val)
Definition: univalue.cpp:126
Initial interface created when a process is first started, and used to give and get access to other i...
Definition: init.h:29
virtual Ipc * ipc()
Definition: init.cpp:16
virtual std::unique_ptr< Echo > makeEcho()
Definition: init.cpp:15
Interface providing access to interprocess-communication (IPC) functionality.
Definition: ipc.h:45
std::unique_ptr< CoinStatsIndex > g_coin_stats_index
The global UTXO set hash object.
void UpdateHTTPServerLogging(bool enable)
Change logging level for libevent.
Definition: httpserver.cpp:414
BCLog::Logger & LogInstance()
Definition: logging.cpp:20
@ LIBEVENT
Definition: logging.h:57
Definition: ipc.h:12
static RPCHelpMan logging()
Definition: node.cpp:231
static RPCHelpMan setmocktime()
Definition: node.cpp:32
void RegisterNodeRPCCommands(CRPCTable &t)
Definition: node.cpp:422
static void EnableOrDisableLogCategories(UniValue cats, bool enable)
Definition: node.cpp:213
static UniValue RPCLockedMemoryInfo()
Definition: node.cpp:126
static RPCHelpMan mockscheduler()
Definition: node.cpp:94
static RPCHelpMan getmemoryinfo()
Definition: node.cpp:158
static RPCHelpMan echo(const std::string &name)
Definition: node.cpp:291
static UniValue SummaryToJSON(const IndexSummary &&summary, std::string index_name)
Definition: node.cpp:364
static RPCHelpMan echojson()
Definition: node.cpp:324
static RPCHelpMan echoipc()
Definition: node.cpp:326
static RPCHelpMan getindexinfo()
Definition: node.cpp:376
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:56
const char * name
Definition: rest.cpp:46
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
Definition: protocol.h:43
void RPCTypeCheck(const UniValue &params, const std::list< UniValueType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.
Definition: util.cpp:33
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:166
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:184
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:20
NodeContext & EnsureAnyNodeContext(const std::any &context)
Definition: server_util.cpp:20
Memory statistics.
Definition: lockedpool.h:146
@ OMITTED_NAMED_ARG
Optional arg that is a named argument and has a default value of null.
@ OMITTED
Optional argument with default value omitted because they are implicitly clear.
@ NO
Required arg.
@ 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:43
interfaces::Init * init
Init interface for initializing current process and connecting to other processes.
Definition: context.h:47
#define LOCK(cs)
Definition: sync.h:261
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
Definition: time.cpp:91
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
std::unique_ptr< TxIndex > g_txindex
The global transaction index, used in GetTransaction. May be null.
Definition: txindex.cpp:16