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"
16 #include "wallet/wallet.h"
18 #include "asyncrpcqueue.h"
22 #include <boost/algorithm/string.hpp>
23 #include <boost/asio.hpp>
24 #include <boost/asio/ssl.hpp>
25 #include <boost/bind.hpp>
26 #include <boost/filesystem.hpp>
27 #include <boost/foreach.hpp>
28 #include <boost/iostreams/concepts.hpp>
29 #include <boost/iostreams/stream.hpp>
30 #include <boost/shared_ptr.hpp>
31 #include <boost/signals2/signal.hpp>
32 #include <boost/thread.hpp>
33 #include "json/json_spirit_writer_template.h"
35 using namespace boost::asio;
36 using namespace json_spirit;
37 using namespace RPCServer;
40 static std::string strRPCUserColonPass;
42 static bool fRPCRunning = false;
43 static bool fRPCInWarmup = true;
44 static std::string rpcWarmupStatus("RPC server started");
45 static CCriticalSection cs_rpcWarmup;
47 //! These are created by StartRPCThreads, destroyed in StopRPCThreads
48 static boost::asio::io_service* rpc_io_service = NULL;
49 static map<string, boost::shared_ptr<deadline_timer> > deadlineTimers;
50 static ssl::context* rpc_ssl_context = NULL;
51 static boost::thread_group* rpc_worker_group = NULL;
52 static boost::asio::io_service::work *rpc_dummy_work = NULL;
53 static std::vector<CSubNet> rpc_allow_subnets; //!< List of subnets to allow RPC connections from
54 static std::vector< boost::shared_ptr<ip::tcp::acceptor> > rpc_acceptors;
56 static struct CRPCSignals
58 boost::signals2::signal<void ()> Started;
59 boost::signals2::signal<void ()> Stopped;
60 boost::signals2::signal<void (const CRPCCommand&)> PreCommand;
61 boost::signals2::signal<void (const CRPCCommand&)> PostCommand;
64 void RPCServer::OnStarted(boost::function<void ()> slot)
66 g_rpcSignals.Started.connect(slot);
69 void RPCServer::OnStopped(boost::function<void ()> slot)
71 g_rpcSignals.Stopped.connect(slot);
74 void RPCServer::OnPreCommand(boost::function<void (const CRPCCommand&)> slot)
76 g_rpcSignals.PreCommand.connect(boost::bind(slot, _1));
79 void RPCServer::OnPostCommand(boost::function<void (const CRPCCommand&)> slot)
81 g_rpcSignals.PostCommand.connect(boost::bind(slot, _1));
84 void RPCTypeCheck(const Array& params,
85 const list<Value_type>& typesExpected,
89 BOOST_FOREACH(Value_type t, typesExpected)
91 if (params.size() <= i)
94 const Value& v = params[i];
95 if (!((v.type() == t) || (fAllowNull && (v.type() == null_type))))
97 string err = strprintf("Expected type %s, got %s",
98 Value_type_name[t], Value_type_name[v.type()]);
99 throw JSONRPCError(RPC_TYPE_ERROR, err);
105 void RPCTypeCheck(const Object& o,
106 const map<string, Value_type>& typesExpected,
109 BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected)
111 const Value& v = find_value(o, t.first);
112 if (!fAllowNull && v.type() == null_type)
113 throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first));
115 if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type))))
117 string err = strprintf("Expected type %s for %s, got %s",
118 Value_type_name[t.second], t.first, Value_type_name[v.type()]);
119 throw JSONRPCError(RPC_TYPE_ERROR, err);
124 static inline int64_t roundint64(double d)
126 return (int64_t)(d > 0 ? d + 0.5 : d - 0.5);
129 CAmount AmountFromValue(const Value& value)
131 double dAmount = value.get_real();
132 if (dAmount <= 0.0 || dAmount > 21000000.0)
133 throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
134 CAmount nAmount = roundint64(dAmount * COIN);
135 if (!MoneyRange(nAmount))
136 throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
140 Value ValueFromAmount(const CAmount& amount)
142 return (double)amount / (double)COIN;
145 uint256 ParseHashV(const Value& v, string strName)
148 if (v.type() == str_type)
149 strHex = v.get_str();
150 if (!IsHex(strHex)) // Note: IsHex("") is false
151 throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
153 result.SetHex(strHex);
156 uint256 ParseHashO(const Object& o, string strKey)
158 return ParseHashV(find_value(o, strKey), strKey);
160 vector<unsigned char> ParseHexV(const Value& v, string strName)
163 if (v.type() == str_type)
164 strHex = v.get_str();
166 throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
167 return ParseHex(strHex);
169 vector<unsigned char> ParseHexO(const Object& o, string strKey)
171 return ParseHexV(find_value(o, strKey), strKey);
176 * Note: This interface may still be subject to change.
179 string CRPCTable::help(string strCommand) const
183 set<rpcfn_type> setDone;
184 vector<pair<string, const CRPCCommand*> > vCommands;
186 for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)
187 vCommands.push_back(make_pair(mi->second->category + mi->first, mi->second));
188 sort(vCommands.begin(), vCommands.end());
190 BOOST_FOREACH(const PAIRTYPE(string, const CRPCCommand*)& command, vCommands)
192 const CRPCCommand *pcmd = command.second;
193 string strMethod = pcmd->name;
194 // We already filter duplicates, but these deprecated screw up the sort order
195 if (strMethod.find("label") != string::npos)
197 if ((strCommand != "" || pcmd->category == "hidden") && strMethod != strCommand)
202 rpcfn_type pfn = pcmd->actor;
203 if (setDone.insert(pfn).second)
204 (*pfn)(params, true);
206 catch (const std::exception& e)
208 // Help text is returned in an exception
209 string strHelp = string(e.what());
210 if (strCommand == "")
212 if (strHelp.find('\n') != string::npos)
213 strHelp = strHelp.substr(0, strHelp.find('\n'));
215 if (category != pcmd->category)
217 if (!category.empty())
219 category = pcmd->category;
220 string firstLetter = category.substr(0,1);
221 boost::to_upper(firstLetter);
222 strRet += "== " + firstLetter + category.substr(1) + " ==\n";
225 strRet += strHelp + "\n";
229 strRet = strprintf("help: unknown command: %s\n", strCommand);
230 strRet = strRet.substr(0,strRet.size()-1);
234 Value help(const Array& params, bool fHelp)
236 if (fHelp || params.size() > 1)
238 "help ( \"command\" )\n"
239 "\nList all commands, or get help for a specified command.\n"
241 "1. \"command\" (string, optional) The command to get help on\n"
243 "\"text\" (string) The help text\n"
247 if (params.size() > 0)
248 strCommand = params[0].get_str();
250 return tableRPC.help(strCommand);
254 Value stop(const Array& params, bool fHelp)
256 // Accept the deprecated and ignored 'detach' boolean argument
257 if (fHelp || params.size() > 1)
260 "\nStop Zcash server.");
261 // Shutdown will take long enough that the response should get back
263 return "Zcash server stopping";
271 static const CRPCCommand vRPCCommands[] =
272 { // category name actor (function) okSafeMode
273 // --------------------- ------------------------ ----------------------- ----------
274 /* Overall control/query calls */
275 { "control", "getinfo", &getinfo, true }, /* uses wallet if enabled */
276 { "control", "help", &help, true },
277 { "control", "stop", &stop, true },
280 { "network", "getnetworkinfo", &getnetworkinfo, true },
281 { "network", "addnode", &addnode, true },
282 { "network", "getaddednodeinfo", &getaddednodeinfo, true },
283 { "network", "getconnectioncount", &getconnectioncount, true },
284 { "network", "getnettotals", &getnettotals, true },
285 { "network", "getpeerinfo", &getpeerinfo, true },
286 { "network", "ping", &ping, true },
288 /* Block chain and UTXO */
289 { "blockchain", "getblockchaininfo", &getblockchaininfo, true },
290 { "blockchain", "getbestblockhash", &getbestblockhash, true },
291 { "blockchain", "getblockcount", &getblockcount, true },
292 { "blockchain", "getblock", &getblock, true },
293 { "blockchain", "getblockhash", &getblockhash, true },
294 { "blockchain", "getchaintips", &getchaintips, true },
295 { "blockchain", "getdifficulty", &getdifficulty, true },
296 { "blockchain", "getmempoolinfo", &getmempoolinfo, true },
297 { "blockchain", "getrawmempool", &getrawmempool, true },
298 { "blockchain", "gettxout", &gettxout, true },
299 { "blockchain", "gettxoutproof", &gettxoutproof, true },
300 { "blockchain", "verifytxoutproof", &verifytxoutproof, true },
301 { "blockchain", "gettxoutsetinfo", &gettxoutsetinfo, true },
302 { "blockchain", "verifychain", &verifychain, true },
305 { "mining", "getblocktemplate", &getblocktemplate, true },
306 { "mining", "getmininginfo", &getmininginfo, true },
307 { "mining", "getnetworkhashps", &getnetworkhashps, true },
308 { "mining", "prioritisetransaction", &prioritisetransaction, true },
309 { "mining", "submitblock", &submitblock, true },
310 { "mining", "getblocksubsidy", &getblocksubsidy, true },
313 /* Coin generation */
314 { "generating", "getgenerate", &getgenerate, true },
315 { "generating", "setgenerate", &setgenerate, true },
316 { "generating", "generate", &generate, true },
319 /* Raw transactions */
320 { "rawtransactions", "createrawtransaction", &createrawtransaction, true },
321 { "rawtransactions", "decoderawtransaction", &decoderawtransaction, true },
322 { "rawtransactions", "decodescript", &decodescript, true },
323 { "rawtransactions", "getrawtransaction", &getrawtransaction, true },
324 { "rawtransactions", "sendrawtransaction", &sendrawtransaction, false },
325 { "rawtransactions", "signrawtransaction", &signrawtransaction, false }, /* uses wallet if enabled */
327 /* Utility functions */
328 { "util", "createmultisig", &createmultisig, true },
329 { "util", "validateaddress", &validateaddress, true }, /* uses wallet if enabled */
330 { "util", "verifymessage", &verifymessage, true },
331 { "util", "estimatefee", &estimatefee, true },
332 { "util", "estimatepriority", &estimatepriority, true },
334 /* Not shown in help */
335 { "hidden", "invalidateblock", &invalidateblock, true },
336 { "hidden", "reconsiderblock", &reconsiderblock, true },
337 { "hidden", "setmocktime", &setmocktime, true },
339 { "hidden", "resendwallettransactions", &resendwallettransactions, true},
344 { "wallet", "addmultisigaddress", &addmultisigaddress, true },
345 { "wallet", "backupwallet", &backupwallet, true },
346 { "wallet", "dumpprivkey", &dumpprivkey, true },
347 { "wallet", "dumpwallet", &dumpwallet, true },
348 { "wallet", "encryptwallet", &encryptwallet, true },
349 { "wallet", "getaccountaddress", &getaccountaddress, true },
350 { "wallet", "getaccount", &getaccount, true },
351 { "wallet", "getaddressesbyaccount", &getaddressesbyaccount, true },
352 { "wallet", "getbalance", &getbalance, false },
353 { "wallet", "getnewaddress", &getnewaddress, true },
354 { "wallet", "getrawchangeaddress", &getrawchangeaddress, true },
355 { "wallet", "getreceivedbyaccount", &getreceivedbyaccount, false },
356 { "wallet", "getreceivedbyaddress", &getreceivedbyaddress, false },
357 { "wallet", "gettransaction", &gettransaction, false },
358 { "wallet", "getunconfirmedbalance", &getunconfirmedbalance, false },
359 { "wallet", "getwalletinfo", &getwalletinfo, false },
360 { "wallet", "importprivkey", &importprivkey, true },
361 { "wallet", "importwallet", &importwallet, true },
362 { "wallet", "importaddress", &importaddress, true },
363 { "wallet", "keypoolrefill", &keypoolrefill, true },
364 { "wallet", "listaccounts", &listaccounts, false },
365 { "wallet", "listaddressgroupings", &listaddressgroupings, false },
366 { "wallet", "listlockunspent", &listlockunspent, false },
367 { "wallet", "listreceivedbyaccount", &listreceivedbyaccount, false },
368 { "wallet", "listreceivedbyaddress", &listreceivedbyaddress, false },
369 { "wallet", "listsinceblock", &listsinceblock, false },
370 { "wallet", "listtransactions", &listtransactions, false },
371 { "wallet", "listunspent", &listunspent, false },
372 { "wallet", "lockunspent", &lockunspent, true },
373 { "wallet", "move", &movecmd, false },
374 { "wallet", "sendfrom", &sendfrom, false },
375 { "wallet", "sendmany", &sendmany, false },
376 { "wallet", "sendtoaddress", &sendtoaddress, false },
377 { "wallet", "setaccount", &setaccount, true },
378 { "wallet", "settxfee", &settxfee, true },
379 { "wallet", "signmessage", &signmessage, true },
380 { "wallet", "walletlock", &walletlock, true },
381 { "wallet", "walletpassphrasechange", &walletpassphrasechange, true },
382 { "wallet", "walletpassphrase", &walletpassphrase, true },
383 { "wallet", "zcbenchmark", &zc_benchmark, true },
384 { "wallet", "zcrawkeygen", &zc_raw_keygen, true },
385 { "wallet", "zcrawjoinsplit", &zc_raw_joinsplit, true },
386 { "wallet", "zcrawreceive", &zc_raw_receive, true },
387 { "wallet", "zcsamplejoinsplit", &zc_sample_joinsplit, true },
388 { "wallet", "z_listreceivedbyaddress",&z_listreceivedbyaddress,false },
389 { "wallet", "z_getbalance", &z_getbalance, false },
390 { "wallet", "z_gettotalbalance", &z_gettotalbalance, false },
391 { "wallet", "z_sendmany", &z_sendmany, false },
392 { "wallet", "z_getoperationstatus", &z_getoperationstatus, true },
393 { "wallet", "z_getoperationresult", &z_getoperationresult, true },
394 { "wallet", "z_listoperationids", &z_listoperationids, true },
395 { "wallet", "z_getnewaddress", &z_getnewaddress, true },
396 { "wallet", "z_listaddresses", &z_listaddresses, true },
397 { "wallet", "z_exportkey", &z_exportkey, true },
398 { "wallet", "z_importkey", &z_importkey, true },
399 { "wallet", "z_exportwallet", &z_exportwallet, true },
400 { "wallet", "z_importwallet", &z_importwallet, true }
401 #endif // ENABLE_WALLET
404 CRPCTable::CRPCTable()
407 for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++)
409 const CRPCCommand *pcmd;
411 pcmd = &vRPCCommands[vcidx];
412 mapCommands[pcmd->name] = pcmd;
416 const CRPCCommand *CRPCTable::operator[](string name) const
418 map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
419 if (it == mapCommands.end())
425 bool HTTPAuthorized(map<string, string>& mapHeaders)
427 string strAuth = mapHeaders["authorization"];
428 if (strAuth.substr(0,6) != "Basic ")
430 string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
431 string strUserPass = DecodeBase64(strUserPass64);
432 return TimingResistantEqual(strUserPass, strRPCUserColonPass);
435 void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
437 // Send error reply from json-rpc error object
438 int nStatus = HTTP_INTERNAL_SERVER_ERROR;
439 int code = find_value(objError, "code").get_int();
440 if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST;
441 else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND;
442 string strReply = JSONRPCReply(Value::null, objError, id);
443 stream << HTTPReply(nStatus, strReply, false) << std::flush;
446 CNetAddr BoostAsioToCNetAddr(boost::asio::ip::address address)
449 // Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses
451 && (address.to_v6().is_v4_compatible()
452 || address.to_v6().is_v4_mapped()))
453 address = address.to_v6().to_v4();
457 boost::asio::ip::address_v4::bytes_type bytes = address.to_v4().to_bytes();
458 netaddr.SetRaw(NET_IPV4, &bytes[0]);
462 boost::asio::ip::address_v6::bytes_type bytes = address.to_v6().to_bytes();
463 netaddr.SetRaw(NET_IPV6, &bytes[0]);
468 bool ClientAllowed(const boost::asio::ip::address& address)
470 CNetAddr netaddr = BoostAsioToCNetAddr(address);
471 BOOST_FOREACH(const CSubNet &subnet, rpc_allow_subnets)
472 if (subnet.Match(netaddr))
477 template <typename Protocol>
478 class AcceptedConnectionImpl : public AcceptedConnection
481 AcceptedConnectionImpl(
482 boost::asio::io_service& io_service,
483 ssl::context &context,
485 sslStream(io_service, context),
486 _d(sslStream, fUseSSL),
491 virtual std::iostream& stream()
496 virtual std::string peer_address_to_string() const
498 return peer.address().to_string();
506 typename Protocol::endpoint peer;
507 boost::asio::ssl::stream<typename Protocol::socket> sslStream;
510 SSLIOStreamDevice<Protocol> _d;
511 boost::iostreams::stream< SSLIOStreamDevice<Protocol> > _stream;
514 void ServiceConnection(AcceptedConnection *conn);
516 //! Forward declaration required for RPCListen
517 template <typename Protocol, typename SocketAcceptorService>
518 static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
519 ssl::context& context,
521 boost::shared_ptr< AcceptedConnection > conn,
522 const boost::system::error_code& error);
525 * Sets up I/O resources to accept and handle a new connection.
527 template <typename Protocol, typename SocketAcceptorService>
528 static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
529 ssl::context& context,
533 boost::shared_ptr< AcceptedConnectionImpl<Protocol> > conn(new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL));
535 acceptor->async_accept(
536 conn->sslStream.lowest_layer(),
538 boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>,
548 * Accept and handle incoming connection.
550 template <typename Protocol, typename SocketAcceptorService>
551 static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
552 ssl::context& context,
554 boost::shared_ptr< AcceptedConnection > conn,
555 const boost::system::error_code& error)
557 // Immediately start accepting new connections, except when we're cancelled or our socket is closed.
558 if (error != boost::asio::error::operation_aborted && acceptor->is_open())
559 RPCListen(acceptor, context, fUseSSL);
561 AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn.get());
565 // TODO: Actually handle errors
566 LogPrintf("%s: Error: %s\n", __func__, error.message());
568 // Restrict callers by IP. It is important to
569 // do this before starting client thread, to filter out
570 // certain DoS and misbehaving clients.
571 else if (tcp_conn && !ClientAllowed(tcp_conn->peer.address()))
573 // Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake.
575 conn->stream() << HTTPError(HTTP_FORBIDDEN, false) << std::flush;
579 ServiceConnection(conn.get());
584 static ip::tcp::endpoint ParseEndpoint(const std::string &strEndpoint, int defaultPort)
587 int port = defaultPort;
588 SplitHostPort(strEndpoint, port, addr);
589 return ip::tcp::endpoint(boost::asio::ip::address::from_string(addr), port);
592 void StartRPCThreads()
594 rpc_allow_subnets.clear();
595 rpc_allow_subnets.push_back(CSubNet("127.0.0.0/8")); // always allow IPv4 local subnet
596 rpc_allow_subnets.push_back(CSubNet("::1")); // always allow IPv6 localhost
597 if (mapMultiArgs.count("-rpcallowip"))
599 const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
600 BOOST_FOREACH(string strAllow, vAllow)
602 CSubNet subnet(strAllow);
603 if(!subnet.IsValid())
605 uiInterface.ThreadSafeMessageBox(
606 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),
607 "", CClientUIInterface::MSG_ERROR);
611 rpc_allow_subnets.push_back(subnet);
614 std::string strAllowed;
615 BOOST_FOREACH(const CSubNet &subnet, rpc_allow_subnets)
616 strAllowed += subnet.ToString() + " ";
617 LogPrint("rpc", "Allowing RPC connections from: %s\n", strAllowed);
619 strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
620 if (((mapArgs["-rpcpassword"] == "") ||
621 (mapArgs["-rpcuser"] == mapArgs["-rpcpassword"])) && Params().RequireRPCPassword())
623 unsigned char rand_pwd[32];
624 GetRandBytes(rand_pwd, 32);
625 uiInterface.ThreadSafeMessageBox(strprintf(
626 _("To use zcashd you must set an rpcpassword in the configuration file:\n"
628 "It is recommended you use the following random password:\n"
631 "(you do not need to remember this password)\n"
632 "The username and password MUST NOT be the same.\n"
633 "If the file does not exist, create it with owner-readable-only file permissions.\n"
634 "It is also recommended to set alertnotify so you are notified of problems;\n"
636 GetConfigFile().string(),
637 EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32)),
638 "", CClientUIInterface::MSG_ERROR | CClientUIInterface::SECURE);
643 assert(rpc_io_service == NULL);
644 rpc_io_service = new boost::asio::io_service();
645 rpc_ssl_context = new ssl::context(*rpc_io_service, ssl::context::sslv23);
647 const bool fUseSSL = GetBoolArg("-rpcssl", false);
651 rpc_ssl_context->set_options(ssl::context::no_sslv2 | ssl::context::no_sslv3);
653 boost::filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert"));
654 if (!pathCertFile.is_complete()) pathCertFile = boost::filesystem::path(GetDataDir()) / pathCertFile;
655 if (boost::filesystem::exists(pathCertFile)) rpc_ssl_context->use_certificate_chain_file(pathCertFile.string());
656 else LogPrintf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string());
658 boost::filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem"));
659 if (!pathPKFile.is_complete()) pathPKFile = boost::filesystem::path(GetDataDir()) / pathPKFile;
660 if (boost::filesystem::exists(pathPKFile)) rpc_ssl_context->use_private_key_file(pathPKFile.string(), ssl::context::pem);
661 else LogPrintf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string());
663 string strCiphers = GetArg("-rpcsslciphers", "TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH");
664 SSL_CTX_set_cipher_list(rpc_ssl_context->impl(), strCiphers.c_str());
667 std::vector<ip::tcp::endpoint> vEndpoints;
668 bool bBindAny = false;
669 int defaultPort = GetArg("-rpcport", BaseParams().RPCPort());
670 if (!mapArgs.count("-rpcallowip")) // Default to loopback if not allowing external IPs
672 vEndpoints.push_back(ip::tcp::endpoint(boost::asio::ip::address_v6::loopback(), defaultPort));
673 vEndpoints.push_back(ip::tcp::endpoint(boost::asio::ip::address_v4::loopback(), defaultPort));
674 if (mapArgs.count("-rpcbind"))
676 LogPrintf("WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n");
678 } else if (mapArgs.count("-rpcbind")) // Specific bind address
680 BOOST_FOREACH(const std::string &addr, mapMultiArgs["-rpcbind"])
683 vEndpoints.push_back(ParseEndpoint(addr, defaultPort));
685 catch (const boost::system::system_error&)
687 uiInterface.ThreadSafeMessageBox(
688 strprintf(_("Could not parse -rpcbind value %s as network address"), addr),
689 "", CClientUIInterface::MSG_ERROR);
694 } else { // No specific bind address specified, bind to any
695 vEndpoints.push_back(ip::tcp::endpoint(boost::asio::ip::address_v6::any(), defaultPort));
696 vEndpoints.push_back(ip::tcp::endpoint(boost::asio::ip::address_v4::any(), defaultPort));
697 // Prefer making the socket dual IPv6/IPv4 instead of binding
698 // to both addresses separately.
702 bool fListening = false;
704 std::string straddress;
705 BOOST_FOREACH(const ip::tcp::endpoint &endpoint, vEndpoints)
708 boost::asio::ip::address bindAddress = endpoint.address();
709 straddress = bindAddress.to_string();
710 LogPrintf("Binding RPC on address %s port %i (IPv4+IPv6 bind any: %i)\n", straddress, endpoint.port(), bBindAny);
711 boost::system::error_code v6_only_error;
712 boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(*rpc_io_service));
714 acceptor->open(endpoint.protocol());
715 acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
717 // Try making the socket dual IPv6/IPv4 when listening on the IPv6 "any" address
718 acceptor->set_option(boost::asio::ip::v6_only(
719 !bBindAny || bindAddress != boost::asio::ip::address_v6::any()), v6_only_error);
721 acceptor->bind(endpoint);
722 acceptor->listen(socket_base::max_connections);
724 RPCListen(acceptor, *rpc_ssl_context, fUseSSL);
727 rpc_acceptors.push_back(acceptor);
728 // If dual IPv6/IPv4 bind successful, skip binding to IPv4 separately
729 if(bBindAny && bindAddress == boost::asio::ip::address_v6::any() && !v6_only_error)
732 catch (const boost::system::system_error& e)
734 LogPrintf("ERROR: Binding RPC on address %s port %i failed: %s\n", straddress, endpoint.port(), e.what());
735 strerr = strprintf(_("An error occurred while setting up the RPC address %s port %u for listening: %s"), straddress, endpoint.port(), e.what());
740 uiInterface.ThreadSafeMessageBox(strerr, "", CClientUIInterface::MSG_ERROR);
745 rpc_worker_group = new boost::thread_group();
746 for (int i = 0; i < GetArg("-rpcthreads", 4); i++)
747 rpc_worker_group->create_thread(boost::bind(&boost::asio::io_service::run, rpc_io_service));
749 g_rpcSignals.Started();
751 // Launch one async rpc worker. The ability to launch multiple workers is not recommended at present and thus the option is disabled.
752 getAsyncRPCQueue()->addWorker();
754 int n = GetArg("-rpcasyncthreads", 1);
756 LogPrintf("ERROR: Invalid value %d for -rpcasyncthreads. Must be at least 1.\n", n);
757 strerr = strprintf(_("An error occurred while setting up the Async RPC threads, invalid parameter value of %d (must be at least 1)."), n);
758 uiInterface.ThreadSafeMessageBox(strerr, "", CClientUIInterface::MSG_ERROR);
762 for (int i = 0; i < n; i++)
763 getAsyncRPCQueue()->addWorker();
767 void StartDummyRPCThread()
769 if(rpc_io_service == NULL)
771 rpc_io_service = new boost::asio::io_service();
772 /* Create dummy "work" to keep the thread from exiting when no timeouts active,
773 * see http://www.boost.org/doc/libs/1_51_0/doc/html/boost_asio/reference/io_service.html#boost_asio.reference.io_service.stopping_the_io_service_from_running_out_of_work */
774 rpc_dummy_work = new boost::asio::io_service::work(*rpc_io_service);
775 rpc_worker_group = new boost::thread_group();
776 rpc_worker_group->create_thread(boost::bind(&boost::asio::io_service::run, rpc_io_service));
781 void StopRPCThreads()
783 if (rpc_io_service == NULL) return;
784 // Set this to false first, so that longpolling loops will exit when woken up
787 // First, cancel all timers and acceptors
788 // This is not done automatically by ->stop(), and in some cases the destructor of
789 // boost::asio::io_service can hang if this is skipped.
790 boost::system::error_code ec;
791 BOOST_FOREACH(const boost::shared_ptr<ip::tcp::acceptor> &acceptor, rpc_acceptors)
793 acceptor->cancel(ec);
795 LogPrintf("%s: Warning: %s when cancelling acceptor\n", __func__, ec.message());
797 rpc_acceptors.clear();
798 BOOST_FOREACH(const PAIRTYPE(std::string, boost::shared_ptr<deadline_timer>) &timer, deadlineTimers)
800 timer.second->cancel(ec);
802 LogPrintf("%s: Warning: %s when cancelling timer\n", __func__, ec.message());
804 deadlineTimers.clear();
806 rpc_io_service->stop();
807 g_rpcSignals.Stopped();
808 if (rpc_worker_group != NULL)
809 rpc_worker_group->join_all();
810 delete rpc_dummy_work; rpc_dummy_work = NULL;
811 delete rpc_worker_group; rpc_worker_group = NULL;
812 delete rpc_ssl_context; rpc_ssl_context = NULL;
813 delete rpc_io_service; rpc_io_service = NULL;
815 // Tells async queue to cancel all operations and shutdown.
816 LogPrintf("%s: waiting for async rpc workers to stop\n", __func__);
817 getAsyncRPCQueue()->closeAndWait();
825 void SetRPCWarmupStatus(const std::string& newStatus)
828 rpcWarmupStatus = newStatus;
831 void SetRPCWarmupFinished()
834 assert(fRPCInWarmup);
835 fRPCInWarmup = false;
838 bool RPCIsInWarmup(std::string *outStatus)
842 *outStatus = rpcWarmupStatus;
846 void RPCRunHandler(const boost::system::error_code& err, boost::function<void(void)> func)
852 void RPCRunLater(const std::string& name, boost::function<void(void)> func, int64_t nSeconds)
854 assert(rpc_io_service != NULL);
856 if (deadlineTimers.count(name) == 0)
858 deadlineTimers.insert(make_pair(name,
859 boost::shared_ptr<deadline_timer>(new deadline_timer(*rpc_io_service))));
861 deadlineTimers[name]->expires_from_now(boost::posix_time::seconds(nSeconds));
862 deadlineTimers[name]->async_wait(boost::bind(RPCRunHandler, _1, func));
872 JSONRequest() { id = Value::null; }
873 void parse(const Value& valRequest);
876 void JSONRequest::parse(const Value& valRequest)
879 if (valRequest.type() != obj_type)
880 throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
881 const Object& request = valRequest.get_obj();
883 // Parse id now so errors from here on will have the id
884 id = find_value(request, "id");
887 Value valMethod = find_value(request, "method");
888 if (valMethod.type() == null_type)
889 throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
890 if (valMethod.type() != str_type)
891 throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
892 strMethod = valMethod.get_str();
893 if (strMethod != "getblocktemplate")
894 LogPrint("rpc", "ThreadRPCServer method=%s\n", SanitizeString(strMethod));
897 Value valParams = find_value(request, "params");
898 if (valParams.type() == array_type)
899 params = valParams.get_array();
900 else if (valParams.type() == null_type)
903 throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array");
907 static Object JSONRPCExecOne(const Value& req)
915 Value result = tableRPC.execute(jreq.strMethod, jreq.params);
916 rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id);
918 catch (const Object& objError)
920 rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id);
922 catch (const std::exception& e)
924 rpc_result = JSONRPCReplyObj(Value::null,
925 JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
931 static string JSONRPCExecBatch(const Array& vReq)
934 for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
935 ret.push_back(JSONRPCExecOne(vReq[reqIdx]));
937 return write_string(Value(ret), false) + "\n";
940 static bool HTTPReq_JSONRPC(AcceptedConnection *conn,
942 map<string, string>& mapHeaders,
945 // Check authorization
946 if (mapHeaders.count("authorization") == 0)
948 conn->stream() << HTTPError(HTTP_UNAUTHORIZED, false) << std::flush;
952 if (!HTTPAuthorized(mapHeaders))
954 LogPrintf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string());
955 /* Deter brute-forcing
956 We don't support exposing the RPC port, so this shouldn't result
960 conn->stream() << HTTPError(HTTP_UNAUTHORIZED, false) << std::flush;
969 if (!read_string(strRequest, valRequest))
970 throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
972 // Return immediately if in warmup
976 throw JSONRPCError(RPC_IN_WARMUP, rpcWarmupStatus);
982 if (valRequest.type() == obj_type) {
983 jreq.parse(valRequest);
985 Value result = tableRPC.execute(jreq.strMethod, jreq.params);
988 strReply = JSONRPCReply(result, Value::null, jreq.id);
991 } else if (valRequest.type() == array_type)
992 strReply = JSONRPCExecBatch(valRequest.get_array());
994 throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
996 conn->stream() << HTTPReplyHeader(HTTP_OK, fRun, strReply.size()) << strReply << std::flush;
998 catch (const Object& objError)
1000 ErrorReply(conn->stream(), objError, jreq.id);
1003 catch (const std::exception& e)
1005 ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
1011 void ServiceConnection(AcceptedConnection *conn)
1014 while (fRun && !ShutdownRequested())
1017 map<string, string> mapHeaders;
1018 string strRequest, strMethod, strURI;
1020 // Read HTTP request line
1021 if (!ReadHTTPRequestLine(conn->stream(), nProto, strMethod, strURI))
1024 // Read HTTP message headers and body
1025 ReadHTTPMessage(conn->stream(), mapHeaders, strRequest, nProto, MAX_SIZE);
1027 // HTTP Keep-Alive is false; close connection immediately
1028 if ((mapHeaders["connection"] == "close") || (!GetBoolArg("-rpckeepalive", true)))
1031 // Process via JSON-RPC API
1032 if (strURI == "/") {
1033 if (!HTTPReq_JSONRPC(conn, strRequest, mapHeaders, fRun))
1036 // Process via HTTP REST API
1037 } else if (strURI.substr(0, 6) == "/rest/" && GetBoolArg("-rest", false)) {
1038 if (!HTTPReq_REST(conn, strURI, strRequest, mapHeaders, fRun))
1042 conn->stream() << HTTPError(HTTP_NOT_FOUND, false) << std::flush;
1048 json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array ¶ms) const
1051 const CRPCCommand *pcmd = tableRPC[strMethod];
1053 throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
1055 g_rpcSignals.PreCommand(*pcmd);
1060 return pcmd->actor(params, false);
1062 catch (const std::exception& e)
1064 throw JSONRPCError(RPC_MISC_ERROR, e.what());
1067 g_rpcSignals.PostCommand(*pcmd);
1070 std::string HelpExampleCli(string methodname, string args){
1071 return "> zcash-cli " + methodname + " " + args + "\n";
1074 std::string HelpExampleRpc(string methodname, string args){
1075 return "> curl --user myusername --data-binary '{\"jsonrpc\": \"1.0\", \"id\":\"curltest\", "
1076 "\"method\": \"" + methodname + "\", \"params\": [" + args + "] }' -H 'content-type: text/plain;' http://127.0.0.1:8232/\n";
1079 const CRPCTable tableRPC;
1081 // Return async rpc queue
1082 std::shared_ptr<AsyncRPCQueue> getAsyncRPCQueue()
1084 return AsyncRPCQueue::sharedInstance();