Bitcoin v0.3.10 · 2010-08-15
rpc.cpp
1// Copyright (c) 2010 Satoshi Nakamoto2// Distributed under the MIT/X11 software license, see the accompanying3// file license.txt or http://www.opensource.org/licenses/mit-license.php.45#include "headers.h"6#undef printf7#include <boost/asio.hpp>8#include "json/json_spirit_reader_template.h"9#include "json/json_spirit_writer_template.h"10#include "json/json_spirit_utils.h"11#define printf OutputDebugStringF12// MinGW 3.4.5 gets "fatal error: had to relocate PCH" if the json headers are13// precompiled in headers.h. The problem might be when the pch file goes over14// a certain size around 145MB. If we need access to json_spirit outside this15// file, we could use the compiled json_spirit option.1617using boost::asio::ip::tcp;18using namespace json_spirit;1920void ThreadRPCServer2(void* parg);21typedef Value(*rpcfn_type)(const Array& params, bool fHelp);22extern map<string, rpcfn_type> mapCallTable;23242526void PrintConsole(const char* format, ...)27{28 char buffer[50000];29 int limit = sizeof(buffer);30 va_list arg_ptr;31 va_start(arg_ptr, format);32 int ret = _vsnprintf(buffer, limit, format, arg_ptr);33 va_end(arg_ptr);34 if (ret < 0 || ret >= limit)35 {36 ret = limit - 1;37 buffer[limit-1] = 0;38 }39#if defined(__WXMSW__) && defined(GUI)40 MyMessageBox(buffer, "Bitcoin", wxOK | wxICON_EXCLAMATION);41#else42 fprintf(stdout, "%s", buffer);43#endif44}4546474849505152///53/// Note: This interface may still be subject to change.54///555657Value help(const Array& params, bool fHelp)58{59 if (fHelp || params.size() > 1)60 throw runtime_error(61 "help [command]\n"62 "List commands, or get help for a command.");6364 string strCommand;65 if (params.size() > 0)66 strCommand = params[0].get_str();6768 string strRet;69 set<rpcfn_type> setDone;70 for (map<string, rpcfn_type>::iterator mi = mapCallTable.begin(); mi != mapCallTable.end(); ++mi)71 {72 string strMethod = (*mi).first;73 // We already filter duplicates, but these deprecated screw up the sort order74 if (strMethod == "getamountreceived" ||75 strMethod == "getallreceived")76 continue;77 if (strCommand != "" && strMethod != strCommand)78 continue;79 try80 {81 Array params;82 rpcfn_type pfn = (*mi).second;83 if (setDone.insert(pfn).second)84 (*pfn)(params, true);85 }86 catch (std::exception& e)87 {88 // Help text is returned in an exception89 string strHelp = string(e.what());90 if (strCommand == "")91 if (strHelp.find('\n') != -1)92 strHelp = strHelp.substr(0, strHelp.find('\n'));93 strRet += strHelp + "\n";94 }95 }96 if (strRet == "")97 strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());98 strRet = strRet.substr(0,strRet.size()-1);99 return strRet;100}101102103Value stop(const Array& params, bool fHelp)104{105 if (fHelp || params.size() != 0)106 throw runtime_error(107 "stop\n"108 "Stop bitcoin server.");109110 // Shutdown will take long enough that the response should get back111 CreateThread(Shutdown, NULL);112 return "bitcoin server stopping";113}114115116Value getblockcount(const Array& params, bool fHelp)117{118 if (fHelp || params.size() != 0)119 throw runtime_error(120 "getblockcount\n"121 "Returns the number of blocks in the longest block chain.");122123 return nBestHeight + 1;124}125126127Value getblocknumber(const Array& params, bool fHelp)128{129 if (fHelp || params.size() != 0)130 throw runtime_error(131 "getblocknumber\n"132 "Returns the block number of the latest block in the longest block chain.");133134 return nBestHeight;135}136137138Value getconnectioncount(const Array& params, bool fHelp)139{140 if (fHelp || params.size() != 0)141 throw runtime_error(142 "getconnectioncount\n"143 "Returns the number of connections to other nodes.");144145 return (int)vNodes.size();146}147148149double GetDifficulty()150{151 // Floating point number that is a multiple of the minimum difficulty,152 // minimum difficulty = 1.0.153 if (pindexBest == NULL)154 return 1.0;155 int nShift = 256 - 32 - 31; // to fit in a uint156 double dMinimum = (CBigNum().SetCompact(bnProofOfWorkLimit.GetCompact()) >> nShift).getuint();157 double dCurrently = (CBigNum().SetCompact(pindexBest->nBits) >> nShift).getuint();158 return dMinimum / dCurrently;159}160161Value getdifficulty(const Array& params, bool fHelp)162{163 if (fHelp || params.size() != 0)164 throw runtime_error(165 "getdifficulty\n"166 "Returns the proof-of-work difficulty as a multiple of the minimum difficulty.");167168 return GetDifficulty();169}170171172Value getbalance(const Array& params, bool fHelp)173{174 if (fHelp || params.size() != 0)175 throw runtime_error(176 "getbalance\n"177 "Returns the server's available balance.");178179 return ((double)GetBalance() / (double)COIN);180}181182183Value getgenerate(const Array& params, bool fHelp)184{185 if (fHelp || params.size() != 0)186 throw runtime_error(187 "getgenerate\n"188 "Returns true or false.");189190 return (bool)fGenerateBitcoins;191}192193194Value setgenerate(const Array& params, bool fHelp)195{196 if (fHelp || params.size() < 1 || params.size() > 2)197 throw runtime_error(198 "setgenerate <generate> [genproclimit]\n"199 "<generate> is true or false to turn generation on or off.\n"200 "Generation is limited to [genproclimit] processors, -1 is unlimited.");201202 bool fGenerate = true;203 if (params.size() > 0)204 fGenerate = params[0].get_bool();205206 if (params.size() > 1)207 {208 int nGenProcLimit = params[1].get_int();209 fLimitProcessors = (nGenProcLimit != -1);210 CWalletDB().WriteSetting("fLimitProcessors", fLimitProcessors);211 if (nGenProcLimit != -1)212 CWalletDB().WriteSetting("nLimitProcessors", nLimitProcessors = nGenProcLimit);213 }214215 GenerateBitcoins(fGenerate);216 return Value::null;217}218219220Value gethashespersec(const Array& params, bool fHelp)221{222 if (fHelp || params.size() != 0)223 throw runtime_error(224 "gethashespersec\n"225 "Returns a recent hashes per second performance measurement while generating.");226227 if (GetTimeMillis() - nHPSTimerStart > 8000)228 return (boost::int64_t)0;229 return (boost::int64_t)dHashesPerSec;230}231232233Value getinfo(const Array& params, bool fHelp)234{235 if (fHelp || params.size() != 0)236 throw runtime_error(237 "getinfo\n"238 "Returns an object containing various state info.");239240 Object obj;241 obj.push_back(Pair("version", (int)VERSION));242 obj.push_back(Pair("balance", (double)GetBalance() / (double)COIN));243 obj.push_back(Pair("blocks", (int)nBestHeight + 1));244 obj.push_back(Pair("connections", (int)vNodes.size()));245 obj.push_back(Pair("proxy", (fUseProxy ? addrProxy.ToStringIPPort() : string())));246 obj.push_back(Pair("generate", (bool)fGenerateBitcoins));247 obj.push_back(Pair("genproclimit", (int)(fLimitProcessors ? nLimitProcessors : -1)));248 obj.push_back(Pair("difficulty", (double)GetDifficulty()));249 obj.push_back(Pair("hashespersec", gethashespersec(params, false)));250 return obj;251}252253254Value getnewaddress(const Array& params, bool fHelp)255{256 if (fHelp || params.size() > 1)257 throw runtime_error(258 "getnewaddress [label]\n"259 "Returns a new bitcoin address for receiving payments. "260 "If [label] is specified (recommended), it is added to the address book "261 "so payments received with the address will be labeled.");262263 // Parse the label first so we don't generate a key if there's an error264 string strLabel;265 if (params.size() > 0)266 strLabel = params[0].get_str();267268 // Generate a new key that is added to wallet269 string strAddress = PubKeyToAddress(GenerateNewKey());270271 SetAddressBookName(strAddress, strLabel);272 return strAddress;273}274275276Value setlabel(const Array& params, bool fHelp)277{278 if (fHelp || params.size() < 1 || params.size() > 2)279 throw runtime_error(280 "setlabel <bitcoinaddress> <label>\n"281 "Sets the label associated with the given address.");282283 string strAddress = params[0].get_str();284 string strLabel;285 if (params.size() > 1)286 strLabel = params[1].get_str();287288 SetAddressBookName(strAddress, strLabel);289 return Value::null;290}291292293Value getlabel(const Array& params, bool fHelp)294{295 if (fHelp || params.size() != 1)296 throw runtime_error(297 "getlabel <bitcoinaddress>\n"298 "Returns the label associated with the given address.");299300 string strAddress = params[0].get_str();301302 string strLabel;303 CRITICAL_BLOCK(cs_mapAddressBook)304 {305 map<string, string>::iterator mi = mapAddressBook.find(strAddress);306 if (mi != mapAddressBook.end() && !(*mi).second.empty())307 strLabel = (*mi).second;308 }309 return strLabel;310}311312313Value getaddressesbylabel(const Array& params, bool fHelp)314{315 if (fHelp || params.size() != 1)316 throw runtime_error(317 "getaddressesbylabel <label>\n"318 "Returns the list of addresses with the given label.");319320 string strLabel = params[0].get_str();321322 // Find all addresses that have the given label323 Array ret;324 CRITICAL_BLOCK(cs_mapAddressBook)325 {326 foreach(const PAIRTYPE(string, string)& item, mapAddressBook)327 {328 const string& strAddress = item.first;329 const string& strName = item.second;330 if (strName == strLabel)331 {332 // We're only adding valid bitcoin addresses and not ip addresses333 CScript scriptPubKey;334 if (scriptPubKey.SetBitcoinAddress(strAddress))335 ret.push_back(strAddress);336 }337 }338 }339 return ret;340}341342343Value sendtoaddress(const Array& params, bool fHelp)344{345 if (fHelp || params.size() < 2 || params.size() > 4)346 throw runtime_error(347 "sendtoaddress <bitcoinaddress> <amount> [comment] [comment-to]\n"348 "<amount> is a real and is rounded to the nearest 0.01");349350 string strAddress = params[0].get_str();351352 // Amount353 if (params[1].get_real() <= 0.0 || params[1].get_real() > 21000000.0)354 throw runtime_error("Invalid amount");355 int64 nAmount = roundint64(params[1].get_real() * 100.00) * CENT;356357 // Wallet comments358 CWalletTx wtx;359 if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty())360 wtx.mapValue["message"] = params[2].get_str();361 if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())362 wtx.mapValue["to"] = params[3].get_str();363364 string strError = SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);365 if (strError != "")366 throw runtime_error(strError);367 return "sent";368}369370371Value listtransactions(const Array& params, bool fHelp)372{373 if (fHelp || params.size() > 2)374 throw runtime_error(375 "listtransactions [count=10] [includegenerated=false]\n"376 "Returns up to [count] most recent transactions.");377378 int64 nCount = 10;379 if (params.size() > 0)380 nCount = params[0].get_int64();381 bool fGenerated = false;382 if (params.size() > 1)383 fGenerated = params[1].get_bool();384385 Array ret;386 //// not finished387 ret.push_back("not implemented yet");388 return ret;389}390391392Value getreceivedbyaddress(const Array& params, bool fHelp)393{394 if (fHelp || params.size() < 1 || params.size() > 2)395 throw runtime_error(396 "getreceivedbyaddress <bitcoinaddress> [minconf=1]\n"397 "Returns the total amount received by <bitcoinaddress> in transactions with at least [minconf] confirmations.");398399 // Bitcoin address400 string strAddress = params[0].get_str();401 CScript scriptPubKey;402 if (!scriptPubKey.SetBitcoinAddress(strAddress))403 throw runtime_error("Invalid bitcoin address");404 if (!IsMine(scriptPubKey))405 return (double)0.0;406407 // Minimum confirmations408 int nMinDepth = 1;409 if (params.size() > 1)410 nMinDepth = params[1].get_int();411412 // Tally413 int64 nAmount = 0;414 CRITICAL_BLOCK(cs_mapWallet)415 {416 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)417 {418 const CWalletTx& wtx = (*it).second;419 if (wtx.IsCoinBase() || !wtx.IsFinal())420 continue;421422 foreach(const CTxOut& txout, wtx.vout)423 if (txout.scriptPubKey == scriptPubKey)424 if (wtx.GetDepthInMainChain() >= nMinDepth)425 nAmount += txout.nValue;426 }427 }428429 return (double)nAmount / (double)COIN;430}431432433Value getreceivedbylabel(const Array& params, bool fHelp)434{435 if (fHelp || params.size() < 1 || params.size() > 2)436 throw runtime_error(437 "getreceivedbylabel <label> [minconf=1]\n"438 "Returns the total amount received by addresses with <label> in transactions with at least [minconf] confirmations.");439440 // Get the set of pub keys that have the label441 string strLabel = params[0].get_str();442 set<CScript> setPubKey;443 CRITICAL_BLOCK(cs_mapAddressBook)444 {445 foreach(const PAIRTYPE(string, string)& item, mapAddressBook)446 {447 const string& strAddress = item.first;448 const string& strName = item.second;449 if (strName == strLabel)450 {451 // We're only counting our own valid bitcoin addresses and not ip addresses452 CScript scriptPubKey;453 if (scriptPubKey.SetBitcoinAddress(strAddress))454 if (IsMine(scriptPubKey))455 setPubKey.insert(scriptPubKey);456 }457 }458 }459460 // Minimum confirmations461 int nMinDepth = 1;462 if (params.size() > 1)463 nMinDepth = params[1].get_int();464465 // Tally466 int64 nAmount = 0;467 CRITICAL_BLOCK(cs_mapWallet)468 {469 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)470 {471 const CWalletTx& wtx = (*it).second;472 if (wtx.IsCoinBase() || !wtx.IsFinal())473 continue;474475 foreach(const CTxOut& txout, wtx.vout)476 if (setPubKey.count(txout.scriptPubKey))477 if (wtx.GetDepthInMainChain() >= nMinDepth)478 nAmount += txout.nValue;479 }480 }481482 return (double)nAmount / (double)COIN;483}484485486487struct tallyitem488{489 int64 nAmount;490 int nConf;491 tallyitem()492 {493 nAmount = 0;494 nConf = INT_MAX;495 }496};497498Value ListReceived(const Array& params, bool fByLabels)499{500 // Minimum confirmations501 int nMinDepth = 1;502 if (params.size() > 0)503 nMinDepth = params[0].get_int();504505 // Whether to include empty accounts506 bool fIncludeEmpty = false;507 if (params.size() > 1)508 fIncludeEmpty = params[1].get_bool();509510 // Tally511 map<uint160, tallyitem> mapTally;512 CRITICAL_BLOCK(cs_mapWallet)513 {514 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)515 {516 const CWalletTx& wtx = (*it).second;517 if (wtx.IsCoinBase() || !wtx.IsFinal())518 continue;519520 int nDepth = wtx.GetDepthInMainChain();521 if (nDepth < nMinDepth)522 continue;523524 foreach(const CTxOut& txout, wtx.vout)525 {526 // Only counting our own bitcoin addresses and not ip addresses527 uint160 hash160 = txout.scriptPubKey.GetBitcoinAddressHash160();528 if (hash160 == 0 || !mapPubKeys.count(hash160)) // IsMine529 continue;530531 tallyitem& item = mapTally[hash160];532 item.nAmount += txout.nValue;533 item.nConf = min(item.nConf, nDepth);534 }535 }536 }537538 // Reply539 Array ret;540 map<string, tallyitem> mapLabelTally;541 CRITICAL_BLOCK(cs_mapAddressBook)542 {543 foreach(const PAIRTYPE(string, string)& item, mapAddressBook)544 {545 const string& strAddress = item.first;546 const string& strLabel = item.second;547 uint160 hash160;548 if (!AddressToHash160(strAddress, hash160))549 continue;550 map<uint160, tallyitem>::iterator it = mapTally.find(hash160);551 if (it == mapTally.end() && !fIncludeEmpty)552 continue;553554 int64 nAmount = 0;555 int nConf = INT_MAX;556 if (it != mapTally.end())557 {558 nAmount = (*it).second.nAmount;559 nConf = (*it).second.nConf;560 }561562 if (fByLabels)563 {564 tallyitem& item = mapLabelTally[strLabel];565 item.nAmount += nAmount;566 item.nConf = min(item.nConf, nConf);567 }568 else569 {570 Object obj;571 obj.push_back(Pair("address", strAddress));572 obj.push_back(Pair("label", strLabel));573 obj.push_back(Pair("amount", (double)nAmount / (double)COIN));574 obj.push_back(Pair("confirmations", (nConf == INT_MAX ? 0 : nConf)));575 ret.push_back(obj);576 }577 }578 }579580 if (fByLabels)581 {582 for (map<string, tallyitem>::iterator it = mapLabelTally.begin(); it != mapLabelTally.end(); ++it)583 {584 int64 nAmount = (*it).second.nAmount;585 int nConf = (*it).second.nConf;586 Object obj;587 obj.push_back(Pair("label", (*it).first));588 obj.push_back(Pair("amount", (double)nAmount / (double)COIN));589 obj.push_back(Pair("confirmations", (nConf == INT_MAX ? 0 : nConf)));590 ret.push_back(obj);591 }592 }593594 return ret;595}596597Value listreceivedbyaddress(const Array& params, bool fHelp)598{599 if (fHelp || params.size() > 2)600 throw runtime_error(601 "listreceivedbyaddress [minconf=1] [includeempty=false]\n"602 "[minconf] is the minimum number of confirmations before payments are included.\n"603 "[includeempty] whether to include addresses that haven't received any payments.\n"604 "Returns an array of objects containing:\n"605 " \"address\" : receiving address\n"606 " \"label\" : the label of the receiving address\n"607 " \"amount\" : total amount received by the address\n"608 " \"confirmations\" : number of confirmations of the most recent transaction included");609610 return ListReceived(params, false);611}612613Value listreceivedbylabel(const Array& params, bool fHelp)614{615 if (fHelp || params.size() > 2)616 throw runtime_error(617 "listreceivedbylabel [minconf=1] [includeempty=false]\n"618 "[minconf] is the minimum number of confirmations before payments are included.\n"619 "[includeempty] whether to include labels that haven't received any payments.\n"620 "Returns an array of objects containing:\n"621 " \"label\" : the label of the receiving addresses\n"622 " \"amount\" : total amount received by addresses with this label\n"623 " \"confirmations\" : number of confirmations of the most recent transaction included");624625 return ListReceived(params, true);626}627628629630631632633634635636637638639640//641// Call Table642//643644pair<string, rpcfn_type> pCallTable[] =645{646 make_pair("help", &help),647 make_pair("stop", &stop),648 make_pair("getblockcount", &getblockcount),649 make_pair("getblocknumber", &getblocknumber),650 make_pair("getconnectioncount", &getconnectioncount),651 make_pair("getdifficulty", &getdifficulty),652 make_pair("getbalance", &getbalance),653 make_pair("getgenerate", &getgenerate),654 make_pair("setgenerate", &setgenerate),655 make_pair("gethashespersec", &gethashespersec),656 make_pair("getinfo", &getinfo),657 make_pair("getnewaddress", &getnewaddress),658 make_pair("setlabel", &setlabel),659 make_pair("getlabel", &getlabel),660 make_pair("getaddressesbylabel", &getaddressesbylabel),661 make_pair("sendtoaddress", &sendtoaddress),662 make_pair("getamountreceived", &getreceivedbyaddress), // deprecated, renamed to getreceivedbyaddress663 make_pair("getallreceived", &listreceivedbyaddress), // deprecated, renamed to listreceivedbyaddress664 make_pair("getreceivedbyaddress", &getreceivedbyaddress),665 make_pair("getreceivedbylabel", &getreceivedbylabel),666 make_pair("listreceivedbyaddress", &listreceivedbyaddress),667 make_pair("listreceivedbylabel", &listreceivedbylabel),668};669map<string, rpcfn_type> mapCallTable(pCallTable, pCallTable + sizeof(pCallTable)/sizeof(pCallTable[0]));670671672673674//675// HTTP protocol676//677// This ain't Apache. We're just using HTTP header for the length field678// and to be compatible with other JSON-RPC implementations.679//680681string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)682{683 ostringstream s;684 s << "POST / HTTP/1.1\r\n"685 << "User-Agent: json-rpc/1.0\r\n"686 << "Host: 127.0.0.1\r\n"687 << "Content-Type: application/json\r\n"688 << "Content-Length: " << strMsg.size() << "\r\n"689 << "Accept: application/json\r\n";690 for (map<string,string>::const_iterator it = mapRequestHeaders.begin(); it != mapRequestHeaders.end(); ++it)691 s << it->first << ": " << it->second << "\r\n";692 s << "\r\n" << strMsg;693694 return s.str();695}696697string HTTPReply(const string& strMsg, int nStatus=200)698{699 if (nStatus == 401)700 return "HTTP/1.0 401 Authorization Required\r\n"701 "Server: HTTPd/1.0\r\n"702 "Date: Sat, 08 Jul 2006 12:04:08 GMT\r\n"703 "WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"704 "Content-Type: text/html\r\n"705 "Content-Length: 311\r\n"706 "\r\n"707 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"708 "\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"709 "<HTML>\r\n"710 "<HEAD>\r\n"711 "<TITLE>Error</TITLE>\r\n"712 "<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"713 "</HEAD>\r\n"714 "<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"715 "</HTML>\r\n";716 string strStatus;717 if (nStatus == 200) strStatus = "OK";718 if (nStatus == 500) strStatus = "Internal Server Error";719 return strprintf(720 "HTTP/1.1 %d %s\r\n"721 "Connection: close\r\n"722 "Content-Length: %d\r\n"723 "Content-Type: application/json\r\n"724 "Date: Sat, 08 Jul 2006 12:04:08 GMT\r\n"725 "Server: json-rpc/1.0\r\n"726 "\r\n"727 "%s",728 nStatus,729 strStatus.c_str(),730 strMsg.size(),731 strMsg.c_str());732}733734int ReadHTTPStatus(tcp::iostream& stream)735{736 string str;737 getline(stream, str);738 vector<string> vWords;739 boost::split(vWords, str, boost::is_any_of(" "));740 int nStatus = atoi(vWords[1].c_str());741 return nStatus;742}743744int ReadHTTPHeader(tcp::iostream& stream, map<string, string>& mapHeadersRet)745{746 int nLen = 0;747 loop748 {749 string str;750 std::getline(stream, str);751 if (str.empty() || str == "\r")752 break;753 string::size_type nColon = str.find(":");754 if (nColon != string::npos)755 {756 string strHeader = str.substr(0, nColon);757 boost::trim(strHeader);758 string strValue = str.substr(nColon+1);759 boost::trim(strValue);760 mapHeadersRet[strHeader] = strValue;761 if (strHeader == "Content-Length")762 nLen = atoi(strValue.c_str());763 }764 }765 return nLen;766}767768int ReadHTTP(tcp::iostream& stream, map<string, string>& mapHeadersRet, string& strMessageRet)769{770 mapHeadersRet.clear();771 strMessageRet = "";772773 // Read status774 int nStatus = ReadHTTPStatus(stream);775776 // Read header777 int nLen = ReadHTTPHeader(stream, mapHeadersRet);778 if (nLen <= 0)779 return 500;780781 // Read message782 vector<char> vch(nLen);783 stream.read(&vch[0], nLen);784 strMessageRet = string(vch.begin(), vch.end());785786 return nStatus;787}788789string EncodeBase64(string s)790{791 BIO *b64, *bmem;792 BUF_MEM *bptr;793794 b64 = BIO_new(BIO_f_base64());795 BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);796 bmem = BIO_new(BIO_s_mem());797 b64 = BIO_push(b64, bmem);798 BIO_write(b64, s.c_str(), s.size());799 BIO_flush(b64);800 BIO_get_mem_ptr(b64, &bptr);801802 string result(bptr->data, bptr->length);803 BIO_free_all(b64);804805 return result;806}807808string DecodeBase64(string s)809{810 BIO *b64, *bmem;811812 char* buffer = static_cast<char*>(calloc(s.size(), sizeof(char)));813814 b64 = BIO_new(BIO_f_base64());815 BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);816 bmem = BIO_new_mem_buf(const_cast<char*>(s.c_str()), s.size());817 bmem = BIO_push(b64, bmem);818 BIO_read(bmem, buffer, s.size());819 BIO_free_all(bmem);820821 string result(buffer);822 free(buffer);823 return result;824}825826bool HTTPAuthorized(map<string, string>& mapHeaders)827{828 string strAuth = mapHeaders["Authorization"];829 if (strAuth.substr(0,6) != "Basic ")830 return false;831 string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);832 string strUserPass = DecodeBase64(strUserPass64);833 string::size_type nColon = strUserPass.find(":");834 if (nColon == string::npos)835 return false;836 string strUser = strUserPass.substr(0, nColon);837 string strPassword = strUserPass.substr(nColon+1);838 return (strUser == mapArgs["-rpcuser"] && strPassword == mapArgs["-rpcpassword"]);839}840841//842// JSON-RPC protocol843//844// http://json-rpc.org/wiki/specification845// http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx846//847848string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)849{850 Object request;851 request.push_back(Pair("method", strMethod));852 request.push_back(Pair("params", params));853 request.push_back(Pair("id", id));854 return write_string(Value(request), false) + "\n";855}856857string JSONRPCReply(const Value& result, const Value& error, const Value& id)858{859 Object reply;860 if (error.type() != null_type)861 reply.push_back(Pair("result", Value::null));862 else863 reply.push_back(Pair("result", result));864 reply.push_back(Pair("error", error));865 reply.push_back(Pair("id", id));866 return write_string(Value(reply), false) + "\n";867}868869870871872void ThreadRPCServer(void* parg)873{874 IMPLEMENT_RANDOMIZE_STACK(ThreadRPCServer(parg));875 try876 {877 vnThreadsRunning[4]++;878 ThreadRPCServer2(parg);879 vnThreadsRunning[4]--;880 }881 catch (std::exception& e) {882 vnThreadsRunning[4]--;883 PrintException(&e, "ThreadRPCServer()");884 } catch (...) {885 vnThreadsRunning[4]--;886 PrintException(NULL, "ThreadRPCServer()");887 }888 printf("ThreadRPCServer exiting\n");889}890891void ThreadRPCServer2(void* parg)892{893 printf("ThreadRPCServer started\n");894895 if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")896 {897 string strWhatAmI = "To use bitcoind";898 if (mapArgs.count("-server"))899 strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");900 else if (mapArgs.count("-daemon"))901 strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");902 PrintConsole(903 _("Warning: %s, you must set rpcpassword=<password>\nin the configuration file: %s\n"904 "If the file does not exist, create it with owner-readable-only file permissions.\n"),905 strWhatAmI.c_str(),906 GetConfigFile().c_str());907 CreateThread(Shutdown, NULL);908 return;909 }910911 // Bind to loopback 127.0.0.1 so the socket can only be accessed locally912 boost::asio::io_service io_service;913 tcp::endpoint endpoint(boost::asio::ip::address_v4::loopback(), 8332);914 tcp::acceptor acceptor(io_service, endpoint);915916 loop917 {918 // Accept connection919 tcp::iostream stream;920 tcp::endpoint peer;921 vnThreadsRunning[4]--;922 acceptor.accept(*stream.rdbuf(), peer);923 vnThreadsRunning[4]++;924 if (fShutdown)925 return;926927 // Shouldn't be possible for anyone else to connect, but just in case928 if (peer.address().to_string() != "127.0.0.1")929 continue;930931 // Receive request932 map<string, string> mapHeaders;933 string strRequest;934 ReadHTTP(stream, mapHeaders, strRequest);935936 // Check authorization937 if (mapHeaders.count("Authorization") == 0)938 {939 stream << HTTPReply("", 401) << std::flush;940 continue;941 }942 if (!HTTPAuthorized(mapHeaders))943 {944 // Deter brute-forcing short passwords945 if (mapArgs["-rpcpassword"].size() < 15)946 Sleep(50);947948 stream << HTTPReply("", 401) << std::flush;949 printf("ThreadRPCServer incorrect password attempt\n");950 continue;951 }952953 // Handle multiple invocations per request954 string::iterator begin = strRequest.begin();955 while (skipspaces(begin), begin != strRequest.end())956 {957 string::iterator prev = begin;958 Value id;959 try960 {961 // Parse request962 Value valRequest;963 if (!read_range(begin, strRequest.end(), valRequest))964 throw runtime_error("Parse error.");965 const Object& request = valRequest.get_obj();966 if (find_value(request, "method").type() != str_type ||967 find_value(request, "params").type() != array_type)968 throw runtime_error("Invalid request.");969970 string strMethod = find_value(request, "method").get_str();971 const Array& params = find_value(request, "params").get_array();972 id = find_value(request, "id");973974 printf("ThreadRPCServer method=%s\n", strMethod.c_str());975976 // Observe lockdown977 if (IsLockdown() && !mapArgs.count("-overridesafety") && strMethod != "help" && strMethod != "stop" && strMethod != "getgenerate" && strMethod != "setgenerate")978 throw runtime_error("WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.");979980 // Execute981 map<string, rpcfn_type>::iterator mi = mapCallTable.find(strMethod);982 if (mi == mapCallTable.end())983 throw runtime_error("Method not found.");984 Value result = (*(*mi).second)(params, false);985986 // Send reply987 string strReply = JSONRPCReply(result, Value::null, id);988 stream << HTTPReply(strReply, 200) << std::flush;989 }990 catch (std::exception& e)991 {992 // Send error reply993 string strReply = JSONRPCReply(Value::null, e.what(), id);994 stream << HTTPReply(strReply, 500) << std::flush;995 }996 if (begin == prev)997 break;998 }999 }1000}10011002100310041005Value CallRPC(const string& strMethod, const Array& params)1006{1007 if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")1008 throw runtime_error(strprintf(1009 _("You must set rpcpassword=<password> in the configuration file:\n%s\n"1010 "If the file does not exist, create it with owner-readable-only file permissions."),1011 GetConfigFile().c_str()));10121013 // Connect to localhost1014 tcp::iostream stream("127.0.0.1", "8332");1015 if (stream.fail())1016 throw runtime_error("couldn't connect to server");10171018 // HTTP basic authentication1019 string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);1020 map<string, string> mapRequestHeaders;1021 mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;10221023 // Send request1024 string strRequest = JSONRPCRequest(strMethod, params, 1);1025 string strPost = HTTPPost(strRequest, mapRequestHeaders);1026 stream << strPost << std::flush;10271028 // Receive reply1029 map<string, string> mapHeaders;1030 string strReply;1031 int nStatus = ReadHTTP(stream, mapHeaders, strReply);1032 if (nStatus == 401)1033 throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");1034 else if (nStatus >= 400 && nStatus != 500)1035 throw runtime_error(strprintf("server returned HTTP error %d", nStatus));1036 else if (strReply.empty())1037 throw runtime_error("no response from server");10381039 // Parse reply1040 Value valReply;1041 if (!read_string(strReply, valReply))1042 throw runtime_error("couldn't parse reply from server");1043 const Object& reply = valReply.get_obj();1044 if (reply.empty())1045 throw runtime_error("expected reply to have result, error and id properties");10461047 const Value& result = find_value(reply, "result");1048 const Value& error = find_value(reply, "error");1049 const Value& id = find_value(reply, "id");10501051 if (error.type() == str_type)1052 throw runtime_error(error.get_str());1053 else if (error.type() != null_type)1054 throw runtime_error(write_string(error, false));1055 return result;1056}10571058105910601061template<typename T>1062void ConvertTo(Value& value)1063{1064 if (value.type() == str_type)1065 {1066 // reinterpret string as unquoted json value1067 Value value2;1068 if (!read_string(value.get_str(), value2))1069 throw runtime_error("type mismatch");1070 value = value2.get_value<T>();1071 }1072 else1073 {1074 value = value.get_value<T>();1075 }1076}10771078int CommandLineRPC(int argc, char *argv[])1079{1080 try1081 {1082 // Skip switches1083 while (argc > 1 && IsSwitchChar(argv[1][0]))1084 {1085 argc--;1086 argv++;1087 }10881089 // Method1090 if (argc < 2)1091 throw runtime_error("too few parameters");1092 string strMethod = argv[1];10931094 // Parameters default to strings1095 Array params;1096 for (int i = 2; i < argc; i++)1097 params.push_back(argv[i]);1098 int n = params.size();10991100 //1101 // Special case non-string parameter types1102 //1103 if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]);1104 if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]);1105 if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);1106 if (strMethod == "listtransactions" && n > 0) ConvertTo<boost::int64_t>(params[0]);1107 if (strMethod == "listtransactions" && n > 1) ConvertTo<bool>(params[1]);1108 if (strMethod == "getamountreceived" && n > 1) ConvertTo<boost::int64_t>(params[1]); // deprecated1109 if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]);1110 if (strMethod == "getreceivedbylabel" && n > 1) ConvertTo<boost::int64_t>(params[1]);1111 if (strMethod == "getallreceived" && n > 0) ConvertTo<boost::int64_t>(params[0]); // deprecated1112 if (strMethod == "getallreceived" && n > 1) ConvertTo<bool>(params[1]);1113 if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);1114 if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);1115 if (strMethod == "listreceivedbylabel" && n > 0) ConvertTo<boost::int64_t>(params[0]);1116 if (strMethod == "listreceivedbylabel" && n > 1) ConvertTo<bool>(params[1]);11171118 // Execute1119 Value result = CallRPC(strMethod, params);11201121 // Print result1122 string strResult = (result.type() == str_type ? result.get_str() : write_string(result, true));1123 if (result.type() != null_type)1124 {1125#if defined(__WXMSW__) && defined(GUI)1126 // Windows GUI apps can't print to command line,1127 // so settle for a message box yuck1128 MyMessageBox(strResult.c_str(), "Bitcoin", wxOK);1129#else1130 fprintf(stdout, "%s\n", strResult.c_str());1131#endif1132 }1133 return 0;1134 }1135 catch (std::exception& e) {1136#if defined(__WXMSW__) && defined(GUI)1137 MyMessageBox(strprintf("error: %s\n", e.what()).c_str(), "Bitcoin", wxOK);1138#else1139 fprintf(stderr, "error: %s\n", e.what());1140#endif1141 } catch (...) {1142 PrintException(NULL, "CommandLineRPC()");1143 }1144 return 1;1145}11461147114811491150#ifdef TEST1151int main(int argc, char *argv[])1152{1153#ifdef _MSC_VER1154 // Turn off microsoft heap dump noise1155 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);1156 _CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));1157#endif1158 setbuf(stdin, NULL);1159 setbuf(stdout, NULL);1160 setbuf(stderr, NULL);11611162 try1163 {1164 if (argc >= 2 && string(argv[1]) == "-server")1165 {1166 printf("server ready\n");1167 ThreadRPCServer(NULL);1168 }1169 else1170 {1171 return CommandLineRPC(argc, argv);1172 }1173 }1174 catch (std::exception& e) {1175 PrintException(&e, "main()");1176 } catch (...) {1177 PrintException(NULL, "main()");1178 }1179 return 0;1180}1181#endif
Click a line number to link to it; use #L10-L20 for a range. "=" next to a version means the file is identical there.
