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