Skip to content

Commit 3826253

Browse files
laanwjachow101
authored andcommitted
rpc: Handle getinfo locally in bitcoin-cli w/ -getinfo
This adds the infrastructure `BaseRequestHandler` class that takes care of converting bitcoin-cli arguments into a JSON-RPC request object, and converting the reply into a JSON object that can be shown as result. This is subsequently used to handle the `-getinfo` option, which sends a JSON-RPC batch request to the RPC server with `["getnetworkinfo", "getblockchaininfo", "getwalletinfo"]`, and after reply combines the result into what looks like a `getinfo` result. There have been some requests for a client-side `getinfo` and this is my PoC of how to do it. If this is considered a good idea some of the logic could be moved up to rpcclient.cpp and used in the GUI console as well. Extra-Author: Andrew Chow <[email protected]>
1 parent ea729d5 commit 3826253

File tree

3 files changed

+127
-15
lines changed

3 files changed

+127
-15
lines changed

src/bitcoin-cli.cpp

Lines changed: 105 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ std::string HelpMessageCli()
3737
strUsage += HelpMessageOpt("-?", _("This help message"));
3838
strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), BITCOIN_CONF_FILENAME));
3939
strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory"));
40+
strUsage += HelpMessageOpt("-getinfo", _("Get general information from the remote server. Note that unlike server-side RPC calls, the results of -getinfo is the result of multiple non-atomic requests. Some entries in the result may represent results from different states (e.g. wallet balance may be as of a different block from the chain state reported)"));
4041
AppendParamsHelpMessages(strUsage);
4142
strUsage += HelpMessageOpt("-named", strprintf(_("Pass named instead of positional arguments (default: %s)"), DEFAULT_NAMED));
4243
strUsage += HelpMessageOpt("-rpcconnect=<ip>", strprintf(_("Send commands to node running on <ip> (default: %s)"), DEFAULT_RPCCONNECT));
@@ -191,7 +192,96 @@ static void http_error_cb(enum evhttp_request_error err, void *ctx)
191192
}
192193
#endif
193194

