1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
11 #include "bitcoinrpc.h"
16 #include <ixwebsocket/IXHttpServer.h>
17 #include <ixwebsocket/IXHttpClient.h>
18 #include <boost/algorithm/string.hpp>
22 #define printf OutputDebugStringF
24 using namespace json_spirit;
26 std::unique_ptr<ix::HttpServer> g_server;
28 static std::string strRPCUserColonPass;
30 const Object emptyobj;
32 static inline unsigned short GetDefaultRPCPort()
34 return GetBoolArg("-testnet", false) ? 18344 : 8344;
37 Object JSONRPCError(int code, const std::string& message)
40 error.push_back(Pair("code", code));
41 error.push_back(Pair("message", message));
45 void RPCTypeCheck(const Array& params,
46 const std::list<Value_type>& typesExpected,
50 for(Value_type t : typesExpected)
52 if (params.size() <= i)
55 const Value& v = params[i];
56 if (!((v.type() == t) || (fAllowNull && (v.type() == null_type))))
58 std::string err = strprintf("Expected type %s, got %s",
59 Value_type_name[t], Value_type_name[v.type()]);
60 throw JSONRPCError(RPC_TYPE_ERROR, err);
66 void RPCTypeCheck(const Object& o,
67 const std::map<std::string, Value_type>& typesExpected,
70 for(const auto& t : typesExpected)
72 const Value& v = find_value(o, t.first);
73 if (!fAllowNull && v.type() == null_type)
74 throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first.c_str()));
76 if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type))))
78 std::string err = strprintf("Expected type %s for %s, got %s",
79 Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]);
80 throw JSONRPCError(RPC_TYPE_ERROR, err);
85 int64_t AmountFromValue(const Value& value)
87 double dAmount = value.get_real();
88 if (dAmount <= 0.0 || dAmount > (double) (MAX_MONEY / 100000000))
89 throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
90 int64_t nAmount = roundint64(dAmount * COIN);
91 if (!MoneyRange(nAmount))
92 throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
96 Value ValueFromAmount(int64_t amount)
98 return (double)amount / (double)COIN;
101 std::string HexBits(unsigned int nBits)
107 uBits.nBits = htonl((int32_t)nBits);
108 return HexStr(BEGIN(uBits.cBits), END(uBits.cBits));
113 // Utilities: convert hex-encoded Values
114 // (throws error if not hex).
116 uint256 ParseHashV(const Value& v, std::string strName)
119 if (v.type() == str_type)
120 strHex = v.get_str();
121 if (!IsHex(strHex)) // Note: IsHex("") is false
122 throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
124 result.SetHex(strHex);
128 uint256 ParseHashO(const Object& o, std::string strKey)
130 return ParseHashV(find_value(o, strKey), strKey);
133 std::vector<unsigned char> ParseHexV(const Value& v, std::string strName)
136 if (v.type() == str_type)
137 strHex = v.get_str();
139 throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
140 return ParseHex(strHex);
143 std::vector<unsigned char> ParseHexO(const Object& o, std::string strKey)
145 return ParseHexV(find_value(o, strKey), strKey);
150 /// Note: This interface may still be subject to change.
153 std::string CRPCTable::help(std::string strCommand) const
156 std::set<rpcfn_type> setDone;
157 for (std::map<std::string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)
159 const CRPCCommand *pcmd = mi->second;
160 std::string strMethod = mi->first;
161 // We already filter duplicates, but these deprecated screw up the sort order
162 if (strMethod.find("label") != std::string::npos)
164 if (!strCommand.empty() && strMethod != strCommand)
169 rpcfn_type pfn = pcmd->actor;
170 if (setDone.insert(pfn).second)
171 (*pfn)(params, true);
173 catch (std::exception& e)
175 // Help text is returned in an exception
176 std::string strHelp = std::string(e.what());
177 if (strCommand.empty())
178 if (strHelp.find('\n') != std::string::npos)
179 strHelp = strHelp.substr(0, strHelp.find('\n'));
180 strRet += strHelp + '\n';
184 strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
185 strRet = strRet.substr(0,strRet.size()-1);
189 Value help(const Array& params, bool fHelp)
191 if (fHelp || params.size() > 1)
192 throw std::runtime_error(
194 "List commands, or get help for a command.");
196 std::string strCommand;
197 if (params.size() > 0)
198 strCommand = params[0].get_str();
200 return tableRPC.help(strCommand);
204 Value stop(const Array& params, bool fHelp)
206 if (fHelp || params.size() > 1)
207 throw std::runtime_error(
209 "<detach> is true or false to detach the database or not for this stop only\n"
210 "Stop NovaCoin server (and possibly override the detachdb config value).");
211 // Shutdown will take long enough that the response should get back
212 if (params.size() > 0)
213 bitdb.SetDetach(params[0].get_bool());
215 return "NovaCoin server stopping";
225 static const CRPCCommand vRPCCommands[] =
226 { // name function safemd unlocked
227 // ------------------------ ----------------------- ------ --------
228 { "help", &help, true, true },
229 { "stop", &stop, true, true },
230 { "getbestblockhash", &getbestblockhash, true, false },
231 { "getblockcount", &getblockcount, true, false },
232 { "getconnectioncount", &getconnectioncount, true, false },
233 { "getaddrmaninfo", &getaddrmaninfo, true, false },
234 { "getpeerinfo", &getpeerinfo, true, false },
235 { "addnode", &addnode, true, true },
236 { "getaddednodeinfo", &getaddednodeinfo, true, true },
237 { "getdifficulty", &getdifficulty, true, false },
238 { "getinfo", &getinfo, true, false },
239 { "getsubsidy", &getsubsidy, true, false },
240 { "getmininginfo", &getmininginfo, true, false },
241 { "scaninput", &scaninput, true, true },
242 { "getnewaddress", &getnewaddress, true, false },
243 { "getnettotals", &getnettotals, true, true },
244 { "ntptime", &ntptime, true, true },
245 { "getaccountaddress", &getaccountaddress, true, false },
246 { "setaccount", &setaccount, true, false },
247 { "getaccount", &getaccount, false, false },
248 { "getaddressesbyaccount", &getaddressesbyaccount, true, false },
249 { "sendtoaddress", &sendtoaddress, false, false },
250 { "mergecoins", &mergecoins, false, false },
251 { "getreceivedbyaddress", &getreceivedbyaddress, false, false },
252 { "getreceivedbyaccount", &getreceivedbyaccount, false, false },
253 { "listreceivedbyaddress", &listreceivedbyaddress, false, false },
254 { "listreceivedbyaccount", &listreceivedbyaccount, false, false },
255 { "backupwallet", &backupwallet, true, false },
256 { "keypoolrefill", &keypoolrefill, true, false },
257 { "keypoolreset", &keypoolreset, true, false },
258 { "walletpassphrase", &walletpassphrase, true, false },
259 { "walletpassphrasechange", &walletpassphrasechange, false, false },
260 { "walletlock", &walletlock, true, false },
261 { "encryptwallet", &encryptwallet, false, false },
262 { "validateaddress", &validateaddress, true, false },
263 { "getbalance", &getbalance, false, false },
264 { "move", &movecmd, false, false },
265 { "sendfrom", &sendfrom, false, false },
266 { "sendmany", &sendmany, false, false },
267 { "addmultisigaddress", &addmultisigaddress, false, false },
268 { "addredeemscript", &addredeemscript, false, false },
269 { "getrawmempool", &getrawmempool, true, false },
270 { "getblock", &getblock, false, false },
271 { "getblockbynumber", &getblockbynumber, false, false },
272 { "dumpblock", &dumpblock, false, false },
273 { "dumpblockbynumber", &dumpblockbynumber, false, false },
274 { "getblockhash", &getblockhash, false, false },
275 { "gettransaction", &gettransaction, false, false },
276 { "listtransactions", &listtransactions, false, false },
277 { "listaddressgroupings", &listaddressgroupings, false, false },
278 { "signmessage", &signmessage, false, false },
279 { "verifymessage", &verifymessage, false, false },
280 { "getwork", &getwork, true, false },
281 { "getworkex", &getworkex, true, false },
282 { "listaccounts", &listaccounts, false, false },
283 { "settxfee", &settxfee, false, false },
284 { "getblocktemplate", &getblocktemplate, true, false },
285 { "submitblock", &submitblock, false, false },
286 { "listsinceblock", &listsinceblock, false, false },
287 { "dumpprivkey", &dumpprivkey, false, false },
288 { "dumpwallet", &dumpwallet, true, false },
289 { "importwallet", &importwallet, false, false },
290 { "importprivkey", &importprivkey, false, false },
291 { "importaddress", &importaddress, false, true },
292 { "removeaddress", &removeaddress, false, true },
293 { "listunspent", &listunspent, false, false },
294 { "getrawtransaction", &getrawtransaction, false, false },
295 { "createrawtransaction", &createrawtransaction, false, false },
296 { "decoderawtransaction", &decoderawtransaction, false, false },
297 { "createmultisig", &createmultisig, false, false },
298 { "decodescript", &decodescript, false, false },
299 { "signrawtransaction", &signrawtransaction, false, false },
300 { "sendrawtransaction", &sendrawtransaction, false, false },
301 { "getcheckpoint", &getcheckpoint, true, false },
302 { "reservebalance", &reservebalance, false, true},
303 { "checkwallet", &checkwallet, false, true},
304 { "repairwallet", &repairwallet, false, true},
305 { "resendwallettransactions", &resendwallettransactions, false, true},
306 { "makekeypair", &makekeypair, false, true},
307 { "newmalleablekey", &newmalleablekey, false, false},
308 { "adjustmalleablekey", &adjustmalleablekey, false, false},
309 { "adjustmalleablepubkey", &adjustmalleablepubkey, false, false},
310 { "listmalleableviews", &listmalleableviews, false, false},
311 { "dumpmalleablekey", &dumpmalleablekey, false, false},
312 { "importmalleablekey", &importmalleablekey, true, false },
313 { "sendalert", &sendalert, false, false},
316 CRPCTable::CRPCTable()
319 for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++)
321 const CRPCCommand *pcmd;
323 pcmd = &vRPCCommands[vcidx];
324 mapCommands[pcmd->name] = pcmd;
328 const CRPCCommand *CRPCTable::operator[](std::string name) const
330 std::map<std::string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
331 if (it == mapCommands.end())
336 bool HTTPAuthorized(ix::WebSocketHttpHeaders& mapHeaders)
338 std::string strAuth = mapHeaders["authorization"];
339 if (strAuth.substr(0,6) != "Basic ")
341 std::string strUserPass64 = strAuth.substr(6); boost::algorithm::trim(strUserPass64);
342 std::string strUserPass = DecodeBase64(strUserPass64);
343 return TimingResistantEqual(strUserPass, strRPCUserColonPass);
347 // JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
348 // but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
349 // unspecified (HTTP errors and contents of 'error').
351 // 1.0 spec: http://json-rpc.org/wiki/specification
352 // 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
353 // http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
356 std::string JSONRPCRequest(const std::string& strMethod, const Array& params, const Value& id)
359 request.push_back(Pair("method", strMethod));
360 request.push_back(Pair("params", params));
361 request.push_back(Pair("id", id));
362 return write_string(Value(request), false) + "\n";
365 Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id)
368 if (error.type() != null_type)
369 reply.push_back(Pair("result", Value::null));
371 reply.push_back(Pair("result", result));
372 reply.push_back(Pair("error", error));
373 reply.push_back(Pair("id", id));
377 std::string JSONRPCReply(const Value& result, const Value& error, const Value& id)
379 Object reply = JSONRPCReplyObj(result, error, id);
380 return write_string(Value(reply), false) + "\n";
383 std::string ErrorReply(const Object& objError, const Value& id)
385 // Send error reply from json-rpc error object
386 int nStatus = HTTP_INTERNAL_SERVER_ERROR;
387 int code = find_value(objError, "code").get_int();
388 if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST;
389 else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND;
390 return JSONRPCReply(Value::null, objError, id);
397 std::string strMethod;
400 JSONRequest() { id = Value::null; }
401 void parse(const Value& valRequest);
404 void JSONRequest::parse(const Value& valRequest)
407 if (valRequest.type() != obj_type)
408 throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
409 const Object& request = valRequest.get_obj();
411 // Parse id now so errors from here on will have the id
412 id = find_value(request, "id");
415 Value valMethod = find_value(request, "method");
416 if (valMethod.type() == null_type)
417 throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
418 if (valMethod.type() != str_type)
419 throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
420 strMethod = valMethod.get_str();
421 if (strMethod != "getwork" && strMethod != "getblocktemplate")
422 printf("RPCServer method=%s\n", strMethod.c_str());
425 Value valParams = find_value(request, "params");
426 if (valParams.type() == array_type)
427 params = valParams.get_array();
428 else if (valParams.type() == null_type)
431 throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array");
434 static Object JSONRPCExecOne(const Value& req)
442 Value result = tableRPC.execute(jreq.strMethod, jreq.params);
443 rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id);
445 catch (Object& objError)
447 rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id);
449 catch (std::exception& e)
451 rpc_result = JSONRPCReplyObj(Value::null,
452 JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
458 static std::string JSONRPCExecBatch(const Array& vReq)
461 for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
462 ret.push_back(JSONRPCExecOne(vReq[reqIdx]));
464 return write_string(Value(ret), false) + "\n";
467 static CCriticalSection cs_THREAD_RPCHANDLER;
469 void StartRPCServer()
471 strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
472 if (mapArgs["-rpcpassword"].empty())
474 unsigned char rand_pwd[32];
475 RAND_bytes(rand_pwd, 32);
476 std::string strWhatAmI = "To use novacoind";
477 if (mapArgs.count("-server"))
478 strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
479 else if (mapArgs.count("-daemon"))
480 strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
481 uiInterface.ThreadSafeMessageBox(strprintf(
482 _("%s, you must set a rpcpassword in the configuration file:\n %s\n"
483 "It is recommended you use the following random password:\n"
484 "rpcuser=novacoinrpc\n"
486 "(you do not need to remember this password)\n"
487 "If the file does not exist, create it with owner-readable-only file permissions.\n"),
489 GetConfigFile().string().c_str(),
490 EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()),
491 _("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL);
496 std::string host = GetArg("-rpchost", "127.0.0.1");
497 int port = GetArg("-rpcport", GetDefaultRPCPort());
499 g_server = std::unique_ptr<ix::HttpServer>(new ix::HttpServer(port, host));
501 LOCK(cs_THREAD_RPCHANDLER);
503 g_server->setOnConnectionCallback([](ix::HttpRequestPtr request, std::shared_ptr<ix::ConnectionState> connectionState) -> ix::HttpResponsePtr {
505 ix::WebSocketHttpHeaders headers;
506 headers["Server"] = std::string("novacoin-json-rpc/") + FormatFullVersion();
507 headers["WWW-Authenticate"] = R"(Basic realm="jsonrpc")";
509 if (!HTTPAuthorized(request->headers))
511 printf("ThreadRPCServer incorrect password attempt from %s\n", connectionState->getRemoteIp().c_str());
512 connectionState->setTerminated();
513 return std::make_shared<ix::HttpResponse>(401, "Unauthorized", ix::HttpErrorCode::Ok, headers, "Not authorized");
516 if (request->method != "POST") {
517 connectionState->setTerminated();
518 return std::make_shared<ix::HttpResponse>(400, "Bad request", ix::HttpErrorCode::Ok, headers, "Bad request");
527 if (!read_string(request->body, valRequest))
528 throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
530 std::string strReply;
533 if (valRequest.type() == obj_type) {
534 jreq.parse(valRequest);
537 Value result = tableRPC.execute(jreq.strMethod, jreq.params);
540 strReply = JSONRPCReply(result, Value::null, jreq.id);
543 } else if (valRequest.type() == array_type)
544 // Execute batch of requests
545 strReply = JSONRPCExecBatch(valRequest.get_array());
547 throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
549 // Send reply to client
550 return std::make_shared<ix::HttpResponse>(200, "OK", ix::HttpErrorCode::Ok, headers, strReply);
553 catch(Object& objError)
555 return std::make_shared<ix::HttpResponse>(500, "Internal Server Error", ix::HttpErrorCode::Ok, headers, ErrorReply(objError, jreq.id));
557 catch(std::exception& e)
559 return std::make_shared<ix::HttpResponse>(500, "Internal Server Error", ix::HttpErrorCode::Ok, headers, ErrorReply(JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id));
563 std::pair<bool, std::string> result = g_server->listen();
565 auto strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on host %s: %s"), port, host.c_str(), result.second.c_str());
566 uiInterface.ThreadSafeMessageBox(strerr, _("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL);
567 return StartShutdown();
570 // Run listening thread
573 // We're listening now
574 vnThreadsRunning[THREAD_RPCLISTENER]++;
579 LOCK(cs_THREAD_RPCHANDLER);
580 if (g_server) g_server->stop();
581 vnThreadsRunning[THREAD_RPCLISTENER]--;
584 json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array ¶ms) const
587 const CRPCCommand *pcmd = tableRPC[strMethod];
589 throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
592 std::string strWarning = GetWarnings("rpc");
593 if (!strWarning.empty() && !GetBoolArg("-disablesafemode") &&
595 throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, std::string("Safe mode: ") + strWarning);
603 result = pcmd->actor(params, false);
605 LOCK2(cs_main, pwalletMain->cs_wallet);
606 result = pcmd->actor(params, false);
611 catch (std::exception& e)
613 throw JSONRPCError(RPC_MISC_ERROR, e.what());
617 std::vector<std::string> CRPCTable::listCommands() const
619 std::vector<std::string> commandList;
620 for (const auto& i : mapCommands) commandList.emplace_back(i.first);
624 Object CallRPC(const std::string& strMethod, const Array& params)
626 if (mapArgs["-rpcuser"].empty() && mapArgs["-rpcpassword"].empty())
627 throw std::runtime_error(strprintf(
628 _("You must set rpcpassword=<password> in the configuration file:\n%s\n"
629 "If the file does not exist, create it with owner-readable-only file permissions."),
630 GetConfigFile().string().c_str()));
632 // Init net subsystem
635 // Create HTTP client
636 ix::HttpClient httpClient;
637 ix::HttpRequestArgsPtr args = httpClient.createRequest();
639 // HTTP basic authentication
640 ix::WebSocketHttpHeaders mapRequestHeaders;
641 std::string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
642 mapRequestHeaders["Authorization"] = std::string("Basic ") + strUserPass64;
643 args->extraHeaders = mapRequestHeaders;
646 args->connectTimeout = GetArgInt("-rpc_connecttimeout", 30000);
647 args->transferTimeout = GetArgInt("-rpc_transfertimeout", 30000);
649 bool fUseSSL = GetBoolArg("-rpcssl");
650 std::string url = std::string(fUseSSL ? "https://" : "http://") + GetArg("-rpcconnect", "127.0.0.1") + ":" + GetArg("-rpcport", itostr(GetDefaultRPCPort()));
653 std::string strRequest = JSONRPCRequest(strMethod, params, GetRandInt(INT32_MAX));
654 auto out = httpClient.post(url, strRequest, args);
657 int nStatus = out->statusCode;
658 std::string strReply = out->body;
659 ix::WebSocketHttpHeaders mapHeaders = out->headers;
662 if (nStatus == HTTP_UNAUTHORIZED)
663 throw std::runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
664 else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR)
665 throw std::runtime_error(strprintf("server returned HTTP error %d", nStatus));
666 else if (strReply.empty())
667 throw std::runtime_error("no response from server");
671 if (!read_string(strReply, valReply))
672 throw std::runtime_error("couldn't parse reply from server");
673 const Object& reply = valReply.get_obj();
675 throw std::runtime_error("expected reply to have result, error and id properties");
684 void ConvertTo(Value& value, bool fAllowNull=false)
686 if (fAllowNull && value.type() == null_type)
688 if (value.type() == str_type)
690 // reinterpret string as unquoted json value
692 std::string strJSON = value.get_str();
693 if (!read_string(strJSON, value2))
694 throw std::runtime_error(std::string("Error parsing JSON:")+strJSON);
695 ConvertTo<T>(value2, fAllowNull);
700 value = value.get_value<T>();
704 // Convert strings to command-specific RPC representation
705 Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
708 for(const auto ¶m : strParams)
709 params.push_back(param);
711 size_t n = params.size();
714 // Special case non-string parameter types
716 if (strMethod == "stop" && n > 0) ConvertTo<bool>(params[0]);
717 if (strMethod == "getaddednodeinfo" && n > 0) ConvertTo<bool>(params[0]);
718 if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);
719 if (strMethod == "mergecoins" && n > 0) ConvertTo<double>(params[0]);
720 if (strMethod == "mergecoins" && n > 1) ConvertTo<double>(params[1]);
721 if (strMethod == "mergecoins" && n > 2) ConvertTo<double>(params[2]);
722 if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]);
723 if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<int64_t>(params[1]);
724 if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<int64_t>(params[1]);
725 if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<int64_t>(params[0]);
726 if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);
727 if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<int64_t>(params[0]);
728 if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]);
729 if (strMethod == "getbalance" && n > 1) ConvertTo<int64_t>(params[1]);
730 if (strMethod == "getblock" && n > 1) ConvertTo<bool>(params[1]);
731 if (strMethod == "getblockbynumber" && n > 0) ConvertTo<int64_t>(params[0]);
732 if (strMethod == "dumpblockbynumber" && n > 0) ConvertTo<int64_t>(params[0]);
733 if (strMethod == "getblockbynumber" && n > 1) ConvertTo<bool>(params[1]);
734 if (strMethod == "getblockhash" && n > 0) ConvertTo<int64_t>(params[0]);
735 if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]);
736 if (strMethod == "move" && n > 3) ConvertTo<int64_t>(params[3]);
737 if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]);
738 if (strMethod == "sendfrom" && n > 3) ConvertTo<int64_t>(params[3]);
739 if (strMethod == "listtransactions" && n > 1) ConvertTo<int64_t>(params[1]);
740 if (strMethod == "listtransactions" && n > 2) ConvertTo<int64_t>(params[2]);
741 if (strMethod == "listaccounts" && n > 0) ConvertTo<int64_t>(params[0]);
742 if (strMethod == "walletpassphrase" && n > 1) ConvertTo<int64_t>(params[1]);
743 if (strMethod == "walletpassphrase" && n > 2) ConvertTo<bool>(params[2]);
744 if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]);
745 if (strMethod == "listsinceblock" && n > 1) ConvertTo<int64_t>(params[1]);
747 if (strMethod == "scaninput" && n > 0) ConvertTo<Object>(params[0]);
749 if (strMethod == "sendalert" && n > 2) ConvertTo<int64_t>(params[2]);
750 if (strMethod == "sendalert" && n > 3) ConvertTo<int64_t>(params[3]);
751 if (strMethod == "sendalert" && n > 4) ConvertTo<int64_t>(params[4]);
752 if (strMethod == "sendalert" && n > 5) ConvertTo<int64_t>(params[5]);
753 if (strMethod == "sendalert" && n > 6) ConvertTo<int64_t>(params[6]);
755 if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]);
756 if (strMethod == "sendmany" && n > 2) ConvertTo<int64_t>(params[2]);
757 if (strMethod == "reservebalance" && n > 0) ConvertTo<bool>(params[0]);
758 if (strMethod == "reservebalance" && n > 1) ConvertTo<double>(params[1]);
759 if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<int64_t>(params[0]);
760 if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]);
761 if (strMethod == "listunspent" && n > 0) ConvertTo<int64_t>(params[0]);
762 if (strMethod == "listunspent" && n > 1) ConvertTo<int64_t>(params[1]);
763 if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]);
764 if (strMethod == "getrawtransaction" && n > 1) ConvertTo<int64_t>(params[1]);
765 if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]);
766 if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]);
767 if (strMethod == "createmultisig" && n > 0) ConvertTo<int64_t>(params[0]);
768 if (strMethod == "createmultisig" && n > 1) ConvertTo<Array>(params[1]);
769 if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1], true);
770 if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2], true);
771 if (strMethod == "keypoolrefill" && n > 0) ConvertTo<int64_t>(params[0]);
772 if (strMethod == "keypoolreset" && n > 0) ConvertTo<int64_t>(params[0]);
773 if (strMethod == "importaddress" && n > 2) ConvertTo<bool>(params[2]);
774 if (strMethod == "importprivkey" && n > 2) ConvertTo<bool>(params[2]);
779 int CommandLineRPC(int argc, char *argv[])
781 std::string strPrint;
786 while (argc > 1 && IsSwitchChar(argv[1][0]))
794 throw std::runtime_error("too few parameters");
795 std::string strMethod = argv[1];
797 // Parameters default to strings
798 std::vector<std::string> strParams(&argv[2], &argv[argc]);
799 Array params = RPCConvertValues(strMethod, strParams);
802 Object reply = CallRPC(strMethod, params);
805 const Value& result = find_value(reply, "result");
806 const Value& error = find_value(reply, "error");
808 if (error.type() != null_type)
811 strPrint = "error: " + write_string(error, false);
812 int code = find_value(error.get_obj(), "code").get_int();
818 if (result.type() == null_type)
820 else if (result.type() == str_type)
821 strPrint = result.get_str();
823 strPrint = write_string(result, true);
826 catch (const std::exception& e)
828 strPrint = std::string("error: ") + e.what();
833 PrintException(nullptr, "CommandLineRPC()");
836 if (!strPrint.empty())
838 fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
844 const CRPCTable tableRPC;