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.
8 #include "bitcoinrpc.h"
10 #include "interface.h"
17 #include <ixwebsocket/IXHttpClient.h>
18 #include <ixwebsocket/IXHttpServer.h>
24 #define printf OutputDebugStringF
26 using namespace json_spirit;
28 std::unique_ptr<ix::HttpServer> g_server;
30 static std::string strRPCUserColonPass;
32 const Object emptyobj;
34 static inline unsigned short GetDefaultRPCPort()
36 return GetBoolArg("-testnet", false) ? 18344 : 8344;
39 Object JSONRPCError(int code, const std::string& message)
42 error.push_back(Pair("code", code));
43 error.push_back(Pair("message", message));
47 void RPCTypeCheck(const Array& params,
48 const std::list<Value_type>& typesExpected,
52 for(Value_type t : typesExpected)
54 if (params.size() <= i)
57 const Value& v = params[i];
58 if (!((v.type() == t) || (fAllowNull && (v.type() == null_type))))
60 std::string err = strprintf("Expected type %s, got %s",
61 Value_type_name[t], Value_type_name[v.type()]);
62 throw JSONRPCError(RPC_TYPE_ERROR, err);
68 void RPCTypeCheck(const Object& o,
69 const std::map<std::string, Value_type>& typesExpected,
72 for(const auto& t : typesExpected)
74 const Value& v = find_value(o, t.first);
75 if (!fAllowNull && v.type() == null_type)
76 throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first.c_str()));
78 if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type))))
80 std::string err = strprintf("Expected type %s for %s, got %s",
81 Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]);
82 throw JSONRPCError(RPC_TYPE_ERROR, err);
87 int64_t AmountFromValue(const Value& value)
89 double dAmount = value.get_real();
90 if (dAmount <= 0.0 || dAmount > (double) (MAX_MONEY / 100000000))
91 throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
92 int64_t nAmount = roundint64(dAmount * COIN);
93 if (!MoneyRange(nAmount))
94 throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
98 Value ValueFromAmount(int64_t amount)
100 return (double)amount / (double)COIN;
103 std::string HexBits(unsigned int nBits)
109 uBits.nBits = htonl((int32_t)nBits);
110 return HexStr(BEGIN(uBits.cBits), END(uBits.cBits));
115 // Utilities: convert hex-encoded Values
116 // (throws error if not hex).
118 uint256 ParseHashV(const Value& v, const std::string& strName)
121 if (v.type() == str_type)
122 strHex = v.get_str();
123 if (!IsHex(strHex)) // Note: IsHex("") is false
124 throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
126 result.SetHex(strHex);
130 uint256 ParseHashO(const Object& o, const std::string& strKey)
132 return ParseHashV(find_value(o, strKey), strKey);
135 std::vector<unsigned char> ParseHexV(const Value& v, const std::string& strName)
138 if (v.type() == str_type)
139 strHex = v.get_str();
141 throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
142 return ParseHex(strHex);
145 std::vector<unsigned char> ParseHexO(const Object& o, const std::string& strKey)
147 return ParseHexV(find_value(o, strKey), strKey);
152 /// Note: This interface may still be subject to change.
155 std::string CRPCTable::help(const std::string& strCommand) const
158 std::set<rpcfn_type> setDone;
159 for (const auto & mapCommand : mapCommands)
161 const CRPCCommand *pcmd = mapCommand.second;
162 std::string strMethod = mapCommand.first;
163 // We already filter duplicates, but these deprecated screw up the sort order
164 if (strMethod.find("label") != std::string::npos)
166 if (!strCommand.empty() && strMethod != strCommand)
171 rpcfn_type pfn = pcmd->actor;
172 if (setDone.insert(pfn).second)
173 (*pfn)(params, true);
175 catch (const std::exception& e)
177 // Help text is returned in an exception
178 std::string strHelp = std::string(e.what());
179 if (strCommand.empty())
180 if (strHelp.find('\n') != std::string::npos)
181 strHelp = strHelp.substr(0, strHelp.find('\n'));
182 strRet += strHelp + '\n';
186 strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
187 strRet = strRet.substr(0,strRet.size()-1);
191 Value help(const Array& params, bool fHelp)
193 if (fHelp || params.size() > 1)
194 throw std::runtime_error(
196 "List commands, or get help for a command.");
198 std::string strCommand;
200 strCommand = params[0].get_str();
202 return tableRPC.help(strCommand);
206 Value stop(const Array& params, bool fHelp)
208 if (fHelp || params.size() > 1)
209 throw std::runtime_error(
211 "<detach> is true or false to detach the database or not for this stop only\n"
212 "Stop NovaCoin server (and possibly override the detachdb config value).");
213 // Shutdown will take long enough that the response should get back
215 bitdb.SetDetach(params[0].get_bool());
217 return "NovaCoin server stopping";
227 static const CRPCCommand vRPCCommands[] =
228 { // name function safemd unlocked
229 // ------------------------ ----------------------- ------ --------
230 { "help", &help, true, true },
231 { "stop", &stop, true, true },
232 { "getbestblockhash", &getbestblockhash, true, false },
233 { "getblockcount", &getblockcount, true, false },
234 { "getconnectioncount", &getconnectioncount, true, false },
235 { "getaddrmaninfo", &getaddrmaninfo, true, false },
236 { "getpeerinfo", &getpeerinfo, true, false },
237 { "addnode", &addnode, true, true },
238 { "getaddednodeinfo", &getaddednodeinfo, true, true },
239 { "getdifficulty", &getdifficulty, true, false },
240 { "getinfo", &getinfo, true, false },
241 { "getsubsidy", &getsubsidy, true, false },
242 { "getmininginfo", &getmininginfo, true, false },
243 { "scaninput", &scaninput, true, true },
244 { "getnewaddress", &getnewaddress, true, false },
245 { "getnettotals", &getnettotals, true, true },
246 { "ntptime", &ntptime, true, true },
247 { "getaccountaddress", &getaccountaddress, true, false },
248 { "setaccount", &setaccount, true, false },
249 { "getaccount", &getaccount, false, false },
250 { "getaddressesbyaccount", &getaddressesbyaccount, true, false },
251 { "sendtoaddress", &sendtoaddress, false, false },
252 { "mergecoins", &mergecoins, false, false },
253 { "getreceivedbyaddress", &getreceivedbyaddress, false, false },
254 { "getreceivedbyaccount", &getreceivedbyaccount, false, false },
255 { "listreceivedbyaddress", &listreceivedbyaddress, false, false },
256 { "listreceivedbyaccount", &listreceivedbyaccount, false, false },
257 { "backupwallet", &backupwallet, true, false },
258 { "keypoolrefill", &keypoolrefill, true, false },
259 { "keypoolreset", &keypoolreset, true, false },
260 { "walletpassphrase", &walletpassphrase, true, false },
261 { "walletpassphrasechange", &walletpassphrasechange, false, false },
262 { "walletlock", &walletlock, true, false },
263 { "encryptwallet", &encryptwallet, false, false },
264 { "validateaddress", &validateaddress, true, false },
265 { "getbalance", &getbalance, false, false },
266 { "move", &movecmd, false, false },
267 { "sendfrom", &sendfrom, false, false },
268 { "sendmany", &sendmany, false, false },
269 { "addmultisigaddress", &addmultisigaddress, false, false },
270 { "addredeemscript", &addredeemscript, false, false },
271 { "getrawmempool", &getrawmempool, true, false },
272 { "getblock", &getblock, false, false },
273 { "getblockbynumber", &getblockbynumber, false, false },
274 { "dumpblock", &dumpblock, false, false },
275 { "dumpblockbynumber", &dumpblockbynumber, false, false },
276 { "getblockhash", &getblockhash, false, false },
277 { "gettransaction", &gettransaction, false, false },
278 { "listtransactions", &listtransactions, false, false },
279 { "listaddressgroupings", &listaddressgroupings, false, false },
280 { "signmessage", &signmessage, false, false },
281 { "verifymessage", &verifymessage, false, false },
282 { "getwork", &getwork, true, false },
283 { "getworkex", &getworkex, true, false },
284 { "listaccounts", &listaccounts, false, false },
285 { "settxfee", &settxfee, false, false },
286 { "getblocktemplate", &getblocktemplate, true, false },
287 { "submitblock", &submitblock, false, false },
288 { "listsinceblock", &listsinceblock, false, false },
289 { "dumpprivkey", &dumpprivkey, false, false },
290 { "dumpwallet", &dumpwallet, true, false },
291 { "importwallet", &importwallet, false, false },
292 { "importprivkey", &importprivkey, false, false },
293 { "importaddress", &importaddress, false, true },
294 { "removeaddress", &removeaddress, false, true },
295 { "listunspent", &listunspent, false, false },
296 { "getrawtransaction", &getrawtransaction, false, false },
297 { "createrawtransaction", &createrawtransaction, false, false },
298 { "decoderawtransaction", &decoderawtransaction, false, false },
299 { "createmultisig", &createmultisig, false, false },
300 { "decodescript", &decodescript, false, false },
301 { "signrawtransaction", &signrawtransaction, false, false },
302 { "sendrawtransaction", &sendrawtransaction, false, false },
303 { "getcheckpoint", &getcheckpoint, true, false },
304 { "reservebalance", &reservebalance, false, true},
305 { "checkwallet", &checkwallet, false, true},
306 { "repairwallet", &repairwallet, false, true},
307 { "resendwallettransactions", &resendwallettransactions, false, true},
308 { "makekeypair", &makekeypair, false, true},
309 { "newmalleablekey", &newmalleablekey, false, false},
310 { "adjustmalleablekey", &adjustmalleablekey, false, false},
311 { "adjustmalleablepubkey", &adjustmalleablepubkey, false, false},
312 { "listmalleableviews", &listmalleableviews, false, false},
313 { "dumpmalleablekey", &dumpmalleablekey, false, false},
314 { "importmalleablekey", &importmalleablekey, true, false },
315 { "sendalert", &sendalert, false, false},
318 CRPCTable::CRPCTable()
320 for (const auto & vRPCCommand : vRPCCommands)
322 const CRPCCommand *pcmd;
325 mapCommands[pcmd->name] = pcmd;
329 const CRPCCommand *CRPCTable::operator[](const std::string& name) const
331 auto it = mapCommands.find(name);
332 if (it == mapCommands.end())
337 bool HTTPAuthorized(ix::WebSocketHttpHeaders& mapHeaders)
339 std::string strAuth = mapHeaders["authorization"];
340 if (strAuth.substr(0,6) != "Basic ")
342 std::string strUserPass64 = std::regex_replace(strAuth.substr(6), static_cast<std::regex>("\\s+"), "");
343 std::string strUserPass = DecodeBase64(strUserPass64);
344 return TimingResistantEqual(strUserPass, strRPCUserColonPass);
348 // JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
349 // but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
350 // unspecified (HTTP errors and contents of 'error').
352 // 1.0 spec: http://json-rpc.org/wiki/specification
353 // 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
354 // http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
357 std::string JSONRPCRequest(const std::string& strMethod, const Array& params, const Value& id)
360 request.push_back(Pair("method", strMethod));
361 request.push_back(Pair("params", params));
362 request.push_back(Pair("id", id));
363 return write_string(Value(request), false) + "\n";
366 Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id)
369 if (error.type() != null_type)
370 reply.push_back(Pair("result", Value::null));
372 reply.push_back(Pair("result", result));
373 reply.push_back(Pair("error", error));
374 reply.push_back(Pair("id", id));
378 std::string JSONRPCReply(const Value& result, const Value& error, const Value& id)
380 Object reply = JSONRPCReplyObj(result, error, id);
381 return write_string(Value(reply), false) + "\n";
384 std::string ErrorReply(const Object& objError, const Value& id)
386 // Send error reply from json-rpc error object
387 int nStatus = HTTP_INTERNAL_SERVER_ERROR;
388 int code = find_value(objError, "code").get_int();
389 if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST;
390 else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND;
391 return JSONRPCReply(Value::null, objError, id);
398 std::string strMethod;
401 JSONRequest() { id = Value::null; }
402 void parse(const Value& valRequest);
405 void JSONRequest::parse(const Value& valRequest)
408 if (valRequest.type() != obj_type)
409 throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
410 const Object& request = valRequest.get_obj();
412 // Parse id now so errors from here on will have the id
413 id = find_value(request, "id");
416 Value valMethod = find_value(request, "method");
417 if (valMethod.type() == null_type)
418 throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
419 if (valMethod.type() != str_type)
420 throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
421 strMethod = valMethod.get_str();
422 if (strMethod != "getwork" && strMethod != "getblocktemplate")
423 printf("RPCServer method=%s\n", strMethod.c_str());
426 Value valParams = find_value(request, "params");
427 if (valParams.type() == array_type)
428 params = valParams.get_array();
429 else if (valParams.type() == null_type)
432 throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array");
435 static Object JSONRPCExecOne(const Value& req)
443 Value result = tableRPC.execute(jreq.strMethod, jreq.params);
444 rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id);
446 catch (Object& objError)
448 rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id);
450 catch (const std::exception& e)
452 rpc_result = JSONRPCReplyObj(Value::null,
453 JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
459 static std::string JSONRPCExecBatch(const Array& vReq)
462 for (const auto & reqIdx : vReq)
463 ret.push_back(JSONRPCExecOne(reqIdx));
465 return write_string(Value(ret), false) + "\n";
468 static CCriticalSection cs_THREAD_RPCHANDLER;
470 void StartRPCServer()
472 strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
473 if (mapArgs["-rpcpassword"].empty())
475 unsigned char rand_pwd[32];
476 RAND_bytes(rand_pwd, 32);
477 std::string strWhatAmI = "To use novacoind";
478 if (mapArgs.count("-server"))
479 strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
480 else if (mapArgs.count("-daemon"))
481 strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
482 uiInterface.ThreadSafeMessageBox(strprintf(
483 _("%s, you must set a rpcpassword in the configuration file:\n %s\n"
484 "It is recommended you use the following random password:\n"
485 "rpcuser=novacoinrpc\n"
487 "(you do not need to remember this password)\n"
488 "If the file does not exist, create it with owner-readable-only file permissions.\n"),
490 GetConfigFile().string().c_str(),
491 EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()),
492 _("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL);
497 std::string host = GetArg("-rpchost", "127.0.0.1");
498 int port = GetArg("-rpcport", GetDefaultRPCPort());
500 g_server = std::make_unique<ix::HttpServer>(port, host);
502 LOCK(cs_THREAD_RPCHANDLER);
504 g_server->setOnConnectionCallback([](const ix::HttpRequestPtr& request, const std::shared_ptr<ix::ConnectionState>& connectionState) -> ix::HttpResponsePtr {
506 ix::WebSocketHttpHeaders headers;
507 headers["Server"] = std::string("novacoin-json-rpc/") + FormatFullVersion();
508 headers["WWW-Authenticate"] = R"(Basic realm="jsonrpc")";
510 if (!HTTPAuthorized(request->headers))
512 printf("ThreadRPCServer incorrect password attempt from %s\n", connectionState->getRemoteIp().c_str());
513 connectionState->setTerminated();
514 return std::make_shared<ix::HttpResponse>(HTTP_UNAUTHORIZED, "Unauthorized", ix::HttpErrorCode::Ok, headers, "Not authorized");
517 if (request->method != "POST") {
518 connectionState->setTerminated();
519 return std::make_shared<ix::HttpResponse>(HTTP_BAD_REQUEST, "Bad request", ix::HttpErrorCode::Ok, headers, "Bad request");
528 if (!read_string(request->body, valRequest))
529 throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
531 std::string strReply;
534 if (valRequest.type() == obj_type) {
535 jreq.parse(valRequest);
538 Value result = tableRPC.execute(jreq.strMethod, jreq.params);
541 strReply = JSONRPCReply(result, Value::null, jreq.id);
544 } else if (valRequest.type() == array_type)
545 // Execute batch of requests
546 strReply = JSONRPCExecBatch(valRequest.get_array());
548 throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
550 // Send reply to client
551 return std::make_shared<ix::HttpResponse>(200, "OK", ix::HttpErrorCode::Ok, headers, strReply);
554 catch(Object& objError)
556 return std::make_shared<ix::HttpResponse>(HTTP_INTERNAL_SERVER_ERROR, "Internal Server Error", ix::HttpErrorCode::Ok, headers, ErrorReply(objError, jreq.id));
558 catch(const std::exception& e)
560 return std::make_shared<ix::HttpResponse>(HTTP_INTERNAL_SERVER_ERROR, "Internal Server Error", ix::HttpErrorCode::Ok, headers, ErrorReply(JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id));
564 std::pair<bool, std::string> result = g_server->listen();
566 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());
567 uiInterface.ThreadSafeMessageBox(strerr, _("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL);
568 return StartShutdown();
571 // Run listening thread
574 // We're listening now
575 vnThreadsRunning[THREAD_RPCLISTENER]++;
580 LOCK(cs_THREAD_RPCHANDLER);
581 if (g_server) g_server->stop();
582 vnThreadsRunning[THREAD_RPCLISTENER]--;
585 json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array ¶ms) const
588 const CRPCCommand *pcmd = tableRPC[strMethod];
590 throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
593 std::string strWarning = GetWarnings("rpc");
594 if (!strWarning.empty() && !GetBoolArg("-disablesafemode") &&
596 throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, std::string("Safe mode: ") + strWarning);
604 result = pcmd->actor(params, false);
606 LOCK2(cs_main, pwalletMain->cs_wallet);
607 result = pcmd->actor(params, false);
612 catch (const std::exception& e)
614 throw JSONRPCError(RPC_MISC_ERROR, e.what());
618 std::vector<std::string> CRPCTable::listCommands() const
620 std::vector<std::string> commandList;
621 for (const auto& i : mapCommands) commandList.emplace_back(i.first);
625 Object CallRPC(const std::string& strMethod, const Array& params)
627 if (mapArgs["-rpcuser"].empty() && mapArgs["-rpcpassword"].empty())
628 throw std::runtime_error(strprintf(
629 _("You must set rpcpassword=<password> in the configuration file:\n%s\n"
630 "If the file does not exist, create it with owner-readable-only file permissions."),
631 GetConfigFile().string().c_str()));
633 // Init net subsystem
636 // Create HTTP client
637 ix::HttpClient httpClient;
638 ix::HttpRequestArgsPtr args = httpClient.createRequest();
640 // HTTP basic authentication
641 ix::WebSocketHttpHeaders mapRequestHeaders;
642 std::string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
643 mapRequestHeaders["Authorization"] = std::string("Basic ") + strUserPass64;
644 args->extraHeaders = mapRequestHeaders;
647 args->connectTimeout = GetArgInt("-rpc_connecttimeout", 30000);
648 args->transferTimeout = GetArgInt("-rpc_transfertimeout", 30000);
650 bool fUseSSL = GetBoolArg("-rpcssl");
651 std::string url = std::string(fUseSSL ? "https://" : "http://") + GetArg("-rpcconnect", "127.0.0.1") + ":" + GetArg("-rpcport", itostr(GetDefaultRPCPort()));
654 std::string strRequest = JSONRPCRequest(strMethod, params, GetRandInt(INT32_MAX));
655 auto out = httpClient.post(url, strRequest, args);
658 int nStatus = out->statusCode;
659 std::string strReply = out->body;
660 ix::WebSocketHttpHeaders mapHeaders = out->headers;
663 if (nStatus == HTTP_UNAUTHORIZED)
664 throw std::runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
665 else if (nStatus >= HTTP_BAD_REQUEST && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR)
666 throw std::runtime_error(strprintf("server returned HTTP error %d", nStatus));
667 else if (strReply.empty())
668 throw std::runtime_error("no response from server");
672 if (!read_string(strReply, valReply))
673 throw std::runtime_error("couldn't parse reply from server");
674 const Object& reply = valReply.get_obj();
676 throw std::runtime_error("expected reply to have result, error and id properties");
685 void ConvertTo(Value& value, bool fAllowNull=false)
687 if (fAllowNull && value.type() == null_type)
689 if (value.type() == str_type)
691 // reinterpret string as unquoted json value
693 std::string strJSON = value.get_str();
694 if (!read_string(strJSON, value2))
695 throw std::runtime_error(std::string("Error parsing JSON:")+strJSON);
696 ConvertTo<T>(value2, fAllowNull);
701 value = value.get_value<T>();
705 // Convert strings to command-specific RPC representation
706 Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
709 for(const auto ¶m : strParams)
710 params.push_back(param);
712 size_t n = params.size();
715 // Special case non-string parameter types
717 if (strMethod == "stop" && n > 0) ConvertTo<bool>(params[0]);
718 if (strMethod == "getaddednodeinfo" && n > 0) ConvertTo<bool>(params[0]);
719 if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);
720 if (strMethod == "mergecoins" && n > 0) ConvertTo<double>(params[0]);
721 if (strMethod == "mergecoins" && n > 1) ConvertTo<double>(params[1]);
722 if (strMethod == "mergecoins" && n > 2) ConvertTo<double>(params[2]);
723 if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]);
724 if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<int64_t>(params[1]);
725 if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<int64_t>(params[1]);
726 if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<int64_t>(params[0]);
727 if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);
728 if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<int64_t>(params[0]);
729 if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]);
730 if (strMethod == "getbalance" && n > 1) ConvertTo<int64_t>(params[1]);
731 if (strMethod == "getblock" && n > 1) ConvertTo<bool>(params[1]);
732 if (strMethod == "getblockbynumber" && n > 0) ConvertTo<int64_t>(params[0]);
733 if (strMethod == "dumpblockbynumber" && n > 0) ConvertTo<int64_t>(params[0]);
734 if (strMethod == "getblockbynumber" && n > 1) ConvertTo<bool>(params[1]);
735 if (strMethod == "getblockhash" && n > 0) ConvertTo<int64_t>(params[0]);
736 if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]);
737 if (strMethod == "move" && n > 3) ConvertTo<int64_t>(params[3]);
738 if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]);
739 if (strMethod == "sendfrom" && n > 3) ConvertTo<int64_t>(params[3]);
740 if (strMethod == "listtransactions" && n > 1) ConvertTo<int64_t>(params[1]);
741 if (strMethod == "listtransactions" && n > 2) ConvertTo<int64_t>(params[2]);
742 if (strMethod == "listaccounts" && n > 0) ConvertTo<int64_t>(params[0]);
743 if (strMethod == "walletpassphrase" && n > 1) ConvertTo<int64_t>(params[1]);
744 if (strMethod == "walletpassphrase" && n > 2) ConvertTo<bool>(params[2]);
745 if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]);
746 if (strMethod == "listsinceblock" && n > 1) ConvertTo<int64_t>(params[1]);
748 if (strMethod == "scaninput" && n > 0) ConvertTo<Object>(params[0]);
750 if (strMethod == "sendalert" && n > 2) ConvertTo<int64_t>(params[2]);
751 if (strMethod == "sendalert" && n > 3) ConvertTo<int64_t>(params[3]);
752 if (strMethod == "sendalert" && n > 4) ConvertTo<int64_t>(params[4]);
753 if (strMethod == "sendalert" && n > 5) ConvertTo<int64_t>(params[5]);
754 if (strMethod == "sendalert" && n > 6) ConvertTo<int64_t>(params[6]);
756 if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]);
757 if (strMethod == "sendmany" && n > 2) ConvertTo<int64_t>(params[2]);
758 if (strMethod == "reservebalance" && n > 0) ConvertTo<bool>(params[0]);
759 if (strMethod == "reservebalance" && n > 1) ConvertTo<double>(params[1]);
760 if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<int64_t>(params[0]);
761 if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]);
762 if (strMethod == "listunspent" && n > 0) ConvertTo<int64_t>(params[0]);
763 if (strMethod == "listunspent" && n > 1) ConvertTo<int64_t>(params[1]);
764 if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]);
765 if (strMethod == "getrawtransaction" && n > 1) ConvertTo<int64_t>(params[1]);
766 if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]);
767 if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]);
768 if (strMethod == "createmultisig" && n > 0) ConvertTo<int64_t>(params[0]);
769 if (strMethod == "createmultisig" && n > 1) ConvertTo<Array>(params[1]);
770 if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1], true);
771 if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2], true);
772 if (strMethod == "keypoolrefill" && n > 0) ConvertTo<int64_t>(params[0]);
773 if (strMethod == "keypoolreset" && n > 0) ConvertTo<int64_t>(params[0]);
774 if (strMethod == "importaddress" && n > 2) ConvertTo<bool>(params[2]);
775 if (strMethod == "importprivkey" && n > 2) ConvertTo<bool>(params[2]);
780 int CommandLineRPC(int argc, char *argv[])
782 std::string strPrint;
787 while (argc > 1 && IsSwitchChar(argv[1][0]))
795 throw std::runtime_error("too few parameters");
796 std::string strMethod = argv[1];
798 // Parameters default to strings
799 std::vector<std::string> strParams(&argv[2], &argv[argc]);
800 Array params = RPCConvertValues(strMethod, strParams);
803 Object reply = CallRPC(strMethod, params);
806 const Value& result = find_value(reply, "result");
807 const Value& error = find_value(reply, "error");
809 if (error.type() != null_type)
812 strPrint = "error: " + write_string(error, false);
813 int code = find_value(error.get_obj(), "code").get_int();
819 if (result.type() == null_type)
821 else if (result.type() == str_type)
822 strPrint = result.get_str();
824 strPrint = write_string(result, true);
827 catch (const std::exception& e)
829 strPrint = std::string("error: ") + e.what();
834 PrintException(nullptr, "CommandLineRPC()");
837 if (!strPrint.empty())
839 fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
845 const CRPCTable tableRPC;