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