Line data Source code
1 : // Copyright (c) 2017-2020 The Bitcoin Core developers
2 : // Distributed under the MIT software license, see the accompanying
3 : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 :
5 : #include <chainparamsbase.h>
6 : #include <consensus/amount.h>
7 : #include <key_io.h>
8 : #include <outputtype.h>
9 : #include <pubkey.h>
10 : #include <rpc/util.h>
11 : #include <script/descriptor.h>
12 : #include <script/signingprovider.h>
13 : #include <tinyformat.h>
14 : #include <util/check.h>
15 : #include <util/std23.h>
16 : #include <util/strencodings.h>
17 : #include <util/string.h>
18 : #include <util/system.h>
19 : #include <util/translation.h>
20 :
21 : const std::string UNIX_EPOCH_TIME = "UNIX epoch time";
22 218 : const std::string EXAMPLE_ADDRESS[2] = {"XunLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPw0", "XwQQkwA4FYkq2XERzMY2CiAZhJTEDAbtc0"};
23 :
24 92 : std::string GetAllOutputTypes()
25 : {
26 92 : std::vector<std::string> ret;
27 : using U = std::underlying_type<TxoutType>::type;
28 644 : for (U i = (U)TxoutType::NONSTANDARD; i <= (U)TxoutType::NULL_DATA; ++i) {
29 552 : ret.emplace_back(GetTxnOutputType(static_cast<TxoutType>(i)));
30 552 : }
31 92 : return Join(ret, ", ");
32 92 : }
33 :
34 17 : void RPCTypeCheck(const UniValue& params,
35 : const std::list<UniValueType>& typesExpected,
36 : bool fAllowNull)
37 : {
38 17 : unsigned int i = 0;
39 45 : for (const UniValueType& t : typesExpected) {
40 41 : if (params.size() <= i)
41 13 : break;
42 :
43 28 : const UniValue& v = params[i];
44 28 : if (!(fAllowNull && v.isNull())) {
45 27 : RPCTypeCheckArgument(v, t);
46 27 : }
47 28 : i++;
48 : }
49 17 : }
50 :
51 27 : void RPCTypeCheckArgument(const UniValue& value, const UniValueType& typeExpected)
52 : {
53 27 : if (!typeExpected.typeAny && value.type() != typeExpected.type) {
54 2 : throw JSONRPCError(RPC_TYPE_ERROR,
55 1 : strprintf("JSON value of type %s is not of expected type %s", uvTypeName(value.type()), uvTypeName(typeExpected.type)));
56 : }
57 27 : }
58 :
59 4 : void RPCTypeCheckObj(const UniValue& o,
60 : const std::map<std::string, UniValueType>& typesExpected,
61 : bool fAllowNull,
62 : bool fStrict)
63 : {
64 12 : for (const auto& t : typesExpected) {
65 8 : const UniValue& v = o.find_value(t.first);
66 8 : if (!fAllowNull && v.isNull())
67 0 : throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first));
68 :
69 8 : if (!(t.second.typeAny || v.type() == t.second.type || (fAllowNull && v.isNull())))
70 0 : throw JSONRPCError(RPC_TYPE_ERROR, strprintf("JSON value of type %s for field %s is not of expected type %s", uvTypeName(v.type()), t.first, uvTypeName(t.second.type)));
71 : }
72 :
73 4 : if (fStrict)
74 : {
75 0 : for (const std::string& k : o.getKeys())
76 : {
77 0 : if (typesExpected.count(k) == 0)
78 : {
79 0 : std::string err = strprintf("Unexpected key %s", k);
80 0 : throw JSONRPCError(RPC_TYPE_ERROR, err);
81 0 : }
82 : }
83 0 : }
84 4 : }
85 :
86 28 : CAmount AmountFromValue(const UniValue& value, int decimals)
87 : {
88 28 : if (!value.isNum() && !value.isStr())
89 9 : throw JSONRPCError(RPC_TYPE_ERROR, "Amount is not a number or string");
90 : CAmount amount;
91 28 : if (!ParseFixedPoint(value.getValStr(), decimals, &amount))
92 8 : throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
93 20 : if (!MoneyRange(amount))
94 1 : throw JSONRPCError(RPC_TYPE_ERROR, "Amount out of range");
95 19 : return amount;
96 9 : }
97 :
98 9 : uint256 ParseHashV(const UniValue& v, std::string strName)
99 : {
100 9 : const std::string& strHex(v.get_str());
101 9 : if (64 != strHex.length())
102 1 : throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("%s must be of length %d (not %d, for '%s')", strName, 64, strHex.length(), strHex));
103 8 : if (!IsHex(strHex)) // Note: IsHex("") is false
104 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
105 8 : return uint256S(strHex);
106 1 : }
107 8 : uint256 ParseHashO(const UniValue& o, std::string strKey)
108 : {
109 8 : return ParseHashV(o.find_value(strKey), strKey);
110 0 : }
111 8 : std::vector<unsigned char> ParseHexV(const UniValue& v, std::string strName)
112 : {
113 8 : std::string strHex;
114 8 : if (v.isStr())
115 8 : strHex = v.get_str();
116 8 : if (!IsHex(strHex))
117 2 : throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
118 6 : return ParseHex(strHex);
119 10 : }
120 2 : std::vector<unsigned char> ParseHexO(const UniValue& o, std::string strKey)
121 : {
122 2 : return ParseHexV(o.find_value(strKey), strKey);
123 0 : }
124 :
125 7 : bool ParseBoolV(const UniValue& v, const std::string &strName)
126 : {
127 7 : if (std23::ranges::contains(gArgs.GetArgs("-deprecatedrpc"), "permissive_bool")) {
128 0 : std::string strBool;
129 0 : if (v.isBool())
130 0 : return v.get_bool();
131 0 : else if (v.isNum())
132 0 : strBool = ToString(v.getInt<int>());
133 0 : else if (v.isStr())
134 0 : strBool = v.get_str();
135 :
136 0 : strBool = ToLower(strBool);
137 :
138 0 : if (strBool == "true" || strBool == "yes" || strBool == "1") {
139 0 : return true;
140 0 : } else if (strBool == "false" || strBool == "no" || strBool == "0") {
141 0 : return false;
142 : }
143 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("%s must be true, false, yes, no, 1 or 0 (not '%s')", strName, strBool));
144 0 : }
145 :
146 7 : if (!v.isBool()) {
147 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("%s must be a JSON boolean. " /* Continued */
148 0 : "Pass -deprecatedrpc=permissive_bool to allow legacy boolean parsing.", strName));
149 : }
150 7 : return v.get_bool();
151 7 : }
152 :
153 : namespace {
154 :
155 : /**
156 : * Quote an argument for shell.
157 : *
158 : * @note This is intended for help, not for security-sensitive purposes.
159 : */
160 13 : std::string ShellQuote(const std::string& s)
161 : {
162 13 : std::string result;
163 13 : result.reserve(s.size() * 2);
164 301 : for (const char ch: s) {
165 288 : if (ch == '\'') {
166 1 : result += "'\''";
167 1 : } else {
168 287 : result += ch;
169 : }
170 : }
171 13 : return "'" + result + "'";
172 13 : }
173 :
174 : /**
175 : * Shell-quotes the argument if it needs quoting, else returns it literally, to save typing.
176 : *
177 : * @note This is intended for help, not for security-sensitive purposes.
178 : */
179 66 : std::string ShellQuoteIfNeeded(const std::string& s)
180 : {
181 607 : for (const char ch: s) {
182 554 : if (ch == ' ' || ch == '\'' || ch == '"') {
183 13 : return ShellQuote(s);
184 : }
185 : }
186 :
187 53 : return s;
188 66 : }
189 :
190 : }
191 :
192 21876 : std::string HelpExampleCli(const std::string& methodname, const std::string& args)
193 : {
194 21876 : return "> dash-cli " + methodname + " " + args + "\n";
195 0 : }
196 :
197 24 : std::string HelpExampleCliNamed(const std::string& methodname, const RPCArgList& args)
198 : {
199 24 : std::string result = "> dash-cli -named " + methodname;
200 90 : for (const auto& argpair: args) {
201 132 : const auto& value = argpair.second.isStr()
202 29 : ? argpair.second.get_str()
203 37 : : argpair.second.write();
204 66 : result += " " + argpair.first + "=" + ShellQuoteIfNeeded(value);
205 66 : }
206 24 : result += "\n";
207 24 : return result;
208 24 : }
209 :
210 17682 : std::string HelpExampleRpc(const std::string& methodname, const std::string& args)
211 : {
212 17682 : return "> curl --user myusername --data-binary '{\"jsonrpc\": \"1.0\", \"id\": \"curltest\", "
213 17682 : "\"method\": \"" + methodname + "\", \"params\": [" + args + "]}' -H 'content-type: application/json;'"
214 : " http://127.0.0.1:9998/\n";
215 0 : }
216 :
217 21 : std::string HelpExampleRpcNamed(const std::string& methodname, const RPCArgList& args)
218 : {
219 21 : UniValue params(UniValue::VOBJ);
220 84 : for (const auto& param: args) {
221 63 : params.pushKV(param.first, param.second);
222 : }
223 :
224 21 : return "> curl --user myusername --data-binary '{\"jsonrpc\": \"1.0\", \"id\": \"curltest\", "
225 21 : "\"method\": \"" + methodname + "\", \"params\": " + params.write() + "}' -H 'content-type: application/json;' http://127.0.0.1:8332/\n";
226 21 : }
227 :
228 : // Converts a hex string to a public key if possible
229 0 : CPubKey HexToPubKey(const std::string& hex_in)
230 : {
231 0 : if (!IsHex(hex_in)) {
232 0 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid public key: " + hex_in);
233 : }
234 0 : CPubKey vchPubKey(ParseHex(hex_in));
235 0 : if (!vchPubKey.IsFullyValid()) {
236 0 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid public key: " + hex_in);
237 : }
238 0 : return vchPubKey;
239 0 : }
240 :
241 : // Retrieves a public key for an address from the given FillableSigningProvider
242 2 : CPubKey AddrToPubKey(const FillableSigningProvider& keystore, const std::string& addr_in)
243 : {
244 2 : CTxDestination dest = DecodeDestination(addr_in);
245 2 : if (!IsValidDestination(dest)) {
246 0 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address: " + addr_in);
247 : }
248 2 : const PKHash *pkhash = std::get_if<PKHash>(&dest);
249 2 : if (!pkhash) {
250 0 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("'%s' does not refer to a key", addr_in));
251 : }
252 2 : CPubKey vchPubKey;
253 2 : if (!keystore.GetPubKey(ToKeyID(*pkhash), vchPubKey)) {
254 0 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("no full public key for address %s", addr_in));
255 : }
256 2 : if (!vchPubKey.IsFullyValid()) {
257 0 : throw JSONRPCError(RPC_INTERNAL_ERROR, "Wallet contains an invalid public key");
258 : }
259 2 : return vchPubKey;
260 0 : }
261 :
262 : // Creates a multisig address from a given list of public keys, number of signatures required
263 1 : CTxDestination AddAndGetMultisigDestination(const int required, const std::vector<CPubKey>& pubkeys, FillableSigningProvider& keystore, CScript& script_out)
264 : {
265 : // Gather public keys
266 1 : if (required < 1) {
267 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "a multisignature address must require at least one key to redeem");
268 : }
269 1 : if ((int)pubkeys.size() < required) {
270 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("not enough keys supplied (got %u keys, but need at least %d to redeem)", pubkeys.size(), required));
271 : }
272 1 : if (pubkeys.size() > MAX_PUBKEYS_PER_MULTISIG) {
273 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Number of keys involved in the multisignature address creation > %d\nReduce the number", MAX_PUBKEYS_PER_MULTISIG));
274 : }
275 :
276 1 : script_out = GetScriptForMultisig(required, pubkeys);
277 :
278 1 : if (script_out.size() > MAX_SCRIPT_ELEMENT_SIZE) {
279 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, (strprintf("redeemScript exceeds size limit: %d > %d", script_out.size(), MAX_SCRIPT_ELEMENT_SIZE)));
280 : }
281 :
282 1 : return AddAndGetDestinationForScript(keystore, script_out, OutputType::LEGACY);
283 0 : }
284 :
285 : class DescribeAddressVisitor
286 : {
287 : public:
288 : explicit DescribeAddressVisitor() = default;
289 :
290 0 : UniValue operator()(const CNoDestination &dest) const { return UniValue(UniValue::VOBJ); }
291 :
292 1 : UniValue operator()(const PKHash &pkhash) const {
293 1 : UniValue obj(UniValue::VOBJ);
294 1 : obj.pushKV("isscript", false);
295 1 : return obj;
296 1 : }
297 :
298 1 : UniValue operator()(const ScriptHash &scriptID) const {
299 1 : UniValue obj(UniValue::VOBJ);
300 1 : obj.pushKV("isscript", true);
301 1 : return obj;
302 1 : }
303 : };
304 :
305 2 : UniValue DescribeAddress(const CTxDestination& dest)
306 : {
307 2 : return std::visit(DescribeAddressVisitor(), dest);
308 : }
309 :
310 0 : unsigned int ParseConfirmTarget(const UniValue& value, unsigned int max_target)
311 : {
312 0 : const int target{value.getInt<int>()};
313 0 : const unsigned int unsigned_target{static_cast<unsigned int>(target)};
314 0 : if (target < 1 || unsigned_target > max_target) {
315 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid conf_target, must be between %u and %u", 1, max_target));
316 : }
317 0 : return unsigned_target;
318 0 : }
319 :
320 : /**
321 : * A pair of strings that can be aligned (through padding) with other Sections
322 : * later on
323 : */
324 1378 : struct Section {
325 1126 : Section(const std::string& left, const std::string& right)
326 1126 : : m_left{left}, m_right{right} {}
327 : std::string m_left;
328 : const std::string m_right;
329 : };
330 :
331 : /**
332 : * Keeps track of RPCArgs by transforming them into sections for the purpose
333 : * of serializing everything to a single string
334 : */
335 17 : struct Sections {
336 : std::vector<Section> m_sections;
337 17 : size_t m_max_pad{0};
338 :
339 545 : void PushSection(const Section& s)
340 : {
341 545 : m_max_pad = std::max(m_max_pad, s.m_left.size());
342 545 : m_sections.push_back(s);
343 545 : }
344 :
345 : /**
346 : * Recursive helper to translate an RPCArg into sections
347 : */
348 28 : void Push(const RPCArg& arg, const size_t current_indent = 5, const OuterType outer_type = OuterType::NONE)
349 : {
350 28 : const auto indent = std::string(current_indent, ' ');
351 28 : const auto indent_next = std::string(current_indent + 2, ' ');
352 28 : const bool push_name{outer_type == OuterType::OBJ}; // Dictionary keys must have a name
353 28 : const bool is_top_level_arg{outer_type == OuterType::NONE}; // True on the first recursion
354 :
355 28 : switch (arg.m_type) {
356 : case RPCArg::Type::STR_HEX:
357 : case RPCArg::Type::STR:
358 : case RPCArg::Type::NUM:
359 : case RPCArg::Type::AMOUNT:
360 : case RPCArg::Type::RANGE:
361 : case RPCArg::Type::BOOL: {
362 21 : if (is_top_level_arg) return; // Nothing more to do for non-recursive types on first recursion
363 7 : auto left = indent;
364 7 : if (arg.m_type_str.size() != 0 && push_name) {
365 0 : left += "\"" + arg.GetName() + "\": " + arg.m_type_str.at(0);
366 0 : } else {
367 7 : left += push_name ? arg.ToStringObj(/*oneline=*/false) : arg.ToString(/*oneline=*/false);
368 : }
369 7 : left += ",";
370 7 : PushSection({left, arg.ToDescriptionString(/*is_named_arg=*/push_name)});
371 : break;
372 7 : }
373 : case RPCArg::Type::OBJ:
374 : case RPCArg::Type::OBJ_USER_KEYS: {
375 3 : const auto right = is_top_level_arg ? "" : arg.ToDescriptionString(/*is_named_arg=*/push_name);
376 3 : PushSection({indent + (push_name ? "\"" + arg.GetName() + "\": " : "") + "{", right});
377 8 : for (const auto& arg_inner : arg.m_inner) {
378 5 : Push(arg_inner, current_indent + 2, OuterType::OBJ);
379 : }
380 3 : if (arg.m_type != RPCArg::Type::OBJ) {
381 1 : PushSection({indent_next + "...", ""});
382 1 : }
383 3 : PushSection({indent + "}" + (is_top_level_arg ? "" : ","), ""});
384 : break;
385 3 : }
386 : case RPCArg::Type::ARR: {
387 4 : auto left = indent;
388 4 : left += push_name ? "\"" + arg.GetName() + "\": " : "";
389 4 : left += "[";
390 4 : const auto right = is_top_level_arg ? "" : arg.ToDescriptionString(/*is_named_arg=*/push_name);
391 4 : PushSection({left, right});
392 9 : for (const auto& arg_inner : arg.m_inner) {
393 5 : Push(arg_inner, current_indent + 2, OuterType::ARR);
394 : }
395 4 : PushSection({indent_next + "...", ""});
396 4 : PushSection({indent + "]" + (is_top_level_arg ? "" : ","), ""});
397 : break;
398 4 : }
399 : } // no default case, so the compiler can warn about missing cases
400 28 : }
401 :
402 : /**
403 : * Concatenate all sections with proper padding
404 : */
405 17 : std::string ToString() const
406 : {
407 17 : std::string ret;
408 17 : const size_t pad = m_max_pad + 4;
409 580 : for (const auto& s : m_sections) {
410 : // The left part of a section is assumed to be a single line, usually it is the name of the JSON struct or a
411 : // brace like {, }, [, or ]
412 563 : CHECK_NONFATAL(s.m_left.find('\n') == std::string::npos);
413 563 : if (s.m_right.empty()) {
414 136 : ret += s.m_left;
415 136 : ret += "\n";
416 136 : continue;
417 : }
418 :
419 427 : std::string left = s.m_left;
420 427 : left.resize(pad, ' ');
421 427 : ret += left;
422 :
423 : // Properly pad after newlines
424 427 : std::string right;
425 427 : size_t begin = 0;
426 427 : size_t new_line_pos = s.m_right.find_first_of('\n');
427 432 : while (true) {
428 432 : right += s.m_right.substr(begin, new_line_pos - begin);
429 432 : if (new_line_pos == std::string::npos) {
430 426 : break; //No new line
431 : }
432 6 : right += "\n" + std::string(pad, ' ');
433 6 : begin = s.m_right.find_first_not_of(' ', new_line_pos + 1);
434 6 : if (begin == std::string::npos) {
435 1 : break; // Empty line
436 : }
437 5 : new_line_pos = s.m_right.find_first_of('\n', begin + 1);
438 : }
439 427 : ret += right;
440 427 : ret += "\n";
441 427 : }
442 17 : return ret;
443 17 : }
444 : };
445 :
446 0 : RPCHelpMan::RPCHelpMan(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples)
447 0 : : RPCHelpMan{std::move(name), std::move(description), std::move(args), std::move(results), std::move(examples), nullptr} {}
448 :
449 46922 : RPCHelpMan::RPCHelpMan(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples, RPCMethodImpl fun)
450 23461 : : m_name{std::move(name)},
451 23461 : m_fun{std::move(fun)},
452 23461 : m_description{std::move(description)},
453 23461 : m_args{std::move(args)},
454 23461 : m_results{std::move(results)},
455 23461 : m_examples{std::move(examples)}
456 23461 : {
457 : std::set<std::string> named_args;
458 : for (const auto& arg : m_args) {
459 : std::vector<std::string> names = SplitString(arg.m_names, '|');
460 : // Should have unique named arguments
461 : for (const std::string& name : names) {
462 : CHECK_NONFATAL(named_args.insert(name).second);
463 : }
464 : // Default value type should match argument type only when defined
465 : if (arg.m_fallback.index() == 2) {
466 : const RPCArg::Type type = arg.m_type;
467 : switch (std::get<RPCArg::Default>(arg.m_fallback).getType()) {
468 : case UniValue::VOBJ:
469 : CHECK_NONFATAL(type == RPCArg::Type::OBJ);
470 : break;
471 : case UniValue::VARR:
472 : CHECK_NONFATAL(type == RPCArg::Type::ARR);
473 : break;
474 : case UniValue::VSTR:
475 : CHECK_NONFATAL(type == RPCArg::Type::STR || type == RPCArg::Type::STR_HEX || type == RPCArg::Type::AMOUNT);
476 : break;
477 : case UniValue::VNUM:
478 : CHECK_NONFATAL(type == RPCArg::Type::NUM || type == RPCArg::Type::AMOUNT || type == RPCArg::Type::RANGE);
479 : break;
480 : case UniValue::VBOOL:
481 : CHECK_NONFATAL(type == RPCArg::Type::BOOL);
482 : break;
483 : case UniValue::VNULL:
484 : // Null values are accepted in all arguments
485 : break;
486 : default:
487 : NONFATAL_UNREACHABLE();
488 : break;
489 : }
490 : }
491 : }
492 23461 : }
493 :
494 8 : std::string RPCResults::ToDescriptionString() const
495 : {
496 8 : std::string result;
497 17 : for (const auto& r : m_results) {
498 9 : if (r.m_type == RPCResult::Type::ANY) continue; // for testing only
499 9 : if (r.m_cond.empty()) {
500 7 : result += "\nResult:\n";
501 7 : } else {
502 2 : result += "\nResult (" + r.m_cond + "):\n";
503 : }
504 9 : Sections sections;
505 9 : r.ToSections(sections);
506 9 : result += sections.ToString();
507 9 : }
508 8 : return result;
509 8 : }
510 :
511 8 : std::string RPCExamples::ToDescriptionString() const
512 : {
513 8 : return m_examples.empty() ? m_examples : "\nExamples:\n" + m_examples;
514 : }
515 :
516 6248 : UniValue RPCHelpMan::HandleRequest(const JSONRPCRequest& request) const
517 : {
518 6248 : if (request.mode == JSONRPCRequest::GET_ARGS) {
519 0 : return GetArgMap();
520 : }
521 : /*
522 : * Check if the given request is valid according to this command or if
523 : * the user is asking for help information, and throw help when appropriate.
524 : */
525 6248 : if (request.mode == JSONRPCRequest::GET_HELP || !IsValidNumArgs(request.params.size())) {
526 8 : throw std::runtime_error(ToString());
527 : }
528 6240 : CHECK_NONFATAL(m_req == nullptr);
529 6240 : m_req = &request;
530 6240 : UniValue ret = m_fun(*this, request);
531 6240 : m_req = nullptr;
532 6240 : if (gArgs.GetBoolArg("-rpcdoccheck", DEFAULT_RPC_DOC_CHECK)) {
533 0 : CHECK_NONFATAL(std::any_of(m_results.m_results.begin(), m_results.m_results.end(), [&ret](const RPCResult& res) { return res.MatchesType(ret); }));
534 0 : }
535 6240 : return ret;
536 12488 : }
537 :
538 : using CheckFn = void(const RPCArg&);
539 0 : static const UniValue* DetailMaybeArg(CheckFn* check, const std::vector<RPCArg>& params, const JSONRPCRequest* req, size_t i)
540 : {
541 0 : CHECK_NONFATAL(i < params.size());
542 0 : const UniValue& arg{CHECK_NONFATAL(req)->params[i]};
543 0 : const RPCArg& param{params.at(i)};
544 0 : if (check) check(param);
545 :
546 0 : if (!arg.isNull()) return &arg;
547 0 : if (!std::holds_alternative<RPCArg::Default>(param.m_fallback)) return nullptr;
548 0 : return &std::get<RPCArg::Default>(param.m_fallback);
549 0 : }
550 :
551 0 : static void CheckRequiredOrDefault(const RPCArg& param)
552 : {
553 : // Must use `Arg<Type>(i)` to get the argument or its default value.
554 0 : const bool required{
555 0 : std::holds_alternative<RPCArg::Optional>(param.m_fallback) && RPCArg::Optional::NO == std::get<RPCArg::Optional>(param.m_fallback),
556 : };
557 0 : CHECK_NONFATAL(required || std::holds_alternative<RPCArg::Default>(param.m_fallback));
558 0 : }
559 :
560 : #define TMPL_INST(check_param, ret_type, return_code) \
561 : template <> \
562 : ret_type RPCHelpMan::ArgValue<ret_type>(size_t i) const \
563 : { \
564 : const UniValue* maybe_arg{ \
565 : DetailMaybeArg(check_param, m_args, m_req, i), \
566 : }; \
567 : return return_code \
568 : } \
569 : void force_semicolon(ret_type)
570 :
571 : // Optional arg (without default). Can also be called on required args, if needed.
572 0 : TMPL_INST(nullptr, std::optional<double>, maybe_arg ? std::optional{maybe_arg->get_real()} : std::nullopt;);
573 0 : TMPL_INST(nullptr, std::optional<bool>, maybe_arg ? std::optional{maybe_arg->get_bool()} : std::nullopt;);
574 0 : TMPL_INST(nullptr, const std::string*, maybe_arg ? &maybe_arg->get_str() : nullptr;);
575 :
576 : // Required arg or optional arg with default value.
577 0 : TMPL_INST(CheckRequiredOrDefault, int, CHECK_NONFATAL(maybe_arg)->getInt<int>(););
578 0 : TMPL_INST(CheckRequiredOrDefault, uint64_t, CHECK_NONFATAL(maybe_arg)->getInt<uint64_t>(););
579 0 : TMPL_INST(CheckRequiredOrDefault, const std::string&, CHECK_NONFATAL(maybe_arg)->get_str(););
580 :
581 6261 : bool RPCHelpMan::IsValidNumArgs(size_t num_args) const
582 : {
583 6261 : size_t num_required_args = 0;
584 12514 : for (size_t n = m_args.size(); n > 0; --n) {
585 6305 : if (!m_args.at(n - 1).IsOptional()) {
586 52 : num_required_args = n;
587 52 : break;
588 : }
589 6253 : }
590 6261 : return num_required_args <= num_args && num_args <= m_args.size();
591 : }
592 :
593 8600 : std::vector<std::string> RPCHelpMan::GetArgNames() const
594 : {
595 8600 : std::vector<std::string> ret;
596 23702 : for (const auto& arg : m_args) {
597 15102 : ret.emplace_back(arg.m_names);
598 : }
599 8600 : return ret;
600 8600 : }
601 :
602 8 : std::string RPCHelpMan::ToString() const
603 : {
604 8 : std::string ret;
605 :
606 : // Oneline summary
607 8 : ret += m_name;
608 8 : bool was_optional{false};
609 26 : for (const auto& arg : m_args) {
610 18 : if (arg.m_hidden) break; // Any arg that follows is also hidden
611 18 : const bool optional = arg.IsOptional();
612 18 : ret += " ";
613 18 : if (optional) {
614 8 : if (!was_optional) ret += "( ";
615 8 : was_optional = true;
616 8 : } else {
617 10 : if (was_optional) ret += ") ";
618 10 : was_optional = false;
619 : }
620 18 : ret += arg.ToString(/*oneline=*/true);
621 : }
622 8 : if (was_optional) ret += " )";
623 :
624 : // Description
625 8 : ret += "\n\n" + TrimString(m_description) + "\n";
626 :
627 : // Arguments
628 8 : Sections sections;
629 26 : for (size_t i{0}; i < m_args.size(); ++i) {
630 18 : const auto& arg = m_args.at(i);
631 18 : if (arg.m_hidden) break; // Any arg that follows is also hidden
632 :
633 18 : if (i == 0) ret += "\nArguments:\n";
634 :
635 : // Push named argument name and description
636 18 : sections.m_sections.emplace_back(::ToString(i + 1) + ". " + arg.GetFirstName(), arg.ToDescriptionString(/*is_named_arg=*/true));
637 18 : sections.m_max_pad = std::max(sections.m_max_pad, sections.m_sections.back().m_left.size());
638 :
639 : // Recursively push nested args
640 18 : sections.Push(arg);
641 18 : }
642 8 : ret += sections.ToString();
643 :
644 : // Result
645 8 : ret += m_results.ToDescriptionString();
646 :
647 : // Examples
648 8 : ret += m_examples.ToDescriptionString();
649 :
650 8 : return ret;
651 8 : }
652 :
653 0 : UniValue RPCHelpMan::GetArgMap() const
654 : {
655 0 : UniValue arr{UniValue::VARR};
656 0 : for (int i{0}; i < int(m_args.size()); ++i) {
657 0 : const auto& arg = m_args.at(i);
658 0 : std::vector<std::string> arg_names = SplitString(arg.m_names, '|');
659 0 : for (const auto& arg_name : arg_names) {
660 0 : UniValue map{UniValue::VARR};
661 0 : map.push_back(m_name);
662 0 : map.push_back(i);
663 0 : map.push_back(arg_name);
664 0 : map.push_back(arg.m_type == RPCArg::Type::STR ||
665 0 : arg.m_type == RPCArg::Type::STR_HEX);
666 0 : arr.push_back(map);
667 0 : }
668 0 : }
669 0 : return arr;
670 0 : }
671 :
672 46 : std::string RPCArg::GetFirstName() const
673 : {
674 46 : return m_names.substr(0, m_names.find("|"));
675 : }
676 :
677 0 : std::string RPCArg::GetName() const
678 : {
679 0 : CHECK_NONFATAL(std::string::npos == m_names.find("|"));
680 0 : return m_names;
681 : }
682 :
683 6323 : bool RPCArg::IsOptional() const
684 : {
685 6323 : if (m_fallback.index() != 0) {
686 6250 : return true;
687 : } else {
688 73 : return RPCArg::Optional::NO != std::get<RPCArg::Optional>(m_fallback);
689 : }
690 6323 : }
691 :
692 34 : std::string RPCArg::ToDescriptionString(bool is_named_arg) const
693 : {
694 34 : std::string ret;
695 34 : ret += "(";
696 28 : if (m_type_str.size() != 0) {
697 0 : ret += m_type_str.at(1);
698 0 : } else {
699 28 : switch (m_type) {
700 : case Type::STR_HEX:
701 : case Type::STR: {
702 14 : ret += "string";
703 11 : break;
704 : }
705 : case Type::NUM: {
706 4 : ret += "numeric";
707 4 : break;
708 : }
709 : case Type::AMOUNT: {
710 2 : ret += "numeric or string";
711 2 : break;
712 : }
713 : case Type::RANGE: {
714 0 : ret += "numeric or array";
715 0 : break;
716 : }
717 : case Type::BOOL: {
718 4 : ret += "boolean";
719 4 : break;
720 : }
721 : case Type::OBJ:
722 : case Type::OBJ_USER_KEYS: {
723 0 : ret += "json object";
724 3 : break;
725 : }
726 : case Type::ARR: {
727 4 : ret += "json array";
728 4 : break;
729 : }
730 : } // no default case, so the compiler can warn about missing cases
731 : }
732 28 : if (m_fallback.index() == 1) {
733 1 : ret += ", optional, default=" + std::get<RPCArg::DefaultHint>(m_fallback);
734 28 : } else if (m_fallback.index() == 2) {
735 6 : ret += ", optional, default=" + std::get<RPCArg::Default>(m_fallback).write();
736 6 : } else {
737 21 : switch (std::get<RPCArg::Optional>(m_fallback)) {
738 : case RPCArg::Optional::OMITTED_NAMED_ARG: // Deprecated alias for OMITTED, can be removed
739 : case RPCArg::Optional::OMITTED: {
740 7 : if (is_named_arg) ret += ", optional"; // Default value is "null" in dicts. Otherwise,
741 : // nothing to do. Element is treated as if not present and has no default value
742 7 : break;
743 : }
744 : case RPCArg::Optional::NO: {
745 14 : ret += ", required";
746 14 : break;
747 : }
748 : } // no default case, so the compiler can warn about missing cases
749 : }
750 28 : ret += ")";
751 28 : ret += m_description.empty() ? "" : " " + m_description;
752 28 : return ret;
753 40 : }
754 :
755 399 : void RPCResult::ToSections(Sections& sections, const OuterType outer_type, const int current_indent) const
756 : {
757 : // Indentation
758 399 : const std::string indent(current_indent, ' ');
759 399 : const std::string indent_next(current_indent + 2, ' ');
760 :
761 : // Elements in a JSON structure (dictionary or array) are separated by a comma
762 399 : const std::string maybe_separator{outer_type != OuterType::NONE ? "," : ""};
763 :
764 : // The key name if recursed into an dictionary
765 399 : const std::string maybe_key{
766 798 : outer_type == OuterType::OBJ ?
767 361 : "\"" + this->m_key_name + "\" : " :
768 38 : ""};
769 :
770 : // Format description with type
771 798 : const auto Description = [&](const std::string& type) {
772 798 : return "(" + type + (this->m_optional ? ", optional" : "") + ")" +
773 399 : (this->m_description.empty() ? "" : " " + this->m_description);
774 0 : };
775 :
776 399 : switch (m_type) {
777 : case Type::ELISION: {
778 : // If the inner result is empty, use three dots for elision
779 0 : sections.PushSection({indent + "..." + maybe_separator, m_description});
780 0 : return;
781 : }
782 : case Type::ANY: {
783 0 : NONFATAL_UNREACHABLE(); // Only for testing
784 : }
785 : case Type::NONE: {
786 1 : sections.PushSection({indent + "null" + maybe_separator, Description("json null")});
787 1 : return;
788 : }
789 : case Type::STR: {
790 70 : sections.PushSection({indent + maybe_key + "\"str\"" + maybe_separator, Description("string")});
791 70 : return;
792 : }
793 : case Type::STR_AMOUNT: {
794 3 : sections.PushSection({indent + maybe_key + "n" + maybe_separator, Description("numeric")});
795 3 : return;
796 : }
797 : case Type::STR_HEX: {
798 97 : sections.PushSection({indent + maybe_key + "\"hex\"" + maybe_separator, Description("string")});
799 97 : return;
800 : }
801 : case Type::NUM: {
802 125 : sections.PushSection({indent + maybe_key + "n" + maybe_separator, Description("numeric")});
803 125 : return;
804 : }
805 : case Type::NUM_TIME: {
806 4 : sections.PushSection({indent + maybe_key + "xxx" + maybe_separator, Description("numeric")});
807 4 : return;
808 : }
809 : case Type::BOOL: {
810 8 : sections.PushSection({indent + maybe_key + "true|false" + maybe_separator, Description("boolean")});
811 8 : return;
812 : }
813 : case Type::ARR_FIXED:
814 : case Type::ARR: {
815 29 : sections.PushSection({indent + maybe_key + "[", Description("json array")});
816 58 : for (const auto& i : m_inner) {
817 29 : i.ToSections(sections, OuterType::ARR, current_indent + 2);
818 : }
819 29 : CHECK_NONFATAL(!m_inner.empty());
820 29 : if (m_type == Type::ARR && m_inner.back().m_type != Type::ELISION) {
821 29 : sections.PushSection({indent_next + "...", ""});
822 29 : } else {
823 : // Remove final comma, which would be invalid JSON
824 0 : sections.m_sections.back().m_left.pop_back();
825 : }
826 29 : sections.PushSection({indent + "]" + maybe_separator, ""});
827 29 : return;
828 : }
829 : case Type::OBJ_DYN:
830 : case Type::OBJ: {
831 62 : if (m_inner.empty()) {
832 0 : sections.PushSection({indent + maybe_key + "{}", Description("empty JSON object")});
833 0 : return;
834 : }
835 62 : sections.PushSection({indent + maybe_key + "{", Description("json object")});
836 423 : for (const auto& i : m_inner) {
837 361 : i.ToSections(sections, OuterType::OBJ, current_indent + 2);
838 : }
839 62 : if (m_type == Type::OBJ_DYN && m_inner.back().m_type != Type::ELISION) {
840 : // If the dictionary keys are dynamic, use three dots for continuation
841 0 : sections.PushSection({indent_next + "...", ""});
842 0 : } else {
843 : // Remove final comma, which would be invalid JSON
844 62 : sections.m_sections.back().m_left.pop_back();
845 : }
846 62 : sections.PushSection({indent + "}" + maybe_separator, ""});
847 62 : return;
848 : }
849 : } // no default case, so the compiler can warn about missing cases
850 0 : NONFATAL_UNREACHABLE();
851 399 : }
852 :
853 0 : bool RPCResult::MatchesType(const UniValue& result) const
854 : {
855 0 : switch (m_type) {
856 : case Type::ELISION: {
857 0 : return false;
858 : }
859 : case Type::ANY: {
860 0 : return true;
861 : }
862 : case Type::NONE: {
863 0 : return UniValue::VNULL == result.getType();
864 : }
865 : case Type::STR:
866 : case Type::STR_HEX: {
867 0 : return UniValue::VSTR == result.getType();
868 : }
869 : case Type::NUM:
870 : case Type::STR_AMOUNT:
871 : case Type::NUM_TIME: {
872 0 : return UniValue::VNUM == result.getType();
873 : }
874 : case Type::BOOL: {
875 0 : return UniValue::VBOOL == result.getType();
876 : }
877 : case Type::ARR_FIXED:
878 : case Type::ARR: {
879 0 : return UniValue::VARR == result.getType();
880 : }
881 : case Type::OBJ_DYN:
882 : case Type::OBJ: {
883 0 : return UniValue::VOBJ == result.getType();
884 : }
885 : } // no default case, so the compiler can warn about missing cases
886 0 : NONFATAL_UNREACHABLE();
887 0 : }
888 :
889 220737 : void RPCResult::CheckInnerDoc() const
890 : {
891 220737 : if (m_type == Type::OBJ) {
892 : // May or may not be empty
893 31294 : return;
894 : }
895 : // Everything else must either be empty or not
896 189443 : const bool inner_needed{m_type == Type::ARR || m_type == Type::ARR_FIXED || m_type == Type::OBJ_DYN};
897 189443 : CHECK_NONFATAL(inner_needed != m_inner.empty());
898 220737 : }
899 :
900 10 : std::string RPCArg::ToStringObj(const bool oneline) const
901 : {
902 10 : std::string res;
903 10 : res += "\"";
904 10 : res += GetFirstName();
905 10 : if (oneline) {
906 5 : res += "\":";
907 5 : } else {
908 5 : res += "\": ";
909 : }
910 10 : switch (m_type) {
911 : case Type::STR:
912 0 : return res + "\"str\"";
913 : case Type::STR_HEX:
914 4 : return res + "\"hex\"";
915 : case Type::NUM:
916 4 : return res + "n";
917 : case Type::RANGE:
918 0 : return res + "n or [n,n]";
919 : case Type::AMOUNT:
920 2 : return res + "amount";
921 : case Type::BOOL:
922 0 : return res + "bool";
923 : case Type::ARR:
924 0 : res += "[";
925 0 : for (const auto& i : m_inner) {
926 0 : res += i.ToString(oneline) + ",";
927 : }
928 0 : return res + "...]";
929 : case Type::OBJ:
930 : case Type::OBJ_USER_KEYS:
931 : // Currently unused, so avoid writing dead code
932 0 : NONFATAL_UNREACHABLE();
933 : } // no default case, so the compiler can warn about missing cases
934 0 : NONFATAL_UNREACHABLE();
935 10 : }
936 :
937 25 : std::string RPCArg::ToString(const bool oneline) const
938 : {
939 25 : if (oneline && !m_oneline_description.empty()) return m_oneline_description;
940 :
941 25 : switch (m_type) {
942 : case Type::STR_HEX:
943 : case Type::STR: {
944 11 : return "\"" + GetFirstName() + "\"";
945 : }
946 : case Type::NUM:
947 : case Type::RANGE:
948 : case Type::AMOUNT:
949 : case Type::BOOL: {
950 7 : return GetFirstName();
951 : }
952 : case Type::OBJ:
953 : case Type::OBJ_USER_KEYS: {
954 8 : const std::string res = Join(m_inner, ",", [&](const RPCArg& i) { return i.ToStringObj(oneline); });
955 3 : if (m_type == Type::OBJ) {
956 2 : return "{" + res + "}";
957 : } else {
958 1 : return "{" + res + ",...}";
959 : }
960 3 : }
961 : case Type::ARR: {
962 4 : std::string res;
963 9 : for (const auto& i : m_inner) {
964 5 : res += i.ToString(oneline) + ",";
965 : }
966 4 : return "[" + res + "...]";
967 4 : }
968 : } // no default case, so the compiler can warn about missing cases
969 0 : NONFATAL_UNREACHABLE();
970 25 : }
971 :
972 0 : static std::pair<int64_t, int64_t> ParseRange(const UniValue& value)
973 : {
974 0 : if (value.isNum()) {
975 0 : return {0, value.getInt<int64_t>()};
976 : }
977 0 : if (value.isArray() && value.size() == 2 && value[0].isNum() && value[1].isNum()) {
978 0 : int64_t low = value[0].getInt<int64_t>();
979 0 : int64_t high = value[1].getInt<int64_t>();
980 0 : if (low > high) throw JSONRPCError(RPC_INVALID_PARAMETER, "Range specified as [begin,end] must not have begin after end");
981 0 : return {low, high};
982 : }
983 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Range must be specified as end or as [begin,end]");
984 0 : }
985 :
986 0 : std::pair<int64_t, int64_t> ParseDescriptorRange(const UniValue& value)
987 : {
988 : int64_t low, high;
989 0 : std::tie(low, high) = ParseRange(value);
990 0 : if (low < 0) {
991 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Range should be greater or equal than 0");
992 : }
993 0 : if ((high >> 31) != 0) {
994 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "End of range is too high");
995 : }
996 0 : if (high >= low + 1000000) {
997 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Range is too large");
998 : }
999 0 : return {low, high};
1000 0 : }
1001 :
1002 0 : RPCErrorCode RPCErrorFromTransactionError(TransactionError terr)
1003 : {
1004 0 : switch (terr) {
1005 : case TransactionError::MEMPOOL_REJECTED:
1006 0 : return RPC_TRANSACTION_REJECTED;
1007 : case TransactionError::ALREADY_IN_CHAIN:
1008 0 : return RPC_TRANSACTION_ALREADY_IN_CHAIN;
1009 : case TransactionError::P2P_DISABLED:
1010 0 : return RPC_CLIENT_P2P_DISABLED;
1011 : case TransactionError::INVALID_PSBT:
1012 : case TransactionError::PSBT_MISMATCH:
1013 0 : return RPC_INVALID_PARAMETER;
1014 : case TransactionError::SIGHASH_MISMATCH:
1015 0 : return RPC_DESERIALIZATION_ERROR;
1016 0 : default: break;
1017 : }
1018 0 : return RPC_TRANSACTION_ERROR;
1019 0 : }
1020 :
1021 0 : UniValue JSONRPCTransactionError(TransactionError terr, const std::string& err_string)
1022 : {
1023 0 : if (err_string.length() > 0) {
1024 0 : return JSONRPCError(RPCErrorFromTransactionError(terr), err_string);
1025 : } else {
1026 0 : return JSONRPCError(RPCErrorFromTransactionError(terr), TransactionErrorString(terr).original);
1027 : }
1028 0 : }
1029 :
1030 0 : std::vector<CScript> EvalDescriptorStringOrObject(const UniValue& scanobject, FlatSigningProvider& provider)
1031 : {
1032 0 : std::string desc_str;
1033 0 : std::pair<int64_t, int64_t> range = {0, 1000};
1034 0 : if (scanobject.isStr()) {
1035 0 : desc_str = scanobject.get_str();
1036 0 : } else if (scanobject.isObject()) {
1037 0 : const UniValue& desc_uni{scanobject.find_value("desc")};
1038 0 : if (desc_uni.isNull()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Descriptor needs to be provided in scan object");
1039 0 : desc_str = desc_uni.get_str();
1040 0 : const UniValue& range_uni{scanobject.find_value("range")};
1041 0 : if (!range_uni.isNull()) {
1042 0 : range = ParseDescriptorRange(range_uni);
1043 0 : }
1044 0 : } else {
1045 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Scan object needs to be either a string or an object");
1046 : }
1047 :
1048 0 : std::string error;
1049 0 : auto desc = Parse(desc_str, provider, error);
1050 0 : if (!desc) {
1051 0 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error);
1052 : }
1053 0 : if (!desc->IsRange()) {
1054 0 : range.first = 0;
1055 0 : range.second = 0;
1056 0 : }
1057 0 : std::vector<CScript> ret;
1058 0 : for (int i = range.first; i <= range.second; ++i) {
1059 0 : std::vector<CScript> scripts;
1060 0 : if (!desc->Expand(i, provider, scripts, provider)) {
1061 0 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Cannot derive script without private keys: '%s'", desc_str));
1062 : }
1063 0 : std::move(scripts.begin(), scripts.end(), std::back_inserter(ret));
1064 0 : }
1065 0 : return ret;
1066 0 : }
|