6#if defined(HAVE_CONFIG_H)
7#include <config/bitcoin-config.h>
28#include <event2/buffer.h>
29#include <event2/keyvalq_struct.h>
71 strprintf(
"Specify configuration file. Relative paths will be "
72 "prefixed by datadir location. (default: %s)",
75 argsman.
AddArg(
"-datadir=<dir>",
"Specify data directory",
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",
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)",
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).",
106 strprintf(
"Pass named instead of positional arguments (default: %s)",
111 strprintf(
"Send commands to node running on <ip> (default: %s)",
115 "-rpccookiefile=<loc>",
116 "Location of the auth cookie. Relative paths will be prefixed "
117 "by a net-specific datadir location. (default: data dir)",
119 argsman.
AddArg(
"-rpcport=<port>",
120 strprintf(
"Connect to JSON-RPC on <port> (default: %u, "
121 "testnet: %u, regtest: %u)",
122 defaultBaseParams->RPCPort(),
123 testnetBaseParams->RPCPort(),
124 regtestBaseParams->RPCPort()),
127 argsman.
AddArg(
"-rpcwait",
"Wait for RPC server to start",
129 argsman.
AddArg(
"-rpcuser=<user>",
"Username for JSON-RPC connections",
131 argsman.
AddArg(
"-rpcpassword=<pw>",
"Password for JSON-RPC connections",
134 "-rpcclienttimeout=<n>",
135 strprintf(
"Timeout in seconds during HTTP requests, or 0 for "
136 "no timeout. (default: %d)",
140 argsman.
AddArg(
"-stdinrpcpass",
141 "Read RPC password from standard input as a single "
142 "line. When combined with -stdin, the first line "
143 "from standard input is used for the RPC password. When "
144 "combined with -stdinwalletpassphrase, -stdinrpcpass "
145 "consumes the first line, and -stdinwalletpassphrase "
146 "consumes the second.",
148 argsman.
AddArg(
"-stdinwalletpassphrase",
149 "Read wallet passphrase from standard input as a single "
150 "line. When combined with -stdin, the first line "
151 "from standard input is used for the wallet passphrase.",
155 "Read extra arguments from standard input, one per line until "
156 "EOF/Ctrl-D (recommended for sensitive information such as "
157 "passphrases). When combined with -stdinrpcpass, the first "
158 "line from standard input is used for the RPC password.",
161 "-rpcwallet=<walletname>",
162 "Send RPC for non-default wallet on RPC server (needs to exactly match "
163 "corresponding -wallet option passed to bitcoind). This changes the "
164 "RPC endpoint used, e.g. http://127.0.0.1:8332/wallet/<walletname>",
172#define EVENT_LOG_ERR _EVENT_LOG_ERR
176 throw std::runtime_error(
strprintf(
"libevent error: %s", msg));
192 :
std::runtime_error(msg) {}
206 tfm::format(std::cerr,
"Error parsing command line arguments: %s\n",
211 std::string strUsage =
218 "Usage: bitcoin-cli [options] <command> [params] "
219 "Send command to " PACKAGE_NAME
"\n"
220 "or: bitcoin-cli [options] -named <command> "
221 "[name=value]... Send command to " PACKAGE_NAME
222 " (with named arguments)\n"
223 "or: bitcoin-cli [options] help "
225 "or: bitcoin-cli [options] help <command> Get "
226 "help for a command\n";
233 tfm::format(std::cerr,
"Error: too few parameters\n");
240 "Error: Specified data directory \"%s\" does not exist.\n",
245 tfm::format(std::cerr,
"Error reading configuration file: %s\n", error);
252 }
catch (
const std::exception &e) {
270 case EVREQ_HTTP_TIMEOUT:
271 return "timeout reached";
273 return "EOF reached";
274 case EVREQ_HTTP_INVALID_HEADER:
275 return "error while reading header, or invalid header";
276 case EVREQ_HTTP_BUFFER_ERROR:
277 return "error encountered while reading or writing";
278 case EVREQ_HTTP_REQUEST_CANCEL:
279 return "request was canceled";
280 case EVREQ_HTTP_DATA_TOO_LONG:
281 return "response body is larger than allowed";
290 if (req ==
nullptr) {
299 reply->
status = evhttp_request_get_response_code(req);
301 struct evbuffer *buf = evhttp_request_get_input_buffer(req);
303 size_t size = evbuffer_get_length(buf);
304 const char *data = (
const char *)evbuffer_pullup(buf, size);
306 reply->
body = std::string(data, size);
308 evbuffer_drain(buf, size);
325 const std::vector<std::string> &args) = 0;
339 const std::vector<std::string> &args)
override {
341 throw std::runtime_error(
"-getinfo takes no arguments");
372 "verificationprogress",
374 result.
pushKV(
"timeoffset",
382 connections.
pushKV(
"total",
384 result.
pushKV(
"connections", std::move(connections));
388 result.
pushKV(
"difficulty",
393 result.
pushKV(
"keypoolsize",
396 result.
pushKV(
"unlocked_until",
418 {
"ipv4",
"ipv6",
"onion"}};
420 std::array<std::array<uint16_t, m_networks_size + 2>, 3>
m_counts{{{}}};
480 const double milliseconds{round(1000 * seconds)};
481 return milliseconds > 999999 ?
"-" :
ToString(milliseconds);
484 TicksSinceEpoch<std::chrono::seconds>(CliClock::now())};
491 const std::vector<std::string> &args)
override {
516 if (networkinfo[
"version"].getInt<int>() < 230000) {
517 throw std::runtime_error(
"-netinfo requires bitcoind server to be "
518 "running v0.23.0 and up");
524 const std::string network{peer[
"network"].get_str()};
529 const bool is_outbound{!peer[
"inbound"].get_bool()};
530 const bool is_block_relay{!peer[
"relaytxes"].get_bool()};
532 ++
m_counts.at(is_outbound).at(network_id);
539 if (is_block_relay) {
547 const int peer_id{peer[
"id"].getInt<
int>()};
548 const int mapped_as{peer[
"mapped_as"].isNull()
550 : peer[
"mapped_as"].getInt<
int>()};
551 const int version{peer[
"version"].getInt<
int>()};
552 const int64_t conn_time{peer[
"conntime"].getInt<int64_t>()};
553 const int64_t last_blck{peer[
"last_block"].getInt<int64_t>()};
554 const int64_t last_recv{peer[
"lastrecv"].getInt<int64_t>()};
555 const int64_t last_send{peer[
"lastsend"].getInt<int64_t>()};
556 const int64_t last_trxn{
557 peer[
"last_transaction"].getInt<int64_t>()};
558 const double min_ping{
559 peer[
"minping"].isNull() ? -1 : peer[
"minping"].get_real()};
560 const double ping{peer[
"pingtime"].isNull()
562 : peer[
"pingtime"].get_real()};
563 const std::string addr{peer[
"addr"].get_str()};
564 const std::string age{
567 const std::string sub_version{peer[
"subver"].get_str()};
568 m_peers.push_back({addr, sub_version, network, age, min_ping,
569 ping, last_blck, last_recv, last_send,
570 last_trxn, peer_id, mapped_as, version,
571 is_block_relay, is_outbound});
584 ChainToString(), networkinfo[
"protocolversion"].getInt<int>(),
585 networkinfo[
"subversion"].get_str())};
592 "Peer connections sorted by direction and min ping\n<-> relay "
593 " net mping ping send recv txn blk %*s ",
603 std::string version{
ToString(peer.version) + peer.sub_version};
605 "%3s %5s %5s%7s%7s%5s%5s%5s%5s %*s%*i %*s %-*s%s\n",
606 peer.is_outbound ?
"out" :
"in",
607 peer.is_block_relay ?
"block" :
"full", peer.network,
610 peer.last_send == 0 ?
""
612 peer.last_recv == 0 ?
""
635 " ms ms sec sec min min %*s\n\n",
640 result +=
" ipv4 ipv6 onion total block-relay\n";
641 const std::array<std::string, 3> rows{{
"in",
"out",
"total"}};
643 result +=
strprintf(
"%-5s %5i %5i %5i %5i %5i\n",
651 result +=
"\nLocal addresses";
652 const std::vector<UniValue> &local_addrs{
653 networkinfo[
"localaddresses"].getValues()};
654 if (local_addrs.empty()) {
657 size_t max_addr_size{0};
658 for (
const UniValue &addr : local_addrs) {
659 max_addr_size = std::max(addr[
"address"].get_str().length() + 1,
662 for (
const UniValue &addr : local_addrs) {
663 result +=
strprintf(
"\n%-*s port %6i score %6i",
664 max_addr_size, addr[
"address"].get_str(),
665 addr[
"port"].getInt<int>(),
666 addr[
"score"].getInt<int>());
678 const std::vector<std::string> &args)
override {
699 const std::vector<std::string> &args)
override {
715 const std::vector<std::string> &args,
716 const std::optional<std::string> &rpcwallet = {}) {
730 raii_evhttp_connection evcon =
738 evhttp_connection_set_timeout(evcon.get(), timeout);
744 constexpr int YEAR_IN_SECONDS = 31556952;
745 evhttp_connection_set_timeout(evcon.get(), 5 * YEAR_IN_SECONDS);
750 raii_evhttp_request req =
752 if (req ==
nullptr) {
753 throw std::runtime_error(
"create http request failed");
760 bool failedToGetAuthCookie =
false;
765 failedToGetAuthCookie =
true;
772 struct evkeyvalq *output_headers =
773 evhttp_request_get_output_headers(req.get());
775 evhttp_add_header(output_headers,
"Host", host.c_str());
776 evhttp_add_header(output_headers,
"Connection",
"close");
777 evhttp_add_header(output_headers,
"Content-Type",
"application/json");
779 output_headers,
"Authorization",
784 struct evbuffer *output_buffer =
785 evhttp_request_get_output_buffer(req.get());
787 evbuffer_add(output_buffer, strRequest.data(), strRequest.size());
790 std::string endpoint =
"/";
793 evhttp_uriencode(rpcwallet->data(), rpcwallet->size(),
false);
795 endpoint =
"/wallet/" + std::string(encodedURI);
801 int r = evhttp_make_request(evcon.get(), req.get(), EVHTTP_REQ_POST,
809 event_base_dispatch(base.get());
812 std::string responseErrorMessage;
814 responseErrorMessage =
819 strprintf(
"Could not connect to the server %s:%d%s\n\nMake sure "
820 "the bitcoind server is running and that you are "
821 "connecting to the correct RPC port.",
822 host, port, responseErrorMessage));
824 if (failedToGetAuthCookie) {
826 "Could not locate RPC credentials. No authentication cookie "
827 "could be found, and RPC password is not set. See "
828 "-rpcpassword and -stdinrpcpass. Configuration file: (%s)",
831 throw std::runtime_error(
832 "Authorization failed: Incorrect rpcuser or rpcpassword");
835 throw std::runtime_error(
840 throw std::runtime_error(
843 throw std::runtime_error(
"no response from server");
848 if (!valReply.read(
response.body)) {
849 throw std::runtime_error(
"couldn't parse reply from server");
853 throw std::runtime_error(
854 "expected reply to have result, error and id properties");
873 const std::vector<std::string> &args,
874 const std::optional<std::string> &rpcwallet = {}) {
918 strPrint =
"error code: " + err_code.
getValStr() +
"\n";
920 if (err_msg.
isStr()) {
921 strPrint += (
"error message:\n" + err_msg.
get_str());
923 if (err_code.
isNum() &&
925 strPrint +=
"\nTry adding \"-rpcwallet=<filename>\" option to "
926 "bitcoin-cli command line.";
929 strPrint =
"error: " + error.
write();
931 nRet = abs(error[
"code"].getInt<int>());
950 if (wallets.
size() <= 1) {
956 const std::string &wallet_name =
wallet.get_str();
960 getbalances.find_value(
"result")[
"mine"][
"trusted"];
963 result.
pushKV(
"balances", std::move(balances));
971 std::optional<std::string> wallet_name{};
987 std::vector<std::string> &args) {
988 if (args.size() > 2) {
989 throw std::runtime_error(
990 "too many arguments (maximum 2 for nblocks and maxtries)");
992 if (args.size() == 0) {
994 }
else if (args.at(0) ==
"0") {
995 throw std::runtime_error(
996 "the first argument (number of blocks to generate, default: " +
999 args.emplace(args.begin() + 1, address);
1003 std::string strPrint;
1011 std::string rpcPass;
1015 fputs(
"RPC password> ", stderr);
1018 if (!std::getline(std::cin, rpcPass)) {
1019 throw std::runtime_error(
"-stdinrpcpass specified but failed "
1020 "to read from standard input");
1023 fputc(
'\n', stdout);
1027 std::vector<std::string> args =
1028 std::vector<std::string>(&argv[1], &argv[argc]);
1031 std::string walletPass;
1032 if (args.size() < 1 ||
1033 args[0].substr(0, 16) !=
"walletpassphrase") {
1034 throw std::runtime_error(
1035 "-stdinwalletpassphrase is only applicable for "
1036 "walletpassphrase(change)");
1039 fputs(
"Wallet passphrase> ", stderr);
1042 if (!std::getline(std::cin, walletPass)) {
1043 throw std::runtime_error(
"-stdinwalletpassphrase specified but "
1044 "failed to read from standard input");
1047 fputc(
'\n', stdout);
1049 args.insert(args.begin() + 1, walletPass);
1054 while (std::getline(std::cin, line)) {
1055 args.push_back(line);
1058 fputc(
'\n', stdout);
1061 std::unique_ptr<BaseRequestHandler> rh;
1079 if (args.size() < 1) {
1080 throw std::runtime_error(
1081 "too few parameters (need at least command)");
1085 args.erase(args.begin());
1090 std::optional<std::string> wallet_name{};
1111 }
catch (
const std::exception &e) {
1112 strPrint = std::string(
"error: ") + e.what();
1113 nRet = EXIT_FAILURE;
1119 if (strPrint !=
"") {
1120 tfm::format(nRet == 0 ? std::cout : std::cerr,
"%s\n", strPrint);
1131__declspec(dllexport)
int main(
int argc,
char *argv[]) {
1132 common::WinCmdLineArgs winArgs;
1133 std::tie(argc, argv) = winArgs.get();
1139 tfm::format(std::cerr,
"Error: Initializing networking failed\n");
1140 return EXIT_FAILURE;
1149 }
catch (
const std::exception &e) {
1151 return EXIT_FAILURE;
1154 return EXIT_FAILURE;
1157 int ret = EXIT_FAILURE;
1160 }
catch (
const std::exception &e) {
bool HelpRequested(const ArgsManager &args)
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
bool CheckDataDirOption(const ArgsManager &args)
const char *const BITCOIN_CONF_FILENAME
bool IsSwitchChar(char c)
static const char DEFAULT_RPCCONNECT[]
int main(int argc, char *argv[])
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
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.
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
std::unique_ptr< CBaseChainParams > CreateBaseChainParams(const ChainType chain)
Port numbers for incoming Tor connections (8334, 18334, 38334, 18445) have been chosen arbitrarily to...
void SetupChainParamsBaseOptions(ArgsManager &argsman)
Set the arguments for chainparams.
void SelectBaseParams(const ChainType chain)
Sets the params returned by Params() to those for the given chain.
@ ALLOW_ANY
disable validation
@ DISALLOW_NEGATION
unimplemented, draft implementation in #16545
ChainType GetChainType() const
Looks for -regtest, -testnet and returns the appropriate BIP70 chain name.
void ForceSetArg(const std::string &strArg, const std::string &strValue)
bool ParseParameters(int argc, const char *const argv[], std::string &error)
std::string GetHelpMessage() const
Get the help string.
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
fs::path GetConfigFilePath() const
Return config file path (read-only)
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
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.
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
Class that handles the conversion from a command-line to a JSON-RPC request, as well as converting ba...
virtual UniValue ProcessReply(const UniValue &batch_in)=0
virtual ~BaseRequestHandler()=default
virtual UniValue PrepareRequest(const std::string &method, const std::vector< std::string > &args)=0
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.
const int ID_BLOCKCHAININFO
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
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)
const std::string & get_str() const
const UniValue & find_value(std::string_view key) const
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
const std::string & getValStr() const
const UniValue & get_obj() const
const std::vector< UniValue > & getValues() const
void pushKV(std::string key, UniValue val)
UniValue RPCConvertValues(const std::string &strMethod, const std::vector< std::string > &strParams)
Convert positional arguments to command-specific RPC representation.
UniValue RPCConvertNamedValues(const std::string &strMethod, const std::vector< std::string > &strParams)
Convert named arguments to command-specific RPC representation.
std::string FormatFullVersion()
std::string LicenseInfo()
Returns licensing information (for -version)
void SetupCurrencyUnitOptions(ArgsManager &argsman)
raii_evhttp_request obtain_evhttp_request(void(*cb)(struct evhttp_request *, void *), void *arg)
raii_evhttp_connection obtain_evhttp_connection_base(struct event_base *base, std::string host, uint16_t port)
raii_event_base obtain_event_base()
void PrintExceptionContinue(const std::exception *pex, std::string_view thread_name)
static std::string strRPCUserColonPass
static const uint64_t DEFAULT_MAX_TRIES
Default max iterations to try in RPC generatetodescriptor, generatetoaddress, and generateblock.
static bool isNull(const AnyVoteItem &item)
static std::string PathToString(const path &path)
Convert path object to byte string.
Implement std::hash so RCUPtr can be used as a key for maps or sets.
std::string ToString(const T &t)
Locale-independent version of std::to_string.
std::vector< UniValue > JSONRPCProcessBatchReply(const UniValue &in)
Parse JSON-RPC batch reply into a vector.
bool GetAuthCookie(std::string *cookie_out)
Read the RPC authentication cookie from disk.
UniValue JSONRPCRequestObj(const std::string &strMethod, const UniValue ¶ms, const UniValue &id)
JSON-RPC protocol.
UniValue JSONRPCReplyObj(const UniValue &result, const UniValue &error, const UniValue &id)
@ HTTP_SERVICE_UNAVAILABLE
@ HTTP_INTERNAL_SERVER_ERROR
@ RPC_WALLET_NOT_SPECIFIED
No wallet specified (error when there are multiple wallets loaded)
@ RPC_IN_WARMUP
Client still warming up.
static RPCHelpMan getnewaddress()
static RPCHelpMan listwallets()
static RPCHelpMan getbalances()
static std::string ToString(const CService &ip)
Reply structure for request_done to fill in.
bool operator<(const Peer &rhs) const
void UninterruptibleSleep(const std::chrono::microseconds &n)
const UniValue NullUniValue
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.
bool SplitHostPort(std::string_view in, uint16_t &portOut, std::string &hostOut)
Splits socket address string into host string and port value.