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"
18 #include <ixwebsocket/IXHttpClient.h>
19 #include <ixwebsocket/IXHttpServer.h>
25 #define printf OutputDebugStringF
27 using namespace json_spirit;
29 std::unique_ptr<ix::HttpServer> g_server;
31 static std::string strRPCUserColonPass;
33 const Object emptyobj;
35 static inline unsigned short GetDefaultRPCPort()
37 return GetBoolArg("-testnet", false) ? 18344 : 8344;
40 Object JSONRPCError(int code, const std::string& message)
43 error.push_back(Pair("code", code));
44 error.push_back(Pair("message", message));
48 void RPCTypeCheck(const Array& params,
49 const std::list<Value_type>& typesExpected,
53 for(Value_type t : typesExpected)
55 if (params.size() <= i)
58 const Value& v = params[i];
59 if (!((v.type() == t) || (fAllowNull && (v.type() == null_type))))
61 std::string err = strprintf("Expected type %s, got %s",
62 Value_type_name[t], Value_type_name[v.type()]);
63 throw JSONRPCError(RPC_TYPE_ERROR, err);
69 void RPCTypeCheck(const Object& o,
70 const std::map<std::string, Value_type>& typesExpected,
73 for(const auto& t : typesExpected)
75 const Value& v = find_value(o, t.first);
76 if (!fAllowNull && v.type() == null_type)
77 throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first.c_str()));
79 if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type))))
81 std::string err = strprintf("Expected type %s for %s, got %s",
82 Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]);
83 throw JSONRPCError(RPC_TYPE_ERROR, err);
88 int64_t AmountFromValue(const Value& value)
90 double dAmount = value.get_real();
91 if (dAmount <= 0.0 || dAmount > (double) (MAX_MONEY / 100000000))
92 throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
93 int64_t nAmount = roundint64(dAmount * COIN);
94 if (!MoneyRange(nAmount))
95 throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
99 Value ValueFromAmount(int64_t amount)
101 return (double)amount / (double)COIN;
104 std::string HexBits(unsigned int nBits)
110 uBits.nBits = htonl((int32_t)nBits);
111 return HexStr(BEGIN(uBits.cBits), END(uBits.cBits));
116 // Utilities: convert hex-encoded Values
117 // (throws error if not hex).
119 uint256 ParseHashV(const Value& v, const std::string& strName)
122 if (v.type() == str_type)
123 strHex = v.get_str();
124 if (!IsHex(strHex)) // Note: IsHex("") is false
125 throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
127 result.SetHex(strHex);
131 uint256 ParseHashO(const Object& o, const std::string& strKey)
133 return ParseHashV(find_value(o, strKey), strKey);
136 std::vector<unsigned char> ParseHexV(const Value& v, const std::string& strName)
139 if (v.type() == str_type)
140 strHex = v.get_str();
142 throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
143 return ParseHex(strHex);
146 std::vector<unsigned char> ParseHexO(const Object& o, const std::string& strKey)
148 return ParseHexV(find_value(o, strKey), strKey);
153 /// Note: This interface may still be subject to change.
156 std::string CRPCTable::help(const std::string& strCommand) const
159 std::set<rpcfn_type> setDone;
160 for (const auto & mapCommand : mapCommands)
162 const CRPCCommand *pcmd = mapCommand.second;
163 std::string strMethod = mapCommand.first;
164 // We already filter duplicates, but these deprecated screw up the sort order
165 if (strMethod.find("label") != std::string::npos)
167 if (!strCommand.empty() && strMethod != strCommand)
172 rpcfn_type pfn = pcmd->actor;
173 if (setDone.insert(pfn).second)
174 (*pfn)(params, true);
176 catch (const std::exception& e)
178 // Help text is returned in an exception
179 std::string strHelp = std::string(e.what());
180 if (strCommand.empty())
181 if (strHelp.find('\n') != std::string::npos)
182 strHelp = strHelp.substr(0, strHelp.find('\n'));
183 strRet += strHelp + '\n';
187 strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
188 strRet = strRet.substr(0,strRet.size()-1);
192 Value help(const Array& params, bool fHelp)
194 if (fHelp || params.size() > 1)
195 throw std::runtime_error(
197 "List commands, or get help for a command.");
199 std::string strCommand;
201 strCommand = params[0].get_str();
203 return tableRPC.help(strCommand);
207 Value stop(const Array& params, bool fHelp)
209 if (fHelp || params.size() > 1)
210 throw std::runtime_error(
212 "<detach> is true or false to detach the database or not for this stop only\n"
213 "Stop NovaCoin server (and possibly override the detachdb config value).");
214 // Shutdown will take long enough that the response should get back
216 bitdb.SetDetach(params[0].get_bool());
218 return "NovaCoin server stopping";
228 static const CRPCCommand vRPCCommands[] =
229 { // name function safemd unlocked
230 // ------------------------ ----------------------- ------ --------
231 { "help", &help, true, true },
232 { "stop", &stop, true, true },
233 { "getbestblockhash", &getbestblockhash, true, false },
234 { "getblockcount", &getblockcount, true, false },
235 { "getconnectioncount", &getconnectioncount, true, false },
236 { "getaddrmaninfo", &getaddrmaninfo, true, false },
237 { "getpeerinfo", &getpeerinfo, true, false },
238 { "addnode", &addnode, true, true },
239 { "getaddednodeinfo", &getaddednodeinfo, true, true },
240 { "getdifficulty", &getdifficulty, true, false },
241 { "getinfo", &getinfo, true, false },
242 { "getsubsidy", &getsubsidy, true, false },
243 { "getmininginfo", &getmininginfo, true, false },
244 { "scaninput", &scaninput, true, true },
245 { "getnewaddress", &getnewaddress, true, false },
246 { "getnettotals", &getnettotals, true, true },
247 { "ntptime", &ntptime, true, true },
248 { "getaccountaddress", &getaccountaddress, true, false },
249 { "setaccount", &setaccount, true, false },
250 { "getaccount", &getaccount, false, false },
251 { "getaddressesbyaccount", &getaddressesbyaccount, true, false },
252 { "sendtoaddress", &sendtoaddress, false, false },
253 { "mergecoins", &mergecoins, false, false },
254 { "getreceivedbyaddress", &getreceivedbyaddress, false, false },
255 { "getreceivedbyaccount", &getreceivedbyaccount, false, false },
256 { "listreceivedbyaddress", &listreceivedbyaddress, false, false },
257 { "listreceivedbyaccount", &listreceivedbyaccount, false, false },
258 { "backupwallet", &backupwallet, true, false },
259 { "keypoolrefill", &keypoolrefill, true, false },
260 { "keypoolreset", &keypoolreset, true, false },
261 { "walletpassphrase", &walletpassphrase, true, false },
262 { "walletpassphrasechange", &walletpassphrasechange, false, false },
263 { "walletlock", &walletlock, true, false },
264 { "encryptwallet", &encryptwallet, false, false },
265 { "validateaddress", &validateaddress, true, false },
266 { "getbalance", &getbalance, false, false },
267 { "move", &movecmd, false, false },
268 { "sendfrom", &sendfrom, false, false },
269 { "sendmany", &sendmany, false, false },
270 { "addmultisigaddress", &addmultisigaddress, false, false },
271 { "addredeemscript", &addredeemscript, false, false },
272 { "getrawmempool", &getrawmempool, true, false },
273 { "getblock", &getblock, false, false },
274 { "getblockbynumber", &getblockbynumber, false, false },
275 { "dumpblock", &dumpblock, false, false },
276 { "dumpblockbynumber", &dumpblockbynumber, false, false },
277 { "getblockhash", &getblockhash, false, false },
278 { "gettransaction", &gettransaction, false, false },
279 { "listtransactions", &listtransactions, false, false },
280 { "listaddressgroupings", &listaddressgroupings, false, false },
281 { "signmessage", &signmessage, false, false },
282 { "verifymessage", &verifymessage, false, false },
283 { "getwork", &getwork, true, false },
284 { "getworkex", &getworkex, true, false },
285 { "listaccounts", &listaccounts, false, false },
286 { "settxfee", &settxfee, false, false },
287 { "getblocktemplate", &getblocktemplate, true, false },
288 { "submitblock", &submitblock, false, false },
289 { "listsinceblock", &listsinceblock, false, false },
290 { "dumpprivkey", &dumpprivkey, false, false },
291 { "dumpwallet", &dumpwallet, true, false },
292 { "importwallet", &importwallet, false, false },
293 { "importprivkey", &importprivkey, false, false },
294 { "importaddress", &importaddress, false, true },
295 { "removeaddress", &removeaddress, false, true },
296 { "listunspent", &listunspent, false, false },
297 { "getrawtransaction", &getrawtransaction, false, false },
298 { "createrawtransaction", &createrawtransaction, false, false },
299 { "decoderawtransaction", &decoderawtransaction, false, false },
300 { "createmultisig", &createmultisig, false, false },
301 { "decodescript", &decodescript, false, false },
302 { "signrawtransaction", &signrawtransaction, false, false },
303 { "sendrawtransaction", &sendrawtransaction, false, false },
304 { "getcheckpoint", &getcheckpoint, true, false },
305 { "reservebalance", &reservebalance, false, true},
306 { "checkwallet", &checkwallet, false, true},
307 { "repairwallet", &repairwallet, false, true},
308 { "resendwallettransactions", &resendwallettransactions, false, true},
309 { "makekeypair", &makekeypair, false, true},
310 { "newmalleablekey", &newmalleablekey, false, false},
311 { "adjustmalleablekey", &adjustmalleablekey, false, false},
312 { "adjustmalleablepubkey", &adjustmalleablepubkey, false, false},
313 { "listmalleableviews", &listmalleableviews, false, false},
314 { "dumpmalleablekey", &dumpmalleablekey, false, false},
315 { "importmalleablekey", &importmalleablekey, true, false },
316 { "sendalert", &sendalert, false, false},
319 CRPCTable::CRPCTable()
321 for (const auto & vRPCCommand : vRPCCommands)
323 const CRPCCommand *pcmd;
326 mapCommands[pcmd->name] = pcmd;
330 const CRPCCommand *CRPCTable::operator[](const std::string& name) const
332 auto it = mapCommands.find(name);
333 if (it == mapCommands.end())
338 bool HTTPAuthorized(ix::WebSocketHttpHeaders& mapHeaders)
340 std::string strAuth = mapHeaders["authorization"];
341 if (strAuth.substr(0,6) != "Basic ")
343 std::string strUserPass64 = std::regex_replace(strAuth.substr(6), static_cast<std::regex>("\\s+"), "");
344 std::string strUserPass = DecodeBase64(strUserPass64);
345 return TimingResistantEqual(strUserPass, strRPCUserColonPass);
349 // JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
350 // but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
351 // unspecified (HTTP errors and contents of 'error').
353 // 1.0 spec: http://json-rpc.org/wiki/specification
354 // 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
355 // http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
358 std::string JSONRPCRequest(const std::string& strMethod, const Array& params, const Value& id)
361 request.push_back(Pair("method", strMethod));
362 request.push_back(Pair("params", params));
363 request.push_back(Pair("id", id));
364 return write_string(Value(request), false) + "\n";
367 Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id)
370 if (error.type() != null_type)
371 reply.push_back(Pair("result", Value::null));
373 reply.push_back(Pair("result", result));
374 reply.push_back(Pair("error", error));
375 reply.push_back(Pair("id", id));
379 std::string JSONRPCReply(const Value& result, const Value& error, const Value& id)
381 Object reply = JSONRPCReplyObj(result, error, id);
382 return write_string(Value(reply), false) + "\n";
385 std::string ErrorReply(const Object& objError, const Value& id)
387 // Send error reply from json-rpc error object
388 int nStatus = HTTP_INTERNAL_SERVER_ERROR;
389 int code = find_value(objError, "code").get_int();
390 if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST;
391 else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND;
392 return JSONRPCReply(Value::null, objError, id);
399 std::string strMethod;
402 JSONRequest() { id = Value::null; }
403 void parse(const Value& valRequest);
406 void JSONRequest::parse(const Value& valRequest)
409 if (valRequest.type() != obj_type)
410 throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
411 const Object& request = valRequest.get_obj();
413 // Parse id now so errors from here on will have the id
414 id = find_value(request, "id");
417 Value valMethod = find_value(request, "method");
418 if (valMethod.type() == null_type)
419 throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
420 if (valMethod.type() != str_type)
421 throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
422 strMethod = valMethod.get_str();
423 if (strMethod != "getwork" && strMethod != "getblocktemplate")
424 printf("RPCServer method=%s\n", strMethod.c_str());
427 Value valParams = find_value(request, "params");
428 if (valParams.type() == array_type)
429 params = valParams.get_array();
430 else if (valParams.type() == null_type)
433 throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array");
436 static Object JSONRPCExecOne(const Value& req)
444 Value result = tableRPC.execute(jreq.strMethod, jreq.params);
445 rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id);
447 catch (Object& objError)
449 rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id);
451 catch (const std::exception& e)
453 rpc_result = JSONRPCReplyObj(Value::null,
454 JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
460 static std::string JSONRPCExecBatch(const Array& vReq)
463 for (const auto & reqIdx : vReq)
464 ret.push_back(JSONRPCExecOne(reqIdx));
466 return write_string(Value(ret), false) + "\n";
469 static CCriticalSection cs_THREAD_RPCHANDLER;
471 void StartRPCServer()
473 strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
474 if (mapArgs["-rpcpassword"].empty())
476 unsigned char rand_pwd[32];
477 GetRandBytes(rand_pwd, 32);
478 std::string strWhatAmI = "To use novacoind";
479 if (mapArgs.count("-server"))
480 strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
481 else if (mapArgs.count("-daemon"))
482 strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
483 uiInterface.ThreadSafeMessageBox(strprintf(
484 _("%s, you must set a rpcpassword in the configuration file:\n %s\n"
485 "It is recommended you use the following random password:\n"
486 "rpcuser=novacoinrpc\n"
488 "(you do not need to remember this password)\n"
489 "If the file does not exist, create it with owner-readable-only file permissions.\n"),
491 GetConfigFile().string().c_str(),
492 EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()),
493 _("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL);
498 std::string host = GetArg("-rpchost", "127.0.0.1");
499 int port = GetArg("-rpcport", GetDefaultRPCPort());
501 g_server = std::make_unique<ix::HttpServer>(port, host);
503 LOCK(cs_THREAD_RPCHANDLER);
505 g_server->setOnConnectionCallback([](const ix::HttpRequestPtr& request, const std::shared_ptr<ix::ConnectionState>& connectionState) -> ix::HttpResponsePtr {
507 ix::WebSocketHttpHeaders headers;
508 headers["Server"] = std::string("novacoin-json-rpc/") + FormatFullVersion();
509 headers["WWW-Authenticate"] = R"(Basic realm="jsonrpc")";
511 if (!HTTPAuthorized(request->headers))
513 printf("ThreadRPCServer incorrect password attempt from %s\n", connectionState->getRemoteIp().c_str());
514 connectionState->setTerminated();
515 return std::make_shared<ix::HttpResponse>(HTTP_UNAUTHORIZED, "Unauthorized", ix::HttpErrorCode::Ok, headers, "Not authorized");
518 if (request->method != "POST") {
519 connectionState->setTerminated();
520 return std::make_shared<ix::HttpResponse>(HTTP_BAD_REQUEST, "Bad request", ix::HttpErrorCode::Ok, headers, "Bad request");
529 if (!read_string(request->body, valRequest))
530 throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
532 std::string strReply;
535 if (valRequest.type() == obj_type) {
536 jreq.parse(valRequest);
539 Value result = tableRPC.execute(jreq.strMethod, jreq.params);
542 strReply = JSONRPCReply(result, Value::null, jreq.id);
545 } else if (valRequest.type() == array_type)
546 // Execute batch of requests
547 strReply = JSONRPCExecBatch(valRequest.get_array());
549 throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
551 // Send reply to client
552 return std::make_shared<ix::HttpResponse>(200, "OK", ix::HttpErrorCode::Ok, headers, strReply);
555 catch(Object& objError)
557 return std::make_shared<ix::HttpResponse>(HTTP_INTERNAL_SERVER_ERROR, "Internal Server Error", ix::HttpErrorCode::Ok, headers, ErrorReply(objError, jreq.id));
559 catch(const std::exception& e)
561 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));
565 std::pair<bool, std::string> result = g_server->listen();
567 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());
568 uiInterface.ThreadSafeMessageBox(strerr, _("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL);
569 return StartShutdown();
572 // Run listening thread
575 // We're listening now
576 vnThreadsRunning[THREAD_RPCLISTENER]++;
581 LOCK(cs_THREAD_RPCHANDLER);
582 if (g_server) g_server->stop();
583 vnThreadsRunning[THREAD_RPCLISTENER]--;
586 json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array ¶ms) const
589 const CRPCCommand *pcmd = tableRPC[strMethod];
591 throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
594 std::string strWarning = GetWarnings("rpc");
595 if (!strWarning.empty() && !GetBoolArg("-disablesafemode") &&
597 throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, std::string("Safe mode: ") + strWarning);
605 result = pcmd->actor(params, false);
607 LOCK2(cs_main, pwalletMain->cs_wallet);
608 result = pcmd->actor(params, false);
613 catch (const std::exception& e)
615 throw JSONRPCError(RPC_MISC_ERROR, e.what());
619 std::vector<std::string> CRPCTable::listCommands() const
621 std::vector<std::string> commandList;
622 for (const auto& i : mapCommands) commandList.emplace_back(i.first);
626 Object CallRPC(const std::string& strMethod, const Array& params)
628 if (mapArgs["-rpcuser"].empty() && mapArgs["-rpcpassword"].empty())
629 throw std::runtime_error(strprintf(
630 _("You must set rpcpassword=<password> in the configuration file:\n%s\n"
631 "If the file does not exist, create it with owner-readable-only file permissions."),
632 GetConfigFile().string().c_str()));
634 // Init net subsystem
637 // Create HTTP client
638 ix::HttpClient httpClient;
639 ix::HttpRequestArgsPtr args = httpClient.createRequest();
641 // HTTP basic authentication
642 ix::WebSocketHttpHeaders mapRequestHeaders;
643 std::string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
644 mapRequestHeaders["Authorization"] = std::string("Basic ") + strUserPass64;
645 args->extraHeaders = mapRequestHeaders;
648 args->connectTimeout = GetArgInt("-rpc_connecttimeout", 30000);
649 args->transferTimeout = GetArgInt("-rpc_transfertimeout", 30000);
651 bool fUseSSL = GetBoolArg("-rpcssl");
652 std::string url = std::string(fUseSSL ? "https://" : "http://") + GetArg("-rpcconnect", "127.0.0.1") + ":" + GetArg("-rpcport", itostr(GetDefaultRPCPort()));
655 std::string strRequest = JSONRPCRequest(strMethod, params, GetRandInt(INT32_MAX));
656 auto out = httpClient.post(url, strRequest, args);
659 int nStatus = out->statusCode;
660 std::string strReply = out->body;
661 ix::WebSocketHttpHeaders mapHeaders = out->headers;
664 if (nStatus == HTTP_UNAUTHORIZED)
665 throw std::runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
666 else if (nStatus >= HTTP_BAD_REQUEST && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR)
667 throw std::runtime_error(strprintf("server returned HTTP error %d", nStatus));
668 else if (strReply.empty())
669 throw std::runtime_error("no response from server");
673 if (!read_string(strReply, valReply))
674 throw std::runtime_error("couldn't parse reply from server");
675 const Object& reply = valReply.get_obj();
677 throw std::runtime_error("expected reply to have result, error and id properties");
686 void ConvertTo(Value& value, bool fAllowNull=false)
688 if (fAllowNull && value.type() == null_type)
690 if (value.type() == str_type)
692 // reinterpret string as unquoted json value
694 std::string strJSON = value.get_str();
695 if (!read_string(strJSON, value2))
696 throw std::runtime_error(std::string("Error parsing JSON:")+strJSON);
697 ConvertTo<T>(value2, fAllowNull);
702 value = value.get_value<T>();
706 // Convert strings to command-specific RPC representation
707 Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
710 for(const auto ¶m : strParams)
711 params.push_back(param);
713 size_t n = params.size();
716 // Special case non-string parameter types
718 if (strMethod == "stop" && n > 0) ConvertTo<bool>(params[0]);
719 if (strMethod == "getaddednodeinfo" && n > 0) ConvertTo<bool>(params[0]);
720 if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);
721 if (strMethod == "mergecoins" && n > 0) ConvertTo<double>(params[0]);
722 if (strMethod == "mergecoins" && n > 1) ConvertTo<double>(params[1]);
723 if (strMethod == "mergecoins" && n > 2) ConvertTo<double>(params[2]);
724 if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]);
725 if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<int64_t>(params[1]);
726 if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<int64_t>(params[1]);
727 if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<int64_t>(params[0]);
728 if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);
729 if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<int64_t>(params[0]);
730 if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]);
731 if (strMethod == "getbalance" && n > 1) ConvertTo<int64_t>(params[1]);
732 if (strMethod == "getblock" && n > 1) ConvertTo<bool>(params[1]);
733 if (strMethod == "getblockbynumber" && n > 0) ConvertTo<int64_t>(params[0]);
734 if (strMethod == "dumpblockbynumber" && n > 0) ConvertTo<int64_t>(params[0]);
735 if (strMethod == "getblockbynumber" && n > 1) ConvertTo<bool>(params[1]);
736 if (strMethod == "getblockhash" && n > 0) ConvertTo<int64_t>(params[0]);
737 if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]);
738 if (strMethod == "move" && n > 3) ConvertTo<int64_t>(params[3]);
739 if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]);
740 if (strMethod == "sendfrom" && n > 3) ConvertTo<int64_t>(params[3]);
741 if (strMethod == "listtransactions" && n > 1) ConvertTo<int64_t>(params[1]);
742 if (strMethod == "listtransactions" && n > 2) ConvertTo<int64_t>(params[2]);
743 if (strMethod == "listaccounts" && n > 0) ConvertTo<int64_t>(params[0]);
744 if (strMethod == "walletpassphrase" && n > 1) ConvertTo<int64_t>(params[1]);
745 if (strMethod == "walletpassphrase" && n > 2) ConvertTo<bool>(params[2]);
746 if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]);
747 if (strMethod == "listsinceblock" && n > 1) ConvertTo<int64_t>(params[1]);
749 if (strMethod == "scaninput" && n > 0) ConvertTo<Object>(params[0]);
751 if (strMethod == "sendalert" && n > 2) ConvertTo<int64_t>(params[2]);
752 if (strMethod == "sendalert" && n > 3) ConvertTo<int64_t>(params[3]);
753 if (strMethod == "sendalert" && n > 4) ConvertTo<int64_t>(params[4]);
754 if (strMethod == "sendalert" && n > 5) ConvertTo<int64_t>(params[5]);
755 if (strMethod == "sendalert" && n > 6) ConvertTo<int64_t>(params[6]);
757 if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]);
758 if (strMethod == "sendmany" && n > 2) ConvertTo<int64_t>(params[2]);
759 if (strMethod == "reservebalance" && n > 0) ConvertTo<bool>(params[0]);
760 if (strMethod == "reservebalance" && n > 1) ConvertTo<double>(params[1]);
761 if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<int64_t>(params[0]);
762 if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]);
763 if (strMethod == "listunspent" && n > 0) ConvertTo<int64_t>(params[0]);
764 if (strMethod == "listunspent" && n > 1) ConvertTo<int64_t>(params[1]);
765 if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]);
766 if (strMethod == "getrawtransaction" && n > 1) ConvertTo<int64_t>(params[1]);
767 if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]);
768 if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]);
769 if (strMethod == "createmultisig" && n > 0) ConvertTo<int64_t>(params[0]);
770 if (strMethod == "createmultisig" && n > 1) ConvertTo<Array>(params[1]);
771 if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1], true);
772 if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2], true);
773 if (strMethod == "keypoolrefill" && n > 0) ConvertTo<int64_t>(params[0]);
774 if (strMethod == "keypoolreset" && n > 0) ConvertTo<int64_t>(params[0]);
775 if (strMethod == "importaddress" && n > 2) ConvertTo<bool>(params[2]);
776 if (strMethod == "importprivkey" && n > 2) ConvertTo<bool>(params[2]);
781 int CommandLineRPC(int argc, char *argv[])
783 std::string strPrint;
788 while (argc > 1 && IsSwitchChar(argv[1][0]))
796 throw std::runtime_error("too few parameters");
797 std::string strMethod = argv[1];
799 // Parameters default to strings
800 std::vector<std::string> strParams(&argv[2], &argv[argc]);
801 Array params = RPCConvertValues(strMethod, strParams);
804 Object reply = CallRPC(strMethod, params);
807 const Value& result = find_value(reply, "result");
808 const Value& error = find_value(reply, "error");
810 if (error.type() != null_type)
813 strPrint = "error: " + write_string(error, false);
814 int code = find_value(error.get_obj(), "code").get_int();
820 if (result.type() == null_type)
822 else if (result.type() == str_type)
823 strPrint = result.get_str();
825 strPrint = write_string(result, true);
828 catch (const std::exception& e)
830 strPrint = std::string("error: ") + e.what();
835 PrintException(nullptr, "CommandLineRPC()");
838 if (!strPrint.empty())
840 fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
846 const CRPCTable tableRPC;