1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
12 #include "ui_interface.h"
14 #include "utilstrencodings.h"
15 #include "asyncrpcqueue.h"
21 #include <boost/bind.hpp>
22 #include <boost/filesystem.hpp>
23 #include <boost/foreach.hpp>
24 #include <boost/iostreams/concepts.hpp>
25 #include <boost/iostreams/stream.hpp>
26 #include <boost/shared_ptr.hpp>
27 #include <boost/signals2/signal.hpp>
28 #include <boost/thread.hpp>
29 #include <boost/algorithm/string/case_conv.hpp> // for to_upper()
31 using namespace RPCServer;
34 static bool fRPCRunning = false;
35 static bool fRPCInWarmup = true;
36 static std::string rpcWarmupStatus("RPC server started");
37 static CCriticalSection cs_rpcWarmup;
38 /* Timer-creating functions */
39 static std::vector<RPCTimerInterface*> timerInterfaces;
40 /* Map of name to timer.
41 * @note Can be changed to std::unique_ptr when C++11 */
42 static std::map<std::string, boost::shared_ptr<RPCTimerBase> > deadlineTimers;
44 static struct CRPCSignals
46 boost::signals2::signal<void ()> Started;
47 boost::signals2::signal<void ()> Stopped;
48 boost::signals2::signal<void (const CRPCCommand&)> PreCommand;
49 boost::signals2::signal<void (const CRPCCommand&)> PostCommand;
52 void RPCServer::OnStarted(boost::function<void ()> slot)
54 g_rpcSignals.Started.connect(slot);
57 void RPCServer::OnStopped(boost::function<void ()> slot)
59 g_rpcSignals.Stopped.connect(slot);
62 void RPCServer::OnPreCommand(boost::function<void (const CRPCCommand&)> slot)
64 g_rpcSignals.PreCommand.connect(boost::bind(slot, _1));
67 void RPCServer::OnPostCommand(boost::function<void (const CRPCCommand&)> slot)
69 g_rpcSignals.PostCommand.connect(boost::bind(slot, _1));
72 void RPCTypeCheck(const UniValue& params,
73 const list<UniValue::VType>& typesExpected,
77 BOOST_FOREACH(UniValue::VType t, typesExpected)
79 if (params.size() <= i)
82 const UniValue& v = params[i];
83 if (!((v.type() == t) || (fAllowNull && (v.isNull()))))
85 string err = strprintf("Expected type %s, got %s",
86 uvTypeName(t), uvTypeName(v.type()));
87 throw JSONRPCError(RPC_TYPE_ERROR, err);
93 void RPCTypeCheckObj(const UniValue& o,
94 const map<string, UniValue::VType>& typesExpected,
97 BOOST_FOREACH(const PAIRTYPE(string, UniValue::VType)& t, typesExpected)
99 const UniValue& v = find_value(o, t.first);
100 if (!fAllowNull && v.isNull())
101 throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first));
103 if (!((v.type() == t.second) || (fAllowNull && (v.isNull()))))
105 string err = strprintf("Expected type %s for %s, got %s",
106 uvTypeName(t.second), t.first, uvTypeName(v.type()));
107 throw JSONRPCError(RPC_TYPE_ERROR, err);
112 CAmount AmountFromValue(const UniValue& value)
114 if (!value.isNum() && !value.isStr())
115 throw JSONRPCError(RPC_TYPE_ERROR, "Amount is not a number or string");
117 if (!ParseFixedPoint(value.getValStr(), 8, &amount))
118 throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
119 if (!MoneyRange(amount))
120 throw JSONRPCError(RPC_TYPE_ERROR, "Amount out of range");
124 UniValue ValueFromAmount(const CAmount& amount)
126 bool sign = amount < 0;
127 int64_t n_abs = (sign ? -amount : amount);
128 int64_t quotient = n_abs / COIN;
129 int64_t remainder = n_abs % COIN;
130 return UniValue(UniValue::VNUM,
131 strprintf("%s%d.%08d", sign ? "-" : "", quotient, remainder));
134 uint256 ParseHashV(const UniValue& v, string strName)
138 strHex = v.get_str();
139 if (!IsHex(strHex)) // Note: IsHex("") is false
140 throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
142 result.SetHex(strHex);
145 uint256 ParseHashO(const UniValue& o, string strKey)
147 return ParseHashV(find_value(o, strKey), strKey);
149 vector<unsigned char> ParseHexV(const UniValue& v, string strName)
153 strHex = v.get_str();
155 throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
156 return ParseHex(strHex);
158 vector<unsigned char> ParseHexO(const UniValue& o, string strKey)
160 return ParseHexV(find_value(o, strKey), strKey);
164 * Note: This interface may still be subject to change.
167 std::string CRPCTable::help(const std::string& strCommand) const
171 set<rpcfn_type> setDone;
172 vector<pair<string, const CRPCCommand*> > vCommands;
174 for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)
175 vCommands.push_back(make_pair(mi->second->category + mi->first, mi->second));
176 sort(vCommands.begin(), vCommands.end());
178 BOOST_FOREACH(const PAIRTYPE(string, const CRPCCommand*)& command, vCommands)
180 const CRPCCommand *pcmd = command.second;
181 string strMethod = pcmd->name;
182 // We already filter duplicates, but these deprecated screw up the sort order
183 if (strMethod.find("label") != string::npos)
185 if ((strCommand != "" || pcmd->category == "hidden") && strMethod != strCommand)
190 rpcfn_type pfn = pcmd->actor;
191 if (setDone.insert(pfn).second)
192 (*pfn)(params, true);
194 catch (const std::exception& e)
196 // Help text is returned in an exception
197 string strHelp = string(e.what());
198 if (strCommand == "")
200 if (strHelp.find('\n') != string::npos)
201 strHelp = strHelp.substr(0, strHelp.find('\n'));
203 if (category != pcmd->category)
205 if (!category.empty())
207 category = pcmd->category;
208 string firstLetter = category.substr(0,1);
209 boost::to_upper(firstLetter);
210 strRet += "== " + firstLetter + category.substr(1) + " ==\n";
213 strRet += strHelp + "\n";
217 strRet = strprintf("help: unknown command: %s\n", strCommand);
218 strRet = strRet.substr(0,strRet.size()-1);
222 UniValue help(const UniValue& params, bool fHelp)
224 if (fHelp || params.size() > 1)
226 "help ( \"command\" )\n"
227 "\nList all commands, or get help for a specified command.\n"
229 "1. \"command\" (string, optional) The command to get help on\n"
231 "\"text\" (string) The help text\n"
235 if (params.size() > 0)
236 strCommand = params[0].get_str();
238 return tableRPC.help(strCommand);
242 UniValue stop(const UniValue& params, bool fHelp)
244 // Accept the deprecated and ignored 'detach' boolean argument
245 if (fHelp || params.size() > 1)
248 "\nStop Komodo server.");
249 // Shutdown will take long enough that the response should get back
251 return "Komodo server stopping";
257 static const CRPCCommand vRPCCommands[] =
258 { // category name actor (function) okSafeMode
259 // --------------------- ------------------------ ----------------------- ----------
260 /* Overall control/query calls */
261 { "control", "getinfo", &getinfo, true }, /* uses wallet if enabled */
262 { "control", "help", &help, true },
263 { "control", "stop", &stop, true },
266 { "network", "getnetworkinfo", &getnetworkinfo, true },
267 { "network", "addnode", &addnode, true },
268 { "network", "disconnectnode", &disconnectnode, true },
269 { "network", "getaddednodeinfo", &getaddednodeinfo, true },
270 { "network", "getconnectioncount", &getconnectioncount, true },
271 { "network", "getnettotals", &getnettotals, true },
272 { "network", "getpeerinfo", &getpeerinfo, true },
273 { "network", "ping", &ping, true },
274 { "network", "setban", &setban, true },
275 { "network", "listbanned", &listbanned, true },
276 { "network", "clearbanned", &clearbanned, true },
278 /* Block chain and UTXO */
279 { "blockchain", "getblockchaininfo", &getblockchaininfo, true },
280 { "blockchain", "getbestblockhash", &getbestblockhash, true },
281 { "blockchain", "getblockcount", &getblockcount, true },
282 { "blockchain", "getblock", &getblock, true },
283 { "blockchain", "getblockhash", &getblockhash, true },
284 { "blockchain", "getblockheader", &getblockheader, true },
285 { "blockchain", "getchaintips", &getchaintips, true },
286 { "blockchain", "getdifficulty", &getdifficulty, true },
287 { "blockchain", "getmempoolinfo", &getmempoolinfo, true },
288 { "blockchain", "getrawmempool", &getrawmempool, true },
289 { "blockchain", "gettxout", &gettxout, true },
290 { "blockchain", "gettxoutproof", &gettxoutproof, true },
291 { "blockchain", "verifytxoutproof", &verifytxoutproof, true },
292 { "blockchain", "gettxoutsetinfo", &gettxoutsetinfo, true },
293 { "blockchain", "verifychain", &verifychain, true },
294 { "blockchain", "paxprice", &paxprice, true },
295 { "blockchain", "paxpending", &paxpending, true },
296 { "blockchain", "paxprices", &paxprices, true },
297 { "blockchain", "notaries", ¬aries, true },
298 { "blockchain", "minerids", &minerids, true },
299 { "blockchain", "kvsearch", &kvsearch, true },
300 { "blockchain", "kvupdate", &kvupdate, true },
304 { "mining", "getblocktemplate", &getblocktemplate, true },
306 { "mining", "getmininginfo", &getmininginfo, true },
307 { "mining", "getlocalsolps", &getlocalsolps, true },
308 { "mining", "getnetworksolps", &getnetworksolps, true },
309 { "mining", "getnetworkhashps", &getnetworkhashps, true },
310 { "mining", "prioritisetransaction", &prioritisetransaction, true },
311 { "mining", "submitblock", &submitblock, true },
312 { "mining", "getblocksubsidy", &getblocksubsidy, true },
315 /* Coin generation */
316 { "generating", "getgenerate", &getgenerate, true },
317 { "generating", "setgenerate", &setgenerate, true },
318 { "generating", "generate", &generate, true },
321 /* Raw transactions */
322 { "rawtransactions", "createrawtransaction", &createrawtransaction, true },
323 { "rawtransactions", "decoderawtransaction", &decoderawtransaction, true },
324 { "rawtransactions", "decodescript", &decodescript, true },
325 { "rawtransactions", "getrawtransaction", &getrawtransaction, true },
326 { "rawtransactions", "sendrawtransaction", &sendrawtransaction, false },
327 { "rawtransactions", "signrawtransaction", &signrawtransaction, false }, /* uses wallet if enabled */
329 { "rawtransactions", "fundrawtransaction", &fundrawtransaction, false },
332 /* Utility functions */
333 { "util", "createmultisig", &createmultisig, true },
334 { "util", "validateaddress", &validateaddress, true }, /* uses wallet if enabled */
335 { "util", "verifymessage", &verifymessage, true },
336 { "util", "estimatefee", &estimatefee, true },
337 { "util", "estimatepriority", &estimatepriority, true },
338 { "util", "z_validateaddress", &z_validateaddress, true }, /* uses wallet if enabled */
340 /* Not shown in help */
341 { "hidden", "invalidateblock", &invalidateblock, true },
342 { "hidden", "reconsiderblock", &reconsiderblock, true },
343 { "hidden", "setmocktime", &setmocktime, true },
345 { "hidden", "resendwallettransactions", &resendwallettransactions, true},
350 { "wallet", "addmultisigaddress", &addmultisigaddress, true },
351 { "wallet", "backupwallet", &backupwallet, true },
352 { "wallet", "dumpprivkey", &dumpprivkey, true },
353 { "wallet", "dumpwallet", &dumpwallet, true },
354 { "wallet", "encryptwallet", &encryptwallet, true },
355 { "wallet", "getaccountaddress", &getaccountaddress, true },
356 { "wallet", "getaccount", &getaccount, true },
357 { "wallet", "getaddressesbyaccount", &getaddressesbyaccount, true },
358 { "wallet", "getbalance", &getbalance, false },
359 { "wallet", "getnewaddress", &getnewaddress, true },
360 { "wallet", "getrawchangeaddress", &getrawchangeaddress, true },
361 { "wallet", "getreceivedbyaccount", &getreceivedbyaccount, false },
362 { "wallet", "getreceivedbyaddress", &getreceivedbyaddress, false },
363 { "wallet", "gettransaction", &gettransaction, false },
364 { "wallet", "getunconfirmedbalance", &getunconfirmedbalance, false },
365 { "wallet", "getwalletinfo", &getwalletinfo, false },
366 { "wallet", "importprivkey", &importprivkey, true },
367 { "wallet", "importwallet", &importwallet, true },
368 { "wallet", "importaddress", &importaddress, true },
369 { "wallet", "keypoolrefill", &keypoolrefill, true },
370 { "wallet", "listaccounts", &listaccounts, false },
371 { "wallet", "listaddressgroupings", &listaddressgroupings, false },
372 { "wallet", "listlockunspent", &listlockunspent, false },
373 { "wallet", "listreceivedbyaccount", &listreceivedbyaccount, false },
374 { "wallet", "listreceivedbyaddress", &listreceivedbyaddress, false },
375 { "wallet", "listsinceblock", &listsinceblock, false },
376 { "wallet", "listtransactions", &listtransactions, false },
377 { "wallet", "listunspent", &listunspent, false },
378 { "wallet", "lockunspent", &lockunspent, true },
379 { "wallet", "move", &movecmd, false },
380 { "wallet", "sendfrom", &sendfrom, false },
381 { "wallet", "sendmany", &sendmany, false },
382 { "wallet", "sendtoaddress", &sendtoaddress, false },
383 { "wallet", "setaccount", &setaccount, true },
384 { "wallet", "settxfee", &settxfee, true },
385 { "wallet", "signmessage", &signmessage, true },
386 { "wallet", "walletlock", &walletlock, true },
387 { "wallet", "walletpassphrasechange", &walletpassphrasechange, true },
388 { "wallet", "walletpassphrase", &walletpassphrase, true },
389 { "wallet", "zcbenchmark", &zc_benchmark, true },
390 { "wallet", "zcrawkeygen", &zc_raw_keygen, true },
391 { "wallet", "zcrawjoinsplit", &zc_raw_joinsplit, true },
392 { "wallet", "zcrawreceive", &zc_raw_receive, true },
393 { "wallet", "zcsamplejoinsplit", &zc_sample_joinsplit, true },
394 { "wallet", "z_listreceivedbyaddress",&z_listreceivedbyaddress,false },
395 { "wallet", "z_getbalance", &z_getbalance, false },
396 { "wallet", "z_gettotalbalance", &z_gettotalbalance, false },
397 { "wallet", "z_sendmany", &z_sendmany, false },
398 { "wallet", "z_getoperationstatus", &z_getoperationstatus, true },
399 { "wallet", "z_getoperationresult", &z_getoperationresult, true },
400 { "wallet", "z_listoperationids", &z_listoperationids, true },
401 { "wallet", "z_getnewaddress", &z_getnewaddress, true },
402 { "wallet", "z_listaddresses", &z_listaddresses, true },
403 { "wallet", "z_exportkey", &z_exportkey, true },
404 { "wallet", "z_importkey", &z_importkey, true },
405 { "wallet", "z_exportwallet", &z_exportwallet, true },
406 { "wallet", "z_importwallet", &z_importwallet, true },
408 { "wallet", "paxdeposit", &paxdeposit, true },
409 { "wallet", "paxwithdraw", &paxwithdraw, true }
410 #endif // ENABLE_WALLET
413 CRPCTable::CRPCTable()
416 for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++)
418 const CRPCCommand *pcmd;
420 pcmd = &vRPCCommands[vcidx];
421 mapCommands[pcmd->name] = pcmd;
425 const CRPCCommand *CRPCTable::operator[](const std::string &name) const
427 map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
428 if (it == mapCommands.end())
437 int port = defaultPort;
438 SplitHostPort(strEndpoint, port, addr);
439 return ip::tcp::endpoint(boost::asio::ip::address::from_string(addr), port);
442 void StartRPCThreads()
444 rpc_allow_subnets.clear();
445 rpc_allow_subnets.push_back(CSubNet("127.0.0.0/8")); // always allow IPv4 local subnet
446 rpc_allow_subnets.push_back(CSubNet("::1")); // always allow IPv6 localhost
447 if (mapMultiArgs.count("-rpcallowip"))
449 const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
450 BOOST_FOREACH(string strAllow, vAllow)
452 CSubNet subnet(strAllow);
453 if(!subnet.IsValid())
455 uiInterface.ThreadSafeMessageBox(
456 strprintf("Invalid -rpcallowip subnet specification: %s. Valid are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24).", strAllow),
457 "", CClientUIInterface::MSG_ERROR);
461 rpc_allow_subnets.push_back(subnet);
464 std::string strAllowed;
465 BOOST_FOREACH(const CSubNet &subnet, rpc_allow_subnets)
466 strAllowed += subnet.ToString() + " ";
467 LogPrint("rpc", "Allowing RPC connections from: %s\n", strAllowed);
469 if (mapArgs["-rpcpassword"] == "")
471 LogPrintf("No rpcpassword set - using random cookie authentication\n");
472 if (!GenerateAuthCookie(&strRPCUserColonPass)) {
473 uiInterface.ThreadSafeMessageBox(
474 _("Error: A fatal internal error occured, see debug.log for details"), // Same message as AbortNode
475 "", CClientUIInterface::MSG_ERROR);
480 strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
483 assert(rpc_io_service == NULL);
484 rpc_io_service = new boost::asio::io_service();
485 rpc_ssl_context = new ssl::context(*rpc_io_service, ssl::context::sslv23);
487 const bool fUseSSL = GetBoolArg("-rpcssl", false);
491 rpc_ssl_context->set_options(ssl::context::no_sslv2 | ssl::context::no_sslv3);
493 boost::filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert"));
494 if (!pathCertFile.is_complete()) pathCertFile = boost::filesystem::path(GetDataDir()) / pathCertFile;
495 if (boost::filesystem::exists(pathCertFile)) rpc_ssl_context->use_certificate_chain_file(pathCertFile.string());
496 else LogPrintf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string());
498 boost::filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem"));
499 if (!pathPKFile.is_complete()) pathPKFile = boost::filesystem::path(GetDataDir()) / pathPKFile;
500 if (boost::filesystem::exists(pathPKFile)) rpc_ssl_context->use_private_key_file(pathPKFile.string(), ssl::context::pem);
501 else LogPrintf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string());
503 string strCiphers = GetArg("-rpcsslciphers", "TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH");
504 SSL_CTX_set_cipher_list(rpc_ssl_context->impl(), strCiphers.c_str());
507 std::vector<ip::tcp::endpoint> vEndpoints;
508 bool bBindAny = false;
509 int defaultPort = GetArg("-rpcport", BaseParams().RPCPort());
510 if (!mapArgs.count("-rpcallowip")) // Default to loopback if not allowing external IPs
512 vEndpoints.push_back(ip::tcp::endpoint(boost::asio::ip::address_v6::loopback(), defaultPort));
513 vEndpoints.push_back(ip::tcp::endpoint(boost::asio::ip::address_v4::loopback(), defaultPort));
514 if (mapArgs.count("-rpcbind"))
516 LogPrintf("WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n");
518 } else if (mapArgs.count("-rpcbind")) // Specific bind address
520 BOOST_FOREACH(const std::string &addr, mapMultiArgs["-rpcbind"])
523 vEndpoints.push_back(ParseEndpoint(addr, defaultPort));
525 catch (const boost::system::system_error&)
527 uiInterface.ThreadSafeMessageBox(
528 strprintf(_("Could not parse -rpcbind value %s as network address"), addr),
529 "", CClientUIInterface::MSG_ERROR);
534 } else { // No specific bind address specified, bind to any
535 vEndpoints.push_back(ip::tcp::endpoint(boost::asio::ip::address_v6::any(), defaultPort));
536 vEndpoints.push_back(ip::tcp::endpoint(boost::asio::ip::address_v4::any(), defaultPort));
537 // Prefer making the socket dual IPv6/IPv4 instead of binding
538 // to both addresses separately.
542 bool fListening = false;
544 std::string straddress;
545 BOOST_FOREACH(const ip::tcp::endpoint &endpoint, vEndpoints)
548 boost::asio::ip::address bindAddress = endpoint.address();
549 straddress = bindAddress.to_string();
550 LogPrintf("Binding RPC on address %s port %i (IPv4+IPv6 bind any: %i)\n", straddress, endpoint.port(), bBindAny);
551 boost::system::error_code v6_only_error;
552 boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(*rpc_io_service));
554 acceptor->open(endpoint.protocol());
555 acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
557 // Try making the socket dual IPv6/IPv4 when listening on the IPv6 "any" address
558 acceptor->set_option(boost::asio::ip::v6_only(
559 !bBindAny || bindAddress != boost::asio::ip::address_v6::any()), v6_only_error);
561 acceptor->bind(endpoint);
562 acceptor->listen(socket_base::max_connections);
564 RPCListen(acceptor, *rpc_ssl_context, fUseSSL);
567 rpc_acceptors.push_back(acceptor);
568 // If dual IPv6/IPv4 bind successful, skip binding to IPv4 separately
569 if(bBindAny && bindAddress == boost::asio::ip::address_v6::any() && !v6_only_error)
572 catch (const boost::system::system_error& e)
574 LogPrintf("ERROR: Binding RPC on address %s port %i failed: %s\n", straddress, endpoint.port(), e.what());
575 strerr = strprintf(_("An error occurred while setting up the RPC address %s port %u for listening: %s"), straddress, endpoint.port(), e.what());
580 uiInterface.ThreadSafeMessageBox(strerr, "", CClientUIInterface::MSG_ERROR);
585 rpc_worker_group = new boost::thread_group();
586 for (int i = 0; i < GetArg("-rpcthreads", 4); i++)
587 rpc_worker_group->create_thread(boost::bind(&boost::asio::io_service::run, rpc_io_service));
589 LogPrint("rpc", "Starting RPC\n");
590 >>>>>>> zcash/master*/
592 g_rpcSignals.Started();
594 // Launch one async rpc worker. The ability to launch multiple workers is not recommended at present and thus the option is disabled.
595 //for (int i=0; i<32; i++)
596 getAsyncRPCQueue()->addWorker();
598 int n = GetArg("-rpcasyncthreads", 1);
600 LogPrintf("ERROR: Invalid value %d for -rpcasyncthreads. Must be at least 1.\n", n);
601 strerr = strprintf(_("An error occurred while setting up the Async RPC threads, invalid parameter value of %d (must be at least 1)."), n);
602 uiInterface.ThreadSafeMessageBox(strerr, "", CClientUIInterface::MSG_ERROR);
606 for (int i = 0; i < n; i++)
607 getAsyncRPCQueue()->addWorker();
614 LogPrint("rpc", "Interrupting RPC\n");
615 // Interrupt e.g. running longpolls
621 LogPrint("rpc", "Stopping RPC\n");
622 deadlineTimers.clear();
623 g_rpcSignals.Stopped();
625 // Tells async queue to cancel all operations and shutdown.
626 LogPrintf("%s: waiting for async rpc workers to stop\n", __func__);
627 getAsyncRPCQueue()->closeAndWait();
635 void SetRPCWarmupStatus(const std::string& newStatus)
638 rpcWarmupStatus = newStatus;
641 void SetRPCWarmupFinished()
644 assert(fRPCInWarmup);
645 fRPCInWarmup = false;
648 bool RPCIsInWarmup(std::string *outStatus)
652 *outStatus = rpcWarmupStatus;
656 void JSONRequest::parse(const UniValue& valRequest)
659 if (!valRequest.isObject())
660 throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
661 const UniValue& request = valRequest.get_obj();
663 // Parse id now so errors from here on will have the id
664 id = find_value(request, "id");
667 UniValue valMethod = find_value(request, "method");
668 if (valMethod.isNull())
669 throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
670 if (!valMethod.isStr())
671 throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
672 strMethod = valMethod.get_str();
673 if (strMethod != "getblocktemplate")
674 LogPrint("rpc", "ThreadRPCServer method=%s\n", SanitizeString(strMethod));
677 UniValue valParams = find_value(request, "params");
678 if (valParams.isArray())
679 params = valParams.get_array();
680 else if (valParams.isNull())
681 params = UniValue(UniValue::VARR);
683 throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array");
686 static UniValue JSONRPCExecOne(const UniValue& req)
688 UniValue rpc_result(UniValue::VOBJ);
694 UniValue result = tableRPC.execute(jreq.strMethod, jreq.params);
695 rpc_result = JSONRPCReplyObj(result, NullUniValue, jreq.id);
697 catch (const UniValue& objError)
699 rpc_result = JSONRPCReplyObj(NullUniValue, objError, jreq.id);
701 catch (const std::exception& e)
703 rpc_result = JSONRPCReplyObj(NullUniValue,
704 JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
710 std::string JSONRPCExecBatch(const UniValue& vReq)
712 UniValue ret(UniValue::VARR);
713 for (size_t reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
714 ret.push_back(JSONRPCExecOne(vReq[reqIdx]));
716 return ret.write() + "\n";
719 UniValue CRPCTable::execute(const std::string &strMethod, const UniValue ¶ms) const
721 // Return immediately if in warmup
725 throw JSONRPCError(RPC_IN_WARMUP, rpcWarmupStatus);
729 if (!HTTPAuthorized(mapHeaders))
731 LogPrintf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string());
732 //Deter brute-forcing We don't support exposing the RPC port, so this shouldn't result in a DoS.
735 conn->stream() << HTTPError(HTTP_UNAUTHORIZED, false) << std::flush;
743 if (!read_string(strRequest, valRequest))
745 fprintf(stderr,"CANTPARSE.(%s)\n",strRequest.c_str());
746 throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
748 // Return immediately if in warmup
752 throw JSONRPCError(RPC_IN_WARMUP, rpcWarmupStatus);
758 if (valRequest.type() == obj_type) {
759 jreq.parse(valRequest);
761 Value result = tableRPC.execute(jreq.strMethod, jreq.params);
764 strReply = JSONRPCReply(result, Value::null, jreq.id);
767 } else if (valRequest.type() == array_type)
768 strReply = JSONRPCExecBatch(valRequest.get_array());
770 throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
772 conn->stream() << HTTPReplyHeader(HTTP_OK, fRun, strReply.size()) << strReply << std::flush;
774 catch (const Object& objError)
776 ErrorReply(conn->stream(), objError, jreq.id);
779 catch (const std::exception& e)
781 ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
787 void ServiceConnection(AcceptedConnection *conn)
790 while (fRun && !ShutdownRequested())
793 map<string, string> mapHeaders;
794 string strRequest, strMethod, strURI;
796 // Read HTTP request line
797 if (!ReadHTTPRequestLine(conn->stream(), nProto, strMethod, strURI))
800 // Read HTTP message headers and body
801 ReadHTTPMessage(conn->stream(), mapHeaders, strRequest, nProto, MAX_SIZE);
803 // TODO #1856: Re-enable support for persistent connections.
804 // We have disabled support for HTTP Keep-Alive until resolution of #1680, upstream rpc deadlock.
805 // Close connection immediately.
808 // HTTP Keep-Alive is false; close connection immediately
809 //if ((mapHeaders["connection"] == "close") || (!GetBoolArg("-rpckeepalive", true)))
813 // Process via JSON-RPC API
815 if (!HTTPReq_JSONRPC(conn, strRequest, mapHeaders, fRun))
818 // Process via HTTP REST API
819 } else if (strURI.substr(0, 6) == "/rest/" && GetBoolArg("-rest", false)) {
820 if (!HTTPReq_REST(conn, strURI, strRequest, mapHeaders, fRun))
824 conn->stream() << HTTPError(HTTP_NOT_FOUND, false) << std::flush;
830 json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array ¶ms) const
833 >>>>>>> zcash/master*/
835 const CRPCCommand *pcmd = tableRPC[strMethod];
837 throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
839 g_rpcSignals.PreCommand(*pcmd);
844 return pcmd->actor(params, false);
846 catch (const std::exception& e)
848 throw JSONRPCError(RPC_MISC_ERROR, e.what());
851 g_rpcSignals.PostCommand(*pcmd);
854 std::string HelpExampleCli(const std::string& methodname, const std::string& args)
856 return "> zcash-cli " + methodname + " " + args + "\n";
859 std::string HelpExampleRpc(const std::string& methodname, const std::string& args)
861 return "> curl --user myusername --data-binary '{\"jsonrpc\": \"1.0\", \"id\":\"curltest\", "
862 "\"method\": \"" + methodname + "\", \"params\": [" + args + "] }' -H 'content-type: text/plain;' http://127.0.0.1:8232/\n";
865 void RPCRegisterTimerInterface(RPCTimerInterface *iface)
867 timerInterfaces.push_back(iface);
870 void RPCUnregisterTimerInterface(RPCTimerInterface *iface)
872 std::vector<RPCTimerInterface*>::iterator i = std::find(timerInterfaces.begin(), timerInterfaces.end(), iface);
873 assert(i != timerInterfaces.end());
874 timerInterfaces.erase(i);
877 void RPCRunLater(const std::string& name, boost::function<void(void)> func, int64_t nSeconds)
879 if (timerInterfaces.empty())
880 throw JSONRPCError(RPC_INTERNAL_ERROR, "No timer handler registered for RPC");
881 deadlineTimers.erase(name);
882 RPCTimerInterface* timerInterface = timerInterfaces[0];
883 LogPrint("rpc", "queue run of timer %s in %i seconds (using %s)\n", name, nSeconds, timerInterface->Name());
884 deadlineTimers.insert(std::make_pair(name, boost::shared_ptr<RPCTimerBase>(timerInterface->NewTimer(func, nSeconds*1000))));
887 const CRPCTable tableRPC;
889 // Return async rpc queue
890 std::shared_ptr<AsyncRPCQueue> getAsyncRPCQueue()
892 return AsyncRPCQueue::sharedInstance();