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