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