1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
7 #include <boost/asio.hpp>
8 #include <boost/iostreams/concepts.hpp>
9 #include <boost/iostreams/stream.hpp>
11 #include <boost/asio/ssl.hpp>
12 typedef boost::asio::ssl::stream<boost::asio::ip::tcp::socket> SSLStream;
14 #include "json/json_spirit_reader_template.h"
15 #include "json/json_spirit_writer_template.h"
16 #include "json/json_spirit_utils.h"
17 #define printf OutputDebugStringF
18 // MinGW 3.4.5 gets "fatal error: had to relocate PCH" if the json headers are
19 // precompiled in headers.h. The problem might be when the pch file goes over
20 // a certain size around 145MB. If we need access to json_spirit outside this
21 // file, we could use the compiled json_spirit option.
23 using namespace boost::asio;
24 using namespace json_spirit;
26 void ThreadRPCServer2(void* parg);
27 typedef Value(*rpcfn_type)(const Array& params, bool fHelp);
28 extern map<string, rpcfn_type> mapCallTable;
31 Object JSONRPCError(int code, const string& message)
34 error.push_back(Pair("code", code));
35 error.push_back(Pair("message", message));
40 void PrintConsole(const char* format, ...)
43 int limit = sizeof(buffer);
45 va_start(arg_ptr, format);
46 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
48 if (ret < 0 || ret >= limit)
53 #if defined(__WXMSW__) && defined(GUI)
54 MyMessageBox(buffer, "Bitcoin", wxOK | wxICON_EXCLAMATION);
56 fprintf(stdout, "%s", buffer);
67 /// Note: This interface may still be subject to change.
71 Value help(const Array& params, bool fHelp)
73 if (fHelp || params.size() > 1)
76 "List commands, or get help for a command.");
79 if (params.size() > 0)
80 strCommand = params[0].get_str();
83 set<rpcfn_type> setDone;
84 for (map<string, rpcfn_type>::iterator mi = mapCallTable.begin(); mi != mapCallTable.end(); ++mi)
86 string strMethod = (*mi).first;
87 // We already filter duplicates, but these deprecated screw up the sort order
88 if (strMethod == "getamountreceived" ||
89 strMethod == "getallreceived")
91 if (strCommand != "" && strMethod != strCommand)
96 rpcfn_type pfn = (*mi).second;
97 if (setDone.insert(pfn).second)
100 catch (std::exception& e)
102 // Help text is returned in an exception
103 string strHelp = string(e.what());
104 if (strCommand == "")
105 if (strHelp.find('\n') != -1)
106 strHelp = strHelp.substr(0, strHelp.find('\n'));
107 strRet += strHelp + "\n";
111 strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
112 strRet = strRet.substr(0,strRet.size()-1);
117 Value stop(const Array& params, bool fHelp)
119 if (fHelp || params.size() != 0)
122 "Stop bitcoin server.");
124 // Shutdown will take long enough that the response should get back
125 CreateThread(Shutdown, NULL);
126 return "bitcoin server stopping";
130 Value getblockcount(const Array& params, bool fHelp)
132 if (fHelp || params.size() != 0)
135 "Returns the number of blocks in the longest block chain.");
141 Value getblocknumber(const Array& params, bool fHelp)
143 if (fHelp || params.size() != 0)
146 "Returns the block number of the latest block in the longest block chain.");
152 Value getconnectioncount(const Array& params, bool fHelp)
154 if (fHelp || params.size() != 0)
156 "getconnectioncount\n"
157 "Returns the number of connections to other nodes.");
159 return (int)vNodes.size();
163 double GetDifficulty()
165 // Floating point number that is a multiple of the minimum difficulty,
166 // minimum difficulty = 1.0.
167 if (pindexBest == NULL)
169 int nShift = 256 - 32 - 31; // to fit in a uint
170 double dMinimum = (CBigNum().SetCompact(bnProofOfWorkLimit.GetCompact()) >> nShift).getuint();
171 double dCurrently = (CBigNum().SetCompact(pindexBest->nBits) >> nShift).getuint();
172 return dMinimum / dCurrently;
175 Value getdifficulty(const Array& params, bool fHelp)
177 if (fHelp || params.size() != 0)
180 "Returns the proof-of-work difficulty as a multiple of the minimum difficulty.");
182 return GetDifficulty();
186 Value getbalance(const Array& params, bool fHelp)
188 if (fHelp || params.size() != 0)
191 "Returns the server's available balance.");
193 return ((double)GetBalance() / (double)COIN);
197 Value getgenerate(const Array& params, bool fHelp)
199 if (fHelp || params.size() != 0)
202 "Returns true or false.");
204 return (bool)fGenerateBitcoins;
208 Value setgenerate(const Array& params, bool fHelp)
210 if (fHelp || params.size() < 1 || params.size() > 2)
212 "setgenerate <generate> [genproclimit]\n"
213 "<generate> is true or false to turn generation on or off.\n"
214 "Generation is limited to [genproclimit] processors, -1 is unlimited.");
216 bool fGenerate = true;
217 if (params.size() > 0)
218 fGenerate = params[0].get_bool();
220 if (params.size() > 1)
222 int nGenProcLimit = params[1].get_int();
223 fLimitProcessors = (nGenProcLimit != -1);
224 CWalletDB().WriteSetting("fLimitProcessors", fLimitProcessors);
225 if (nGenProcLimit != -1)
226 CWalletDB().WriteSetting("nLimitProcessors", nLimitProcessors = nGenProcLimit);
229 GenerateBitcoins(fGenerate);
234 Value gethashespersec(const Array& params, bool fHelp)
236 if (fHelp || params.size() != 0)
239 "Returns a recent hashes per second performance measurement while generating.");
241 if (GetTimeMillis() - nHPSTimerStart > 8000)
242 return (boost::int64_t)0;
243 return (boost::int64_t)dHashesPerSec;
247 Value getinfo(const Array& params, bool fHelp)
249 if (fHelp || params.size() != 0)
252 "Returns an object containing various state info.");
255 obj.push_back(Pair("version", (int)VERSION));
256 obj.push_back(Pair("balance", (double)GetBalance() / (double)COIN));
257 obj.push_back(Pair("blocks", (int)nBestHeight));
258 obj.push_back(Pair("connections", (int)vNodes.size()));
259 obj.push_back(Pair("proxy", (fUseProxy ? addrProxy.ToStringIPPort() : string())));
260 obj.push_back(Pair("generate", (bool)fGenerateBitcoins));
261 obj.push_back(Pair("genproclimit", (int)(fLimitProcessors ? nLimitProcessors : -1)));
262 obj.push_back(Pair("difficulty", (double)GetDifficulty()));
263 obj.push_back(Pair("hashespersec", gethashespersec(params, false)));
264 obj.push_back(Pair("errors", GetWarnings("statusbar")));
269 Value getnewaddress(const Array& params, bool fHelp)
271 if (fHelp || params.size() > 1)
273 "getnewaddress [label]\n"
274 "Returns a new bitcoin address for receiving payments. "
275 "If [label] is specified (recommended), it is added to the address book "
276 "so payments received with the address will be labeled.");
278 // Parse the label first so we don't generate a key if there's an error
280 if (params.size() > 0)
281 strLabel = params[0].get_str();
283 // Generate a new key that is added to wallet
284 string strAddress = PubKeyToAddress(CWalletDB().GetKeyFromKeyPool());
286 SetAddressBookName(strAddress, strLabel);
291 Value setlabel(const Array& params, bool fHelp)
293 if (fHelp || params.size() < 1 || params.size() > 2)
295 "setlabel <bitcoinaddress> <label>\n"
296 "Sets the label associated with the given address.");
298 string strAddress = params[0].get_str();
300 if (params.size() > 1)
301 strLabel = params[1].get_str();
303 SetAddressBookName(strAddress, strLabel);
308 Value getlabel(const Array& params, bool fHelp)
310 if (fHelp || params.size() != 1)
312 "getlabel <bitcoinaddress>\n"
313 "Returns the label associated with the given address.");
315 string strAddress = params[0].get_str();
318 CRITICAL_BLOCK(cs_mapAddressBook)
320 map<string, string>::iterator mi = mapAddressBook.find(strAddress);
321 if (mi != mapAddressBook.end() && !(*mi).second.empty())
322 strLabel = (*mi).second;
328 Value getaddressesbylabel(const Array& params, bool fHelp)
330 if (fHelp || params.size() != 1)
332 "getaddressesbylabel <label>\n"
333 "Returns the list of addresses with the given label.");
335 string strLabel = params[0].get_str();
337 // Find all addresses that have the given label
339 CRITICAL_BLOCK(cs_mapAddressBook)
341 foreach(const PAIRTYPE(string, string)& item, mapAddressBook)
343 const string& strAddress = item.first;
344 const string& strName = item.second;
345 if (strName == strLabel)
347 // We're only adding valid bitcoin addresses and not ip addresses
348 CScript scriptPubKey;
349 if (scriptPubKey.SetBitcoinAddress(strAddress))
350 ret.push_back(strAddress);
358 Value sendtoaddress(const Array& params, bool fHelp)
360 if (fHelp || params.size() < 2 || params.size() > 4)
362 "sendtoaddress <bitcoinaddress> <amount> [comment] [comment-to]\n"
363 "<amount> is a real and is rounded to the nearest 0.01");
365 string strAddress = params[0].get_str();
368 if (params[1].get_real() <= 0.0 || params[1].get_real() > 21000000.0)
369 throw JSONRPCError(-3, "Invalid amount");
370 int64 nAmount = roundint64(params[1].get_real() * 100.00) * CENT;
374 if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty())
375 wtx.mapValue["message"] = params[2].get_str();
376 if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
377 wtx.mapValue["to"] = params[3].get_str();
379 string strError = SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);
381 throw JSONRPCError(-4, strError);
386 Value listtransactions(const Array& params, bool fHelp)
388 if (fHelp || params.size() > 2)
390 "listtransactions [count=10] [includegenerated=false]\n"
391 "Returns up to [count] most recent transactions.");
394 if (params.size() > 0)
395 nCount = params[0].get_int64();
396 bool fGenerated = false;
397 if (params.size() > 1)
398 fGenerated = params[1].get_bool();
402 ret.push_back("not implemented yet");
407 Value getreceivedbyaddress(const Array& params, bool fHelp)
409 if (fHelp || params.size() < 1 || params.size() > 2)
411 "getreceivedbyaddress <bitcoinaddress> [minconf=1]\n"
412 "Returns the total amount received by <bitcoinaddress> in transactions with at least [minconf] confirmations.");
415 string strAddress = params[0].get_str();
416 CScript scriptPubKey;
417 if (!scriptPubKey.SetBitcoinAddress(strAddress))
418 throw JSONRPCError(-5, "Invalid bitcoin address");
419 if (!IsMine(scriptPubKey))
422 // Minimum confirmations
424 if (params.size() > 1)
425 nMinDepth = params[1].get_int();
429 CRITICAL_BLOCK(cs_mapWallet)
431 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
433 const CWalletTx& wtx = (*it).second;
434 if (wtx.IsCoinBase() || !wtx.IsFinal())
437 foreach(const CTxOut& txout, wtx.vout)
438 if (txout.scriptPubKey == scriptPubKey)
439 if (wtx.GetDepthInMainChain() >= nMinDepth)
440 nAmount += txout.nValue;
444 return (double)nAmount / (double)COIN;
448 Value getreceivedbylabel(const Array& params, bool fHelp)
450 if (fHelp || params.size() < 1 || params.size() > 2)
452 "getreceivedbylabel <label> [minconf=1]\n"
453 "Returns the total amount received by addresses with <label> in transactions with at least [minconf] confirmations.");
455 // Get the set of pub keys that have the label
456 string strLabel = params[0].get_str();
457 set<CScript> setPubKey;
458 CRITICAL_BLOCK(cs_mapAddressBook)
460 foreach(const PAIRTYPE(string, string)& item, mapAddressBook)
462 const string& strAddress = item.first;
463 const string& strName = item.second;
464 if (strName == strLabel)
466 // We're only counting our own valid bitcoin addresses and not ip addresses
467 CScript scriptPubKey;
468 if (scriptPubKey.SetBitcoinAddress(strAddress))
469 if (IsMine(scriptPubKey))
470 setPubKey.insert(scriptPubKey);
475 // Minimum confirmations
477 if (params.size() > 1)
478 nMinDepth = params[1].get_int();
482 CRITICAL_BLOCK(cs_mapWallet)
484 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
486 const CWalletTx& wtx = (*it).second;
487 if (wtx.IsCoinBase() || !wtx.IsFinal())
490 foreach(const CTxOut& txout, wtx.vout)
491 if (setPubKey.count(txout.scriptPubKey))
492 if (wtx.GetDepthInMainChain() >= nMinDepth)
493 nAmount += txout.nValue;
497 return (double)nAmount / (double)COIN;
513 Value ListReceived(const Array& params, bool fByLabels)
515 // Minimum confirmations
517 if (params.size() > 0)
518 nMinDepth = params[0].get_int();
520 // Whether to include empty accounts
521 bool fIncludeEmpty = false;
522 if (params.size() > 1)
523 fIncludeEmpty = params[1].get_bool();
526 map<uint160, tallyitem> mapTally;
527 CRITICAL_BLOCK(cs_mapWallet)
529 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
531 const CWalletTx& wtx = (*it).second;
532 if (wtx.IsCoinBase() || !wtx.IsFinal())
535 int nDepth = wtx.GetDepthInMainChain();
536 if (nDepth < nMinDepth)
539 foreach(const CTxOut& txout, wtx.vout)
541 // Only counting our own bitcoin addresses and not ip addresses
542 uint160 hash160 = txout.scriptPubKey.GetBitcoinAddressHash160();
543 if (hash160 == 0 || !mapPubKeys.count(hash160)) // IsMine
546 tallyitem& item = mapTally[hash160];
547 item.nAmount += txout.nValue;
548 item.nConf = min(item.nConf, nDepth);
555 map<string, tallyitem> mapLabelTally;
556 CRITICAL_BLOCK(cs_mapAddressBook)
558 foreach(const PAIRTYPE(string, string)& item, mapAddressBook)
560 const string& strAddress = item.first;
561 const string& strLabel = item.second;
563 if (!AddressToHash160(strAddress, hash160))
565 map<uint160, tallyitem>::iterator it = mapTally.find(hash160);
566 if (it == mapTally.end() && !fIncludeEmpty)
571 if (it != mapTally.end())
573 nAmount = (*it).second.nAmount;
574 nConf = (*it).second.nConf;
579 tallyitem& item = mapLabelTally[strLabel];
580 item.nAmount += nAmount;
581 item.nConf = min(item.nConf, nConf);
586 obj.push_back(Pair("address", strAddress));
587 obj.push_back(Pair("label", strLabel));
588 obj.push_back(Pair("amount", (double)nAmount / (double)COIN));
589 obj.push_back(Pair("confirmations", (nConf == INT_MAX ? 0 : nConf)));
597 for (map<string, tallyitem>::iterator it = mapLabelTally.begin(); it != mapLabelTally.end(); ++it)
599 int64 nAmount = (*it).second.nAmount;
600 int nConf = (*it).second.nConf;
602 obj.push_back(Pair("label", (*it).first));
603 obj.push_back(Pair("amount", (double)nAmount / (double)COIN));
604 obj.push_back(Pair("confirmations", (nConf == INT_MAX ? 0 : nConf)));
612 Value listreceivedbyaddress(const Array& params, bool fHelp)
614 if (fHelp || params.size() > 2)
616 "listreceivedbyaddress [minconf=1] [includeempty=false]\n"
617 "[minconf] is the minimum number of confirmations before payments are included.\n"
618 "[includeempty] whether to include addresses that haven't received any payments.\n"
619 "Returns an array of objects containing:\n"
620 " \"address\" : receiving address\n"
621 " \"label\" : the label of the receiving address\n"
622 " \"amount\" : total amount received by the address\n"
623 " \"confirmations\" : number of confirmations of the most recent transaction included");
625 return ListReceived(params, false);
628 Value listreceivedbylabel(const Array& params, bool fHelp)
630 if (fHelp || params.size() > 2)
632 "listreceivedbylabel [minconf=1] [includeempty=false]\n"
633 "[minconf] is the minimum number of confirmations before payments are included.\n"
634 "[includeempty] whether to include labels that haven't received any payments.\n"
635 "Returns an array of objects containing:\n"
636 " \"label\" : the label of the receiving addresses\n"
637 " \"amount\" : total amount received by addresses with this label\n"
638 " \"confirmations\" : number of confirmations of the most recent transaction included");
640 return ListReceived(params, true);
644 Value backupwallet(const Array& params, bool fHelp)
646 if (fHelp || params.size() != 1)
648 "backupwallet <destination>\n"
649 "Safely copies wallet.dat to destination, which can be a directory or a path with filename.");
651 string strDest = params[0].get_str();
652 BackupWallet(strDest);
673 pair<string, rpcfn_type> pCallTable[] =
675 make_pair("help", &help),
676 make_pair("stop", &stop),
677 make_pair("getblockcount", &getblockcount),
678 make_pair("getblocknumber", &getblocknumber),
679 make_pair("getconnectioncount", &getconnectioncount),
680 make_pair("getdifficulty", &getdifficulty),
681 make_pair("getbalance", &getbalance),
682 make_pair("getgenerate", &getgenerate),
683 make_pair("setgenerate", &setgenerate),
684 make_pair("gethashespersec", &gethashespersec),
685 make_pair("getinfo", &getinfo),
686 make_pair("getnewaddress", &getnewaddress),
687 make_pair("setlabel", &setlabel),
688 make_pair("getlabel", &getlabel),
689 make_pair("getaddressesbylabel", &getaddressesbylabel),
690 make_pair("sendtoaddress", &sendtoaddress),
691 make_pair("getamountreceived", &getreceivedbyaddress), // deprecated, renamed to getreceivedbyaddress
692 make_pair("getallreceived", &listreceivedbyaddress), // deprecated, renamed to listreceivedbyaddress
693 make_pair("getreceivedbyaddress", &getreceivedbyaddress),
694 make_pair("getreceivedbylabel", &getreceivedbylabel),
695 make_pair("listreceivedbyaddress", &listreceivedbyaddress),
696 make_pair("listreceivedbylabel", &listreceivedbylabel),
697 make_pair("backupwallet", &backupwallet),
699 map<string, rpcfn_type> mapCallTable(pCallTable, pCallTable + sizeof(pCallTable)/sizeof(pCallTable[0]));
701 string pAllowInSafeMode[] =
707 "getconnectioncount",
716 "getaddressesbylabel",
719 set<string> setAllowInSafeMode(pAllowInSafeMode, pAllowInSafeMode + sizeof(pAllowInSafeMode)/sizeof(pAllowInSafeMode[0]));
727 // This ain't Apache. We're just using HTTP header for the length field
728 // and to be compatible with other JSON-RPC implementations.
731 string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
734 s << "POST / HTTP/1.1\r\n"
735 << "User-Agent: json-rpc/1.0\r\n"
736 << "Host: 127.0.0.1\r\n"
737 << "Content-Type: application/json\r\n"
738 << "Content-Length: " << strMsg.size() << "\r\n"
739 << "Accept: application/json\r\n";
740 foreach(const PAIRTYPE(string, string)& item, mapRequestHeaders)
741 s << item.first << ": " << item.second << "\r\n";
742 s << "\r\n" << strMsg;
747 string HTTPReply(int nStatus, const string& strMsg)
750 return "HTTP/1.0 401 Authorization Required\r\n"
751 "Server: HTTPd/1.0\r\n"
752 "Date: Sat, 08 Jul 2006 12:04:08 GMT\r\n"
753 "WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
754 "Content-Type: text/html\r\n"
755 "Content-Length: 311\r\n"
757 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
758 "\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
761 "<TITLE>Error</TITLE>\r\n"
762 "<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
764 "<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
767 if (nStatus == 200) strStatus = "OK";
768 else if (nStatus == 400) strStatus = "Bad Request";
769 else if (nStatus == 404) strStatus = "Not Found";
770 else if (nStatus == 500) strStatus = "Internal Server Error";
773 "Connection: close\r\n"
774 "Content-Length: %d\r\n"
775 "Content-Type: application/json\r\n"
776 "Date: Sat, 08 Jul 2006 12:04:08 GMT\r\n"
777 "Server: json-rpc/1.0\r\n"
786 int ReadHTTPStatus(std::basic_istream<char>& stream)
789 getline(stream, str);
790 vector<string> vWords;
791 boost::split(vWords, str, boost::is_any_of(" "));
792 if (vWords.size() < 2)
794 return atoi(vWords[1].c_str());
797 int ReadHTTPHeader(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
803 std::getline(stream, str);
804 if (str.empty() || str == "\r")
806 string::size_type nColon = str.find(":");
807 if (nColon != string::npos)
809 string strHeader = str.substr(0, nColon);
810 boost::trim(strHeader);
811 string strValue = str.substr(nColon+1);
812 boost::trim(strValue);
813 mapHeadersRet[strHeader] = strValue;
814 if (strHeader == "Content-Length")
815 nLen = atoi(strValue.c_str());
821 int ReadHTTP(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet)
823 mapHeadersRet.clear();
827 int nStatus = ReadHTTPStatus(stream);
830 int nLen = ReadHTTPHeader(stream, mapHeadersRet);
831 if (nLen < 0 || nLen > MAX_SIZE)
837 vector<char> vch(nLen);
838 stream.read(&vch[0], nLen);
839 strMessageRet = string(vch.begin(), vch.end());
845 string EncodeBase64(string s)
850 b64 = BIO_new(BIO_f_base64());
851 BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
852 bmem = BIO_new(BIO_s_mem());
853 b64 = BIO_push(b64, bmem);
854 BIO_write(b64, s.c_str(), s.size());
856 BIO_get_mem_ptr(b64, &bptr);
858 string result(bptr->data, bptr->length);
864 string DecodeBase64(string s)
868 char* buffer = static_cast<char*>(calloc(s.size(), sizeof(char)));
870 b64 = BIO_new(BIO_f_base64());
871 BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
872 bmem = BIO_new_mem_buf(const_cast<char*>(s.c_str()), s.size());
873 bmem = BIO_push(b64, bmem);
874 BIO_read(bmem, buffer, s.size());
877 string result(buffer);
882 bool HTTPAuthorized(map<string, string>& mapHeaders)
884 string strAuth = mapHeaders["Authorization"];
885 if (strAuth.substr(0,6) != "Basic ")
887 string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
888 string strUserPass = DecodeBase64(strUserPass64);
889 string::size_type nColon = strUserPass.find(":");
890 if (nColon == string::npos)
892 string strUser = strUserPass.substr(0, nColon);
893 string strPassword = strUserPass.substr(nColon+1);
894 return (strUser == mapArgs["-rpcuser"] && strPassword == mapArgs["-rpcpassword"]);
898 // JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
899 // but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
900 // unspecified (HTTP errors and contents of 'error').
902 // 1.0 spec: http://json-rpc.org/wiki/specification
903 // 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
904 // http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
907 string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
910 request.push_back(Pair("method", strMethod));
911 request.push_back(Pair("params", params));
912 request.push_back(Pair("id", id));
913 return write_string(Value(request), false) + "\n";
916 string JSONRPCReply(const Value& result, const Value& error, const Value& id)
919 if (error.type() != null_type)
920 reply.push_back(Pair("result", Value::null));
922 reply.push_back(Pair("result", result));
923 reply.push_back(Pair("error", error));
924 reply.push_back(Pair("id", id));
925 return write_string(Value(reply), false) + "\n";
928 bool ClientAllowed(const string& strAddress)
930 if (strAddress == asio::ip::address_v4::loopback().to_string())
932 const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
933 foreach(string strAllow, vAllow)
934 if (WildcardMatch(strAddress, strAllow))
941 // IOStream device that speaks SSL but can also speak non-SSL
943 class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {
945 SSLIOStreamDevice(SSLStream &streamIn, bool fUseSSLIn) : stream(streamIn)
948 fNeedHandshake = fUseSSLIn;
951 void handshake(ssl::stream_base::handshake_type role)
953 if (!fNeedHandshake) return;
954 fNeedHandshake = false;
955 stream.handshake(role);
957 std::streamsize read(char* s, std::streamsize n)
959 handshake(ssl::stream_base::server); // HTTPS servers read first
960 if (fUseSSL) return stream.read_some(asio::buffer(s, n));
961 return stream.next_layer().read_some(asio::buffer(s, n));
963 std::streamsize write(const char* s, std::streamsize n)
965 handshake(ssl::stream_base::client); // HTTPS clients write first
966 if (fUseSSL) return asio::write(stream, asio::buffer(s, n));
967 return asio::write(stream.next_layer(), asio::buffer(s, n));
969 bool connect(const std::string& server, const std::string& port)
971 ip::tcp::resolver resolver(stream.get_io_service());
972 ip::tcp::resolver::query query(server.c_str(), port.c_str());
973 ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
974 ip::tcp::resolver::iterator end;
975 boost::system::error_code error = asio::error::host_not_found;
976 while (error && endpoint_iterator != end)
978 stream.lowest_layer().close();
979 stream.lowest_layer().connect(*endpoint_iterator++, error);
993 void ThreadRPCServer(void* parg)
995 IMPLEMENT_RANDOMIZE_STACK(ThreadRPCServer(parg));
998 vnThreadsRunning[4]++;
999 ThreadRPCServer2(parg);
1000 vnThreadsRunning[4]--;
1002 catch (std::exception& e) {
1003 vnThreadsRunning[4]--;
1004 PrintException(&e, "ThreadRPCServer()");
1006 vnThreadsRunning[4]--;
1007 PrintException(NULL, "ThreadRPCServer()");
1009 printf("ThreadRPCServer exiting\n");
1012 void ThreadRPCServer2(void* parg)
1014 printf("ThreadRPCServer started\n");
1016 if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
1018 string strWhatAmI = "To use bitcoind";
1019 if (mapArgs.count("-server"))
1020 strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
1021 else if (mapArgs.count("-daemon"))
1022 strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
1024 _("Warning: %s, you must set rpcpassword=<password>\nin the configuration file: %s\n"
1025 "If the file does not exist, create it with owner-readable-only file permissions.\n"),
1027 GetConfigFile().c_str());
1028 CreateThread(Shutdown, NULL);
1032 bool fUseSSL = (mapArgs.count("-rpcssl") > 0);
1033 asio::ip::address bindAddress = mapArgs.count("-rpcallowip") ? asio::ip::address_v4::any() : asio::ip::address_v4::loopback();
1035 asio::io_service io_service;
1036 ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", 8332));
1037 ip::tcp::acceptor acceptor(io_service, endpoint);
1040 ssl::context context(io_service, ssl::context::sslv23);
1043 context.set_options(ssl::context::no_sslv2);
1044 filesystem::path certfile = GetArg("-rpcsslcertificatechainfile", "server.cert");
1045 if (!certfile.is_complete()) certfile = filesystem::path(GetDataDir()) / certfile;
1046 if (filesystem::exists(certfile)) context.use_certificate_chain_file(certfile.string().c_str());
1047 else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", certfile.string().c_str());
1048 filesystem::path pkfile = GetArg("-rpcsslprivatekeyfile", "server.pem");
1049 if (!pkfile.is_complete()) pkfile = filesystem::path(GetDataDir()) / pkfile;
1050 if (filesystem::exists(pkfile)) context.use_private_key_file(pkfile.string().c_str(), ssl::context::pem);
1051 else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pkfile.string().c_str());
1053 string ciphers = GetArg("-rpcsslciphers",
1054 "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
1055 SSL_CTX_set_cipher_list(context.impl(), ciphers.c_str());
1059 throw runtime_error("-rpcssl=true, but bitcoin compiled without full openssl libraries.");
1064 // Accept connection
1066 SSLStream sslStream(io_service, context);
1067 SSLIOStreamDevice d(sslStream, fUseSSL);
1068 iostreams::stream<SSLIOStreamDevice> stream(d);
1070 ip::tcp::iostream stream;
1073 ip::tcp::endpoint peer;
1074 vnThreadsRunning[4]--;
1076 acceptor.accept(sslStream.lowest_layer(), peer);
1078 acceptor.accept(*stream.rdbuf(), peer);
1080 vnThreadsRunning[4]++;
1084 // Restrict callers by IP
1085 if (!ClientAllowed(peer.address().to_string()))
1089 map<string, string> mapHeaders;
1091 ReadHTTP(stream, mapHeaders, strRequest);
1093 // Check authorization
1094 if (mapHeaders.count("Authorization") == 0)
1096 stream << HTTPReply(401, "") << std::flush;
1099 if (!HTTPAuthorized(mapHeaders))
1101 // Deter brute-forcing short passwords
1102 if (mapArgs["-rpcpassword"].size() < 15)
1105 stream << HTTPReply(401, "") << std::flush;
1106 printf("ThreadRPCServer incorrect password attempt\n");
1110 Value id = Value::null;
1115 if (!read_string(strRequest, valRequest) || valRequest.type() != obj_type)
1116 throw JSONRPCError(-32700, "Parse error");
1117 const Object& request = valRequest.get_obj();
1119 // Parse id now so errors from here on will have the id
1120 id = find_value(request, "id");
1123 Value valMethod = find_value(request, "method");
1124 if (valMethod.type() == null_type)
1125 throw JSONRPCError(-32600, "Missing method");
1126 if (valMethod.type() != str_type)
1127 throw JSONRPCError(-32600, "Method must be a string");
1128 string strMethod = valMethod.get_str();
1129 printf("ThreadRPCServer method=%s\n", strMethod.c_str());
1132 Value valParams = find_value(request, "params");
1134 if (valParams.type() == array_type)
1135 params = valParams.get_array();
1136 else if (valParams.type() == null_type)
1139 throw JSONRPCError(-32600, "Params must be an array");
1142 map<string, rpcfn_type>::iterator mi = mapCallTable.find(strMethod);
1143 if (mi == mapCallTable.end())
1144 throw JSONRPCError(-32601, "Method not found");
1146 // Observe safe mode
1147 string strWarning = GetWarnings("rpc");
1148 if (strWarning != "" && !mapArgs.count("-disablesafemode") && !setAllowInSafeMode.count(strMethod))
1149 throw JSONRPCError(-2, string("Safe mode: ") + strWarning);
1154 Value result = (*(*mi).second)(params, false);
1157 string strReply = JSONRPCReply(result, Value::null, id);
1158 stream << HTTPReply(200, strReply) << std::flush;
1160 catch (std::exception& e)
1162 // Send error reply from method
1163 string strReply = JSONRPCReply(Value::null, JSONRPCError(-1, e.what()), id);
1164 stream << HTTPReply(500, strReply) << std::flush;
1167 catch (Object& objError)
1169 // Send error reply from json-rpc error object
1171 int code = find_value(objError, "code").get_int();
1172 if (code == -32600) nStatus = 400;
1173 else if (code == -32601) nStatus = 404;
1174 string strReply = JSONRPCReply(Value::null, objError, id);
1175 stream << HTTPReply(nStatus, strReply) << std::flush;
1177 catch (std::exception& e)
1179 // Send error reply from other json-rpc parsing errors
1180 string strReply = JSONRPCReply(Value::null, JSONRPCError(-32700, e.what()), id);
1181 stream << HTTPReply(500, strReply) << std::flush;
1189 Object CallRPC(const string& strMethod, const Array& params)
1191 if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
1192 throw runtime_error(strprintf(
1193 _("You must set rpcpassword=<password> in the configuration file:\n%s\n"
1194 "If the file does not exist, create it with owner-readable-only file permissions."),
1195 GetConfigFile().c_str()));
1197 // Connect to localhost
1198 bool fUseSSL = (mapArgs.count("-rpcssl") > 0);
1200 asio::io_service io_service;
1201 ssl::context context(io_service, ssl::context::sslv23);
1202 context.set_options(ssl::context::no_sslv2);
1203 SSLStream sslStream(io_service, context);
1204 SSLIOStreamDevice d(sslStream, fUseSSL);
1205 iostreams::stream<SSLIOStreamDevice> stream(d);
1206 if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", "8332")))
1207 throw runtime_error("couldn't connect to server");
1210 throw runtime_error("-rpcssl=true, but bitcoin compiled without full openssl libraries.");
1212 ip::tcp::iostream stream(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", "8332"));
1214 throw runtime_error("couldn't connect to server");
1218 // HTTP basic authentication
1219 string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
1220 map<string, string> mapRequestHeaders;
1221 mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
1224 string strRequest = JSONRPCRequest(strMethod, params, 1);
1225 string strPost = HTTPPost(strRequest, mapRequestHeaders);
1226 stream << strPost << std::flush;
1229 map<string, string> mapHeaders;
1231 int nStatus = ReadHTTP(stream, mapHeaders, strReply);
1233 throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
1234 else if (nStatus >= 400 && nStatus != 400 && nStatus != 404 && nStatus != 500)
1235 throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
1236 else if (strReply.empty())
1237 throw runtime_error("no response from server");
1241 if (!read_string(strReply, valReply))
1242 throw runtime_error("couldn't parse reply from server");
1243 const Object& reply = valReply.get_obj();
1245 throw runtime_error("expected reply to have result, error and id properties");
1253 template<typename T>
1254 void ConvertTo(Value& value)
1256 if (value.type() == str_type)
1258 // reinterpret string as unquoted json value
1260 if (!read_string(value.get_str(), value2))
1261 throw runtime_error("type mismatch");
1262 value = value2.get_value<T>();
1266 value = value.get_value<T>();
1270 int CommandLineRPC(int argc, char *argv[])
1277 while (argc > 1 && IsSwitchChar(argv[1][0]))
1285 throw runtime_error("too few parameters");
1286 string strMethod = argv[1];
1288 // Parameters default to strings
1290 for (int i = 2; i < argc; i++)
1291 params.push_back(argv[i]);
1292 int n = params.size();
1295 // Special case non-string parameter types
1297 if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]);
1298 if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1299 if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);
1300 if (strMethod == "listtransactions" && n > 0) ConvertTo<boost::int64_t>(params[0]);
1301 if (strMethod == "listtransactions" && n > 1) ConvertTo<bool>(params[1]);
1302 if (strMethod == "getamountreceived" && n > 1) ConvertTo<boost::int64_t>(params[1]); // deprecated
1303 if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1304 if (strMethod == "getreceivedbylabel" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1305 if (strMethod == "getallreceived" && n > 0) ConvertTo<boost::int64_t>(params[0]); // deprecated
1306 if (strMethod == "getallreceived" && n > 1) ConvertTo<bool>(params[1]);
1307 if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
1308 if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);
1309 if (strMethod == "listreceivedbylabel" && n > 0) ConvertTo<boost::int64_t>(params[0]);
1310 if (strMethod == "listreceivedbylabel" && n > 1) ConvertTo<bool>(params[1]);
1313 Object reply = CallRPC(strMethod, params);
1316 const Value& result = find_value(reply, "result");
1317 const Value& error = find_value(reply, "error");
1318 const Value& id = find_value(reply, "id");
1320 if (error.type() != null_type)
1323 strPrint = "error: " + write_string(error, false);
1324 int code = find_value(error.get_obj(), "code").get_int();
1330 if (result.type() == null_type)
1332 else if (result.type() == str_type)
1333 strPrint = result.get_str();
1335 strPrint = write_string(result, true);
1338 catch (std::exception& e)
1340 strPrint = string("error: ") + e.what();
1345 PrintException(NULL, "CommandLineRPC()");
1350 #if defined(__WXMSW__) && defined(GUI)
1351 // Windows GUI apps can't print to command line,
1352 // so settle for a message box yuck
1353 MyMessageBox(strPrint, "Bitcoin", wxOK);
1355 fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
1365 int main(int argc, char *argv[])
1368 // Turn off microsoft heap dump noise
1369 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
1370 _CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
1372 setbuf(stdin, NULL);
1373 setbuf(stdout, NULL);
1374 setbuf(stderr, NULL);
1378 if (argc >= 2 && string(argv[1]) == "-server")
1380 printf("server ready\n");
1381 ThreadRPCServer(NULL);
1385 return CommandLineRPC(argc, argv);
1388 catch (std::exception& e) {
1389 PrintException(&e, "main()");
1391 PrintException(NULL, "main()");