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