ecoinrpc.cpp 43 KB

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