ecoinrpc.cpp 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229
  1. // ECOin - Copyright (c) - 2014/2024 - GPLv3 - epsylon@riseup.net (https://03c8.net)
  2. #include "init.h"
  3. #include "util.h"
  4. #include "sync.h"
  5. #include "ui_interface.h"
  6. #include "base58.h"
  7. #include "ecoinrpc.h"
  8. #include "db.h"
  9. #undef printf
  10. #include <boost/asio.hpp>
  11. #include <boost/asio/ip/v6_only.hpp>
  12. #include <boost/bind/bind.hpp>
  13. using namespace boost::placeholders;
  14. #include <boost/filesystem.hpp>
  15. #include <boost/foreach.hpp>
  16. #include <boost/iostreams/concepts.hpp>
  17. #include <boost/iostreams/stream.hpp>
  18. #include <boost/algorithm/string.hpp>
  19. #include <boost/lexical_cast.hpp>
  20. #include <boost/asio/ssl.hpp>
  21. #include <boost/filesystem/fstream.hpp>
  22. #include <boost/shared_ptr.hpp>
  23. #include <list>
  24. #define printf OutputDebugStringF
  25. using namespace std;
  26. using namespace boost;
  27. using namespace boost::asio;
  28. using namespace json_spirit;
  29. void ThreadRPCServer2(void* parg);
  30. static std::string strRPCUserColonPass;
  31. const Object emptyobj;
  32. void ThreadRPCServer3(void* parg);
  33. static inline unsigned short GetDefaultRPCPort()
  34. {
  35. return GetBoolArg("-testnet", false) ? 17474 : 7474;
  36. }
  37. Object JSONRPCError(int code, const string& message)
  38. {
  39. Object error;
  40. error.push_back(Pair("code", code));
  41. error.push_back(Pair("message", message));
  42. return error;
  43. }
  44. void RPCTypeCheck(const Array& params,
  45. const list<Value_type>& typesExpected,
  46. bool fAllowNull)
  47. {
  48. unsigned int i = 0;
  49. BOOST_FOREACH(Value_type t, typesExpected)
  50. {
  51. if (params.size() <= i)
  52. break;
  53. const Value& v = params[i];
  54. if (!((v.type() == t) || (fAllowNull && (v.type() == null_type))))
  55. {
  56. string err = strprintf("Expected type %s, got %s",
  57. Value_type_name[t], Value_type_name[v.type()]);
  58. throw JSONRPCError(RPC_TYPE_ERROR, err);
  59. }
  60. i++;
  61. }
  62. }
  63. void RPCTypeCheck(const Object& o,
  64. const map<string, Value_type>& typesExpected,
  65. bool fAllowNull)
  66. {
  67. BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected)
  68. {
  69. const Value& v = find_value(o, t.first);
  70. if (!fAllowNull && v.type() == null_type)
  71. throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first.c_str()));
  72. if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type))))
  73. {
  74. string err = strprintf("Expected type %s for %s, got %s",
  75. Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]);
  76. throw JSONRPCError(RPC_TYPE_ERROR, err);
  77. }
  78. }
  79. }
  80. int64 AmountFromValue(const Value& value)
  81. {
  82. double dAmount = value.get_real();
  83. if (dAmount <= 0.0 || dAmount > MAX_MONEY)
  84. throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
  85. int64 nAmount = roundint64(dAmount * COIN);
  86. if (!MoneyRange(nAmount))
  87. throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
  88. return nAmount;
  89. }
  90. Value ValueFromAmount(int64 amount)
  91. {
  92. return (double)amount / (double)COIN;
  93. }
  94. std::string HexBits(unsigned int nBits)
  95. {
  96. union {
  97. int32_t nBits;
  98. char cBits[4];
  99. } uBits;
  100. uBits.nBits = htonl((int32_t)nBits);
  101. return HexStr(BEGIN(uBits.cBits), END(uBits.cBits));
  102. }
  103. uint256 ParseHashV(const Value& v, string strName)
  104. {
  105. string strHex;
  106. if (v.type() == str_type)
  107. strHex = v.get_str();
  108. if (!IsHex(strHex)) // Note: IsHex("") is false
  109. throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
  110. uint256 result;
  111. result.SetHex(strHex);
  112. return result;
  113. }
  114. uint256 ParseHashO(const Object& o, string strKey)
  115. {
  116. return ParseHashV(find_value(o, strKey), strKey);
  117. }
  118. vector<unsigned char> ParseHexV(const Value& v, string strName)
  119. {
  120. string strHex;
  121. if (v.type() == str_type)
  122. strHex = v.get_str();
  123. if (!IsHex(strHex))
  124. throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
  125. return ParseHex(strHex);
  126. }
  127. vector<unsigned char> ParseHexO(const Object& o, string strKey)
  128. {
  129. return ParseHexV(find_value(o, strKey), strKey);
  130. }
  131. string CRPCTable::help(string strCommand) const
  132. {
  133. string strRet;
  134. set<rpcfn_type> setDone;
  135. for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)
  136. {
  137. const CRPCCommand *pcmd = mi->second;
  138. string strMethod = mi->first;
  139. // We already filter duplicates, but these deprecated screw up the sort order
  140. if (strMethod.find("label") != string::npos)
  141. continue;
  142. if (strCommand != "" && strMethod != strCommand)
  143. continue;
  144. try
  145. {
  146. Array params;
  147. rpcfn_type pfn = pcmd->actor;
  148. if (setDone.insert(pfn).second)
  149. (*pfn)(params, true);
  150. }
  151. catch (std::exception& e)
  152. {
  153. // Help text is returned in an exception
  154. string strHelp = string(e.what());
  155. if (strCommand == "")
  156. if (strHelp.find('\n') != string::npos)
  157. strHelp = strHelp.substr(0, strHelp.find('\n'));
  158. strRet += strHelp + "\n";
  159. }
  160. }
  161. if (strRet == "")
  162. strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
  163. strRet = strRet.substr(0,strRet.size()-1);
  164. return strRet;
  165. }
  166. Value help(const Array& params, bool fHelp)
  167. {
  168. if (fHelp || params.size() > 1)
  169. throw runtime_error(
  170. "help [command]\n"
  171. "List commands, or get help for a command.");
  172. string strCommand;
  173. if (params.size() > 0)
  174. strCommand = params[0].get_str();
  175. return tableRPC.help(strCommand);
  176. }
  177. Value stop(const Array& params, bool fHelp)
  178. {
  179. if (fHelp || params.size() > 1)
  180. throw runtime_error(
  181. "stop <detach>\n"
  182. "<detach> is true or false to detach the database or not for this stop only\n"
  183. "Stop Ecoin server (and possibly override the detachdb config value).");
  184. // Shutdown will take long enough that the response should get back
  185. if (params.size() > 0)
  186. bitdb.SetDetach(params[0].get_bool());
  187. StartShutdown();
  188. return "Ecoin server stopping";
  189. }
  190. static const CRPCCommand vRPCCommands[] =
  191. { // name function safemd unlocked
  192. // ------------------------ ----------------------- ------ --------
  193. { "help", &help, true, true },
  194. { "stop", &stop, true, true },
  195. { "getblockhash", &getblockhash, true, false },
  196. { "getblockcount", &getblockcount, true, false },
  197. { "getconnectioncount", &getconnectioncount, true, false },
  198. { "getpeerinfo", &getpeerinfo, true, false },
  199. { "getdifficulty", &getdifficulty, true, false },
  200. { "getinfo", &getinfo, true, false },
  201. { "getmininginfo", &getmininginfo, true, false },
  202. { "getnewaddress", &getnewaddress, true, false },
  203. { "getnewpubkey", &getnewpubkey, true, false },
  204. { "getaccountaddress", &getaccountaddress, true, false },
  205. { "setaccount", &setaccount, true, false },
  206. { "getaccount", &getaccount, false, false },
  207. { "getaddressesbyaccount", &getaddressesbyaccount, true, false },
  208. { "sendtoaddress", &sendtoaddress, false, false },
  209. { "getreceivedbyaddress", &getreceivedbyaddress, false, false },
  210. { "getreceivedbyaccount", &getreceivedbyaccount, false, false },
  211. { "listreceivedbyaddress", &listreceivedbyaddress, false, false },
  212. { "listreceivedbyaccount", &listreceivedbyaccount, false, false },
  213. { "backupwallet", &backupwallet, true, false },
  214. { "keypoolrefill", &keypoolrefill, true, false },
  215. { "walletpassphrase", &walletpassphrase, true, false },
  216. { "walletpassphrasechange", &walletpassphrasechange, false, false },
  217. { "walletlock", &walletlock, true, false },
  218. { "encryptwallet", &encryptwallet, false, false },
  219. { "validateaddress", &validateaddress, true, false },
  220. { "validatepubkey", &validatepubkey, true, false },
  221. { "getbalance", &getbalance, false, false },
  222. { "move", &movecmd, false, false },
  223. { "sendfrom", &sendfrom, false, false },
  224. { "sendmany", &sendmany, false, false },
  225. { "addmultisigaddress", &addmultisigaddress, false, false },
  226. { "getrawmempool", &getrawmempool, true, false },
  227. { "getblock", &getblock, false, false },
  228. { "getblockbynumber", &getblockbynumber, false, false },
  229. { "getblockhash", &getblockhash, false, false },
  230. { "gettransaction", &gettransaction, false, false },
  231. { "listtransactions", &listtransactions, false, false },
  232. { "listaddressgroupings", &listaddressgroupings, false, false },
  233. { "signmessage", &signmessage, false, false },
  234. { "verifymessage", &verifymessage, false, false },
  235. { "getwork", &getwork, true, false },
  236. { "getworkex", &getworkex, true, false },
  237. { "listaccounts", &listaccounts, false, false },
  238. { "settxfee", &settxfee, false, false },
  239. { "getblocktemplate", &getblocktemplate, true, false },
  240. { "submitblock", &submitblock, false, false },
  241. { "listsinceblock", &listsinceblock, false, false },
  242. { "dumpprivkey", &dumpprivkey, false, false },
  243. { "checkwallet", &checkwallet, true, false },
  244. { "repairwallet", &repairwallet, false, false },
  245. { "importprivkey", &importprivkey, false, false },
  246. { "listunspent", &listunspent, false, false },
  247. { "getrawtransaction", &getrawtransaction, false, false },
  248. { "createrawtransaction", &createrawtransaction, false, false },
  249. { "decoderawtransaction", &decoderawtransaction, false, false },
  250. { "signrawtransaction", &signrawtransaction, false, false },
  251. { "sendrawtransaction", &sendrawtransaction, false, false },
  252. { "getcheckpoint", &getcheckpoint, true, false },
  253. { "reservebalance", &reservebalance, false, true},
  254. { "checkwallet", &checkwallet, false, true},
  255. { "resendtx", &resendtx, false, true},
  256. { "makekeypair", &makekeypair, false, true},
  257. { "sendalert", &sendalert, false, false},
  258. };
  259. CRPCTable::CRPCTable()
  260. {
  261. unsigned int vcidx;
  262. for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++)
  263. {
  264. const CRPCCommand *pcmd;
  265. pcmd = &vRPCCommands[vcidx];
  266. mapCommands[pcmd->name] = pcmd;
  267. }
  268. }
  269. const CRPCCommand *CRPCTable::operator[](string name) const
  270. {
  271. map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
  272. if (it == mapCommands.end())
  273. return NULL;
  274. return (*it).second;
  275. }
  276. string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
  277. {
  278. ostringstream s;
  279. s << "POST / HTTP/1.1\r\n"
  280. << "User-Agent: ecoin-json-rpc/" << FormatFullVersion() << "\r\n"
  281. << "Host: 127.0.0.1\r\n"
  282. << "Content-Type: application/json\r\n"
  283. << "Content-Length: " << strMsg.size() << "\r\n"
  284. << "Connection: close\r\n"
  285. << "Accept: application/json\r\n";
  286. BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders)
  287. s << item.first << ": " << item.second << "\r\n";
  288. s << "\r\n" << strMsg;
  289. return s.str();
  290. }
  291. string rfc1123Time()
  292. {
  293. char buffer[64];
  294. time_t now;
  295. time(&now);
  296. struct tm* now_gmt = gmtime(&now);
  297. string locale(setlocale(LC_TIME, NULL));
  298. setlocale(LC_TIME, "C"); // we want POSIX (aka "C") weekday/month strings
  299. strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt);
  300. setlocale(LC_TIME, locale.c_str());
  301. return string(buffer);
  302. }
  303. static string HTTPReply(int nStatus, const string& strMsg, bool keepalive)
  304. {
  305. if (nStatus == HTTP_UNAUTHORIZED)
  306. return strprintf("HTTP/1.0 401 Authorization Required\r\n"
  307. "Date: %s\r\n"
  308. "Server: ecoin-json-rpc/%s\r\n"
  309. "WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
  310. "Content-Type: text/html\r\n"
  311. "Content-Length: 296\r\n"
  312. "\r\n"
  313. "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
  314. "\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
  315. "<HTML>\r\n"
  316. "<HEAD>\r\n"
  317. "<TITLE>Error</TITLE>\r\n"
  318. "<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
  319. "</HEAD>\r\n"
  320. "<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
  321. "</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str());
  322. const char *cStatus;
  323. if (nStatus == HTTP_OK) cStatus = "OK";
  324. else if (nStatus == HTTP_BAD_REQUEST) cStatus = "Bad Request";
  325. else if (nStatus == HTTP_FORBIDDEN) cStatus = "Forbidden";
  326. else if (nStatus == HTTP_NOT_FOUND) cStatus = "Not Found";
  327. else if (nStatus == HTTP_INTERNAL_SERVER_ERROR) cStatus = "Internal Server Error";
  328. else cStatus = "";
  329. return strprintf(
  330. "HTTP/1.1 %d %s\r\n"
  331. "Date: %s\r\n"
  332. "Connection: %s\r\n"
  333. "Content-Length: %" PRIszu"\r\n"
  334. "Content-Type: application/json\r\n"
  335. "Server: ecoin-json-rpc/%s\r\n"
  336. "\r\n"
  337. "%s",
  338. nStatus,
  339. cStatus,
  340. rfc1123Time().c_str(),
  341. keepalive ? "keep-alive" : "close",
  342. strMsg.size(),
  343. FormatFullVersion().c_str(),
  344. strMsg.c_str());
  345. }
  346. int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto)
  347. {
  348. string str;
  349. getline(stream, str);
  350. vector<string> vWords;
  351. boost::split(vWords, str, boost::is_any_of(" "));
  352. if (vWords.size() < 2)
  353. return HTTP_INTERNAL_SERVER_ERROR;
  354. proto = 0;
  355. const char *ver = strstr(str.c_str(), "HTTP/1.");
  356. if (ver != NULL)
  357. proto = atoi(ver+7);
  358. return atoi(vWords[1].c_str());
  359. }
  360. int ReadHTTPHeader(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
  361. {
  362. int nLen = 0;
  363. while (true)
  364. {
  365. string str;
  366. std::getline(stream, str);
  367. if (str.empty() || str == "\r")
  368. break;
  369. string::size_type nColon = str.find(":");
  370. if (nColon != string::npos)
  371. {
  372. string strHeader = str.substr(0, nColon);
  373. boost::trim(strHeader);
  374. boost::to_lower(strHeader);
  375. string strValue = str.substr(nColon+1);
  376. boost::trim(strValue);
  377. mapHeadersRet[strHeader] = strValue;
  378. if (strHeader == "content-length")
  379. nLen = atoi(strValue.c_str());
  380. }
  381. }
  382. return nLen;
  383. }
  384. int ReadHTTP(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet)
  385. {
  386. mapHeadersRet.clear();
  387. strMessageRet = "";
  388. int nProto = 0;
  389. int nStatus = ReadHTTPStatus(stream, nProto);
  390. int nLen = ReadHTTPHeader(stream, mapHeadersRet);
  391. if (nLen < 0 || nLen > (int)MAX_SIZE)
  392. return HTTP_INTERNAL_SERVER_ERROR;
  393. if (nLen > 0)
  394. {
  395. vector<char> vch(nLen);
  396. stream.read(&vch[0], nLen);
  397. strMessageRet = string(vch.begin(), vch.end());
  398. }
  399. string sConHdr = mapHeadersRet["connection"];
  400. if ((sConHdr != "close") && (sConHdr != "keep-alive"))
  401. {
  402. if (nProto >= 1)
  403. mapHeadersRet["connection"] = "keep-alive";
  404. else
  405. mapHeadersRet["connection"] = "close";
  406. }
  407. return nStatus;
  408. }
  409. bool HTTPAuthorized(map<string, string>& mapHeaders)
  410. {
  411. string strAuth = mapHeaders["authorization"];
  412. if (strAuth.substr(0,6) != "Basic ")
  413. return false;
  414. string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
  415. string strUserPass = DecodeBase64(strUserPass64);
  416. return TimingResistantEqual(strUserPass, strRPCUserColonPass);
  417. }
  418. string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
  419. {
  420. Object request;
  421. request.push_back(Pair("method", strMethod));
  422. request.push_back(Pair("params", params));
  423. request.push_back(Pair("id", id));
  424. return write_string(Value(request), false) + "\n";
  425. }
  426. Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id)
  427. {
  428. Object reply;
  429. if (error.type() != null_type)
  430. reply.push_back(Pair("result", Value::null));
  431. else
  432. reply.push_back(Pair("result", result));
  433. reply.push_back(Pair("error", error));
  434. reply.push_back(Pair("id", id));
  435. return reply;
  436. }
  437. string JSONRPCReply(const Value& result, const Value& error, const Value& id)
  438. {
  439. Object reply = JSONRPCReplyObj(result, error, id);
  440. return write_string(Value(reply), false) + "\n";
  441. }
  442. void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
  443. {
  444. int nStatus = HTTP_INTERNAL_SERVER_ERROR;
  445. int code = find_value(objError, "code").get_int();
  446. if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST;
  447. else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND;
  448. string strReply = JSONRPCReply(Value::null, objError, id);
  449. stream << HTTPReply(nStatus, strReply, false) << std::flush;
  450. }
  451. bool ClientAllowed(const boost::asio::ip::address& address)
  452. {
  453. if (address.is_v6()
  454. && (address.to_v6().is_v4_compatible()
  455. || address.to_v6().is_v4_mapped()))
  456. return ClientAllowed(address.to_v6().to_v4());
  457. if (address == asio::ip::address_v4::loopback()
  458. || address == asio::ip::address_v6::loopback()
  459. || (address.is_v4()
  460. && (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000))
  461. return true;
  462. const string strAddress = address.to_string();
  463. const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
  464. BOOST_FOREACH(string strAllow, vAllow)
  465. if (WildcardMatch(strAddress, strAllow))
  466. return true;
  467. return false;
  468. }
  469. template <typename Protocol>
  470. class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {
  471. public:
  472. SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn)
  473. {
  474. fUseSSL = fUseSSLIn;
  475. fNeedHandshake = fUseSSLIn;
  476. }
  477. void handshake(ssl::stream_base::handshake_type role)
  478. {
  479. if (!fNeedHandshake) return;
  480. fNeedHandshake = false;
  481. stream.handshake(role);
  482. }
  483. std::streamsize read(char* s, std::streamsize n)
  484. {
  485. handshake(ssl::stream_base::server); // HTTPS servers read first
  486. if (fUseSSL) return stream.read_some(asio::buffer(s, n));
  487. return stream.next_layer().read_some(asio::buffer(s, n));
  488. }
  489. std::streamsize write(const char* s, std::streamsize n)
  490. {
  491. handshake(ssl::stream_base::client); // HTTPS clients write first
  492. if (fUseSSL) return asio::write(stream, asio::buffer(s, n));
  493. return asio::write(stream.next_layer(), asio::buffer(s, n));
  494. }
  495. bool connect(const std::string& server, const std::string& port)
  496. {
  497. ip::tcp::resolver resolver(GetIOService(stream));
  498. ip::tcp::resolver::query query(server.c_str(), port.c_str());
  499. ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
  500. ip::tcp::resolver::iterator end;
  501. boost::system::error_code error = asio::error::host_not_found;
  502. while (error && endpoint_iterator != end)
  503. {
  504. stream.lowest_layer().close();
  505. stream.lowest_layer().connect(*endpoint_iterator++, error);
  506. }
  507. if (error)
  508. return false;
  509. return true;
  510. }
  511. private:
  512. bool fNeedHandshake;
  513. bool fUseSSL;
  514. asio::ssl::stream<typename Protocol::socket>& stream;
  515. };
  516. class AcceptedConnection
  517. {
  518. public:
  519. virtual ~AcceptedConnection() {}
  520. virtual std::iostream& stream() = 0;
  521. virtual std::string peer_address_to_string() const = 0;
  522. virtual void close() = 0;
  523. };
  524. template <typename Protocol>
  525. class AcceptedConnectionImpl : public AcceptedConnection
  526. {
  527. public:
  528. AcceptedConnectionImpl(
  529. asio::io_service& io_service,
  530. ssl::context &context,
  531. bool fUseSSL) :
  532. sslStream(io_service, context),
  533. _d(sslStream, fUseSSL),
  534. _stream(_d)
  535. {
  536. }
  537. virtual std::iostream& stream()
  538. {
  539. return _stream;
  540. }
  541. virtual std::string peer_address_to_string() const
  542. {
  543. return peer.address().to_string();
  544. }
  545. virtual void close()
  546. {
  547. _stream.close();
  548. }
  549. typename Protocol::endpoint peer;
  550. asio::ssl::stream<typename Protocol::socket> sslStream;
  551. private:
  552. SSLIOStreamDevice<Protocol> _d;
  553. iostreams::stream< SSLIOStreamDevice<Protocol> > _stream;
  554. };
  555. void ThreadRPCServer(void* parg)
  556. {
  557. RenameThread("ecoin-rpclist");
  558. try
  559. {
  560. vnThreadsRunning[THREAD_RPCLISTENER]++;
  561. ThreadRPCServer2(parg);
  562. vnThreadsRunning[THREAD_RPCLISTENER]--;
  563. }
  564. catch (std::exception& e) {
  565. vnThreadsRunning[THREAD_RPCLISTENER]--;
  566. PrintException(&e, "ThreadRPCServer()");
  567. } catch (...) {
  568. vnThreadsRunning[THREAD_RPCLISTENER]--;
  569. PrintException(NULL, "ThreadRPCServer()");
  570. }
  571. printf("ThreadRPCServer exited\n");
  572. }
  573. template <typename Protocol, typename SocketAcceptorService>
  574. static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
  575. ssl::context& context,
  576. bool fUseSSL,
  577. AcceptedConnection* conn,
  578. const boost::system::error_code& error);
  579. template <typename Protocol, typename SocketAcceptorService>
  580. static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
  581. ssl::context& context,
  582. const bool fUseSSL)
  583. {
  584. AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(GetIOService(*acceptor), context, fUseSSL);
  585. acceptor->async_accept(
  586. conn->sslStream.lowest_layer(),
  587. conn->peer,
  588. boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>,
  589. acceptor,
  590. boost::ref(context),
  591. fUseSSL,
  592. conn,
  593. boost::asio::placeholders::error));
  594. }
  595. template <typename Protocol, typename SocketAcceptorService>
  596. static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
  597. ssl::context& context,
  598. const bool fUseSSL,
  599. AcceptedConnection* conn,
  600. const boost::system::error_code& error)
  601. {
  602. vnThreadsRunning[THREAD_RPCLISTENER]++;
  603. if (error != asio::error::operation_aborted
  604. && acceptor->is_open())
  605. RPCListen(acceptor, context, fUseSSL);
  606. AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn);
  607. if (error)
  608. {
  609. delete conn;
  610. }
  611. else if (tcp_conn
  612. && !ClientAllowed(tcp_conn->peer.address()))
  613. {
  614. if (!fUseSSL)
  615. conn->stream() << HTTPReply(HTTP_FORBIDDEN, "", false) << std::flush;
  616. delete conn;
  617. }
  618. else if (!NewThread(ThreadRPCServer3, conn)) {
  619. printf("Failed to create RPC server client thread\n");
  620. delete conn;
  621. }
  622. vnThreadsRunning[THREAD_RPCLISTENER]--;
  623. }
  624. void ThreadRPCServer2(void* parg)
  625. {
  626. printf("ThreadRPCServer started\n");
  627. strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
  628. if (mapArgs["-rpcpassword"] == "")
  629. {
  630. unsigned char rand_pwd[32];
  631. RAND_bytes(rand_pwd, 32);
  632. string strWhatAmI = "To use ecoind";
  633. if (mapArgs.count("-server"))
  634. strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
  635. else if (mapArgs.count("-daemon"))
  636. strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
  637. uiInterface.ThreadSafeMessageBox(strprintf(
  638. _("%s, you must set a rpcpassword in the configuration file:\n %s\n"
  639. "It is recommended you use the following random password:\n"
  640. "rpcuser=ecoinrpc\n"
  641. "rpcpassword=%s\n"
  642. "(you do not need to remember this password)\n"
  643. "If the file does not exist, create it with owner-readable-only file permissions.\n"),
  644. strWhatAmI.c_str(),
  645. GetConfigFile().string().c_str(),
  646. EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()),
  647. _("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL);
  648. StartShutdown();
  649. return;
  650. }
  651. const bool fUseSSL = GetBoolArg("-rpcssl");
  652. asio::io_service io_service;
  653. //ssl::context context(io_service, ssl::context::no_sslv2);
  654. ssl::context context(ssl::context::sslv23);
  655. if (fUseSSL)
  656. {
  657. context.set_options(ssl::context::no_sslv2);
  658. boost::filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert"));
  659. if (!pathCertFile.is_complete()) pathCertFile = boost::filesystem::path(GetDataDir()) / pathCertFile;
  660. if (boost::filesystem::exists(pathCertFile)) context.use_certificate_chain_file(pathCertFile.string());
  661. else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string().c_str());
  662. boost::filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem"));
  663. if (!pathPKFile.is_complete()) pathPKFile = boost::filesystem::path(GetDataDir()) / pathPKFile;
  664. if (boost::filesystem::exists(pathPKFile)) context.use_private_key_file(pathPKFile.string(), ssl::context::pem);
  665. else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str());
  666. string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
  667. //SSL_CTX_set_cipher_list(context.impl(), strCiphers.c_str());
  668. SSL_CTX_set_cipher_list(context.native_handle(), strCiphers.c_str());
  669. }
  670. const bool loopback = !mapArgs.count("-rpcallowip");
  671. asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any();
  672. ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", GetDefaultRPCPort()));
  673. boost::system::error_code v6_only_error;
  674. boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(io_service));
  675. boost::signals2::signal<void ()> StopRequests;
  676. bool fListening = false;
  677. std::string strerr;
  678. try
  679. {
  680. acceptor->open(endpoint.protocol());
  681. acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
  682. acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error);
  683. acceptor->bind(endpoint);
  684. acceptor->listen(socket_base::max_connections);
  685. RPCListen(acceptor, context, fUseSSL);
  686. StopRequests.connect(signals2::slot<void ()>(
  687. static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get())
  688. .track(acceptor));
  689. fListening = true;
  690. }
  691. catch(boost::system::system_error &e)
  692. {
  693. strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s"), endpoint.port(), e.what());
  694. }
  695. try {
  696. if (!fListening || loopback || v6_only_error)
  697. {
  698. bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any();
  699. endpoint.address(bindAddress);
  700. acceptor.reset(new ip::tcp::acceptor(io_service));
  701. acceptor->open(endpoint.protocol());
  702. acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
  703. acceptor->bind(endpoint);
  704. acceptor->listen(socket_base::max_connections);
  705. RPCListen(acceptor, context, fUseSSL);
  706. StopRequests.connect(signals2::slot<void ()>(
  707. static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get())
  708. .track(acceptor));
  709. fListening = true;
  710. }
  711. }
  712. catch(boost::system::system_error &e)
  713. {
  714. strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv4: %s"), endpoint.port(), e.what());
  715. }
  716. if (!fListening) {
  717. uiInterface.ThreadSafeMessageBox(strerr, _("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL);
  718. StartShutdown();
  719. return;
  720. }
  721. vnThreadsRunning[THREAD_RPCLISTENER]--;
  722. while (!fShutdown)
  723. io_service.run_one();
  724. vnThreadsRunning[THREAD_RPCLISTENER]++;
  725. StopRequests();
  726. }
  727. class JSONRequest
  728. {
  729. public:
  730. Value id;
  731. string strMethod;
  732. Array params;
  733. JSONRequest() { id = Value::null; }
  734. void parse(const Value& valRequest);
  735. };
  736. void JSONRequest::parse(const Value& valRequest)
  737. {
  738. if (valRequest.type() != obj_type)
  739. throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
  740. const Object& request = valRequest.get_obj();
  741. id = find_value(request, "id");
  742. Value valMethod = find_value(request, "method");
  743. if (valMethod.type() == null_type)
  744. throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
  745. if (valMethod.type() != str_type)
  746. throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
  747. strMethod = valMethod.get_str();
  748. if (strMethod != "getwork" && strMethod != "getblocktemplate")
  749. printf("ThreadRPCServer method=%s\n", strMethod.c_str());
  750. Value valParams = find_value(request, "params");
  751. if (valParams.type() == array_type)
  752. params = valParams.get_array();
  753. else if (valParams.type() == null_type)
  754. params = Array();
  755. else
  756. throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array");
  757. }
  758. static Object JSONRPCExecOne(const Value& req)
  759. {
  760. Object rpc_result;
  761. JSONRequest jreq;
  762. try {
  763. jreq.parse(req);
  764. Value result = tableRPC.execute(jreq.strMethod, jreq.params);
  765. rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id);
  766. }
  767. catch (Object& objError)
  768. {
  769. rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id);
  770. }
  771. catch (std::exception& e)
  772. {
  773. rpc_result = JSONRPCReplyObj(Value::null,
  774. JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
  775. }
  776. return rpc_result;
  777. }
  778. static string JSONRPCExecBatch(const Array& vReq)
  779. {
  780. Array ret;
  781. for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
  782. ret.push_back(JSONRPCExecOne(vReq[reqIdx]));
  783. return write_string(Value(ret), false) + "\n";
  784. }
  785. static CCriticalSection cs_THREAD_RPCHANDLER;
  786. void ThreadRPCServer3(void* parg)
  787. {
  788. RenameThread("ecoin-rpchand");
  789. {
  790. LOCK(cs_THREAD_RPCHANDLER);
  791. vnThreadsRunning[THREAD_RPCHANDLER]++;
  792. }
  793. AcceptedConnection *conn = (AcceptedConnection *) parg;
  794. bool fRun = true;
  795. while (true)
  796. {
  797. if (fShutdown || !fRun)
  798. {
  799. conn->close();
  800. delete conn;
  801. {
  802. LOCK(cs_THREAD_RPCHANDLER);
  803. --vnThreadsRunning[THREAD_RPCHANDLER];
  804. }
  805. return;
  806. }
  807. map<string, string> mapHeaders;
  808. string strRequest;
  809. ReadHTTP(conn->stream(), mapHeaders, strRequest);
  810. if (mapHeaders.count("authorization") == 0)
  811. {
  812. conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
  813. break;
  814. }
  815. if (!HTTPAuthorized(mapHeaders))
  816. {
  817. printf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string().c_str());
  818. if (mapArgs["-rpcpassword"].size() < 20)
  819. Sleep(250);
  820. conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
  821. break;
  822. }
  823. if (mapHeaders["connection"] == "close")
  824. fRun = false;
  825. JSONRequest jreq;
  826. try
  827. {
  828. Value valRequest;
  829. if (!read_string(strRequest, valRequest))
  830. throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
  831. string strReply;
  832. if (valRequest.type() == obj_type) {
  833. jreq.parse(valRequest);
  834. Value result = tableRPC.execute(jreq.strMethod, jreq.params);
  835. strReply = JSONRPCReply(result, Value::null, jreq.id);
  836. } else if (valRequest.type() == array_type)
  837. strReply = JSONRPCExecBatch(valRequest.get_array());
  838. else
  839. throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
  840. conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush;
  841. }
  842. catch (Object& objError)
  843. {
  844. ErrorReply(conn->stream(), objError, jreq.id);
  845. break;
  846. }
  847. catch (std::exception& e)
  848. {
  849. ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
  850. break;
  851. }
  852. }
  853. delete conn;
  854. {
  855. LOCK(cs_THREAD_RPCHANDLER);
  856. vnThreadsRunning[THREAD_RPCHANDLER]--;
  857. }
  858. }
  859. json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array &params) const
  860. {
  861. const CRPCCommand *pcmd = tableRPC[strMethod];
  862. if (!pcmd)
  863. throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
  864. string strWarning = GetWarnings("rpc");
  865. if (strWarning != "" && !GetBoolArg("-disablesafemode") &&
  866. !pcmd->okSafeMode)
  867. throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
  868. try
  869. {
  870. Value result;
  871. {
  872. if (pcmd->unlocked)
  873. result = pcmd->actor(params, false);
  874. else {
  875. LOCK2(cs_main, pwalletMain->cs_wallet);
  876. result = pcmd->actor(params, false);
  877. }
  878. }
  879. return result;
  880. }
  881. catch (std::exception& e)
  882. {
  883. throw JSONRPCError(RPC_MISC_ERROR, e.what());
  884. }
  885. }
  886. Object CallRPC(const string& strMethod, const Array& params)
  887. {
  888. if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
  889. throw runtime_error(strprintf(
  890. _("You must set rpcpassword=<password> in the configuration file:\n%s\n"
  891. "If the file does not exist, create it with owner-readable-only file permissions."),
  892. GetConfigFile().string().c_str()));
  893. bool fUseSSL = GetBoolArg("-rpcssl");
  894. asio::io_service io_service;
  895. //ssl::context context(io_service, ssl::context::sslv23);
  896. ssl::context context(ssl::context::sslv23);
  897. context.set_options(ssl::context::no_sslv2);
  898. asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context);
  899. SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL);
  900. iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d);
  901. if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(GetDefaultRPCPort()))))
  902. throw runtime_error("couldn't connect to server");
  903. string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
  904. map<string, string> mapRequestHeaders;
  905. mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
  906. string strRequest = JSONRPCRequest(strMethod, params, 1);
  907. string strPost = HTTPPost(strRequest, mapRequestHeaders);
  908. stream << strPost << std::flush;
  909. map<string, string> mapHeaders;
  910. string strReply;
  911. int nStatus = ReadHTTP(stream, mapHeaders, strReply);
  912. if (nStatus == HTTP_UNAUTHORIZED)
  913. throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
  914. else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR)
  915. throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
  916. else if (strReply.empty())
  917. throw runtime_error("no response from server");
  918. Value valReply;
  919. if (!read_string(strReply, valReply))
  920. throw runtime_error("couldn't parse reply from server");
  921. const Object& reply = valReply.get_obj();
  922. if (reply.empty())
  923. throw runtime_error("expected reply to have result, error and id properties");
  924. return reply;
  925. }
  926. template<typename T>
  927. void ConvertTo(Value& value, bool fAllowNull=false)
  928. {
  929. if (fAllowNull && value.type() == null_type)
  930. return;
  931. if (value.type() == str_type)
  932. {
  933. Value value2;
  934. string strJSON = value.get_str();
  935. if (!read_string(strJSON, value2))
  936. throw runtime_error(string("Error parsing JSON:")+strJSON);
  937. ConvertTo<T>(value2, fAllowNull);
  938. value = value2;
  939. }
  940. else
  941. {
  942. value = value.get_value<T>();
  943. }
  944. }
  945. Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
  946. {
  947. Array params;
  948. BOOST_FOREACH(const std::string &param, strParams)
  949. params.push_back(param);
  950. int n = params.size();
  951. if (strMethod == "stop" && n > 0) ConvertTo<bool>(params[0]);
  952. if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);
  953. if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]);
  954. if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]);
  955. if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]);
  956. if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
  957. if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);
  958. if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]);
  959. if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]);
  960. if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]);
  961. if (strMethod == "getblock" && n > 1) ConvertTo<bool>(params[1]);
  962. if (strMethod == "getblockbynumber" && n > 0) ConvertTo<boost::int64_t>(params[0]);
  963. if (strMethod == "getblockbynumber" && n > 1) ConvertTo<bool>(params[1]);
  964. if (strMethod == "getblockhash" && n > 0) ConvertTo<boost::int64_t>(params[0]);
  965. if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]);
  966. if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]);
  967. if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]);
  968. if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]);
  969. if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]);
  970. if (strMethod == "listtransactions" && n > 2) ConvertTo<boost::int64_t>(params[2]);
  971. if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]);
  972. if (strMethod == "walletpassphrase" && n > 1) ConvertTo<boost::int64_t>(params[1]);
  973. if (strMethod == "walletpassphrase" && n > 2) ConvertTo<bool>(params[2]);
  974. if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]);
  975. if (strMethod == "listsinceblock" && n > 1) ConvertTo<boost::int64_t>(params[1]);
  976. if (strMethod == "sendalert" && n > 2) ConvertTo<boost::int64_t>(params[2]);
  977. if (strMethod == "sendalert" && n > 3) ConvertTo<boost::int64_t>(params[3]);
  978. if (strMethod == "sendalert" && n > 4) ConvertTo<boost::int64_t>(params[4]);
  979. if (strMethod == "sendalert" && n > 5) ConvertTo<boost::int64_t>(params[5]);
  980. if (strMethod == "sendalert" && n > 6) ConvertTo<boost::int64_t>(params[6]);
  981. if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]);
  982. if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]);
  983. if (strMethod == "reservebalance" && n > 0) ConvertTo<bool>(params[0]);
  984. if (strMethod == "reservebalance" && n > 1) ConvertTo<double>(params[1]);
  985. if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
  986. if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]);
  987. if (strMethod == "listunspent" && n > 0) ConvertTo<boost::int64_t>(params[0]);
  988. if (strMethod == "listunspent" && n > 1) ConvertTo<boost::int64_t>(params[1]);
  989. if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]);
  990. if (strMethod == "getrawtransaction" && n > 1) ConvertTo<boost::int64_t>(params[1]);
  991. if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]);
  992. if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]);
  993. if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1], true);
  994. if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2], true);
  995. if (strMethod == "keypoolrefill" && n > 0) ConvertTo<boost::int64_t>(params[0]);
  996. return params;
  997. }
  998. int CommandLineRPC(int argc, char *argv[])
  999. {
  1000. string strPrint;
  1001. int nRet = 0;
  1002. try
  1003. {
  1004. while (argc > 1 && IsSwitchChar(argv[1][0]))
  1005. {
  1006. argc--;
  1007. argv++;
  1008. }
  1009. if (argc < 2)
  1010. throw runtime_error("too few parameters");
  1011. string strMethod = argv[1];
  1012. std::vector<std::string> strParams(&argv[2], &argv[argc]);
  1013. Array params = RPCConvertValues(strMethod, strParams);
  1014. Object reply = CallRPC(strMethod, params);
  1015. const Value& result = find_value(reply, "result");
  1016. const Value& error = find_value(reply, "error");
  1017. if (error.type() != null_type)
  1018. {
  1019. strPrint = "error: " + write_string(error, false);
  1020. int code = find_value(error.get_obj(), "code").get_int();
  1021. nRet = abs(code);
  1022. }
  1023. else
  1024. {
  1025. if (result.type() == null_type)
  1026. strPrint = "";
  1027. else if (result.type() == str_type)
  1028. strPrint = result.get_str();
  1029. else
  1030. strPrint = write_string(result, true);
  1031. }
  1032. }
  1033. catch (std::exception& e)
  1034. {
  1035. strPrint = string("error: ") + e.what();
  1036. nRet = 87;
  1037. }
  1038. catch (...)
  1039. {
  1040. PrintException(NULL, "CommandLineRPC()");
  1041. }
  1042. if (strPrint != "")
  1043. {
  1044. fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
  1045. }
  1046. return nRet;
  1047. }
  1048. #ifdef TEST
  1049. int main(int argc, char *argv[])
  1050. {
  1051. #ifdef _MSC_VER
  1052. _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
  1053. _CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
  1054. #endif
  1055. setbuf(stdin, NULL);
  1056. setbuf(stdout, NULL);
  1057. setbuf(stderr, NULL);
  1058. try
  1059. {
  1060. if (argc >= 2 && string(argv[1]) == "-server")
  1061. {
  1062. printf("server ready\n");
  1063. ThreadRPCServer(NULL);
  1064. }
  1065. else
  1066. {
  1067. return CommandLineRPC(argc, argv);
  1068. }
  1069. }
  1070. catch (std::exception& e) {
  1071. PrintException(&e, "main()");
  1072. } catch (...) {
  1073. PrintException(NULL, "main()");
  1074. }
  1075. return 0;
  1076. }
  1077. #endif
  1078. const CRPCTable tableRPC;