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_t 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_t nAmount = roundint64(dAmount * COIN);
103 if (!MoneyRange(nAmount))
104 throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
108 Value ValueFromAmount(int64_t 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));
125 // Utilities: convert hex-encoded Values
126 // (throws error if not hex).
128 uint256 ParseHashV(const Value& v, string strName)
131 if (v.type() == str_type)
132 strHex = v.get_str();
133 if (!IsHex(strHex)) // Note: IsHex("") is false
134 throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
136 result.SetHex(strHex);
140 uint256 ParseHashO(const Object& o, string strKey)
142 return ParseHashV(find_value(o, strKey), strKey);
145 vector<unsigned char> ParseHexV(const Value& v, string strName)
148 if (v.type() == str_type)
149 strHex = v.get_str();
151 throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
152 return ParseHex(strHex);
155 vector<unsigned char> ParseHexO(const Object& o, string strKey)
157 return ParseHexV(find_value(o, strKey), strKey);
162 /// Note: This interface may still be subject to change.
165 string CRPCTable::help(string strCommand) const
168 set<rpcfn_type> setDone;
169 for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)
171 const CRPCCommand *pcmd = mi->second;
172 string strMethod = mi->first;
173 // We already filter duplicates, but these deprecated screw up the sort order
174 if (strMethod.find("label") != string::npos)
176 if (strCommand != "" && strMethod != strCommand)
181 rpcfn_type pfn = pcmd->actor;
182 if (setDone.insert(pfn).second)
183 (*pfn)(params, true);
185 catch (std::exception& e)
187 // Help text is returned in an exception
188 string strHelp = string(e.what());
189 if (strCommand == "")
190 if (strHelp.find('\n') != string::npos)
191 strHelp = strHelp.substr(0, strHelp.find('\n'));
192 strRet += strHelp + "\n";
196 strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
197 strRet = strRet.substr(0,strRet.size()-1);
201 Value help(const Array& params, bool fHelp)
203 if (fHelp || params.size() > 1)
206 "List commands, or get help for a command.");
209 if (params.size() > 0)
210 strCommand = params[0].get_str();
212 return tableRPC.help(strCommand);
216 Value stop(const Array& params, bool fHelp)
218 if (fHelp || params.size() > 1)
221 "<detach> is true or false to detach the database or not for this stop only\n"
222 "Stop NovaCoin server (and possibly override the detachdb config value).");
223 // Shutdown will take long enough that the response should get back
224 if (params.size() > 0)
225 bitdb.SetDetach(params[0].get_bool());
227 return "NovaCoin server stopping";
237 static const CRPCCommand vRPCCommands[] =
238 { // name function safemd unlocked
239 // ------------------------ ----------------------- ------ --------
240 { "help", &help, true, true },
241 { "stop", &stop, true, true },
242 { "getbestblockhash", &getbestblockhash, true, false },
243 { "getblockcount", &getblockcount, true, false },
244 { "getconnectioncount", &getconnectioncount, true, false },
245 { "getaddrmaninfo", &getaddrmaninfo, true, false },
246 { "getpeerinfo", &getpeerinfo, true, false },
247 { "addnode", &addnode, true, true },
248 { "getaddednodeinfo", &getaddednodeinfo, true, true },
249 { "getdifficulty", &getdifficulty, true, false },
250 { "getinfo", &getinfo, true, false },
251 { "getsubsidy", &getsubsidy, true, false },
252 { "getmininginfo", &getmininginfo, true, false },
253 { "scaninput", &scaninput, true, true },
254 { "getnewaddress", &getnewaddress, true, false },
255 { "getnettotals", &getnettotals, true, true },
256 { "ntptime", &ntptime, true, true },
257 { "getaccountaddress", &getaccountaddress, true, false },
258 { "setaccount", &setaccount, true, false },
259 { "getaccount", &getaccount, false, false },
260 { "getaddressesbyaccount", &getaddressesbyaccount, true, false },
261 { "sendtoaddress", &sendtoaddress, false, false },
262 { "mergecoins", &mergecoins, false, false },
263 { "getreceivedbyaddress", &getreceivedbyaddress, false, false },
264 { "getreceivedbyaccount", &getreceivedbyaccount, false, false },
265 { "listreceivedbyaddress", &listreceivedbyaddress, false, false },
266 { "listreceivedbyaccount", &listreceivedbyaccount, false, false },
267 { "backupwallet", &backupwallet, true, false },
268 { "keypoolrefill", &keypoolrefill, true, false },
269 { "keypoolreset", &keypoolreset, true, false },
270 { "walletpassphrase", &walletpassphrase, true, false },
271 { "walletpassphrasechange", &walletpassphrasechange, false, false },
272 { "walletlock", &walletlock, true, false },
273 { "encryptwallet", &encryptwallet, false, false },
274 { "validateaddress", &validateaddress, true, false },
275 { "getbalance", &getbalance, false, false },
276 { "move", &movecmd, false, false },
277 { "sendfrom", &sendfrom, false, false },
278 { "sendmany", &sendmany, false, false },
279 { "addmultisigaddress", &addmultisigaddress, false, false },
280 { "addredeemscript", &addredeemscript, false, false },
281 { "getrawmempool", &getrawmempool, true, false },
282 { "getblock", &getblock, false, false },
283 { "getblockbynumber", &getblockbynumber, false, false },
284 { "dumpblock", &dumpblock, false, false },
285 { "dumpblockbynumber", &dumpblockbynumber, false, false },
286 { "getblockhash", &getblockhash, false, false },
287 { "gettransaction", &gettransaction, false, false },
288 { "listtransactions", &listtransactions, false, false },
289 { "listaddressgroupings", &listaddressgroupings, false, false },
290 { "signmessage", &signmessage, false, false },
291 { "verifymessage", &verifymessage, false, false },
292 { "getwork", &getwork, true, false },
293 { "getworkex", &getworkex, true, false },
294 { "listaccounts", &listaccounts, false, false },
295 { "settxfee", &settxfee, false, false },
296 { "getblocktemplate", &getblocktemplate, true, false },
297 { "submitblock", &submitblock, false, false },
298 { "listsinceblock", &listsinceblock, false, false },
299 { "dumpprivkey", &dumpprivkey, false, false },
300 { "dumpwallet", &dumpwallet, true, false },
301 { "importwallet", &importwallet, false, false },
302 { "importprivkey", &importprivkey, false, false },
303 { "importaddress", &importaddress, false, true },
304 { "removeaddress", &removeaddress, false, true },
305 { "listunspent", &listunspent, false, false },
306 { "getrawtransaction", &getrawtransaction, false, false },
307 { "createrawtransaction", &createrawtransaction, false, false },
308 { "decoderawtransaction", &decoderawtransaction, false, false },
309 { "createmultisig", &createmultisig, false, false },
310 { "decodescript", &decodescript, false, false },
311 { "signrawtransaction", &signrawtransaction, false, false },
312 { "sendrawtransaction", &sendrawtransaction, false, false },
313 { "getcheckpoint", &getcheckpoint, true, false },
314 { "reservebalance", &reservebalance, false, true},
315 { "checkwallet", &checkwallet, false, true},
316 { "repairwallet", &repairwallet, false, true},
317 { "resendtx", &resendtx, false, true},
318 { "makekeypair", &makekeypair, false, true},
319 { "newmalleablekey", &newmalleablekey, false, false},
320 { "adjustmalleablekey", &adjustmalleablekey, false, false},
321 { "adjustmalleablepubkey", &adjustmalleablepubkey, false, false},
322 { "listmalleableviews", &listmalleableviews, false, false},
323 { "dumpmalleablekey", &dumpmalleablekey, false, false},
324 { "encryptdata", &encryptdata, false, false },
325 { "decryptdata", &decryptdata, false, false },
326 { "encryptmessage", &encryptmessage, false, false },
327 { "decryptmessage", &decryptmessage, false, false },
328 { "sendalert", &sendalert, false, false},
331 CRPCTable::CRPCTable()
334 for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++)
336 const CRPCCommand *pcmd;
338 pcmd = &vRPCCommands[vcidx];
339 mapCommands[pcmd->name] = pcmd;
343 const CRPCCommand *CRPCTable::operator[](string name) const
345 map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
346 if (it == mapCommands.end())
354 // This ain't Apache. We're just using HTTP header for the length field
355 // and to be compatible with other JSON-RPC implementations.
358 string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
361 s << "POST / HTTP/1.1\r\n"
362 << "User-Agent: novacoin-json-rpc/" << FormatFullVersion() << "\r\n"
363 << "Host: 127.0.0.1\r\n"
364 << "Content-Type: application/json\r\n"
365 << "Content-Length: " << strMsg.size() << "\r\n"
366 << "Connection: close\r\n"
367 << "Accept: application/json\r\n";
368 BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders)
369 s << item.first << ": " << item.second << "\r\n";
370 s << "\r\n" << strMsg;
377 return DateTimeStrFormat("%a, %d %b %Y %H:%M:%S +0000", GetTime());
380 static string HTTPReply(int nStatus, const string& strMsg, bool keepalive)
382 if (nStatus == HTTP_UNAUTHORIZED)
383 return strprintf("HTTP/1.0 401 Authorization Required\r\n"
385 "Server: novacoin-json-rpc/%s\r\n"
386 "WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
387 "Content-Type: text/html\r\n"
388 "Content-Length: 296\r\n"
390 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
391 "\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
394 "<TITLE>Error</TITLE>\r\n"
395 "<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
397 "<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
398 "</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str());
400 if (nStatus == HTTP_OK) cStatus = "OK";
401 else if (nStatus == HTTP_BAD_REQUEST) cStatus = "Bad Request";
402 else if (nStatus == HTTP_FORBIDDEN) cStatus = "Forbidden";
403 else if (nStatus == HTTP_NOT_FOUND) cStatus = "Not Found";
404 else if (nStatus == HTTP_INTERNAL_SERVER_ERROR) cStatus = "Internal Server Error";
410 "Content-Length: %" PRIszu "\r\n"
411 "Content-Type: application/json\r\n"
412 "Server: novacoin-json-rpc/%s\r\n"
417 rfc1123Time().c_str(),
418 keepalive ? "keep-alive" : "close",
420 FormatFullVersion().c_str(),
424 int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto)
427 getline(stream, str);
428 vector<string> vWords;
429 boost::split(vWords, str, boost::is_any_of(" "));
430 if (vWords.size() < 2)
431 return HTTP_INTERNAL_SERVER_ERROR;
433 const char *ver = strstr(str.c_str(), "HTTP/1.");
436 return atoi(vWords[1].c_str());
439 int ReadHTTPHeader(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
445 std::getline(stream, str);
446 if (str.empty() || str == "\r")
448 string::size_type nColon = str.find(":");
449 if (nColon != string::npos)
451 string strHeader = str.substr(0, nColon);
452 boost::trim(strHeader);
453 boost::to_lower(strHeader);
454 string strValue = str.substr(nColon+1);
455 boost::trim(strValue);
456 mapHeadersRet[strHeader] = strValue;
457 if (strHeader == "content-length")
458 nLen = atoi(strValue.c_str());
464 int ReadHTTP(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet)
466 mapHeadersRet.clear();
471 int nStatus = ReadHTTPStatus(stream, nProto);
474 int nLen = ReadHTTPHeader(stream, mapHeadersRet);
475 if (nLen < 0 || nLen > (int)MAX_SIZE)
476 return HTTP_INTERNAL_SERVER_ERROR;
481 vector<char> vch(nLen);
482 stream.read(&vch[0], nLen);
483 strMessageRet = string(vch.begin(), vch.end());
486 string sConHdr = mapHeadersRet["connection"];
488 if ((sConHdr != "close") && (sConHdr != "keep-alive"))
491 mapHeadersRet["connection"] = "keep-alive";
493 mapHeadersRet["connection"] = "close";
499 bool HTTPAuthorized(map<string, string>& mapHeaders)
501 string strAuth = mapHeaders["authorization"];
502 if (strAuth.substr(0,6) != "Basic ")
504 string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
505 string strUserPass = DecodeBase64(strUserPass64);
506 return TimingResistantEqual(strUserPass, strRPCUserColonPass);
510 // JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
511 // but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
512 // unspecified (HTTP errors and contents of 'error').
514 // 1.0 spec: http://json-rpc.org/wiki/specification
515 // 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
516 // http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
519 string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
522 request.push_back(Pair("method", strMethod));
523 request.push_back(Pair("params", params));
524 request.push_back(Pair("id", id));
525 return write_string(Value(request), false) + "\n";
528 Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id)
531 if (error.type() != null_type)
532 reply.push_back(Pair("result", Value::null));
534 reply.push_back(Pair("result", result));
535 reply.push_back(Pair("error", error));
536 reply.push_back(Pair("id", id));
540 string JSONRPCReply(const Value& result, const Value& error, const Value& id)
542 Object reply = JSONRPCReplyObj(result, error, id);
543 return write_string(Value(reply), false) + "\n";
546 void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
548 // Send error reply from json-rpc error object
549 int nStatus = HTTP_INTERNAL_SERVER_ERROR;
550 int code = find_value(objError, "code").get_int();
551 if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST;
552 else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND;
553 string strReply = JSONRPCReply(Value::null, objError, id);
554 stream << HTTPReply(nStatus, strReply, false) << std::flush;
557 bool ClientAllowed(const boost::asio::ip::address& address)
559 // Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses
561 && (address.to_v6().is_v4_compatible()
562 || address.to_v6().is_v4_mapped()))
563 return ClientAllowed(address.to_v6().to_v4());
565 if (address == asio::ip::address_v4::loopback()
566 || address == asio::ip::address_v6::loopback()
568 // Check whether IPv4 addresses match 127.0.0.0/8 (loopback subnet)
569 && (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000))
572 const string strAddress = address.to_string();
573 const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
574 BOOST_FOREACH(string strAllow, vAllow)
575 if (WildcardMatch(strAddress, strAllow))
581 // IOStream device that speaks SSL but can also speak non-SSL
583 template <typename Protocol>
584 class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {
586 SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn)
589 fNeedHandshake = fUseSSLIn;
592 void handshake(ssl::stream_base::handshake_type role)
594 if (!fNeedHandshake) return;
595 fNeedHandshake = false;
596 stream.handshake(role);
598 std::streamsize read(char* s, std::streamsize n)
600 handshake(ssl::stream_base::server); // HTTPS servers read first
601 if (fUseSSL) return stream.read_some(asio::buffer(s, n));
602 return stream.next_layer().read_some(asio::buffer(s, n));
604 std::streamsize write(const char* s, std::streamsize n)
606 handshake(ssl::stream_base::client); // HTTPS clients write first
607 if (fUseSSL) return asio::write(stream, asio::buffer(s, n));
608 return asio::write(stream.next_layer(), asio::buffer(s, n));
610 bool connect(const std::string& server, const std::string& port)
612 ip::tcp::resolver resolver(stream.get_io_service());
613 ip::tcp::resolver::query query(server.c_str(), port.c_str());
614 ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
615 ip::tcp::resolver::iterator end;
616 boost::system::error_code error = asio::error::host_not_found;
617 while (error && endpoint_iterator != end)
619 stream.lowest_layer().close();
620 stream.lowest_layer().connect(*endpoint_iterator++, error);
630 SSLIOStreamDevice& operator=(SSLIOStreamDevice const&);
631 asio::ssl::stream<typename Protocol::socket>& stream;
634 class AcceptedConnection
637 virtual ~AcceptedConnection() {}
639 virtual std::iostream& stream() = 0;
640 virtual std::string peer_address_to_string() const = 0;
641 virtual void close() = 0;
644 template <typename Protocol>
645 class AcceptedConnectionImpl : public AcceptedConnection
648 AcceptedConnectionImpl(
649 asio::io_service& io_service,
650 ssl::context &context,
652 sslStream(io_service, context),
653 _d(sslStream, fUseSSL),
658 virtual std::iostream& stream()
663 virtual std::string peer_address_to_string() const
665 return peer.address().to_string();
673 typename Protocol::endpoint peer;
674 asio::ssl::stream<typename Protocol::socket> sslStream;
677 SSLIOStreamDevice<Protocol> _d;
678 iostreams::stream< SSLIOStreamDevice<Protocol> > _stream;
681 void ThreadRPCServer(void* parg)
683 // Make this thread recognisable as the RPC listener
684 RenameThread("novacoin-rpclist");
688 vnThreadsRunning[THREAD_RPCLISTENER]++;
689 ThreadRPCServer2(parg);
690 vnThreadsRunning[THREAD_RPCLISTENER]--;
692 catch (std::exception& e) {
693 vnThreadsRunning[THREAD_RPCLISTENER]--;
694 PrintException(&e, "ThreadRPCServer()");
696 vnThreadsRunning[THREAD_RPCLISTENER]--;
697 PrintException(NULL, "ThreadRPCServer()");
699 printf("ThreadRPCServer exited\n");
702 // Forward declaration required for RPCListen
703 template <typename Protocol, typename SocketAcceptorService>
704 static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
705 ssl::context& context,
707 AcceptedConnection* conn,
708 const boost::system::error_code& error);
711 * Sets up I/O resources to accept and handle a new connection.
713 template <typename Protocol, typename SocketAcceptorService>
714 static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
715 ssl::context& context,
719 AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL);
721 acceptor->async_accept(
722 conn->sslStream.lowest_layer(),
724 boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>,
729 boost::asio::placeholders::error));
733 * Accept and handle incoming connection.
735 template <typename Protocol, typename SocketAcceptorService>
736 static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
737 ssl::context& context,
739 AcceptedConnection* conn,
740 const boost::system::error_code& error)
742 vnThreadsRunning[THREAD_RPCLISTENER]++;
744 // Immediately start accepting new connections, except when we're cancelled or our socket is closed.
745 if (error != asio::error::operation_aborted
746 && acceptor->is_open())
747 RPCListen(acceptor, context, fUseSSL);
749 AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn);
751 // TODO: Actually handle errors
757 // Restrict callers by IP. It is important to
758 // do this before starting client thread, to filter out
759 // certain DoS and misbehaving clients.
761 && !ClientAllowed(tcp_conn->peer.address()))
763 // Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake.
765 conn->stream() << HTTPReply(HTTP_FORBIDDEN, "", false) << std::flush;
769 // start HTTP client thread
770 else if (!NewThread(ThreadRPCServer3, conn)) {
771 printf("Failed to create RPC server client thread\n");
775 vnThreadsRunning[THREAD_RPCLISTENER]--;
778 void ThreadRPCServer2(void* parg)
780 printf("ThreadRPCServer started\n");
782 strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
783 if (mapArgs["-rpcpassword"] == "")
785 unsigned char rand_pwd[32];
786 RAND_bytes(rand_pwd, 32);
787 string strWhatAmI = "To use novacoind";
788 if (mapArgs.count("-server"))
789 strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
790 else if (mapArgs.count("-daemon"))
791 strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
792 uiInterface.ThreadSafeMessageBox(strprintf(
793 _("%s, you must set a rpcpassword in the configuration file:\n %s\n"
794 "It is recommended you use the following random password:\n"
795 "rpcuser=novacoinrpc\n"
797 "(you do not need to remember this password)\n"
798 "If the file does not exist, create it with owner-readable-only file permissions.\n"),
800 GetConfigFile().string().c_str(),
801 EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()),
802 _("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL);
807 const bool fUseSSL = GetBoolArg("-rpcssl");
809 asio::io_service io_service;
811 ssl::context context(io_service, ssl::context::sslv23);
814 context.set_options(ssl::context::no_sslv2);
816 filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert"));
817 if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile;
818 if (filesystem::exists(pathCertFile)) context.use_certificate_chain_file(pathCertFile.string());
819 else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string().c_str());
821 filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem"));
822 if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile;
823 if (filesystem::exists(pathPKFile)) context.use_private_key_file(pathPKFile.string(), ssl::context::pem);
824 else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str());
826 string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
827 SSL_CTX_set_cipher_list(context.impl(), strCiphers.c_str());
830 // Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets
831 const bool loopback = !mapArgs.count("-rpcallowip");
832 asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any();
833 ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", GetDefaultRPCPort()));
834 boost::system::error_code v6_only_error;
835 boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(io_service));
837 boost::signals2::signal<void ()> StopRequests;
839 bool fListening = false;
843 acceptor->open(endpoint.protocol());
844 acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
846 // Try making the socket dual IPv6/IPv4 (if listening on the "any" address)
847 acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error);
849 acceptor->bind(endpoint);
850 acceptor->listen(socket_base::max_connections);
852 RPCListen(acceptor, context, fUseSSL);
853 // Cancel outstanding listen-requests for this acceptor when shutting down
854 StopRequests.connect(signals2::slot<void ()>(
855 static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get())
860 catch(boost::system::system_error &e)
862 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());
866 // If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately
867 if (!fListening || loopback || v6_only_error)
869 bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any();
870 endpoint.address(bindAddress);
872 acceptor.reset(new ip::tcp::acceptor(io_service));
873 acceptor->open(endpoint.protocol());
874 acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
875 acceptor->bind(endpoint);
876 acceptor->listen(socket_base::max_connections);
878 RPCListen(acceptor, context, fUseSSL);
879 // Cancel outstanding listen-requests for this acceptor when shutting down
880 StopRequests.connect(signals2::slot<void ()>(
881 static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get())
887 catch(boost::system::system_error &e)
889 strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv4: %s"), endpoint.port(), e.what());
893 uiInterface.ThreadSafeMessageBox(strerr, _("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL);
898 vnThreadsRunning[THREAD_RPCLISTENER]--;
900 io_service.run_one();
901 vnThreadsRunning[THREAD_RPCLISTENER]++;
912 JSONRequest() { id = Value::null; }
913 void parse(const Value& valRequest);
916 void JSONRequest::parse(const Value& valRequest)
919 if (valRequest.type() != obj_type)
920 throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
921 const Object& request = valRequest.get_obj();
923 // Parse id now so errors from here on will have the id
924 id = find_value(request, "id");
927 Value valMethod = find_value(request, "method");
928 if (valMethod.type() == null_type)
929 throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
930 if (valMethod.type() != str_type)
931 throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
932 strMethod = valMethod.get_str();
933 if (strMethod != "getwork" && strMethod != "getblocktemplate")
934 printf("ThreadRPCServer method=%s\n", strMethod.c_str());
937 Value valParams = find_value(request, "params");
938 if (valParams.type() == array_type)
939 params = valParams.get_array();
940 else if (valParams.type() == null_type)
943 throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array");
946 static Object JSONRPCExecOne(const Value& req)
954 Value result = tableRPC.execute(jreq.strMethod, jreq.params);
955 rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id);
957 catch (Object& objError)
959 rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id);
961 catch (std::exception& e)
963 rpc_result = JSONRPCReplyObj(Value::null,
964 JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
970 static string JSONRPCExecBatch(const Array& vReq)
973 for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
974 ret.push_back(JSONRPCExecOne(vReq[reqIdx]));
976 return write_string(Value(ret), false) + "\n";
979 static CCriticalSection cs_THREAD_RPCHANDLER;
981 void ThreadRPCServer3(void* parg)
983 // Make this thread recognisable as the RPC handler
984 RenameThread("novacoin-rpchand");
987 LOCK(cs_THREAD_RPCHANDLER);
988 vnThreadsRunning[THREAD_RPCHANDLER]++;
990 AcceptedConnection *conn = (AcceptedConnection *) parg;
995 if (fShutdown || !fRun)
1000 LOCK(cs_THREAD_RPCHANDLER);
1001 --vnThreadsRunning[THREAD_RPCHANDLER];
1005 map<string, string> mapHeaders;
1008 ReadHTTP(conn->stream(), mapHeaders, strRequest);
1010 // Check authorization
1011 if (mapHeaders.count("authorization") == 0)
1013 conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
1016 if (!HTTPAuthorized(mapHeaders))
1018 printf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string().c_str());
1019 /* Deter brute-forcing short passwords.
1020 If this results in a DOS the user really
1021 shouldn't have their RPC port exposed.*/
1022 if (mapArgs["-rpcpassword"].size() < 20)
1025 conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
1028 if (mapHeaders["connection"] == "close")
1036 if (!read_string(strRequest, valRequest))
1037 throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
1041 // singleton request
1042 if (valRequest.type() == obj_type) {
1043 jreq.parse(valRequest);
1045 Value result = tableRPC.execute(jreq.strMethod, jreq.params);
1048 strReply = JSONRPCReply(result, Value::null, jreq.id);
1050 // array of requests
1051 } else if (valRequest.type() == array_type)
1052 strReply = JSONRPCExecBatch(valRequest.get_array());
1054 throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
1056 conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush;
1058 catch (Object& objError)
1060 ErrorReply(conn->stream(), objError, jreq.id);
1063 catch (std::exception& e)
1065 ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
1072 LOCK(cs_THREAD_RPCHANDLER);
1073 vnThreadsRunning[THREAD_RPCHANDLER]--;
1077 json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array ¶ms) const
1080 const CRPCCommand *pcmd = tableRPC[strMethod];
1082 throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
1084 // Observe safe mode
1085 string strWarning = GetWarnings("rpc");
1086 if (strWarning != "" && !GetBoolArg("-disablesafemode") &&
1088 throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
1096 result = pcmd->actor(params, false);
1098 LOCK2(cs_main, pwalletMain->cs_wallet);
1099 result = pcmd->actor(params, false);
1104 catch (std::exception& e)
1106 throw JSONRPCError(RPC_MISC_ERROR, e.what());
1111 Object CallRPC(const string& strMethod, const Array& params)
1113 if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
1114 throw runtime_error(strprintf(
1115 _("You must set rpcpassword=<password> in the configuration file:\n%s\n"
1116 "If the file does not exist, create it with owner-readable-only file permissions."),
1117 GetConfigFile().string().c_str()));
1119 // Connect to localhost
1120 bool fUseSSL = GetBoolArg("-rpcssl");
1121 asio::io_service io_service;
1122 ssl::context context(io_service, ssl::context::sslv23);
1123 context.set_options(ssl::context::no_sslv2);
1124 asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context);
1125 SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL);
1126 iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d);
1127 if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(GetDefaultRPCPort()))))
1128 throw runtime_error("couldn't connect to server");
1130 // HTTP basic authentication
1131 string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
1132 map<string, string> mapRequestHeaders;
1133 mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
1136 string strRequest = JSONRPCRequest(strMethod, params, 1);
1137 string strPost = HTTPPost(strRequest, mapRequestHeaders);
1138 stream << strPost << std::flush;
1141 map<string, string> mapHeaders;
1143 int nStatus = ReadHTTP(stream, mapHeaders, strReply);
1144 if (nStatus == HTTP_UNAUTHORIZED)
1145 throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
1146 else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR)
1147 throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
1148 else if (strReply.empty())
1149 throw runtime_error("no response from server");
1153 if (!read_string(strReply, valReply))
1154 throw runtime_error("couldn't parse reply from server");
1155 const Object& reply = valReply.get_obj();
1157 throw runtime_error("expected reply to have result, error and id properties");
1165 template<typename T>
1166 void ConvertTo(Value& value, bool fAllowNull=false)
1168 if (fAllowNull && value.type() == null_type)
1170 if (value.type() == str_type)
1172 // reinterpret string as unquoted json value
1174 string strJSON = value.get_str();
1175 if (!read_string(strJSON, value2))
1176 throw runtime_error(string("Error parsing JSON:")+strJSON);
1177 ConvertTo<T>(value2, fAllowNull);
1182 value = value.get_value<T>();
1186 // Convert strings to command-specific RPC representation
1187 Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
1190 BOOST_FOREACH(const std::string ¶m, strParams)
1191 params.push_back(param);
1193 size_t n = params.size();
1196 // Special case non-string parameter types
1198 if (strMethod == "stop" && n > 0) ConvertTo<bool>(params[0]);
1199 if (strMethod == "getaddednodeinfo" && n > 0) ConvertTo<bool>(params[0]);
1200 if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);
1201 if (strMethod == "mergecoins" && n > 0) ConvertTo<double>(params[0]);
1202 if (strMethod == "mergecoins" && n > 1) ConvertTo<double>(params[1]);
1203 if (strMethod == "mergecoins" && n > 2) ConvertTo<double>(params[2]);
1204 if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]);
1205 if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<int64_t>(params[1]);
1206 if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<int64_t>(params[1]);
1207 if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<int64_t>(params[0]);
1208 if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);
1209 if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<int64_t>(params[0]);
1210 if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]);
1211 if (strMethod == "getbalance" && n > 1) ConvertTo<int64_t>(params[1]);
1212 if (strMethod == "getblock" && n > 1) ConvertTo<bool>(params[1]);
1213 if (strMethod == "getblockbynumber" && n > 0) ConvertTo<int64_t>(params[0]);
1214 if (strMethod == "dumpblockbynumber" && n > 0) ConvertTo<int64_t>(params[0]);
1215 if (strMethod == "getblockbynumber" && n > 1) ConvertTo<bool>(params[1]);
1216 if (strMethod == "getblockhash" && n > 0) ConvertTo<int64_t>(params[0]);
1217 if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]);
1218 if (strMethod == "move" && n > 3) ConvertTo<int64_t>(params[3]);
1219 if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]);
1220 if (strMethod == "sendfrom" && n > 3) ConvertTo<int64_t>(params[3]);
1221 if (strMethod == "listtransactions" && n > 1) ConvertTo<int64_t>(params[1]);
1222 if (strMethod == "listtransactions" && n > 2) ConvertTo<int64_t>(params[2]);
1223 if (strMethod == "listaccounts" && n > 0) ConvertTo<int64_t>(params[0]);
1224 if (strMethod == "walletpassphrase" && n > 1) ConvertTo<int64_t>(params[1]);
1225 if (strMethod == "walletpassphrase" && n > 2) ConvertTo<bool>(params[2]);
1226 if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]);
1227 if (strMethod == "listsinceblock" && n > 1) ConvertTo<int64_t>(params[1]);
1229 if (strMethod == "scaninput" && n > 0) ConvertTo<Object>(params[0]);
1231 if (strMethod == "sendalert" && n > 2) ConvertTo<int64_t>(params[2]);
1232 if (strMethod == "sendalert" && n > 3) ConvertTo<int64_t>(params[3]);
1233 if (strMethod == "sendalert" && n > 4) ConvertTo<int64_t>(params[4]);
1234 if (strMethod == "sendalert" && n > 5) ConvertTo<int64_t>(params[5]);
1235 if (strMethod == "sendalert" && n > 6) ConvertTo<int64_t>(params[6]);
1237 if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]);
1238 if (strMethod == "sendmany" && n > 2) ConvertTo<int64_t>(params[2]);
1239 if (strMethod == "reservebalance" && n > 0) ConvertTo<bool>(params[0]);
1240 if (strMethod == "reservebalance" && n > 1) ConvertTo<double>(params[1]);
1241 if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<int64_t>(params[0]);
1242 if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]);
1243 if (strMethod == "listunspent" && n > 0) ConvertTo<int64_t>(params[0]);
1244 if (strMethod == "listunspent" && n > 1) ConvertTo<int64_t>(params[1]);
1245 if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]);
1246 if (strMethod == "getrawtransaction" && n > 1) ConvertTo<int64_t>(params[1]);
1247 if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]);
1248 if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]);
1249 if (strMethod == "createmultisig" && n > 0) ConvertTo<int64_t>(params[0]);
1250 if (strMethod == "createmultisig" && n > 1) ConvertTo<Array>(params[1]);
1251 if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1], true);
1252 if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2], true);
1253 if (strMethod == "keypoolrefill" && n > 0) ConvertTo<int64_t>(params[0]);
1254 if (strMethod == "keypoolreset" && n > 0) ConvertTo<int64_t>(params[0]);
1255 if (strMethod == "importaddress" && n > 2) ConvertTo<bool>(params[2]);
1260 int CommandLineRPC(int argc, char *argv[])
1267 while (argc > 1 && IsSwitchChar(argv[1][0]))
1275 throw runtime_error("too few parameters");
1276 string strMethod = argv[1];
1278 // Parameters default to strings
1279 std::vector<std::string> strParams(&argv[2], &argv[argc]);
1280 Array params = RPCConvertValues(strMethod, strParams);
1283 Object reply = CallRPC(strMethod, params);
1286 const Value& result = find_value(reply, "result");
1287 const Value& error = find_value(reply, "error");
1289 if (error.type() != null_type)
1292 strPrint = "error: " + write_string(error, false);
1293 int code = find_value(error.get_obj(), "code").get_int();
1299 if (result.type() == null_type)
1301 else if (result.type() == str_type)
1302 strPrint = result.get_str();
1304 strPrint = write_string(result, true);
1307 catch (std::exception& e)
1309 strPrint = string("error: ") + e.what();
1314 PrintException(NULL, "CommandLineRPC()");
1319 fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
1328 int main(int argc, char *argv[])
1331 // Turn off Microsoft heap dump noise
1332 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
1333 _CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
1335 setbuf(stdin, NULL);
1336 setbuf(stdout, NULL);
1337 setbuf(stderr, NULL);
1341 if (argc >= 2 && string(argv[1]) == "-server")
1343 printf("server ready\n");
1344 ThreadRPCServer(NULL);
1348 return CommandLineRPC(argc, argv);
1351 catch (std::exception& e) {
1352 PrintException(&e, "main()");
1354 PrintException(NULL, "main()");
1360 const CRPCTable tableRPC;