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("testnet", fTestNet));
265 obj.push_back(Pair("keypoololdest", (boost::int64_t)CWalletDB().GetOldestKeyPoolTime()));
266 obj.push_back(Pair("paytxfee", (double)nTransactionFee / (double)COIN));
267 obj.push_back(Pair("errors", GetWarnings("statusbar")));
272 Value getnewaddress(const Array& params, bool fHelp)
274 if (fHelp || params.size() > 1)
276 "getnewaddress [label]\n"
277 "Returns a new bitcoin address for receiving payments. "
278 "If [label] is specified (recommended), it is added to the address book "
279 "so payments received with the address will be labeled.");
281 // Parse the label first so we don't generate a key if there's an error
283 if (params.size() > 0)
284 strLabel = params[0].get_str();
286 // Generate a new key that is added to wallet
287 string strAddress = PubKeyToAddress(CWalletDB().GetKeyFromKeyPool());
289 SetAddressBookName(strAddress, strLabel);
294 Value setlabel(const Array& params, bool fHelp)
296 if (fHelp || params.size() < 1 || params.size() > 2)
298 "setlabel <bitcoinaddress> <label>\n"
299 "Sets the label associated with the given address.");
301 string strAddress = params[0].get_str();
303 if (params.size() > 1)
304 strLabel = params[1].get_str();
306 SetAddressBookName(strAddress, strLabel);
311 Value getlabel(const Array& params, bool fHelp)
313 if (fHelp || params.size() != 1)
315 "getlabel <bitcoinaddress>\n"
316 "Returns the label associated with the given address.");
318 string strAddress = params[0].get_str();
321 CRITICAL_BLOCK(cs_mapAddressBook)
323 map<string, string>::iterator mi = mapAddressBook.find(strAddress);
324 if (mi != mapAddressBook.end() && !(*mi).second.empty())
325 strLabel = (*mi).second;
331 Value getaddressesbylabel(const Array& params, bool fHelp)
333 if (fHelp || params.size() != 1)
335 "getaddressesbylabel <label>\n"
336 "Returns the list of addresses with the given label.");
338 string strLabel = params[0].get_str();
340 // Find all addresses that have the given label
342 CRITICAL_BLOCK(cs_mapAddressBook)
344 foreach(const PAIRTYPE(string, string)& item, mapAddressBook)
346 const string& strAddress = item.first;
347 const string& strName = item.second;
348 if (strName == strLabel)
350 // We're only adding valid bitcoin addresses and not ip addresses
351 CScript scriptPubKey;
352 if (scriptPubKey.SetBitcoinAddress(strAddress))
353 ret.push_back(strAddress);
361 Value sendtoaddress(const Array& params, bool fHelp)
363 if (fHelp || params.size() < 2 || params.size() > 4)
365 "sendtoaddress <bitcoinaddress> <amount> [comment] [comment-to]\n"
366 "<amount> is a real and is rounded to the nearest 0.01");
368 string strAddress = params[0].get_str();
371 if (params[1].get_real() <= 0.0 || params[1].get_real() > 21000000.0)
372 throw JSONRPCError(-3, "Invalid amount");
373 int64 nAmount = roundint64(params[1].get_real() * 100.00) * CENT;
377 if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty())
378 wtx.mapValue["message"] = params[2].get_str();
379 if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
380 wtx.mapValue["to"] = params[3].get_str();
382 string strError = SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);
384 throw JSONRPCError(-4, strError);
389 Value listtransactions(const Array& params, bool fHelp)
391 if (fHelp || params.size() > 2)
393 "listtransactions [count=10] [includegenerated=false]\n"
394 "Returns up to [count] most recent transactions.");
397 if (params.size() > 0)
398 nCount = params[0].get_int64();
399 bool fGenerated = false;
400 if (params.size() > 1)
401 fGenerated = params[1].get_bool();
405 ret.push_back("not implemented yet");
410 Value getreceivedbyaddress(const Array& params, bool fHelp)
412 if (fHelp || params.size() < 1 || params.size() > 2)
414 "getreceivedbyaddress <bitcoinaddress> [minconf=1]\n"
415 "Returns the total amount received by <bitcoinaddress> in transactions with at least [minconf] confirmations.");
418 string strAddress = params[0].get_str();
419 CScript scriptPubKey;
420 if (!scriptPubKey.SetBitcoinAddress(strAddress))
421 throw JSONRPCError(-5, "Invalid bitcoin address");
422 if (!IsMine(scriptPubKey))
425 // Minimum confirmations
427 if (params.size() > 1)
428 nMinDepth = params[1].get_int();
432 CRITICAL_BLOCK(cs_mapWallet)
434 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
436 const CWalletTx& wtx = (*it).second;
437 if (wtx.IsCoinBase() || !wtx.IsFinal())
440 foreach(const CTxOut& txout, wtx.vout)
441 if (txout.scriptPubKey == scriptPubKey)
442 if (wtx.GetDepthInMainChain() >= nMinDepth)
443 nAmount += txout.nValue;
447 return (double)nAmount / (double)COIN;
451 Value getreceivedbylabel(const Array& params, bool fHelp)
453 if (fHelp || params.size() < 1 || params.size() > 2)
455 "getreceivedbylabel <label> [minconf=1]\n"
456 "Returns the total amount received by addresses with <label> in transactions with at least [minconf] confirmations.");
458 // Get the set of pub keys that have the label
459 string strLabel = params[0].get_str();
460 set<CScript> setPubKey;
461 CRITICAL_BLOCK(cs_mapAddressBook)
463 foreach(const PAIRTYPE(string, string)& item, mapAddressBook)
465 const string& strAddress = item.first;
466 const string& strName = item.second;
467 if (strName == strLabel)
469 // We're only counting our own valid bitcoin addresses and not ip addresses
470 CScript scriptPubKey;
471 if (scriptPubKey.SetBitcoinAddress(strAddress))
472 if (IsMine(scriptPubKey))
473 setPubKey.insert(scriptPubKey);
478 // Minimum confirmations
480 if (params.size() > 1)
481 nMinDepth = params[1].get_int();
485 CRITICAL_BLOCK(cs_mapWallet)
487 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
489 const CWalletTx& wtx = (*it).second;
490 if (wtx.IsCoinBase() || !wtx.IsFinal())
493 foreach(const CTxOut& txout, wtx.vout)
494 if (setPubKey.count(txout.scriptPubKey))
495 if (wtx.GetDepthInMainChain() >= nMinDepth)
496 nAmount += txout.nValue;
500 return (double)nAmount / (double)COIN;
516 Value ListReceived(const Array& params, bool fByLabels)
518 // Minimum confirmations
520 if (params.size() > 0)
521 nMinDepth = params[0].get_int();
523 // Whether to include empty accounts
524 bool fIncludeEmpty = false;
525 if (params.size() > 1)
526 fIncludeEmpty = params[1].get_bool();
529 map<uint160, tallyitem> mapTally;
530 CRITICAL_BLOCK(cs_mapWallet)
532 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
534 const CWalletTx& wtx = (*it).second;
535 if (wtx.IsCoinBase() || !wtx.IsFinal())
538 int nDepth = wtx.GetDepthInMainChain();
539 if (nDepth < nMinDepth)
542 foreach(const CTxOut& txout, wtx.vout)
544 // Only counting our own bitcoin addresses and not ip addresses
545 uint160 hash160 = txout.scriptPubKey.GetBitcoinAddressHash160();
546 if (hash160 == 0 || !mapPubKeys.count(hash160)) // IsMine
549 tallyitem& item = mapTally[hash160];
550 item.nAmount += txout.nValue;
551 item.nConf = min(item.nConf, nDepth);
558 map<string, tallyitem> mapLabelTally;
559 CRITICAL_BLOCK(cs_mapAddressBook)
561 foreach(const PAIRTYPE(string, string)& item, mapAddressBook)
563 const string& strAddress = item.first;
564 const string& strLabel = item.second;
566 if (!AddressToHash160(strAddress, hash160))
568 map<uint160, tallyitem>::iterator it = mapTally.find(hash160);
569 if (it == mapTally.end() && !fIncludeEmpty)
574 if (it != mapTally.end())
576 nAmount = (*it).second.nAmount;
577 nConf = (*it).second.nConf;
582 tallyitem& item = mapLabelTally[strLabel];
583 item.nAmount += nAmount;
584 item.nConf = min(item.nConf, nConf);
589 obj.push_back(Pair("address", strAddress));
590 obj.push_back(Pair("label", strLabel));
591 obj.push_back(Pair("amount", (double)nAmount / (double)COIN));
592 obj.push_back(Pair("confirmations", (nConf == INT_MAX ? 0 : nConf)));
600 for (map<string, tallyitem>::iterator it = mapLabelTally.begin(); it != mapLabelTally.end(); ++it)
602 int64 nAmount = (*it).second.nAmount;
603 int nConf = (*it).second.nConf;
605 obj.push_back(Pair("label", (*it).first));
606 obj.push_back(Pair("amount", (double)nAmount / (double)COIN));
607 obj.push_back(Pair("confirmations", (nConf == INT_MAX ? 0 : nConf)));
615 Value listreceivedbyaddress(const Array& params, bool fHelp)
617 if (fHelp || params.size() > 2)
619 "listreceivedbyaddress [minconf=1] [includeempty=false]\n"
620 "[minconf] is the minimum number of confirmations before payments are included.\n"
621 "[includeempty] whether to include addresses that haven't received any payments.\n"
622 "Returns an array of objects containing:\n"
623 " \"address\" : receiving address\n"
624 " \"label\" : the label of the receiving address\n"
625 " \"amount\" : total amount received by the address\n"
626 " \"confirmations\" : number of confirmations of the most recent transaction included");
628 return ListReceived(params, false);
631 Value listreceivedbylabel(const Array& params, bool fHelp)
633 if (fHelp || params.size() > 2)
635 "listreceivedbylabel [minconf=1] [includeempty=false]\n"
636 "[minconf] is the minimum number of confirmations before payments are included.\n"
637 "[includeempty] whether to include labels that haven't received any payments.\n"
638 "Returns an array of objects containing:\n"
639 " \"label\" : the label of the receiving addresses\n"
640 " \"amount\" : total amount received by addresses with this label\n"
641 " \"confirmations\" : number of confirmations of the most recent transaction included");
643 return ListReceived(params, true);
647 Value backupwallet(const Array& params, bool fHelp)
649 if (fHelp || params.size() != 1)
651 "backupwallet <destination>\n"
652 "Safely copies wallet.dat to destination, which can be a directory or a path with filename.");
654 string strDest = params[0].get_str();
655 BackupWallet(strDest);
661 Value validateaddress(const Array& params, bool fHelp)
663 if (fHelp || params.size() != 1)
665 "validateaddress <bitcoinaddress>\n"
666 "Return information about <bitcoinaddress>.");
668 string strAddress = params[0].get_str();
670 bool isValid = AddressToHash160(strAddress, hash160);
673 ret.push_back(Pair("isvalid", isValid));
676 // Call Hash160ToAddress() so we always return current ADDRESSVERSION
677 // version of the address:
678 ret.push_back(Pair("address", Hash160ToAddress(hash160)));
679 ret.push_back(Pair("ismine", (mapPubKeys.count(hash160) > 0)));
698 pair<string, rpcfn_type> pCallTable[] =
700 make_pair("help", &help),
701 make_pair("stop", &stop),
702 make_pair("getblockcount", &getblockcount),
703 make_pair("getblocknumber", &getblocknumber),
704 make_pair("getconnectioncount", &getconnectioncount),
705 make_pair("getdifficulty", &getdifficulty),
706 make_pair("getbalance", &getbalance),
707 make_pair("getgenerate", &getgenerate),
708 make_pair("setgenerate", &setgenerate),
709 make_pair("gethashespersec", &gethashespersec),
710 make_pair("getinfo", &getinfo),
711 make_pair("getnewaddress", &getnewaddress),
712 make_pair("setlabel", &setlabel),
713 make_pair("getlabel", &getlabel),
714 make_pair("getaddressesbylabel", &getaddressesbylabel),
715 make_pair("sendtoaddress", &sendtoaddress),
716 make_pair("getamountreceived", &getreceivedbyaddress), // deprecated, renamed to getreceivedbyaddress
717 make_pair("getallreceived", &listreceivedbyaddress), // deprecated, renamed to listreceivedbyaddress
718 make_pair("getreceivedbyaddress", &getreceivedbyaddress),
719 make_pair("getreceivedbylabel", &getreceivedbylabel),
720 make_pair("listreceivedbyaddress", &listreceivedbyaddress),
721 make_pair("listreceivedbylabel", &listreceivedbylabel),
722 make_pair("backupwallet", &backupwallet),
723 make_pair("validateaddress", &validateaddress),
725 map<string, rpcfn_type> mapCallTable(pCallTable, pCallTable + sizeof(pCallTable)/sizeof(pCallTable[0]));
727 string pAllowInSafeMode[] =
733 "getconnectioncount",
742 "getaddressesbylabel",
746 set<string> setAllowInSafeMode(pAllowInSafeMode, pAllowInSafeMode + sizeof(pAllowInSafeMode)/sizeof(pAllowInSafeMode[0]));
754 // This ain't Apache. We're just using HTTP header for the length field
755 // and to be compatible with other JSON-RPC implementations.
758 string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
761 s << "POST / HTTP/1.1\r\n"
762 << "User-Agent: json-rpc/1.0\r\n"
763 << "Host: 127.0.0.1\r\n"
764 << "Content-Type: application/json\r\n"
765 << "Content-Length: " << strMsg.size() << "\r\n"
766 << "Accept: application/json\r\n";
767 foreach(const PAIRTYPE(string, string)& item, mapRequestHeaders)
768 s << item.first << ": " << item.second << "\r\n";
769 s << "\r\n" << strMsg;
779 struct tm* now_gmt = gmtime(&now);
780 strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S %Z", now_gmt);
781 return string(buffer);
784 string HTTPReply(int nStatus, const string& strMsg)
787 return strprintf("HTTP/1.0 401 Authorization Required\r\n"
789 "Server: bitcoin-json-rpc\r\n"
790 "WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
791 "Content-Type: text/html\r\n"
792 "Content-Length: 311\r\n"
794 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
795 "\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
798 "<TITLE>Error</TITLE>\r\n"
799 "<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
801 "<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
802 "</HTML>\r\n", rfc1123Time().c_str());
804 if (nStatus == 200) strStatus = "OK";
805 else if (nStatus == 400) strStatus = "Bad Request";
806 else if (nStatus == 404) strStatus = "Not Found";
807 else if (nStatus == 500) strStatus = "Internal Server Error";
811 "Connection: close\r\n"
812 "Content-Length: %d\r\n"
813 "Content-Type: application/json\r\n"
814 "Server: bitcoin-json-rpc/1.0\r\n"
819 rfc1123Time().c_str(),
824 int ReadHTTPStatus(std::basic_istream<char>& stream)
827 getline(stream, str);
828 vector<string> vWords;
829 boost::split(vWords, str, boost::is_any_of(" "));
830 if (vWords.size() < 2)
832 return atoi(vWords[1].c_str());
835 int ReadHTTPHeader(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
841 std::getline(stream, str);
842 if (str.empty() || str == "\r")
844 string::size_type nColon = str.find(":");
845 if (nColon != string::npos)
847 string strHeader = str.substr(0, nColon);
848 boost::trim(strHeader);
849 string strValue = str.substr(nColon+1);
850 boost::trim(strValue);
851 mapHeadersRet[strHeader] = strValue;
852 if (strHeader == "Content-Length")
853 nLen = atoi(strValue.c_str());
859 int ReadHTTP(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet)
861 mapHeadersRet.clear();
865 int nStatus = ReadHTTPStatus(stream);
868 int nLen = ReadHTTPHeader(stream, mapHeadersRet);
869 if (nLen < 0 || nLen > MAX_SIZE)
875 vector<char> vch(nLen);
876 stream.read(&vch[0], nLen);
877 strMessageRet = string(vch.begin(), vch.end());
883 string EncodeBase64(string s)
888 b64 = BIO_new(BIO_f_base64());
889 BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
890 bmem = BIO_new(BIO_s_mem());
891 b64 = BIO_push(b64, bmem);
892 BIO_write(b64, s.c_str(), s.size());
894 BIO_get_mem_ptr(b64, &bptr);
896 string result(bptr->data, bptr->length);
902 string DecodeBase64(string s)
906 char* buffer = static_cast<char*>(calloc(s.size(), sizeof(char)));
908 b64 = BIO_new(BIO_f_base64());
909 BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
910 bmem = BIO_new_mem_buf(const_cast<char*>(s.c_str()), s.size());
911 bmem = BIO_push(b64, bmem);
912 BIO_read(bmem, buffer, s.size());
915 string result(buffer);
920 bool HTTPAuthorized(map<string, string>& mapHeaders)
922 string strAuth = mapHeaders["Authorization"];
923 if (strAuth.substr(0,6) != "Basic ")
925 string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
926 string strUserPass = DecodeBase64(strUserPass64);
927 string::size_type nColon = strUserPass.find(":");
928 if (nColon == string::npos)
930 string strUser = strUserPass.substr(0, nColon);
931 string strPassword = strUserPass.substr(nColon+1);
932 return (strUser == mapArgs["-rpcuser"] && strPassword == mapArgs["-rpcpassword"]);
936 // JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
937 // but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
938 // unspecified (HTTP errors and contents of 'error').
940 // 1.0 spec: http://json-rpc.org/wiki/specification
941 // 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
942 // http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
945 string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
948 request.push_back(Pair("method", strMethod));
949 request.push_back(Pair("params", params));
950 request.push_back(Pair("id", id));
951 return write_string(Value(request), false) + "\n";
954 string JSONRPCReply(const Value& result, const Value& error, const Value& id)
957 if (error.type() != null_type)
958 reply.push_back(Pair("result", Value::null));
960 reply.push_back(Pair("result", result));
961 reply.push_back(Pair("error", error));
962 reply.push_back(Pair("id", id));
963 return write_string(Value(reply), false) + "\n";
966 bool ClientAllowed(const string& strAddress)
968 if (strAddress == asio::ip::address_v4::loopback().to_string())
970 const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
971 foreach(string strAllow, vAllow)
972 if (WildcardMatch(strAddress, strAllow))
979 // IOStream device that speaks SSL but can also speak non-SSL
981 class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {
983 SSLIOStreamDevice(SSLStream &streamIn, bool fUseSSLIn) : stream(streamIn)
986 fNeedHandshake = fUseSSLIn;
989 void handshake(ssl::stream_base::handshake_type role)
991 if (!fNeedHandshake) return;
992 fNeedHandshake = false;
993 stream.handshake(role);
995 std::streamsize read(char* s, std::streamsize n)
997 handshake(ssl::stream_base::server); // HTTPS servers read first
998 if (fUseSSL) return stream.read_some(asio::buffer(s, n));
999 return stream.next_layer().read_some(asio::buffer(s, n));
1001 std::streamsize write(const char* s, std::streamsize n)
1003 handshake(ssl::stream_base::client); // HTTPS clients write first
1004 if (fUseSSL) return asio::write(stream, asio::buffer(s, n));
1005 return asio::write(stream.next_layer(), asio::buffer(s, n));
1007 bool connect(const std::string& server, const std::string& port)
1009 ip::tcp::resolver resolver(stream.get_io_service());
1010 ip::tcp::resolver::query query(server.c_str(), port.c_str());
1011 ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
1012 ip::tcp::resolver::iterator end;
1013 boost::system::error_code error = asio::error::host_not_found;
1014 while (error && endpoint_iterator != end)
1016 stream.lowest_layer().close();
1017 stream.lowest_layer().connect(*endpoint_iterator++, error);
1025 bool fNeedHandshake;
1031 void ThreadRPCServer(void* parg)
1033 IMPLEMENT_RANDOMIZE_STACK(ThreadRPCServer(parg));
1036 vnThreadsRunning[4]++;
1037 ThreadRPCServer2(parg);
1038 vnThreadsRunning[4]--;
1040 catch (std::exception& e) {
1041 vnThreadsRunning[4]--;
1042 PrintException(&e, "ThreadRPCServer()");
1044 vnThreadsRunning[4]--;
1045 PrintException(NULL, "ThreadRPCServer()");
1047 printf("ThreadRPCServer exiting\n");
1050 void ThreadRPCServer2(void* parg)
1052 printf("ThreadRPCServer started\n");
1054 if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
1056 string strWhatAmI = "To use bitcoind";
1057 if (mapArgs.count("-server"))
1058 strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
1059 else if (mapArgs.count("-daemon"))
1060 strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
1062 _("Warning: %s, you must set rpcpassword=<password>\nin the configuration file: %s\n"
1063 "If the file does not exist, create it with owner-readable-only file permissions.\n"),
1065 GetConfigFile().c_str());
1066 CreateThread(Shutdown, NULL);
1070 bool fUseSSL = (mapArgs.count("-rpcssl") > 0);
1071 asio::ip::address bindAddress = mapArgs.count("-rpcallowip") ? asio::ip::address_v4::any() : asio::ip::address_v4::loopback();
1073 asio::io_service io_service;
1074 ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", 8332));
1075 ip::tcp::acceptor acceptor(io_service, endpoint);
1078 ssl::context context(io_service, ssl::context::sslv23);
1081 context.set_options(ssl::context::no_sslv2);
1082 filesystem::path certfile = GetArg("-rpcsslcertificatechainfile", "server.cert");
1083 if (!certfile.is_complete()) certfile = filesystem::path(GetDataDir()) / certfile;
1084 if (filesystem::exists(certfile)) context.use_certificate_chain_file(certfile.string().c_str());
1085 else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", certfile.string().c_str());
1086 filesystem::path pkfile = GetArg("-rpcsslprivatekeyfile", "server.pem");
1087 if (!pkfile.is_complete()) pkfile = filesystem::path(GetDataDir()) / pkfile;
1088 if (filesystem::exists(pkfile)) context.use_private_key_file(pkfile.string().c_str(), ssl::context::pem);
1089 else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pkfile.string().c_str());
1091 string ciphers = GetArg("-rpcsslciphers",
1092 "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
1093 SSL_CTX_set_cipher_list(context.impl(), ciphers.c_str());
1097 throw runtime_error("-rpcssl=true, but bitcoin compiled without full openssl libraries.");
1102 // Accept connection
1104 SSLStream sslStream(io_service, context);
1105 SSLIOStreamDevice d(sslStream, fUseSSL);
1106 iostreams::stream<SSLIOStreamDevice> stream(d);
1108 ip::tcp::iostream stream;
1111 ip::tcp::endpoint peer;
1112 vnThreadsRunning[4]--;
1114 acceptor.accept(sslStream.lowest_layer(), peer);
1116 acceptor.accept(*stream.rdbuf(), peer);
1118 vnThreadsRunning[4]++;
1122 // Restrict callers by IP
1123 if (!ClientAllowed(peer.address().to_string()))
1127 map<string, string> mapHeaders;
1129 ReadHTTP(stream, mapHeaders, strRequest);
1131 // Check authorization
1132 if (mapHeaders.count("Authorization") == 0)
1134 stream << HTTPReply(401, "") << std::flush;
1137 if (!HTTPAuthorized(mapHeaders))
1139 // Deter brute-forcing short passwords
1140 if (mapArgs["-rpcpassword"].size() < 15)
1143 stream << HTTPReply(401, "") << std::flush;
1144 printf("ThreadRPCServer incorrect password attempt\n");
1148 Value id = Value::null;
1153 if (!read_string(strRequest, valRequest) || valRequest.type() != obj_type)
1154 throw JSONRPCError(-32700, "Parse error");
1155 const Object& request = valRequest.get_obj();
1157 // Parse id now so errors from here on will have the id
1158 id = find_value(request, "id");
1161 Value valMethod = find_value(request, "method");
1162 if (valMethod.type() == null_type)
1163 throw JSONRPCError(-32600, "Missing method");
1164 if (valMethod.type() != str_type)
1165 throw JSONRPCError(-32600, "Method must be a string");
1166 string strMethod = valMethod.get_str();
1167 printf("ThreadRPCServer method=%s\n", strMethod.c_str());
1170 Value valParams = find_value(request, "params");
1172 if (valParams.type() == array_type)
1173 params = valParams.get_array();
1174 else if (valParams.type() == null_type)
1177 throw JSONRPCError(-32600, "Params must be an array");
1180 map<string, rpcfn_type>::iterator mi = mapCallTable.find(strMethod);
1181 if (mi == mapCallTable.end())
1182 throw JSONRPCError(-32601, "Method not found");
1184 // Observe safe mode
1185 string strWarning = GetWarnings("rpc");
1186 if (strWarning != "" && !mapArgs.count("-disablesafemode") && !setAllowInSafeMode.count(strMethod))
1187 throw JSONRPCError(-2, string("Safe mode: ") + strWarning);
1192 Value result = (*(*mi).second)(params, false);
1195 string strReply = JSONRPCReply(result, Value::null, id);
1196 stream << HTTPReply(200, strReply) << std::flush;
1198 catch (std::exception& e)
1200 // Send error reply from method
1201 string strReply = JSONRPCReply(Value::null, JSONRPCError(-1, e.what()), id);
1202 stream << HTTPReply(500, strReply) << std::flush;
1205 catch (Object& objError)
1207 // Send error reply from json-rpc error object
1209 int code = find_value(objError, "code").get_int();
1210 if (code == -32600) nStatus = 400;
1211 else if (code == -32601) nStatus = 404;
1212 string strReply = JSONRPCReply(Value::null, objError, id);
1213 stream << HTTPReply(nStatus, strReply) << std::flush;
1215 catch (std::exception& e)
1217 // Send error reply from other json-rpc parsing errors
1218 string strReply = JSONRPCReply(Value::null, JSONRPCError(-32700, e.what()), id);
1219 stream << HTTPReply(500, strReply) << std::flush;
1227 Object CallRPC(const string& strMethod, const Array& params)
1229 if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
1230 throw runtime_error(strprintf(
1231 _("You must set rpcpassword=<password> in the configuration file:\n%s\n"
1232 "If the file does not exist, create it with owner-readable-only file permissions."),
1233 GetConfigFile().c_str()));
1235 // Connect to localhost
1236 bool fUseSSL = (mapArgs.count("-rpcssl") > 0);
1238 asio::io_service io_service;
1239 ssl::context context(io_service, ssl::context::sslv23);
1240 context.set_options(ssl::context::no_sslv2);
1241 SSLStream sslStream(io_service, context);
1242 SSLIOStreamDevice d(sslStream, fUseSSL);
1243 iostreams::stream<SSLIOStreamDevice> stream(d);
1244 if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", "8332")))
1245 throw runtime_error("couldn't connect to server");
1248 throw runtime_error("-rpcssl=true, but bitcoin compiled without full openssl libraries.");
1250 ip::tcp::iostream stream(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", "8332"));
1252 throw runtime_error("couldn't connect to server");
1256 // HTTP basic authentication
1257 string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
1258 map<string, string> mapRequestHeaders;
1259 mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
1262 string strRequest = JSONRPCRequest(strMethod, params, 1);
1263 string strPost = HTTPPost(strRequest, mapRequestHeaders);
1264 stream << strPost << std::flush;
1267 map<string, string> mapHeaders;
1269 int nStatus = ReadHTTP(stream, mapHeaders, strReply);
1271 throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
1272 else if (nStatus >= 400 && nStatus != 400 && nStatus != 404 && nStatus != 500)
1273 throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
1274 else if (strReply.empty())
1275 throw runtime_error("no response from server");
1279 if (!read_string(strReply, valReply))
1280 throw runtime_error("couldn't parse reply from server");
1281 const Object& reply = valReply.get_obj();
1283 throw runtime_error("expected reply to have result, error and id properties");
1291 template<typename T>
1292 void ConvertTo(Value& value)
1294 if (value.type() == str_type)
1296 // reinterpret string as unquoted json value
1298 if (!read_string(value.get_str(), value2))
1299 throw runtime_error("type mismatch");
1300 value = value2.get_value<T>();
1304 value = value.get_value<T>();
1308 int CommandLineRPC(int argc, char *argv[])
1315 while (argc > 1 && IsSwitchChar(argv[1][0]))
1323 throw runtime_error("too few parameters");
1324 string strMethod = argv[1];
1326 // Parameters default to strings
1328 for (int i = 2; i < argc; i++)
1329 params.push_back(argv[i]);
1330 int n = params.size();
1333 // Special case non-string parameter types
1335 if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]);
1336 if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1337 if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);
1338 if (strMethod == "listtransactions" && n > 0) ConvertTo<boost::int64_t>(params[0]);
1339 if (strMethod == "listtransactions" && n > 1) ConvertTo<bool>(params[1]);
1340 if (strMethod == "getamountreceived" && n > 1) ConvertTo<boost::int64_t>(params[1]); // deprecated
1341 if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1342 if (strMethod == "getreceivedbylabel" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1343 if (strMethod == "getallreceived" && n > 0) ConvertTo<boost::int64_t>(params[0]); // deprecated
1344 if (strMethod == "getallreceived" && n > 1) ConvertTo<bool>(params[1]);
1345 if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
1346 if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);
1347 if (strMethod == "listreceivedbylabel" && n > 0) ConvertTo<boost::int64_t>(params[0]);
1348 if (strMethod == "listreceivedbylabel" && n > 1) ConvertTo<bool>(params[1]);
1351 Object reply = CallRPC(strMethod, params);
1354 const Value& result = find_value(reply, "result");
1355 const Value& error = find_value(reply, "error");
1356 const Value& id = find_value(reply, "id");
1358 if (error.type() != null_type)
1361 strPrint = "error: " + write_string(error, false);
1362 int code = find_value(error.get_obj(), "code").get_int();
1368 if (result.type() == null_type)
1370 else if (result.type() == str_type)
1371 strPrint = result.get_str();
1373 strPrint = write_string(result, true);
1376 catch (std::exception& e)
1378 strPrint = string("error: ") + e.what();
1383 PrintException(NULL, "CommandLineRPC()");
1388 #if defined(__WXMSW__) && defined(GUI)
1389 // Windows GUI apps can't print to command line,
1390 // so settle for a message box yuck
1391 MyMessageBox(strPrint, "Bitcoin", wxOK);
1393 fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
1403 int main(int argc, char *argv[])
1406 // Turn off microsoft heap dump noise
1407 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
1408 _CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
1410 setbuf(stdin, NULL);
1411 setbuf(stdout, NULL);
1412 setbuf(stderr, NULL);
1416 if (argc >= 2 && string(argv[1]) == "-server")
1418 printf("server ready\n");
1419 ThreadRPCServer(NULL);
1423 return CommandLineRPC(argc, argv);
1426 catch (std::exception& e) {
1427 PrintException(&e, "main()");
1429 PrintException(NULL, "main()");