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