getnettotals
[novacoin.git] / src / bitcoinrpc.cpp
1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6 #include "init.h"
7 #include "util.h"
8 #include "sync.h"
9 #include "ui_interface.h"
10 #include "base58.h"
11 #include "bitcoinrpc.h"
12 #include "db.h"
13
14 #undef printf
15 #include <boost/asio.hpp>
16 #include <boost/asio/ip/v6_only.hpp>
17 #include <boost/bind.hpp>
18 #include <boost/filesystem.hpp>
19 #include <boost/foreach.hpp>
20 #include <boost/iostreams/concepts.hpp>
21 #include <boost/iostreams/stream.hpp>
22 #include <boost/algorithm/string.hpp>
23 #include <boost/lexical_cast.hpp>
24 #include <boost/asio/ssl.hpp>
25 #include <boost/filesystem/fstream.hpp>
26 #include <boost/shared_ptr.hpp>
27 #include <list>
28
29 #define printf OutputDebugStringF
30
31 using namespace std;
32 using namespace boost;
33 using namespace boost::asio;
34 using namespace json_spirit;
35
36 void ThreadRPCServer2(void* parg);
37
38 static std::string strRPCUserColonPass;
39
40 const Object emptyobj;
41
42 void ThreadRPCServer3(void* parg);
43
44 static inline unsigned short GetDefaultRPCPort()
45 {
46     return GetBoolArg("-testnet", false) ? 18344 : 8344;
47 }
48
49 Object JSONRPCError(int code, const string& message)
50 {
51     Object error;
52     error.push_back(Pair("code", code));
53     error.push_back(Pair("message", message));
54     return error;
55 }
56
57 void RPCTypeCheck(const Array& params,
58                   const list<Value_type>& typesExpected,
59                   bool fAllowNull)
60 {
61     unsigned int i = 0;
62     BOOST_FOREACH(Value_type t, typesExpected)
63     {
64         if (params.size() <= i)
65             break;
66
67         const Value& v = params[i];
68         if (!((v.type() == t) || (fAllowNull && (v.type() == null_type))))
69         {
70             string err = strprintf("Expected type %s, got %s",
71                                    Value_type_name[t], Value_type_name[v.type()]);
72             throw JSONRPCError(RPC_TYPE_ERROR, err);
73         }
74         i++;
75     }
76 }
77
78 void RPCTypeCheck(const Object& o,
79                   const map<string, Value_type>& typesExpected,
80                   bool fAllowNull)
81 {
82     BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected)
83     {
84         const Value& v = find_value(o, t.first);
85         if (!fAllowNull && v.type() == null_type)
86             throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first.c_str()));
87
88         if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type))))
89         {
90             string err = strprintf("Expected type %s for %s, got %s",
91                                    Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]);
92             throw JSONRPCError(RPC_TYPE_ERROR, err);
93         }
94     }
95 }
96
97 int64 AmountFromValue(const Value& value)
98 {
99     double dAmount = value.get_real();
100     if (dAmount <= 0.0 || dAmount > MAX_MONEY)
101         throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
102     int64 nAmount = roundint64(dAmount * COIN);
103     if (!MoneyRange(nAmount))
104         throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
105     return nAmount;
106 }
107
108 Value ValueFromAmount(int64 amount)
109 {
110     return (double)amount / (double)COIN;
111 }
112
113 std::string HexBits(unsigned int nBits)
114 {
115     union {
116         int32_t nBits;
117         char cBits[4];
118     } uBits;
119     uBits.nBits = htonl((int32_t)nBits);
120     return HexStr(BEGIN(uBits.cBits), END(uBits.cBits));
121 }
122
123
124 //
125 // Utilities: convert hex-encoded Values
126 // (throws error if not hex).
127 //
128 uint256 ParseHashV(const Value& v, string strName)
129 {
130     string strHex;
131     if (v.type() == str_type)
132         strHex = v.get_str();
133     if (!IsHex(strHex)) // Note: IsHex("") is false
134         throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
135     uint256 result;
136     result.SetHex(strHex);
137     return result;
138 }
139
140 uint256 ParseHashO(const Object& o, string strKey)
141 {
142     return ParseHashV(find_value(o, strKey), strKey);
143 }
144
145 vector<unsigned char> ParseHexV(const Value& v, string strName)
146 {
147     string strHex;
148     if (v.type() == str_type)
149         strHex = v.get_str();
150     if (!IsHex(strHex))
151         throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
152     return ParseHex(strHex);
153 }
154
155 vector<unsigned char> ParseHexO(const Object& o, string strKey)
156 {
157     return ParseHexV(find_value(o, strKey), strKey);
158 }
159
160
161 ///
162 /// Note: This interface may still be subject to change.
163 ///
164
165 string CRPCTable::help(string strCommand) const
166 {
167     string strRet;
168     set<rpcfn_type> setDone;
169     for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)
170     {
171         const CRPCCommand *pcmd = mi->second;
172         string strMethod = mi->first;
173         // We already filter duplicates, but these deprecated screw up the sort order
174         if (strMethod.find("label") != string::npos)
175             continue;
176         if (strCommand != "" && strMethod != strCommand)
177             continue;
178         try
179         {
180             Array params;
181             rpcfn_type pfn = pcmd->actor;
182             if (setDone.insert(pfn).second)
183                 (*pfn)(params, true);
184         }
185         catch (std::exception& e)
186         {
187             // Help text is returned in an exception
188             string strHelp = string(e.what());
189             if (strCommand == "")
190                 if (strHelp.find('\n') != string::npos)
191                     strHelp = strHelp.substr(0, strHelp.find('\n'));
192             strRet += strHelp + "\n";
193         }
194     }
195     if (strRet == "")
196         strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
197     strRet = strRet.substr(0,strRet.size()-1);
198     return strRet;
199 }
200
201 Value help(const Array& params, bool fHelp)
202 {
203     if (fHelp || params.size() > 1)
204         throw runtime_error(
205             "help [command]\n"
206             "List commands, or get help for a command.");
207
208     string strCommand;
209     if (params.size() > 0)
210         strCommand = params[0].get_str();
211
212     return tableRPC.help(strCommand);
213 }
214
215
216 Value stop(const Array& params, bool fHelp)
217 {
218     if (fHelp || params.size() > 1)
219         throw runtime_error(
220             "stop <detach>\n"
221             "<detach> is true or false to detach the database or not for this stop only\n"
222             "Stop NovaCoin server (and possibly override the detachdb config value).");
223     // Shutdown will take long enough that the response should get back
224     if (params.size() > 0)
225         bitdb.SetDetach(params[0].get_bool());
226     StartShutdown();
227     return "NovaCoin server stopping";
228 }
229
230
231
232 //
233 // Call Table
234 //
235
236
237 static const CRPCCommand vRPCCommands[] =
238 { //  name                      function                 safemd  unlocked
239   //  ------------------------  -----------------------  ------  --------
240     { "help",                   &help,                   true,   true },
241     { "stop",                   &stop,                   true,   true },
242     { "getbestblockhash",       &getbestblockhash,       true,   false },
243     { "getblockcount",          &getblockcount,          true,   false },
244     { "getconnectioncount",     &getconnectioncount,     true,   false },
245     { "getpeerinfo",            &getpeerinfo,            true,   false },
246     { "getdifficulty",          &getdifficulty,          true,   false },
247     { "getinfo",                &getinfo,                true,   false },
248     { "getsubsidy",             &getsubsidy,             true,   false },
249     { "getmininginfo",          &getmininginfo,          true,   false },
250     { "getnewaddress",          &getnewaddress,          true,   false },
251     { "getnettotals",           &getnettotals,           true,   true  },
252     { "getaccountaddress",      &getaccountaddress,      true,   false },
253     { "setaccount",             &setaccount,             true,   false },
254     { "getaccount",             &getaccount,             false,  false },
255     { "getaddressesbyaccount",  &getaddressesbyaccount,  true,   false },
256     { "sendtoaddress",          &sendtoaddress,          false,  false },
257     { "mergecoins",             &mergecoins,            false,  false },
258     { "getreceivedbyaddress",   &getreceivedbyaddress,   false,  false },
259     { "getreceivedbyaccount",   &getreceivedbyaccount,   false,  false },
260     { "listreceivedbyaddress",  &listreceivedbyaddress,  false,  false },
261     { "listreceivedbyaccount",  &listreceivedbyaccount,  false,  false },
262     { "backupwallet",           &backupwallet,           true,   false },
263     { "keypoolrefill",          &keypoolrefill,          true,   false },
264     { "walletpassphrase",       &walletpassphrase,       true,   false },
265     { "walletpassphrasechange", &walletpassphrasechange, false,  false },
266     { "walletlock",             &walletlock,             true,   false },
267     { "encryptwallet",          &encryptwallet,          false,  false },
268     { "validateaddress",        &validateaddress,        true,   false },
269     { "getbalance",             &getbalance,             false,  false },
270     { "move",                   &movecmd,                false,  false },
271     { "sendfrom",               &sendfrom,               false,  false },
272     { "sendmany",               &sendmany,               false,  false },
273     { "addmultisigaddress",     &addmultisigaddress,     false,  false },
274     { "addredeemscript",        &addredeemscript,        false,  false },
275     { "getrawmempool",          &getrawmempool,          true,   false },
276     { "getblock",               &getblock,               false,  false },
277     { "getblockbynumber",       &getblockbynumber,       false,  false },
278     { "getblockhash",           &getblockhash,           false,  false },
279     { "gettransaction",         &gettransaction,         false,  false },
280     { "listtransactions",       &listtransactions,       false,  false },
281     { "listaddressgroupings",   &listaddressgroupings,   false,  false },
282     { "signmessage",            &signmessage,            false,  false },
283     { "verifymessage",          &verifymessage,          false,  false },
284     { "getwork",                &getwork,                true,   false },
285     { "getworkex",              &getworkex,              true,   false },
286     { "listaccounts",           &listaccounts,           false,  false },
287     { "settxfee",               &settxfee,               false,  false },
288     { "getblocktemplate",       &getblocktemplate,       true,   false },
289     { "submitblock",            &submitblock,            false,  false },
290     { "listsinceblock",         &listsinceblock,         false,  false },
291     { "dumpprivkey",            &dumpprivkey,            false,  false },
292     { "dumpwallet",             &dumpwallet,             true,   false },
293     { "importwallet",           &importwallet,           false,  false },
294     { "importprivkey",          &importprivkey,          false,  false },
295     { "importaddress",          &importaddress,          false,  true  },
296     { "listunspent",            &listunspent,            false,  false },
297     { "getrawtransaction",      &getrawtransaction,      false,  false },
298     { "createrawtransaction",   &createrawtransaction,   false,  false },
299     { "decoderawtransaction",   &decoderawtransaction,   false,  false },
300     { "createmultisig",         &createmultisig,         false,  false },
301     { "decodescript",           &decodescript,           false,  false },
302     { "signrawtransaction",     &signrawtransaction,     false,  false },
303     { "sendrawtransaction",     &sendrawtransaction,     false,  false },
304     { "getcheckpoint",          &getcheckpoint,          true,   false },
305     { "reservebalance",         &reservebalance,         false,  true},
306     { "checkwallet",            &checkwallet,            false,  true},
307     { "repairwallet",           &repairwallet,           false,  true},
308     { "resendtx",               &resendtx,               false,  true},
309     { "makekeypair",            &makekeypair,            false,  true},
310     { "sendalert",              &sendalert,              false,  false},
311 };
312
313 CRPCTable::CRPCTable()
314 {
315     unsigned int vcidx;
316     for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++)
317     {
318         const CRPCCommand *pcmd;
319
320         pcmd = &vRPCCommands[vcidx];
321         mapCommands[pcmd->name] = pcmd;
322     }
323 }
324
325 const CRPCCommand *CRPCTable::operator[](string name) const
326 {
327     map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
328     if (it == mapCommands.end())
329         return NULL;
330     return (*it).second;
331 }
332
333 //
334 // HTTP protocol
335 //
336 // This ain't Apache.  We're just using HTTP header for the length field
337 // and to be compatible with other JSON-RPC implementations.
338 //
339
340 string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
341 {
342     ostringstream s;
343     s << "POST / HTTP/1.1\r\n"
344       << "User-Agent: novacoin-json-rpc/" << FormatFullVersion() << "\r\n"
345       << "Host: 127.0.0.1\r\n"
346       << "Content-Type: application/json\r\n"
347       << "Content-Length: " << strMsg.size() << "\r\n"
348       << "Connection: close\r\n"
349       << "Accept: application/json\r\n";
350     BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders)
351         s << item.first << ": " << item.second << "\r\n";
352     s << "\r\n" << strMsg;
353
354     return s.str();
355 }
356
357 string rfc1123Time()
358 {
359     char buffer[64];
360     time_t now;
361     time(&now);
362     struct tm* now_gmt = gmtime(&now);
363     string locale(setlocale(LC_TIME, NULL));
364     setlocale(LC_TIME, "C"); // we want POSIX (aka "C") weekday/month strings
365     strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt);
366     setlocale(LC_TIME, locale.c_str());
367     return string(buffer);
368 }
369
370 static string HTTPReply(int nStatus, const string& strMsg, bool keepalive)
371 {
372     if (nStatus == HTTP_UNAUTHORIZED)
373         return strprintf("HTTP/1.0 401 Authorization Required\r\n"
374             "Date: %s\r\n"
375             "Server: novacoin-json-rpc/%s\r\n"
376             "WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
377             "Content-Type: text/html\r\n"
378             "Content-Length: 296\r\n"
379             "\r\n"
380             "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
381             "\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
382             "<HTML>\r\n"
383             "<HEAD>\r\n"
384             "<TITLE>Error</TITLE>\r\n"
385             "<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
386             "</HEAD>\r\n"
387             "<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
388             "</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str());
389     const char *cStatus;
390          if (nStatus == HTTP_OK) cStatus = "OK";
391     else if (nStatus == HTTP_BAD_REQUEST) cStatus = "Bad Request";
392     else if (nStatus == HTTP_FORBIDDEN) cStatus = "Forbidden";
393     else if (nStatus == HTTP_NOT_FOUND) cStatus = "Not Found";
394     else if (nStatus == HTTP_INTERNAL_SERVER_ERROR) cStatus = "Internal Server Error";
395     else cStatus = "";
396     return strprintf(
397             "HTTP/1.1 %d %s\r\n"
398             "Date: %s\r\n"
399             "Connection: %s\r\n"
400             "Content-Length: %"PRIszu"\r\n"
401             "Content-Type: application/json\r\n"
402             "Server: novacoin-json-rpc/%s\r\n"
403             "\r\n"
404             "%s",
405         nStatus,
406         cStatus,
407         rfc1123Time().c_str(),
408         keepalive ? "keep-alive" : "close",
409         strMsg.size(),
410         FormatFullVersion().c_str(),
411         strMsg.c_str());
412 }
413
414 int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto)
415 {
416     string str;
417     getline(stream, str);
418     vector<string> vWords;
419     boost::split(vWords, str, boost::is_any_of(" "));
420     if (vWords.size() < 2)
421         return HTTP_INTERNAL_SERVER_ERROR;
422     proto = 0;
423     const char *ver = strstr(str.c_str(), "HTTP/1.");
424     if (ver != NULL)
425         proto = atoi(ver+7);
426     return atoi(vWords[1].c_str());
427 }
428
429 int ReadHTTPHeader(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
430 {
431     int nLen = 0;
432     while (true)
433     {
434         string str;
435         std::getline(stream, str);
436         if (str.empty() || str == "\r")
437             break;
438         string::size_type nColon = str.find(":");
439         if (nColon != string::npos)
440         {
441             string strHeader = str.substr(0, nColon);
442             boost::trim(strHeader);
443             boost::to_lower(strHeader);
444             string strValue = str.substr(nColon+1);
445             boost::trim(strValue);
446             mapHeadersRet[strHeader] = strValue;
447             if (strHeader == "content-length")
448                 nLen = atoi(strValue.c_str());
449         }
450     }
451     return nLen;
452 }
453
454 int ReadHTTP(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet)
455 {
456     mapHeadersRet.clear();
457     strMessageRet = "";
458
459     // Read status
460     int nProto = 0;
461     int nStatus = ReadHTTPStatus(stream, nProto);
462
463     // Read header
464     int nLen = ReadHTTPHeader(stream, mapHeadersRet);
465     if (nLen < 0 || nLen > (int)MAX_SIZE)
466         return HTTP_INTERNAL_SERVER_ERROR;
467
468     // Read message
469     if (nLen > 0)
470     {
471         vector<char> vch(nLen);
472         stream.read(&vch[0], nLen);
473         strMessageRet = string(vch.begin(), vch.end());
474     }
475
476     string sConHdr = mapHeadersRet["connection"];
477
478     if ((sConHdr != "close") && (sConHdr != "keep-alive"))
479     {
480         if (nProto >= 1)
481             mapHeadersRet["connection"] = "keep-alive";
482         else
483             mapHeadersRet["connection"] = "close";
484     }
485
486     return nStatus;
487 }
488
489 bool HTTPAuthorized(map<string, string>& mapHeaders)
490 {
491     string strAuth = mapHeaders["authorization"];
492     if (strAuth.substr(0,6) != "Basic ")
493         return false;
494     string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
495     string strUserPass = DecodeBase64(strUserPass64);
496     return TimingResistantEqual(strUserPass, strRPCUserColonPass);
497 }
498
499 //
500 // JSON-RPC protocol.  Bitcoin speaks version 1.0 for maximum compatibility,
501 // but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
502 // unspecified (HTTP errors and contents of 'error').
503 //
504 // 1.0 spec: http://json-rpc.org/wiki/specification
505 // 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
506 // http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
507 //
508
509 string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
510 {
511     Object request;
512     request.push_back(Pair("method", strMethod));
513     request.push_back(Pair("params", params));
514     request.push_back(Pair("id", id));
515     return write_string(Value(request), false) + "\n";
516 }
517
518 Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id)
519 {
520     Object reply;
521     if (error.type() != null_type)
522         reply.push_back(Pair("result", Value::null));
523     else
524         reply.push_back(Pair("result", result));
525     reply.push_back(Pair("error", error));
526     reply.push_back(Pair("id", id));
527     return reply;
528 }
529
530 string JSONRPCReply(const Value& result, const Value& error, const Value& id)
531 {
532     Object reply = JSONRPCReplyObj(result, error, id);
533     return write_string(Value(reply), false) + "\n";
534 }
535
536 void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
537 {
538     // Send error reply from json-rpc error object
539     int nStatus = HTTP_INTERNAL_SERVER_ERROR;
540     int code = find_value(objError, "code").get_int();
541     if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST;
542     else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND;
543     string strReply = JSONRPCReply(Value::null, objError, id);
544     stream << HTTPReply(nStatus, strReply, false) << std::flush;
545 }
546
547 bool ClientAllowed(const boost::asio::ip::address& address)
548 {
549     // Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses
550     if (address.is_v6()
551      && (address.to_v6().is_v4_compatible()
552       || address.to_v6().is_v4_mapped()))
553         return ClientAllowed(address.to_v6().to_v4());
554
555     if (address == asio::ip::address_v4::loopback()
556      || address == asio::ip::address_v6::loopback()
557      || (address.is_v4()
558          // Check whether IPv4 addresses match 127.0.0.0/8 (loopback subnet)
559       && (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000))
560         return true;
561
562     const string strAddress = address.to_string();
563     const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
564     BOOST_FOREACH(string strAllow, vAllow)
565         if (WildcardMatch(strAddress, strAllow))
566             return true;
567     return false;
568 }
569
570 //
571 // IOStream device that speaks SSL but can also speak non-SSL
572 //
573 template <typename Protocol>
574 class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {
575 public:
576     SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn)
577     {
578         fUseSSL = fUseSSLIn;
579         fNeedHandshake = fUseSSLIn;
580     }
581
582     void handshake(ssl::stream_base::handshake_type role)
583     {
584         if (!fNeedHandshake) return;
585         fNeedHandshake = false;
586         stream.handshake(role);
587     }
588     std::streamsize read(char* s, std::streamsize n)
589     {
590         handshake(ssl::stream_base::server); // HTTPS servers read first
591         if (fUseSSL) return stream.read_some(asio::buffer(s, n));
592         return stream.next_layer().read_some(asio::buffer(s, n));
593     }
594     std::streamsize write(const char* s, std::streamsize n)
595     {
596         handshake(ssl::stream_base::client); // HTTPS clients write first
597         if (fUseSSL) return asio::write(stream, asio::buffer(s, n));
598         return asio::write(stream.next_layer(), asio::buffer(s, n));
599     }
600     bool connect(const std::string& server, const std::string& port)
601     {
602         ip::tcp::resolver resolver(stream.get_io_service());
603         ip::tcp::resolver::query query(server.c_str(), port.c_str());
604         ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
605         ip::tcp::resolver::iterator end;
606         boost::system::error_code error = asio::error::host_not_found;
607         while (error && endpoint_iterator != end)
608         {
609             stream.lowest_layer().close();
610             stream.lowest_layer().connect(*endpoint_iterator++, error);
611         }
612         if (error)
613             return false;
614         return true;
615     }
616
617 private:
618     bool fNeedHandshake;
619     bool fUseSSL;
620     asio::ssl::stream<typename Protocol::socket>& stream;
621 };
622
623 class AcceptedConnection
624 {
625 public:
626     virtual ~AcceptedConnection() {}
627
628     virtual std::iostream& stream() = 0;
629     virtual std::string peer_address_to_string() const = 0;
630     virtual void close() = 0;
631 };
632
633 template <typename Protocol>
634 class AcceptedConnectionImpl : public AcceptedConnection
635 {
636 public:
637     AcceptedConnectionImpl(
638             asio::io_service& io_service,
639             ssl::context &context,
640             bool fUseSSL) :
641         sslStream(io_service, context),
642         _d(sslStream, fUseSSL),
643         _stream(_d)
644     {
645     }
646
647     virtual std::iostream& stream()
648     {
649         return _stream;
650     }
651
652     virtual std::string peer_address_to_string() const
653     {
654         return peer.address().to_string();
655     }
656
657     virtual void close()
658     {
659         _stream.close();
660     }
661
662     typename Protocol::endpoint peer;
663     asio::ssl::stream<typename Protocol::socket> sslStream;
664
665 private:
666     SSLIOStreamDevice<Protocol> _d;
667     iostreams::stream< SSLIOStreamDevice<Protocol> > _stream;
668 };
669
670 void ThreadRPCServer(void* parg)
671 {
672     // Make this thread recognisable as the RPC listener
673     RenameThread("novacoin-rpclist");
674
675     try
676     {
677         vnThreadsRunning[THREAD_RPCLISTENER]++;
678         ThreadRPCServer2(parg);
679         vnThreadsRunning[THREAD_RPCLISTENER]--;
680     }
681     catch (std::exception& e) {
682         vnThreadsRunning[THREAD_RPCLISTENER]--;
683         PrintException(&e, "ThreadRPCServer()");
684     } catch (...) {
685         vnThreadsRunning[THREAD_RPCLISTENER]--;
686         PrintException(NULL, "ThreadRPCServer()");
687     }
688     printf("ThreadRPCServer exited\n");
689 }
690
691 // Forward declaration required for RPCListen
692 template <typename Protocol, typename SocketAcceptorService>
693 static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
694                              ssl::context& context,
695                              bool fUseSSL,
696                              AcceptedConnection* conn,
697                              const boost::system::error_code& error);
698
699 /**
700  * Sets up I/O resources to accept and handle a new connection.
701  */
702 template <typename Protocol, typename SocketAcceptorService>
703 static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
704                    ssl::context& context,
705                    const bool fUseSSL)
706 {
707     // Accept connection
708     AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL);
709
710     acceptor->async_accept(
711             conn->sslStream.lowest_layer(),
712             conn->peer,
713             boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>,
714                 acceptor,
715                 boost::ref(context),
716                 fUseSSL,
717                 conn,
718                 boost::asio::placeholders::error));
719 }
720
721 /**
722  * Accept and handle incoming connection.
723  */
724 template <typename Protocol, typename SocketAcceptorService>
725 static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
726                              ssl::context& context,
727                              const bool fUseSSL,
728                              AcceptedConnection* conn,
729                              const boost::system::error_code& error)
730 {
731     vnThreadsRunning[THREAD_RPCLISTENER]++;
732
733     // Immediately start accepting new connections, except when we're cancelled or our socket is closed.
734     if (error != asio::error::operation_aborted
735      && acceptor->is_open())
736         RPCListen(acceptor, context, fUseSSL);
737
738     AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn);
739
740     // TODO: Actually handle errors
741     if (error)
742     {
743         delete conn;
744     }
745
746     // Restrict callers by IP.  It is important to
747     // do this before starting client thread, to filter out
748     // certain DoS and misbehaving clients.
749     else if (tcp_conn
750           && !ClientAllowed(tcp_conn->peer.address()))
751     {
752         // Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake.
753         if (!fUseSSL)
754             conn->stream() << HTTPReply(HTTP_FORBIDDEN, "", false) << std::flush;
755         delete conn;
756     }
757
758     // start HTTP client thread
759     else if (!NewThread(ThreadRPCServer3, conn)) {
760         printf("Failed to create RPC server client thread\n");
761         delete conn;
762     }
763
764     vnThreadsRunning[THREAD_RPCLISTENER]--;
765 }
766
767 void ThreadRPCServer2(void* parg)
768 {
769     printf("ThreadRPCServer started\n");
770
771     strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
772     if (mapArgs["-rpcpassword"] == "")
773     {
774         unsigned char rand_pwd[32];
775         RAND_bytes(rand_pwd, 32);
776         string strWhatAmI = "To use novacoind";
777         if (mapArgs.count("-server"))
778             strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
779         else if (mapArgs.count("-daemon"))
780             strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
781         uiInterface.ThreadSafeMessageBox(strprintf(
782             _("%s, you must set a rpcpassword in the configuration file:\n %s\n"
783               "It is recommended you use the following random password:\n"
784               "rpcuser=bitcoinrpc\n"
785               "rpcpassword=%s\n"
786               "(you do not need to remember this password)\n"
787               "If the file does not exist, create it with owner-readable-only file permissions.\n"),
788                 strWhatAmI.c_str(),
789                 GetConfigFile().string().c_str(),
790                 EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()),
791             _("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL);
792         StartShutdown();
793         return;
794     }
795
796     const bool fUseSSL = GetBoolArg("-rpcssl");
797
798     asio::io_service io_service;
799
800     ssl::context context(io_service, ssl::context::sslv23);
801     if (fUseSSL)
802     {
803         context.set_options(ssl::context::no_sslv2);
804
805         filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert"));
806         if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile;
807         if (filesystem::exists(pathCertFile)) context.use_certificate_chain_file(pathCertFile.string());
808         else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string().c_str());
809
810         filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem"));
811         if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile;
812         if (filesystem::exists(pathPKFile)) context.use_private_key_file(pathPKFile.string(), ssl::context::pem);
813         else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str());
814
815         string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
816         SSL_CTX_set_cipher_list(context.impl(), strCiphers.c_str());
817     }
818
819     // Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets
820     const bool loopback = !mapArgs.count("-rpcallowip");
821     asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any();
822     ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", GetDefaultRPCPort()));
823     boost::system::error_code v6_only_error;
824     boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(io_service));
825
826     boost::signals2::signal<void ()> StopRequests;
827
828     bool fListening = false;
829     std::string strerr;
830     try
831     {
832         acceptor->open(endpoint.protocol());
833         acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
834
835         // Try making the socket dual IPv6/IPv4 (if listening on the "any" address)
836         acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error);
837
838         acceptor->bind(endpoint);
839         acceptor->listen(socket_base::max_connections);
840
841         RPCListen(acceptor, context, fUseSSL);
842         // Cancel outstanding listen-requests for this acceptor when shutting down
843         StopRequests.connect(signals2::slot<void ()>(
844                     static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get())
845                 .track(acceptor));
846
847         fListening = true;
848     }
849     catch(boost::system::system_error &e)
850     {
851         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());
852     }
853
854     try {
855         // If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately
856         if (!fListening || loopback || v6_only_error)
857         {
858             bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any();
859             endpoint.address(bindAddress);
860
861             acceptor.reset(new ip::tcp::acceptor(io_service));
862             acceptor->open(endpoint.protocol());
863             acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
864             acceptor->bind(endpoint);
865             acceptor->listen(socket_base::max_connections);
866
867             RPCListen(acceptor, context, fUseSSL);
868             // Cancel outstanding listen-requests for this acceptor when shutting down
869             StopRequests.connect(signals2::slot<void ()>(
870                         static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get())
871                     .track(acceptor));
872
873             fListening = true;
874         }
875     }
876     catch(boost::system::system_error &e)
877     {
878         strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv4: %s"), endpoint.port(), e.what());
879     }
880
881     if (!fListening) {
882         uiInterface.ThreadSafeMessageBox(strerr, _("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL);
883         StartShutdown();
884         return;
885     }
886
887     vnThreadsRunning[THREAD_RPCLISTENER]--;
888     while (!fShutdown)
889         io_service.run_one();
890     vnThreadsRunning[THREAD_RPCLISTENER]++;
891     StopRequests();
892 }
893
894 class JSONRequest
895 {
896 public:
897     Value id;
898     string strMethod;
899     Array params;
900
901     JSONRequest() { id = Value::null; }
902     void parse(const Value& valRequest);
903 };
904
905 void JSONRequest::parse(const Value& valRequest)
906 {
907     // Parse request
908     if (valRequest.type() != obj_type)
909         throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
910     const Object& request = valRequest.get_obj();
911
912     // Parse id now so errors from here on will have the id
913     id = find_value(request, "id");
914
915     // Parse method
916     Value valMethod = find_value(request, "method");
917     if (valMethod.type() == null_type)
918         throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
919     if (valMethod.type() != str_type)
920         throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
921     strMethod = valMethod.get_str();
922     if (strMethod != "getwork" && strMethod != "getblocktemplate")
923         printf("ThreadRPCServer method=%s\n", strMethod.c_str());
924
925     // Parse params
926     Value valParams = find_value(request, "params");
927     if (valParams.type() == array_type)
928         params = valParams.get_array();
929     else if (valParams.type() == null_type)
930         params = Array();
931     else
932         throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array");
933 }
934
935 static Object JSONRPCExecOne(const Value& req)
936 {
937     Object rpc_result;
938
939     JSONRequest jreq;
940     try {
941         jreq.parse(req);
942
943         Value result = tableRPC.execute(jreq.strMethod, jreq.params);
944         rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id);
945     }
946     catch (Object& objError)
947     {
948         rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id);
949     }
950     catch (std::exception& e)
951     {
952         rpc_result = JSONRPCReplyObj(Value::null,
953                                      JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
954     }
955
956     return rpc_result;
957 }
958
959 static string JSONRPCExecBatch(const Array& vReq)
960 {
961     Array ret;
962     for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
963         ret.push_back(JSONRPCExecOne(vReq[reqIdx]));
964
965     return write_string(Value(ret), false) + "\n";
966 }
967
968 static CCriticalSection cs_THREAD_RPCHANDLER;
969
970 void ThreadRPCServer3(void* parg)
971 {
972     // Make this thread recognisable as the RPC handler
973     RenameThread("novacoin-rpchand");
974
975     {
976         LOCK(cs_THREAD_RPCHANDLER);
977         vnThreadsRunning[THREAD_RPCHANDLER]++;
978     }
979     AcceptedConnection *conn = (AcceptedConnection *) parg;
980
981     bool fRun = true;
982     while (true)
983     {
984         if (fShutdown || !fRun)
985         {
986             conn->close();
987             delete conn;
988             {
989                 LOCK(cs_THREAD_RPCHANDLER);
990                 --vnThreadsRunning[THREAD_RPCHANDLER];
991             }
992             return;
993         }
994         map<string, string> mapHeaders;
995         string strRequest;
996
997         ReadHTTP(conn->stream(), mapHeaders, strRequest);
998
999         // Check authorization
1000         if (mapHeaders.count("authorization") == 0)
1001         {
1002             conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
1003             break;
1004         }
1005         if (!HTTPAuthorized(mapHeaders))
1006         {
1007             printf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string().c_str());
1008             /* Deter brute-forcing short passwords.
1009                If this results in a DOS the user really
1010                shouldn't have their RPC port exposed.*/
1011             if (mapArgs["-rpcpassword"].size() < 20)
1012                 Sleep(250);
1013
1014             conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
1015             break;
1016         }
1017         if (mapHeaders["connection"] == "close")
1018             fRun = false;
1019
1020         JSONRequest jreq;
1021         try
1022         {
1023             // Parse request
1024             Value valRequest;
1025             if (!read_string(strRequest, valRequest))
1026                 throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
1027
1028             string strReply;
1029
1030             // singleton request
1031             if (valRequest.type() == obj_type) {
1032                 jreq.parse(valRequest);
1033
1034                 Value result = tableRPC.execute(jreq.strMethod, jreq.params);
1035
1036                 // Send reply
1037                 strReply = JSONRPCReply(result, Value::null, jreq.id);
1038
1039             // array of requests
1040             } else if (valRequest.type() == array_type)
1041                 strReply = JSONRPCExecBatch(valRequest.get_array());
1042             else
1043                 throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
1044
1045             conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush;
1046         }
1047         catch (Object& objError)
1048         {
1049             ErrorReply(conn->stream(), objError, jreq.id);
1050             break;
1051         }
1052         catch (std::exception& e)
1053         {
1054             ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
1055             break;
1056         }
1057     }
1058
1059     delete conn;
1060     {
1061         LOCK(cs_THREAD_RPCHANDLER);
1062         vnThreadsRunning[THREAD_RPCHANDLER]--;
1063     }
1064 }
1065
1066 json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array &params) const
1067 {
1068     // Find method
1069     const CRPCCommand *pcmd = tableRPC[strMethod];
1070     if (!pcmd)
1071         throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
1072
1073     // Observe safe mode
1074     string strWarning = GetWarnings("rpc");
1075     if (strWarning != "" && !GetBoolArg("-disablesafemode") &&
1076         !pcmd->okSafeMode)
1077         throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
1078
1079     try
1080     {
1081         // Execute
1082         Value result;
1083         {
1084             if (pcmd->unlocked)
1085                 result = pcmd->actor(params, false);
1086             else {
1087                 LOCK2(cs_main, pwalletMain->cs_wallet);
1088                 result = pcmd->actor(params, false);
1089             }
1090         }
1091         return result;
1092     }
1093     catch (std::exception& e)
1094     {
1095         throw JSONRPCError(RPC_MISC_ERROR, e.what());
1096     }
1097 }
1098
1099
1100 Object CallRPC(const string& strMethod, const Array& params)
1101 {
1102     if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
1103         throw runtime_error(strprintf(
1104             _("You must set rpcpassword=<password> in the configuration file:\n%s\n"
1105               "If the file does not exist, create it with owner-readable-only file permissions."),
1106                 GetConfigFile().string().c_str()));
1107
1108     // Connect to localhost
1109     bool fUseSSL = GetBoolArg("-rpcssl");
1110     asio::io_service io_service;
1111     ssl::context context(io_service, ssl::context::sslv23);
1112     context.set_options(ssl::context::no_sslv2);
1113     asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context);
1114     SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL);
1115     iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d);
1116     if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(GetDefaultRPCPort()))))
1117         throw runtime_error("couldn't connect to server");
1118
1119     // HTTP basic authentication
1120     string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
1121     map<string, string> mapRequestHeaders;
1122     mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
1123
1124     // Send request
1125     string strRequest = JSONRPCRequest(strMethod, params, 1);
1126     string strPost = HTTPPost(strRequest, mapRequestHeaders);
1127     stream << strPost << std::flush;
1128
1129     // Receive reply
1130     map<string, string> mapHeaders;
1131     string strReply;
1132     int nStatus = ReadHTTP(stream, mapHeaders, strReply);
1133     if (nStatus == HTTP_UNAUTHORIZED)
1134         throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
1135     else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR)
1136         throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
1137     else if (strReply.empty())
1138         throw runtime_error("no response from server");
1139
1140     // Parse reply
1141     Value valReply;
1142     if (!read_string(strReply, valReply))
1143         throw runtime_error("couldn't parse reply from server");
1144     const Object& reply = valReply.get_obj();
1145     if (reply.empty())
1146         throw runtime_error("expected reply to have result, error and id properties");
1147
1148     return reply;
1149 }
1150
1151
1152
1153
1154 template<typename T>
1155 void ConvertTo(Value& value, bool fAllowNull=false)
1156 {
1157     if (fAllowNull && value.type() == null_type)
1158         return;
1159     if (value.type() == str_type)
1160     {
1161         // reinterpret string as unquoted json value
1162         Value value2;
1163         string strJSON = value.get_str();
1164         if (!read_string(strJSON, value2))
1165             throw runtime_error(string("Error parsing JSON:")+strJSON);
1166         ConvertTo<T>(value2, fAllowNull);
1167         value = value2;
1168     }
1169     else
1170     {
1171         value = value.get_value<T>();
1172     }
1173 }
1174
1175 // Convert strings to command-specific RPC representation
1176 Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
1177 {
1178     Array params;
1179     BOOST_FOREACH(const std::string &param, strParams)
1180         params.push_back(param);
1181
1182     int n = params.size();
1183
1184     //
1185     // Special case non-string parameter types
1186     //
1187     if (strMethod == "stop"                   && n > 0) ConvertTo<bool>(params[0]);
1188     if (strMethod == "sendtoaddress"          && n > 1) ConvertTo<double>(params[1]);
1189     if (strMethod == "mergecoins"            && n > 0) ConvertTo<double>(params[0]);
1190     if (strMethod == "mergecoins"            && n > 1) ConvertTo<double>(params[1]);
1191     if (strMethod == "mergecoins"            && n > 2) ConvertTo<double>(params[2]);
1192     if (strMethod == "settxfee"               && n > 0) ConvertTo<double>(params[0]);
1193     if (strMethod == "getreceivedbyaddress"   && n > 1) ConvertTo<boost::int64_t>(params[1]);
1194     if (strMethod == "getreceivedbyaccount"   && n > 1) ConvertTo<boost::int64_t>(params[1]);
1195     if (strMethod == "listreceivedbyaddress"  && n > 0) ConvertTo<boost::int64_t>(params[0]);
1196     if (strMethod == "listreceivedbyaddress"  && n > 1) ConvertTo<bool>(params[1]);
1197     if (strMethod == "listreceivedbyaccount"  && n > 0) ConvertTo<boost::int64_t>(params[0]);
1198     if (strMethod == "listreceivedbyaccount"  && n > 1) ConvertTo<bool>(params[1]);
1199     if (strMethod == "getbalance"             && n > 1) ConvertTo<boost::int64_t>(params[1]);
1200     if (strMethod == "getblock"               && n > 1) ConvertTo<bool>(params[1]);
1201     if (strMethod == "getblockbynumber"       && n > 0) ConvertTo<boost::int64_t>(params[0]);
1202     if (strMethod == "getblockbynumber"       && n > 1) ConvertTo<bool>(params[1]);
1203     if (strMethod == "getblockhash"           && n > 0) ConvertTo<boost::int64_t>(params[0]);
1204     if (strMethod == "move"                   && n > 2) ConvertTo<double>(params[2]);
1205     if (strMethod == "move"                   && n > 3) ConvertTo<boost::int64_t>(params[3]);
1206     if (strMethod == "sendfrom"               && n > 2) ConvertTo<double>(params[2]);
1207     if (strMethod == "sendfrom"               && n > 3) ConvertTo<boost::int64_t>(params[3]);
1208     if (strMethod == "listtransactions"       && n > 1) ConvertTo<boost::int64_t>(params[1]);
1209     if (strMethod == "listtransactions"       && n > 2) ConvertTo<boost::int64_t>(params[2]);
1210     if (strMethod == "listaccounts"           && n > 0) ConvertTo<boost::int64_t>(params[0]);
1211     if (strMethod == "walletpassphrase"       && n > 1) ConvertTo<boost::int64_t>(params[1]);
1212     if (strMethod == "walletpassphrase"       && n > 2) ConvertTo<bool>(params[2]);
1213     if (strMethod == "getblocktemplate"       && n > 0) ConvertTo<Object>(params[0]);
1214     if (strMethod == "listsinceblock"         && n > 1) ConvertTo<boost::int64_t>(params[1]);
1215
1216     if (strMethod == "sendalert"              && n > 2) ConvertTo<boost::int64_t>(params[2]);
1217     if (strMethod == "sendalert"              && n > 3) ConvertTo<boost::int64_t>(params[3]);
1218     if (strMethod == "sendalert"              && n > 4) ConvertTo<boost::int64_t>(params[4]);
1219     if (strMethod == "sendalert"              && n > 5) ConvertTo<boost::int64_t>(params[5]);
1220     if (strMethod == "sendalert"              && n > 6) ConvertTo<boost::int64_t>(params[6]);
1221
1222     if (strMethod == "sendmany"               && n > 1) ConvertTo<Object>(params[1]);
1223     if (strMethod == "sendmany"               && n > 2) ConvertTo<boost::int64_t>(params[2]);
1224     if (strMethod == "reservebalance"         && n > 0) ConvertTo<bool>(params[0]);
1225     if (strMethod == "reservebalance"         && n > 1) ConvertTo<double>(params[1]);
1226     if (strMethod == "addmultisigaddress"     && n > 0) ConvertTo<boost::int64_t>(params[0]);
1227     if (strMethod == "addmultisigaddress"     && n > 1) ConvertTo<Array>(params[1]);
1228     if (strMethod == "listunspent"            && n > 0) ConvertTo<boost::int64_t>(params[0]);
1229     if (strMethod == "listunspent"            && n > 1) ConvertTo<boost::int64_t>(params[1]);
1230     if (strMethod == "listunspent"            && n > 2) ConvertTo<Array>(params[2]);
1231     if (strMethod == "getrawtransaction"      && n > 1) ConvertTo<boost::int64_t>(params[1]);
1232     if (strMethod == "createrawtransaction"   && n > 0) ConvertTo<Array>(params[0]);
1233     if (strMethod == "createrawtransaction"   && n > 1) ConvertTo<Object>(params[1]);
1234     if (strMethod == "createmultisig"         && n > 0) ConvertTo<boost::int64_t>(params[0]);
1235     if (strMethod == "createmultisig"         && n > 1) ConvertTo<Array>(params[1]);
1236     if (strMethod == "signrawtransaction"     && n > 1) ConvertTo<Array>(params[1], true);
1237     if (strMethod == "signrawtransaction"     && n > 2) ConvertTo<Array>(params[2], true);
1238     if (strMethod == "keypoolrefill"          && n > 0) ConvertTo<boost::int64_t>(params[0]);
1239     if (strMethod == "importaddress"          && n > 2) ConvertTo<bool>(params[2]);
1240
1241     return params;
1242 }
1243
1244 int CommandLineRPC(int argc, char *argv[])
1245 {
1246     string strPrint;
1247     int nRet = 0;
1248     try
1249     {
1250         // Skip switches
1251         while (argc > 1 && IsSwitchChar(argv[1][0]))
1252         {
1253             argc--;
1254             argv++;
1255         }
1256
1257         // Method
1258         if (argc < 2)
1259             throw runtime_error("too few parameters");
1260         string strMethod = argv[1];
1261
1262         // Parameters default to strings
1263         std::vector<std::string> strParams(&argv[2], &argv[argc]);
1264         Array params = RPCConvertValues(strMethod, strParams);
1265
1266         // Execute
1267         Object reply = CallRPC(strMethod, params);
1268
1269         // Parse reply
1270         const Value& result = find_value(reply, "result");
1271         const Value& error  = find_value(reply, "error");
1272
1273         if (error.type() != null_type)
1274         {
1275             // Error
1276             strPrint = "error: " + write_string(error, false);
1277             int code = find_value(error.get_obj(), "code").get_int();
1278             nRet = abs(code);
1279         }
1280         else
1281         {
1282             // Result
1283             if (result.type() == null_type)
1284                 strPrint = "";
1285             else if (result.type() == str_type)
1286                 strPrint = result.get_str();
1287             else
1288                 strPrint = write_string(result, true);
1289         }
1290     }
1291     catch (std::exception& e)
1292     {
1293         strPrint = string("error: ") + e.what();
1294         nRet = 87;
1295     }
1296     catch (...)
1297     {
1298         PrintException(NULL, "CommandLineRPC()");
1299     }
1300
1301     if (strPrint != "")
1302     {
1303         fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
1304     }
1305     return nRet;
1306 }
1307
1308
1309
1310
1311 #ifdef TEST
1312 int main(int argc, char *argv[])
1313 {
1314 #ifdef _MSC_VER
1315     // Turn off Microsoft heap dump noise
1316     _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
1317     _CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
1318 #endif
1319     setbuf(stdin, NULL);
1320     setbuf(stdout, NULL);
1321     setbuf(stderr, NULL);
1322
1323     try
1324     {
1325         if (argc >= 2 && string(argv[1]) == "-server")
1326         {
1327             printf("server ready\n");
1328             ThreadRPCServer(NULL);
1329         }
1330         else
1331         {
1332             return CommandLineRPC(argc, argv);
1333         }
1334     }
1335     catch (std::exception& e) {
1336         PrintException(&e, "main()");
1337     } catch (...) {
1338         PrintException(NULL, "main()");
1339     }
1340     return 0;
1341 }
1342 #endif
1343
1344 const CRPCTable tableRPC;