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