6 #if defined(HAVE_CONFIG_H) 20 #include <event2/buffer.h> 21 #include <event2/keyvalq_struct.h> 26 static const char DEFAULT_RPCCONNECT[] =
"127.0.0.1";
27 static const int DEFAULT_HTTP_CLIENT_TIMEOUT=900;
28 static const bool DEFAULT_NAMED=
false;
29 static const int CONTINUE_EXECUTION=-1;
39 strUsage +=
HelpMessageOpt(
"-datadir=<dir>",
_(
"Specify data directory"));
41 strUsage +=
HelpMessageOpt(
"-named",
strprintf(
_(
"Pass named instead of positional arguments (default: %s)"), DEFAULT_NAMED));
42 strUsage +=
HelpMessageOpt(
"-rpcconnect=<ip>",
strprintf(
_(
"Send commands to node running on <ip> (default: %s)"), DEFAULT_RPCCONNECT));
43 strUsage +=
HelpMessageOpt(
"-rpcport=<port>",
strprintf(
_(
"Connect to JSON-RPC on <port> (default: %u or testnet: %u)"), defaultBaseParams->RPCPort(), testnetBaseParams->RPCPort()));
44 strUsage +=
HelpMessageOpt(
"-rpcwait",
_(
"Wait for RPC server to start"));
45 strUsage +=
HelpMessageOpt(
"-rpcuser=<user>",
_(
"Username for JSON-RPC connections"));
46 strUsage +=
HelpMessageOpt(
"-rpcpassword=<pw>",
_(
"Password for JSON-RPC connections"));
47 strUsage +=
HelpMessageOpt(
"-rpcclienttimeout=<n>",
strprintf(
_(
"Timeout in seconds during HTTP requests, or 0 for no timeout. (default: %d)"), DEFAULT_HTTP_CLIENT_TIMEOUT));
48 strUsage +=
HelpMessageOpt(
"-stdin",
_(
"Read extra arguments from standard input, one per line until EOF/Ctrl-D (recommended for sensitive information such as passphrases)"));
49 strUsage +=
HelpMessageOpt(
"-rpcwallet=<walletname>",
_(
"Send RPC for non-default wallet on RPC server (argument is wallet filename in fabcoind directory, required if fabcoind/-Qt runs with multiple wallets)"));
68 std::runtime_error(msg)
77 static int AppInitRPC(
int argc,
char* argv[])
86 strUsage +=
"\n" +
_(
"Usage:") +
"\n" +
88 " fabcoin-cli [options] -named <command> [name=value] ... " +
strprintf(
_(
"Send command to %s (with named arguments)"),
_(
PACKAGE_NAME)) +
"\n" +
89 " fabcoin-cli [options] help " +
_(
"List commands") +
"\n" +
90 " fabcoin-cli [options] help <command> " +
_(
"Get help for a command") +
"\n";
95 fprintf(stdout,
"%s", strUsage.c_str());
97 fprintf(stderr,
"Error: too few parameters\n");
103 fprintf(stderr,
"Error: Specified data directory \"%s\" does not exist.\n",
gArgs.
GetArg(
"-datadir",
"").c_str());
108 }
catch (
const std::exception&
e) {
109 fprintf(stderr,
"Error reading configuration file: %s\n", e.what());
115 }
catch (
const std::exception& e) {
116 fprintf(stderr,
"Error: %s\n", e.what());
121 fprintf(stderr,
"Error: SSL mode for RPC (-rpcssl) is no longer supported.\n");
124 return CONTINUE_EXECUTION;
141 #if LIBEVENT_VERSION_NUMBER >= 0x02010300 142 case EVREQ_HTTP_TIMEOUT:
143 return "timeout reached";
145 return "EOF reached";
146 case EVREQ_HTTP_INVALID_HEADER:
147 return "error while reading header, or invalid header";
148 case EVREQ_HTTP_BUFFER_ERROR:
149 return "error encountered while reading or writing";
150 case EVREQ_HTTP_REQUEST_CANCEL:
151 return "request was canceled";
152 case EVREQ_HTTP_DATA_TOO_LONG:
153 return "response body is larger than allowed";
160 static void http_request_done(
struct evhttp_request *req,
void *ctx)
164 if (req ==
nullptr) {
172 reply->
status = evhttp_request_get_response_code(req);
174 struct evbuffer *buf = evhttp_request_get_input_buffer(req);
177 size_t size = evbuffer_get_length(buf);
178 const char *
data = (
const char*)evbuffer_pullup(buf, size);
180 reply->
body = std::string(data, size);
181 evbuffer_drain(buf, size);
185 #if LIBEVENT_VERSION_NUMBER >= 0x02010300 186 static void http_error_cb(
enum evhttp_request_error err,
void *ctx)
209 evhttp_connection_set_timeout(evcon.get(),
gArgs.
GetArg(
"-rpcclienttimeout", DEFAULT_HTTP_CLIENT_TIMEOUT));
214 throw std::runtime_error(
"create http request failed");
215 #if LIBEVENT_VERSION_NUMBER >= 0x02010300 216 evhttp_request_set_error_cb(req.get(), http_error_cb);
220 std::string strRPCUserColonPass;
225 _(
"Could not locate RPC credentials. No authentication cookie could be found, and no rpcpassword is set in the configuration file (%s)"),
233 struct evkeyvalq* output_headers = evhttp_request_get_output_headers(req.get());
235 evhttp_add_header(output_headers,
"Host", host.c_str());
236 evhttp_add_header(output_headers,
"Connection",
"close");
237 evhttp_add_header(output_headers,
"Authorization", (std::string(
"Basic ") +
EncodeBase64(strRPCUserColonPass)).c_str());
241 struct evbuffer* output_buffer = evhttp_request_get_output_buffer(req.get());
243 evbuffer_add(output_buffer, strRequest.data(), strRequest.size());
246 std::string endpoint =
"/";
247 std::string walletName =
gArgs.
GetArg(
"-rpcwallet",
"");
248 if (!walletName.empty()) {
249 char *encodedURI = evhttp_uriencode(walletName.c_str(), walletName.size(),
false);
251 endpoint =
"/wallet/"+ std::string(encodedURI);
258 int r = evhttp_make_request(evcon.get(), req.get(), EVHTTP_REQ_POST, endpoint.c_str());
264 event_base_dispatch(base.get());
266 if (response.status == 0)
267 throw CConnectionFailed(
strprintf(
"couldn't connect to server: %s (code %d)\n(make sure server is running and you are connecting to the correct RPC port)",
http_errorstring(response.error), response.error));
269 throw std::runtime_error(
"incorrect rpcuser or rpcpassword (authorization failed)");
271 throw std::runtime_error(
strprintf(
"server returned HTTP error %d", response.status));
272 else if (response.body.empty())
273 throw std::runtime_error(
"no response from server");
277 if (!valReply.
read(response.body))
278 throw std::runtime_error(
"couldn't parse reply from server");
281 throw std::runtime_error(
"expected reply to have result, error and id properties");
288 std::string strPrint;
296 std::vector<std::string> args = std::vector<std::string>(&argv[1], &argv[argc]);
300 while (std::getline(std::cin,line))
301 args.push_back(line);
304 throw std::runtime_error(
"too few parameters (need at least command)");
305 std::string strMethod = args[0];
306 args.erase(args.begin());
330 strPrint =
"error: " + error.
write();
336 strPrint = errCode.
isNull() ?
"" :
"error code: "+errCode.
getValStr()+
"\n";
339 strPrint +=
"error message:\n"+errMsg.
get_str();
342 strPrint +=
"\nTry adding \"-rpcwallet=<filename>\" option to fabcoin-cli command line.";
349 else if (result.
isStr())
352 strPrint = result.
write(2);
365 catch (
const boost::thread_interrupted&) {
368 catch (
const std::exception&
e) {
369 strPrint = std::string(
"error: ") + e.what();
377 if (strPrint !=
"") {
378 fprintf((nRet == 0 ? stdout : stderr),
"%s\n", strPrint.c_str());
383 int main(
int argc,
char* argv[])
387 fprintf(stderr,
"Error: Initializing networking failed\n");
392 int ret = AppInitRPC(argc, argv);
393 if (ret != CONTINUE_EXECUTION)
396 catch (
const std::exception&
e) {
404 int ret = EXIT_FAILURE;
408 catch (
const std::exception& e) {
No wallet specified (error when there are multiple wallets loaded)
std::string HelpMessageOpt(const std::string &option, const std::string &message)
Format a string to be used as option description in help messages.
bool error(const char *fmt, const Args &...args)
const std::string & get_str() const
std::unique_ptr< CBaseChainParams > CreateBaseChainParams(const std::string &chain)
Creates and returns a std::unique_ptr<CBaseChainParams> of the chosen chain.
void AppendParamsHelpMessages(std::string &strUsage, bool debugHelp)
Append the help messages for the chainparams options to the parameter string.
raii_event_base obtain_event_base()
void ParseParameters(int argc, const char *const argv[])
void MilliSleep(int64_t n)
UniValue CallRPC(const std::string &strMethod, const UniValue ¶ms)
bool IsArgSet(const std::string &strArg)
Return true if the given argument has been manually set.
bool read(const char *raw, size_t len)
UniValue JSONRPCRequestObj(const std::string &strMethod, const UniValue ¶ms, const UniValue &id)
JSON-RPC protocol.
const char * http_errorstring(int code)
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
bool GetBoolArg(const std::string &strArg, bool fDefault)
Return boolean argument or default value.
void PrintExceptionContinue(const std::exception *pex, const char *pszThread)
std::hash for asio::adress
raii_evhttp_request obtain_evhttp_request(void(*cb)(struct evhttp_request *, void *), void *arg)
assert(len-trim+(2 *lenIndices)<=WIDTH)
int CommandLineRPC(int argc, char *argv[])
void ReadConfigFile(const std::string &confPath)
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.
bool GetAuthCookie(std::string *cookie_out)
Read the RPC authentication cookie from disk.
const char *const FABCOIN_CONF_FILENAME
const Object_type::value_type::Value_type & find_value(const Object_type &obj, const String_type &name)
raii_evhttp_connection obtain_evhttp_connection_base(struct event_base *base, std::string host, uint16_t port)
std::string FormatFullVersion()
CConnectionFailed(const std::string &msg)
bool IsSwitchChar(char c)
const std::string & getValStr() const
void SplitHostPort(std::string in, int &portOut, std::string &hostOut)
uint8_t const size_t const size
fs::path GetConfigFile(const std::string &confPath)
std::string GetArg(const std::string &strArg, const std::string &strDefault)
Return string argument or default value.
std::string ChainNameFromCommandLine()
Looks for -regtest, -testnet and returns the appropriate BIP70 chain name.
std::string HelpMessageCli()
UniValue RPCConvertNamedValues(const std::string &strMethod, const std::vector< std::string > &strParams)
Convert named arguments to command-specific RPC representation.
static const std::string TESTNET
const fs::path & GetDataDir(bool fNetSpecific)
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
void SelectBaseParams(const std::string &chain)
Sets the params returned by Params() to those for the given network.
const UniValue & get_obj() const
std::string HelpMessageGroup(const std::string &message)
Format a string to be used as group of options in help messages.
int main(int argc, char *argv[])
std::string _(const char *psz)
Translation function: Call Translate signal on UI interface, which returns a boost::optional result...
Reply structure for request_done to fill in.
std::string EncodeBase64(const unsigned char *pch, size_t len)