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