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"
13 #include "ui_interface.h"
15 #include "utilstrencodings.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
;
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
,
59 for (UniValue::VType t
: typesExpected
)
61 if (params
.size() <= i
)
64 const UniValue
& v
= params
[i
];
65 if (!(fAllowNull
&& v
.isNull())) {
66 RPCTypeCheckArgument(v
, t
);
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
,
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
);
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");
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");
121 uint256
ParseHashV(const UniValue
& v
, std::string strName
)
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()));
131 result
.SetHex(strHex
);
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
)
142 strHex
= v
.get_str();
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
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
);
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
)
177 jreq
.strMethod
= strMethod
;
180 rpcfn_type pfn
= pcmd
->actor
;
181 if (setDone
.insert(pfn
).second
)
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())
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";
207 strRet
= strprintf("help: unknown command: %s\n", strCommand
);
208 strRet
= strRet
.substr(0,strRet
.size()-1);
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"
219 "1. \"command\" (string, optional) The command to get help on\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(
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.
242 return "Bitcoin server stopping";
245 UniValue
uptime(const JSONRPCRequest
& jsonRequest
)
247 if (jsonRequest
.fHelp
|| jsonRequest
.params
.size() > 1)
248 throw std::runtime_error(
250 "\nReturns the total uptime of the server.\n"
252 "ttt (numeric) The number of seconds that the server has been running\n"
254 + HelpExampleCli("uptime", "")
255 + HelpExampleRpc("uptime", "")
258 return GetTime() - GetStartupTime();
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()
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())
293 bool CRPCTable::appendCommand(const std::string
& name
, const CRPCCommand
* pcmd
)
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())
303 mapCommands
[name
] = pcmd
;
309 LogPrint(BCLog::RPC
, "Starting RPC\n");
311 g_rpcSignals
.Started();
317 LogPrint(BCLog::RPC
, "Interrupting RPC\n");
318 // Interrupt e.g. running longpolls
324 LogPrint(BCLog::RPC
, "Stopping RPC\n");
325 deadlineTimers
.clear();
327 g_rpcSignals
.Stopped();
335 void SetRPCWarmupStatus(const std::string
& newStatus
)
338 rpcWarmupStatus
= newStatus
;
341 void SetRPCWarmupFinished()
344 assert(fRPCInWarmup
);
345 fRPCInWarmup
= false;
348 bool RPCIsInWarmup(std::string
*outStatus
)
352 *outStatus
= rpcWarmupStatus
;
356 void JSONRPCRequest::parse(const UniValue
& valRequest
)
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");
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
));
376 UniValue valParams
= find_value(request
, "params");
377 if (valParams
.isArray() || valParams
.isObject())
379 else if (valParams
.isNull())
380 params
= UniValue(UniValue::VARR
);
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
);
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
);
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.
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()) {
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());
461 out
.params
.push_back(*fr
->second
);
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
475 UniValue
CRPCTable::execute(const JSONRPCRequest
&request
) const
477 // Return immediately if in warmup
481 throw JSONRPCError(RPC_IN_WARMUP
, rpcWarmupStatus
);
485 const CRPCCommand
*pcmd
= tableRPC
[request
.strMethod
];
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
));
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
) );
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
)
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
)
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()
557 if (gArgs
.GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION
) == 0)
558 flag
|= SERIALIZE_TRANSACTION_NO_WITNESS
;