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