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