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