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.
6 #include "chainparams.h"
10 #include "ui_interface.h"
12 #include "bitcoinrpc.h"
15 #include <boost/algorithm/string.hpp>
16 #include <boost/asio.hpp>
17 #include <boost/asio/ip/v6_only.hpp>
18 #include <boost/asio/ssl.hpp>
19 #include <boost/bind.hpp>
20 #include <boost/filesystem.hpp>
21 #include <boost/filesystem/fstream.hpp>
22 #include <boost/foreach.hpp>
23 #include <boost/iostreams/concepts.hpp>
24 #include <boost/iostreams/stream.hpp>
25 #include <boost/lexical_cast.hpp>
26 #include <boost/shared_ptr.hpp>
30 using namespace boost;
31 using namespace boost::asio;
32 using namespace json_spirit;
34 static std::string strRPCUserColonPass;
36 // These are created by StartRPCThreads, destroyed in StopRPCThreads
37 static asio::io_service* rpc_io_service = NULL;
38 static map<string, boost::shared_ptr<deadline_timer> > deadlineTimers;
39 static ssl::context* rpc_ssl_context = NULL;
40 static boost::thread_group* rpc_worker_group = NULL;
42 Object JSONRPCError(int code, const string& message)
45 error.push_back(Pair("code", code));
46 error.push_back(Pair("message", message));
50 void RPCTypeCheck(const Array& params,
51 const list<Value_type>& typesExpected,
55 BOOST_FOREACH(Value_type t, typesExpected)
57 if (params.size() <= i)
60 const Value& v = params[i];
61 if (!((v.type() == t) || (fAllowNull && (v.type() == null_type))))
63 string err = strprintf("Expected type %s, got %s",
64 Value_type_name[t], Value_type_name[v.type()]);
65 throw JSONRPCError(RPC_TYPE_ERROR, err);
71 void RPCTypeCheck(const Object& o,
72 const map<string, Value_type>& typesExpected,
75 BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected)
77 const Value& v = find_value(o, t.first);
78 if (!fAllowNull && v.type() == null_type)
79 throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first.c_str()));
81 if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type))))
83 string err = strprintf("Expected type %s for %s, got %s",
84 Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]);
85 throw JSONRPCError(RPC_TYPE_ERROR, err);
90 int64 AmountFromValue(const Value& value)
92 double dAmount = value.get_real();
93 if (dAmount <= 0.0 || dAmount > 21000000.0)
94 throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
95 int64 nAmount = roundint64(dAmount * COIN);
96 if (!MoneyRange(nAmount))
97 throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
101 Value ValueFromAmount(int64 amount)
103 return (double)amount / (double)COIN;
106 std::string HexBits(unsigned int nBits)
112 uBits.nBits = htonl((int32_t)nBits);
113 return HexStr(BEGIN(uBits.cBits), END(uBits.cBits));
119 /// Note: This interface may still be subject to change.
122 string CRPCTable::help(string strCommand) const
125 set<rpcfn_type> setDone;
126 for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)
128 const CRPCCommand *pcmd = mi->second;
129 string strMethod = mi->first;
130 // We already filter duplicates, but these deprecated screw up the sort order
131 if (strMethod.find("label") != string::npos)
133 if (strCommand != "" && strMethod != strCommand)
138 rpcfn_type pfn = pcmd->actor;
139 if (setDone.insert(pfn).second)
140 (*pfn)(params, true);
142 catch (std::exception& e)
144 // Help text is returned in an exception
145 string strHelp = string(e.what());
146 if (strCommand == "")
147 if (strHelp.find('\n') != string::npos)
148 strHelp = strHelp.substr(0, strHelp.find('\n'));
149 strRet += strHelp + "\n";
153 strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
154 strRet = strRet.substr(0,strRet.size()-1);
158 Value help(const Array& params, bool fHelp)
160 if (fHelp || params.size() > 1)
163 "List commands, or get help for a command.");
166 if (params.size() > 0)
167 strCommand = params[0].get_str();
169 return tableRPC.help(strCommand);
173 Value stop(const Array& params, bool fHelp)
175 // Accept the deprecated and ignored 'detach' boolean argument
176 if (fHelp || params.size() > 1)
179 "Stop Bitcoin server.");
180 // Shutdown will take long enough that the response should get back
182 return "Bitcoin server stopping";
192 static const CRPCCommand vRPCCommands[] =
193 { // name actor (function) okSafeMode threadSafe
194 // ------------------------ ----------------------- ---------- ----------
195 { "help", &help, true, true },
196 { "stop", &stop, true, true },
197 { "getblockcount", &getblockcount, true, false },
198 { "getconnectioncount", &getconnectioncount, true, false },
199 { "getpeerinfo", &getpeerinfo, true, false },
200 { "addnode", &addnode, true, true },
201 { "getaddednodeinfo", &getaddednodeinfo, true, true },
202 { "getdifficulty", &getdifficulty, true, false },
203 { "getgenerate", &getgenerate, true, false },
204 { "setgenerate", &setgenerate, true, false },
205 { "gethashespersec", &gethashespersec, true, false },
206 { "getinfo", &getinfo, true, false },
207 { "getmininginfo", &getmininginfo, true, false },
208 { "getnewaddress", &getnewaddress, true, false },
209 { "getaccountaddress", &getaccountaddress, true, false },
210 { "setaccount", &setaccount, true, false },
211 { "getaccount", &getaccount, false, false },
212 { "getaddressesbyaccount", &getaddressesbyaccount, true, false },
213 { "sendtoaddress", &sendtoaddress, false, false },
214 { "getreceivedbyaddress", &getreceivedbyaddress, false, false },
215 { "getreceivedbyaccount", &getreceivedbyaccount, false, false },
216 { "listreceivedbyaddress", &listreceivedbyaddress, false, false },
217 { "listreceivedbyaccount", &listreceivedbyaccount, false, false },
218 { "backupwallet", &backupwallet, true, false },
219 { "keypoolrefill", &keypoolrefill, true, false },
220 { "walletpassphrase", &walletpassphrase, true, false },
221 { "walletpassphrasechange", &walletpassphrasechange, false, false },
222 { "walletlock", &walletlock, true, false },
223 { "encryptwallet", &encryptwallet, false, false },
224 { "validateaddress", &validateaddress, true, false },
225 { "getbalance", &getbalance, false, false },
226 { "move", &movecmd, false, false },
227 { "sendfrom", &sendfrom, false, false },
228 { "sendmany", &sendmany, false, false },
229 { "addmultisigaddress", &addmultisigaddress, false, false },
230 { "createmultisig", &createmultisig, true, true },
231 { "getrawmempool", &getrawmempool, true, false },
232 { "getblock", &getblock, false, false },
233 { "getblockhash", &getblockhash, false, false },
234 { "gettransaction", &gettransaction, false, false },
235 { "listtransactions", &listtransactions, false, false },
236 { "listaddressgroupings", &listaddressgroupings, false, false },
237 { "signmessage", &signmessage, false, false },
238 { "verifymessage", &verifymessage, false, false },
239 { "getwork", &getwork, true, false },
240 { "listaccounts", &listaccounts, false, false },
241 { "settxfee", &settxfee, false, false },
242 { "getblocktemplate", &getblocktemplate, true, false },
243 { "submitblock", &submitblock, false, false },
244 { "listsinceblock", &listsinceblock, false, false },
245 { "dumpprivkey", &dumpprivkey, true, false },
246 { "dumpwallet", &dumpwallet, true, false },
247 { "importprivkey", &importprivkey, false, false },
248 { "importwallet", &importwallet, false, false },
249 { "listunspent", &listunspent, false, false },
250 { "getrawtransaction", &getrawtransaction, false, false },
251 { "createrawtransaction", &createrawtransaction, false, false },
252 { "decoderawtransaction", &decoderawtransaction, false, false },
253 { "signrawtransaction", &signrawtransaction, false, false },
254 { "sendrawtransaction", &sendrawtransaction, false, false },
255 { "gettxoutsetinfo", &gettxoutsetinfo, true, false },
256 { "gettxout", &gettxout, true, false },
257 { "lockunspent", &lockunspent, false, false },
258 { "listlockunspent", &listlockunspent, false, false },
259 { "verifychain", &verifychain, true, false },
262 CRPCTable::CRPCTable()
265 for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++)
267 const CRPCCommand *pcmd;
269 pcmd = &vRPCCommands[vcidx];
270 mapCommands[pcmd->name] = pcmd;
274 const CRPCCommand *CRPCTable::operator[](string name) const
276 map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
277 if (it == mapCommands.end())
285 // This ain't Apache. We're just using HTTP header for the length field
286 // and to be compatible with other JSON-RPC implementations.
289 string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
292 s << "POST / HTTP/1.1\r\n"
293 << "User-Agent: bitcoin-json-rpc/" << FormatFullVersion() << "\r\n"
294 << "Host: 127.0.0.1\r\n"
295 << "Content-Type: application/json\r\n"
296 << "Content-Length: " << strMsg.size() << "\r\n"
297 << "Connection: close\r\n"
298 << "Accept: application/json\r\n";
299 BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders)
300 s << item.first << ": " << item.second << "\r\n";
301 s << "\r\n" << strMsg;
311 struct tm* now_gmt = gmtime(&now);
312 string locale(setlocale(LC_TIME, NULL));
313 setlocale(LC_TIME, "C"); // we want POSIX (aka "C") weekday/month strings
314 strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt);
315 setlocale(LC_TIME, locale.c_str());
316 return string(buffer);
319 static string HTTPReply(int nStatus, const string& strMsg, bool keepalive)
321 if (nStatus == HTTP_UNAUTHORIZED)
322 return strprintf("HTTP/1.0 401 Authorization Required\r\n"
324 "Server: bitcoin-json-rpc/%s\r\n"
325 "WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
326 "Content-Type: text/html\r\n"
327 "Content-Length: 296\r\n"
329 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
330 "\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
333 "<TITLE>Error</TITLE>\r\n"
334 "<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
336 "<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
337 "</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str());
339 if (nStatus == HTTP_OK) cStatus = "OK";
340 else if (nStatus == HTTP_BAD_REQUEST) cStatus = "Bad Request";
341 else if (nStatus == HTTP_FORBIDDEN) cStatus = "Forbidden";
342 else if (nStatus == HTTP_NOT_FOUND) cStatus = "Not Found";
343 else if (nStatus == HTTP_INTERNAL_SERVER_ERROR) cStatus = "Internal Server Error";
349 "Content-Length: %"PRIszu"\r\n"
350 "Content-Type: application/json\r\n"
351 "Server: bitcoin-json-rpc/%s\r\n"
356 rfc1123Time().c_str(),
357 keepalive ? "keep-alive" : "close",
359 FormatFullVersion().c_str(),
363 bool ReadHTTPRequestLine(std::basic_istream<char>& stream, int &proto,
364 string& http_method, string& http_uri)
367 getline(stream, str);
369 // HTTP request line is space-delimited
370 vector<string> vWords;
371 boost::split(vWords, str, boost::is_any_of(" "));
372 if (vWords.size() < 2)
375 // HTTP methods permitted: GET, POST
376 http_method = vWords[0];
377 if (http_method != "GET" && http_method != "POST")
380 // HTTP URI must be an absolute path, relative to current host
381 http_uri = vWords[1];
382 if (http_uri.size() == 0 || http_uri[0] != '/')
385 // parse proto, if present
386 string strProto = "";
387 if (vWords.size() > 2)
388 strProto = vWords[2];
391 const char *ver = strstr(strProto.c_str(), "HTTP/1.");
398 int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto)
401 getline(stream, str);
402 vector<string> vWords;
403 boost::split(vWords, str, boost::is_any_of(" "));
404 if (vWords.size() < 2)
405 return HTTP_INTERNAL_SERVER_ERROR;
407 const char *ver = strstr(str.c_str(), "HTTP/1.");
410 return atoi(vWords[1].c_str());
413 int ReadHTTPHeaders(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
419 std::getline(stream, str);
420 if (str.empty() || str == "\r")
422 string::size_type nColon = str.find(":");
423 if (nColon != string::npos)
425 string strHeader = str.substr(0, nColon);
426 boost::trim(strHeader);
427 boost::to_lower(strHeader);
428 string strValue = str.substr(nColon+1);
429 boost::trim(strValue);
430 mapHeadersRet[strHeader] = strValue;
431 if (strHeader == "content-length")
432 nLen = atoi(strValue.c_str());
438 int ReadHTTPMessage(std::basic_istream<char>& stream, map<string,
439 string>& mapHeadersRet, string& strMessageRet,
442 mapHeadersRet.clear();
446 int nLen = ReadHTTPHeaders(stream, mapHeadersRet);
447 if (nLen < 0 || nLen > (int)MAX_SIZE)
448 return HTTP_INTERNAL_SERVER_ERROR;
453 vector<char> vch(nLen);
454 stream.read(&vch[0], nLen);
455 strMessageRet = string(vch.begin(), vch.end());
458 string sConHdr = mapHeadersRet["connection"];
460 if ((sConHdr != "close") && (sConHdr != "keep-alive"))
463 mapHeadersRet["connection"] = "keep-alive";
465 mapHeadersRet["connection"] = "close";
471 bool HTTPAuthorized(map<string, string>& mapHeaders)
473 string strAuth = mapHeaders["authorization"];
474 if (strAuth.substr(0,6) != "Basic ")
476 string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
477 string strUserPass = DecodeBase64(strUserPass64);
478 return strUserPass == strRPCUserColonPass;
482 // JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
483 // but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
484 // unspecified (HTTP errors and contents of 'error').
486 // 1.0 spec: http://json-rpc.org/wiki/specification
487 // 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
488 // http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
491 string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
494 request.push_back(Pair("method", strMethod));
495 request.push_back(Pair("params", params));
496 request.push_back(Pair("id", id));
497 return write_string(Value(request), false) + "\n";
500 Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id)
503 if (error.type() != null_type)
504 reply.push_back(Pair("result", Value::null));
506 reply.push_back(Pair("result", result));
507 reply.push_back(Pair("error", error));
508 reply.push_back(Pair("id", id));
512 string JSONRPCReply(const Value& result, const Value& error, const Value& id)
514 Object reply = JSONRPCReplyObj(result, error, id);
515 return write_string(Value(reply), false) + "\n";
518 void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
520 // Send error reply from json-rpc error object
521 int nStatus = HTTP_INTERNAL_SERVER_ERROR;
522 int code = find_value(objError, "code").get_int();
523 if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST;
524 else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND;
525 string strReply = JSONRPCReply(Value::null, objError, id);
526 stream << HTTPReply(nStatus, strReply, false) << std::flush;
529 bool ClientAllowed(const boost::asio::ip::address& address)
531 // Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses
533 && (address.to_v6().is_v4_compatible()
534 || address.to_v6().is_v4_mapped()))
535 return ClientAllowed(address.to_v6().to_v4());
537 if (address == asio::ip::address_v4::loopback()
538 || address == asio::ip::address_v6::loopback()
540 // Check whether IPv4 addresses match 127.0.0.0/8 (loopback subnet)
541 && (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000))
544 const string strAddress = address.to_string();
545 const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
546 BOOST_FOREACH(string strAllow, vAllow)
547 if (WildcardMatch(strAddress, strAllow))
553 // IOStream device that speaks SSL but can also speak non-SSL
555 template <typename Protocol>
556 class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {
558 SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn)
561 fNeedHandshake = fUseSSLIn;
564 void handshake(ssl::stream_base::handshake_type role)
566 if (!fNeedHandshake) return;
567 fNeedHandshake = false;
568 stream.handshake(role);
570 std::streamsize read(char* s, std::streamsize n)
572 handshake(ssl::stream_base::server); // HTTPS servers read first
573 if (fUseSSL) return stream.read_some(asio::buffer(s, n));
574 return stream.next_layer().read_some(asio::buffer(s, n));
576 std::streamsize write(const char* s, std::streamsize n)
578 handshake(ssl::stream_base::client); // HTTPS clients write first
579 if (fUseSSL) return asio::write(stream, asio::buffer(s, n));
580 return asio::write(stream.next_layer(), asio::buffer(s, n));
582 bool connect(const std::string& server, const std::string& port)
584 ip::tcp::resolver resolver(stream.get_io_service());
585 ip::tcp::resolver::query query(server.c_str(), port.c_str());
586 ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
587 ip::tcp::resolver::iterator end;
588 boost::system::error_code error = asio::error::host_not_found;
589 while (error && endpoint_iterator != end)
591 stream.lowest_layer().close();
592 stream.lowest_layer().connect(*endpoint_iterator++, error);
602 asio::ssl::stream<typename Protocol::socket>& stream;
605 class AcceptedConnection
608 virtual ~AcceptedConnection() {}
610 virtual std::iostream& stream() = 0;
611 virtual std::string peer_address_to_string() const = 0;
612 virtual void close() = 0;
615 template <typename Protocol>
616 class AcceptedConnectionImpl : public AcceptedConnection
619 AcceptedConnectionImpl(
620 asio::io_service& io_service,
621 ssl::context &context,
623 sslStream(io_service, context),
624 _d(sslStream, fUseSSL),
629 virtual std::iostream& stream()
634 virtual std::string peer_address_to_string() const
636 return peer.address().to_string();
644 typename Protocol::endpoint peer;
645 asio::ssl::stream<typename Protocol::socket> sslStream;
648 SSLIOStreamDevice<Protocol> _d;
649 iostreams::stream< SSLIOStreamDevice<Protocol> > _stream;
652 void ServiceConnection(AcceptedConnection *conn);
654 // Forward declaration required for RPCListen
655 template <typename Protocol, typename SocketAcceptorService>
656 static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
657 ssl::context& context,
659 AcceptedConnection* conn,
660 const boost::system::error_code& error);
663 * Sets up I/O resources to accept and handle a new connection.
665 template <typename Protocol, typename SocketAcceptorService>
666 static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
667 ssl::context& context,
671 AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL);
673 acceptor->async_accept(
674 conn->sslStream.lowest_layer(),
676 boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>,
681 boost::asio::placeholders::error));
685 * Accept and handle incoming connection.
687 template <typename Protocol, typename SocketAcceptorService>
688 static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
689 ssl::context& context,
691 AcceptedConnection* conn,
692 const boost::system::error_code& error)
694 // Immediately start accepting new connections, except when we're cancelled or our socket is closed.
695 if (error != asio::error::operation_aborted && acceptor->is_open())
696 RPCListen(acceptor, context, fUseSSL);
698 AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn);
700 // TODO: Actually handle errors
706 // Restrict callers by IP. It is important to
707 // do this before starting client thread, to filter out
708 // certain DoS and misbehaving clients.
709 else if (tcp_conn && !ClientAllowed(tcp_conn->peer.address()))
711 // Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake.
713 conn->stream() << HTTPReply(HTTP_FORBIDDEN, "", false) << std::flush;
717 ServiceConnection(conn);
723 void StartRPCThreads()
725 strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
726 if (((mapArgs["-rpcpassword"] == "") ||
727 (mapArgs["-rpcuser"] == mapArgs["-rpcpassword"])) && Params().RequireRPCPassword())
729 unsigned char rand_pwd[32];
730 RAND_bytes(rand_pwd, 32);
731 string strWhatAmI = "To use bitcoind";
732 if (mapArgs.count("-server"))
733 strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
734 else if (mapArgs.count("-daemon"))
735 strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
736 uiInterface.ThreadSafeMessageBox(strprintf(
737 _("%s, you must set a rpcpassword in the configuration file:\n"
739 "It is recommended you use the following random password:\n"
740 "rpcuser=bitcoinrpc\n"
742 "(you do not need to remember this password)\n"
743 "The username and password MUST NOT be the same.\n"
744 "If the file does not exist, create it with owner-readable-only file permissions.\n"
745 "It is also recommended to set alertnotify so you are notified of problems;\n"
748 GetConfigFile().string().c_str(),
749 EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()),
750 "", CClientUIInterface::MSG_ERROR);
755 assert(rpc_io_service == NULL);
756 rpc_io_service = new asio::io_service();
757 rpc_ssl_context = new ssl::context(*rpc_io_service, ssl::context::sslv23);
759 const bool fUseSSL = GetBoolArg("-rpcssl", false);
763 rpc_ssl_context->set_options(ssl::context::no_sslv2);
765 filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert"));
766 if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile;
767 if (filesystem::exists(pathCertFile)) rpc_ssl_context->use_certificate_chain_file(pathCertFile.string());
768 else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string().c_str());
770 filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem"));
771 if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile;
772 if (filesystem::exists(pathPKFile)) rpc_ssl_context->use_private_key_file(pathPKFile.string(), ssl::context::pem);
773 else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str());
775 string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
776 SSL_CTX_set_cipher_list(rpc_ssl_context->impl(), strCiphers.c_str());
779 // Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets
780 const bool loopback = !mapArgs.count("-rpcallowip");
781 asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any();
782 ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", Params().RPCPort()));
783 boost::system::error_code v6_only_error;
784 boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(*rpc_io_service));
786 bool fListening = false;
790 acceptor->open(endpoint.protocol());
791 acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
793 // Try making the socket dual IPv6/IPv4 (if listening on the "any" address)
794 acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error);
796 acceptor->bind(endpoint);
797 acceptor->listen(socket_base::max_connections);
799 RPCListen(acceptor, *rpc_ssl_context, fUseSSL);
803 catch(boost::system::system_error &e)
805 strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s"), endpoint.port(), e.what());
809 // If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately
810 if (!fListening || loopback || v6_only_error)
812 bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any();
813 endpoint.address(bindAddress);
815 acceptor.reset(new ip::tcp::acceptor(*rpc_io_service));
816 acceptor->open(endpoint.protocol());
817 acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
818 acceptor->bind(endpoint);
819 acceptor->listen(socket_base::max_connections);
821 RPCListen(acceptor, *rpc_ssl_context, fUseSSL);
826 catch(boost::system::system_error &e)
828 strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv4: %s"), endpoint.port(), e.what());
832 uiInterface.ThreadSafeMessageBox(strerr, "", CClientUIInterface::MSG_ERROR);
837 rpc_worker_group = new boost::thread_group();
838 for (int i = 0; i < GetArg("-rpcthreads", 4); i++)
839 rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service));
842 void StopRPCThreads()
844 if (rpc_io_service == NULL) return;
846 deadlineTimers.clear();
847 rpc_io_service->stop();
848 rpc_worker_group->join_all();
849 delete rpc_worker_group; rpc_worker_group = NULL;
850 delete rpc_ssl_context; rpc_ssl_context = NULL;
851 delete rpc_io_service; rpc_io_service = NULL;
854 void RPCRunHandler(const boost::system::error_code& err, boost::function<void(void)> func)
860 void RPCRunLater(const std::string& name, boost::function<void(void)> func, int64 nSeconds)
862 assert(rpc_io_service != NULL);
864 if (deadlineTimers.count(name) == 0)
866 deadlineTimers.insert(make_pair(name,
867 boost::shared_ptr<deadline_timer>(new deadline_timer(*rpc_io_service))));
869 deadlineTimers[name]->expires_from_now(posix_time::seconds(nSeconds));
870 deadlineTimers[name]->async_wait(boost::bind(RPCRunHandler, _1, func));
881 JSONRequest() { id = Value::null; }
882 void parse(const Value& valRequest);
885 void JSONRequest::parse(const Value& valRequest)
888 if (valRequest.type() != obj_type)
889 throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
890 const Object& request = valRequest.get_obj();
892 // Parse id now so errors from here on will have the id
893 id = find_value(request, "id");
896 Value valMethod = find_value(request, "method");
897 if (valMethod.type() == null_type)
898 throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
899 if (valMethod.type() != str_type)
900 throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
901 strMethod = valMethod.get_str();
902 if (strMethod != "getwork" && strMethod != "getblocktemplate")
903 printf("ThreadRPCServer method=%s\n", strMethod.c_str());
906 Value valParams = find_value(request, "params");
907 if (valParams.type() == array_type)
908 params = valParams.get_array();
909 else if (valParams.type() == null_type)
912 throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array");
915 static Object JSONRPCExecOne(const Value& req)
923 Value result = tableRPC.execute(jreq.strMethod, jreq.params);
924 rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id);
926 catch (Object& objError)
928 rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id);
930 catch (std::exception& e)
932 rpc_result = JSONRPCReplyObj(Value::null,
933 JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
939 static string JSONRPCExecBatch(const Array& vReq)
942 for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
943 ret.push_back(JSONRPCExecOne(vReq[reqIdx]));
945 return write_string(Value(ret), false) + "\n";
948 void ServiceConnection(AcceptedConnection *conn)
954 map<string, string> mapHeaders;
955 string strRequest, strMethod, strURI;
957 // Read HTTP request line
958 if (!ReadHTTPRequestLine(conn->stream(), nProto, strMethod, strURI))
961 // Read HTTP message headers and body
962 ReadHTTPMessage(conn->stream(), mapHeaders, strRequest, nProto);
965 conn->stream() << HTTPReply(HTTP_NOT_FOUND, "", false) << std::flush;
969 // Check authorization
970 if (mapHeaders.count("authorization") == 0)
972 conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
975 if (!HTTPAuthorized(mapHeaders))
977 printf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string().c_str());
978 /* Deter brute-forcing short passwords.
979 If this results in a DOS the user really
980 shouldn't have their RPC port exposed.*/
981 if (mapArgs["-rpcpassword"].size() < 20)
984 conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
987 if (mapHeaders["connection"] == "close")
995 if (!read_string(strRequest, valRequest))
996 throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
1000 // singleton request
1001 if (valRequest.type() == obj_type) {
1002 jreq.parse(valRequest);
1004 Value result = tableRPC.execute(jreq.strMethod, jreq.params);
1007 strReply = JSONRPCReply(result, Value::null, jreq.id);
1009 // array of requests
1010 } else if (valRequest.type() == array_type)
1011 strReply = JSONRPCExecBatch(valRequest.get_array());
1013 throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
1015 conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush;
1017 catch (Object& objError)
1019 ErrorReply(conn->stream(), objError, jreq.id);
1022 catch (std::exception& e)
1024 ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
1030 json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array ¶ms) const
1033 const CRPCCommand *pcmd = tableRPC[strMethod];
1035 throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
1037 // Observe safe mode
1038 string strWarning = GetWarnings("rpc");
1039 if (strWarning != "" && !GetBoolArg("-disablesafemode", false) &&
1041 throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
1048 if (pcmd->threadSafe)
1049 result = pcmd->actor(params, false);
1051 LOCK2(cs_main, pwalletMain->cs_wallet);
1052 result = pcmd->actor(params, false);
1057 catch (std::exception& e)
1059 throw JSONRPCError(RPC_MISC_ERROR, e.what());
1064 Object CallRPC(const string& strMethod, const Array& params)
1066 if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
1067 throw runtime_error(strprintf(
1068 _("You must set rpcpassword=<password> in the configuration file:\n%s\n"
1069 "If the file does not exist, create it with owner-readable-only file permissions."),
1070 GetConfigFile().string().c_str()));
1072 // Connect to localhost
1073 bool fUseSSL = GetBoolArg("-rpcssl", false);
1074 asio::io_service io_service;
1075 ssl::context context(io_service, ssl::context::sslv23);
1076 context.set_options(ssl::context::no_sslv2);
1077 asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context);
1078 SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL);
1079 iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d);
1080 if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(Params().RPCPort()))))
1081 throw runtime_error("couldn't connect to server");
1083 // HTTP basic authentication
1084 string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
1085 map<string, string> mapRequestHeaders;
1086 mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
1089 string strRequest = JSONRPCRequest(strMethod, params, 1);
1090 string strPost = HTTPPost(strRequest, mapRequestHeaders);
1091 stream << strPost << std::flush;
1093 // Receive HTTP reply status
1095 int nStatus = ReadHTTPStatus(stream, nProto);
1097 // Receive HTTP reply message headers and body
1098 map<string, string> mapHeaders;
1100 ReadHTTPMessage(stream, mapHeaders, strReply, nProto);
1102 if (nStatus == HTTP_UNAUTHORIZED)
1103 throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
1104 else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR)
1105 throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
1106 else if (strReply.empty())
1107 throw runtime_error("no response from server");
1111 if (!read_string(strReply, valReply))
1112 throw runtime_error("couldn't parse reply from server");
1113 const Object& reply = valReply.get_obj();
1115 throw runtime_error("expected reply to have result, error and id properties");
1123 template<typename T>
1124 void ConvertTo(Value& value, bool fAllowNull=false)
1126 if (fAllowNull && value.type() == null_type)
1128 if (value.type() == str_type)
1130 // reinterpret string as unquoted json value
1132 string strJSON = value.get_str();
1133 if (!read_string(strJSON, value2))
1134 throw runtime_error(string("Error parsing JSON:")+strJSON);
1135 ConvertTo<T>(value2, fAllowNull);
1140 value = value.get_value<T>();
1144 // Convert strings to command-specific RPC representation
1145 Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
1148 BOOST_FOREACH(const std::string ¶m, strParams)
1149 params.push_back(param);
1151 int n = params.size();
1154 // Special case non-string parameter types
1156 if (strMethod == "stop" && n > 0) ConvertTo<bool>(params[0]);
1157 if (strMethod == "getaddednodeinfo" && n > 0) ConvertTo<bool>(params[0]);
1158 if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]);
1159 if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1160 if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);
1161 if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]);
1162 if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1163 if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1164 if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
1165 if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);
1166 if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]);
1167 if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]);
1168 if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1169 if (strMethod == "getblockhash" && n > 0) ConvertTo<boost::int64_t>(params[0]);
1170 if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]);
1171 if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]);
1172 if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]);
1173 if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]);
1174 if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1175 if (strMethod == "listtransactions" && n > 2) ConvertTo<boost::int64_t>(params[2]);
1176 if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]);
1177 if (strMethod == "walletpassphrase" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1178 if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]);
1179 if (strMethod == "listsinceblock" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1180 if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]);
1181 if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]);
1182 if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
1183 if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]);
1184 if (strMethod == "createmultisig" && n > 0) ConvertTo<boost::int64_t>(params[0]);
1185 if (strMethod == "createmultisig" && n > 1) ConvertTo<Array>(params[1]);
1186 if (strMethod == "listunspent" && n > 0) ConvertTo<boost::int64_t>(params[0]);
1187 if (strMethod == "listunspent" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1188 if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]);
1189 if (strMethod == "getblock" && n > 1) ConvertTo<bool>(params[1]);
1190 if (strMethod == "getrawtransaction" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1191 if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]);
1192 if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]);
1193 if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1], true);
1194 if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2], true);
1195 if (strMethod == "gettxout" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1196 if (strMethod == "gettxout" && n > 2) ConvertTo<bool>(params[2]);
1197 if (strMethod == "lockunspent" && n > 0) ConvertTo<bool>(params[0]);
1198 if (strMethod == "lockunspent" && n > 1) ConvertTo<Array>(params[1]);
1199 if (strMethod == "importprivkey" && n > 2) ConvertTo<bool>(params[2]);
1200 if (strMethod == "verifychain" && n > 0) ConvertTo<boost::int64_t>(params[0]);
1201 if (strMethod == "verifychain" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1206 int CommandLineRPC(int argc, char *argv[])
1213 while (argc > 1 && IsSwitchChar(argv[1][0]))
1221 throw runtime_error("too few parameters");
1222 string strMethod = argv[1];
1224 // Parameters default to strings
1225 std::vector<std::string> strParams(&argv[2], &argv[argc]);
1226 Array params = RPCConvertValues(strMethod, strParams);
1229 Object reply = CallRPC(strMethod, params);
1232 const Value& result = find_value(reply, "result");
1233 const Value& error = find_value(reply, "error");
1235 if (error.type() != null_type)
1238 strPrint = "error: " + write_string(error, false);
1239 int code = find_value(error.get_obj(), "code").get_int();
1245 if (result.type() == null_type)
1247 else if (result.type() == str_type)
1248 strPrint = result.get_str();
1250 strPrint = write_string(result, true);
1253 catch (boost::thread_interrupted) {
1256 catch (std::exception& e) {
1257 strPrint = string("error: ") + e.what();
1261 PrintException(NULL, "CommandLineRPC()");
1266 fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
1275 int main(int argc, char *argv[])
1278 // Turn off Microsoft heap dump noise
1279 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
1280 _CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
1282 setbuf(stdin, NULL);
1283 setbuf(stdout, NULL);
1284 setbuf(stderr, NULL);
1288 if (argc >= 2 && string(argv[1]) == "-server")
1290 printf("server ready\n");
1291 ThreadRPCServer(NULL);
1295 return CommandLineRPC(argc, argv);
1298 catch (boost::thread_interrupted) {
1301 catch (std::exception& e) {
1302 PrintException(&e, "main()");
1304 PrintException(NULL, "main()");
1310 const CRPCTable tableRPC;