Skip to content

Commit c9a4aa8

Browse files
committed
Merge #10871: Handle getinfo in bitcoin-cli w/ -getinfo (revival of #8843)
5e69a43 Add test for bitcoin-cli -getinfo (John Newbery) 3826253 rpc: Handle `getinfo` locally in bitcoin-cli w/ `-getinfo` (Wladimir J. van der Laan) Pull request description: Since @laanwj doesn't want to maintain these changes anymore, I will. This PR is a revival of #8843. I have addressed @jnewbery's comments. Regarding atomicity, I don't think that is a concern here. This is explicitly a new API and those who use it will know that this is different and that it is not atomic. Tree-SHA512: 9664ed13a5557bda8c43f34d6527669a641f260b7830e592409b28c845258fc7e0fdd85dd42bfa88c103fea3ecdfede5f81e3d91870e2accba81c6d6de6b21ff
2 parents d90a00e + 5e69a43 commit c9a4aa8

File tree

4 files changed

+150
-15
lines changed

4 files changed

+150
-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
@@ -98,5 +98,7 @@ bool GenerateAuthCookie(std::string *cookie_out);
9898
bool GetAuthCookie(std::string *cookie_out);
9999
/** Delete RPC authentication cookie from disk */
100100
void DeleteAuthCookie();
101+
/** Parse JSON-RPC batch reply into a vector */
102+
std::vector<UniValue> JSONRPCProcessBatchReply(const UniValue &in, size_t num);
101103

102104
#endif // BITCOIN_RPCPROTOCOL_H

test/functional/bitcoin_cli.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,5 +35,28 @@ def run_test(self):
3535
assert_equal(["foo", "bar"], self.nodes[0].cli('-rpcuser=%s' % user, '-stdin', '-stdinrpcpass', input=password + "\nfoo\nbar").echo())
3636
assert_raises_process_error(1, "incorrect rpcuser or rpcpassword", self.nodes[0].cli('-rpcuser=%s' % user, '-stdin', '-stdinrpcpass', input="foo").echo)
3737

38+
self.log.info("Compare responses from `bitcoin-cli -getinfo` and the RPCs data is retrieved from.")
39+
cli_get_info = self.nodes[0].cli('-getinfo').help()
40+
wallet_info = self.nodes[0].getwalletinfo()
41+
network_info = self.nodes[0].getnetworkinfo()
42+
blockchain_info = self.nodes[0].getblockchaininfo()
43+
44+
assert_equal(cli_get_info['version'], network_info['version'])
45+
assert_equal(cli_get_info['protocolversion'], network_info['protocolversion'])
46+
assert_equal(cli_get_info['walletversion'], wallet_info['walletversion'])
47+
assert_equal(cli_get_info['balance'], wallet_info['balance'])
48+
assert_equal(cli_get_info['blocks'], blockchain_info['blocks'])
49+
assert_equal(cli_get_info['timeoffset'], network_info['timeoffset'])
50+
assert_equal(cli_get_info['connections'], network_info['connections'])
51+
assert_equal(cli_get_info['proxy'], network_info['networks'][0]['proxy'])
52+
assert_equal(cli_get_info['difficulty'], blockchain_info['difficulty'])
53+
assert_equal(cli_get_info['testnet'], blockchain_info['chain'] == "test")
54+
assert_equal(cli_get_info['balance'], wallet_info['balance'])
55+
assert_equal(cli_get_info['keypoololdest'], wallet_info['keypoololdest'])
56+
assert_equal(cli_get_info['keypoolsize'], wallet_info['keypoolsize'])
57+
assert_equal(cli_get_info['paytxfee'], wallet_info['paytxfee'])
58+
assert_equal(cli_get_info['relayfee'], network_info['relayfee'])
59+
# unlocked_until is not tested because the wallet is not encrypted
60+
3861
if __name__ == '__main__':
3962
TestBitcoinCli().main()

0 commit comments

Comments
 (0)