Bitcoin Core  0.20.99
P2P Digital Currency
bitcoin-cli.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2020 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 <chainparamsbase.h>
11 #include <clientversion.h>
12 #include <optional.h>
13 #include <rpc/client.h>
14 #include <rpc/mining.h>
15 #include <rpc/protocol.h>
16 #include <rpc/request.h>
17 #include <util/strencodings.h>
18 #include <util/system.h>
19 #include <util/translation.h>
20 #include <util/url.h>
21 
22 #include <functional>
23 #include <memory>
24 #include <stdio.h>
25 #include <string>
26 #include <tuple>
27 
28 #include <event2/buffer.h>
29 #include <event2/keyvalq_struct.h>
30 #include <support/events.h>
31 
32 #include <univalue.h>
33 #include <compat/stdin.h>
34 
35 const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr;
37 
38 static const char DEFAULT_RPCCONNECT[] = "127.0.0.1";
39 static const int DEFAULT_HTTP_CLIENT_TIMEOUT=900;
40 static const bool DEFAULT_NAMED=false;
41 static const int CONTINUE_EXECUTION=-1;
42 
44 static const std::string DEFAULT_NBLOCKS = "1";
45 
46 static void SetupCliArgs(ArgsManager& argsman)
47 {
48  SetupHelpOptions(argsman);
49 
50  const auto defaultBaseParams = CreateBaseChainParams(CBaseChainParams::MAIN);
51  const auto testnetBaseParams = CreateBaseChainParams(CBaseChainParams::TESTNET);
52  const auto signetBaseParams = CreateBaseChainParams(CBaseChainParams::SIGNET);
53  const auto regtestBaseParams = CreateBaseChainParams(CBaseChainParams::REGTEST);
54 
55  argsman.AddArg("-version", "Print version and exit", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
56  argsman.AddArg("-conf=<file>", strprintf("Specify configuration file. Relative paths will be prefixed by datadir location. (default: %s)", BITCOIN_CONF_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
57  argsman.AddArg("-datadir=<dir>", "Specify data directory", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
58  argsman.AddArg("-generate", strprintf("Generate blocks immediately, equivalent to RPC generatenewaddress followed by RPC generatetoaddress. Optional positional integer arguments are number of blocks to generate (default: %s) and maximum iterations to try (default: %s), equivalent to RPC generatetoaddress nblocks and maxtries arguments. Example: bitcoin-cli -generate 4 1000", DEFAULT_NBLOCKS, DEFAULT_MAX_TRIES), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
59  argsman.AddArg("-getinfo", "Get general information from the remote server. Note that unlike server-side RPC calls, the results of -getinfo is the result of multiple non-atomic requests. Some entries in the result may represent results from different states (e.g. wallet balance may be as of a different block from the chain state reported)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
60  argsman.AddArg("-netinfo", "Get network peer connection information from the remote server. An optional integer argument from 0 to 4 can be passed for different peers listings (default: 0).", ArgsManager::ALLOW_INT, OptionsCategory::OPTIONS);
61 
63  argsman.AddArg("-named", strprintf("Pass named instead of positional arguments (default: %s)", DEFAULT_NAMED), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
64  argsman.AddArg("-rpcclienttimeout=<n>", strprintf("Timeout in seconds during HTTP requests, or 0 for no timeout. (default: %d)", DEFAULT_HTTP_CLIENT_TIMEOUT), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
65  argsman.AddArg("-rpcconnect=<ip>", strprintf("Send commands to node running on <ip> (default: %s)", DEFAULT_RPCCONNECT), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
66  argsman.AddArg("-rpccookiefile=<loc>", "Location of the auth cookie. Relative paths will be prefixed by a net-specific datadir location. (default: data dir)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
67  argsman.AddArg("-rpcpassword=<pw>", "Password for JSON-RPC connections", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
68  argsman.AddArg("-rpcport=<port>", strprintf("Connect to JSON-RPC on <port> (default: %u, testnet: %u, signet: %u, regtest: %u)", defaultBaseParams->RPCPort(), testnetBaseParams->RPCPort(), signetBaseParams->RPCPort(), regtestBaseParams->RPCPort()), ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::OPTIONS);
69  argsman.AddArg("-rpcuser=<user>", "Username for JSON-RPC connections", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
70  argsman.AddArg("-rpcwait", "Wait for RPC server to start", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
71  argsman.AddArg("-rpcwallet=<walletname>", "Send RPC for non-default wallet on RPC server (needs to exactly match corresponding -wallet option passed to bitcoind). This changes the RPC endpoint used, e.g. http://127.0.0.1:8332/wallet/<walletname>", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
72  argsman.AddArg("-stdin", "Read extra arguments from standard input, one per line until EOF/Ctrl-D (recommended for sensitive information such as passphrases). When combined with -stdinrpcpass, the first line from standard input is used for the RPC password.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
73  argsman.AddArg("-stdinrpcpass", "Read RPC password from standard input as a single line. When combined with -stdin, the first line from standard input is used for the RPC password. When combined with -stdinwalletpassphrase, -stdinrpcpass consumes the first line, and -stdinwalletpassphrase consumes the second.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
74  argsman.AddArg("-stdinwalletpassphrase", "Read wallet passphrase from standard input as a single line. When combined with -stdin, the first line from standard input is used for the wallet passphrase.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
75 }
76 
78 static void libevent_log_cb(int severity, const char *msg)
79 {
80 #ifndef EVENT_LOG_ERR // EVENT_LOG_ERR was added in 2.0.19; but before then _EVENT_LOG_ERR existed.
81 # define EVENT_LOG_ERR _EVENT_LOG_ERR
82 #endif
83  // Ignore everything other than errors
84  if (severity >= EVENT_LOG_ERR) {
85  throw std::runtime_error(strprintf("libevent error: %s", msg));
86  }
87 }
88 
89 //
90 // Exception thrown on connection error. This error is used to determine
91 // when to wait if -rpcwait is given.
92 //
93 class CConnectionFailed : public std::runtime_error
94 {
95 public:
96 
97  explicit inline CConnectionFailed(const std::string& msg) :
98  std::runtime_error(msg)
99  {}
100 
101 };
102 
103 //
104 // This function returns either one of EXIT_ codes when it's expected to stop the process or
105 // CONTINUE_EXECUTION when it's expected to continue further.
106 //
107 static int AppInitRPC(int argc, char* argv[])
108 {
110  std::string error;
111  if (!gArgs.ParseParameters(argc, argv, error)) {
112  tfm::format(std::cerr, "Error parsing command line arguments: %s\n", error);
113  return EXIT_FAILURE;
114  }
115  if (argc < 2 || HelpRequested(gArgs) || gArgs.IsArgSet("-version")) {
116  std::string strUsage = PACKAGE_NAME " RPC client version " + FormatFullVersion() + "\n";
117  if (!gArgs.IsArgSet("-version")) {
118  strUsage += "\n"
119  "Usage: bitcoin-cli [options] <command> [params] Send command to " PACKAGE_NAME "\n"
120  "or: bitcoin-cli [options] -named <command> [name=value]... Send command to " PACKAGE_NAME " (with named arguments)\n"
121  "or: bitcoin-cli [options] help List commands\n"
122  "or: bitcoin-cli [options] help <command> Get help for a command\n";
123  strUsage += "\n" + gArgs.GetHelpMessage();
124  }
125 
126  tfm::format(std::cout, "%s", strUsage);
127  if (argc < 2) {
128  tfm::format(std::cerr, "Error: too few parameters\n");
129  return EXIT_FAILURE;
130  }
131  return EXIT_SUCCESS;
132  }
133  if (!CheckDataDirOption()) {
134  tfm::format(std::cerr, "Error: Specified data directory \"%s\" does not exist.\n", gArgs.GetArg("-datadir", ""));
135  return EXIT_FAILURE;
136  }
137  if (!gArgs.ReadConfigFiles(error, true)) {
138  tfm::format(std::cerr, "Error reading configuration file: %s\n", error);
139  return EXIT_FAILURE;
140  }
141  // Check for chain settings (BaseParams() calls are only valid after this clause)
142  try {
144  } catch (const std::exception& e) {
145  tfm::format(std::cerr, "Error: %s\n", e.what());
146  return EXIT_FAILURE;
147  }
148  return CONTINUE_EXECUTION;
149 }
150 
151 
153 struct HTTPReply
154 {
155  HTTPReply(): status(0), error(-1) {}
156 
157  int status;
158  int error;
159  std::string body;
160 };
161 
162 static std::string http_errorstring(int code)
163 {
164  switch(code) {
165 #if LIBEVENT_VERSION_NUMBER >= 0x02010300
166  case EVREQ_HTTP_TIMEOUT:
167  return "timeout reached";
168  case EVREQ_HTTP_EOF:
169  return "EOF reached";
170  case EVREQ_HTTP_INVALID_HEADER:
171  return "error while reading header, or invalid header";
172  case EVREQ_HTTP_BUFFER_ERROR:
173  return "error encountered while reading or writing";
174  case EVREQ_HTTP_REQUEST_CANCEL:
175  return "request was canceled";
176  case EVREQ_HTTP_DATA_TOO_LONG:
177  return "response body is larger than allowed";
178 #endif
179  default:
180  return "unknown";
181  }
182 }
183 
184 static void http_request_done(struct evhttp_request *req, void *ctx)
185 {
186  HTTPReply *reply = static_cast<HTTPReply*>(ctx);
187 
188  if (req == nullptr) {
189  /* If req is nullptr, it means an error occurred while connecting: the
190  * error code will have been passed to http_error_cb.
191  */
192  reply->status = 0;
193  return;
194  }
195 
196  reply->status = evhttp_request_get_response_code(req);
197 
198  struct evbuffer *buf = evhttp_request_get_input_buffer(req);
199  if (buf)
200  {
201  size_t size = evbuffer_get_length(buf);
202  const char *data = (const char*)evbuffer_pullup(buf, size);
203  if (data)
204  reply->body = std::string(data, size);
205  evbuffer_drain(buf, size);
206  }
207 }
208 
209 #if LIBEVENT_VERSION_NUMBER >= 0x02010300
210 static void http_error_cb(enum evhttp_request_error err, void *ctx)
211 {
212  HTTPReply *reply = static_cast<HTTPReply*>(ctx);
213  reply->error = err;
214 }
215 #endif
216 
221 {
222 public:
223  virtual ~BaseRequestHandler() {}
224  virtual UniValue PrepareRequest(const std::string& method, const std::vector<std::string>& args) = 0;
225  virtual UniValue ProcessReply(const UniValue &batch_in) = 0;
226 };
227 
230 {
231 public:
232  const int ID_NETWORKINFO = 0;
233  const int ID_BLOCKCHAININFO = 1;
234  const int ID_WALLETINFO = 2;
235  const int ID_BALANCES = 3;
236 
238  UniValue PrepareRequest(const std::string& method, const std::vector<std::string>& args) override
239  {
240  if (!args.empty()) {
241  throw std::runtime_error("-getinfo takes no arguments");
242  }
243  UniValue result(UniValue::VARR);
244  result.push_back(JSONRPCRequestObj("getnetworkinfo", NullUniValue, ID_NETWORKINFO));
245  result.push_back(JSONRPCRequestObj("getblockchaininfo", NullUniValue, ID_BLOCKCHAININFO));
246  result.push_back(JSONRPCRequestObj("getwalletinfo", NullUniValue, ID_WALLETINFO));
247  result.push_back(JSONRPCRequestObj("getbalances", NullUniValue, ID_BALANCES));
248  return result;
249  }
250 
252  UniValue ProcessReply(const UniValue &batch_in) override
253  {
254  UniValue result(UniValue::VOBJ);
255  const std::vector<UniValue> batch = JSONRPCProcessBatchReply(batch_in);
256  // Errors in getnetworkinfo() and getblockchaininfo() are fatal, pass them on;
257  // getwalletinfo() and getbalances() are allowed to fail if there is no wallet.
258  if (!batch[ID_NETWORKINFO]["error"].isNull()) {
259  return batch[ID_NETWORKINFO];
260  }
261  if (!batch[ID_BLOCKCHAININFO]["error"].isNull()) {
262  return batch[ID_BLOCKCHAININFO];
263  }
264  result.pushKV("version", batch[ID_NETWORKINFO]["result"]["version"]);
265  result.pushKV("blocks", batch[ID_BLOCKCHAININFO]["result"]["blocks"]);
266  result.pushKV("headers", batch[ID_BLOCKCHAININFO]["result"]["headers"]);
267  result.pushKV("verificationprogress", batch[ID_BLOCKCHAININFO]["result"]["verificationprogress"]);
268  result.pushKV("timeoffset", batch[ID_NETWORKINFO]["result"]["timeoffset"]);
269 
270  UniValue connections(UniValue::VOBJ);
271  connections.pushKV("in", batch[ID_NETWORKINFO]["result"]["connections_in"]);
272  connections.pushKV("out", batch[ID_NETWORKINFO]["result"]["connections_out"]);
273  connections.pushKV("total", batch[ID_NETWORKINFO]["result"]["connections"]);
274  result.pushKV("connections", connections);
275 
276  result.pushKV("proxy", batch[ID_NETWORKINFO]["result"]["networks"][0]["proxy"]);
277  result.pushKV("difficulty", batch[ID_BLOCKCHAININFO]["result"]["difficulty"]);
278  result.pushKV("chain", UniValue(batch[ID_BLOCKCHAININFO]["result"]["chain"]));
279  if (!batch[ID_WALLETINFO]["result"].isNull()) {
280  result.pushKV("keypoolsize", batch[ID_WALLETINFO]["result"]["keypoolsize"]);
281  if (!batch[ID_WALLETINFO]["result"]["unlocked_until"].isNull()) {
282  result.pushKV("unlocked_until", batch[ID_WALLETINFO]["result"]["unlocked_until"]);
283  }
284  result.pushKV("paytxfee", batch[ID_WALLETINFO]["result"]["paytxfee"]);
285  }
286  if (!batch[ID_BALANCES]["result"].isNull()) {
287  result.pushKV("balance", batch[ID_BALANCES]["result"]["mine"]["trusted"]);
288  }
289  result.pushKV("relayfee", batch[ID_NETWORKINFO]["result"]["relayfee"]);
290  result.pushKV("warnings", batch[ID_NETWORKINFO]["result"]["warnings"]);
291  return JSONRPCReplyObj(result, NullUniValue, 1);
292  }
293 };
294 
297 {
298 private:
299  static constexpr int8_t UNKNOWN_NETWORK{-1};
300  static constexpr size_t m_networks_size{3};
301  const std::array<std::string, m_networks_size> m_networks{{"ipv4", "ipv6", "onion"}};
302  std::array<std::array<uint16_t, m_networks_size + 2>, 3> m_counts{{{}}};
303  int8_t NetworkStringToId(const std::string& str) const
304  {
305  for (size_t i = 0; i < m_networks_size; ++i) {
306  if (str == m_networks.at(i)) return i;
307  }
308  return UNKNOWN_NETWORK;
309  }
310  uint8_t m_details_level{0};
311  bool DetailsRequested() const { return m_details_level > 0 && m_details_level < 5; }
312  bool IsAddressSelected() const { return m_details_level == 2 || m_details_level == 4; }
313  bool IsVersionSelected() const { return m_details_level == 3 || m_details_level == 4; }
314  bool m_is_asmap_on{false};
315  size_t m_max_addr_length{0};
316  size_t m_max_id_length{2};
317  struct Peer {
318  int id;
320  int version;
321  int64_t conn_time;
322  int64_t last_blck;
323  int64_t last_recv;
324  int64_t last_send;
325  int64_t last_trxn;
326  double min_ping;
327  double ping;
328  std::string addr;
329  std::string network;
330  std::string sub_version;
333  bool operator<(const Peer& rhs) const { return std::tie(is_outbound, min_ping) < std::tie(rhs.is_outbound, rhs.min_ping); }
334  };
335  std::vector<Peer> m_peers;
336  std::string ChainToString() const
337  {
338  if (gArgs.GetChainName() == CBaseChainParams::TESTNET) return " testnet";
339  if (gArgs.GetChainName() == CBaseChainParams::REGTEST) return " regtest";
340  return "";
341  }
342  const int64_t m_time_now{GetSystemTimeInSeconds()};
343 
344 public:
345  static constexpr int ID_PEERINFO = 0;
346  static constexpr int ID_NETWORKINFO = 1;
347 
348  UniValue PrepareRequest(const std::string& method, const std::vector<std::string>& args) override
349  {
350  if (!args.empty()) {
351  uint8_t n{0};
352  if (ParseUInt8(args.at(0), &n)) {
353  m_details_level = n;
354  }
355  }
356  UniValue result(UniValue::VARR);
357  result.push_back(JSONRPCRequestObj("getpeerinfo", NullUniValue, ID_PEERINFO));
358  result.push_back(JSONRPCRequestObj("getnetworkinfo", NullUniValue, ID_NETWORKINFO));
359  return result;
360  }
361 
362  UniValue ProcessReply(const UniValue& batch_in) override
363  {
364  const std::vector<UniValue> batch{JSONRPCProcessBatchReply(batch_in)};
365  if (!batch[ID_PEERINFO]["error"].isNull()) return batch[ID_PEERINFO];
366  if (!batch[ID_NETWORKINFO]["error"].isNull()) return batch[ID_NETWORKINFO];
367 
368  const UniValue& networkinfo{batch[ID_NETWORKINFO]["result"]};
369  if (networkinfo["version"].get_int() < 209900) {
370  throw std::runtime_error("-netinfo requires bitcoind server to be running v0.21.0 and up");
371  }
372 
373  // Count peer connection totals, and if DetailsRequested(), store peer data in a vector of structs.
374  for (const UniValue& peer : batch[ID_PEERINFO]["result"].getValues()) {
375  const std::string network{peer["network"].get_str()};
376  const int8_t network_id{NetworkStringToId(network)};
377  if (network_id == UNKNOWN_NETWORK) continue;
378  const bool is_outbound{!peer["inbound"].get_bool()};
379  const bool is_block_relay{!peer["relaytxes"].get_bool()};
380  ++m_counts.at(is_outbound).at(network_id); // in/out by network
381  ++m_counts.at(is_outbound).at(m_networks_size); // in/out overall
382  ++m_counts.at(2).at(network_id); // total by network
383  ++m_counts.at(2).at(m_networks_size); // total overall
384  if (is_block_relay) {
385  ++m_counts.at(is_outbound).at(m_networks_size + 1); // in/out block-relay
386  ++m_counts.at(2).at(m_networks_size + 1); // total block-relay
387  }
388  if (DetailsRequested()) {
389  // Push data for this peer to the peers vector.
390  const int peer_id{peer["id"].get_int()};
391  const int mapped_as{peer["mapped_as"].isNull() ? 0 : peer["mapped_as"].get_int()};
392  const int version{peer["version"].get_int()};
393  const int64_t conn_time{peer["conntime"].get_int64()};
394  const int64_t last_blck{peer["last_block"].get_int64()};
395  const int64_t last_recv{peer["lastrecv"].get_int64()};
396  const int64_t last_send{peer["lastsend"].get_int64()};
397  const int64_t last_trxn{peer["last_transaction"].get_int64()};
398  const double min_ping{peer["minping"].isNull() ? -1 : peer["minping"].get_real()};
399  const double ping{peer["pingtime"].isNull() ? -1 : peer["pingtime"].get_real()};
400  const std::string addr{peer["addr"].get_str()};
401  const std::string sub_version{peer["subver"].get_str()};
402  m_peers.push_back({peer_id, mapped_as, version, conn_time, last_blck, last_recv, last_send, last_trxn, min_ping, ping, addr, network, sub_version, is_block_relay, is_outbound});
403  m_max_id_length = std::max(ToString(peer_id).length(), m_max_id_length);
404  m_max_addr_length = std::max(addr.length() + 1, m_max_addr_length);
405  m_is_asmap_on |= (mapped_as != 0);
406  }
407  }
408 
409  // Generate report header.
410  std::string result{strprintf("%s %s%s - %i%s\n\n", PACKAGE_NAME, FormatFullVersion(), ChainToString(), networkinfo["protocolversion"].get_int(), networkinfo["subversion"].get_str())};
411 
412  // Report detailed peer connections list sorted by direction and minimum ping time.
413  if (DetailsRequested() && !m_peers.empty()) {
414  std::sort(m_peers.begin(), m_peers.end());
415  result += "Peer connections sorted by direction and min ping\n<-> relay net mping ping send recv txn blk uptime ";
416  if (m_is_asmap_on) result += " asmap ";
417  result += strprintf("%*s %-*s%s\n", m_max_id_length, "id", IsAddressSelected() ? m_max_addr_length : 0, IsAddressSelected() ? "address" : "", IsVersionSelected() ? "version" : "");
418  for (const Peer& peer : m_peers) {
419  std::string version{ToString(peer.version) + peer.sub_version};
420  result += strprintf(
421  "%3s %5s %5s%6s%7s%5s%5s%5s%5s%7s%*i %*s %-*s%s\n",
422  peer.is_outbound ? "out" : "in",
423  peer.is_block_relay ? "block" : "full",
424  peer.network,
425  peer.min_ping == -1 ? "" : ToString(round(1000 * peer.min_ping)),
426  peer.ping == -1 ? "" : ToString(round(1000 * peer.ping)),
427  peer.last_send == 0 ? "" : ToString(m_time_now - peer.last_send),
428  peer.last_recv == 0 ? "" : ToString(m_time_now - peer.last_recv),
429  peer.last_trxn == 0 ? "" : ToString((m_time_now - peer.last_trxn) / 60),
430  peer.last_blck == 0 ? "" : ToString((m_time_now - peer.last_blck) / 60),
431  peer.conn_time == 0 ? "" : ToString((m_time_now - peer.conn_time) / 60),
432  m_is_asmap_on ? 7 : 0, // variable spacing
433  m_is_asmap_on && peer.mapped_as != 0 ? ToString(peer.mapped_as) : "",
434  m_max_id_length, // variable spacing
435  peer.id,
436  IsAddressSelected() ? m_max_addr_length : 0, // variable spacing
437  IsAddressSelected() ? peer.addr : "",
438  IsVersionSelected() && version != "0" ? version : "");
439  }
440  result += " ms ms sec sec min min min\n\n";
441  }
442 
443  // Report peer connection totals by type.
444  result += " ipv4 ipv6 onion total block-relay\n";
445  const std::array<std::string, 3> rows{{"in", "out", "total"}};
446  for (size_t i = 0; i < m_networks_size; ++i) {
447  result += strprintf("%-5s %5i %5i %5i %5i %5i\n", rows.at(i), m_counts.at(i).at(0), m_counts.at(i).at(1), m_counts.at(i).at(2), m_counts.at(i).at(m_networks_size), m_counts.at(i).at(m_networks_size + 1));
448  }
449 
450  // Report local addresses, ports, and scores.
451  result += "\nLocal addresses";
452  const UniValue& local_addrs{networkinfo["localaddresses"]};
453  if (local_addrs.empty()) {
454  result += ": n/a\n";
455  } else {
456  for (const UniValue& addr : local_addrs.getValues()) {
457  result += strprintf("\n%-40i port %5i score %6i", addr["address"].get_str(), addr["port"].get_int(), addr["score"].get_int());
458  }
459  }
460 
461  return JSONRPCReplyObj(UniValue{result}, NullUniValue, 1);
462  }
463 };
464 
467 {
468 public:
469  UniValue PrepareRequest(const std::string& method, const std::vector<std::string>& args) override
470  {
471  address_str = args.at(1);
472  UniValue params{RPCConvertValues("generatetoaddress", args)};
473  return JSONRPCRequestObj("generatetoaddress", params, 1);
474  }
475 
476  UniValue ProcessReply(const UniValue &reply) override
477  {
478  UniValue result(UniValue::VOBJ);
479  result.pushKV("address", address_str);
480  result.pushKV("blocks", reply.get_obj()["result"]);
481  return JSONRPCReplyObj(result, NullUniValue, 1);
482  }
483 protected:
484  std::string address_str;
485 };
486 
489 public:
490  UniValue PrepareRequest(const std::string& method, const std::vector<std::string>& args) override
491  {
492  UniValue params;
493  if(gArgs.GetBoolArg("-named", DEFAULT_NAMED)) {
494  params = RPCConvertNamedValues(method, args);
495  } else {
496  params = RPCConvertValues(method, args);
497  }
498  return JSONRPCRequestObj(method, params, 1);
499  }
500 
501  UniValue ProcessReply(const UniValue &reply) override
502  {
503  return reply.get_obj();
504  }
505 };
506 
507 static UniValue CallRPC(BaseRequestHandler* rh, const std::string& strMethod, const std::vector<std::string>& args, const Optional<std::string>& rpcwallet = {})
508 {
509  std::string host;
510  // In preference order, we choose the following for the port:
511  // 1. -rpcport
512  // 2. port in -rpcconnect (ie following : in ipv4 or ]: in ipv6)
513  // 3. default port for chain
514  int port = BaseParams().RPCPort();
515  SplitHostPort(gArgs.GetArg("-rpcconnect", DEFAULT_RPCCONNECT), port, host);
516  port = gArgs.GetArg("-rpcport", port);
517 
518  // Obtain event base
519  raii_event_base base = obtain_event_base();
520 
521  // Synchronously look up hostname
522  raii_evhttp_connection evcon = obtain_evhttp_connection_base(base.get(), host, port);
523 
524  // Set connection timeout
525  {
526  const int timeout = gArgs.GetArg("-rpcclienttimeout", DEFAULT_HTTP_CLIENT_TIMEOUT);
527  if (timeout > 0) {
528  evhttp_connection_set_timeout(evcon.get(), timeout);
529  } else {
530  // Indefinite request timeouts are not possible in libevent-http, so we
531  // set the timeout to a very long time period instead.
532 
533  constexpr int YEAR_IN_SECONDS = 31556952; // Average length of year in Gregorian calendar
534  evhttp_connection_set_timeout(evcon.get(), 5 * YEAR_IN_SECONDS);
535  }
536  }
537 
538  HTTPReply response;
539  raii_evhttp_request req = obtain_evhttp_request(http_request_done, (void*)&response);
540  if (req == nullptr)
541  throw std::runtime_error("create http request failed");
542 #if LIBEVENT_VERSION_NUMBER >= 0x02010300
543  evhttp_request_set_error_cb(req.get(), http_error_cb);
544 #endif
545 
546  // Get credentials
547  std::string strRPCUserColonPass;
548  bool failedToGetAuthCookie = false;
549  if (gArgs.GetArg("-rpcpassword", "") == "") {
550  // Try fall back to cookie-based authentication if no password is provided
551  if (!GetAuthCookie(&strRPCUserColonPass)) {
552  failedToGetAuthCookie = true;
553  }
554  } else {
555  strRPCUserColonPass = gArgs.GetArg("-rpcuser", "") + ":" + gArgs.GetArg("-rpcpassword", "");
556  }
557 
558  struct evkeyvalq* output_headers = evhttp_request_get_output_headers(req.get());
559  assert(output_headers);
560  evhttp_add_header(output_headers, "Host", host.c_str());
561  evhttp_add_header(output_headers, "Connection", "close");
562  evhttp_add_header(output_headers, "Content-Type", "application/json");
563  evhttp_add_header(output_headers, "Authorization", (std::string("Basic ") + EncodeBase64(strRPCUserColonPass)).c_str());
564 
565  // Attach request data
566  std::string strRequest = rh->PrepareRequest(strMethod, args).write() + "\n";
567  struct evbuffer* output_buffer = evhttp_request_get_output_buffer(req.get());
568  assert(output_buffer);
569  evbuffer_add(output_buffer, strRequest.data(), strRequest.size());
570 
571  // check if we should use a special wallet endpoint
572  std::string endpoint = "/";
573  if (rpcwallet) {
574  char* encodedURI = evhttp_uriencode(rpcwallet->data(), rpcwallet->size(), false);
575  if (encodedURI) {
576  endpoint = "/wallet/" + std::string(encodedURI);
577  free(encodedURI);
578  } else {
579  throw CConnectionFailed("uri-encode failed");
580  }
581  }
582  int r = evhttp_make_request(evcon.get(), req.get(), EVHTTP_REQ_POST, endpoint.c_str());
583  req.release(); // ownership moved to evcon in above call
584  if (r != 0) {
585  throw CConnectionFailed("send http request failed");
586  }
587 
588  event_base_dispatch(base.get());
589 
590  if (response.status == 0) {
591  std::string responseErrorMessage;
592  if (response.error != -1) {
593  responseErrorMessage = strprintf(" (error code %d - \"%s\")", response.error, http_errorstring(response.error));
594  }
595  throw CConnectionFailed(strprintf("Could not connect to the server %s:%d%s\n\nMake sure the bitcoind server is running and that you are connecting to the correct RPC port.", host, port, responseErrorMessage));
596  } else if (response.status == HTTP_UNAUTHORIZED) {
597  if (failedToGetAuthCookie) {
598  throw std::runtime_error(strprintf(
599  "Could not locate RPC credentials. No authentication cookie could be found, and RPC password is not set. See -rpcpassword and -stdinrpcpass. Configuration file: (%s)",
600  GetConfigFile(gArgs.GetArg("-conf", BITCOIN_CONF_FILENAME)).string()));
601  } else {
602  throw std::runtime_error("Authorization failed: Incorrect rpcuser or rpcpassword");
603  }
604  } else if (response.status >= 400 && response.status != HTTP_BAD_REQUEST && response.status != HTTP_NOT_FOUND && response.status != HTTP_INTERNAL_SERVER_ERROR)
605  throw std::runtime_error(strprintf("server returned HTTP error %d", response.status));
606  else if (response.body.empty())
607  throw std::runtime_error("no response from server");
608 
609  // Parse reply
610  UniValue valReply(UniValue::VSTR);
611  if (!valReply.read(response.body))
612  throw std::runtime_error("couldn't parse reply from server");
613  const UniValue reply = rh->ProcessReply(valReply);
614  if (reply.empty())
615  throw std::runtime_error("expected reply to have result, error and id properties");
616 
617  return reply;
618 }
619 
629 static UniValue ConnectAndCallRPC(BaseRequestHandler* rh, const std::string& strMethod, const std::vector<std::string>& args, const Optional<std::string>& rpcwallet = {})
630 {
631  UniValue response(UniValue::VOBJ);
632  // Execute and handle connection failures with -rpcwait.
633  const bool fWait = gArgs.GetBoolArg("-rpcwait", false);
634  do {
635  try {
636  response = CallRPC(rh, strMethod, args, rpcwallet);
637  if (fWait) {
638  const UniValue& error = find_value(response, "error");
639  if (!error.isNull() && error["code"].get_int() == RPC_IN_WARMUP) {
640  throw CConnectionFailed("server in warmup");
641  }
642  }
643  break; // Connection succeeded, no need to retry.
644  } catch (const CConnectionFailed&) {
645  if (fWait) {
646  UninterruptibleSleep(std::chrono::milliseconds{1000});
647  } else {
648  throw;
649  }
650  }
651  } while (fWait);
652  return response;
653 }
654 
656 static void ParseResult(const UniValue& result, std::string& strPrint)
657 {
658  if (result.isNull()) return;
659  strPrint = result.isStr() ? result.get_str() : result.write(2);
660 }
661 
663 static void ParseError(const UniValue& error, std::string& strPrint, int& nRet)
664 {
665  if (error.isObject()) {
666  const UniValue& err_code = find_value(error, "code");
667  const UniValue& err_msg = find_value(error, "message");
668  if (!err_code.isNull()) {
669  strPrint = "error code: " + err_code.getValStr() + "\n";
670  }
671  if (err_msg.isStr()) {
672  strPrint += ("error message:\n" + err_msg.get_str());
673  }
674  if (err_code.isNum() && err_code.get_int() == RPC_WALLET_NOT_SPECIFIED) {
675  strPrint += "\nTry adding \"-rpcwallet=<filename>\" option to bitcoin-cli command line.";
676  }
677  } else {
678  strPrint = "error: " + error.write();
679  }
680  nRet = abs(error["code"].get_int());
681 }
682 
689 static void GetWalletBalances(UniValue& result)
690 {
692  const UniValue listwallets = ConnectAndCallRPC(&rh, "listwallets", /* args=*/{});
693  if (!find_value(listwallets, "error").isNull()) return;
694  const UniValue& wallets = find_value(listwallets, "result");
695  if (wallets.size() <= 1) return;
696 
697  UniValue balances(UniValue::VOBJ);
698  for (const UniValue& wallet : wallets.getValues()) {
699  const std::string wallet_name = wallet.get_str();
700  const UniValue getbalances = ConnectAndCallRPC(&rh, "getbalances", /* args=*/{}, wallet_name);
701  const UniValue& balance = find_value(getbalances, "result")["mine"]["trusted"];
702  balances.pushKV(wallet_name, balance);
703  }
704  result.pushKV("balances", balances);
705 }
706 
712 {
713  Optional<std::string> wallet_name{};
714  if (gArgs.IsArgSet("-rpcwallet")) wallet_name = gArgs.GetArg("-rpcwallet", "");
716  return ConnectAndCallRPC(&rh, "getnewaddress", /* args=*/{}, wallet_name);
717 }
718 
724 static void SetGenerateToAddressArgs(const std::string& address, std::vector<std::string>& args)
725 {
726  if (args.size() > 2) throw std::runtime_error("too many arguments (maximum 2 for nblocks and maxtries)");
727  if (args.size() == 0) {
728  args.emplace_back(DEFAULT_NBLOCKS);
729  } else if (args.at(0) == "0") {
730  throw std::runtime_error("the first argument (number of blocks to generate, default: " + DEFAULT_NBLOCKS + ") must be an integer value greater than zero");
731  }
732  args.emplace(args.begin() + 1, address);
733 }
734 
735 static int CommandLineRPC(int argc, char *argv[])
736 {
737  std::string strPrint;
738  int nRet = 0;
739  try {
740  // Skip switches
741  while (argc > 1 && IsSwitchChar(argv[1][0])) {
742  argc--;
743  argv++;
744  }
745  std::string rpcPass;
746  if (gArgs.GetBoolArg("-stdinrpcpass", false)) {
747  NO_STDIN_ECHO();
748  if (!StdinReady()) {
749  fputs("RPC password> ", stderr);
750  fflush(stderr);
751  }
752  if (!std::getline(std::cin, rpcPass)) {
753  throw std::runtime_error("-stdinrpcpass specified but failed to read from standard input");
754  }
755  if (StdinTerminal()) {
756  fputc('\n', stdout);
757  }
758  gArgs.ForceSetArg("-rpcpassword", rpcPass);
759  }
760  std::vector<std::string> args = std::vector<std::string>(&argv[1], &argv[argc]);
761  if (gArgs.GetBoolArg("-stdinwalletpassphrase", false)) {
762  NO_STDIN_ECHO();
763  std::string walletPass;
764  if (args.size() < 1 || args[0].substr(0, 16) != "walletpassphrase") {
765  throw std::runtime_error("-stdinwalletpassphrase is only applicable for walletpassphrase(change)");
766  }
767  if (!StdinReady()) {
768  fputs("Wallet passphrase> ", stderr);
769  fflush(stderr);
770  }
771  if (!std::getline(std::cin, walletPass)) {
772  throw std::runtime_error("-stdinwalletpassphrase specified but failed to read from standard input");
773  }
774  if (StdinTerminal()) {
775  fputc('\n', stdout);
776  }
777  args.insert(args.begin() + 1, walletPass);
778  }
779  if (gArgs.GetBoolArg("-stdin", false)) {
780  // Read one arg per line from stdin and append
781  std::string line;
782  while (std::getline(std::cin, line)) {
783  args.push_back(line);
784  }
785  if (StdinTerminal()) {
786  fputc('\n', stdout);
787  }
788  }
789  std::unique_ptr<BaseRequestHandler> rh;
790  std::string method;
791  if (gArgs.IsArgSet("-getinfo")) {
792  rh.reset(new GetinfoRequestHandler());
793  } else if (gArgs.GetBoolArg("-netinfo", false)) {
794  rh.reset(new NetinfoRequestHandler());
795  } else if (gArgs.GetBoolArg("-generate", false)) {
797  const UniValue& error{find_value(getnewaddress, "error")};
798  if (error.isNull()) {
799  SetGenerateToAddressArgs(find_value(getnewaddress, "result").get_str(), args);
800  rh.reset(new GenerateToAddressRequestHandler());
801  } else {
802  ParseError(error, strPrint, nRet);
803  }
804  } else {
805  rh.reset(new DefaultRequestHandler());
806  if (args.size() < 1) {
807  throw std::runtime_error("too few parameters (need at least command)");
808  }
809  method = args[0];
810  args.erase(args.begin()); // Remove trailing method name from arguments vector
811  }
812  if (nRet == 0) {
813  // Perform RPC call
814  Optional<std::string> wallet_name{};
815  if (gArgs.IsArgSet("-rpcwallet")) wallet_name = gArgs.GetArg("-rpcwallet", "");
816  const UniValue reply = ConnectAndCallRPC(rh.get(), method, args, wallet_name);
817 
818  // Parse reply
819  UniValue result = find_value(reply, "result");
820  const UniValue& error = find_value(reply, "error");
821  if (error.isNull()) {
822  if (gArgs.IsArgSet("-getinfo") && !gArgs.IsArgSet("-rpcwallet")) {
823  GetWalletBalances(result); // fetch multiwallet balances and append to result
824  }
825  ParseResult(result, strPrint);
826  } else {
827  ParseError(error, strPrint, nRet);
828  }
829  }
830  } catch (const std::exception& e) {
831  strPrint = std::string("error: ") + e.what();
832  nRet = EXIT_FAILURE;
833  } catch (...) {
834  PrintExceptionContinue(nullptr, "CommandLineRPC()");
835  throw;
836  }
837 
838  if (strPrint != "") {
839  tfm::format(nRet == 0 ? std::cout : std::cerr, "%s\n", strPrint);
840  }
841  return nRet;
842 }
843 
844 #ifdef WIN32
845 // Export main() and ensure working ASLR on Windows.
846 // Exporting a symbol will prevent the linker from stripping
847 // the .reloc section from the binary, which is a requirement
848 // for ASLR. This is a temporary workaround until a fixed
849 // version of binutils is used for releases.
850 __declspec(dllexport) int main(int argc, char* argv[])
851 {
852  util::WinCmdLineArgs winArgs;
853  std::tie(argc, argv) = winArgs.get();
854 #else
855 int main(int argc, char* argv[])
856 {
857 #endif
859  if (!SetupNetworking()) {
860  tfm::format(std::cerr, "Error: Initializing networking failed\n");
861  return EXIT_FAILURE;
862  }
863  event_set_log_callback(&libevent_log_cb);
864 
865  try {
866  int ret = AppInitRPC(argc, argv);
867  if (ret != CONTINUE_EXECUTION)
868  return ret;
869  }
870  catch (const std::exception& e) {
871  PrintExceptionContinue(&e, "AppInitRPC()");
872  return EXIT_FAILURE;
873  } catch (...) {
874  PrintExceptionContinue(nullptr, "AppInitRPC()");
875  return EXIT_FAILURE;
876  }
877 
878  int ret = EXIT_FAILURE;
879  try {
880  ret = CommandLineRPC(argc, argv);
881  }
882  catch (const std::exception& e) {
883  PrintExceptionContinue(&e, "CommandLineRPC()");
884  } catch (...) {
885  PrintExceptionContinue(nullptr, "CommandLineRPC()");
886  }
887  return ret;
888 }
NODISCARD bool ReadConfigFiles(std::string &error, bool ignore_invalid_keys=false)
Definition: system.cpp:830
No wallet specified (error when there are multiple wallets loaded)
Definition: protocol.h:80
std::string ChainToString() const
static const std::string DEFAULT_NBLOCKS
Default number of blocks to generate for RPC generatetoaddress.
Definition: bitcoin-cli.cpp:44
bool DetailsRequested() const
static RPCHelpMan ping()
Definition: net.cpp:64
bool isObject() const
Definition: univalue.h:84
bool StdinTerminal()
Definition: stdin.cpp:47
std::unique_ptr< CBaseChainParams > CreateBaseChainParams(const std::string &chain)
Port numbers for incoming Tor connections (8334, 18334, 38334, 18445) have been chosen arbitrarily to...
bool StdinReady()
Definition: stdin.cpp:56
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:370
static int CommandLineRPC(int argc, char *argv[])
static UniValue ConnectAndCallRPC(BaseRequestHandler *rh, const std::string &strMethod, const std::vector< std::string > &args, const Optional< std::string > &rpcwallet={})
ConnectAndCallRPC wraps CallRPC with -rpcwait and an exception handler.
raii_event_base obtain_event_base()
Definition: events.h:30
void SetupChainParamsBaseOptions(ArgsManager &argsman)
Set the arguments for chainparams.
const std::vector< UniValue > & getValues() const
UniValue PrepareRequest(const std::string &method, const std::vector< std::string > &args) override
static int AppInitRPC(int argc, char *argv[])
static void libevent_log_cb(int severity, const char *msg)
libevent event log callback
Definition: bitcoin-cli.cpp:78
static const std::string REGTEST
bool read(const char *raw, size_t len)
static std::string strRPCUserColonPass
Definition: httprpc.cpp:68
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
UrlDecodeFn urlDecode
Definition: url.h:11
UniValue ProcessReply(const UniValue &reply) override
static UniValue CallRPC(BaseRequestHandler *rh, const std::string &strMethod, const std::vector< std::string > &args, const Optional< std::string > &rpcwallet={})
int8_t NetworkStringToId(const std::string &str) const
virtual ~BaseRequestHandler()
static const int DEFAULT_HTTP_CLIENT_TIMEOUT
Definition: bitcoin-cli.cpp:39
void SetupEnvironment()
Definition: system.cpp:1213
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
#define PACKAGE_NAME
const std::string & get_str() const
static RPCHelpMan listwallets()
Definition: rpcwallet.cpp:2547
bool isNum() const
Definition: univalue.h:82
raii_evhttp_request obtain_evhttp_request(void(*cb)(struct evhttp_request *, void *), void *arg)
Definition: events.h:45
NODISCARD bool ParseParameters(int argc, const char *const argv[], std::string &error)
Definition: system.cpp:283
std::vector< Peer > m_peers
bool isStr() const
Definition: univalue.h:81
static std::string http_errorstring(int code)
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:478
void ForceSetArg(const std::string &strArg, const std::string &strValue)
Definition: system.cpp:500
const char *const BITCOIN_CONF_FILENAME
Definition: system.cpp:73
bool SetupNetworking()
Definition: system.cpp:1250
int64_t GetSystemTimeInSeconds()
Returns the system time (not mockable)
Definition: time.cpp:73
const std::string & getValStr() const
Definition: univalue.h:65
Client still warming up.
Definition: protocol.h:49
bool operator<(const Peer &rhs) const
#define NO_STDIN_ECHO()
Definition: stdin.h:13
virtual UniValue ProcessReply(const UniValue &batch_in)=0
UniValue PrepareRequest(const std::string &method, const std::vector< std::string > &args) override
Create a simulated getinfo request.
const UniValue & find_value(const UniValue &obj, const std::string &name)
Definition: univalue.cpp:234
std::string GetHelpMessage() const
Get the help string.
Definition: system.cpp:532
static const std::string MAIN
Chain name strings.
UniValue RPCConvertValues(const std::string &strMethod, const std::vector< std::string > &strParams)
Convert positional arguments to command-specific RPC representation.
Definition: client.cpp:235
bool CheckDataDirOption()
Definition: system.cpp:736
std::vector< UniValue > JSONRPCProcessBatchReply(const UniValue &in)
Parse JSON-RPC batch reply into a vector.
Definition: request.cpp:133
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:71
std::string EncodeBase64(Span< const unsigned char > input)
uint16_t RPCPort() const
static const char DEFAULT_RPCCONNECT[]
Definition: bitcoin-cli.cpp:38
bool push_back(const UniValue &val)
Definition: univalue.cpp:108
static CAmount balance
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 secp256k1_context * ctx
Definition: tests.c:36
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:1062
Process netinfo requests.
static RPCHelpMan getbalances()
Definition: rpcwallet.cpp:2347
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
Definition: system.cpp:506
bool HelpRequested(const ArgsManager &args)
Definition: system.cpp:601
#define EVENT_LOG_ERR
static const uint64_t DEFAULT_MAX_TRIES
Default max iterations to try in RPC generatetodescriptor, generatetoaddress, and generateblock...
Definition: mining.h:9
static const int CONTINUE_EXECUTION
Definition: bitcoin-cli.cpp:41
bool empty() const
Definition: univalue.h:66
virtual UniValue PrepareRequest(const std::string &method, const std::vector< std::string > &args)=0
raii_evhttp_connection obtain_evhttp_connection_base(struct event_base *base, std::string host, uint16_t port)
Definition: events.h:49
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
static void GetWalletBalances(UniValue &result)
GetWalletBalances calls listwallets; if more than one wallet is loaded, it then fetches mine...
bool pushKV(const std::string &key, const UniValue &val)
Definition: univalue.cpp:133
int get_int() const
void PrintExceptionContinue(const std::exception *pex, const char *pszThread)
Definition: system.cpp:643
int main(int argc, char *argv[])
UniValue ProcessReply(const UniValue &batch_in) override
Collect values from the batch and form a simulated getinfo reply.
bool isNull() const
Definition: univalue.h:77
Class that handles the conversion from a command-line to a JSON-RPC request, as well as converting ba...
std::string FormatFullVersion()
static void SetupCliArgs(ArgsManager &argsman)
Definition: bitcoin-cli.cpp:46
bool IsVersionSelected() const
static void ParseResult(const UniValue &result, std::string &strPrint)
Parse UniValue result to update the message to print to std::cout.
CConnectionFailed(const std::string &msg)
Definition: bitcoin-cli.cpp:97
void UninterruptibleSleep(const std::chrono::microseconds &n)
Definition: time.cpp:19
fs::path GetConfigFile(const std::string &confPath)
Definition: system.cpp:751
const UniValue & get_obj() const
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:466
Process RPC generatetoaddress request.
UniValue JSONRPCReplyObj(const UniValue &result, const UniValue &error, const UniValue &id)
Definition: request.cpp:33
Process default single requests.
ArgsManager gArgs
Definition: system.cpp:76
const std::function< std::string(const char *)> G_TRANSLATION_FUN
Translate string to current locale using Qt.
Definition: bitcoin-cli.cpp:35
UniValue JSONRPCRequestObj(const std::string &strMethod, const UniValue &params, const UniValue &id)
JSON-RPC protocol.
Definition: request.cpp:24
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
Definition: system.cpp:606
static RPCHelpMan getnewaddress()
Definition: rpcwallet.cpp:234
std::string body
const UniValue NullUniValue
Definition: univalue.cpp:13
UniValue PrepareRequest(const std::string &method, const std::vector< std::string > &args) override
UrlDecodeFn *const URL_DECODE
Definition: bitcoin-cli.cpp:36
UniValue RPCConvertNamedValues(const std::string &strMethod, const std::vector< std::string > &strParams)
Convert named arguments to command-specific RPC representation.
Definition: client.cpp:254
static const std::string TESTNET
static const bool DEFAULT_NAMED
Definition: bitcoin-cli.cpp:40
std::string GetChainName() const
Returns the appropriate chain name from the program arguments.
Definition: system.cpp:917
static UniValue GetNewAddress()
Call RPC getnewaddress.
bool IsSwitchChar(char c)
Definition: system.h:122
UniValue PrepareRequest(const std::string &method, const std::vector< std::string > &args) override
bool ParseUInt8(const std::string &str, uint8_t *out)
Convert decimal string to unsigned 8-bit integer with strict parse error feedback.
size_t size() const
Definition: univalue.h:68
boost::optional< T > Optional
Substitute for C++17 std::optional.
Definition: optional.h:14
UniValue ProcessReply(const UniValue &batch_in) override
void SelectBaseParams(const std::string &chain)
Sets the params returned by Params() to those for the given network.
bool IsAddressSelected() const
Process getinfo requests.
bool error(const char *fmt, const Args &... args)
Definition: system.h:52
bool GetAuthCookie(std::string *cookie_out)
Read the RPC authentication cookie from disk.
Definition: request.cpp:108
static const std::string SIGNET
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 http_request_done(struct evhttp_request *req, void *ctx)
Reply structure for request_done to fill in.
UniValue ProcessReply(const UniValue &reply) override
std::string(const std::string &url_encoded) UrlDecodeFn
Definition: url.h:10
void SplitHostPort(std::string in, int &portOut, std::string &hostOut)