Bitcoin ABC  0.29.2
P2P Digital Currency
bitcoin-cli.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 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)
7 #include <config/bitcoin-config.h>
8 #endif
9 
10 #include <chainparamsbase.h>
11 #include <clientversion.h>
12 #include <currencyunit.h>
13 #include <rpc/client.h>
14 #include <rpc/mining.h>
15 #include <rpc/protocol.h>
16 #include <rpc/request.h>
17 #include <support/events.h>
18 #include <tinyformat.h>
19 #include <util/strencodings.h>
20 #include <util/system.h>
21 #include <util/translation.h>
22 
23 #include <event2/buffer.h>
24 #include <event2/keyvalq_struct.h>
25 
26 #include <compat/stdin.h>
27 #include <univalue.h>
28 
29 #include <algorithm>
30 #include <chrono>
31 #include <cmath>
32 #include <cstdio>
33 #include <functional>
34 #include <memory>
35 #include <string>
36 #include <tuple>
37 
38 // The server returns time values from a mockable system clock, but it is not
39 // trivial to get the mocked time from the server, nor is it needed for now, so
40 // just use a plain system_clock.
41 using CliClock = std::chrono::system_clock;
42 
43 const std::function<std::string(const char *)> G_TRANSLATION_FUN = nullptr;
44 
45 static const char DEFAULT_RPCCONNECT[] = "127.0.0.1";
46 static const int DEFAULT_HTTP_CLIENT_TIMEOUT = 900;
47 static const bool DEFAULT_NAMED = false;
48 static const int CONTINUE_EXECUTION = -1;
50 static const std::string DEFAULT_NBLOCKS = "1";
51 
52 static void SetupCliArgs(ArgsManager &argsman) {
53  SetupHelpOptions(argsman);
54 
55  const auto defaultBaseParams =
57  const auto testnetBaseParams =
59  const auto regtestBaseParams =
61 
62  SetupCurrencyUnitOptions(argsman);
63  argsman.AddArg("-version", "Print version and exit", ArgsManager::ALLOW_ANY,
65  argsman.AddArg(
66  "-conf=<file>",
67  strprintf("Specify configuration file. Relative paths will be "
68  "prefixed by datadir location. (default: %s)",
71  argsman.AddArg("-datadir=<dir>", "Specify data directory",
73  argsman.AddArg(
74  "-generate",
75  strprintf(
76  "Generate blocks immediately, equivalent to RPC getnewaddress "
77  "followed by RPC generatetoaddress. Optional positional integer "
78  "arguments are number of blocks to generate (default: %s) and "
79  "maximum iterations to try (default: %s), equivalent to RPC "
80  "generatetoaddress nblocks and maxtries arguments. Example: "
81  "bitcoin-cli -generate 4 1000",
84  argsman.AddArg(
85  "-getinfo",
86  "Get general information from the remote server. Note that unlike "
87  "server-side RPC calls, the results of -getinfo is the result of "
88  "multiple non-atomic requests. Some entries in the result may "
89  "represent results from different states (e.g. wallet balance may be "
90  "as of a different block from the chain state reported)",
92  argsman.AddArg("-netinfo",
93  "Get network peer connection information from the remote "
94  "server. An optional integer argument from 0 to 4 can be "
95  "passed for different peers listings (default: 0).",
97 
99  argsman.AddArg(
100  "-named",
101  strprintf("Pass named instead of positional arguments (default: %s)",
102  DEFAULT_NAMED),
104  argsman.AddArg(
105  "-rpcconnect=<ip>",
106  strprintf("Send commands to node running on <ip> (default: %s)",
109  argsman.AddArg(
110  "-rpccookiefile=<loc>",
111  "Location of the auth cookie. Relative paths will be prefixed "
112  "by a net-specific datadir location. (default: data dir)",
114  argsman.AddArg("-rpcport=<port>",
115  strprintf("Connect to JSON-RPC on <port> (default: %u, "
116  "testnet: %u, regtest: %u)",
117  defaultBaseParams->RPCPort(),
118  testnetBaseParams->RPCPort(),
119  regtestBaseParams->RPCPort()),
122  argsman.AddArg("-rpcwait", "Wait for RPC server to start",
124  argsman.AddArg("-rpcuser=<user>", "Username for JSON-RPC connections",
126  argsman.AddArg("-rpcpassword=<pw>", "Password for JSON-RPC connections",
128  argsman.AddArg(
129  "-rpcclienttimeout=<n>",
130  strprintf("Timeout in seconds during HTTP requests, or 0 for "
131  "no timeout. (default: %d)",
134 
135  argsman.AddArg("-stdinrpcpass",
136  "Read RPC password from standard input as a single "
137  "line. When combined with -stdin, the first line "
138  "from standard input is used for the RPC password. When "
139  "combined with -stdinwalletpassphrase, -stdinrpcpass "
140  "consumes the first line, and -stdinwalletpassphrase "
141  "consumes the second.",
143  argsman.AddArg("-stdinwalletpassphrase",
144  "Read wallet passphrase from standard input as a single "
145  "line. When combined with -stdin, the first line "
146  "from standard input is used for the wallet passphrase.",
148  argsman.AddArg(
149  "-stdin",
150  "Read extra arguments from standard input, one per line until "
151  "EOF/Ctrl-D (recommended for sensitive information such as "
152  "passphrases). When combined with -stdinrpcpass, the first "
153  "line from standard input is used for the RPC password.",
155  argsman.AddArg(
156  "-rpcwallet=<walletname>",
157  "Send RPC for non-default wallet on RPC server (needs to exactly match "
158  "corresponding -wallet option passed to bitcoind). This changes the "
159  "RPC endpoint used, e.g. http://127.0.0.1:8332/wallet/<walletname>",
161 }
162 
164 static void libevent_log_cb(int severity, const char *msg) {
165 #ifndef EVENT_LOG_ERR
166 // EVENT_LOG_ERR was added in 2.0.19; but before then _EVENT_LOG_ERR existed.
167 #define EVENT_LOG_ERR _EVENT_LOG_ERR
168 #endif
169  // Ignore everything other than errors
170  if (severity >= EVENT_LOG_ERR) {
171  throw std::runtime_error(strprintf("libevent error: %s", msg));
172  }
173 }
174 
176 //
177 // Start
178 //
179 
180 //
181 // Exception thrown on connection error. This error is used to determine when
182 // to wait if -rpcwait is given.
183 //
184 class CConnectionFailed : public std::runtime_error {
185 public:
186  explicit inline CConnectionFailed(const std::string &msg)
187  : std::runtime_error(msg) {}
188 };
189 
190 //
191 // This function returns either one of EXIT_ codes when it's expected to stop
192 // the process or CONTINUE_EXECUTION when it's expected to continue further.
193 //
194 static int AppInitRPC(int argc, char *argv[]) {
195  //
196  // Parameters
197  //
199  std::string error;
200  if (!gArgs.ParseParameters(argc, argv, error)) {
201  tfm::format(std::cerr, "Error parsing command line arguments: %s\n",
202  error);
203  return EXIT_FAILURE;
204  }
205  if (argc < 2 || HelpRequested(gArgs) || gArgs.IsArgSet("-version")) {
206  std::string strUsage =
207  PACKAGE_NAME " RPC client version " + FormatFullVersion() + "\n";
208  if (!gArgs.IsArgSet("-version")) {
209  strUsage += "\n"
210  "Usage: bitcoin-cli [options] <command> [params] "
211  "Send command to " PACKAGE_NAME "\n"
212  "or: bitcoin-cli [options] -named <command> "
213  "[name=value]... Send command to " PACKAGE_NAME
214  " (with named arguments)\n"
215  "or: bitcoin-cli [options] help "
216  "List commands\n"
217  "or: bitcoin-cli [options] help <command> Get "
218  "help for a command\n";
219 
220  strUsage += "\n" + gArgs.GetHelpMessage();
221  }
222 
223  tfm::format(std::cout, "%s", strUsage);
224  if (argc < 2) {
225  tfm::format(std::cerr, "Error: too few parameters\n");
226  return EXIT_FAILURE;
227  }
228  return EXIT_SUCCESS;
229  }
230  if (!CheckDataDirOption()) {
231  tfm::format(std::cerr,
232  "Error: Specified data directory \"%s\" does not exist.\n",
233  gArgs.GetArg("-datadir", ""));
234  return EXIT_FAILURE;
235  }
236  if (!gArgs.ReadConfigFiles(error, true)) {
237  tfm::format(std::cerr, "Error reading configuration file: %s\n", error);
238  return EXIT_FAILURE;
239  }
240  // Check for -chain, -testnet or -regtest parameter (BaseParams() calls are
241  // only valid after this clause)
242  try {
244  } catch (const std::exception &e) {
245  tfm::format(std::cerr, "Error: %s\n", e.what());
246  return EXIT_FAILURE;
247  }
248  return CONTINUE_EXECUTION;
249 }
250 
252 struct HTTPReply {
253  HTTPReply() : status(0), error(-1) {}
254 
255  int status;
256  int error;
257  std::string body;
258 };
259 
260 static std::string http_errorstring(int code) {
261  switch (code) {
262 #if LIBEVENT_VERSION_NUMBER >= 0x02010300
263  case EVREQ_HTTP_TIMEOUT:
264  return "timeout reached";
265  case EVREQ_HTTP_EOF:
266  return "EOF reached";
267  case EVREQ_HTTP_INVALID_HEADER:
268  return "error while reading header, or invalid header";
269  case EVREQ_HTTP_BUFFER_ERROR:
270  return "error encountered while reading or writing";
271  case EVREQ_HTTP_REQUEST_CANCEL:
272  return "request was canceled";
273  case EVREQ_HTTP_DATA_TOO_LONG:
274  return "response body is larger than allowed";
275 #endif
276  default:
277  return "unknown";
278  }
279 }
280 
281 static void http_request_done(struct evhttp_request *req, void *ctx) {
282  HTTPReply *reply = static_cast<HTTPReply *>(ctx);
283 
284  if (req == nullptr) {
289  reply->status = 0;
290  return;
291  }
292 
293  reply->status = evhttp_request_get_response_code(req);
294 
295  struct evbuffer *buf = evhttp_request_get_input_buffer(req);
296  if (buf) {
297  size_t size = evbuffer_get_length(buf);
298  const char *data = (const char *)evbuffer_pullup(buf, size);
299  if (data) {
300  reply->body = std::string(data, size);
301  }
302  evbuffer_drain(buf, size);
303  }
304 }
305 
306 #if LIBEVENT_VERSION_NUMBER >= 0x02010300
307 static void http_error_cb(enum evhttp_request_error err, void *ctx) {
308  HTTPReply *reply = static_cast<HTTPReply *>(ctx);
309  reply->error = err;
310 }
311 #endif
312 
318 public:
319  virtual ~BaseRequestHandler() {}
320  virtual UniValue PrepareRequest(const std::string &method,
321  const std::vector<std::string> &args) = 0;
322  virtual UniValue ProcessReply(const UniValue &batch_in) = 0;
323 };
324 
327 public:
328  const int ID_NETWORKINFO = 0;
329  const int ID_BLOCKCHAININFO = 1;
330  const int ID_WALLETINFO = 2;
331  const int ID_BALANCES = 3;
332 
334  UniValue PrepareRequest(const std::string &method,
335  const std::vector<std::string> &args) override {
336  if (!args.empty()) {
337  throw std::runtime_error("-getinfo takes no arguments");
338  }
339  UniValue result(UniValue::VARR);
340  result.push_back(
341  JSONRPCRequestObj("getnetworkinfo", NullUniValue, ID_NETWORKINFO));
342  result.push_back(JSONRPCRequestObj("getblockchaininfo", NullUniValue,
344  result.push_back(
345  JSONRPCRequestObj("getwalletinfo", NullUniValue, ID_WALLETINFO));
346  result.push_back(
347  JSONRPCRequestObj("getbalances", NullUniValue, ID_BALANCES));
348  return result;
349  }
350 
352  UniValue ProcessReply(const UniValue &batch_in) override {
353  UniValue result(UniValue::VOBJ);
354  const std::vector<UniValue> batch = JSONRPCProcessBatchReply(batch_in);
355  // Errors in getnetworkinfo() and getblockchaininfo() are fatal, pass
356  // them on; getwalletinfo() and getbalances are allowed to fail if there
357  // is no wallet.
358  if (!batch[ID_NETWORKINFO]["error"].isNull()) {
359  return batch[ID_NETWORKINFO];
360  }
361  if (!batch[ID_BLOCKCHAININFO]["error"].isNull()) {
362  return batch[ID_BLOCKCHAININFO];
363  }
364  result.pushKV("version", batch[ID_NETWORKINFO]["result"]["version"]);
365  result.pushKV("blocks", batch[ID_BLOCKCHAININFO]["result"]["blocks"]);
366  result.pushKV("headers", batch[ID_BLOCKCHAININFO]["result"]["headers"]);
367  result.pushKV(
368  "verificationprogress",
369  batch[ID_BLOCKCHAININFO]["result"]["verificationprogress"]);
370  result.pushKV("timeoffset",
371  batch[ID_NETWORKINFO]["result"]["timeoffset"]);
372 
373  UniValue connections(UniValue::VOBJ);
374  connections.pushKV("in",
375  batch[ID_NETWORKINFO]["result"]["connections_in"]);
376  connections.pushKV("out",
377  batch[ID_NETWORKINFO]["result"]["connections_out"]);
378  connections.pushKV("total",
379  batch[ID_NETWORKINFO]["result"]["connections"]);
380  result.pushKV("connections", connections);
381 
382  result.pushKV("proxy",
383  batch[ID_NETWORKINFO]["result"]["networks"][0]["proxy"]);
384  result.pushKV("difficulty",
385  batch[ID_BLOCKCHAININFO]["result"]["difficulty"]);
386  result.pushKV("chain",
387  UniValue(batch[ID_BLOCKCHAININFO]["result"]["chain"]));
388  if (!batch[ID_WALLETINFO]["result"].isNull()) {
389  result.pushKV("keypoolsize",
390  batch[ID_WALLETINFO]["result"]["keypoolsize"]);
391  if (!batch[ID_WALLETINFO]["result"]["unlocked_until"].isNull()) {
392  result.pushKV("unlocked_until",
393  batch[ID_WALLETINFO]["result"]["unlocked_until"]);
394  }
395  result.pushKV("paytxfee",
396  batch[ID_WALLETINFO]["result"]["paytxfee"]);
397  }
398  if (!batch[ID_BALANCES]["result"].isNull()) {
399  result.pushKV("balance",
400  batch[ID_BALANCES]["result"]["mine"]["trusted"]);
401  }
402  result.pushKV("relayfee", batch[ID_NETWORKINFO]["result"]["relayfee"]);
403  result.pushKV("warnings", batch[ID_NETWORKINFO]["result"]["warnings"]);
404  return JSONRPCReplyObj(result, NullUniValue, 1);
405  }
406 };
407 
410 private:
411  static constexpr int8_t UNKNOWN_NETWORK{-1};
412  static constexpr uint8_t m_networks_size{3};
413  const std::array<std::string, m_networks_size> m_networks{
414  {"ipv4", "ipv6", "onion"}};
416  std::array<std::array<uint16_t, m_networks_size + 2>, 3> m_counts{{{}}};
417  int8_t NetworkStringToId(const std::string &str) const {
418  for (uint8_t i = 0; i < m_networks_size; ++i) {
419  if (str == m_networks.at(i)) {
420  return i;
421  }
422  }
423  return UNKNOWN_NETWORK;
424  }
426  uint8_t m_details_level{0};
427  bool DetailsRequested() const {
428  return m_details_level > 0 && m_details_level < 5;
429  }
430  bool IsAddressSelected() const {
431  return m_details_level == 2 || m_details_level == 4;
432  }
433  bool IsVersionSelected() const {
434  return m_details_level == 3 || m_details_level == 4;
435  }
436  bool m_is_asmap_on{false};
437  size_t m_max_addr_length{0};
438  size_t m_max_age_length{4};
439  size_t m_max_id_length{2};
440  struct Peer {
441  std::string addr;
442  std::string sub_version;
443  std::string network;
444  std::string age;
445  double min_ping;
446  double ping;
447  int64_t last_blck;
448  int64_t last_recv;
449  int64_t last_send;
450  int64_t last_trxn;
451  int id;
453  int version;
456  bool operator<(const Peer &rhs) const {
457  return std::tie(is_outbound, min_ping) <
458  std::tie(rhs.is_outbound, rhs.min_ping);
459  }
460  };
461  std::vector<Peer> m_peers;
462  std::string ChainToString() const {
464  return " testnet";
465  }
467  return " regtest";
468  }
469  return "";
470  }
471  std::string PingTimeToString(double seconds) const {
472  if (seconds < 0) {
473  return "";
474  }
475  const double milliseconds{round(1000 * seconds)};
476  return milliseconds > 999999 ? "-" : ToString(milliseconds);
477  }
478  const int64_t m_time_now{
479  TicksSinceEpoch<std::chrono::seconds>(CliClock::now())};
480 
481 public:
482  static constexpr int ID_PEERINFO = 0;
483  static constexpr int ID_NETWORKINFO = 1;
484 
485  UniValue PrepareRequest(const std::string &method,
486  const std::vector<std::string> &args) override {
487  if (!args.empty()) {
488  uint8_t n{0};
489  if (ParseUInt8(args.at(0), &n)) {
490  m_details_level = n;
491  }
492  }
493  UniValue result(UniValue::VARR);
494  result.push_back(
495  JSONRPCRequestObj("getpeerinfo", NullUniValue, ID_PEERINFO));
496  result.push_back(
497  JSONRPCRequestObj("getnetworkinfo", NullUniValue, ID_NETWORKINFO));
498  return result;
499  }
500 
501  UniValue ProcessReply(const UniValue &batch_in) override {
502  const std::vector<UniValue> batch{JSONRPCProcessBatchReply(batch_in)};
503  if (!batch[ID_PEERINFO]["error"].isNull()) {
504  return batch[ID_PEERINFO];
505  }
506  if (!batch[ID_NETWORKINFO]["error"].isNull()) {
507  return batch[ID_NETWORKINFO];
508  }
509 
510  const UniValue &networkinfo{batch[ID_NETWORKINFO]["result"]};
511  if (networkinfo["version"].get_int() < 230000) {
512  throw std::runtime_error("-netinfo requires bitcoind server to be "
513  "running v0.23.0 and up");
514  }
515 
516  // Count peer connection totals, and if DetailsRequested(), store peer
517  // data in a vector of structs.
518  for (const UniValue &peer : batch[ID_PEERINFO]["result"].getValues()) {
519  const std::string network{peer["network"].get_str()};
520  const int8_t network_id{NetworkStringToId(network)};
521  if (network_id == UNKNOWN_NETWORK) {
522  continue;
523  }
524  const bool is_outbound{!peer["inbound"].get_bool()};
525  const bool is_block_relay{!peer["relaytxes"].get_bool()};
526  // in/out by network
527  ++m_counts.at(is_outbound).at(network_id);
528  // in/out overall
529  ++m_counts.at(is_outbound).at(m_networks_size);
530  // total by network
531  ++m_counts.at(2).at(network_id);
532  // total overall
533  ++m_counts.at(2).at(m_networks_size);
534  if (is_block_relay) {
535  // in/out block-relay
536  ++m_counts.at(is_outbound).at(m_networks_size + 1);
537  // total block-relay
538  ++m_counts.at(2).at(m_networks_size + 1);
539  }
540  if (DetailsRequested()) {
541  // Push data for this peer to the peers vector.
542  const int peer_id{peer["id"].get_int()};
543  const int mapped_as{peer["mapped_as"].isNull()
544  ? 0
545  : peer["mapped_as"].get_int()};
546  const int version{peer["version"].get_int()};
547  const int64_t conn_time{peer["conntime"].get_int64()};
548  const int64_t last_blck{peer["last_block"].get_int64()};
549  const int64_t last_recv{peer["lastrecv"].get_int64()};
550  const int64_t last_send{peer["lastsend"].get_int64()};
551  const int64_t last_trxn{peer["last_transaction"].get_int64()};
552  const double min_ping{
553  peer["minping"].isNull() ? -1 : peer["minping"].get_real()};
554  const double ping{peer["pingtime"].isNull()
555  ? -1
556  : peer["pingtime"].get_real()};
557  const std::string addr{peer["addr"].get_str()};
558  const std::string age{
559  conn_time == 0 ? ""
560  : ToString((m_time_now - conn_time) / 60)};
561  const std::string sub_version{peer["subver"].get_str()};
562  m_peers.push_back({addr, sub_version, network, age, min_ping,
563  ping, last_blck, last_recv, last_send,
564  last_trxn, peer_id, mapped_as, version,
565  is_block_relay, is_outbound});
567  std::max(addr.length() + 1, m_max_addr_length);
568  m_max_age_length = std::max(age.length(), m_max_age_length);
570  std::max(ToString(peer_id).length(), m_max_id_length);
571  m_is_asmap_on |= (mapped_as != 0);
572  }
573  }
574 
575  // Generate report header.
576  std::string result{strprintf("%s %s%s - %i%s\n\n", PACKAGE_NAME,
578  networkinfo["protocolversion"].get_int(),
579  networkinfo["subversion"].get_str())};
580 
581  // Report detailed peer connections list sorted by direction and minimum
582  // ping time.
583  if (DetailsRequested() && !m_peers.empty()) {
584  std::sort(m_peers.begin(), m_peers.end());
585  result += strprintf(
586  "Peer connections sorted by direction and min ping\n<-> relay "
587  " net mping ping send recv txn blk %*s ",
588  m_max_age_length, "age");
589  if (m_is_asmap_on) {
590  result += " asmap ";
591  }
592  result += strprintf("%*s %-*s%s\n", m_max_id_length, "id",
594  IsAddressSelected() ? "address" : "",
595  IsVersionSelected() ? "version" : "");
596  for (const Peer &peer : m_peers) {
597  std::string version{ToString(peer.version) + peer.sub_version};
598  result += strprintf(
599  "%3s %5s %5s%7s%7s%5s%5s%5s%5s %*s%*i %*s %-*s%s\n",
600  peer.is_outbound ? "out" : "in",
601  peer.is_block_relay ? "block" : "full", peer.network,
602  PingTimeToString(peer.min_ping),
603  PingTimeToString(peer.ping),
604  peer.last_send == 0 ? ""
605  : ToString(m_time_now - peer.last_send),
606  peer.last_recv == 0 ? ""
607  : ToString(m_time_now - peer.last_recv),
608  peer.last_trxn == 0
609  ? ""
610  : ToString((m_time_now - peer.last_trxn) / 60),
611  peer.last_blck == 0
612  ? ""
613  : ToString((m_time_now - peer.last_blck) / 60),
614  // variable spacing
615  m_max_age_length, peer.age,
616  // variable spacing
617  m_is_asmap_on ? 7 : 0,
618  m_is_asmap_on && peer.mapped_as != 0
619  ? ToString(peer.mapped_as)
620  : "",
621  // variable spacing
622  m_max_id_length, peer.id,
623  // variable spacing
625  IsAddressSelected() ? peer.addr : "",
626  IsVersionSelected() && version != "0" ? version : "");
627  }
628  result += strprintf(
629  " ms ms sec sec min min %*s\n\n",
630  m_max_age_length, "min");
631  }
632 
633  // Report peer connection totals by type.
634  result += " ipv4 ipv6 onion total block-relay\n";
635  const std::array<std::string, 3> rows{{"in", "out", "total"}};
636  for (uint8_t i = 0; i < m_networks_size; ++i) {
637  result += strprintf("%-5s %5i %5i %5i %5i %5i\n",
638  rows.at(i), m_counts.at(i).at(0),
639  m_counts.at(i).at(1), m_counts.at(i).at(2),
640  m_counts.at(i).at(m_networks_size),
641  m_counts.at(i).at(m_networks_size + 1));
642  }
643 
644  // Report local addresses, ports, and scores.
645  result += "\nLocal addresses";
646  const std::vector<UniValue> &local_addrs{
647  networkinfo["localaddresses"].getValues()};
648  if (local_addrs.empty()) {
649  result += ": n/a\n";
650  } else {
651  size_t max_addr_size{0};
652  for (const UniValue &addr : local_addrs) {
653  max_addr_size = std::max(addr["address"].get_str().length() + 1,
654  max_addr_size);
655  }
656  for (const UniValue &addr : local_addrs) {
657  result +=
658  strprintf("\n%-*s port %6i score %6i", max_addr_size,
659  addr["address"].get_str(), addr["port"].get_int(),
660  addr["score"].get_int());
661  }
662  }
663 
664  return JSONRPCReplyObj(UniValue{result}, NullUniValue, 1);
665  }
666 };
667 
670 public:
671  UniValue PrepareRequest(const std::string &method,
672  const std::vector<std::string> &args) override {
673  address_str = args.at(1);
674  UniValue params{RPCConvertValues("generatetoaddress", args)};
675  return JSONRPCRequestObj("generatetoaddress", params, 1);
676  }
677 
678  UniValue ProcessReply(const UniValue &reply) override {
679  UniValue result(UniValue::VOBJ);
680  result.pushKV("address", address_str);
681  result.pushKV("blocks", reply.get_obj()["result"]);
682  return JSONRPCReplyObj(result, NullUniValue, 1);
683  }
684 
685 protected:
686  std::string address_str;
687 };
688 
691 public:
692  UniValue PrepareRequest(const std::string &method,
693  const std::vector<std::string> &args) override {
694  UniValue params;
695  if (gArgs.GetBoolArg("-named", DEFAULT_NAMED)) {
696  params = RPCConvertNamedValues(method, args);
697  } else {
698  params = RPCConvertValues(method, args);
699  }
700  return JSONRPCRequestObj(method, params, 1);
701  }
702 
703  UniValue ProcessReply(const UniValue &reply) override {
704  return reply.get_obj();
705  }
706 };
707 
708 static UniValue CallRPC(BaseRequestHandler *rh, const std::string &strMethod,
709  const std::vector<std::string> &args,
710  const std::optional<std::string> &rpcwallet = {}) {
711  std::string host;
712  // In preference order, we choose the following for the port:
713  // 1. -rpcport
714  // 2. port in -rpcconnect (ie following : in ipv4 or ]: in ipv6)
715  // 3. default port for chain
716  uint16_t port{BaseParams().RPCPort()};
717  SplitHostPort(gArgs.GetArg("-rpcconnect", DEFAULT_RPCCONNECT), port, host);
718  port = static_cast<uint16_t>(gArgs.GetIntArg("-rpcport", port));
719 
720  // Obtain event base
721  raii_event_base base = obtain_event_base();
722 
723  // Synchronously look up hostname
724  raii_evhttp_connection evcon =
725  obtain_evhttp_connection_base(base.get(), host, port);
726 
727  // Set connection timeout
728  {
729  const int timeout =
730  gArgs.GetIntArg("-rpcclienttimeout", DEFAULT_HTTP_CLIENT_TIMEOUT);
731  if (timeout > 0) {
732  evhttp_connection_set_timeout(evcon.get(), timeout);
733  } else {
734  // Indefinite request timeouts are not possible in libevent-http,
735  // so we set the timeout to a very long time period instead.
736 
737  // Average length of year in Gregorian calendar
738  constexpr int YEAR_IN_SECONDS = 31556952;
739  evhttp_connection_set_timeout(evcon.get(), 5 * YEAR_IN_SECONDS);
740  }
741  }
742 
744  raii_evhttp_request req =
746  if (req == nullptr) {
747  throw std::runtime_error("create http request failed");
748  }
749 #if LIBEVENT_VERSION_NUMBER >= 0x02010300
750  evhttp_request_set_error_cb(req.get(), http_error_cb);
751 #endif
752 
753  // Get credentials
754  std::string strRPCUserColonPass;
755  bool failedToGetAuthCookie = false;
756  if (gArgs.GetArg("-rpcpassword", "") == "") {
757  // Try fall back to cookie-based authentication if no password is
758  // provided
760  failedToGetAuthCookie = true;
761  }
762  } else {
763  strRPCUserColonPass = gArgs.GetArg("-rpcuser", "") + ":" +
764  gArgs.GetArg("-rpcpassword", "");
765  }
766 
767  struct evkeyvalq *output_headers =
768  evhttp_request_get_output_headers(req.get());
769  assert(output_headers);
770  evhttp_add_header(output_headers, "Host", host.c_str());
771  evhttp_add_header(output_headers, "Connection", "close");
772  evhttp_add_header(output_headers, "Content-Type", "application/json");
773  evhttp_add_header(
774  output_headers, "Authorization",
775  (std::string("Basic ") + EncodeBase64(strRPCUserColonPass)).c_str());
776 
777  // Attach request data
778  std::string strRequest = rh->PrepareRequest(strMethod, args).write() + "\n";
779  struct evbuffer *output_buffer =
780  evhttp_request_get_output_buffer(req.get());
781  assert(output_buffer);
782  evbuffer_add(output_buffer, strRequest.data(), strRequest.size());
783 
784  // check if we should use a special wallet endpoint
785  std::string endpoint = "/";
786  if (rpcwallet) {
787  char *encodedURI =
788  evhttp_uriencode(rpcwallet->data(), rpcwallet->size(), false);
789  if (encodedURI) {
790  endpoint = "/wallet/" + std::string(encodedURI);
791  free(encodedURI);
792  } else {
793  throw CConnectionFailed("uri-encode failed");
794  }
795  }
796  int r = evhttp_make_request(evcon.get(), req.get(), EVHTTP_REQ_POST,
797  endpoint.c_str());
798  // ownership moved to evcon in above call
799  req.release();
800  if (r != 0) {
801  throw CConnectionFailed("send http request failed");
802  }
803 
804  event_base_dispatch(base.get());
805 
806  if (response.status == 0) {
807  std::string responseErrorMessage;
808  if (response.error != -1) {
809  responseErrorMessage =
810  strprintf(" (error code %d - \"%s\")", response.error,
811  http_errorstring(response.error));
812  }
813  throw CConnectionFailed(
814  strprintf("Could not connect to the server %s:%d%s\n\nMake sure "
815  "the bitcoind server is running and that you are "
816  "connecting to the correct RPC port.",
817  host, port, responseErrorMessage));
818  } else if (response.status == HTTP_UNAUTHORIZED) {
819  if (failedToGetAuthCookie) {
820  throw std::runtime_error(strprintf(
821  "Could not locate RPC credentials. No authentication cookie "
822  "could be found, and RPC password is not set. See "
823  "-rpcpassword and -stdinrpcpass. Configuration file: (%s)",
825  gArgs.GetArg("-conf", BITCOIN_CONF_FILENAME)))));
826  } else {
827  throw std::runtime_error(
828  "Authorization failed: Incorrect rpcuser or rpcpassword");
829  }
830  } else if (response.status == HTTP_SERVICE_UNAVAILABLE) {
831  throw std::runtime_error(
832  strprintf("Server response: %s", response.body));
833  } else if (response.status >= 400 && response.status != HTTP_BAD_REQUEST &&
834  response.status != HTTP_NOT_FOUND &&
836  throw std::runtime_error(
837  strprintf("server returned HTTP error %d", response.status));
838  } else if (response.body.empty()) {
839  throw std::runtime_error("no response from server");
840  }
841 
842  // Parse reply
843  UniValue valReply(UniValue::VSTR);
844  if (!valReply.read(response.body)) {
845  throw std::runtime_error("couldn't parse reply from server");
846  }
847  const UniValue reply = rh->ProcessReply(valReply);
848  if (reply.empty()) {
849  throw std::runtime_error(
850  "expected reply to have result, error and id properties");
851  }
852 
853  return reply;
854 }
855 
867 static UniValue
868 ConnectAndCallRPC(BaseRequestHandler *rh, const std::string &strMethod,
869  const std::vector<std::string> &args,
870  const std::optional<std::string> &rpcwallet = {}) {
872  // Execute and handle connection failures with -rpcwait.
873  const bool fWait = gArgs.GetBoolArg("-rpcwait", false);
874  do {
875  try {
876  response = CallRPC(rh, strMethod, args, rpcwallet);
877  if (fWait) {
878  const UniValue &error = response.find_value("error");
879  if (!error.isNull() &&
880  error["code"].get_int() == RPC_IN_WARMUP) {
881  throw CConnectionFailed("server in warmup");
882  }
883  }
884  break; // Connection succeeded, no need to retry.
885  } catch (const CConnectionFailed &) {
886  if (fWait) {
887  UninterruptibleSleep(std::chrono::milliseconds{1000});
888  } else {
889  throw;
890  }
891  }
892  } while (fWait);
893  return response;
894 }
895 
897 static void ParseResult(const UniValue &result, std::string &strPrint) {
898  if (result.isNull()) {
899  return;
900  }
901  strPrint = result.isStr() ? result.get_str() : result.write(2);
902 }
903 
908 static void ParseError(const UniValue &error, std::string &strPrint,
909  int &nRet) {
910  if (error.isObject()) {
911  const UniValue &err_code = error.find_value("code");
912  const UniValue &err_msg = error.find_value("message");
913  if (!err_code.isNull()) {
914  strPrint = "error code: " + err_code.getValStr() + "\n";
915  }
916  if (err_msg.isStr()) {
917  strPrint += ("error message:\n" + err_msg.get_str());
918  }
919  if (err_code.isNum() &&
920  err_code.get_int() == RPC_WALLET_NOT_SPECIFIED) {
921  strPrint += "\nTry adding \"-rpcwallet=<filename>\" option to "
922  "bitcoin-cli command line.";
923  }
924  } else {
925  strPrint = "error: " + error.write();
926  }
927  nRet = abs(error["code"].get_int());
928 }
929 
938 static void GetWalletBalances(UniValue &result) {
940  const UniValue listwallets =
941  ConnectAndCallRPC(&rh, "listwallets", /* args=*/{});
942  if (!listwallets.find_value("error").isNull()) {
943  return;
944  }
945  const UniValue &wallets = listwallets.find_value("result");
946  if (wallets.size() <= 1) {
947  return;
948  }
949 
950  UniValue balances(UniValue::VOBJ);
951  for (const UniValue &wallet : wallets.getValues()) {
952  const std::string wallet_name = wallet.get_str();
953  const UniValue getbalances =
954  ConnectAndCallRPC(&rh, "getbalances", /* args=*/{}, wallet_name);
955  const UniValue &balance =
956  getbalances.find_value("result")["mine"]["trusted"];
957  balances.pushKV(wallet_name, balance);
958  }
959  result.pushKV("balances", balances);
960 }
961 
967  std::optional<std::string> wallet_name{};
968  if (gArgs.IsArgSet("-rpcwallet")) {
969  wallet_name = gArgs.GetArg("-rpcwallet", "");
970  }
972  return ConnectAndCallRPC(&rh, "getnewaddress", /* args=*/{}, wallet_name);
973 }
974 
982 static void SetGenerateToAddressArgs(const std::string &address,
983  std::vector<std::string> &args) {
984  if (args.size() > 2) {
985  throw std::runtime_error(
986  "too many arguments (maximum 2 for nblocks and maxtries)");
987  }
988  if (args.size() == 0) {
989  args.emplace_back(DEFAULT_NBLOCKS);
990  } else if (args.at(0) == "0") {
991  throw std::runtime_error(
992  "the first argument (number of blocks to generate, default: " +
993  DEFAULT_NBLOCKS + ") must be an integer value greater than zero");
994  }
995  args.emplace(args.begin() + 1, address);
996 }
997 
998 static int CommandLineRPC(int argc, char *argv[]) {
999  std::string strPrint;
1000  int nRet = 0;
1001  try {
1002  // Skip switches
1003  while (argc > 1 && IsSwitchChar(argv[1][0])) {
1004  argc--;
1005  argv++;
1006  }
1007  std::string rpcPass;
1008  if (gArgs.GetBoolArg("-stdinrpcpass", false)) {
1009  NO_STDIN_ECHO();
1010  if (!StdinReady()) {
1011  fputs("RPC password> ", stderr);
1012  fflush(stderr);
1013  }
1014  if (!std::getline(std::cin, rpcPass)) {
1015  throw std::runtime_error("-stdinrpcpass specified but failed "
1016  "to read from standard input");
1017  }
1018  if (StdinTerminal()) {
1019  fputc('\n', stdout);
1020  }
1021  gArgs.ForceSetArg("-rpcpassword", rpcPass);
1022  }
1023  std::vector<std::string> args =
1024  std::vector<std::string>(&argv[1], &argv[argc]);
1025  if (gArgs.GetBoolArg("-stdinwalletpassphrase", false)) {
1026  NO_STDIN_ECHO();
1027  std::string walletPass;
1028  if (args.size() < 1 ||
1029  args[0].substr(0, 16) != "walletpassphrase") {
1030  throw std::runtime_error(
1031  "-stdinwalletpassphrase is only applicable for "
1032  "walletpassphrase(change)");
1033  }
1034  if (!StdinReady()) {
1035  fputs("Wallet passphrase> ", stderr);
1036  fflush(stderr);
1037  }
1038  if (!std::getline(std::cin, walletPass)) {
1039  throw std::runtime_error("-stdinwalletpassphrase specified but "
1040  "failed to read from standard input");
1041  }
1042  if (StdinTerminal()) {
1043  fputc('\n', stdout);
1044  }
1045  args.insert(args.begin() + 1, walletPass);
1046  }
1047  if (gArgs.GetBoolArg("-stdin", false)) {
1048  // Read one arg per line from stdin and append
1049  std::string line;
1050  while (std::getline(std::cin, line)) {
1051  args.push_back(line);
1052  }
1053  if (StdinTerminal()) {
1054  fputc('\n', stdout);
1055  }
1056  }
1057  std::unique_ptr<BaseRequestHandler> rh;
1058  std::string method;
1059  if (gArgs.IsArgSet("-getinfo")) {
1060  rh.reset(new GetinfoRequestHandler());
1061  } else if (gArgs.GetBoolArg("-generate", false)) {
1063  const UniValue &error{getnewaddress.find_value("error")};
1064  if (error.isNull()) {
1066  getnewaddress.find_value("result").get_str(), args);
1067  rh.reset(new GenerateToAddressRequestHandler());
1068  } else {
1069  ParseError(error, strPrint, nRet);
1070  }
1071  } else if (gArgs.GetBoolArg("-netinfo", false)) {
1072  rh.reset(new NetinfoRequestHandler());
1073  } else {
1074  rh.reset(new DefaultRequestHandler());
1075  if (args.size() < 1) {
1076  throw std::runtime_error(
1077  "too few parameters (need at least command)");
1078  }
1079  method = args[0];
1080  // Remove trailing method name from arguments vector
1081  args.erase(args.begin());
1082  }
1083 
1084  if (nRet == 0) {
1085  // Perform RPC call
1086  std::optional<std::string> wallet_name{};
1087  if (gArgs.IsArgSet("-rpcwallet")) {
1088  wallet_name = gArgs.GetArg("-rpcwallet", "");
1089  }
1090  const UniValue reply =
1091  ConnectAndCallRPC(rh.get(), method, args, wallet_name);
1092 
1093  // Parse reply
1094  UniValue result = reply.find_value("result");
1095  const UniValue &error = reply.find_value("error");
1096  if (error.isNull()) {
1097  if (gArgs.IsArgSet("-getinfo") &&
1098  !gArgs.IsArgSet("-rpcwallet")) {
1099  // fetch multiwallet balances and append to result
1100  GetWalletBalances(result);
1101  }
1102  ParseResult(result, strPrint);
1103  } else {
1104  ParseError(error, strPrint, nRet);
1105  }
1106  }
1107  } catch (const std::exception &e) {
1108  strPrint = std::string("error: ") + e.what();
1109  nRet = EXIT_FAILURE;
1110  } catch (...) {
1111  PrintExceptionContinue(nullptr, "CommandLineRPC()");
1112  throw;
1113  }
1114 
1115  if (strPrint != "") {
1116  tfm::format(nRet == 0 ? std::cout : std::cerr, "%s\n", strPrint);
1117  }
1118  return nRet;
1119 }
1120 
1121 #ifdef WIN32
1122 // Export main() and ensure working ASLR on Windows.
1123 // Exporting a symbol will prevent the linker from stripping
1124 // the .reloc section from the binary, which is a requirement
1125 // for ASLR. This is a temporary workaround until a fixed
1126 // version of binutils is used for releases.
1127 __declspec(dllexport) int main(int argc, char *argv[]) {
1128  util::WinCmdLineArgs winArgs;
1129  std::tie(argc, argv) = winArgs.get();
1130 #else
1131 int main(int argc, char *argv[]) {
1132 #endif
1133  SetupEnvironment();
1134  if (!SetupNetworking()) {
1135  tfm::format(std::cerr, "Error: Initializing networking failed\n");
1136  return EXIT_FAILURE;
1137  }
1138  event_set_log_callback(&libevent_log_cb);
1139 
1140  try {
1141  int ret = AppInitRPC(argc, argv);
1142  if (ret != CONTINUE_EXECUTION) {
1143  return ret;
1144  }
1145  } catch (const std::exception &e) {
1146  PrintExceptionContinue(&e, "AppInitRPC()");
1147  return EXIT_FAILURE;
1148  } catch (...) {
1149  PrintExceptionContinue(nullptr, "AppInitRPC()");
1150  return EXIT_FAILURE;
1151  }
1152 
1153  int ret = EXIT_FAILURE;
1154  try {
1155  ret = CommandLineRPC(argc, argv);
1156  } catch (const std::exception &e) {
1157  PrintExceptionContinue(&e, "CommandLineRPC()");
1158  } catch (...) {
1159  PrintExceptionContinue(nullptr, "CommandLineRPC()");
1160  }
1161  return ret;
1162 }
secp256k1_context * ctx
static const char DEFAULT_RPCCONNECT[]
Definition: bitcoin-cli.cpp:45
int main(int argc, char *argv[])
static const int CONTINUE_EXECUTION
Definition: bitcoin-cli.cpp:48
static int AppInitRPC(int argc, char *argv[])
static void ParseError(const UniValue &error, std::string &strPrint, int &nRet)
Parse UniValue error to update the message to print to std::cerr and the code to return.
static int CommandLineRPC(int argc, char *argv[])
static const int DEFAULT_HTTP_CLIENT_TIMEOUT
Definition: bitcoin-cli.cpp:46
static void http_request_done(struct evhttp_request *req, void *ctx)
const std::function< std::string(const char *)> G_TRANSLATION_FUN
Translate string to current locale using Qt.
Definition: bitcoin-cli.cpp:43
static void ParseResult(const UniValue &result, std::string &strPrint)
Parse UniValue result to update the message to print to std::cout.
static const std::string DEFAULT_NBLOCKS
Default number of blocks to generate for RPC generatetoaddress.
Definition: bitcoin-cli.cpp:50
static UniValue ConnectAndCallRPC(BaseRequestHandler *rh, const std::string &strMethod, const std::vector< std::string > &args, const std::optional< std::string > &rpcwallet={})
ConnectAndCallRPC wraps CallRPC with -rpcwait and an exception handler.
static void SetGenerateToAddressArgs(const std::string &address, std::vector< std::string > &args)
Check bounds and set up args for RPC generatetoaddress params: nblocks, address, maxtries.
static void GetWalletBalances(UniValue &result)
GetWalletBalances calls listwallets; if more than one wallet is loaded, it then fetches mine....
static void SetupCliArgs(ArgsManager &argsman)
Definition: bitcoin-cli.cpp:52
std::chrono::system_clock CliClock
Definition: bitcoin-cli.cpp:41
#define EVENT_LOG_ERR
static std::string http_errorstring(int code)
static void libevent_log_cb(int severity, const char *msg)
libevent event log callback
static const bool DEFAULT_NAMED
Definition: bitcoin-cli.cpp:47
static UniValue CallRPC(BaseRequestHandler *rh, const std::string &strMethod, const std::vector< std::string > &args, const std::optional< std::string > &rpcwallet={})
static UniValue GetNewAddress()
Call RPC getnewaddress.
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
void SetupChainParamsBaseOptions(ArgsManager &argsman)
Set the arguments for chainparams.
void SelectBaseParams(const std::string &chain)
Sets the params returned by Params() to those for the given network.
std::unique_ptr< CBaseChainParams > CreateBaseChainParams(const std::string &chain)
Port numbers for incoming Tor connections (8334, 18334, 38334, 18445) have been chosen arbitrarily to...
@ NETWORK_ONLY
Definition: system.h:166
@ ALLOW_ANY
Definition: system.h:159
@ ALLOW_INT
Definition: system.h:157
void ForceSetArg(const std::string &strArg, const std::string &strValue)
Definition: system.cpp:706
bool ParseParameters(int argc, const char *const argv[], std::string &error)
Definition: system.cpp:322
std::string GetHelpMessage() const
Get the help string.
Definition: system.cpp:762
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:490
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: system.cpp:635
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:603
bool ReadConfigFiles(std::string &error, bool ignore_invalid_keys=false)
Definition: system.cpp:1021
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:665
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
Definition: system.cpp:729
std::string GetChainName() const
Looks for -regtest, -testnet and returns the appropriate BIP70 chain name.
Definition: system.cpp:1123
Class that handles the conversion from a command-line to a JSON-RPC request, as well as converting ba...
virtual ~BaseRequestHandler()
virtual UniValue ProcessReply(const UniValue &batch_in)=0
virtual UniValue PrepareRequest(const std::string &method, const std::vector< std::string > &args)=0
uint16_t RPCPort() const
static const std::string REGTEST
static const std::string TESTNET
static const std::string MAIN
BIP70 chain name strings (main, test or regtest)
CConnectionFailed(const std::string &msg)
Process default single requests.
UniValue PrepareRequest(const std::string &method, const std::vector< std::string > &args) override
UniValue ProcessReply(const UniValue &reply) override
Process RPC generatetoaddress request.
UniValue PrepareRequest(const std::string &method, const std::vector< std::string > &args) override
UniValue ProcessReply(const UniValue &reply) override
Process getinfo requests.
UniValue PrepareRequest(const std::string &method, const std::vector< std::string > &args) override
Create a simulated getinfo request.
UniValue ProcessReply(const UniValue &batch_in) override
Collect values from the batch and form a simulated getinfo reply.
Process netinfo requests.
bool DetailsRequested() const
std::vector< Peer > m_peers
UniValue ProcessReply(const UniValue &batch_in) override
uint8_t m_details_level
Optional user-supplied arg to set dashboard details level.
std::array< std::array< uint16_t, m_networks_size+2 >, 3 > m_counts
Peer counts by (in/out/total, networks/total/block-relay)
bool IsAddressSelected() const
static constexpr int8_t UNKNOWN_NETWORK
bool IsVersionSelected() const
int8_t NetworkStringToId(const std::string &str) const
static constexpr int ID_PEERINFO
std::string ChainToString() const
const int64_t m_time_now
UniValue PrepareRequest(const std::string &method, const std::vector< std::string > &args) override
static constexpr int ID_NETWORKINFO
const std::array< std::string, m_networks_size > m_networks
std::string PingTimeToString(double seconds) const
static constexpr uint8_t m_networks_size
const std::string & get_str() const
const UniValue & find_value(std::string_view key) const
Definition: univalue.cpp:234
@ VOBJ
Definition: univalue.h:27
@ VSTR
Definition: univalue.h:27
@ VARR
Definition: univalue.h:27
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
bool isNull() const
Definition: univalue.h:89
const UniValue & get_obj() const
const std::string & getValStr() const
Definition: univalue.h:77
size_t size() const
Definition: univalue.h:80
const std::vector< UniValue > & getValues() const
bool empty() const
Definition: univalue.h:78
bool isStr() const
Definition: univalue.h:93
bool push_back(const UniValue &val)
Definition: univalue.cpp:108
bool pushKV(const std::string &key, const UniValue &val)
Definition: univalue.cpp:133
bool isNum() const
Definition: univalue.h:94
int get_int() const
UniValue RPCConvertValues(const std::string &strMethod, const std::vector< std::string > &strParams)
Convert positional arguments to command-specific RPC representation.
Definition: client.cpp:222
UniValue RPCConvertNamedValues(const std::string &strMethod, const std::vector< std::string > &strParams)
Convert named arguments to command-specific RPC representation.
Definition: client.cpp:241
std::string FormatFullVersion()
static Amount balance
void SetupCurrencyUnitOptions(ArgsManager &argsman)
Definition: currencyunit.cpp:9
raii_evhttp_request obtain_evhttp_request(void(*cb)(struct evhttp_request *, void *), void *arg)
Definition: events.h:46
raii_evhttp_connection obtain_evhttp_connection_base(struct event_base *base, std::string host, uint16_t port)
Definition: events.h:51
raii_event_base obtain_event_base()
Definition: events.h:28
static std::string strRPCUserColonPass
Definition: httprpc.cpp:68
static const uint64_t DEFAULT_MAX_TRIES
Default max iterations to try in RPC generatetodescriptor, generatetoaddress, and generateblock.
Definition: mining.h:12
static bool isNull(const AnyVoteItem &item)
Definition: processor.cpp:405
static std::string PathToString(const path &path)
Convert path object to byte string.
Definition: fs.h:142
Implement std::hash so RCUPtr can be used as a key for maps or sets.
Definition: rcu.h:257
void format(std::ostream &out, const char *fmt, const Args &...args)
Format list of arguments to the stream according to given format string.
Definition: tinyformat.h:1112
Response response
Definition: processor.cpp:490
std::vector< UniValue > JSONRPCProcessBatchReply(const UniValue &in)
Parse JSON-RPC batch reply into a vector.
Definition: request.cpp:143
bool GetAuthCookie(std::string *cookie_out)
Read the RPC authentication cookie from disk.
Definition: request.cpp:117
UniValue JSONRPCRequestObj(const std::string &strMethod, const UniValue &params, const UniValue &id)
JSON-RPC protocol.
Definition: request.cpp:29
UniValue JSONRPCReplyObj(const UniValue &result, const UniValue &error, const UniValue &id)
Definition: request.cpp:38
static RPCHelpMan ping()
Definition: net.cpp:56
@ HTTP_BAD_REQUEST
Definition: protocol.h:12
@ HTTP_SERVICE_UNAVAILABLE
Definition: protocol.h:18
@ HTTP_UNAUTHORIZED
Definition: protocol.h:13
@ HTTP_NOT_FOUND
Definition: protocol.h:15
@ HTTP_INTERNAL_SERVER_ERROR
Definition: protocol.h:17
@ RPC_WALLET_NOT_SPECIFIED
No wallet specified (error when there are multiple wallets loaded)
Definition: protocol.h:111
@ RPC_IN_WARMUP
Client still warming up.
Definition: protocol.h:58
static RPCHelpMan getnewaddress()
Definition: rpcwallet.cpp:95
static RPCHelpMan listwallets()
Definition: rpcwallet.cpp:2645
static RPCHelpMan getbalances()
Definition: rpcwallet.cpp:2375
bool StdinReady()
Definition: stdin.cpp:54
bool StdinTerminal()
Definition: stdin.cpp:46
#define NO_STDIN_ECHO()
Definition: stdin.h:13
std::string EncodeBase64(Span< const uint8_t > input)
void SplitHostPort(std::string in, uint16_t &portOut, std::string &hostOut)
bool ParseUInt8(const std::string &str, uint8_t *out)
Convert decimal string to unsigned 8-bit integer with strict parse error feedback.
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:87
Reply structure for request_done to fill in.
std::string body
bool operator<(const Peer &rhs) const
bool HelpRequested(const ArgsManager &args)
Definition: system.cpp:841
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
Definition: system.cpp:846
bool CheckDataDirOption()
Definition: system.cpp:917
bool SetupNetworking()
Definition: system.cpp:1426
ArgsManager gArgs
Definition: system.cpp:80
void SetupEnvironment()
Definition: system.cpp:1398
fs::path GetConfigFile(const std::string &confPath)
Definition: system.cpp:922
void PrintExceptionContinue(const std::exception *pex, const char *pszThread)
Definition: system.cpp:886
const char *const BITCOIN_CONF_FILENAME
Definition: system.cpp:77
bool error(const char *fmt, const Args &...args)
Definition: system.h:45
bool IsSwitchChar(char c)
Definition: system.h:108
void UninterruptibleSleep(const std::chrono::microseconds &n)
Definition: time.cpp:23
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1202
const UniValue NullUniValue
Definition: univalue.cpp:13
assert(!tx.IsCoinBase())