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