[tests] Add -blocknotify functional test
[bitcoinplatinum.git] / src / rpc / server.cpp
bloba73b697e01e0b87cb96816cfed26c5dc898f8d15
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(const UniValue& req)
394 UniValue rpc_result(UniValue::VOBJ);
396 JSONRPCRequest jreq;
397 try {
398 jreq.parse(req);
400 UniValue result = tableRPC.execute(jreq);
401 rpc_result = JSONRPCReplyObj(result, NullUniValue, jreq.id);
403 catch (const UniValue& objError)
405 rpc_result = JSONRPCReplyObj(NullUniValue, objError, jreq.id);
407 catch (const std::exception& e)
409 rpc_result = JSONRPCReplyObj(NullUniValue,
410 JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
413 return rpc_result;
416 std::string JSONRPCExecBatch(const UniValue& vReq)
418 UniValue ret(UniValue::VARR);
419 for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
420 ret.push_back(JSONRPCExecOne(vReq[reqIdx]));
422 return ret.write() + "\n";
426 * Process named arguments into a vector of positional arguments, based on the
427 * passed-in specification for the RPC call's arguments.
429 static inline JSONRPCRequest transformNamedArguments(const JSONRPCRequest& in, const std::vector<std::string>& argNames)
431 JSONRPCRequest out = in;
432 out.params = UniValue(UniValue::VARR);
433 // Build a map of parameters, and remove ones that have been processed, so that we can throw a focused error if
434 // there is an unknown one.
435 const std::vector<std::string>& keys = in.params.getKeys();
436 const std::vector<UniValue>& values = in.params.getValues();
437 std::unordered_map<std::string, const UniValue*> argsIn;
438 for (size_t i=0; i<keys.size(); ++i) {
439 argsIn[keys[i]] = &values[i];
441 // Process expected parameters.
442 int hole = 0;
443 for (const std::string &argNamePattern: argNames) {
444 std::vector<std::string> vargNames;
445 boost::algorithm::split(vargNames, argNamePattern, boost::algorithm::is_any_of("|"));
446 auto fr = argsIn.end();
447 for (const std::string & argName : vargNames) {
448 fr = argsIn.find(argName);
449 if (fr != argsIn.end()) {
450 break;
453 if (fr != argsIn.end()) {
454 for (int i = 0; i < hole; ++i) {
455 // Fill hole between specified parameters with JSON nulls,
456 // but not at the end (for backwards compatibility with calls
457 // that act based on number of specified parameters).
458 out.params.push_back(UniValue());
460 hole = 0;
461 out.params.push_back(*fr->second);
462 argsIn.erase(fr);
463 } else {
464 hole += 1;
467 // If there are still arguments in the argsIn map, this is an error.
468 if (!argsIn.empty()) {
469 throw JSONRPCError(RPC_INVALID_PARAMETER, "Unknown named parameter " + argsIn.begin()->first);
471 // Return request with named arguments transformed to positional arguments
472 return out;
475 UniValue CRPCTable::execute(const JSONRPCRequest &request) const
477 // Return immediately if in warmup
479 LOCK(cs_rpcWarmup);
480 if (fRPCInWarmup)
481 throw JSONRPCError(RPC_IN_WARMUP, rpcWarmupStatus);
484 // Find method
485 const CRPCCommand *pcmd = tableRPC[request.strMethod];
486 if (!pcmd)
487 throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
489 g_rpcSignals.PreCommand(*pcmd);
493 // Execute, convert arguments to array if necessary
494 if (request.params.isObject()) {
495 return pcmd->actor(transformNamedArguments(request, pcmd->argNames));
496 } else {
497 return pcmd->actor(request);
500 catch (const std::exception& e)
502 throw JSONRPCError(RPC_MISC_ERROR, e.what());
506 std::vector<std::string> CRPCTable::listCommands() const
508 std::vector<std::string> commandList;
509 typedef std::map<std::string, const CRPCCommand*> commandMap;
511 std::transform( mapCommands.begin(), mapCommands.end(),
512 std::back_inserter(commandList),
513 boost::bind(&commandMap::value_type::first,_1) );
514 return commandList;
517 std::string HelpExampleCli(const std::string& methodname, const std::string& args)
519 return "> bitcoin-cli " + methodname + " " + args + "\n";
522 std::string HelpExampleRpc(const std::string& methodname, const std::string& args)
524 return "> curl --user myusername --data-binary '{\"jsonrpc\": \"1.0\", \"id\":\"curltest\", "
525 "\"method\": \"" + methodname + "\", \"params\": [" + args + "] }' -H 'content-type: text/plain;' http://127.0.0.1:8332/\n";
528 void RPCSetTimerInterfaceIfUnset(RPCTimerInterface *iface)
530 if (!timerInterface)
531 timerInterface = iface;
534 void RPCSetTimerInterface(RPCTimerInterface *iface)
536 timerInterface = iface;
539 void RPCUnsetTimerInterface(RPCTimerInterface *iface)
541 if (timerInterface == iface)
542 timerInterface = nullptr;
545 void RPCRunLater(const std::string& name, std::function<void(void)> func, int64_t nSeconds)
547 if (!timerInterface)
548 throw JSONRPCError(RPC_INTERNAL_ERROR, "No timer handler registered for RPC");
549 deadlineTimers.erase(name);
550 LogPrint(BCLog::RPC, "queue run of timer %s in %i seconds (using %s)\n", name, nSeconds, timerInterface->Name());
551 deadlineTimers.emplace(name, std::unique_ptr<RPCTimerBase>(timerInterface->NewTimer(func, nSeconds*1000)));
554 int RPCSerializationFlags()
556 int flag = 0;
557 if (gArgs.GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) == 0)
558 flag |= SERIALIZE_TRANSACTION_NO_WITNESS;
559 return flag;
562 CRPCTable tableRPC;