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.
9 #include "ui_interface.h"
11 #include "bitcoinrpc.h"
14 #include <boost/asio.hpp>
15 #include <boost/asio/ip/v6_only.hpp>
16 #include <boost/bind.hpp>
17 #include <boost/filesystem.hpp>
18 #include <boost/foreach.hpp>
19 #include <boost/iostreams/concepts.hpp>
20 #include <boost/iostreams/stream.hpp>
21 #include <boost/algorithm/string.hpp>
22 #include <boost/lexical_cast.hpp>
23 #include <boost/asio/ssl.hpp>
24 #include <boost/filesystem/fstream.hpp>
25 #include <boost/shared_ptr.hpp>
29 using namespace boost;
30 using namespace boost::asio;
31 using namespace json_spirit;
33 static std::string strRPCUserColonPass;
35 // These are created by StartRPCThreads, destroyed in StopRPCThreads
36 static asio::io_service* rpc_io_service = NULL;
37 static ssl::context* rpc_ssl_context = NULL;
38 static boost::thread_group* rpc_worker_group = NULL;
40 static inline unsigned short GetDefaultRPCPort()
42 return GetBoolArg("-testnet", false) ? 18332 : 8332;
45 Object JSONRPCError(int code, const string& message)
48 error.push_back(Pair("code", code));
49 error.push_back(Pair("message", message));
53 void RPCTypeCheck(const Array& params,
54 const list<Value_type>& typesExpected,
58 BOOST_FOREACH(Value_type t, typesExpected)
60 if (params.size() <= i)
63 const Value& v = params[i];
64 if (!((v.type() == t) || (fAllowNull && (v.type() == null_type))))
66 string err = strprintf("Expected type %s, got %s",
67 Value_type_name[t], Value_type_name[v.type()]);
68 throw JSONRPCError(RPC_TYPE_ERROR, err);
74 void RPCTypeCheck(const Object& o,
75 const map<string, Value_type>& typesExpected,
78 BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected)
80 const Value& v = find_value(o, t.first);
81 if (!fAllowNull && v.type() == null_type)
82 throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first.c_str()));
84 if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type))))
86 string err = strprintf("Expected type %s for %s, got %s",
87 Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]);
88 throw JSONRPCError(RPC_TYPE_ERROR, err);
93 int64 AmountFromValue(const Value& value)
95 double dAmount = value.get_real();
96 if (dAmount <= 0.0 || dAmount > 21000000.0)
97 throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
98 int64 nAmount = roundint64(dAmount * COIN);
99 if (!MoneyRange(nAmount))
100 throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
104 Value ValueFromAmount(int64 amount)
106 return (double)amount / (double)COIN;
109 std::string HexBits(unsigned int nBits)
115 uBits.nBits = htonl((int32_t)nBits);
116 return HexStr(BEGIN(uBits.cBits), END(uBits.cBits));
122 /// Note: This interface may still be subject to change.
125 string CRPCTable::help(string strCommand) const
128 set<rpcfn_type> setDone;
129 for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)
131 const CRPCCommand *pcmd = mi->second;
132 string strMethod = mi->first;
133 // We already filter duplicates, but these deprecated screw up the sort order
134 if (strMethod.find("label") != string::npos)
136 if (strCommand != "" && strMethod != strCommand)
141 rpcfn_type pfn = pcmd->actor;
142 if (setDone.insert(pfn).second)
143 (*pfn)(params, true);
145 catch (std::exception& e)
147 // Help text is returned in an exception
148 string strHelp = string(e.what());
149 if (strCommand == "")
150 if (strHelp.find('\n') != string::npos)
151 strHelp = strHelp.substr(0, strHelp.find('\n'));
152 strRet += strHelp + "\n";
156 strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
157 strRet = strRet.substr(0,strRet.size()-1);
161 Value help(const Array& params, bool fHelp)
163 if (fHelp || params.size() > 1)
166 "List commands, or get help for a command.");
169 if (params.size() > 0)
170 strCommand = params[0].get_str();
172 return tableRPC.help(strCommand);
176 Value stop(const Array& params, bool fHelp)
178 // Accept the deprecated and ignored 'detach' boolean argument
179 if (fHelp || params.size() > 1)
182 "Stop Bitcoin server.");
183 // Shutdown will take long enough that the response should get back
185 return "Bitcoin server stopping";
195 static const CRPCCommand vRPCCommands[] =
196 { // name actor (function) okSafeMode threadSafe
197 // ------------------------ ----------------------- ---------- ----------
198 { "help", &help, true, true },
199 { "stop", &stop, true, true },
200 { "getblockcount", &getblockcount, true, false },
201 { "getconnectioncount", &getconnectioncount, true, false },
202 { "getpeerinfo", &getpeerinfo, true, false },
203 { "addnode", &addnode, true, true },
204 { "getaddednodeinfo", &getaddednodeinfo, true, true },
205 { "getdifficulty", &getdifficulty, true, false },
206 { "getgenerate", &getgenerate, true, false },
207 { "setgenerate", &setgenerate, true, false },
208 { "gethashespersec", &gethashespersec, true, false },
209 { "getinfo", &getinfo, true, false },
210 { "getmininginfo", &getmininginfo, true, false },
211 { "getnewaddress", &getnewaddress, true, false },
212 { "getaccountaddress", &getaccountaddress, true, false },
213 { "setaccount", &setaccount, true, false },
214 { "getaccount", &getaccount, false, false },
215 { "getaddressesbyaccount", &getaddressesbyaccount, true, false },
216 { "sendtoaddress", &sendtoaddress, false, false },
217 { "getreceivedbyaddress", &getreceivedbyaddress, false, false },
218 { "getreceivedbyaccount", &getreceivedbyaccount, false, false },
219 { "listreceivedbyaddress", &listreceivedbyaddress, false, false },
220 { "listreceivedbyaccount", &listreceivedbyaccount, false, false },
221 { "backupwallet", &backupwallet, true, false },
222 { "keypoolrefill", &keypoolrefill, true, false },
223 { "walletpassphrase", &walletpassphrase, true, false },
224 { "walletpassphrasechange", &walletpassphrasechange, false, false },
225 { "walletlock", &walletlock, true, false },
226 { "encryptwallet", &encryptwallet, false, false },
227 { "validateaddress", &validateaddress, true, false },
228 { "getbalance", &getbalance, false, false },
229 { "move", &movecmd, false, false },
230 { "sendfrom", &sendfrom, false, false },
231 { "sendmany", &sendmany, false, false },
232 { "addmultisigaddress", &addmultisigaddress, false, false },
233 { "createmultisig", &createmultisig, true, true },
234 { "getrawmempool", &getrawmempool, true, false },
235 { "getblock", &getblock, false, false },
236 { "getblockhash", &getblockhash, false, false },
237 { "gettransaction", &gettransaction, false, false },
238 { "listtransactions", &listtransactions, false, false },
239 { "listaddressgroupings", &listaddressgroupings, false, false },
240 { "signmessage", &signmessage, false, false },
241 { "verifymessage", &verifymessage, false, false },
242 { "getwork", &getwork, true, false },
243 { "listaccounts", &listaccounts, false, false },
244 { "settxfee", &settxfee, false, false },
245 { "getblocktemplate", &getblocktemplate, true, false },
246 { "submitblock", &submitblock, false, false },
247 { "listsinceblock", &listsinceblock, false, false },
248 { "dumpprivkey", &dumpprivkey, true, false },
249 { "importprivkey", &importprivkey, false, false },
250 { "listunspent", &listunspent, false, false },
251 { "getrawtransaction", &getrawtransaction, false, false },
252 { "createrawtransaction", &createrawtransaction, false, false },
253 { "decoderawtransaction", &decoderawtransaction, false, false },
254 { "signrawtransaction", &signrawtransaction, false, false },
255 { "sendrawtransaction", &sendrawtransaction, false, false },
256 { "gettxoutsetinfo", &gettxoutsetinfo, true, false },
257 { "gettxout", &gettxout, true, false },
258 { "lockunspent", &lockunspent, false, false },
259 { "listlockunspent", &listlockunspent, false, 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"]))
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");
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", GetDefaultRPCPort()));
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 rpc_io_service->stop();
847 rpc_worker_group->join_all();
848 delete rpc_worker_group; rpc_worker_group = NULL;
849 delete rpc_ssl_context; rpc_ssl_context = NULL;
850 delete rpc_io_service; rpc_io_service = NULL;
860 JSONRequest() { id = Value::null; }
861 void parse(const Value& valRequest);
864 void JSONRequest::parse(const Value& valRequest)
867 if (valRequest.type() != obj_type)
868 throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
869 const Object& request = valRequest.get_obj();
871 // Parse id now so errors from here on will have the id
872 id = find_value(request, "id");
875 Value valMethod = find_value(request, "method");
876 if (valMethod.type() == null_type)
877 throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
878 if (valMethod.type() != str_type)
879 throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
880 strMethod = valMethod.get_str();
881 if (strMethod != "getwork" && strMethod != "getblocktemplate")
882 printf("ThreadRPCServer method=%s\n", strMethod.c_str());
885 Value valParams = find_value(request, "params");
886 if (valParams.type() == array_type)
887 params = valParams.get_array();
888 else if (valParams.type() == null_type)
891 throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array");
894 static Object JSONRPCExecOne(const Value& req)
902 Value result = tableRPC.execute(jreq.strMethod, jreq.params);
903 rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id);
905 catch (Object& objError)
907 rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id);
909 catch (std::exception& e)
911 rpc_result = JSONRPCReplyObj(Value::null,
912 JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
918 static string JSONRPCExecBatch(const Array& vReq)
921 for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
922 ret.push_back(JSONRPCExecOne(vReq[reqIdx]));
924 return write_string(Value(ret), false) + "\n";
927 void ServiceConnection(AcceptedConnection *conn)
933 map<string, string> mapHeaders;
934 string strRequest, strMethod, strURI;
936 // Read HTTP request line
937 if (!ReadHTTPRequestLine(conn->stream(), nProto, strMethod, strURI))
940 // Read HTTP message headers and body
941 ReadHTTPMessage(conn->stream(), mapHeaders, strRequest, nProto);
944 conn->stream() << HTTPReply(HTTP_NOT_FOUND, "", false) << std::flush;
948 // Check authorization
949 if (mapHeaders.count("authorization") == 0)
951 conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
954 if (!HTTPAuthorized(mapHeaders))
956 printf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string().c_str());
957 /* Deter brute-forcing short passwords.
958 If this results in a DOS the user really
959 shouldn't have their RPC port exposed.*/
960 if (mapArgs["-rpcpassword"].size() < 20)
963 conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
966 if (mapHeaders["connection"] == "close")
974 if (!read_string(strRequest, valRequest))
975 throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
980 if (valRequest.type() == obj_type) {
981 jreq.parse(valRequest);
983 Value result = tableRPC.execute(jreq.strMethod, jreq.params);
986 strReply = JSONRPCReply(result, Value::null, jreq.id);
989 } else if (valRequest.type() == array_type)
990 strReply = JSONRPCExecBatch(valRequest.get_array());
992 throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
994 conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush;
996 catch (Object& objError)
998 ErrorReply(conn->stream(), objError, jreq.id);
1001 catch (std::exception& e)
1003 ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
1009 json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array ¶ms) const
1012 const CRPCCommand *pcmd = tableRPC[strMethod];
1014 throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
1016 // Observe safe mode
1017 string strWarning = GetWarnings("rpc");
1018 if (strWarning != "" && !GetBoolArg("-disablesafemode") &&
1020 throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
1027 if (pcmd->threadSafe)
1028 result = pcmd->actor(params, false);
1030 LOCK2(cs_main, pwalletMain->cs_wallet);
1031 result = pcmd->actor(params, false);
1036 catch (std::exception& e)
1038 throw JSONRPCError(RPC_MISC_ERROR, e.what());
1043 Object CallRPC(const string& strMethod, const Array& params)
1045 if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
1046 throw runtime_error(strprintf(
1047 _("You must set rpcpassword=<password> in the configuration file:\n%s\n"
1048 "If the file does not exist, create it with owner-readable-only file permissions."),
1049 GetConfigFile().string().c_str()));
1051 // Connect to localhost
1052 bool fUseSSL = GetBoolArg("-rpcssl");
1053 asio::io_service io_service;
1054 ssl::context context(io_service, ssl::context::sslv23);
1055 context.set_options(ssl::context::no_sslv2);
1056 asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context);
1057 SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL);
1058 iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d);
1059 if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(GetDefaultRPCPort()))))
1060 throw runtime_error("couldn't connect to server");
1062 // HTTP basic authentication
1063 string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
1064 map<string, string> mapRequestHeaders;
1065 mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
1068 string strRequest = JSONRPCRequest(strMethod, params, 1);
1069 string strPost = HTTPPost(strRequest, mapRequestHeaders);
1070 stream << strPost << std::flush;
1072 // Receive HTTP reply status
1074 int nStatus = ReadHTTPStatus(stream, nProto);
1076 // Receive HTTP reply message headers and body
1077 map<string, string> mapHeaders;
1079 ReadHTTPMessage(stream, mapHeaders, strReply, nProto);
1081 if (nStatus == HTTP_UNAUTHORIZED)
1082 throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
1083 else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR)
1084 throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
1085 else if (strReply.empty())
1086 throw runtime_error("no response from server");
1090 if (!read_string(strReply, valReply))
1091 throw runtime_error("couldn't parse reply from server");
1092 const Object& reply = valReply.get_obj();
1094 throw runtime_error("expected reply to have result, error and id properties");
1102 template<typename T>
1103 void ConvertTo(Value& value, bool fAllowNull=false)
1105 if (fAllowNull && value.type() == null_type)
1107 if (value.type() == str_type)
1109 // reinterpret string as unquoted json value
1111 string strJSON = value.get_str();
1112 if (!read_string(strJSON, value2))
1113 throw runtime_error(string("Error parsing JSON:")+strJSON);
1114 ConvertTo<T>(value2, fAllowNull);
1119 value = value.get_value<T>();
1123 // Convert strings to command-specific RPC representation
1124 Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
1127 BOOST_FOREACH(const std::string ¶m, strParams)
1128 params.push_back(param);
1130 int n = params.size();
1133 // Special case non-string parameter types
1135 if (strMethod == "stop" && n > 0) ConvertTo<bool>(params[0]);
1136 if (strMethod == "getaddednodeinfo" && n > 0) ConvertTo<bool>(params[0]);
1137 if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]);
1138 if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1139 if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);
1140 if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]);
1141 if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1142 if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1143 if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
1144 if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);
1145 if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]);
1146 if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]);
1147 if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1148 if (strMethod == "getblockhash" && n > 0) ConvertTo<boost::int64_t>(params[0]);
1149 if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]);
1150 if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]);
1151 if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]);
1152 if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]);
1153 if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1154 if (strMethod == "listtransactions" && n > 2) ConvertTo<boost::int64_t>(params[2]);
1155 if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]);
1156 if (strMethod == "walletpassphrase" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1157 if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]);
1158 if (strMethod == "listsinceblock" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1159 if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]);
1160 if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]);
1161 if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
1162 if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]);
1163 if (strMethod == "createmultisig" && n > 0) ConvertTo<boost::int64_t>(params[0]);
1164 if (strMethod == "createmultisig" && n > 1) ConvertTo<Array>(params[1]);
1165 if (strMethod == "listunspent" && n > 0) ConvertTo<boost::int64_t>(params[0]);
1166 if (strMethod == "listunspent" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1167 if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]);
1168 if (strMethod == "getrawtransaction" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1169 if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]);
1170 if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]);
1171 if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1], true);
1172 if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2], true);
1173 if (strMethod == "gettxout" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1174 if (strMethod == "gettxout" && n > 2) ConvertTo<bool>(params[2]);
1175 if (strMethod == "lockunspent" && n > 0) ConvertTo<bool>(params[0]);
1176 if (strMethod == "lockunspent" && n > 1) ConvertTo<Array>(params[1]);
1177 if (strMethod == "importprivkey" && n > 2) ConvertTo<bool>(params[2]);
1182 int CommandLineRPC(int argc, char *argv[])
1189 while (argc > 1 && IsSwitchChar(argv[1][0]))
1197 throw runtime_error("too few parameters");
1198 string strMethod = argv[1];
1200 // Parameters default to strings
1201 std::vector<std::string> strParams(&argv[2], &argv[argc]);
1202 Array params = RPCConvertValues(strMethod, strParams);
1205 Object reply = CallRPC(strMethod, params);
1208 const Value& result = find_value(reply, "result");
1209 const Value& error = find_value(reply, "error");
1211 if (error.type() != null_type)
1214 strPrint = "error: " + write_string(error, false);
1215 int code = find_value(error.get_obj(), "code").get_int();
1221 if (result.type() == null_type)
1223 else if (result.type() == str_type)
1224 strPrint = result.get_str();
1226 strPrint = write_string(result, true);
1229 catch (boost::thread_interrupted) {
1232 catch (std::exception& e) {
1233 strPrint = string("error: ") + e.what();
1237 PrintException(NULL, "CommandLineRPC()");
1242 fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
1251 int main(int argc, char *argv[])
1254 // Turn off Microsoft heap dump noise
1255 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
1256 _CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
1258 setbuf(stdin, NULL);
1259 setbuf(stdout, NULL);
1260 setbuf(stderr, NULL);
1264 if (argc >= 2 && string(argv[1]) == "-server")
1266 printf("server ready\n");
1267 ThreadRPCServer(NULL);
1271 return CommandLineRPC(argc, argv);
1274 catch (boost::thread_interrupted) {
1277 catch (std::exception& e) {
1278 PrintException(&e, "main()");
1280 PrintException(NULL, "main()");
1286 const CRPCTable tableRPC;