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