Bitcoin Core  0.19.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-2018 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 <rpc/client.h>
13 #include <rpc/protocol.h>
14 #include <rpc/request.h>
15 #include <util/strencodings.h>
16 #include <util/system.h>
17 #include <util/translation.h>
18 
19 #include <functional>
20 #include <memory>
21 #include <stdio.h>
22 #include <tuple>
23 
24 #include <event2/buffer.h>
25 #include <event2/keyvalq_struct.h>
26 #include <support/events.h>
27 
28 #include <univalue.h>
29 #include <compat/stdin.h>
30 
31 const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr;
32 
33 static const char DEFAULT_RPCCONNECT[] = "127.0.0.1";
34 static const int DEFAULT_HTTP_CLIENT_TIMEOUT=900;
35 static const bool DEFAULT_NAMED=false;
36 static const int CONTINUE_EXECUTION=-1;
37 
38 static void SetupCliArgs()
39 {
41 
42  const auto defaultBaseParams = CreateBaseChainParams(CBaseChainParams::MAIN);
43  const auto testnetBaseParams = CreateBaseChainParams(CBaseChainParams::TESTNET);
44  const auto regtestBaseParams = CreateBaseChainParams(CBaseChainParams::REGTEST);
45 
46  gArgs.AddArg("-version", "Print version and exit", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
47  gArgs.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);
48  gArgs.AddArg("-datadir=<dir>", "Specify data directory", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
49  gArgs.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);
51  gArgs.AddArg("-named", strprintf("Pass named instead of positional arguments (default: %s)", DEFAULT_NAMED), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
52  gArgs.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);
53  gArgs.AddArg("-rpcconnect=<ip>", strprintf("Send commands to node running on <ip> (default: %s)", DEFAULT_RPCCONNECT), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
54  gArgs.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);
55  gArgs.AddArg("-rpcpassword=<pw>", "Password for JSON-RPC connections", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
56  gArgs.AddArg("-rpcport=<port>", strprintf("Connect to JSON-RPC on <port> (default: %u, testnet: %u, regtest: %u)", defaultBaseParams->RPCPort(), testnetBaseParams->RPCPort(), regtestBaseParams->RPCPort()), ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::OPTIONS);
57  gArgs.AddArg("-rpcuser=<user>", "Username for JSON-RPC connections", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
58  gArgs.AddArg("-rpcwait", "Wait for RPC server to start", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
59  gArgs.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);
60  gArgs.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);
61  gArgs.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);
62  gArgs.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);
63 }
64 
66 static void libevent_log_cb(int severity, const char *msg)
67 {
68 #ifndef EVENT_LOG_ERR // EVENT_LOG_ERR was added in 2.0.19; but before then _EVENT_LOG_ERR existed.
69 # define EVENT_LOG_ERR _EVENT_LOG_ERR
70 #endif
71  // Ignore everything other than errors
72  if (severity >= EVENT_LOG_ERR) {
73  throw std::runtime_error(strprintf("libevent error: %s", msg));
74  }
75 }
76 
78 //
79 // Start
80 //
81 
82 //
83 // Exception thrown on connection error. This error is used to determine
84 // when to wait if -rpcwait is given.
85 //
86 class CConnectionFailed : public std::runtime_error
87 {
88 public:
89 
90  explicit inline CConnectionFailed(const std::string& msg) :
91  std::runtime_error(msg)
92  {}
93 
94 };
95 
96 //
97 // This function returns either one of EXIT_ codes when it's expected to stop the process or
98 // CONTINUE_EXECUTION when it's expected to continue further.
99 //
100 static int AppInitRPC(int argc, char* argv[])
101 {
102  //
103  // Parameters
104  //
105  SetupCliArgs();
106  std::string error;
107  if (!gArgs.ParseParameters(argc, argv, error)) {
108  tfm::format(std::cerr, "Error parsing command line arguments: %s\n", error);
109  return EXIT_FAILURE;
110  }
111  if (argc < 2 || HelpRequested(gArgs) || gArgs.IsArgSet("-version")) {
112  std::string strUsage = PACKAGE_NAME " RPC client version " + FormatFullVersion() + "\n";
113  if (!gArgs.IsArgSet("-version")) {
114  strUsage += "\n"
115  "Usage: bitcoin-cli [options] <command> [params] Send command to " PACKAGE_NAME "\n"
116  "or: bitcoin-cli [options] -named <command> [name=value]... Send command to " PACKAGE_NAME " (with named arguments)\n"
117  "or: bitcoin-cli [options] help List commands\n"
118  "or: bitcoin-cli [options] help <command> Get help for a command\n";
119  strUsage += "\n" + gArgs.GetHelpMessage();
120  }
121 
122  tfm::format(std::cout, "%s", strUsage);
123  if (argc < 2) {
124  tfm::format(std::cerr, "Error: too few parameters\n");
125  return EXIT_FAILURE;
126  }
127  return EXIT_SUCCESS;
128  }
129  if (!CheckDataDirOption()) {
130  tfm::format(std::cerr, "Error: Specified data directory \"%s\" does not exist.\n", gArgs.GetArg("-datadir", ""));
131  return EXIT_FAILURE;
132  }
133  if (!gArgs.ReadConfigFiles(error, true)) {
134  tfm::format(std::cerr, "Error reading configuration file: %s\n", error);
135  return EXIT_FAILURE;
136  }
137  // Check for -chain, -testnet or -regtest parameter (BaseParams() calls are only valid after this clause)
138  try {
140  } catch (const std::exception& e) {
141  tfm::format(std::cerr, "Error: %s\n", e.what());
142  return EXIT_FAILURE;
143  }
144  return CONTINUE_EXECUTION;
145 }
146 
147 
149 struct HTTPReply
150 {
151  HTTPReply(): status(0), error(-1) {}
152 
153  int status;
154  int error;
155  std::string body;
156 };
157 
158 static const char *http_errorstring(int code)
159 {
160  switch(code) {
161 #if LIBEVENT_VERSION_NUMBER >= 0x02010300
162  case EVREQ_HTTP_TIMEOUT:
163  return "timeout reached";
164  case EVREQ_HTTP_EOF:
165  return "EOF reached";
166  case EVREQ_HTTP_INVALID_HEADER:
167  return "error while reading header, or invalid header";
168  case EVREQ_HTTP_BUFFER_ERROR:
169  return "error encountered while reading or writing";
170  case EVREQ_HTTP_REQUEST_CANCEL:
171  return "request was canceled";
172  case EVREQ_HTTP_DATA_TOO_LONG:
173  return "response body is larger than allowed";
174 #endif
175  default:
176  return "unknown";
177  }
178 }
179 
180 static void http_request_done(struct evhttp_request *req, void *ctx)
181 {
182  HTTPReply *reply = static_cast<HTTPReply*>(ctx);
183 
184  if (req == nullptr) {
185  /* If req is nullptr, it means an error occurred while connecting: the
186  * error code will have been passed to http_error_cb.
187  */
188  reply->status = 0;
189  return;
190  }
191 
192  reply->status = evhttp_request_get_response_code(req);
193 
194  struct evbuffer *buf = evhttp_request_get_input_buffer(req);
195  if (buf)
196  {
197  size_t size = evbuffer_get_length(buf);
198  const char *data = (const char*)evbuffer_pullup(buf, size);
199  if (data)
200  reply->body = std::string(data, size);
201  evbuffer_drain(buf, size);
202  }
203 }
204 
205 #if LIBEVENT_VERSION_NUMBER >= 0x02010300
206 static void http_error_cb(enum evhttp_request_error err, void *ctx)
207 {
208  HTTPReply *reply = static_cast<HTTPReply*>(ctx);
209  reply->error = err;
210 }
211 #endif
212 
217 {
218 public:
219  virtual ~BaseRequestHandler() {}
220  virtual UniValue PrepareRequest(const std::string& method, const std::vector<std::string>& args) = 0;
221  virtual UniValue ProcessReply(const UniValue &batch_in) = 0;
222 };
223 
226 {
227 public:
228  const int ID_NETWORKINFO = 0;
229  const int ID_BLOCKCHAININFO = 1;
230  const int ID_WALLETINFO = 2;
231 
233  UniValue PrepareRequest(const std::string& method, const std::vector<std::string>& args) override
234  {
235  if (!args.empty()) {
236  throw std::runtime_error("-getinfo takes no arguments");
237  }
238  UniValue result(UniValue::VARR);
239  result.push_back(JSONRPCRequestObj("getnetworkinfo", NullUniValue, ID_NETWORKINFO));
240  result.push_back(JSONRPCRequestObj("getblockchaininfo", NullUniValue, ID_BLOCKCHAININFO));
241  result.push_back(JSONRPCRequestObj("getwalletinfo", NullUniValue, ID_WALLETINFO));
242  return result;
243  }
244 
246  UniValue ProcessReply(const UniValue &batch_in) override
247  {
248  UniValue result(UniValue::VOBJ);
249  std::vector<UniValue> batch = JSONRPCProcessBatchReply(batch_in, 3);
250  // Errors in getnetworkinfo() and getblockchaininfo() are fatal, pass them on
251  // getwalletinfo() is allowed to fail in case there is no wallet.
252  if (!batch[ID_NETWORKINFO]["error"].isNull()) {
253  return batch[ID_NETWORKINFO];
254  }
255  if (!batch[ID_BLOCKCHAININFO]["error"].isNull()) {
256  return batch[ID_BLOCKCHAININFO];
257  }
258  result.pushKV("version", batch[ID_NETWORKINFO]["result"]["version"]);
259  result.pushKV("blocks", batch[ID_BLOCKCHAININFO]["result"]["blocks"]);
260  result.pushKV("headers", batch[ID_BLOCKCHAININFO]["result"]["headers"]);
261  result.pushKV("verificationprogress", batch[ID_BLOCKCHAININFO]["result"]["verificationprogress"]);
262  result.pushKV("timeoffset", batch[ID_NETWORKINFO]["result"]["timeoffset"]);
263  result.pushKV("connections", batch[ID_NETWORKINFO]["result"]["connections"]);
264  result.pushKV("proxy", batch[ID_NETWORKINFO]["result"]["networks"][0]["proxy"]);
265  result.pushKV("difficulty", batch[ID_BLOCKCHAININFO]["result"]["difficulty"]);
266  result.pushKV("chain", UniValue(batch[ID_BLOCKCHAININFO]["result"]["chain"]));
267  if (!batch[ID_WALLETINFO]["result"].isNull()) {
268  result.pushKV("balance", batch[ID_WALLETINFO]["result"]["balance"]);
269  result.pushKV("keypoolsize", batch[ID_WALLETINFO]["result"]["keypoolsize"]);
270  if (!batch[ID_WALLETINFO]["result"]["unlocked_until"].isNull()) {
271  result.pushKV("unlocked_until", batch[ID_WALLETINFO]["result"]["unlocked_until"]);
272  }
273  result.pushKV("paytxfee", batch[ID_WALLETINFO]["result"]["paytxfee"]);
274  }
275  result.pushKV("relayfee", batch[ID_NETWORKINFO]["result"]["relayfee"]);
276  result.pushKV("warnings", batch[ID_NETWORKINFO]["result"]["warnings"]);
277  return JSONRPCReplyObj(result, NullUniValue, 1);
278  }
279 };
280 
283 public:
284  UniValue PrepareRequest(const std::string& method, const std::vector<std::string>& args) override
285  {
286  UniValue params;
287  if(gArgs.GetBoolArg("-named", DEFAULT_NAMED)) {
288  params = RPCConvertNamedValues(method, args);
289  } else {
290  params = RPCConvertValues(method, args);
291  }
292  return JSONRPCRequestObj(method, params, 1);
293  }
294 
295  UniValue ProcessReply(const UniValue &reply) override
296  {
297  return reply.get_obj();
298  }
299 };
300 
301 static UniValue CallRPC(BaseRequestHandler *rh, const std::string& strMethod, const std::vector<std::string>& args)
302 {
303  std::string host;
304  // In preference order, we choose the following for the port:
305  // 1. -rpcport
306  // 2. port in -rpcconnect (ie following : in ipv4 or ]: in ipv6)
307  // 3. default port for chain
308  int port = BaseParams().RPCPort();
309  SplitHostPort(gArgs.GetArg("-rpcconnect", DEFAULT_RPCCONNECT), port, host);
310  port = gArgs.GetArg("-rpcport", port);
311 
312  // Obtain event base
313  raii_event_base base = obtain_event_base();
314 
315  // Synchronously look up hostname
316  raii_evhttp_connection evcon = obtain_evhttp_connection_base(base.get(), host, port);
317 
318  // Set connection timeout
319  {
320  const int timeout = gArgs.GetArg("-rpcclienttimeout", DEFAULT_HTTP_CLIENT_TIMEOUT);
321  if (timeout > 0) {
322  evhttp_connection_set_timeout(evcon.get(), timeout);
323  } else {
324  // Indefinite request timeouts are not possible in libevent-http, so we
325  // set the timeout to a very long time period instead.
326 
327  constexpr int YEAR_IN_SECONDS = 31556952; // Average length of year in Gregorian calendar
328  evhttp_connection_set_timeout(evcon.get(), 5 * YEAR_IN_SECONDS);
329  }
330  }
331 
332  HTTPReply response;
333  raii_evhttp_request req = obtain_evhttp_request(http_request_done, (void*)&response);
334  if (req == nullptr)
335  throw std::runtime_error("create http request failed");
336 #if LIBEVENT_VERSION_NUMBER >= 0x02010300
337  evhttp_request_set_error_cb(req.get(), http_error_cb);
338 #endif
339 
340  // Get credentials
341  std::string strRPCUserColonPass;
342  bool failedToGetAuthCookie = false;
343  if (gArgs.GetArg("-rpcpassword", "") == "") {
344  // Try fall back to cookie-based authentication if no password is provided
345  if (!GetAuthCookie(&strRPCUserColonPass)) {
346  failedToGetAuthCookie = true;
347  }
348  } else {
349  strRPCUserColonPass = gArgs.GetArg("-rpcuser", "") + ":" + gArgs.GetArg("-rpcpassword", "");
350  }
351 
352  struct evkeyvalq* output_headers = evhttp_request_get_output_headers(req.get());
353  assert(output_headers);
354  evhttp_add_header(output_headers, "Host", host.c_str());
355  evhttp_add_header(output_headers, "Connection", "close");
356  evhttp_add_header(output_headers, "Authorization", (std::string("Basic ") + EncodeBase64(strRPCUserColonPass)).c_str());
357 
358  // Attach request data
359  std::string strRequest = rh->PrepareRequest(strMethod, args).write() + "\n";
360  struct evbuffer* output_buffer = evhttp_request_get_output_buffer(req.get());
361  assert(output_buffer);
362  evbuffer_add(output_buffer, strRequest.data(), strRequest.size());
363 
364  // check if we should use a special wallet endpoint
365  std::string endpoint = "/";
366  if (!gArgs.GetArgs("-rpcwallet").empty()) {
367  std::string walletName = gArgs.GetArg("-rpcwallet", "");
368  char *encodedURI = evhttp_uriencode(walletName.data(), walletName.size(), false);
369  if (encodedURI) {
370  endpoint = "/wallet/"+ std::string(encodedURI);
371  free(encodedURI);
372  }
373  else {
374  throw CConnectionFailed("uri-encode failed");
375  }
376  }
377  int r = evhttp_make_request(evcon.get(), req.get(), EVHTTP_REQ_POST, endpoint.c_str());
378  req.release(); // ownership moved to evcon in above call
379  if (r != 0) {
380  throw CConnectionFailed("send http request failed");
381  }
382 
383  event_base_dispatch(base.get());
384 
385  if (response.status == 0) {
386  std::string responseErrorMessage;
387  if (response.error != -1) {
388  responseErrorMessage = strprintf(" (error code %d - \"%s\")", response.error, http_errorstring(response.error));
389  }
390  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));
391  } else if (response.status == HTTP_UNAUTHORIZED) {
392  if (failedToGetAuthCookie) {
393  throw std::runtime_error(strprintf(
394  "Could not locate RPC credentials. No authentication cookie could be found, and RPC password is not set. See -rpcpassword and -stdinrpcpass. Configuration file: (%s)",
395  GetConfigFile(gArgs.GetArg("-conf", BITCOIN_CONF_FILENAME)).string()));
396  } else {
397  throw std::runtime_error("Authorization failed: Incorrect rpcuser or rpcpassword");
398  }
399  } else if (response.status >= 400 && response.status != HTTP_BAD_REQUEST && response.status != HTTP_NOT_FOUND && response.status != HTTP_INTERNAL_SERVER_ERROR)
400  throw std::runtime_error(strprintf("server returned HTTP error %d", response.status));
401  else if (response.body.empty())
402  throw std::runtime_error("no response from server");
403 
404  // Parse reply
405  UniValue valReply(UniValue::VSTR);
406  if (!valReply.read(response.body))
407  throw std::runtime_error("couldn't parse reply from server");
408  const UniValue reply = rh->ProcessReply(valReply);
409  if (reply.empty())
410  throw std::runtime_error("expected reply to have result, error and id properties");
411 
412  return reply;
413 }
414 
415 static int CommandLineRPC(int argc, char *argv[])
416 {
417  std::string strPrint;
418  int nRet = 0;
419  try {
420  // Skip switches
421  while (argc > 1 && IsSwitchChar(argv[1][0])) {
422  argc--;
423  argv++;
424  }
425  std::string rpcPass;
426  if (gArgs.GetBoolArg("-stdinrpcpass", false)) {
427  NO_STDIN_ECHO();
428  if (!StdinReady()) {
429  fputs("RPC password> ", stderr);
430  fflush(stderr);
431  }
432  if (!std::getline(std::cin, rpcPass)) {
433  throw std::runtime_error("-stdinrpcpass specified but failed to read from standard input");
434  }
435  if (StdinTerminal()) {
436  fputc('\n', stdout);
437  }
438  gArgs.ForceSetArg("-rpcpassword", rpcPass);
439  }
440  std::vector<std::string> args = std::vector<std::string>(&argv[1], &argv[argc]);
441  if (gArgs.GetBoolArg("-stdinwalletpassphrase", false)) {
442  NO_STDIN_ECHO();
443  std::string walletPass;
444  if (args.size() < 1 || args[0].substr(0, 16) != "walletpassphrase") {
445  throw std::runtime_error("-stdinwalletpassphrase is only applicable for walletpassphrase(change)");
446  }
447  if (!StdinReady()) {
448  fputs("Wallet passphrase> ", stderr);
449  fflush(stderr);
450  }
451  if (!std::getline(std::cin, walletPass)) {
452  throw std::runtime_error("-stdinwalletpassphrase specified but failed to read from standard input");
453  }
454  if (StdinTerminal()) {
455  fputc('\n', stdout);
456  }
457  args.insert(args.begin() + 1, walletPass);
458  }
459  if (gArgs.GetBoolArg("-stdin", false)) {
460  // Read one arg per line from stdin and append
461  std::string line;
462  while (std::getline(std::cin, line)) {
463  args.push_back(line);
464  }
465  if (StdinTerminal()) {
466  fputc('\n', stdout);
467  }
468  }
469  std::unique_ptr<BaseRequestHandler> rh;
470  std::string method;
471  if (gArgs.GetBoolArg("-getinfo", false)) {
472  rh.reset(new GetinfoRequestHandler());
473  method = "";
474  } else {
475  rh.reset(new DefaultRequestHandler());
476  if (args.size() < 1) {
477  throw std::runtime_error("too few parameters (need at least command)");
478  }
479  method = args[0];
480  args.erase(args.begin()); // Remove trailing method name from arguments vector
481  }
482 
483  // Execute and handle connection failures with -rpcwait
484  const bool fWait = gArgs.GetBoolArg("-rpcwait", false);
485  do {
486  try {
487  const UniValue reply = CallRPC(rh.get(), method, args);
488 
489  // Parse reply
490  const UniValue& result = find_value(reply, "result");
491  const UniValue& error = find_value(reply, "error");
492 
493  if (!error.isNull()) {
494  // Error
495  int code = error["code"].get_int();
496  if (fWait && code == RPC_IN_WARMUP)
497  throw CConnectionFailed("server in warmup");
498  strPrint = "error: " + error.write();
499  nRet = abs(code);
500  if (error.isObject())
501  {
502  UniValue errCode = find_value(error, "code");
503  UniValue errMsg = find_value(error, "message");
504  strPrint = errCode.isNull() ? "" : "error code: "+errCode.getValStr()+"\n";
505 
506  if (errMsg.isStr())
507  strPrint += "error message:\n"+errMsg.get_str();
508 
509  if (errCode.isNum() && errCode.get_int() == RPC_WALLET_NOT_SPECIFIED) {
510  strPrint += "\nTry adding \"-rpcwallet=<filename>\" option to bitcoin-cli command line.";
511  }
512  }
513  } else {
514  // Result
515  if (result.isNull())
516  strPrint = "";
517  else if (result.isStr())
518  strPrint = result.get_str();
519  else
520  strPrint = result.write(2);
521  }
522  // Connection succeeded, no need to retry.
523  break;
524  }
525  catch (const CConnectionFailed&) {
526  if (fWait)
527  MilliSleep(1000);
528  else
529  throw;
530  }
531  } while (fWait);
532  }
533  catch (const std::exception& e) {
534  strPrint = std::string("error: ") + e.what();
535  nRet = EXIT_FAILURE;
536  }
537  catch (...) {
538  PrintExceptionContinue(nullptr, "CommandLineRPC()");
539  throw;
540  }
541 
542  if (strPrint != "") {
543  tfm::format(nRet == 0 ? std::cout : std::cerr, "%s\n", strPrint);
544  }
545  return nRet;
546 }
547 
548 int main(int argc, char* argv[])
549 {
550 #ifdef WIN32
551  util::WinCmdLineArgs winArgs;
552  std::tie(argc, argv) = winArgs.get();
553 #endif
555  if (!SetupNetworking()) {
556  tfm::format(std::cerr, "Error: Initializing networking failed\n");
557  return EXIT_FAILURE;
558  }
559  event_set_log_callback(&libevent_log_cb);
560 
561  try {
562  int ret = AppInitRPC(argc, argv);
563  if (ret != CONTINUE_EXECUTION)
564  return ret;
565  }
566  catch (const std::exception& e) {
567  PrintExceptionContinue(&e, "AppInitRPC()");
568  return EXIT_FAILURE;
569  } catch (...) {
570  PrintExceptionContinue(nullptr, "AppInitRPC()");
571  return EXIT_FAILURE;
572  }
573 
574  int ret = EXIT_FAILURE;
575  try {
576  ret = CommandLineRPC(argc, argv);
577  }
578  catch (const std::exception& e) {
579  PrintExceptionContinue(&e, "CommandLineRPC()");
580  } catch (...) {
581  PrintExceptionContinue(nullptr, "CommandLineRPC()");
582  }
583  return ret;
584 }
NODISCARD bool ReadConfigFiles(std::string &error, bool ignore_invalid_keys=false)
Definition: system.cpp:766
No wallet specified (error when there are multiple wallets loaded)
Definition: protocol.h:80
bool isObject() const
Definition: univalue.h:84
bool StdinTerminal()
Definition: stdin.cpp:47
std::unique_ptr< CBaseChainParams > CreateBaseChainParams(const std::string &chain)
Creates and returns a std::unique_ptr<CBaseChainParams> of the chosen chain.
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:382
static int CommandLineRPC(int argc, char *argv[])
raii_event_base obtain_event_base()
Definition: events.h:30
std::vector< UniValue > JSONRPCProcessBatchReply(const UniValue &in, size_t num)
Parse JSON-RPC batch reply into a vector.
Definition: request.cpp:133
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:66
static const std::string REGTEST
bool read(const char *raw, size_t len)
static std::string strRPCUserColonPass
Definition: httprpc.cpp:64
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
UniValue ProcessReply(const UniValue &reply) override
virtual ~BaseRequestHandler()
static const int DEFAULT_HTTP_CLIENT_TIMEOUT
Definition: bitcoin-cli.cpp:34
void MilliSleep(int64_t n)
Definition: time.cpp:75
void SetupEnvironment()
Definition: system.cpp:1049
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
#define PACKAGE_NAME
const std::string & get_str() const
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:289
bool isStr() const
Definition: univalue.h:81
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:404
void ForceSetArg(const std::string &strArg, const std::string &strValue)
Definition: system.cpp:426
const char *const BITCOIN_CONF_FILENAME
Definition: system.cpp:71
bool SetupNetworking()
Definition: system.cpp:1086
const std::string & getValStr() const
Definition: univalue.h:65
Client still warming up.
Definition: protocol.h:49
#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:458
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:221
bool CheckDataDirOption()
Definition: system.cpp:662
static const char DEFAULT_RPCCONNECT[]
Definition: bitcoin-cli.cpp:33
bool push_back(const UniValue &val)
Definition: univalue.cpp:108
static const char * http_errorstring(int code)
static secp256k1_context * ctx
Definition: tests.c:46
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
std::string EncodeBase64(const unsigned char *pch, size_t len)
static UniValue CallRPC(BaseRequestHandler *rh, const std::string &strMethod, const std::vector< std::string > &args)
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
Definition: system.cpp:432
bool HelpRequested(const ArgsManager &args)
Definition: system.cpp:527
#define EVENT_LOG_ERR
static const int CONTINUE_EXECUTION
Definition: bitcoin-cli.cpp:36
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
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:569
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()
CConnectionFailed(const std::string &msg)
Definition: bitcoin-cli.cpp:90
int RPCPort() const
void SetupChainParamsBaseOptions()
Set the arguments for chainparams.
fs::path GetConfigFile(const std::string &confPath)
Definition: system.cpp:677
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:392
UniValue JSONRPCReplyObj(const UniValue &result, const UniValue &error, const UniValue &id)
Definition: request.cpp:33
Process default single requests.
ArgsManager gArgs
Definition: system.cpp:73
const std::function< std::string(const char *)> G_TRANSLATION_FUN
Translate string to current locale using Qt.
Definition: bitcoin-cli.cpp:31
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:532
static void SetupCliArgs()
Definition: bitcoin-cli.cpp:38
std::string body
const UniValue NullUniValue
Definition: univalue.cpp:13
UniValue RPCConvertNamedValues(const std::string &strMethod, const std::vector< std::string > &strParams)
Convert named arguments to command-specific RPC representation.
Definition: client.cpp:240
static const std::string TESTNET
static const bool DEFAULT_NAMED
Definition: bitcoin-cli.cpp:35
std::string GetChainName() const
Returns the appropriate chain name from the program arguments.
Definition: system.cpp:853
bool IsSwitchChar(char c)
Definition: system.h:97
UniValue PrepareRequest(const std::string &method, const std::vector< std::string > &args) override
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: system.cpp:370
void SelectBaseParams(const std::string &chain)
Sets the params returned by Params() to those for the given network.
Process getinfo requests.
bool error(const char *fmt, const Args &... args)
Definition: system.h:48
bool GetAuthCookie(std::string *cookie_out)
Read the RPC authentication cookie from disk.
Definition: request.cpp:108
static void http_request_done(struct evhttp_request *req, void *ctx)
Reply structure for request_done to fill in.
void SplitHostPort(std::string in, int &portOut, std::string &hostOut)