6 #if defined(HAVE_CONFIG_H)
7 #include <config/bitcoin-config.h>
23 #include <event2/buffer.h>
24 #include <event2/keyvalq_struct.h>
55 const auto defaultBaseParams =
57 const auto testnetBaseParams =
59 const auto regtestBaseParams =
67 strprintf(
"Specify configuration file. Relative paths will be "
68 "prefixed by datadir location. (default: %s)",
71 argsman.
AddArg(
"-datadir=<dir>",
"Specify data directory",
76 "Generate blocks immediately, equivalent to RPC getnewaddress "
77 "followed by RPC generatetoaddress. Optional positional integer "
78 "arguments are number of blocks to generate (default: %s) and "
79 "maximum iterations to try (default: %s), equivalent to RPC "
80 "generatetoaddress nblocks and maxtries arguments. Example: "
81 "bitcoin-cli -generate 4 1000",
86 "Get general information from the remote server. Note that unlike "
87 "server-side RPC calls, the results of -getinfo is the result of "
88 "multiple non-atomic requests. Some entries in the result may "
89 "represent results from different states (e.g. wallet balance may be "
90 "as of a different block from the chain state reported)",
93 "Get network peer connection information from the remote "
94 "server. An optional integer argument from 0 to 4 can be "
95 "passed for different peers listings (default: 0).",
101 strprintf(
"Pass named instead of positional arguments (default: %s)",
106 strprintf(
"Send commands to node running on <ip> (default: %s)",
110 "-rpccookiefile=<loc>",
111 "Location of the auth cookie. Relative paths will be prefixed "
112 "by a net-specific datadir location. (default: data dir)",
114 argsman.
AddArg(
"-rpcport=<port>",
115 strprintf(
"Connect to JSON-RPC on <port> (default: %u, "
116 "testnet: %u, regtest: %u)",
117 defaultBaseParams->RPCPort(),
118 testnetBaseParams->RPCPort(),
119 regtestBaseParams->RPCPort()),
122 argsman.
AddArg(
"-rpcwait",
"Wait for RPC server to start",
124 argsman.
AddArg(
"-rpcuser=<user>",
"Username for JSON-RPC connections",
126 argsman.
AddArg(
"-rpcpassword=<pw>",
"Password for JSON-RPC connections",
129 "-rpcclienttimeout=<n>",
130 strprintf(
"Timeout in seconds during HTTP requests, or 0 for "
131 "no timeout. (default: %d)",
135 argsman.
AddArg(
"-stdinrpcpass",
136 "Read RPC password from standard input as a single "
137 "line. When combined with -stdin, the first line "
138 "from standard input is used for the RPC password. When "
139 "combined with -stdinwalletpassphrase, -stdinrpcpass "
140 "consumes the first line, and -stdinwalletpassphrase "
141 "consumes the second.",
143 argsman.
AddArg(
"-stdinwalletpassphrase",
144 "Read wallet passphrase from standard input as a single "
145 "line. When combined with -stdin, the first line "
146 "from standard input is used for the wallet passphrase.",
150 "Read extra arguments from standard input, one per line until "
151 "EOF/Ctrl-D (recommended for sensitive information such as "
152 "passphrases). When combined with -stdinrpcpass, the first "
153 "line from standard input is used for the RPC password.",
156 "-rpcwallet=<walletname>",
157 "Send RPC for non-default wallet on RPC server (needs to exactly match "
158 "corresponding -wallet option passed to bitcoind). This changes the "
159 "RPC endpoint used, e.g. http://127.0.0.1:8332/wallet/<walletname>",
165 #ifndef EVENT_LOG_ERR
167 #define EVENT_LOG_ERR _EVENT_LOG_ERR
171 throw std::runtime_error(
strprintf(
"libevent error: %s", msg));
187 :
std::runtime_error(msg) {}
201 tfm::format(std::cerr,
"Error parsing command line arguments: %s\n",
206 std::string strUsage =
210 "Usage: bitcoin-cli [options] <command> [params] "
211 "Send command to " PACKAGE_NAME
"\n"
212 "or: bitcoin-cli [options] -named <command> "
213 "[name=value]... Send command to " PACKAGE_NAME
214 " (with named arguments)\n"
215 "or: bitcoin-cli [options] help "
217 "or: bitcoin-cli [options] help <command> Get "
218 "help for a command\n";
225 tfm::format(std::cerr,
"Error: too few parameters\n");
232 "Error: Specified data directory \"%s\" does not exist.\n",
244 }
catch (
const std::exception &e) {
262 #if LIBEVENT_VERSION_NUMBER >= 0x02010300
263 case EVREQ_HTTP_TIMEOUT:
264 return "timeout reached";
266 return "EOF reached";
267 case EVREQ_HTTP_INVALID_HEADER:
268 return "error while reading header, or invalid header";
269 case EVREQ_HTTP_BUFFER_ERROR:
270 return "error encountered while reading or writing";
271 case EVREQ_HTTP_REQUEST_CANCEL:
272 return "request was canceled";
273 case EVREQ_HTTP_DATA_TOO_LONG:
274 return "response body is larger than allowed";
284 if (req ==
nullptr) {
293 reply->
status = evhttp_request_get_response_code(req);
295 struct evbuffer *buf = evhttp_request_get_input_buffer(req);
297 size_t size = evbuffer_get_length(buf);
298 const char *data = (
const char *)evbuffer_pullup(buf, size);
300 reply->
body = std::string(data, size);
302 evbuffer_drain(buf, size);
306 #if LIBEVENT_VERSION_NUMBER >= 0x02010300
307 static void http_error_cb(
enum evhttp_request_error err,
void *
ctx) {
321 const std::vector<std::string> &args) = 0;
335 const std::vector<std::string> &args)
override {
337 throw std::runtime_error(
"-getinfo takes no arguments");
368 "verificationprogress",
370 result.
pushKV(
"timeoffset",
378 connections.
pushKV(
"total",
380 result.
pushKV(
"connections", connections);
384 result.
pushKV(
"difficulty",
389 result.
pushKV(
"keypoolsize",
392 result.
pushKV(
"unlocked_until",
414 {
"ipv4",
"ipv6",
"onion"}};
416 std::array<std::array<uint16_t, m_networks_size + 2>, 3>
m_counts{{{}}};
475 const double milliseconds{round(1000 * seconds)};
476 return milliseconds > 999999 ?
"-" :
ToString(milliseconds);
479 TicksSinceEpoch<std::chrono::seconds>(CliClock::now())};
486 const std::vector<std::string> &args)
override {
511 if (networkinfo[
"version"].get_int() < 230000) {
512 throw std::runtime_error(
"-netinfo requires bitcoind server to be "
513 "running v0.23.0 and up");
519 const std::string network{peer[
"network"].get_str()};
524 const bool is_outbound{!peer[
"inbound"].get_bool()};
525 const bool is_block_relay{!peer[
"relaytxes"].get_bool()};
527 ++
m_counts.at(is_outbound).at(network_id);
534 if (is_block_relay) {
542 const int peer_id{peer[
"id"].get_int()};
543 const int mapped_as{peer[
"mapped_as"].isNull()
545 : peer[
"mapped_as"].get_int()};
546 const int version{peer[
"version"].get_int()};
547 const int64_t conn_time{peer[
"conntime"].get_int64()};
548 const int64_t last_blck{peer[
"last_block"].get_int64()};
549 const int64_t last_recv{peer[
"lastrecv"].get_int64()};
550 const int64_t last_send{peer[
"lastsend"].get_int64()};
551 const int64_t last_trxn{peer[
"last_transaction"].get_int64()};
552 const double min_ping{
553 peer[
"minping"].isNull() ? -1 : peer[
"minping"].get_real()};
554 const double ping{peer[
"pingtime"].isNull()
556 : peer[
"pingtime"].get_real()};
557 const std::string addr{peer[
"addr"].get_str()};
558 const std::string age{
561 const std::string sub_version{peer[
"subver"].get_str()};
562 m_peers.push_back({addr, sub_version, network, age, min_ping,
563 ping, last_blck, last_recv, last_send,
564 last_trxn, peer_id, mapped_as, version,
565 is_block_relay, is_outbound});
576 std::string result{
strprintf(
"%s %s%s - %i%s\n\n", PACKAGE_NAME,
578 networkinfo[
"protocolversion"].get_int(),
579 networkinfo[
"subversion"].get_str())};
586 "Peer connections sorted by direction and min ping\n<-> relay "
587 " net mping ping send recv txn blk %*s ",
597 std::string version{
ToString(peer.version) + peer.sub_version};
599 "%3s %5s %5s%7s%7s%5s%5s%5s%5s %*s%*i %*s %-*s%s\n",
600 peer.is_outbound ?
"out" :
"in",
601 peer.is_block_relay ?
"block" :
"full", peer.network,
604 peer.last_send == 0 ?
""
606 peer.last_recv == 0 ?
""
629 " ms ms sec sec min min %*s\n\n",
634 result +=
" ipv4 ipv6 onion total block-relay\n";
635 const std::array<std::string, 3> rows{{
"in",
"out",
"total"}};
637 result +=
strprintf(
"%-5s %5i %5i %5i %5i %5i\n",
645 result +=
"\nLocal addresses";
646 const std::vector<UniValue> &local_addrs{
647 networkinfo[
"localaddresses"].getValues()};
648 if (local_addrs.empty()) {
651 size_t max_addr_size{0};
652 for (
const UniValue &addr : local_addrs) {
653 max_addr_size = std::max(addr[
"address"].get_str().length() + 1,
656 for (
const UniValue &addr : local_addrs) {
658 strprintf(
"\n%-*s port %6i score %6i", max_addr_size,
659 addr[
"address"].get_str(), addr[
"port"].get_int(),
660 addr[
"score"].get_int());
672 const std::vector<std::string> &args)
override {
693 const std::vector<std::string> &args)
override {
709 const std::vector<std::string> &args,
710 const std::optional<std::string> &rpcwallet = {}) {
724 raii_evhttp_connection evcon =
732 evhttp_connection_set_timeout(evcon.get(), timeout);
738 constexpr
int YEAR_IN_SECONDS = 31556952;
739 evhttp_connection_set_timeout(evcon.get(), 5 * YEAR_IN_SECONDS);
744 raii_evhttp_request req =
746 if (req ==
nullptr) {
747 throw std::runtime_error(
"create http request failed");
749 #if LIBEVENT_VERSION_NUMBER >= 0x02010300
750 evhttp_request_set_error_cb(req.get(), http_error_cb);
755 bool failedToGetAuthCookie =
false;
760 failedToGetAuthCookie =
true;
767 struct evkeyvalq *output_headers =
768 evhttp_request_get_output_headers(req.get());
770 evhttp_add_header(output_headers,
"Host", host.c_str());
771 evhttp_add_header(output_headers,
"Connection",
"close");
772 evhttp_add_header(output_headers,
"Content-Type",
"application/json");
774 output_headers,
"Authorization",
779 struct evbuffer *output_buffer =
780 evhttp_request_get_output_buffer(req.get());
782 evbuffer_add(output_buffer, strRequest.data(), strRequest.size());
785 std::string endpoint =
"/";
788 evhttp_uriencode(rpcwallet->data(), rpcwallet->size(),
false);
790 endpoint =
"/wallet/" + std::string(encodedURI);
796 int r = evhttp_make_request(evcon.get(), req.get(), EVHTTP_REQ_POST,
804 event_base_dispatch(base.get());
807 std::string responseErrorMessage;
809 responseErrorMessage =
814 strprintf(
"Could not connect to the server %s:%d%s\n\nMake sure "
815 "the bitcoind server is running and that you are "
816 "connecting to the correct RPC port.",
817 host, port, responseErrorMessage));
819 if (failedToGetAuthCookie) {
821 "Could not locate RPC credentials. No authentication cookie "
822 "could be found, and RPC password is not set. See "
823 "-rpcpassword and -stdinrpcpass. Configuration file: (%s)",
827 throw std::runtime_error(
828 "Authorization failed: Incorrect rpcuser or rpcpassword");
831 throw std::runtime_error(
836 throw std::runtime_error(
839 throw std::runtime_error(
"no response from server");
844 if (!valReply.read(
response.body)) {
845 throw std::runtime_error(
"couldn't parse reply from server");
849 throw std::runtime_error(
850 "expected reply to have result, error and id properties");
869 const std::vector<std::string> &args,
870 const std::optional<std::string> &rpcwallet = {}) {
879 if (!
error.isNull() &&
910 if (
error.isObject()) {
914 strPrint =
"error code: " + err_code.
getValStr() +
"\n";
916 if (err_msg.
isStr()) {
917 strPrint += (
"error message:\n" + err_msg.
get_str());
919 if (err_code.
isNum() &&
921 strPrint +=
"\nTry adding \"-rpcwallet=<filename>\" option to "
922 "bitcoin-cli command line.";
925 strPrint =
"error: " +
error.write();
927 nRet = abs(
error[
"code"].get_int());
946 if (wallets.
size() <= 1) {
952 const std::string wallet_name =
wallet.get_str();
956 getbalances.find_value(
"result")[
"mine"][
"trusted"];
959 result.
pushKV(
"balances", balances);
967 std::optional<std::string> wallet_name{};
983 std::vector<std::string> &args) {
984 if (args.size() > 2) {
985 throw std::runtime_error(
986 "too many arguments (maximum 2 for nblocks and maxtries)");
988 if (args.size() == 0) {
990 }
else if (args.at(0) ==
"0") {
991 throw std::runtime_error(
992 "the first argument (number of blocks to generate, default: " +
995 args.emplace(args.begin() + 1, address);
999 std::string strPrint;
1007 std::string rpcPass;
1011 fputs(
"RPC password> ", stderr);
1014 if (!std::getline(std::cin, rpcPass)) {
1015 throw std::runtime_error(
"-stdinrpcpass specified but failed "
1016 "to read from standard input");
1019 fputc(
'\n', stdout);
1023 std::vector<std::string> args =
1024 std::vector<std::string>(&argv[1], &argv[argc]);
1027 std::string walletPass;
1028 if (args.size() < 1 ||
1029 args[0].substr(0, 16) !=
"walletpassphrase") {
1030 throw std::runtime_error(
1031 "-stdinwalletpassphrase is only applicable for "
1032 "walletpassphrase(change)");
1035 fputs(
"Wallet passphrase> ", stderr);
1038 if (!std::getline(std::cin, walletPass)) {
1039 throw std::runtime_error(
"-stdinwalletpassphrase specified but "
1040 "failed to read from standard input");
1043 fputc(
'\n', stdout);
1045 args.insert(args.begin() + 1, walletPass);
1050 while (std::getline(std::cin, line)) {
1051 args.push_back(line);
1054 fputc(
'\n', stdout);
1057 std::unique_ptr<BaseRequestHandler> rh;
1064 if (
error.isNull()) {
1075 if (args.size() < 1) {
1076 throw std::runtime_error(
1077 "too few parameters (need at least command)");
1081 args.erase(args.begin());
1086 std::optional<std::string> wallet_name{};
1096 if (
error.isNull()) {
1107 }
catch (
const std::exception &e) {
1108 strPrint = std::string(
"error: ") + e.what();
1109 nRet = EXIT_FAILURE;
1115 if (strPrint !=
"") {
1116 tfm::format(nRet == 0 ? std::cout : std::cerr,
"%s\n", strPrint);
1127 __declspec(dllexport)
int main(
int argc,
char *argv[]) {
1128 util::WinCmdLineArgs winArgs;
1129 std::tie(argc, argv) = winArgs.get();
1135 tfm::format(std::cerr,
"Error: Initializing networking failed\n");
1136 return EXIT_FAILURE;
1145 }
catch (
const std::exception &e) {
1147 return EXIT_FAILURE;
1150 return EXIT_FAILURE;
1153 int ret = EXIT_FAILURE;
1156 }
catch (
const std::exception &e) {
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 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.
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.
std::unique_ptr< CBaseChainParams > CreateBaseChainParams(const std::string &chain)
Port numbers for incoming Tor connections (8334, 18334, 38334, 18445) have been chosen arbitrarily to...
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.
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.
std::string GetChainName() const
Looks for -regtest, -testnet and returns the appropriate BIP70 chain name.
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
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.
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
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 UniValue & get_obj() const
const std::string & getValStr() const
const std::vector< UniValue > & getValues() const
bool push_back(const UniValue &val)
bool pushKV(const std::string &key, const 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()
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()
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::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()
std::string EncodeBase64(Span< const uint8_t > input)
void SplitHostPort(std::string in, uint16_t &portOut, std::string &hostOut)
bool ParseUInt8(const std::string &str, uint8_t *out)
Convert decimal string to unsigned 8-bit integer with strict parse error feedback.
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Reply structure for request_done to fill in.
bool operator<(const Peer &rhs) const
bool HelpRequested(const ArgsManager &args)
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
bool CheckDataDirOption()
fs::path GetConfigFile(const std::string &confPath)
void PrintExceptionContinue(const std::exception *pex, const char *pszThread)
const char *const BITCOIN_CONF_FILENAME
bool error(const char *fmt, const Args &...args)
bool IsSwitchChar(char c)
void UninterruptibleSleep(const std::chrono::microseconds &n)
const UniValue NullUniValue