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