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"
15 #include <boost/asio.hpp>
16 #include <boost/asio/ip/v6_only.hpp>
17 #include <boost/bind.hpp>
18 #include <boost/filesystem.hpp>
19 #include <boost/foreach.hpp>
20 #include <boost/iostreams/concepts.hpp>
21 #include <boost/iostreams/stream.hpp>
22 #include <boost/algorithm/string.hpp>
23 #include <boost/lexical_cast.hpp>
24 #include <boost/asio/ssl.hpp>
25 #include <boost/filesystem/fstream.hpp>
26 #include <boost/shared_ptr.hpp>
29 #define printf OutputDebugStringF
32 using namespace boost;
33 using namespace boost::asio;
34 using namespace json_spirit;
36 void ThreadRPCServer2(void* parg);
38 static std::string strRPCUserColonPass;
40 const Object emptyobj;
42 void ThreadRPCServer3(void* parg);
44 static inline unsigned short GetDefaultRPCPort()
46 return GetBoolArg("-testnet", false) ? 18344 : 8344;
49 Object JSONRPCError(int code, const string& message)
52 error.push_back(Pair("code", code));
53 error.push_back(Pair("message", message));
57 void RPCTypeCheck(const Array& params,
58 const list<Value_type>& typesExpected,
62 BOOST_FOREACH(Value_type t, typesExpected)
64 if (params.size() <= i)
67 const Value& v = params[i];
68 if (!((v.type() == t) || (fAllowNull && (v.type() == null_type))))
70 string err = strprintf("Expected type %s, got %s",
71 Value_type_name[t], Value_type_name[v.type()]);
72 throw JSONRPCError(RPC_TYPE_ERROR, err);
78 void RPCTypeCheck(const Object& o,
79 const map<string, Value_type>& typesExpected,
82 BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected)
84 const Value& v = find_value(o, t.first);
85 if (!fAllowNull && v.type() == null_type)
86 throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first.c_str()));
88 if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type))))
90 string err = strprintf("Expected type %s for %s, got %s",
91 Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]);
92 throw JSONRPCError(RPC_TYPE_ERROR, err);
97 int64 AmountFromValue(const Value& value)
99 double dAmount = value.get_real();
100 if (dAmount <= 0.0 || dAmount > MAX_MONEY)
101 throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
102 int64 nAmount = roundint64(dAmount * COIN);
103 if (!MoneyRange(nAmount))
104 throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
108 Value ValueFromAmount(int64 amount)
110 return (double)amount / (double)COIN;
113 std::string HexBits(unsigned int nBits)
119 uBits.nBits = htonl((int32_t)nBits);
120 return HexStr(BEGIN(uBits.cBits), END(uBits.cBits));
126 /// Note: This interface may still be subject to change.
129 string CRPCTable::help(string strCommand) const
132 set<rpcfn_type> setDone;
133 for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)
135 const CRPCCommand *pcmd = mi->second;
136 string strMethod = mi->first;
137 // We already filter duplicates, but these deprecated screw up the sort order
138 if (strMethod.find("label") != string::npos)
140 if (strCommand != "" && strMethod != strCommand)
145 rpcfn_type pfn = pcmd->actor;
146 if (setDone.insert(pfn).second)
147 (*pfn)(params, true);
149 catch (std::exception& e)
151 // Help text is returned in an exception
152 string strHelp = string(e.what());
153 if (strCommand == "")
154 if (strHelp.find('\n') != string::npos)
155 strHelp = strHelp.substr(0, strHelp.find('\n'));
156 strRet += strHelp + "\n";
160 strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
161 strRet = strRet.substr(0,strRet.size()-1);
165 Value help(const Array& params, bool fHelp)
167 if (fHelp || params.size() > 1)
170 "List commands, or get help for a command.");
173 if (params.size() > 0)
174 strCommand = params[0].get_str();
176 return tableRPC.help(strCommand);
180 Value stop(const Array& params, bool fHelp)
182 if (fHelp || params.size() > 1)
185 "<detach> is true or false to detach the database or not for this stop only\n"
186 "Stop NovaCoin server (and possibly override the detachdb config value).");
187 // Shutdown will take long enough that the response should get back
188 if (params.size() > 0)
189 bitdb.SetDetach(params[0].get_bool());
191 return "NovaCoin server stopping";
201 static const CRPCCommand vRPCCommands[] =
202 { // name function safemd unlocked
203 // ------------------------ ----------------------- ------ --------
204 { "help", &help, true, true },
205 { "stop", &stop, true, true },
206 { "getbestblockhash", &getbestblockhash, true, false },
207 { "getblockcount", &getblockcount, true, false },
208 { "getconnectioncount", &getconnectioncount, true, false },
209 { "getpeerinfo", &getpeerinfo, true, false },
210 { "getdifficulty", &getdifficulty, true, false },
211 { "getinfo", &getinfo, true, false },
212 { "getmininginfo", &getmininginfo, true, false },
213 { "getnewaddress", &getnewaddress, true, false },
214 { "getnewpubkey", &getnewpubkey, true, false },
215 { "getaccountaddress", &getaccountaddress, true, false },
216 { "setaccount", &setaccount, true, false },
217 { "getaccount", &getaccount, false, false },
218 { "getaddressesbyaccount", &getaddressesbyaccount, true, false },
219 { "sendtoaddress", &sendtoaddress, false, false },
220 { "getreceivedbyaddress", &getreceivedbyaddress, false, false },
221 { "getreceivedbyaccount", &getreceivedbyaccount, false, false },
222 { "listreceivedbyaddress", &listreceivedbyaddress, false, false },
223 { "listreceivedbyaccount", &listreceivedbyaccount, false, false },
224 { "backupwallet", &backupwallet, true, false },
225 { "keypoolrefill", &keypoolrefill, true, false },
226 { "walletpassphrase", &walletpassphrase, true, false },
227 { "walletpassphrasechange", &walletpassphrasechange, false, false },
228 { "walletlock", &walletlock, true, false },
229 { "encryptwallet", &encryptwallet, false, false },
230 { "validateaddress", &validateaddress, true, false },
231 { "validatepubkey", &validatepubkey, true, false },
232 { "getbalance", &getbalance, false, false },
233 { "move", &movecmd, false, false },
234 { "sendfrom", &sendfrom, false, false },
235 { "sendmany", &sendmany, false, false },
236 { "addmultisigaddress", &addmultisigaddress, false, false },
237 { "getrawmempool", &getrawmempool, true, false },
238 { "getblock", &getblock, false, false },
239 { "getblockbynumber", &getblockbynumber, false, false },
240 { "getblockhash", &getblockhash, false, false },
241 { "gettransaction", &gettransaction, false, false },
242 { "listtransactions", &listtransactions, false, false },
243 { "listaddressgroupings", &listaddressgroupings, false, false },
244 { "signmessage", &signmessage, false, false },
245 { "verifymessage", &verifymessage, false, false },
246 { "getwork", &getwork, true, false },
247 { "getworkex", &getworkex, true, false },
248 { "listaccounts", &listaccounts, false, false },
249 { "settxfee", &settxfee, false, false },
250 { "getblocktemplate", &getblocktemplate, true, false },
251 { "submitblock", &submitblock, false, false },
252 { "listsinceblock", &listsinceblock, false, false },
253 { "dumpprivkey", &dumpprivkey, false, false },
254 { "importprivkey", &importprivkey, false, false },
255 { "listunspent", &listunspent, false, false },
256 { "getrawtransaction", &getrawtransaction, false, false },
257 { "createrawtransaction", &createrawtransaction, false, false },
258 { "decoderawtransaction", &decoderawtransaction, false, false },
259 { "signrawtransaction", &signrawtransaction, false, false },
260 { "sendrawtransaction", &sendrawtransaction, false, false },
261 { "getcheckpoint", &getcheckpoint, true, false },
262 { "reservebalance", &reservebalance, false, true},
263 { "checkwallet", &checkwallet, false, true},
264 { "repairwallet", &repairwallet, false, true},
265 { "resendtx", &resendtx, false, true},
266 { "makekeypair", &makekeypair, false, true},
267 { "sendalert", &sendalert, false, false},
270 CRPCTable::CRPCTable()
273 for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++)
275 const CRPCCommand *pcmd;
277 pcmd = &vRPCCommands[vcidx];
278 mapCommands[pcmd->name] = pcmd;
282 const CRPCCommand *CRPCTable::operator[](string name) const
284 map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
285 if (it == mapCommands.end())
293 // This ain't Apache. We're just using HTTP header for the length field
294 // and to be compatible with other JSON-RPC implementations.
297 string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
300 s << "POST / HTTP/1.1\r\n"
301 << "User-Agent: novacoin-json-rpc/" << FormatFullVersion() << "\r\n"
302 << "Host: 127.0.0.1\r\n"
303 << "Content-Type: application/json\r\n"
304 << "Content-Length: " << strMsg.size() << "\r\n"
305 << "Connection: close\r\n"
306 << "Accept: application/json\r\n";
307 BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders)
308 s << item.first << ": " << item.second << "\r\n";
309 s << "\r\n" << strMsg;
319 struct tm* now_gmt = gmtime(&now);
320 string locale(setlocale(LC_TIME, NULL));
321 setlocale(LC_TIME, "C"); // we want POSIX (aka "C") weekday/month strings
322 strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt);
323 setlocale(LC_TIME, locale.c_str());
324 return string(buffer);
327 static string HTTPReply(int nStatus, const string& strMsg, bool keepalive)
329 if (nStatus == HTTP_UNAUTHORIZED)
330 return strprintf("HTTP/1.0 401 Authorization Required\r\n"
332 "Server: novacoin-json-rpc/%s\r\n"
333 "WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
334 "Content-Type: text/html\r\n"
335 "Content-Length: 296\r\n"
337 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
338 "\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
341 "<TITLE>Error</TITLE>\r\n"
342 "<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
344 "<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
345 "</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str());
347 if (nStatus == HTTP_OK) cStatus = "OK";
348 else if (nStatus == HTTP_BAD_REQUEST) cStatus = "Bad Request";
349 else if (nStatus == HTTP_FORBIDDEN) cStatus = "Forbidden";
350 else if (nStatus == HTTP_NOT_FOUND) cStatus = "Not Found";
351 else if (nStatus == HTTP_INTERNAL_SERVER_ERROR) cStatus = "Internal Server Error";
357 "Content-Length: %"PRIszu"\r\n"
358 "Content-Type: application/json\r\n"
359 "Server: novacoin-json-rpc/%s\r\n"
364 rfc1123Time().c_str(),
365 keepalive ? "keep-alive" : "close",
367 FormatFullVersion().c_str(),
371 int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto)
374 getline(stream, str);
375 vector<string> vWords;
376 boost::split(vWords, str, boost::is_any_of(" "));
377 if (vWords.size() < 2)
378 return HTTP_INTERNAL_SERVER_ERROR;
380 const char *ver = strstr(str.c_str(), "HTTP/1.");
383 return atoi(vWords[1].c_str());
386 int ReadHTTPHeader(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
392 std::getline(stream, str);
393 if (str.empty() || str == "\r")
395 string::size_type nColon = str.find(":");
396 if (nColon != string::npos)
398 string strHeader = str.substr(0, nColon);
399 boost::trim(strHeader);
400 boost::to_lower(strHeader);
401 string strValue = str.substr(nColon+1);
402 boost::trim(strValue);
403 mapHeadersRet[strHeader] = strValue;
404 if (strHeader == "content-length")
405 nLen = atoi(strValue.c_str());
411 int ReadHTTP(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet)
413 mapHeadersRet.clear();
418 int nStatus = ReadHTTPStatus(stream, nProto);
421 int nLen = ReadHTTPHeader(stream, mapHeadersRet);
422 if (nLen < 0 || nLen > (int)MAX_SIZE)
423 return HTTP_INTERNAL_SERVER_ERROR;
428 vector<char> vch(nLen);
429 stream.read(&vch[0], nLen);
430 strMessageRet = string(vch.begin(), vch.end());
433 string sConHdr = mapHeadersRet["connection"];
435 if ((sConHdr != "close") && (sConHdr != "keep-alive"))
438 mapHeadersRet["connection"] = "keep-alive";
440 mapHeadersRet["connection"] = "close";
446 bool HTTPAuthorized(map<string, string>& mapHeaders)
448 string strAuth = mapHeaders["authorization"];
449 if (strAuth.substr(0,6) != "Basic ")
451 string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
452 string strUserPass = DecodeBase64(strUserPass64);
453 return strUserPass == strRPCUserColonPass;
457 // JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
458 // but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
459 // unspecified (HTTP errors and contents of 'error').
461 // 1.0 spec: http://json-rpc.org/wiki/specification
462 // 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
463 // http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
466 string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
469 request.push_back(Pair("method", strMethod));
470 request.push_back(Pair("params", params));
471 request.push_back(Pair("id", id));
472 return write_string(Value(request), false) + "\n";
475 Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id)
478 if (error.type() != null_type)
479 reply.push_back(Pair("result", Value::null));
481 reply.push_back(Pair("result", result));
482 reply.push_back(Pair("error", error));
483 reply.push_back(Pair("id", id));
487 string JSONRPCReply(const Value& result, const Value& error, const Value& id)
489 Object reply = JSONRPCReplyObj(result, error, id);
490 return write_string(Value(reply), false) + "\n";
493 void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
495 // Send error reply from json-rpc error object
496 int nStatus = HTTP_INTERNAL_SERVER_ERROR;
497 int code = find_value(objError, "code").get_int();
498 if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST;
499 else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND;
500 string strReply = JSONRPCReply(Value::null, objError, id);
501 stream << HTTPReply(nStatus, strReply, false) << std::flush;
504 bool ClientAllowed(const boost::asio::ip::address& address)
506 // Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses
508 && (address.to_v6().is_v4_compatible()
509 || address.to_v6().is_v4_mapped()))
510 return ClientAllowed(address.to_v6().to_v4());
512 if (address == asio::ip::address_v4::loopback()
513 || address == asio::ip::address_v6::loopback()
515 // Check whether IPv4 addresses match 127.0.0.0/8 (loopback subnet)
516 && (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000))
519 const string strAddress = address.to_string();
520 const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
521 BOOST_FOREACH(string strAllow, vAllow)
522 if (WildcardMatch(strAddress, strAllow))
528 // IOStream device that speaks SSL but can also speak non-SSL
530 template <typename Protocol>
531 class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {
533 SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn)
536 fNeedHandshake = fUseSSLIn;
539 void handshake(ssl::stream_base::handshake_type role)
541 if (!fNeedHandshake) return;
542 fNeedHandshake = false;
543 stream.handshake(role);
545 std::streamsize read(char* s, std::streamsize n)
547 handshake(ssl::stream_base::server); // HTTPS servers read first
548 if (fUseSSL) return stream.read_some(asio::buffer(s, n));
549 return stream.next_layer().read_some(asio::buffer(s, n));
551 std::streamsize write(const char* s, std::streamsize n)
553 handshake(ssl::stream_base::client); // HTTPS clients write first
554 if (fUseSSL) return asio::write(stream, asio::buffer(s, n));
555 return asio::write(stream.next_layer(), asio::buffer(s, n));
557 bool connect(const std::string& server, const std::string& port)
559 ip::tcp::resolver resolver(stream.get_io_service());
560 ip::tcp::resolver::query query(server.c_str(), port.c_str());
561 ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
562 ip::tcp::resolver::iterator end;
563 boost::system::error_code error = asio::error::host_not_found;
564 while (error && endpoint_iterator != end)
566 stream.lowest_layer().close();
567 stream.lowest_layer().connect(*endpoint_iterator++, error);
577 asio::ssl::stream<typename Protocol::socket>& stream;
580 class AcceptedConnection
583 virtual ~AcceptedConnection() {}
585 virtual std::iostream& stream() = 0;
586 virtual std::string peer_address_to_string() const = 0;
587 virtual void close() = 0;
590 template <typename Protocol>
591 class AcceptedConnectionImpl : public AcceptedConnection
594 AcceptedConnectionImpl(
595 asio::io_service& io_service,
596 ssl::context &context,
598 sslStream(io_service, context),
599 _d(sslStream, fUseSSL),
604 virtual std::iostream& stream()
609 virtual std::string peer_address_to_string() const
611 return peer.address().to_string();
619 typename Protocol::endpoint peer;
620 asio::ssl::stream<typename Protocol::socket> sslStream;
623 SSLIOStreamDevice<Protocol> _d;
624 iostreams::stream< SSLIOStreamDevice<Protocol> > _stream;
627 void ThreadRPCServer(void* parg)
629 // Make this thread recognisable as the RPC listener
630 RenameThread("bitcoin-rpclist");
634 vnThreadsRunning[THREAD_RPCLISTENER]++;
635 ThreadRPCServer2(parg);
636 vnThreadsRunning[THREAD_RPCLISTENER]--;
638 catch (std::exception& e) {
639 vnThreadsRunning[THREAD_RPCLISTENER]--;
640 PrintException(&e, "ThreadRPCServer()");
642 vnThreadsRunning[THREAD_RPCLISTENER]--;
643 PrintException(NULL, "ThreadRPCServer()");
645 printf("ThreadRPCServer exited\n");
648 // Forward declaration required for RPCListen
649 template <typename Protocol, typename SocketAcceptorService>
650 static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
651 ssl::context& context,
653 AcceptedConnection* conn,
654 const boost::system::error_code& error);
657 * Sets up I/O resources to accept and handle a new connection.
659 template <typename Protocol, typename SocketAcceptorService>
660 static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
661 ssl::context& context,
665 AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL);
667 acceptor->async_accept(
668 conn->sslStream.lowest_layer(),
670 boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>,
675 boost::asio::placeholders::error));
679 * Accept and handle incoming connection.
681 template <typename Protocol, typename SocketAcceptorService>
682 static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
683 ssl::context& context,
685 AcceptedConnection* conn,
686 const boost::system::error_code& error)
688 vnThreadsRunning[THREAD_RPCLISTENER]++;
690 // Immediately start accepting new connections, except when we're cancelled or our socket is closed.
691 if (error != asio::error::operation_aborted
692 && acceptor->is_open())
693 RPCListen(acceptor, context, fUseSSL);
695 AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn);
697 // TODO: Actually handle errors
703 // Restrict callers by IP. It is important to
704 // do this before starting client thread, to filter out
705 // certain DoS and misbehaving clients.
707 && !ClientAllowed(tcp_conn->peer.address()))
709 // Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake.
711 conn->stream() << HTTPReply(HTTP_FORBIDDEN, "", false) << std::flush;
715 // start HTTP client thread
716 else if (!NewThread(ThreadRPCServer3, conn)) {
717 printf("Failed to create RPC server client thread\n");
721 vnThreadsRunning[THREAD_RPCLISTENER]--;
724 void ThreadRPCServer2(void* parg)
726 printf("ThreadRPCServer started\n");
728 strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
729 if (mapArgs["-rpcpassword"] == "")
731 unsigned char rand_pwd[32];
732 RAND_bytes(rand_pwd, 32);
733 string strWhatAmI = "To use novacoind";
734 if (mapArgs.count("-server"))
735 strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
736 else if (mapArgs.count("-daemon"))
737 strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
738 uiInterface.ThreadSafeMessageBox(strprintf(
739 _("%s, you must set a rpcpassword in the configuration file:\n %s\n"
740 "It is recommended you use the following random password:\n"
741 "rpcuser=bitcoinrpc\n"
743 "(you do not need to remember this password)\n"
744 "If the file does not exist, create it with owner-readable-only file permissions.\n"),
746 GetConfigFile().string().c_str(),
747 EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()),
748 _("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL);
753 const bool fUseSSL = GetBoolArg("-rpcssl");
755 asio::io_service io_service;
757 ssl::context context(io_service, ssl::context::sslv23);
760 context.set_options(ssl::context::no_sslv2);
762 filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert"));
763 if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile;
764 if (filesystem::exists(pathCertFile)) context.use_certificate_chain_file(pathCertFile.string());
765 else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string().c_str());
767 filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem"));
768 if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile;
769 if (filesystem::exists(pathPKFile)) context.use_private_key_file(pathPKFile.string(), ssl::context::pem);
770 else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str());
772 string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
773 SSL_CTX_set_cipher_list(context.impl(), strCiphers.c_str());
776 // Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets
777 const bool loopback = !mapArgs.count("-rpcallowip");
778 asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any();
779 ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", GetDefaultRPCPort()));
780 boost::system::error_code v6_only_error;
781 boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(io_service));
783 boost::signals2::signal<void ()> StopRequests;
785 bool fListening = false;
789 acceptor->open(endpoint.protocol());
790 acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
792 // Try making the socket dual IPv6/IPv4 (if listening on the "any" address)
793 acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error);
795 acceptor->bind(endpoint);
796 acceptor->listen(socket_base::max_connections);
798 RPCListen(acceptor, context, fUseSSL);
799 // Cancel outstanding listen-requests for this acceptor when shutting down
800 StopRequests.connect(signals2::slot<void ()>(
801 static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get())
806 catch(boost::system::system_error &e)
808 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());
812 // If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately
813 if (!fListening || loopback || v6_only_error)
815 bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any();
816 endpoint.address(bindAddress);
818 acceptor.reset(new ip::tcp::acceptor(io_service));
819 acceptor->open(endpoint.protocol());
820 acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
821 acceptor->bind(endpoint);
822 acceptor->listen(socket_base::max_connections);
824 RPCListen(acceptor, context, fUseSSL);
825 // Cancel outstanding listen-requests for this acceptor when shutting down
826 StopRequests.connect(signals2::slot<void ()>(
827 static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get())
833 catch(boost::system::system_error &e)
835 strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv4: %s"), endpoint.port(), e.what());
839 uiInterface.ThreadSafeMessageBox(strerr, _("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL);
844 vnThreadsRunning[THREAD_RPCLISTENER]--;
846 io_service.run_one();
847 vnThreadsRunning[THREAD_RPCLISTENER]++;
858 JSONRequest() { id = Value::null; }
859 void parse(const Value& valRequest);
862 void JSONRequest::parse(const Value& valRequest)
865 if (valRequest.type() != obj_type)
866 throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
867 const Object& request = valRequest.get_obj();
869 // Parse id now so errors from here on will have the id
870 id = find_value(request, "id");
873 Value valMethod = find_value(request, "method");
874 if (valMethod.type() == null_type)
875 throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
876 if (valMethod.type() != str_type)
877 throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
878 strMethod = valMethod.get_str();
879 if (strMethod != "getwork" && strMethod != "getblocktemplate")
880 printf("ThreadRPCServer method=%s\n", strMethod.c_str());
883 Value valParams = find_value(request, "params");
884 if (valParams.type() == array_type)
885 params = valParams.get_array();
886 else if (valParams.type() == null_type)
889 throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array");
892 static Object JSONRPCExecOne(const Value& req)
900 Value result = tableRPC.execute(jreq.strMethod, jreq.params);
901 rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id);
903 catch (Object& objError)
905 rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id);
907 catch (std::exception& e)
909 rpc_result = JSONRPCReplyObj(Value::null,
910 JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
916 static string JSONRPCExecBatch(const Array& vReq)
919 for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
920 ret.push_back(JSONRPCExecOne(vReq[reqIdx]));
922 return write_string(Value(ret), false) + "\n";
925 static CCriticalSection cs_THREAD_RPCHANDLER;
927 void ThreadRPCServer3(void* parg)
929 // Make this thread recognisable as the RPC handler
930 RenameThread("bitcoin-rpchand");
933 LOCK(cs_THREAD_RPCHANDLER);
934 vnThreadsRunning[THREAD_RPCHANDLER]++;
936 AcceptedConnection *conn = (AcceptedConnection *) parg;
940 if (fShutdown || !fRun)
945 LOCK(cs_THREAD_RPCHANDLER);
946 --vnThreadsRunning[THREAD_RPCHANDLER];
950 map<string, string> mapHeaders;
953 ReadHTTP(conn->stream(), mapHeaders, strRequest);
955 // Check authorization
956 if (mapHeaders.count("authorization") == 0)
958 conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
961 if (!HTTPAuthorized(mapHeaders))
963 printf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string().c_str());
964 /* Deter brute-forcing short passwords.
965 If this results in a DOS the user really
966 shouldn't have their RPC port exposed.*/
967 if (mapArgs["-rpcpassword"].size() < 20)
970 conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
973 if (mapHeaders["connection"] == "close")
981 if (!read_string(strRequest, valRequest))
982 throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
987 if (valRequest.type() == obj_type) {
988 jreq.parse(valRequest);
990 Value result = tableRPC.execute(jreq.strMethod, jreq.params);
993 strReply = JSONRPCReply(result, Value::null, jreq.id);
996 } else if (valRequest.type() == array_type)
997 strReply = JSONRPCExecBatch(valRequest.get_array());
999 throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
1001 conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush;
1003 catch (Object& objError)
1005 ErrorReply(conn->stream(), objError, jreq.id);
1008 catch (std::exception& e)
1010 ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
1017 LOCK(cs_THREAD_RPCHANDLER);
1018 vnThreadsRunning[THREAD_RPCHANDLER]--;
1022 json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array ¶ms) const
1025 const CRPCCommand *pcmd = tableRPC[strMethod];
1027 throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
1029 // Observe safe mode
1030 string strWarning = GetWarnings("rpc");
1031 if (strWarning != "" && !GetBoolArg("-disablesafemode") &&
1033 throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
1041 result = pcmd->actor(params, false);
1043 LOCK2(cs_main, pwalletMain->cs_wallet);
1044 result = pcmd->actor(params, false);
1049 catch (std::exception& e)
1051 throw JSONRPCError(RPC_MISC_ERROR, e.what());
1056 Object CallRPC(const string& strMethod, const Array& params)
1058 if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
1059 throw runtime_error(strprintf(
1060 _("You must set rpcpassword=<password> in the configuration file:\n%s\n"
1061 "If the file does not exist, create it with owner-readable-only file permissions."),
1062 GetConfigFile().string().c_str()));
1064 // Connect to localhost
1065 bool fUseSSL = GetBoolArg("-rpcssl");
1066 asio::io_service io_service;
1067 ssl::context context(io_service, ssl::context::sslv23);
1068 context.set_options(ssl::context::no_sslv2);
1069 asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context);
1070 SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL);
1071 iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d);
1072 if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(GetDefaultRPCPort()))))
1073 throw runtime_error("couldn't connect to server");
1075 // HTTP basic authentication
1076 string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
1077 map<string, string> mapRequestHeaders;
1078 mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
1081 string strRequest = JSONRPCRequest(strMethod, params, 1);
1082 string strPost = HTTPPost(strRequest, mapRequestHeaders);
1083 stream << strPost << std::flush;
1086 map<string, string> mapHeaders;
1088 int nStatus = ReadHTTP(stream, mapHeaders, strReply);
1089 if (nStatus == HTTP_UNAUTHORIZED)
1090 throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
1091 else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR)
1092 throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
1093 else if (strReply.empty())
1094 throw runtime_error("no response from server");
1098 if (!read_string(strReply, valReply))
1099 throw runtime_error("couldn't parse reply from server");
1100 const Object& reply = valReply.get_obj();
1102 throw runtime_error("expected reply to have result, error and id properties");
1110 template<typename T>
1111 void ConvertTo(Value& value, bool fAllowNull=false)
1113 if (fAllowNull && value.type() == null_type)
1115 if (value.type() == str_type)
1117 // reinterpret string as unquoted json value
1119 string strJSON = value.get_str();
1120 if (!read_string(strJSON, value2))
1121 throw runtime_error(string("Error parsing JSON:")+strJSON);
1122 ConvertTo<T>(value2, fAllowNull);
1127 value = value.get_value<T>();
1131 // Convert strings to command-specific RPC representation
1132 Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
1135 BOOST_FOREACH(const std::string ¶m, strParams)
1136 params.push_back(param);
1138 int n = params.size();
1141 // Special case non-string parameter types
1143 if (strMethod == "stop" && n > 0) ConvertTo<bool>(params[0]);
1144 if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);
1145 if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]);
1146 if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1147 if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1148 if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
1149 if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);
1150 if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]);
1151 if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]);
1152 if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1153 if (strMethod == "getblock" && n > 1) ConvertTo<bool>(params[1]);
1154 if (strMethod == "getblockbynumber" && n > 0) ConvertTo<boost::int64_t>(params[0]);
1155 if (strMethod == "getblockbynumber" && n > 1) ConvertTo<bool>(params[1]);
1156 if (strMethod == "getblockhash" && n > 0) ConvertTo<boost::int64_t>(params[0]);
1157 if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]);
1158 if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]);
1159 if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]);
1160 if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]);
1161 if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1162 if (strMethod == "listtransactions" && n > 2) ConvertTo<boost::int64_t>(params[2]);
1163 if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]);
1164 if (strMethod == "walletpassphrase" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1165 if (strMethod == "walletpassphrase" && n > 2) ConvertTo<bool>(params[2]);
1166 if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]);
1167 if (strMethod == "listsinceblock" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1168 if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]);
1169 if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]);
1170 if (strMethod == "reservebalance" && n > 0) ConvertTo<bool>(params[0]);
1171 if (strMethod == "reservebalance" && n > 1) ConvertTo<double>(params[1]);
1172 if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
1173 if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]);
1174 if (strMethod == "listunspent" && n > 0) ConvertTo<boost::int64_t>(params[0]);
1175 if (strMethod == "listunspent" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1176 if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]);
1177 if (strMethod == "getrawtransaction" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1178 if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]);
1179 if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]);
1180 if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1], true);
1181 if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2], true);
1186 int CommandLineRPC(int argc, char *argv[])
1193 while (argc > 1 && IsSwitchChar(argv[1][0]))
1201 throw runtime_error("too few parameters");
1202 string strMethod = argv[1];
1204 // Parameters default to strings
1205 std::vector<std::string> strParams(&argv[2], &argv[argc]);
1206 Array params = RPCConvertValues(strMethod, strParams);
1209 Object reply = CallRPC(strMethod, params);
1212 const Value& result = find_value(reply, "result");
1213 const Value& error = find_value(reply, "error");
1215 if (error.type() != null_type)
1218 strPrint = "error: " + write_string(error, false);
1219 int code = find_value(error.get_obj(), "code").get_int();
1225 if (result.type() == null_type)
1227 else if (result.type() == str_type)
1228 strPrint = result.get_str();
1230 strPrint = write_string(result, true);
1233 catch (std::exception& e)
1235 strPrint = string("error: ") + e.what();
1240 PrintException(NULL, "CommandLineRPC()");
1245 fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
1254 int main(int argc, char *argv[])
1257 // Turn off Microsoft heap dump noise
1258 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
1259 _CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
1261 setbuf(stdin, NULL);
1262 setbuf(stdout, NULL);
1263 setbuf(stderr, NULL);
1267 if (argc >= 2 && string(argv[1]) == "-server")
1269 printf("server ready\n");
1270 ThreadRPCServer(NULL);
1274 return CommandLineRPC(argc, argv);
1277 catch (std::exception& e) {
1278 PrintException(&e, "main()");
1280 PrintException(NULL, "main()");
1286 const CRPCTable tableRPC;