Merge #11683: tests: Remove unused mininode functions {ser,deser}_int_vector(......
[bitcoinplatinum.git] / src / rpc / server.cpp
blobfa813982721c8d2811a9438628acb216b209de42
1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #include <rpc/server.h>
8 #include <base58.h>
9 #include <fs.h>
10 #include <init.h>
11 #include <random.h>
12 #include <sync.h>
13 #include <ui_interface.h>
14 #include <util.h>
15 #include <utilstrencodings.h>
17 #include <univalue.h>
19 #include <boost/bind.hpp>
20 #include <boost/signals2/signal.hpp>
21 #include <boost/algorithm/string/case_conv.hpp> // for to_upper()
22 #include <boost/algorithm/string/classification.hpp>
23 #include <boost/algorithm/string/split.hpp>
25 #include <memory> // for unique_ptr
26 #include <unordered_map>
28 static bool fRPCRunning = false;
29 static bool fRPCInWarmup = true;
30 static std::string rpcWarmupStatus("RPC server started");
31 static CCriticalSection cs_rpcWarmup;
32 /* Timer-creating functions */
33 static RPCTimerInterface* timerInterface = nullptr;
34 /* Map of name to timer. */
35 static std::map<std::string, std::unique_ptr<RPCTimerBase> > deadlineTimers;
37 static struct CRPCSignals
39 boost::signals2::signal<void ()> Started;
40 boost::signals2::signal<void ()> Stopped;
41 boost::signals2::signal<void (const CRPCCommand&)> PreCommand;
42 } g_rpcSignals;
44 void RPCServer::OnStarted(std::function<void ()> slot)
46 g_rpcSignals.Started.connect(slot);
49 void RPCServer::OnStopped(std::function<void ()> slot)
51 g_rpcSignals.Stopped.connect(slot);
54 void RPCTypeCheck(const UniValue& params,
55 const std::list<UniValue::VType>& typesExpected,
56 bool fAllowNull)
58 unsigned int i = 0;
59 for (UniValue::VType t : typesExpected)
61 if (params.size() <= i)
62 break;
64 const UniValue& v = params[i];
65 if (!(fAllowNull && v.isNull())) {
66 RPCTypeCheckArgument(v, t);
68 i++;
72 void RPCTypeCheckArgument(const UniValue& value, UniValue::VType typeExpected)
74 if (value.type() != typeExpected) {
75 throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Expected type %s, got %s", uvTypeName(typeExpected), uvTypeName(value.type())));
79 void RPCTypeCheckObj(const UniValue& o,
80 const std::map<std::string, UniValueType>& typesExpected,
81 bool fAllowNull,
82 bool fStrict)
84 for (const auto& t : typesExpected) {
85 const UniValue& v = find_value(o, t.first);
86 if (!fAllowNull && v.isNull())
87 throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first));
89 if (!(t.second.typeAny || v.type() == t.second.type || (fAllowNull && v.isNull()))) {
90 std::string err = strprintf("Expected type %s for %s, got %s",
91 uvTypeName(t.second.type), t.first, uvTypeName(v.type()));
92 throw JSONRPCError(RPC_TYPE_ERROR, err);
96 if (fStrict)
98 for (const std::string& k : o.getKeys())
100 if (typesExpected.count(k) == 0)
102 std::string err = strprintf("Unexpected key %s", k);
103 throw JSONRPCError(RPC_TYPE_ERROR, err);
109 CAmount AmountFromValue(const UniValue& value)
111 if (!value.isNum() && !value.isStr())
112 throw JSONRPCError(RPC_TYPE_ERROR, "Amount is not a number or string");
113 CAmount amount;
114 if (!ParseFixedPoint(value.getValStr(), 8, &amount))
115 throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
116 if (!MoneyRange(amount))
117 throw JSONRPCError(RPC_TYPE_ERROR, "Amount out of range");
118 return amount;
121 uint256 ParseHashV(const UniValue& v, std::string strName)
123 std::string strHex;
124 if (v.isStr())
125 strHex = v.get_str();
126 if (!IsHex(strHex)) // Note: IsHex("") is false
127 throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
128 if (64 != strHex.length())
129 throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("%s must be of length %d (not %d)", strName, 64, strHex.length()));
130 uint256 result;
131 result.SetHex(strHex);
132 return result;
134 uint256 ParseHashO(const UniValue& o, std::string strKey)
136 return ParseHashV(find_value(o, strKey), strKey);
138 std::vector<unsigned char> ParseHexV(const UniValue& v, std::string strName)
140 std::string strHex;
141 if (v.isStr())
142 strHex = v.get_str();
143 if (!IsHex(strHex))
144 throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
145 return ParseHex(strHex);
147 std::vector<unsigned char> ParseHexO(const UniValue& o, std::string strKey)
149 return ParseHexV(find_value(o, strKey), strKey);
153 * Note: This interface may still be subject to change.
156 std::string CRPCTable::help(const std::string& strCommand, const JSONRPCRequest& helpreq) const
158 std::string strRet;
159 std::string category;
160 std::set<rpcfn_type> setDone;
161 std::vector<std::pair<std::string, const CRPCCommand*> > vCommands;
163 for (std::map<std::string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)
164 vCommands.push_back(make_pair(mi->second->category + mi->first, mi->second));
165 sort(vCommands.begin(), vCommands.end());
167 JSONRPCRequest jreq(helpreq);
168 jreq.fHelp = true;
169 jreq.params = UniValue();
171 for (const std::pair<std::string, const CRPCCommand*>& command : vCommands)
173 const CRPCCommand *pcmd = command.second;
174 std::string strMethod = pcmd->name;
175 if ((strCommand != "" || pcmd->category == "hidden") && strMethod != strCommand)
176 continue;
177 jreq.strMethod = strMethod;
180 rpcfn_type pfn = pcmd->actor;
181 if (setDone.insert(pfn).second)
182 (*pfn)(jreq);
184 catch (const std::exception& e)
186 // Help text is returned in an exception
187 std::string strHelp = std::string(e.what());
188 if (strCommand == "")
190 if (strHelp.find('\n') != std::string::npos)
191 strHelp = strHelp.substr(0, strHelp.find('\n'));
193 if (category != pcmd->category)
195 if (!category.empty())
196 strRet += "\n";
197 category = pcmd->category;
198 std::string firstLetter = category.substr(0,1);
199 boost::to_upper(firstLetter);
200 strRet += "== " + firstLetter + category.substr(1) + " ==\n";
203 strRet += strHelp + "\n";
206 if (strRet == "")
207 strRet = strprintf("help: unknown command: %s\n", strCommand);
208 strRet = strRet.substr(0,strRet.size()-1);
209 return strRet;
212 UniValue help(const JSONRPCRequest& jsonRequest)
214 if (jsonRequest.fHelp || jsonRequest.params.size() > 1)
215 throw std::runtime_error(
216 "help ( \"command\" )\n"
217 "\nList all commands, or get help for a specified command.\n"
218 "\nArguments:\n"
219 "1. \"command\" (string, optional) The command to get help on\n"
220 "\nResult:\n"
221 "\"text\" (string) The help text\n"
224 std::string strCommand;
225 if (jsonRequest.params.size() > 0)
226 strCommand = jsonRequest.params[0].get_str();
228 return tableRPC.help(strCommand, jsonRequest);
232 UniValue stop(const JSONRPCRequest& jsonRequest)
234 // Accept the deprecated and ignored 'detach' boolean argument
235 if (jsonRequest.fHelp || jsonRequest.params.size() > 1)
236 throw std::runtime_error(
237 "stop\n"
238 "\nStop Bitcoin server.");
239 // Event loop will exit after current HTTP requests have been handled, so
240 // this reply will get back to the client.
241 StartShutdown();
242 return "Bitcoin server stopping";
245 UniValue uptime(const JSONRPCRequest& jsonRequest)
247 if (jsonRequest.fHelp || jsonRequest.params.size() > 1)
248 throw std::runtime_error(
249 "uptime\n"
250 "\nReturns the total uptime of the server.\n"
251 "\nResult:\n"
252 "ttt (numeric) The number of seconds that the server has been running\n"
253 "\nExamples:\n"
254 + HelpExampleCli("uptime", "")
255 + HelpExampleRpc("uptime", "")
258 return GetTime() - GetStartupTime();
262 * Call Table
264 static const CRPCCommand vRPCCommands[] =
265 { // category name actor (function) argNames
266 // --------------------- ------------------------ ----------------------- ----------
267 /* Overall control/query calls */
268 { "control", "help", &help, {"command"} },
269 { "control", "stop", &stop, {} },
270 { "control", "uptime", &uptime, {} },
273 CRPCTable::CRPCTable()
275 unsigned int vcidx;
276 for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++)
278 const CRPCCommand *pcmd;
280 pcmd = &vRPCCommands[vcidx];
281 mapCommands[pcmd->name] = pcmd;
285 const CRPCCommand *CRPCTable::operator[](const std::string &name) const
287 std::map<std::string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
288 if (it == mapCommands.end())
289 return nullptr;
290 return (*it).second;
293 bool CRPCTable::appendCommand(const std::string& name, const CRPCCommand* pcmd)
295 if (IsRPCRunning())
296 return false;
298 // don't allow overwriting for now
299 std::map<std::string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
300 if (it != mapCommands.end())
301 return false;
303 mapCommands[name] = pcmd;
304 return true;
307 bool StartRPC()
309 LogPrint(BCLog::RPC, "Starting RPC\n");
310 fRPCRunning = true;
311 g_rpcSignals.Started();
312 return true;
315 void InterruptRPC()
317 LogPrint(BCLog::RPC, "Interrupting RPC\n");
318 // Interrupt e.g. running longpolls
319 fRPCRunning = false;
322 void StopRPC()
324 LogPrint(BCLog::RPC, "Stopping RPC\n");
325 deadlineTimers.clear();
326 DeleteAuthCookie();
327 g_rpcSignals.Stopped();
330 bool IsRPCRunning()
332 return fRPCRunning;
335 void SetRPCWarmupStatus(const std::string& newStatus)
337 LOCK(cs_rpcWarmup);
338 rpcWarmupStatus = newStatus;
341 void SetRPCWarmupFinished()
343 LOCK(cs_rpcWarmup);
344 assert(fRPCInWarmup);
345 fRPCInWarmup = false;
348 bool RPCIsInWarmup(std::string *outStatus)
350 LOCK(cs_rpcWarmup);
351 if (outStatus)
352 *outStatus = rpcWarmupStatus;
353 return fRPCInWarmup;
356 void JSONRPCRequest::parse(const UniValue& valRequest)
358 // Parse request
359 if (!valRequest.isObject())
360 throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
361 const UniValue& request = valRequest.get_obj();
363 // Parse id now so errors from here on will have the id
364 id = find_value(request, "id");
366 // Parse method
367 UniValue valMethod = find_value(request, "method");
368 if (valMethod.isNull())
369 throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
370 if (!valMethod.isStr())
371 throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
372 strMethod = valMethod.get_str();
373 LogPrint(BCLog::RPC, "ThreadRPCServer method=%s\n", SanitizeString(strMethod));
375 // Parse params
376 UniValue valParams = find_value(request, "params");
377 if (valParams.isArray() || valParams.isObject())
378 params = valParams;
379 else if (valParams.isNull())
380 params = UniValue(UniValue::VARR);
381 else
382 throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array or object");
385 bool IsDeprecatedRPCEnabled(const std::string& method)
387 const std::vector<std::string> enabled_methods = gArgs.GetArgs("-deprecatedrpc");
389 return find(enabled_methods.begin(), enabled_methods.end(), method) != enabled_methods.end();
392 static UniValue JSONRPCExecOne(JSONRPCRequest jreq, const UniValue& req)
394 UniValue rpc_result(UniValue::VOBJ);
396 try {
397 jreq.parse(req);
399 UniValue result = tableRPC.execute(jreq);
400 rpc_result = JSONRPCReplyObj(result, NullUniValue, jreq.id);
402 catch (const UniValue& objError)
404 rpc_result = JSONRPCReplyObj(NullUniValue, objError, jreq.id);
406 catch (const std::exception& e)
408 rpc_result = JSONRPCReplyObj(NullUniValue,
409 JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
412 return rpc_result;
415 std::string JSONRPCExecBatch(const JSONRPCRequest& jreq, const UniValue& vReq)
417 UniValue ret(UniValue::VARR);
418 for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
419 ret.push_back(JSONRPCExecOne(jreq, vReq[reqIdx]));
421 return ret.write() + "\n";
425 * Process named arguments into a vector of positional arguments, based on the
426 * passed-in specification for the RPC call's arguments.
428 static inline JSONRPCRequest transformNamedArguments(const JSONRPCRequest& in, const std::vector<std::string>& argNames)
430 JSONRPCRequest out = in;
431 out.params = UniValue(UniValue::VARR);
432 // Build a map of parameters, and remove ones that have been processed, so that we can throw a focused error if
433 // there is an unknown one.
434 const std::vector<std::string>& keys = in.params.getKeys();
435 const std::vector<UniValue>& values = in.params.getValues();
436 std::unordered_map<std::string, const UniValue*> argsIn;
437 for (size_t i=0; i<keys.size(); ++i) {
438 argsIn[keys[i]] = &values[i];
440 // Process expected parameters.
441 int hole = 0;
442 for (const std::string &argNamePattern: argNames) {
443 std::vector<std::string> vargNames;
444 boost::algorithm::split(vargNames, argNamePattern, boost::algorithm::is_any_of("|"));
445 auto fr = argsIn.end();
446 for (const std::string & argName : vargNames) {
447 fr = argsIn.find(argName);
448 if (fr != argsIn.end()) {
449 break;
452 if (fr != argsIn.end()) {
453 for (int i = 0; i < hole; ++i) {
454 // Fill hole between specified parameters with JSON nulls,
455 // but not at the end (for backwards compatibility with calls
456 // that act based on number of specified parameters).
457 out.params.push_back(UniValue());
459 hole = 0;
460 out.params.push_back(*fr->second);
461 argsIn.erase(fr);
462 } else {
463 hole += 1;
466 // If there are still arguments in the argsIn map, this is an error.
467 if (!argsIn.empty()) {
468 throw JSONRPCError(RPC_INVALID_PARAMETER, "Unknown named parameter " + argsIn.begin()->first);
470 // Return request with named arguments transformed to positional arguments
471 return out;
474 UniValue CRPCTable::execute(const JSONRPCRequest &request) const
476 // Return immediately if in warmup
478 LOCK(cs_rpcWarmup);
479 if (fRPCInWarmup)
480 throw JSONRPCError(RPC_IN_WARMUP, rpcWarmupStatus);
483 // Find method
484 const CRPCCommand *pcmd = tableRPC[request.strMethod];
485 if (!pcmd)
486 throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
488 g_rpcSignals.PreCommand(*pcmd);
492 // Execute, convert arguments to array if necessary
493 if (request.params.isObject()) {
494 return pcmd->actor(transformNamedArguments(request, pcmd->argNames));
495 } else {
496 return pcmd->actor(request);
499 catch (const std::exception& e)
501 throw JSONRPCError(RPC_MISC_ERROR, e.what());
505 std::vector<std::string> CRPCTable::listCommands() const
507 std::vector<std::string> commandList;
508 typedef std::map<std::string, const CRPCCommand*> commandMap;
510 std::transform( mapCommands.begin(), mapCommands.end(),
511 std::back_inserter(commandList),
512 boost::bind(&commandMap::value_type::first,_1) );
513 return commandList;
516 std::string HelpExampleCli(const std::string& methodname, const std::string& args)
518 return "> bitcoin-cli " + methodname + " " + args + "\n";
521 std::string HelpExampleRpc(const std::string& methodname, const std::string& args)
523 return "> curl --user myusername --data-binary '{\"jsonrpc\": \"1.0\", \"id\":\"curltest\", "
524 "\"method\": \"" + methodname + "\", \"params\": [" + args + "] }' -H 'content-type: text/plain;' http://127.0.0.1:8332/\n";
527 void RPCSetTimerInterfaceIfUnset(RPCTimerInterface *iface)
529 if (!timerInterface)
530 timerInterface = iface;
533 void RPCSetTimerInterface(RPCTimerInterface *iface)
535 timerInterface = iface;
538 void RPCUnsetTimerInterface(RPCTimerInterface *iface)
540 if (timerInterface == iface)
541 timerInterface = nullptr;
544 void RPCRunLater(const std::string& name, std::function<void(void)> func, int64_t nSeconds)
546 if (!timerInterface)
547 throw JSONRPCError(RPC_INTERNAL_ERROR, "No timer handler registered for RPC");
548 deadlineTimers.erase(name);
549 LogPrint(BCLog::RPC, "queue run of timer %s in %i seconds (using %s)\n", name, nSeconds, timerInterface->Name());
550 deadlineTimers.emplace(name, std::unique_ptr<RPCTimerBase>(timerInterface->NewTimer(func, nSeconds*1000)));
553 int RPCSerializationFlags()
555 int flag = 0;
556 if (gArgs.GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) == 0)
557 flag |= SERIALIZE_TRANSACTION_NO_WITNESS;
558 return flag;
561 CRPCTable tableRPC;