194-
static UniValue CallRPC(const std::string& strMethod, const UniValue& params)
195+
/** Class that handles the conversion from a command-line to a JSON-RPC request,
196+
* as well as converting back to a JSON object that can be shown as result.
197+
*/
198+
class BaseRequestHandler
199+
{
200+
public:
201+
virtual UniValue PrepareRequest(const std::string& method, const std::vector<std::string>& args) = 0;
202+
virtual UniValue ProcessReply(const UniValue &batch_in) = 0;
203+
};
204+
205+
/** Process getinfo requests */
206+
class GetinfoRequestHandler: public BaseRequestHandler
207+
{
208+
public:
209+
const int ID_NETWORKINFO = 0;
210+
const int ID_BLOCKCHAININFO = 1;
211+
const int ID_WALLETINFO = 2;
212+
213+
/** Create a simulated `getinfo` request. */
214+
UniValue PrepareRequest(const std::string& method, const std::vector<std::string>& args) override
215+
{
216+
UniValue result(UniValue::VARR);
217+
result.push_back(JSONRPCRequestObj("getnetworkinfo", NullUniValue, ID_NETWORKINFO));
218+
result.push_back(JSONRPCRequestObj("getblockchaininfo", NullUniValue, ID_BLOCKCHAININFO));
219+
result.push_back(JSONRPCRequestObj("getwalletinfo", NullUniValue, ID_WALLETINFO));
220+
return result;
221+
}
222+
223+
/** Collect values from the batch and form a simulated `getinfo` reply. */
224+
UniValue ProcessReply(const UniValue &batch_in) override
225+
{
226+
UniValue result(UniValue::VOBJ);
227+
std::vector<UniValue> batch = JSONRPCProcessBatchReply(batch_in, 3);
228+
// Errors in getnetworkinfo() and getblockchaininfo() are fatal, pass them on
229+
// getwalletinfo() is allowed to fail in case there is no wallet.
230+
if (!batch[ID_NETWORKINFO]["error"].isNull()) {
231+
return batch[ID_NETWORKINFO];
232+
}
233+
if (!batch[ID_BLOCKCHAININFO]["error"].isNull()) {
234+
return batch[ID_BLOCKCHAININFO];
235+
}
236+
result.pushKV("version", batch[ID_NETWORKINFO]["result"]["version"]);
237+
result.pushKV("protocolversion", batch[ID_NETWORKINFO]["result"]["protocolversion"]);
238+
if (!batch[ID_WALLETINFO].isNull()) {
239+
result.pushKV("walletversion", batch[ID_WALLETINFO]["result"]["walletversion"]);
240+
result.pushKV("balance", batch[ID_WALLETINFO]["result"]["balance"]);
241+
}
242+
result.pushKV("blocks", batch[ID_BLOCKCHAININFO]["result"]["blocks"]);
243+
result.pushKV("timeoffset", batch[ID_NETWORKINFO]["result"]["timeoffset"]);
244+
result.pushKV("connections", batch[ID_NETWORKINFO]["result"]["connections"]);
245+
result.pushKV("proxy", batch[ID_NETWORKINFO]["result"]["networks"][0]["proxy"]);
246+
result.pushKV("difficulty", batch[ID_BLOCKCHAININFO]["result"]["difficulty"]);
247+
result.pushKV("testnet", UniValue(batch[ID_BLOCKCHAININFO]["result"]["chain"].get_str() == "test"));
248+
if (!batch[ID_WALLETINFO].isNull()) {
249+
result.pushKV("walletversion", batch[ID_WALLETINFO]["result"]["walletversion"]);
250+
result.pushKV("balance", batch[ID_WALLETINFO]["result"]["balance"]);
251+
result.pushKV("keypoololdest", batch[ID_WALLETINFO]["result"]["keypoololdest"]);
252+
result.pushKV("keypoolsize", batch[ID_WALLETINFO]["result"]["keypoolsize"]);
253+
if (!batch[ID_WALLETINFO]["result"]["unlocked_until"].isNull()) {
254+
result.pushKV("unlocked_until", batch[ID_WALLETINFO]["result"]["unlocked_until"]);
255+
}
256+
result.pushKV("paytxfee", batch[ID_WALLETINFO]["result"]["paytxfee"]);
257+
}
258+
result.pushKV("relayfee", batch[ID_NETWORKINFO]["result"]["relayfee"]);
259+
result.pushKV("warnings", batch[ID_NETWORKINFO]["result"]["warnings"]);
260+
return JSONRPCReplyObj(result, NullUniValue, 1);
261+
}
262+
};
263+
264+
/** Process default single requests */
265+
class DefaultRequestHandler: public BaseRequestHandler {
266+
public:
267+
UniValue PrepareRequest(const std::string& method, const std::vector<std::string>& args) override
268+
{
269+
UniValue params;
270+
if(gArgs.GetBoolArg("-named", DEFAULT_NAMED)) {
271+
params = RPCConvertNamedValues(method, args);
272+
} else {
273+
params = RPCConvertValues(method, args);
274+
}
275+
return JSONRPCRequestObj(method, params, 1);
276+
}
277+
278+
UniValue ProcessReply(const UniValue &reply) override
279+
{
280+
return reply.get_obj();
281+
}
282+
};
283+
284+
static UniValue CallRPC(BaseRequestHandler *rh, const std::string& strMethod, const std::vector<std::string>& args)
195285
{
196286
std::string host;
197287
// In preference order, we choose the following for the port:
@@ -238,7 +328,7 @@ static UniValue CallRPC(const std::string& strMethod, const UniValue& params)
238328
evhttp_add_header(output_headers, "Authorization", (std::string("Basic ") + EncodeBase64(strRPCUserColonPass)).c_str());
239329

240330
// Attach request data
241-
std::string strRequest = JSONRPCRequestObj(strMethod, params, 1).write() + "\n";
331+
std::string strRequest = rh->PrepareRequest(strMethod, args).write() + "\n";
242332
struct evbuffer* output_buffer = evhttp_request_get_output_buffer(req.get());
243333
assert(output_buffer);
244334
evbuffer_add(output_buffer, strRequest.data(), strRequest.size());
@@ -277,7 +367,7 @@ static UniValue CallRPC(const std::string& strMethod, const UniValue& params)
277367
UniValue valReply(UniValue::VSTR);
278368
if (!valReply.read(response.body))
279369
throw std::runtime_error("couldn't parse reply from server");
280-
const UniValue& reply = valReply.get_obj();
370+
const UniValue reply = rh->ProcessReply(valReply);
281371
if (reply.empty())
282372
throw std::runtime_error("expected reply to have result, error and id properties");
283373

@@ -309,24 +399,25 @@ int CommandLineRPC(int argc, char *argv[])
309399
args.push_back(line);
310400
}
311401
}
312-
if (args.size() < 1) {
313-
throw std::runtime_error("too few parameters (need at least command)");
314-
}
315-
std::string strMethod = args[0];
316-
args.erase(args.begin()); // Remove trailing method name from arguments vector
317-
318-
UniValue params;
319-
if(gArgs.GetBoolArg("-named", DEFAULT_NAMED)) {
320-
params = RPCConvertNamedValues(strMethod, args);
402+
std::unique_ptr<BaseRequestHandler> rh;
403+
std::string method;
404+
if (gArgs.GetBoolArg("-getinfo", false)) {
405+
rh.reset(new GetinfoRequestHandler());
406+
method = "";
321407
} else {
322-
params = RPCConvertValues(strMethod, args);
408+
rh.reset(new DefaultRequestHandler());
409+
if (args.size() < 1) {
410+
throw std::runtime_error("too few parameters (need at least command)");
411+
}
412+
method = args[0];
413+
args.erase(args.begin()); // Remove trailing method name from arguments vector
323414
}
324415

325416
// Execute and handle connection failures with -rpcwait
326417
const bool fWait = gArgs.GetBoolArg("-rpcwait", false);
327418
do {
328419
try {
329-
const UniValue reply = CallRPC(strMethod, params);
420+
const UniValue reply = CallRPC(rh.get(), method, args);
330421

331422
// Parse reply
332423
const UniValue& result = find_value(reply, "result");

src/rpc/protocol.cpp

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
* JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
2020
* but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
2121
* unspecified (HTTP errors and contents of 'error').
22-
*
22+
*
2323
* 1.0 spec: http://json-rpc.org/wiki/specification
2424
* 1.2 spec: http://jsonrpc.org/historical/json-rpc-over-http.html
2525
*/
@@ -135,3 +135,22 @@ void DeleteAuthCookie()
135135
}
136136
}
137137

138+
std::vector<UniValue> JSONRPCProcessBatchReply(const UniValue &in, size_t num)
139+
{
140+
if (!in.isArray()) {
141+
throw std::runtime_error("Batch must be an array");
142+
}
143+
std::vector<UniValue> batch(num);
144+
for (size_t i=0; i<in.size(); ++i) {
145+
const UniValue &rec = in[i];
146+
if (!rec.isObject()) {
147+
throw std::runtime_error("Batch member must be object");
148+
}
149+
size_t id = rec["id"].get_int();
150+
if (id >= num) {
151+
throw std::runtime_error("Batch member id larger than size");
152+
}
153+
batch[id] = rec;
154+
}
155+
return batch;
156+
}

src/rpc/protocol.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,5 +97,7 @@ bool GenerateAuthCookie(std::string *cookie_out);
9797
bool GetAuthCookie(std::string *cookie_out);
9898
/** Delete RPC authentication cookie from disk */
9999
void DeleteAuthCookie();
100+
/** Parse JSON-RPC batch reply into a vector */
101+
std::vector<UniValue> JSONRPCProcessBatchReply(const UniValue &in, size_t num);
100102

101103
#endif // BITCOIN_RPCPROTOCOL_H

0 commit comments

Comments
 (0)