Bitcoin v0.3.0 · 2010-07-06
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;2324252627282930///31/// Note: This interface may still be subject to change.32///33343536Value help(const Array& params, bool fHelp)37{38 if (fHelp || params.size() != 0)39 throw runtime_error(40 "help\n"41 "List commands.");4243 string strRet;44 for (map<string, rpcfn_type>::iterator mi = mapCallTable.begin(); mi != mapCallTable.end(); ++mi)45 {46 try47 {48 Array params;49 (*(*mi).second)(params, true);50 }51 catch (std::exception& e)52 {53 // Help text is returned in an exception54 string strHelp = string(e.what());55 if (strHelp.find('\n') != -1)56 strHelp = strHelp.substr(0, strHelp.find('\n'));57 strRet += strHelp + "\n";58 }59 }60 strRet = strRet.substr(0,strRet.size()-1);61 return strRet;62}636465Value stop(const Array& params, bool fHelp)66{67 if (fHelp || params.size() != 0)68 throw runtime_error(69 "stop\n"70 "Stop bitcoin server.");7172 // Shutdown will take long enough that the response should get back73 CreateThread(Shutdown, NULL);74 return "bitcoin server stopping";75}767778Value getblockcount(const Array& params, bool fHelp)79{80 if (fHelp || params.size() != 0)81 throw runtime_error(82 "getblockcount\n"83 "Returns the number of blocks in the longest block chain.");8485 return nBestHeight + 1;86}878889Value getblocknumber(const Array& params, bool fHelp)90{91 if (fHelp || params.size() != 0)92 throw runtime_error(93 "getblocknumber\n"94 "Returns the block number of the latest block in the longest block chain.");9596 return nBestHeight;97}9899100Value getconnectioncount(const Array& params, bool fHelp)101{102 if (fHelp || params.size() != 0)103 throw runtime_error(104 "getconnectioncount\n"105 "Returns the number of connections to other nodes.");106107 return (int)vNodes.size();108}109110111double GetDifficulty()112{113 // Floating point number that is a multiple of the minimum difficulty,114 // minimum difficulty = 1.0.115 if (pindexBest == NULL)116 return 1.0;117 int nShift = 256 - 32 - 31; // to fit in a uint118 double dMinimum = (CBigNum().SetCompact(bnProofOfWorkLimit.GetCompact()) >> nShift).getuint();119 double dCurrently = (CBigNum().SetCompact(pindexBest->nBits) >> nShift).getuint();120 return dMinimum / dCurrently;121}122123Value getdifficulty(const Array& params, bool fHelp)124{125 if (fHelp || params.size() != 0)126 throw runtime_error(127 "getdifficulty\n"128 "Returns the proof-of-work difficulty as a multiple of the minimum difficulty.");129130 return GetDifficulty();131}132133134Value getbalance(const Array& params, bool fHelp)135{136 if (fHelp || params.size() != 0)137 throw runtime_error(138 "getbalance\n"139 "Returns the server's available balance.");140141 return ((double)GetBalance() / (double)COIN);142}143144145Value getgenerate(const Array& params, bool fHelp)146{147 if (fHelp || params.size() != 0)148 throw runtime_error(149 "getgenerate\n"150 "Returns true or false.");151152 return (bool)fGenerateBitcoins;153}154155156Value setgenerate(const Array& params, bool fHelp)157{158 if (fHelp || params.size() < 1 || params.size() > 2)159 throw runtime_error(160 "setgenerate <generate> [genproclimit]\n"161 "<generate> is true or false to turn generation on or off.\n"162 "Generation is limited to [genproclimit] processors, -1 is unlimited.");163164 bool fGenerate = true;165 if (params.size() > 0)166 fGenerate = params[0].get_bool();167168 if (params.size() > 1)169 {170 int nGenProcLimit = params[1].get_int();171 fLimitProcessors = (nGenProcLimit != -1);172 CWalletDB().WriteSetting("fLimitProcessors", fLimitProcessors);173 if (nGenProcLimit != -1)174 CWalletDB().WriteSetting("nLimitProcessors", nLimitProcessors = nGenProcLimit);175 }176177 GenerateBitcoins(fGenerate);178 return Value::null;179}180181182Value getinfo(const Array& params, bool fHelp)183{184 if (fHelp || params.size() != 0)185 throw runtime_error(186 "getinfo");187188 Object obj;189 obj.push_back(Pair("balance", (double)GetBalance() / (double)COIN));190 obj.push_back(Pair("blocks", (int)nBestHeight + 1));191 obj.push_back(Pair("connections", (int)vNodes.size()));192 obj.push_back(Pair("proxy", (fUseProxy ? addrProxy.ToStringIPPort() : string())));193 obj.push_back(Pair("generate", (bool)fGenerateBitcoins));194 obj.push_back(Pair("genproclimit", (int)(fLimitProcessors ? nLimitProcessors : -1)));195 obj.push_back(Pair("difficulty", (double)GetDifficulty()));196 return obj;197}198199200Value getnewaddress(const Array& params, bool fHelp)201{202 if (fHelp || params.size() > 1)203 throw runtime_error(204 "getnewaddress [label]\n"205 "Returns a new bitcoin address for receiving payments. "206 "If [label] is specified (recommended), it is added to the address book "207 "so payments received with the address will be labeled.");208209 // Parse the label first so we don't generate a key if there's an error210 string strLabel;211 if (params.size() > 0)212 strLabel = params[0].get_str();213214 // Generate a new key that is added to wallet215 string strAddress = PubKeyToAddress(GenerateNewKey());216217 SetAddressBookName(strAddress, strLabel);218 return strAddress;219}220221222Value setlabel(const Array& params, bool fHelp)223{224 if (fHelp || params.size() < 1 || params.size() > 2)225 throw runtime_error(226 "setlabel <bitcoinaddress> <label>\n"227 "Sets the label associated with the given address.");228229 string strAddress = params[0].get_str();230 string strLabel;231 if (params.size() > 1)232 strLabel = params[1].get_str();233234 SetAddressBookName(strAddress, strLabel);235 return Value::null;236}237238239Value getlabel(const Array& params, bool fHelp)240{241 if (fHelp || params.size() != 1)242 throw runtime_error(243 "getlabel <bitcoinaddress>\n"244 "Returns the label associated with the given address.");245246 string strAddress = params[0].get_str();247248 string strLabel;249 CRITICAL_BLOCK(cs_mapAddressBook)250 {251 map<string, string>::iterator mi = mapAddressBook.find(strAddress);252 if (mi != mapAddressBook.end() && !(*mi).second.empty())253 strLabel = (*mi).second;254 }255 return strLabel;256}257258259Value getaddressesbylabel(const Array& params, bool fHelp)260{261 if (fHelp || params.size() != 1)262 throw runtime_error(263 "getaddressesbylabel <label>\n"264 "Returns the list of addresses with the given label.");265266 string strLabel = params[0].get_str();267268 // Find all addresses that have the given label269 Array ret;270 CRITICAL_BLOCK(cs_mapAddressBook)271 {272 foreach(const PAIRTYPE(string, string)& item, mapAddressBook)273 {274 const string& strAddress = item.first;275 const string& strName = item.second;276 if (strName == strLabel)277 {278 // We're only adding valid bitcoin addresses and not ip addresses279 CScript scriptPubKey;280 if (scriptPubKey.SetBitcoinAddress(strAddress))281 ret.push_back(strAddress);282 }283 }284 }285 return ret;286}287288289Value sendtoaddress(const Array& params, bool fHelp)290{291 if (fHelp || params.size() < 2 || params.size() > 4)292 throw runtime_error(293 "sendtoaddress <bitcoinaddress> <amount> [comment] [comment-to]\n"294 "<amount> is a real and is rounded to the nearest 0.01");295296 string strAddress = params[0].get_str();297298 // Amount299 if (params[1].get_real() <= 0.0 || params[1].get_real() > 21000000.0)300 throw runtime_error("Invalid amount");301 int64 nAmount = roundint64(params[1].get_real() * 100.00) * CENT;302303 // Wallet comments304 CWalletTx wtx;305 if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty())306 wtx.mapValue["message"] = params[2].get_str();307 if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())308 wtx.mapValue["to"] = params[3].get_str();309310 string strError = SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);311 if (strError != "")312 throw runtime_error(strError);313 return "sent";314}315316317Value listtransactions(const Array& params, bool fHelp)318{319 if (fHelp || params.size() > 2)320 throw runtime_error(321 "listtransactions [count=10] [includegenerated=false]\n"322 "Returns up to [count] most recent transactions.");323324 int64 nCount = 10;325 if (params.size() > 0)326 nCount = params[0].get_int64();327 bool fGenerated = false;328 if (params.size() > 1)329 fGenerated = params[1].get_bool();330331 Array ret;332 //// not finished333 ret.push_back("not implemented yet");334 return ret;335}336337338Value getreceivedbyaddress(const Array& params, bool fHelp)339{340 if (fHelp || params.size() < 1 || params.size() > 2)341 throw runtime_error(342 "getreceivedbyaddress <bitcoinaddress> [minconf=1]\n"343 "Returns the total amount received by <bitcoinaddress> in transactions with at least [minconf] confirmations.");344345 // Bitcoin address346 string strAddress = params[0].get_str();347 CScript scriptPubKey;348 if (!scriptPubKey.SetBitcoinAddress(strAddress))349 throw runtime_error("Invalid bitcoin address");350 if (!IsMine(scriptPubKey))351 return (double)0.0;352353 // Minimum confirmations354 int nMinDepth = 1;355 if (params.size() > 1)356 nMinDepth = params[1].get_int();357358 // Tally359 int64 nAmount = 0;360 CRITICAL_BLOCK(cs_mapWallet)361 {362 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)363 {364 const CWalletTx& wtx = (*it).second;365 if (wtx.IsCoinBase() || !wtx.IsFinal())366 continue;367368 foreach(const CTxOut& txout, wtx.vout)369 if (txout.scriptPubKey == scriptPubKey)370 if (wtx.GetDepthInMainChain() >= nMinDepth)371 nAmount += txout.nValue;372 }373 }374375 return (double)nAmount / (double)COIN;376}377378379Value getreceivedbylabel(const Array& params, bool fHelp)380{381 if (fHelp || params.size() < 1 || params.size() > 2)382 throw runtime_error(383 "getreceivedbylabel <label> [minconf=1]\n"384 "Returns the total amount received by addresses with <label> in transactions with at least [minconf] confirmations.");385386 // Get the set of pub keys that have the label387 string strLabel = params[0].get_str();388 set<CScript> setPubKey;389 CRITICAL_BLOCK(cs_mapAddressBook)390 {391 foreach(const PAIRTYPE(string, string)& item, mapAddressBook)392 {393 const string& strAddress = item.first;394 const string& strName = item.second;395 if (strName == strLabel)396 {397 // We're only counting our own valid bitcoin addresses and not ip addresses398 CScript scriptPubKey;399 if (scriptPubKey.SetBitcoinAddress(strAddress))400 if (IsMine(scriptPubKey))401 setPubKey.insert(scriptPubKey);402 }403 }404 }405406 // Minimum confirmations407 int nMinDepth = 1;408 if (params.size() > 1)409 nMinDepth = params[1].get_int();410411 // Tally412 int64 nAmount = 0;413 CRITICAL_BLOCK(cs_mapWallet)414 {415 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)416 {417 const CWalletTx& wtx = (*it).second;418 if (wtx.IsCoinBase() || !wtx.IsFinal())419 continue;420421 foreach(const CTxOut& txout, wtx.vout)422 if (setPubKey.count(txout.scriptPubKey))423 if (wtx.GetDepthInMainChain() >= nMinDepth)424 nAmount += txout.nValue;425 }426 }427428 return (double)nAmount / (double)COIN;429}430431432struct tallyitem433{434 int64 nAmount;435 int nConf;436 tallyitem()437 {438 nAmount = 0;439 nConf = INT_MAX;440 }441};442443Value ListReceived(const Array& params, bool fByLabels)444{445 // Minimum confirmations446 int nMinDepth = 1;447 if (params.size() > 0)448 nMinDepth = params[0].get_int();449450 // Whether to include empty accounts451 bool fIncludeEmpty = false;452 if (params.size() > 1)453 fIncludeEmpty = params[1].get_bool();454455 // Tally456 map<uint160, tallyitem> mapTally;457 CRITICAL_BLOCK(cs_mapWallet)458 {459 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)460 {461 const CWalletTx& wtx = (*it).second;462 if (wtx.IsCoinBase() || !wtx.IsFinal())463 continue;464465 int nDepth = wtx.GetDepthInMainChain();466 if (nDepth < nMinDepth)467 continue;468469 foreach(const CTxOut& txout, wtx.vout)470 {471 // Only counting our own bitcoin addresses and not ip addresses472 uint160 hash160 = txout.scriptPubKey.GetBitcoinAddressHash160();473 if (hash160 == 0 || !mapPubKeys.count(hash160)) // IsMine474 continue;475476 tallyitem& item = mapTally[hash160];477 item.nAmount += txout.nValue;478 item.nConf = min(item.nConf, nDepth);479 }480 }481 }482483 // Reply484 Array ret;485 map<string, tallyitem> mapLabelTally;486 CRITICAL_BLOCK(cs_mapAddressBook)487 {488 foreach(const PAIRTYPE(string, string)& item, mapAddressBook)489 {490 const string& strAddress = item.first;491 const string& strLabel = item.second;492 uint160 hash160;493 if (!AddressToHash160(strAddress, hash160))494 continue;495 map<uint160, tallyitem>::iterator it = mapTally.find(hash160);496 if (it == mapTally.end() && !fIncludeEmpty)497 continue;498499 int64 nAmount = 0;500 int nConf = INT_MAX;501 if (it != mapTally.end())502 {503 nAmount = (*it).second.nAmount;504 nConf = (*it).second.nConf;505 }506507 if (fByLabels)508 {509 tallyitem& item = mapLabelTally[strLabel];510 item.nAmount += nAmount;511 item.nConf = min(item.nConf, nConf);512 }513 else514 {515 Object obj;516 obj.push_back(Pair("address", strAddress));517 obj.push_back(Pair("label", strLabel));518 obj.push_back(Pair("amount", (double)nAmount / (double)COIN));519 obj.push_back(Pair("confirmations", (nConf == INT_MAX ? 0 : nConf)));520 ret.push_back(obj);521 }522 }523 }524525 if (fByLabels)526 {527 for (map<string, tallyitem>::iterator it = mapLabelTally.begin(); it != mapLabelTally.end(); ++it)528 {529 int64 nAmount = (*it).second.nAmount;530 int nConf = (*it).second.nConf;531 Object obj;532 obj.push_back(Pair("label", (*it).first));533 obj.push_back(Pair("amount", (double)nAmount / (double)COIN));534 obj.push_back(Pair("confirmations", (nConf == INT_MAX ? 0 : nConf)));535 ret.push_back(obj);536 }537 }538539 return ret;540}541542Value listreceivedbyaddress(const Array& params, bool fHelp)543{544 if (fHelp || params.size() > 2)545 throw runtime_error(546 "listreceivedbyaddress [minconf=1] [includeempty=false]\n"547 "[minconf] is the minimum number of confirmations before payments are included.\n"548 "[includeempty] whether to include addresses that haven't received any payments.\n"549 "Returns an array of objects containing:\n"550 " \"address\" : receiving address\n"551 " \"label\" : the label of the receiving address\n"552 " \"amount\" : total amount received by the address\n"553 " \"confirmations\" : number of confirmations of the most recent transaction included");554555 return ListReceived(params, false);556}557558Value listreceivedbylabel(const Array& params, bool fHelp)559{560 if (fHelp || params.size() > 2)561 throw runtime_error(562 "listreceivedbylabel [minconf=1] [includeempty=false]\n"563 "[minconf] is the minimum number of confirmations before payments are included.\n"564 "[includeempty] whether to include labels that haven't received any payments.\n"565 "Returns an array of objects containing:\n"566 " \"label\" : the label of the receiving addresses\n"567 " \"amount\" : total amount received by addresses with this label\n"568 " \"confirmations\" : number of confirmations of the most recent transaction included");569570 return ListReceived(params, true);571}572573574575576577578579580581582583584585//586// Call Table587//588589pair<string, rpcfn_type> pCallTable[] =590{591 make_pair("help", &help),592 make_pair("stop", &stop),593 make_pair("getblockcount", &getblockcount),594 make_pair("getblocknumber", &getblocknumber),595 make_pair("getconnectioncount", &getconnectioncount),596 make_pair("getdifficulty", &getdifficulty),597 make_pair("getbalance", &getbalance),598 make_pair("getgenerate", &getgenerate),599 make_pair("setgenerate", &setgenerate),600 make_pair("getinfo", &getinfo),601 make_pair("getnewaddress", &getnewaddress),602 make_pair("setlabel", &setlabel),603 make_pair("getlabel", &getlabel),604 make_pair("getaddressesbylabel", &getaddressesbylabel),605 make_pair("sendtoaddress", &sendtoaddress),606 make_pair("listtransactions", &listtransactions),607 make_pair("getamountreceived", &getreceivedbyaddress), // deprecated, renamed to getreceivedbyaddress608 make_pair("getallreceived", &listreceivedbyaddress), // deprecated, renamed to listreceivedbyaddress609 make_pair("getreceivedbyaddress", &getreceivedbyaddress),610 make_pair("getreceivedbylabel", &getreceivedbylabel),611 make_pair("listreceivedbyaddress", &listreceivedbyaddress),612 make_pair("listreceivedbylabel", &listreceivedbylabel),613};614map<string, rpcfn_type> mapCallTable(pCallTable, pCallTable + sizeof(pCallTable)/sizeof(pCallTable[0]));615616617618619//620// HTTP protocol621//622// This ain't Apache. We're just using HTTP header for the length field623// and to be compatible with other JSON-RPC implementations.624//625626string HTTPPost(const string& strMsg)627{628 return strprintf(629 "POST / HTTP/1.1\r\n"630 "User-Agent: json-rpc/1.0\r\n"631 "Host: 127.0.0.1\r\n"632 "Content-Type: application/json\r\n"633 "Content-Length: %d\r\n"634 "Accept: application/json\r\n"635 "\r\n"636 "%s",637 strMsg.size(),638 strMsg.c_str());639}640641string HTTPReply(const string& strMsg, int nStatus=200)642{643 string strStatus;644 if (nStatus == 200) strStatus = "OK";645 if (nStatus == 500) strStatus = "Internal Server Error";646 return strprintf(647 "HTTP/1.1 %d %s\r\n"648 "Connection: close\r\n"649 "Content-Length: %d\r\n"650 "Content-Type: application/json\r\n"651 "Date: Sat, 08 Jul 2006 12:04:08 GMT\r\n"652 "Server: json-rpc/1.0\r\n"653 "\r\n"654 "%s",655 nStatus,656 strStatus.c_str(),657 strMsg.size(),658 strMsg.c_str());659}660661int ReadHTTPHeader(tcp::iostream& stream)662{663 int nLen = 0;664 loop665 {666 string str;667 std::getline(stream, str);668 if (str.empty() || str == "\r")669 break;670 if (str.substr(0,15) == "Content-Length:")671 nLen = atoi(str.substr(15));672 }673 return nLen;674}675676inline string ReadHTTP(tcp::iostream& stream)677{678 // Read header679 int nLen = ReadHTTPHeader(stream);680 if (nLen <= 0)681 return string();682683 // Read message684 vector<char> vch(nLen);685 stream.read(&vch[0], nLen);686 return string(vch.begin(), vch.end());687}688689690691//692// JSON-RPC protocol693//694// http://json-rpc.org/wiki/specification695// http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx696//697698string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)699{700 Object request;701 request.push_back(Pair("method", strMethod));702 request.push_back(Pair("params", params));703 request.push_back(Pair("id", id));704 return write_string(Value(request), false) + "\n";705}706707string JSONRPCReply(const Value& result, const Value& error, const Value& id)708{709 Object reply;710 if (error.type() != null_type)711 reply.push_back(Pair("result", Value::null));712 else713 reply.push_back(Pair("result", result));714 reply.push_back(Pair("error", error));715 reply.push_back(Pair("id", id));716 return write_string(Value(reply), false) + "\n";717}718719720721722void ThreadRPCServer(void* parg)723{724 IMPLEMENT_RANDOMIZE_STACK(ThreadRPCServer(parg));725 try726 {727 vnThreadsRunning[4]++;728 ThreadRPCServer2(parg);729 vnThreadsRunning[4]--;730 }731 catch (std::exception& e) {732 vnThreadsRunning[4]--;733 PrintException(&e, "ThreadRPCServer()");734 } catch (...) {735 vnThreadsRunning[4]--;736 PrintException(NULL, "ThreadRPCServer()");737 }738 printf("ThreadRPCServer exiting\n");739}740741void ThreadRPCServer2(void* parg)742{743 printf("ThreadRPCServer started\n");744745 // Bind to loopback 127.0.0.1 so the socket can only be accessed locally746 boost::asio::io_service io_service;747 tcp::endpoint endpoint(boost::asio::ip::address_v4::loopback(), 8332);748 tcp::acceptor acceptor(io_service, endpoint);749750 loop751 {752 // Accept connection753 tcp::iostream stream;754 tcp::endpoint peer;755 vnThreadsRunning[4]--;756 acceptor.accept(*stream.rdbuf(), peer);757 vnThreadsRunning[4]++;758 if (fShutdown)759 return;760761 // Shouldn't be possible for anyone else to connect, but just in case762 if (peer.address().to_string() != "127.0.0.1")763 continue;764765 // Receive request766 string strRequest = ReadHTTP(stream);767 printf("ThreadRPCServer request=%s", strRequest.c_str());768769 // Handle multiple invocations per request770 string::iterator begin = strRequest.begin();771 while (skipspaces(begin), begin != strRequest.end())772 {773 string::iterator prev = begin;774 Value id;775 try776 {777 // Parse request778 Value valRequest;779 if (!read_range(begin, strRequest.end(), valRequest))780 throw runtime_error("Parse error.");781 const Object& request = valRequest.get_obj();782 if (find_value(request, "method").type() != str_type ||783 find_value(request, "params").type() != array_type)784 throw runtime_error("Invalid request.");785786 string strMethod = find_value(request, "method").get_str();787 const Array& params = find_value(request, "params").get_array();788 id = find_value(request, "id");789790 // Execute791 map<string, rpcfn_type>::iterator mi = mapCallTable.find(strMethod);792 if (mi == mapCallTable.end())793 throw runtime_error("Method not found.");794 Value result = (*(*mi).second)(params, false);795796 // Send reply797 string strReply = JSONRPCReply(result, Value::null, id);798 stream << HTTPReply(strReply, 200) << std::flush;799 }800 catch (std::exception& e)801 {802 // Send error reply803 string strReply = JSONRPCReply(Value::null, e.what(), id);804 stream << HTTPReply(strReply, 500) << std::flush;805 }806 if (begin == prev)807 break;808 }809 }810}811812813814815Value CallRPC(const string& strMethod, const Array& params)816{817 // Connect to localhost818 tcp::iostream stream("127.0.0.1", "8332");819 if (stream.fail())820 throw runtime_error("couldn't connect to server");821822 // Send request823 string strRequest = JSONRPCRequest(strMethod, params, 1);824 stream << HTTPPost(strRequest) << std::flush;825826 // Receive reply827 string strReply = ReadHTTP(stream);828 if (strReply.empty())829 throw runtime_error("no response from server");830831 // Parse reply832 Value valReply;833 if (!read_string(strReply, valReply))834 throw runtime_error("couldn't parse reply from server");835 const Object& reply = valReply.get_obj();836 if (reply.empty())837 throw runtime_error("expected reply to have result, error and id properties");838839 const Value& result = find_value(reply, "result");840 const Value& error = find_value(reply, "error");841 const Value& id = find_value(reply, "id");842843 if (error.type() == str_type)844 throw runtime_error(error.get_str());845 else if (error.type() != null_type)846 throw runtime_error(write_string(error, false));847 return result;848}849850851852853template<typename T>854void ConvertTo(Value& value)855{856 if (value.type() == str_type)857 {858 // reinterpret string as unquoted json value859 Value value2;860 if (!read_string(value.get_str(), value2))861 throw runtime_error("type mismatch");862 value = value2.get_value<T>();863 }864 else865 {866 value = value.get_value<T>();867 }868}869870int CommandLineRPC(int argc, char *argv[])871{872 try873 {874 // Check that method exists875 if (argc < 2)876 throw runtime_error("too few parameters");877 string strMethod = argv[1];878 if (!mapCallTable.count(strMethod))879 throw runtime_error(strprintf("unknown command: %s", strMethod.c_str()));880881 Value result;882 if (argc == 3 && strcmp(argv[2], "-?") == 0)883 {884 // Call help locally, help text is returned in an exception885 try886 {887 map<string, rpcfn_type>::iterator mi = mapCallTable.find(strMethod);888 Array params;889 (*(*mi).second)(params, true);890 }891 catch (std::exception& e)892 {893 result = e.what();894 }895 }896 else897 {898 // Parameters default to strings899 Array params;900 for (int i = 2; i < argc; i++)901 params.push_back(argv[i]);902 int n = params.size();903904 //905 // Special case non-string parameter types906 //907 if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]);908 if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]);909 if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);910 if (strMethod == "listtransactions" && n > 0) ConvertTo<boost::int64_t>(params[0]);911 if (strMethod == "listtransactions" && n > 1) ConvertTo<bool>(params[1]);912 if (strMethod == "getamountreceived" && n > 1) ConvertTo<boost::int64_t>(params[1]); // deprecated913 if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]);914 if (strMethod == "getreceivedbylabel" && n > 1) ConvertTo<boost::int64_t>(params[1]);915 if (strMethod == "getallreceived" && n > 0) ConvertTo<boost::int64_t>(params[0]); // deprecated916 if (strMethod == "getallreceived" && n > 1) ConvertTo<bool>(params[1]);917 if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);918 if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);919 if (strMethod == "listreceivedbylabel" && n > 0) ConvertTo<boost::int64_t>(params[0]);920 if (strMethod == "listreceivedbylabel" && n > 1) ConvertTo<bool>(params[1]);921922 // Execute923 result = CallRPC(strMethod, params);924 }925926 // Print result927 string strResult = (result.type() == str_type ? result.get_str() : write_string(result, true));928 if (result.type() != null_type)929 {930 if (fWindows && fGUI)931 // Windows GUI apps can't print to command line,932 // so settle for a message box yuck933 MyMessageBox(strResult.c_str(), "Bitcoin", wxOK);934 else935 fprintf(stdout, "%s\n", strResult.c_str());936 }937 return 0;938 }939 catch (std::exception& e) {940 if (fWindows && fGUI)941 MyMessageBox(strprintf("error: %s\n", e.what()).c_str(), "Bitcoin", wxOK);942 else943 fprintf(stderr, "error: %s\n", e.what());944 } catch (...) {945 PrintException(NULL, "CommandLineRPC()");946 }947 return 1;948}949950951952953#ifdef TEST954int main(int argc, char *argv[])955{956#ifdef _MSC_VER957 // Turn off microsoft heap dump noise958 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);959 _CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));960#endif961 setbuf(stdin, NULL);962 setbuf(stdout, NULL);963 setbuf(stderr, NULL);964965 try966 {967 if (argc >= 2 && string(argv[1]) == "-server")968 {969 printf("server ready\n");970 ThreadRPCServer(NULL);971 }972 else973 {974 return CommandLineRPC(argc, argv);975 }976 }977 catch (std::exception& e) {978 PrintException(&e, "main()");979 } catch (...) {980 PrintException(NULL, "main()");981 }982 return 0;983}984#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.
