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