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