Bitcoin Core  0.18.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 <fs.h>
13 #include <rpc/client.h>
14 #include <rpc/protocol.h>
15 #include <rpc/request.h>
16 #include <util/strencodings.h>
17 #include <util/system.h>
18 #include <util/translation.h>
19 
20 #include <functional>
21 #include <memory>
22 #include <stdio.h>
23 #include <tuple>
24 
25 #include <event2/buffer.h>
26 #include <event2/keyvalq_struct.h>
27 #include <support/events.h>
28 
29 #include <univalue.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.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
62 }
63 
65 static void libevent_log_cb(int severity, const char *msg)
66 {
67 #ifndef EVENT_LOG_ERR // EVENT_LOG_ERR was added in 2.0.19; but before then _EVENT_LOG_ERR existed.
68 # define EVENT_LOG_ERR _EVENT_LOG_ERR
69 #endif
70  // Ignore everything other than errors
71  if (severity >= EVENT_LOG_ERR) {
72  throw std::runtime_error(strprintf("libevent error: %s", msg));
73  }
74 }
75 
77 //
78 // Start
79 //
80 
81 //
82 // Exception thrown on connection error. This error is used to determine
83 // when to wait if -rpcwait is given.
84 //
85 class CConnectionFailed : public std::runtime_error
86 {
87 public:
88 
89  explicit inline CConnectionFailed(const std::string& msg) :
90  std::runtime_error(msg)
91  {}
92 
93 };
94 
95 //
96 // This function returns either one of EXIT_ codes when it's expected to stop the process or
97 // CONTINUE_EXECUTION when it's expected to continue further.
98 //
99 static int AppInitRPC(int argc, char* argv[])
100 {
101  //
102  // Parameters
103  //
104  SetupCliArgs();
105  std::string error;
106  if (!gArgs.ParseParameters(argc, argv, error)) {
107  tfm::format(std::cerr, "Error parsing command line arguments: %s\n", error.c_str());
108  return EXIT_FAILURE;
109  }
110  if (argc < 2 || HelpRequested(gArgs) || gArgs.IsArgSet("-version")) {
111  std::string strUsage = PACKAGE_NAME " RPC client version " + FormatFullVersion() + "\n";
112  if (!gArgs.IsArgSet("-version")) {
113  strUsage += "\n"
114  "Usage: bitcoin-cli [options] <command> [params] Send command to " PACKAGE_NAME "\n"
115  "or: bitcoin-cli [options] -named <command> [name=value]... Send command to " PACKAGE_NAME " (with named arguments)\n"
116  "or: bitcoin-cli [options] help List commands\n"
117  "or: bitcoin-cli [options] help <command> Get help for a command\n";
118  strUsage += "\n" + gArgs.GetHelpMessage();
119  }
120 
121  tfm::format(std::cout, "%s", strUsage.c_str());
122  if (argc < 2) {
123  tfm::format(std::cerr, "Error: too few parameters\n");
124  return EXIT_FAILURE;
125  }
126  return EXIT_SUCCESS;
127  }
128  if (!CheckDataDirOption()) {
129  tfm::format(std::cerr, "Error: Specified data directory \"%s\" does not exist.\n", gArgs.GetArg("-datadir", "").c_str());
130  return EXIT_FAILURE;
131  }
132  if (!gArgs.ReadConfigFiles(error, true)) {
133  tfm::format(std::cerr, "Error reading configuration file: %s\n", error.c_str());
134  return EXIT_FAILURE;
135  }
136  // Check for -testnet or -regtest parameter (BaseParams() calls are only valid after this clause)
137  try {
139  } catch (const std::exception& e) {
140  tfm::format(std::cerr, "Error: %s\n", e.what());
141  return EXIT_FAILURE;
142  }
143  return CONTINUE_EXECUTION;
144 }
145 
146 
148 struct HTTPReply
149 {
150  HTTPReply(): status(0), error(-1) {}
151 
152  int status;
153  int error;
154  std::string body;
155 };
156 
157 static const char *http_errorstring(int code)
158 {
159  switch(code) {
160 #if LIBEVENT_VERSION_NUMBER >= 0x02010300
161  case EVREQ_HTTP_TIMEOUT:
162  return "timeout reached";
163  case EVREQ_HTTP_EOF:
164  return "EOF reached";
165  case EVREQ_HTTP_INVALID_HEADER:
166  return "error while reading header, or invalid header";
167  case EVREQ_HTTP_BUFFER_ERROR:
168  return "error encountered while reading or writing";
169  case EVREQ_HTTP_REQUEST_CANCEL:
170  return "request was canceled";
171  case EVREQ_HTTP_DATA_TOO_LONG:
172  return "response body is larger than allowed";
173 #endif
174  default:
175  return "unknown";
176  }
177 }
178 
179 static void http_request_done(struct evhttp_request *req, void *ctx)
180 {
181  HTTPReply *reply = static_cast<HTTPReply*>(ctx);
182 
183  if (req == nullptr) {
184  /* If req is nullptr, it means an error occurred while connecting: the
185  * error code will have been passed to http_error_cb.
186  */
187  reply->status = 0;
188  return;
189  }
190 
191  reply->status = evhttp_request_get_response_code(req);
192 
193  struct evbuffer *buf = evhttp_request_get_input_buffer(req);
194  if (buf)
195  {
196  size_t size = evbuffer_get_length(buf);
197  const char *data = (const char*)evbuffer_pullup(buf, size);
198  if (data)
199  reply->body = std::string(data, size);
200  evbuffer_drain(buf, size);
201  }
202 }
203 
204 #if LIBEVENT_VERSION_NUMBER >= 0x02010300
205 static void http_error_cb(enum evhttp_request_error err, void *ctx)
206 {
207  HTTPReply *reply = static_cast<HTTPReply*>(ctx);
208  reply->error = err;
209 }
210 #endif
211 
216 {
217 public:
218  virtual ~BaseRequestHandler() {}
219  virtual UniValue PrepareRequest(const std::string& method, const std::vector<std::string>& args) = 0;
220  virtual UniValue ProcessReply(const UniValue &batch_in) = 0;
221 };
222 
225 {
226 public:
227  const int ID_NETWORKINFO = 0;
228  const int ID_BLOCKCHAININFO = 1;
229  const int ID_WALLETINFO = 2;
230 
232  UniValue PrepareRequest(const std::string& method, const std::vector<std::string>& args) override
233  {
234  if (!args.empty()) {
235  throw std::runtime_error("-getinfo takes no arguments");
236  }
237  UniValue result(UniValue::VARR);
238  result.push_back(JSONRPCRequestObj("getnetworkinfo", NullUniValue, ID_NETWORKINFO));
239  result.push_back(JSONRPCRequestObj("getblockchaininfo", NullUniValue, ID_BLOCKCHAININFO));
240  result.push_back(JSONRPCRequestObj("getwalletinfo", NullUniValue, ID_WALLETINFO));
241  return result;
242  }
243 
245  UniValue ProcessReply(const UniValue &batch_in) override
246  {
247  UniValue result(UniValue::VOBJ);
248  std::vector<UniValue> batch = JSONRPCProcessBatchReply(batch_in, 3);
249  // Errors in getnetworkinfo() and getblockchaininfo() are fatal, pass them on
250  // getwalletinfo() is allowed to fail in case there is no wallet.
251  if (!batch[ID_NETWORKINFO]["error"].isNull()) {
252  return batch[ID_NETWORKINFO];
253  }
254  if (!batch[ID_BLOCKCHAININFO]["error"].isNull()) {
255  return batch[ID_BLOCKCHAININFO];
256  }
257  result.pushKV("version", batch[ID_NETWORKINFO]["result"]["version"]);
258  result.pushKV("protocolversion", batch[ID_NETWORKINFO]["result"]["protocolversion"]);
259  result.pushKV("blocks", batch[ID_BLOCKCHAININFO]["result"]["blocks"]);
260  result.pushKV("timeoffset", batch[ID_NETWORKINFO]["result"]["timeoffset"]);
261  result.pushKV("connections", batch[ID_NETWORKINFO]["result"]["connections"]);
262  result.pushKV("proxy", batch[ID_NETWORKINFO]["result"]["networks"][0]["proxy"]);
263  result.pushKV("difficulty", batch[ID_BLOCKCHAININFO]["result"]["difficulty"]);
264  result.pushKV("chain", UniValue(batch[ID_BLOCKCHAININFO]["result"]["chain"]));
265  if (!batch[ID_WALLETINFO].isNull()) {
266  result.pushKV("walletversion", batch[ID_WALLETINFO]["result"]["walletversion"]);
267  result.pushKV("balance", batch[ID_WALLETINFO]["result"]["balance"]);
268  result.pushKV("keypoololdest", batch[ID_WALLETINFO]["result"]["keypoololdest"]);
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  evhttp_connection_set_timeout(evcon.get(), gArgs.GetArg("-rpcclienttimeout", DEFAULT_HTTP_CLIENT_TIMEOUT));
318 
319  HTTPReply response;
320  raii_evhttp_request req = obtain_evhttp_request(http_request_done, (void*)&response);
321  if (req == nullptr)
322  throw std::runtime_error("create http request failed");
323 #if LIBEVENT_VERSION_NUMBER >= 0x02010300
324  evhttp_request_set_error_cb(req.get(), http_error_cb);
325 #endif
326 
327  // Get credentials
328  std::string strRPCUserColonPass;
329  bool failedToGetAuthCookie = false;
330  if (gArgs.GetArg("-rpcpassword", "") == "") {
331  // Try fall back to cookie-based authentication if no password is provided
332  if (!GetAuthCookie(&strRPCUserColonPass)) {
333  failedToGetAuthCookie = true;
334  }
335  } else {
336  strRPCUserColonPass = gArgs.GetArg("-rpcuser", "") + ":" + gArgs.GetArg("-rpcpassword", "");
337  }
338 
339  struct evkeyvalq* output_headers = evhttp_request_get_output_headers(req.get());
340  assert(output_headers);
341  evhttp_add_header(output_headers, "Host", host.c_str());
342  evhttp_add_header(output_headers, "Connection", "close");
343  evhttp_add_header(output_headers, "Authorization", (std::string("Basic ") + EncodeBase64(strRPCUserColonPass)).c_str());
344 
345  // Attach request data
346  std::string strRequest = rh->PrepareRequest(strMethod, args).write() + "\n";
347  struct evbuffer* output_buffer = evhttp_request_get_output_buffer(req.get());
348  assert(output_buffer);
349  evbuffer_add(output_buffer, strRequest.data(), strRequest.size());
350 
351  // check if we should use a special wallet endpoint
352  std::string endpoint = "/";
353  if (!gArgs.GetArgs("-rpcwallet").empty()) {
354  std::string walletName = gArgs.GetArg("-rpcwallet", "");
355  char *encodedURI = evhttp_uriencode(walletName.c_str(), walletName.size(), false);
356  if (encodedURI) {
357  endpoint = "/wallet/"+ std::string(encodedURI);
358  free(encodedURI);
359  }
360  else {
361  throw CConnectionFailed("uri-encode failed");
362  }
363  }
364  int r = evhttp_make_request(evcon.get(), req.get(), EVHTTP_REQ_POST, endpoint.c_str());
365  req.release(); // ownership moved to evcon in above call
366  if (r != 0) {
367  throw CConnectionFailed("send http request failed");
368  }
369 
370  event_base_dispatch(base.get());
371 
372  if (response.status == 0) {
373  std::string responseErrorMessage;
374  if (response.error != -1) {
375  responseErrorMessage = strprintf(" (error code %d - \"%s\")", response.error, http_errorstring(response.error));
376  }
377  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));
378  } else if (response.status == HTTP_UNAUTHORIZED) {
379  if (failedToGetAuthCookie) {
380  throw std::runtime_error(strprintf(
381  "Could not locate RPC credentials. No authentication cookie could be found, and RPC password is not set. See -rpcpassword and -stdinrpcpass. Configuration file: (%s)",
382  GetConfigFile(gArgs.GetArg("-conf", BITCOIN_CONF_FILENAME)).string().c_str()));
383  } else {
384  throw std::runtime_error("Authorization failed: Incorrect rpcuser or rpcpassword");
385  }
386  } else if (response.status >= 400 && response.status != HTTP_BAD_REQUEST && response.status != HTTP_NOT_FOUND && response.status != HTTP_INTERNAL_SERVER_ERROR)
387  throw std::runtime_error(strprintf("server returned HTTP error %d", response.status));
388  else if (response.body.empty())
389  throw std::runtime_error("no response from server");
390 
391  // Parse reply
392  UniValue valReply(UniValue::VSTR);
393  if (!valReply.read(response.body))
394  throw std::runtime_error("couldn't parse reply from server");
395  const UniValue reply = rh->ProcessReply(valReply);
396  if (reply.empty())
397  throw std::runtime_error("expected reply to have result, error and id properties");
398 
399  return reply;
400 }
401 
402 static int CommandLineRPC(int argc, char *argv[])
403 {
404  std::string strPrint;
405  int nRet = 0;
406  try {
407  // Skip switches
408  while (argc > 1 && IsSwitchChar(argv[1][0])) {
409  argc--;
410  argv++;
411  }
412  std::string rpcPass;
413  if (gArgs.GetBoolArg("-stdinrpcpass", false)) {
414  if (!std::getline(std::cin, rpcPass)) {
415  throw std::runtime_error("-stdinrpcpass specified but failed to read from standard input");
416  }
417  gArgs.ForceSetArg("-rpcpassword", rpcPass);
418  }
419  std::vector<std::string> args = std::vector<std::string>(&argv[1], &argv[argc]);
420  if (gArgs.GetBoolArg("-stdin", false)) {
421  // Read one arg per line from stdin and append
422  std::string line;
423  while (std::getline(std::cin, line)) {
424  args.push_back(line);
425  }
426  }
427  std::unique_ptr<BaseRequestHandler> rh;
428  std::string method;
429  if (gArgs.GetBoolArg("-getinfo", false)) {
430  rh.reset(new GetinfoRequestHandler());
431  method = "";
432  } else {
433  rh.reset(new DefaultRequestHandler());
434  if (args.size() < 1) {
435  throw std::runtime_error("too few parameters (need at least command)");
436  }
437  method = args[0];
438  args.erase(args.begin()); // Remove trailing method name from arguments vector
439  }
440 
441  // Execute and handle connection failures with -rpcwait
442  const bool fWait = gArgs.GetBoolArg("-rpcwait", false);
443  do {
444  try {
445  const UniValue reply = CallRPC(rh.get(), method, args);
446 
447  // Parse reply
448  const UniValue& result = find_value(reply, "result");
449  const UniValue& error = find_value(reply, "error");
450 
451  if (!error.isNull()) {
452  // Error
453  int code = error["code"].get_int();
454  if (fWait && code == RPC_IN_WARMUP)
455  throw CConnectionFailed("server in warmup");
456  strPrint = "error: " + error.write();
457  nRet = abs(code);
458  if (error.isObject())
459  {
460  UniValue errCode = find_value(error, "code");
461  UniValue errMsg = find_value(error, "message");
462  strPrint = errCode.isNull() ? "" : "error code: "+errCode.getValStr()+"\n";
463 
464  if (errMsg.isStr())
465  strPrint += "error message:\n"+errMsg.get_str();
466 
467  if (errCode.isNum() && errCode.get_int() == RPC_WALLET_NOT_SPECIFIED) {
468  strPrint += "\nTry adding \"-rpcwallet=<filename>\" option to bitcoin-cli command line.";
469  }
470  }
471  } else {
472  // Result
473  if (result.isNull())
474  strPrint = "";
475  else if (result.isStr())
476  strPrint = result.get_str();
477  else
478  strPrint = result.write(2);
479  }
480  // Connection succeeded, no need to retry.
481  break;
482  }
483  catch (const CConnectionFailed&) {
484  if (fWait)
485  MilliSleep(1000);
486  else
487  throw;
488  }
489  } while (fWait);
490  }
491  catch (const std::exception& e) {
492  strPrint = std::string("error: ") + e.what();
493  nRet = EXIT_FAILURE;
494  }
495  catch (...) {
496  PrintExceptionContinue(nullptr, "CommandLineRPC()");
497  throw;
498  }
499 
500  if (strPrint != "") {
501  tfm::format(nRet == 0 ? std::cout : std::cerr, "%s\n", strPrint.c_str());
502  }
503  return nRet;
504 }
505 
506 int main(int argc, char* argv[])
507 {
508 #ifdef WIN32
509  util::WinCmdLineArgs winArgs;
510  std::tie(argc, argv) = winArgs.get();
511 #endif
513  if (!SetupNetworking()) {
514  tfm::format(std::cerr, "Error: Initializing networking failed\n");
515  return EXIT_FAILURE;
516  }
517  event_set_log_callback(&libevent_log_cb);
518 
519  try {
520  int ret = AppInitRPC(argc, argv);
521  if (ret != CONTINUE_EXECUTION)
522  return ret;
523  }
524  catch (const std::exception& e) {
525  PrintExceptionContinue(&e, "AppInitRPC()");
526  return EXIT_FAILURE;
527  } catch (...) {
528  PrintExceptionContinue(nullptr, "AppInitRPC()");
529  return EXIT_FAILURE;
530  }
531 
532  int ret = EXIT_FAILURE;
533  try {
534  ret = CommandLineRPC(argc, argv);
535  }
536  catch (const std::exception& e) {
537  PrintExceptionContinue(&e, "CommandLineRPC()");
538  } catch (...) {
539  PrintExceptionContinue(nullptr, "CommandLineRPC()");
540  }
541  return ret;
542 }
NODISCARD bool ReadConfigFiles(std::string &error, bool ignore_invalid_keys=false)
Definition: system.cpp:873
No wallet specified (error when there are multiple wallets loaded)
Definition: protocol.h:77
bool isObject() const
Definition: univalue.h:85
std::unique_ptr< CBaseChainParams > CreateBaseChainParams(const std::string &chain)
Creates and returns a std::unique_ptr<CBaseChainParams> of the chosen chain.
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:472
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[])
Definition: bitcoin-cli.cpp:99
static void libevent_log_cb(int severity, const char *msg)
libevent event log callback
Definition: bitcoin-cli.cpp:65
static const std::string REGTEST
bool read(const char *raw, size_t len)
static std::string strRPCUserColonPass
Definition: httprpc.cpp:66
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1067
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:1141
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
#define PACKAGE_NAME
const std::string & get_str() const
bool isNum() const
Definition: univalue.h:83
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:376
bool isStr() const
Definition: univalue.h:82
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:512
void ForceSetArg(const std::string &strArg, const std::string &strValue)
Definition: system.cpp:536
const char *const BITCOIN_CONF_FILENAME
Definition: system.cpp:71
bool SetupNetworking()
Definition: system.cpp:1178
const std::string & getValStr() const
Definition: univalue.h:66
Client still warming up.
Definition: protocol.h:49
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:568
static const std::string MAIN
BIP70 chain name strings (main, test or regtest)
UniValue RPCConvertValues(const std::string &strMethod, const std::vector< std::string > &strParams)
Convert positional arguments to command-specific RPC representation.
Definition: client.cpp:219
bool CheckDataDirOption()
Definition: system.cpp:772
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:967
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:542
bool HelpRequested(const ArgsManager &args)
Definition: system.cpp:637
#define EVENT_LOG_ERR
static const int CONTINUE_EXECUTION
Definition: bitcoin-cli.cpp:36
bool empty() const
Definition: univalue.h:67
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:679
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:78
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:89
int RPCPort() const
void SetupChainParamsBaseOptions()
Set the arguments for chainparams.
fs::path GetConfigFile(const std::string &confPath)
Definition: system.cpp:787
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:496
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:642
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:238
static const std::string TESTNET
static const bool DEFAULT_NAMED
Definition: bitcoin-cli.cpp:35
std::string GetChainName() const
Looks for -regtest, -testnet and returns the appropriate BIP70 chain name.
Definition: system.cpp:954
bool IsSwitchChar(char c)
Definition: system.h:96
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:453
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:47
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)