Anoncoin  0.9.4
P2P Digital Currency
rpcserver.cpp
Go to the documentation of this file.
1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin developers
3 // Copyright (c) 2013-2014 The Anoncoin Core developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 
7 // Many builder specific things set in the config file, ENABLE_WALLET is a good example. Don't forget to include it this way in your source files.
8 #if defined(HAVE_CONFIG_H)
10 #endif
11 
12 #include "rpcserver.h"
13 
14 #include "base58.h"
15 #include "init.h"
16 #include "main.h"
17 #include "ui_interface.h"
18 #include "util.h"
19 #ifdef ENABLE_WALLET
20 #include "wallet.h"
21 #endif
22 
23 #include <boost/algorithm/string.hpp>
24 #include <boost/asio.hpp>
25 #include <boost/asio/ssl.hpp>
26 #include <boost/bind.hpp>
27 #include <boost/filesystem.hpp>
28 #include <boost/foreach.hpp>
29 #include <boost/iostreams/concepts.hpp>
30 #include <boost/iostreams/stream.hpp>
31 #include <boost/shared_ptr.hpp>
32 #include "json/json_spirit_writer_template.h"
33 
34 using namespace std;
35 using namespace boost;
36 using namespace boost::asio;
37 using namespace json_spirit;
38 
39 static std::string strRPCUserColonPass;
40 
41 // These are created by StartRPCThreads, destroyed in StopRPCThreads
42 static asio::io_service* rpc_io_service = NULL;
43 static map<string, boost::shared_ptr<deadline_timer> > deadlineTimers;
44 static ssl::context* rpc_ssl_context = NULL;
45 static boost::thread_group* rpc_worker_group = NULL;
46 static boost::asio::io_service::work *rpc_dummy_work = NULL;
47 static std::vector< boost::shared_ptr<ip::tcp::acceptor> > rpc_acceptors;
48 
49 void RPCTypeCheck(const Array& params,
50  const list<Value_type>& typesExpected,
51  bool fAllowNull)
52 {
53  unsigned int i = 0;
54  BOOST_FOREACH(Value_type t, typesExpected)
55  {
56  if (params.size() <= i)
57  break;
58 
59  const Value& v = params[i];
60  if (!((v.type() == t) || (fAllowNull && (v.type() == null_type))))
61  {
62  string err = strprintf("Expected type %s, got %s",
63  Value_type_name[t], Value_type_name[v.type()]);
64  throw JSONRPCError(RPC_TYPE_ERROR, err);
65  }
66  i++;
67  }
68 }
69 
70 void RPCTypeCheck(const Object& o,
71  const map<string, Value_type>& typesExpected,
72  bool fAllowNull)
73 {
74  BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected)
75  {
76  const Value& v = find_value(o, t.first);
77  if (!fAllowNull && v.type() == null_type)
78  throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first));
79 
80  if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type))))
81  {
82  string err = strprintf("Expected type %s for %s, got %s",
83  Value_type_name[t.second], t.first, Value_type_name[v.type()]);
84  throw JSONRPCError(RPC_TYPE_ERROR, err);
85  }
86  }
87 }
88 
89 int64_t AmountFromValue(const Value& value)
90 {
91  double dAmount = value.get_real();
92  if (dAmount <= 0.0 || dAmount > 84000000.0)
93  throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
94  int64_t nAmount = roundint64(dAmount * COIN);
95  if (!MoneyRange(nAmount))
96  throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
97  return nAmount;
98 }
99 
100 Value ValueFromAmount(int64_t amount)
101 {
102  return (double)amount / (double)COIN;
103 }
104 
105 std::string HexBits(unsigned int nBits)
106 {
107  union {
108  int32_t nBits;
109  char cBits[4];
110  } uBits;
111  uBits.nBits = htonl((int32_t)nBits);
112  return HexStr(BEGIN(uBits.cBits), END(uBits.cBits));
113 }
114 
115 uint256 ParseHashV(const Value& v, string strName)
116 {
117  string strHex;
118  if (v.type() == str_type)
119  strHex = v.get_str();
120  if (!IsHex(strHex)) // Note: IsHex("") is false
121  throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
122  uint256 result;
123  result.SetHex(strHex);
124  return result;
125 }
126 uint256 ParseHashO(const Object& o, string strKey)
127 {
128  return ParseHashV(find_value(o, strKey), strKey);
129 }
130 vector<unsigned char> ParseHexV(const Value& v, string strName)
131 {
132  string strHex;
133  if (v.type() == str_type)
134  strHex = v.get_str();
135  if (!IsHex(strHex))
136  throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
137  return ParseHex(strHex);
138 }
139 vector<unsigned char> ParseHexO(const Object& o, string strKey)
140 {
141  return ParseHexV(find_value(o, strKey), strKey);
142 }
143 
144 
148 
149 string CRPCTable::help(string strCommand) const
150 {
151  string strRet;
152  set<rpcfn_type> setDone;
153  for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)
154  {
155  const CRPCCommand *pcmd = mi->second;
156  string strMethod = mi->first;
157  // We already filter duplicates, but these deprecated screw up the sort order
158  if (strMethod.find("label") != string::npos)
159  continue;
160  if (strCommand != "" && strMethod != strCommand)
161  continue;
162 #ifdef ENABLE_WALLET
163  if (pcmd->reqWallet && !pwalletMain)
164  continue;
165 #endif
166 
167  try
168  {
169  Array params;
170  rpcfn_type pfn = pcmd->actor;
171  if (setDone.insert(pfn).second)
172  (*pfn)(params, true);
173  }
174  catch (std::exception& e)
175  {
176  // Help text is returned in an exception
177  string strHelp = string(e.what());
178  if (strCommand == "")
179  if (strHelp.find('\n') != string::npos)
180  strHelp = strHelp.substr(0, strHelp.find('\n'));
181  strRet += strHelp + "\n";
182  }
183  }
184  if (strRet == "")
185  strRet = strprintf("help: unknown command: %s\n", strCommand);
186  strRet = strRet.substr(0,strRet.size()-1);
187  return strRet;
188 }
189 
190 Value help(const Array& params, bool fHelp)
191 {
192  if (fHelp || params.size() > 1)
193  throw runtime_error(
194  "help ( \"command\" )\n"
195  "\nList all commands, or get help for a specified command.\n"
196  "\nArguments:\n"
197  "1. \"command\" (string, optional) The command to get help on\n"
198  "\nResult:\n"
199  "\"text\" (string) The help text\n"
200  );
201 
202  string strCommand;
203  if (params.size() > 0)
204  strCommand = params[0].get_str();
205 
206  return tableRPC.help(strCommand);
207 }
208 
209 
210 Value stop(const Array& params, bool fHelp)
211 {
212  // Accept the deprecated and ignored 'detach' boolean argument
213  if (fHelp || params.size() > 1)
214  throw runtime_error(
215  "stop\n"
216  "\nStop Anoncoin server.");
217  // Shutdown will take long enough that the response should get back
218  StartShutdown();
219  return "Anoncoin server stopping";
220 }
221 
222 
223 
224 //
225 // Call Table
226 //
227 
228 
229 static const CRPCCommand vRPCCommands[] =
230 { // name actor (function) okSafeMode threadSafe reqWallet
231  // ------------------------ ----------------------- ---------- ---------- ---------
232  /* Overall control/query calls */
233  { "getinfo", &getinfo, true, false, false }, /* uses wallet if enabled */
234  { "help", &help, true, true, false },
235  { "stop", &stop, true, true, false },
236 
237  /* P2P networking */
238  { "getnetworkinfo", &getnetworkinfo, true, false, false },
239  { "addnode", &addnode, true, true, false },
240  { "getaddednodeinfo", &getaddednodeinfo, true, true, false },
241  { "getconnectioncount", &getconnectioncount, true, false, false },
242  { "getnettotals", &getnettotals, true, true, false },
243  { "getpeerinfo", &getpeerinfo, true, false, false },
244  { "ping", &ping, true, false, false },
245 
246  /* Block chain and UTXO */
247  { "getblockchaininfo", &getblockchaininfo, true, false, false },
248  { "getbestblockhash", &getbestblockhash, true, false, false },
249  { "getblockcount", &getblockcount, true, false, false },
250  { "getblock", &getblock, false, false, false },
251  { "getblockhash", &getblockhash, false, false, false },
252  { "getdifficulty", &getdifficulty, true, false, false },
253  { "getrawmempool", &getrawmempool, true, false, false },
254  { "gettxout", &gettxout, true, false, false },
255  { "gettxoutsetinfo", &gettxoutsetinfo, true, false, false },
256  { "verifychain", &verifychain, true, false, false },
257 
258  /* Mining */
259  { "getblocktemplate", &getblocktemplate, true, false, false },
260  { "getmininginfo", &getmininginfo, true, false, false },
261  { "getnetworkhashps", &getnetworkhashps, true, false, false },
262  { "submitblock", &submitblock, false, false, false },
263 
264  /* Raw transactions */
265  { "createrawtransaction", &createrawtransaction, false, false, false },
266  { "decoderawtransaction", &decoderawtransaction, false, false, false },
267  { "decodescript", &decodescript, false, false, false },
268  { "getrawtransaction", &getrawtransaction, false, false, false },
269  { "sendrawtransaction", &sendrawtransaction, false, false, false },
270  { "signrawtransaction", &signrawtransaction, false, false, false }, /* uses wallet if enabled */
271 
272  /* Utility functions */
273  { "createmultisig", &createmultisig, true, true , false },
274  { "validateaddress", &validateaddress, true, false, false }, /* uses wallet if enabled */
275  { "verifymessage", &verifymessage, false, false, false },
276 
277 #ifdef ENABLE_WALLET
278  /* Wallet */
279  { "addmultisigaddress", &addmultisigaddress, false, false, true },
280  { "backupwallet", &backupwallet, true, false, true },
281  { "dumpprivkey", &dumpprivkey, true, false, true },
282  { "dumpwallet", &dumpwallet, true, false, true },
283  { "encryptwallet", &encryptwallet, false, false, true },
284  { "getaccountaddress", &getaccountaddress, true, false, true },
285  { "getaccount", &getaccount, false, false, true },
286  { "getaddressesbyaccount", &getaddressesbyaccount, true, false, true },
287  { "getbalance", &getbalance, false, false, true },
288  { "getnewaddress", &getnewaddress, true, false, true },
289  { "getrawchangeaddress", &getrawchangeaddress, true, false, true },
290  { "getreceivedbyaccount", &getreceivedbyaccount, false, false, true },
291  { "getreceivedbyaddress", &getreceivedbyaddress, false, false, true },
292  { "gettransaction", &gettransaction, false, false, true },
293  { "getunconfirmedbalance", &getunconfirmedbalance, false, false, true },
294  { "getwalletinfo", &getwalletinfo, true, false, true },
295  { "importprivkey", &importprivkey, false, false, true },
296  { "importwallet", &importwallet, false, false, true },
297  { "importaddress", &importaddress, false, false, true },
298  { "keypoolrefill", &keypoolrefill, true, false, true },
299  { "listaccounts", &listaccounts, false, false, true },
300  { "listaddressgroupings", &listaddressgroupings, false, false, true },
301  { "listlockunspent", &listlockunspent, false, false, true },
302  { "listreceivedbyaccount", &listreceivedbyaccount, false, false, true },
303  { "listreceivedbyaddress", &listreceivedbyaddress, false, false, true },
304  { "listsinceblock", &listsinceblock, false, false, true },
305  { "listtransactions", &listtransactions, false, false, true },
306  { "makekeypair", &makekeypair, true, false, true },
307  { "dumpprivkey", &dumpprivkey, true, false, true },
308  { "listunspent", &listunspent, false, false, true },
309  { "lockunspent", &lockunspent, false, false, true },
310  { "move", &movecmd, false, false, true },
311  { "sendfrom", &sendfrom, false, false, true },
312  { "sendmany", &sendmany, false, false, true },
313  { "sendtoaddress", &sendtoaddress, false, false, true },
314  { "setaccount", &setaccount, true, false, true },
315  { "settxfee", &settxfee, false, false, true },
316  { "signmessage", &signmessage, false, false, true },
317  { "walletlock", &walletlock, true, false, true },
318  { "walletpassphrasechange", &walletpassphrasechange, false, false, true },
319  { "walletpassphrase", &walletpassphrase, true, false, true },
320 
321  /* Wallet-enabled mining */
322  { "getgenerate", &getgenerate, true, false, false },
323  { "gethashespersec", &gethashespersec, true, false, false },
324  { "getwork", &getwork, true, false, true },
325  { "setgenerate", &setgenerate, true, true, false },
326 #endif // ENABLE_WALLET
327 };
328 
330 {
331  unsigned int vcidx;
332  for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++)
333  {
334  const CRPCCommand *pcmd;
335 
336  pcmd = &vRPCCommands[vcidx];
337  mapCommands[pcmd->name] = pcmd;
338  }
339 }
340 
341 const CRPCCommand *CRPCTable::operator[](string name) const
342 {
343  map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
344  if (it == mapCommands.end())
345  return NULL;
346  return (*it).second;
347 }
348 
349 
350 bool HTTPAuthorized(map<string, string>& mapHeaders)
351 {
352  string strAuth = mapHeaders["authorization"];
353  if (strAuth.substr(0,6) != "Basic ")
354  return false;
355  string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
356  string strUserPass = DecodeBase64(strUserPass64);
357  return TimingResistantEqual(strUserPass, strRPCUserColonPass);
358 }
359 
360 void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
361 {
362  // Send error reply from json-rpc error object
363  int nStatus = HTTP_INTERNAL_SERVER_ERROR;
364  int code = find_value(objError, "code").get_int();
365  if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST;
366  else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND;
367  string strReply = JSONRPCReply(Value::null, objError, id);
368  stream << HTTPReply(nStatus, strReply, false) << std::flush;
369 }
370 
371 bool ClientAllowed(const boost::asio::ip::address& address)
372 {
373  // Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses
374  if (address.is_v6()
375  && (address.to_v6().is_v4_compatible()
376  || address.to_v6().is_v4_mapped()))
377  return ClientAllowed(address.to_v6().to_v4());
378 
379  if (address == asio::ip::address_v4::loopback()
380  || address == asio::ip::address_v6::loopback()
381  || (address.is_v4()
382  // Check whether IPv4 addresses match 127.0.0.0/8 (loopback subnet)
383  && (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000))
384  return true;
385 
386  const string strAddress = address.to_string();
387  const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
388  BOOST_FOREACH(string strAllow, vAllow)
389  if (WildcardMatch(strAddress, strAllow))
390  return true;
391  return false;
392 }
393 
395 {
396 public:
397  virtual ~AcceptedConnection() {}
398 
399  virtual std::iostream& stream() = 0;
400  virtual std::string peer_address_to_string() const = 0;
401  virtual void close() = 0;
402 };
403 
404 template <typename Protocol>
406 {
407 public:
409  asio::io_service& io_service,
410  ssl::context &context,
411  bool fUseSSL) :
412  sslStream(io_service, context),
413  _d(sslStream, fUseSSL),
414  _stream(_d)
415  {
416  }
417 
418  virtual std::iostream& stream()
419  {
420  return _stream;
421  }
422 
423  virtual std::string peer_address_to_string() const
424  {
425  return peer.address().to_string();
426  }
427 
428  virtual void close()
429  {
430  _stream.close();
431  }
432 
433  typename Protocol::endpoint peer;
434  asio::ssl::stream<typename Protocol::socket> sslStream;
435 
436 private:
438  iostreams::stream< SSLIOStreamDevice<Protocol> > _stream;
439 };
440 
442 
443 // Forward declaration required for RPCListen
444 template <typename Protocol, typename SocketAcceptorService>
445 static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
446  ssl::context& context,
447  bool fUseSSL,
448  boost::shared_ptr< AcceptedConnection > conn,
449  const boost::system::error_code& error);
450 
454 template <typename Protocol, typename SocketAcceptorService>
455 static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
456  ssl::context& context,
457  const bool fUseSSL)
458 {
459  // Accept connection
460  boost::shared_ptr< AcceptedConnectionImpl<Protocol> > conn(new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL));
461 
462  acceptor->async_accept(
463  conn->sslStream.lowest_layer(),
464  conn->peer,
465  boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>,
466  acceptor,
467  boost::ref(context),
468  fUseSSL,
469  conn,
470  _1));
471 }
472 
473 
477 template <typename Protocol, typename SocketAcceptorService>
478 static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
479  ssl::context& context,
480  const bool fUseSSL,
481  boost::shared_ptr< AcceptedConnection > conn,
482  const boost::system::error_code& error)
483 {
484  // Immediately start accepting new connections, except when we're cancelled or our socket is closed.
485  if (error != asio::error::operation_aborted && acceptor->is_open())
486  RPCListen(acceptor, context, fUseSSL);
487 
488  AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn.get());
489 
490  if (error)
491  {
492  // TODO: Actually handle errors
493  LogPrintf("%s: Error: %s\n", __func__, error.message());
494  }
495  // Restrict callers by IP. It is important to
496  // do this before starting client thread, to filter out
497  // certain DoS and misbehaving clients.
498  else if (tcp_conn && !ClientAllowed(tcp_conn->peer.address()))
499  {
500  // Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake.
501  if (!fUseSSL)
502  conn->stream() << HTTPReply(HTTP_FORBIDDEN, "", false) << std::flush;
503  conn->close();
504  }
505  else {
506  ServiceConnection(conn.get());
507  conn->close();
508  }
509 }
510 
512 {
513  strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
514  if (((mapArgs["-rpcpassword"] == "") ||
515  (mapArgs["-rpcuser"] == mapArgs["-rpcpassword"])) && Params().RequireRPCPassword())
516  {
517  unsigned char rand_pwd[32];
518  RAND_bytes(rand_pwd, 32);
519  string strWhatAmI = "To use anoncoind";
520  if (mapArgs.count("-server"))
521  strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
522  else if (mapArgs.count("-daemon"))
523  strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
525  _("%s, you must set a rpcpassword in the configuration file:\n"
526  "%s\n"
527  "It is recommended you use the following random password:\n"
528  "rpcuser=anoncoinrpc\n"
529  "rpcpassword=%s\n"
530  "(you do not need to remember this password)\n"
531  "The username and password MUST NOT be the same.\n"
532  "If the file does not exist, create it with owner-readable-only file permissions.\n"
533  "It is also recommended to set alertnotify so you are notified of problems;\n"
534  "for example: alertnotify=echo %%s | mail -s \"Anoncoin Alert\" admin@foo.com\n"),
535  strWhatAmI,
536  GetConfigFile().string(),
537  EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32)),
539  StartShutdown();
540  return;
541  }
542 
543  assert(rpc_io_service == NULL);
544  rpc_io_service = new asio::io_service();
545  rpc_ssl_context = new ssl::context(*rpc_io_service, ssl::context::sslv23);
546 
547  const bool fUseSSL = GetBoolArg("-rpcssl", false);
548 
549  if (fUseSSL)
550  {
551  rpc_ssl_context->set_options(ssl::context::no_sslv2);
552 
553  filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert"));
554  if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile;
555  if (filesystem::exists(pathCertFile)) rpc_ssl_context->use_certificate_chain_file(pathCertFile.string());
556  else LogPrintf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string());
557 
558  filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem"));
559  if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile;
560  if (filesystem::exists(pathPKFile)) rpc_ssl_context->use_private_key_file(pathPKFile.string(), ssl::context::pem);
561  else LogPrintf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string());
562 
563  string strCiphers = GetArg("-rpcsslciphers", "TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH");
564  SSL_CTX_set_cipher_list(rpc_ssl_context->impl(), strCiphers.c_str());
565  }
566 
567  // Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets
568  const bool loopback = !mapArgs.count("-rpcallowip");
569  asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any();
570  ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", Params().RPCPort()));
571  boost::system::error_code v6_only_error;
572 
573  bool fListening = false;
574  std::string strerr;
575  try
576  {
577  boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(*rpc_io_service));
578  acceptor->open(endpoint.protocol());
579  acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
580 
581  // Try making the socket dual IPv6/IPv4 (if listening on the "any" address)
582  acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error);
583 
584  acceptor->bind(endpoint);
585  acceptor->listen(socket_base::max_connections);
586 
587  RPCListen(acceptor, *rpc_ssl_context, fUseSSL);
588 
589  rpc_acceptors.push_back(acceptor);
590  fListening = true;
591  }
592  catch(boost::system::system_error &e)
593  {
594  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());
595  }
596  try {
597  // If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately
598  if (!fListening || loopback || v6_only_error)
599  {
600  bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any();
601  endpoint.address(bindAddress);
602 
603  boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(*rpc_io_service));
604  acceptor->open(endpoint.protocol());
605  acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
606  acceptor->bind(endpoint);
607  acceptor->listen(socket_base::max_connections);
608 
609  RPCListen(acceptor, *rpc_ssl_context, fUseSSL);
610 
611  rpc_acceptors.push_back(acceptor);
612  fListening = true;
613  }
614  }
615  catch(boost::system::system_error &e)
616  {
617  strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv4: %s"), endpoint.port(), e.what());
618  }
619 
620  if (!fListening) {
622  StartShutdown();
623  return;
624  }
625 
626  rpc_worker_group = new boost::thread_group();
627  for (int i = 0; i < GetArg("-rpcthreads", 4); i++)
628  rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service));
629 }
630 
632 {
633  if(rpc_io_service == NULL)
634  {
635  rpc_io_service = new asio::io_service();
636  /* Create dummy "work" to keep the thread from exiting when no timeouts active,
637  * see http://www.boost.org/doc/libs/1_51_0/doc/html/boost_asio/reference/io_service.html#boost_asio.reference.io_service.stopping_the_io_service_from_running_out_of_work */
638  rpc_dummy_work = new asio::io_service::work(*rpc_io_service);
639  rpc_worker_group = new boost::thread_group();
640  rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service));
641  }
642 }
643 
645 {
646  if (rpc_io_service == NULL) return;
647 
648  // First, cancel all timers and acceptors
649  // This is not done automatically by ->stop(), and in some cases the destructor of
650  // asio::io_service can hang if this is skipped.
651  boost::system::error_code ec;
652  BOOST_FOREACH(const boost::shared_ptr<ip::tcp::acceptor> &acceptor, rpc_acceptors)
653  {
654  acceptor->cancel(ec);
655  if (ec)
656  LogPrintf("%s: Warning: %s when cancelling acceptor", __func__, ec.message());
657  }
658  rpc_acceptors.clear();
659  BOOST_FOREACH(const PAIRTYPE(std::string, boost::shared_ptr<deadline_timer>) &timer, deadlineTimers)
660  {
661  timer.second->cancel(ec);
662  if (ec)
663  LogPrintf("%s: Warning: %s when cancelling timer", __func__, ec.message());
664  }
665  deadlineTimers.clear();
666 
667  rpc_io_service->stop();
668  if (rpc_worker_group != NULL)
669  rpc_worker_group->join_all();
670  delete rpc_dummy_work; rpc_dummy_work = NULL;
671  delete rpc_worker_group; rpc_worker_group = NULL;
672  delete rpc_ssl_context; rpc_ssl_context = NULL;
673  delete rpc_io_service; rpc_io_service = NULL;
674 }
675 
676 void RPCRunHandler(const boost::system::error_code& err, boost::function<void(void)> func)
677 {
678  if (!err)
679  func();
680 }
681 
682 void RPCRunLater(const std::string& name, boost::function<void(void)> func, int64_t nSeconds)
683 {
684  assert(rpc_io_service != NULL);
685 
686  if (deadlineTimers.count(name) == 0)
687  {
688  deadlineTimers.insert(make_pair(name,
689  boost::shared_ptr<deadline_timer>(new deadline_timer(*rpc_io_service))));
690  }
691  deadlineTimers[name]->expires_from_now(posix_time::seconds(nSeconds));
692  deadlineTimers[name]->async_wait(boost::bind(RPCRunHandler, _1, func));
693 }
694 
696 {
697 public:
698  Value id;
699  string strMethod;
700  Array params;
701 
702  JSONRequest() { id = Value::null; }
703  void parse(const Value& valRequest);
704 };
705 
706 void JSONRequest::parse(const Value& valRequest)
707 {
708  // Parse request
709  if (valRequest.type() != obj_type)
710  throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
711  const Object& request = valRequest.get_obj();
712 
713  // Parse id now so errors from here on will have the id
714  id = find_value(request, "id");
715 
716  // Parse method
717  Value valMethod = find_value(request, "method");
718  if (valMethod.type() == null_type)
719  throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
720  if (valMethod.type() != str_type)
721  throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
722  strMethod = valMethod.get_str();
723  if (strMethod != "getwork" && strMethod != "getblocktemplate")
724  LogPrint("rpc", "ThreadRPCServer method=%s\n", strMethod);
725 
726  // Parse params
727  Value valParams = find_value(request, "params");
728  if (valParams.type() == array_type)
729  params = valParams.get_array();
730  else if (valParams.type() == null_type)
731  params = Array();
732  else
733  throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array");
734 }
735 
736 
737 static Object JSONRPCExecOne(const Value& req)
738 {
739  Object rpc_result;
740 
741  JSONRequest jreq;
742  try {
743  jreq.parse(req);
744 
745  Value result = tableRPC.execute(jreq.strMethod, jreq.params);
746  rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id);
747  }
748  catch (Object& objError)
749  {
750  rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id);
751  }
752  catch (std::exception& e)
753  {
754  rpc_result = JSONRPCReplyObj(Value::null,
755  JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
756  }
757 
758  return rpc_result;
759 }
760 
761 static string JSONRPCExecBatch(const Array& vReq)
762 {
763  Array ret;
764  for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
765  ret.push_back(JSONRPCExecOne(vReq[reqIdx]));
766 
767  return write_string(Value(ret), false) + "\n";
768 }
769 
771 {
772  bool fRun = true;
773  while (fRun && !ShutdownRequested())
774  {
775  int nProto = 0;
776  map<string, string> mapHeaders;
777  string strRequest, strMethod, strURI;
778 
779  // Read HTTP request line
780  if (!ReadHTTPRequestLine(conn->stream(), nProto, strMethod, strURI))
781  break;
782 
783  // Read HTTP message headers and body
784  ReadHTTPMessage(conn->stream(), mapHeaders, strRequest, nProto);
785 
786  if (strURI != "/") {
787  conn->stream() << HTTPReply(HTTP_NOT_FOUND, "", false) << std::flush;
788  break;
789  }
790 
791  // Check authorization
792  if (mapHeaders.count("authorization") == 0)
793  {
794  conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
795  break;
796  }
797  if (!HTTPAuthorized(mapHeaders))
798  {
799  LogPrintf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string());
800  /* Deter brute-forcing short passwords.
801  If this results in a DoS the user really
802  shouldn't have their RPC port exposed. */
803  if (mapArgs["-rpcpassword"].size() < 20)
804  MilliSleep(250);
805 
806  conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
807  break;
808  }
809  if (mapHeaders["connection"] == "close")
810  fRun = false;
811 
812  JSONRequest jreq;
813  try
814  {
815  // Parse request
816  Value valRequest;
817  if (!read_string(strRequest, valRequest))
818  throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
819 
820  string strReply;
821 
822  // singleton request
823  if (valRequest.type() == obj_type) {
824  jreq.parse(valRequest);
825 
826  Value result = tableRPC.execute(jreq.strMethod, jreq.params);
827 
828  // Send reply
829  strReply = JSONRPCReply(result, Value::null, jreq.id);
830 
831  // array of requests
832  } else if (valRequest.type() == array_type)
833  strReply = JSONRPCExecBatch(valRequest.get_array());
834  else
835  throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
836 
837  conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush;
838  }
839  catch (Object& objError)
840  {
841  ErrorReply(conn->stream(), objError, jreq.id);
842  break;
843  }
844  catch (std::exception& e)
845  {
846  ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
847  break;
848  }
849  }
850 }
851 
852 json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array &params) const
853 {
854  // Find method
855  const CRPCCommand *pcmd = tableRPC[strMethod];
856  if (!pcmd)
857  throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
858 #ifdef ENABLE_WALLET
859  if (pcmd->reqWallet && !pwalletMain)
860  throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)");
861 #endif
862 
863  // Observe safe mode
864  string strWarning = GetWarnings("rpc");
865  if (strWarning != "" && !GetBoolArg("-disablesafemode", false) &&
866  !pcmd->okSafeMode)
867  throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
868 
869  try
870  {
871  // Execute
872  Value result;
873  {
874  if (pcmd->threadSafe)
875  result = pcmd->actor(params, false);
876 #ifdef ENABLE_WALLET
877  else if (!pwalletMain) {
878  LOCK(cs_main);
879  result = pcmd->actor(params, false);
880  } else {
882  result = pcmd->actor(params, false);
883  }
884 #else // ENABLE_WALLET
885  else {
886  LOCK(cs_main);
887  result = pcmd->actor(params, false);
888  }
889 #endif // !ENABLE_WALLET
890  }
891  return result;
892  }
893  catch (std::exception& e)
894  {
895  throw JSONRPCError(RPC_MISC_ERROR, e.what());
896  }
897 }
898 
899 std::string HelpExampleCli(string methodname, string args){
900  return "> anoncoin-cli " + methodname + " " + args + "\n";
901 }
902 
903 std::string HelpExampleRpc(string methodname, string args){
904  return "> curl --user myusername --data-binary '{\"jsonrpc\": \"1.0\", \"id\":\"curltest\", "
905  "\"method\": \"" + methodname + "\", \"params\": [" + args + "] }' -H 'content-type: text/plain;' http://127.0.0.1:9332/\n";
906 }
907 
const boost::filesystem::path & GetDataDir(bool fNetSpecific)
Definition: util.cpp:968
CClientUIInterface uiInterface
Definition: util.cpp:100
void SetHex(const char *psz)
Definition: uint256.h:306
json_spirit::Value setgenerate(const json_spirit::Array &params, bool fHelp)
bool HTTPAuthorized(map< string, string > &mapHeaders)
Definition: rpcserver.cpp:350
json_spirit::Value signmessage(const json_spirit::Array &params, bool fHelp)
Array params
Definition: rpcserver.cpp:700
Value createrawtransaction(const Array &params, bool fHelp)
void RPCRunLater(const std::string &name, boost::function< void(void)> func, int64_t nSeconds)
Definition: rpcserver.cpp:682
json_spirit::Value movecmd(const json_spirit::Array &params, bool fHelp)
Value stop(const Array &params, bool fHelp)
Definition: rpcserver.cpp:210
json_spirit::Value walletpassphrasechange(const json_spirit::Array &params, bool fHelp)
bool okSafeMode
Definition: rpcserver.h:61
SSLIOStreamDevice< Protocol > _d
Definition: rpcserver.cpp:437
virtual void close()
Definition: rpcserver.cpp:428
string JSONRPCReply(const Value &result, const Value &error, const Value &id)
Value help(const Array &params, bool fHelp)
Definition: rpcserver.cpp:190
Anoncoin RPC command dispatcher.
Definition: rpcserver.h:69
rpcfn_type actor
Definition: rpcserver.h:60
iostreams::stream< SSLIOStreamDevice< Protocol > > _stream
Definition: rpcserver.cpp:438
Value addnode(const Array &params, bool fHelp)
Definition: rpcnet.cpp:150
Definition: init.h:14
vector< unsigned char > ParseHexO(const Object &o, string strKey)
Definition: rpcserver.cpp:139
uint256 ParseHashO(const Object &o, string strKey)
Definition: rpcserver.cpp:126
bool threadSafe
Definition: rpcserver.h:62
asio::ssl::stream< typename Protocol::socket > sslStream
Definition: rpcserver.cpp:434
#define PAIRTYPE(t1, t2)
Definition: util.h:49
Value getblockcount(const Array &params, bool fHelp)
CCriticalSection cs_wallet
Main wallet lock.
Definition: wallet.h:133
void MilliSleep(int64_t n)
Definition: util.h:80
bool ShutdownRequested()
Definition: init.cpp:107
#define END(a)
Definition: util.h:43
bool ReadHTTPRequestLine(std::basic_istream< char > &stream, int &proto, string &http_method, string &http_uri)
#define strprintf
Definition: tinyformat.h:1011
Value getinfo(const Array &params, bool fHelp)
Definition: rpcmisc.cpp:35
std::string HelpExampleRpc(string methodname, string args)
Definition: rpcserver.cpp:903
Value sendrawtransaction(const Array &params, bool fHelp)
const CRPCCommand * operator[](std::string name) const
Definition: rpcserver.cpp:341
void StartShutdown()
Definition: init.cpp:103
Value importwallet(const Array &params, bool fHelp)
Definition: rpcdump.cpp:190
CCriticalSection cs_main
Definition: main.cpp:38
std::string EncodeBase58(const unsigned char *pbegin, const unsigned char *pend)
Encode a byte sequence as a base58-encoded string.
Definition: base58.cpp:67
string GetWarnings(string strFor)
Definition: main.cpp:3093
json_spirit::Value execute(const std::string &method, const json_spirit::Array &params) const
Execute a method.
Definition: rpcserver.cpp:852
Value gettxoutsetinfo(const Array &params, bool fHelp)
bool MoneyRange(int64_t nValue)
Definition: core.h:21
bool IsHex(const string &str)
Definition: util.cpp:409
void RPCRunHandler(const boost::system::error_code &err, boost::function< void(void)> func)
Definition: rpcserver.cpp:676
Value dumpwallet(const Array &params, bool fHelp)
Definition: rpcdump.cpp:321
virtual ~AcceptedConnection()
Definition: rpcserver.cpp:397
Object JSONRPCError(int code, const string &message)
Value getblockchaininfo(const Array &params, bool fHelp)
Value getblock(const Array &params, bool fHelp)
Value getnetworkinfo(const Array &params, bool fHelp)
Definition: rpcnet.cpp:362
void RPCTypeCheck(const Array &params, const list< Value_type > &typesExpected, bool fAllowNull)
Definition: rpcserver.cpp:49
virtual std::iostream & stream()
Definition: rpcserver.cpp:418
Value getdifficulty(const Array &params, bool fHelp)
void ErrorReply(std::ostream &stream, const Object &objError, const Value &id)
Definition: rpcserver.cpp:360
Value decodescript(const Array &params, bool fHelp)
Value importprivkey(const Array &params, bool fHelp)
Definition: rpcdump.cpp:68
AcceptedConnectionImpl(asio::io_service &io_service, ssl::context &context, bool fUseSSL)
Definition: rpcserver.cpp:408
void ServiceConnection(AcceptedConnection *conn)
Definition: rpcserver.cpp:770
bool reqWallet
Definition: rpcserver.h:63
virtual std::string peer_address_to_string() const
Definition: rpcserver.cpp:423
virtual std::string peer_address_to_string() const =0
json_spirit::Value listunspent(const json_spirit::Array &params, bool fHelp)
#define LOCK2(cs1, cs2)
Definition: sync.h:158
std::string name
Definition: rpcserver.h:59
Value decoderawtransaction(const Array &params, bool fHelp)
json_spirit::Value getunconfirmedbalance(const json_spirit::Array &params, bool fHelp)
std::string HexBits(unsigned int nBits)
Definition: rpcserver.cpp:105
bool GetBoolArg(const std::string &strArg, bool fDefault)
Return boolean argument or default value.
Definition: util.cpp:520
#define LogPrintf(...)
Definition: util.h:118
int ReadHTTPMessage(std::basic_istream< char > &stream, map< string, string > &mapHeadersRet, string &strMessageRet, int nProto)
Value ValueFromAmount(int64_t amount)
Definition: rpcserver.cpp:100
json_spirit::Value gethashespersec(const json_spirit::Array &params, bool fHelp)
json_spirit::Value listreceivedbyaddress(const json_spirit::Array &params, bool fHelp)
#define LOCK(cs)
Definition: sync.h:157
json_spirit::Value getnewaddress(const json_spirit::Array &params, bool fHelp)
json_spirit::Value walletlock(const json_spirit::Array &params, bool fHelp)
json_spirit::Value settxfee(const json_spirit::Array &params, bool fHelp)
Value getconnectioncount(const Array &params, bool fHelp)
Definition: rpcnet.cpp:25
Value getmininginfo(const Array &params, bool fHelp)
Definition: rpcmining.cpp:241
json_spirit::Value listaddressgroupings(const json_spirit::Array &params, bool fHelp)
Protocol::endpoint peer
Definition: rpcserver.cpp:433
json_spirit::Value sendmany(const json_spirit::Array &params, bool fHelp)
json_spirit::Value keypoolrefill(const json_spirit::Array &params, bool fHelp)
Value getrawmempool(const Array &params, bool fHelp)
Value makekeypair(const Array &params, bool fHelp)
Definition: rpcnet.cpp:420
std::string help(std::string name) const
Note: This interface may still be subject to change.
Definition: rpcserver.cpp:149
string HTTPReply(int nStatus, const string &strMsg, bool keepalive)
Definition: rpcprotocol.cpp:60
const CRPCTable tableRPC
Definition: rpcserver.cpp:908
Value submitblock(const Array &params, bool fHelp)
Definition: rpcmining.cpp:597
Value getnettotals(const Array &params, bool fHelp)
Definition: rpcnet.cpp:317
json_spirit::Value getgenerate(const json_spirit::Array &params, bool fHelp)
void StopRPCThreads()
Definition: rpcserver.cpp:644
Value getpeerinfo(const Array &params, bool fHelp)
Definition: rpcnet.cpp:77
Value createmultisig(const Array &params, bool fHelp)
Definition: rpcmisc.cpp:255
#define BEGIN(a)
Definition: util.h:42
256-bit unsigned integer
Definition: uint256.h:532
Object JSONRPCReplyObj(const Value &result, const Value &error, const Value &id)
json_spirit::Value listaccounts(const json_spirit::Array &params, bool fHelp)
json_spirit::Value getwalletinfo(const json_spirit::Array &params, bool fHelp)
json_spirit::Value listsinceblock(const json_spirit::Array &params, bool fHelp)
json_spirit::Value encryptwallet(const json_spirit::Array &params, bool fHelp)
const CChainParams & Params()
Return the currently selected parameters.
bool ClientAllowed(const boost::asio::ip::address &address)
Definition: rpcserver.cpp:371
Timer timer
Definition: Benchmark.cpp:81
string strMethod
Definition: rpcserver.cpp:699
vector< unsigned char > ParseHexV(const Value &v, string strName)
Definition: rpcserver.cpp:130
bool WildcardMatch(const char *psz, const char *mask)
Definition: util.cpp:876
std::string _(const char *psz)
Translation function: Call Translate signal on UI interface, which returns a boost::optional result...
Definition: ui_interface.h:125
Value signrawtransaction(const Array &params, bool fHelp)
virtual std::iostream & stream()=0
void parse(const Value &valRequest)
Definition: rpcserver.cpp:706
json_spirit::Value sendfrom(const json_spirit::Array &params, bool fHelp)
int64_t AmountFromValue(const Value &value)
Definition: rpcserver.cpp:89
bool TimingResistantEqual(const T &a, const T &b)
Timing-attack-resistant comparison.
Definition: util.h:407
Value getaddednodeinfo(const Array &params, bool fHelp)
Definition: rpcnet.cpp:200
json_spirit::Value gettransaction(const json_spirit::Array &params, bool fHelp)
Value getrawtransaction(const Array &params, bool fHelp)
boost::signals2::signal< bool(const std::string &message, const std::string &caption, unsigned int style), boost::signals2::last_value< bool > > ThreadSafeMessageBox
Show message box.
Definition: ui_interface.h:81
Value verifymessage(const Array &params, bool fHelp)
Definition: rpcmisc.cpp:298
Value getbestblockhash(const Array &params, bool fHelp)
json_spirit::Value getreceivedbyaccount(const json_spirit::Array &params, bool fHelp)
json_spirit::Value listtransactions(const json_spirit::Array &params, bool fHelp)
uint256 ParseHashV(const Value &v, string strName)
Definition: rpcserver.cpp:115
std::string HelpExampleCli(string methodname, string args)
Definition: rpcserver.cpp:899
Value getnetworkhashps(const Array &params, bool fHelp)
Definition: rpcmining.cpp:100
std::string GetArg(const std::string &strArg, const std::string &strDefault)
Return string argument or default value.
Definition: util.cpp:506
Value getblockhash(const Array &params, bool fHelp)
json_spirit::Value walletpassphrase(const json_spirit::Array &params, bool fHelp)
int64_t roundint64(double d)
Definition: util.h:245
json_spirit::Value lockunspent(const json_spirit::Array &params, bool fHelp)
Value getblocktemplate(const Array &params, bool fHelp)
Definition: rpcmining.cpp:409
json_spirit::Value sendtoaddress(const json_spirit::Array &params, bool fHelp)
Value gettxout(const Array &params, bool fHelp)
vector< unsigned char > DecodeBase64(const char *p, bool *pfInvalid)
Definition: util.cpp:599
json_spirit::Value listreceivedbyaccount(const json_spirit::Array &params, bool fHelp)
Value ping(const Array &params, bool fHelp)
Definition: rpcnet.cpp:42
std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
Definition: util.h:256
json_spirit::Value getreceivedbyaddress(const json_spirit::Array &params, bool fHelp)
json_spirit::Value backupwallet(const json_spirit::Array &params, bool fHelp)
map< string, vector< string > > mapMultiArgs
Definition: util.cpp:90
json_spirit::Value getwork(const json_spirit::Array &params, bool fHelp)
json_spirit::Value addmultisigaddress(const json_spirit::Array &params, bool fHelp)
Value verifychain(const Array &params, bool fHelp)
json_spirit::Value getrawchangeaddress(const json_spirit::Array &params, bool fHelp)
vector< unsigned char > ParseHex(const char *psz)
Definition: util.cpp:419
Value validateaddress(const Array &params, bool fHelp)
Definition: rpcmisc.cpp:144
json_spirit::Value listlockunspent(const json_spirit::Array &params, bool fHelp)
json_spirit::Value getaccount(const json_spirit::Array &params, bool fHelp)
json_spirit::Value(* rpcfn_type)(const json_spirit::Array &params, bool fHelp)
Definition: rpcserver.h:54
json_spirit::Value getbalance(const json_spirit::Array &params, bool fHelp)
json_spirit::Value setaccount(const json_spirit::Array &params, bool fHelp)
Value importaddress(const Array &params, bool fHelp)
Definition: rpcdump.cpp:135
CWallet * pwalletMain
map< string, string > mapArgs
Definition: util.cpp:89
void StartRPCThreads()
Definition: rpcserver.cpp:511
boost::filesystem::path GetConfigFile()
Definition: util.cpp:1007
Value dumpprivkey(const Array &params, bool fHelp)
Definition: rpcdump.cpp:288
json_spirit::Value getaddressesbyaccount(const json_spirit::Array &params, bool fHelp)
void StartDummyRPCThread()
Definition: rpcserver.cpp:631
json_spirit::Value getaccountaddress(const json_spirit::Array &params, bool fHelp)