util.cpp raw
1 // Copyright (c) 2017-2022 The Limenka 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 <limenka-build-config.h> // IWYU pragma: keep
6
7 #include <chain.h>
8 #include <clientversion.h>
9 #include <common/args.h>
10 #include <common/messages.h>
11 #include <common/types.h>
12 #include <consensus/amount.h>
13 #include <core_io.h>
14 #include <key_io.h>
15 #include <node/types.h>
16 #include <outputtype.h>
17 #include <pow.h>
18 #include <rpc/util.h>
19 #include <script/descriptor.h>
20 #include <script/interpreter.h>
21 #include <script/signingprovider.h>
22 #include <script/solver.h>
23 #include <tinyformat.h>
24 #include <uint256.h>
25 #include <univalue.h>
26 #include <util/check.h>
27 #include <util/result.h>
28 #include <util/strencodings.h>
29 #include <util/string.h>
30 #include <util/translation.h>
31
32 #include <algorithm>
33 #include <iterator>
34 #include <string_view>
35 #include <tuple>
36 #include <utility>
37
38 using common::PSBTError;
39 using common::PSBTErrorString;
40 using common::TransactionErrorString;
41 using node::TransactionError;
42 using util::Join;
43 using util::SplitString;
44 using util::TrimString;
45
46 const std::string UNIX_EPOCH_TIME = "UNIX epoch time";
47 const std::string EXAMPLE_ADDRESS[2] = {"bc1q09vm5lfy0j5reeulh4x5752q25uqqvz34hufdl", "bc1q02ad21edsxd23d32dfgqqsz4vv4nmtfzuklhy3"};
48
49 std::string GetAllOutputTypes()
50 {
51 std::vector<std::string> ret;
52 using U = std::underlying_type<TxoutType>::type;
53 for (U i = (U)TxoutType::NONSTANDARD; i <= (U)TxoutType::WITNESS_UNKNOWN; ++i) {
54 ret.emplace_back(GetTxnOutputType(static_cast<TxoutType>(i)));
55 }
56 return Join(ret, ", ");
57 }
58
59 void RPCTypeCheckObj(const UniValue& o,
60 const std::map<std::string, UniValueType>& typesExpected,
61 bool fAllowNull,
62 bool fStrict)
63 {
64 for (const auto& t : typesExpected) {
65 const UniValue& v = o.find_value(t.first);
66 if (!fAllowNull && v.isNull())
67 throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first));
68
69 if (!(t.second.typeAny || v.type() == t.second.type || (fAllowNull && v.isNull())))
70 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 if (fStrict)
74 {
75 for (const std::string& k : o.getKeys())
76 {
77 if (typesExpected.count(k) == 0)
78 {
79 std::string err = strprintf("Unexpected key %s", k);
80 throw JSONRPCError(RPC_TYPE_ERROR, err);
81 }
82 }
83 }
84 }
85
86 int ParseVerbosity(const UniValue& arg, int default_verbosity, bool allow_bool)
87 {
88 if (!arg.isNull()) {
89 if (arg.isBool()) {
90 if (!allow_bool) {
91 throw JSONRPCError(RPC_TYPE_ERROR, "Verbosity was boolean but only integer allowed");
92 }
93 return arg.get_bool(); // true = 1
94 } else {
95 return arg.getInt<int>();
96 }
97 }
98 return default_verbosity;
99 }
100
101 CAmount AmountFromValue(const UniValue& value, int decimals)
102 {
103 if (!value.isNum() && !value.isStr())
104 throw JSONRPCError(RPC_TYPE_ERROR, "Amount is not a number or string");
105 int64_t amount_i64;
106 if (!ParseFixedPoint(value.getValStr(), decimals, &amount_i64))
107 throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
108 CAmount amount{amount_i64};
109 if (!MoneyRange(amount))
110 throw JSONRPCError(RPC_TYPE_ERROR, "Amount out of range");
111 return amount;
112 }
113
114 CFeeRate ParseFeeRate(const UniValue& json)
115 {
116 CAmount val{AmountFromValue(json)};
117 if (val >= COIN) throw JSONRPCError(RPC_INVALID_PARAMETER, "Fee rates larger than or equal to 1BTC/kvB are not accepted");
118 return CFeeRate{val};
119 }
120
121 uint256 ParseHashV(const UniValue& v, std::string_view name)
122 {
123 const std::string& strHex(v.get_str());
124 if (auto rv{uint256::FromHex(strHex)}) return *rv;
125 if (auto expected_len{uint256::size() * 2}; strHex.length() != expected_len) {
126 throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("%s must be of length %d (not %d, for '%s')", name, expected_len, strHex.length(), strHex));
127 }
128 throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("%s must be hexadecimal string (not '%s')", name, strHex));
129 }
130 uint256 ParseHashO(const UniValue& o, std::string_view strKey)
131 {
132 return ParseHashV(o.find_value(strKey), strKey);
133 }
134 std::vector<unsigned char> ParseHexV(const UniValue& v, std::string_view name)
135 {
136 std::string strHex;
137 if (v.isStr())
138 strHex = v.get_str();
139 if (!IsHex(strHex))
140 throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("%s must be hexadecimal string (not '%s')", name, strHex));
141 return ParseHex(strHex);
142 }
143 std::vector<unsigned char> ParseHexO(const UniValue& o, std::string_view strKey)
144 {
145 return ParseHexV(o.find_value(strKey), strKey);
146 }
147
148 namespace {
149
150 /**
151 * Quote an argument for shell.
152 *
153 * @note This is intended for help, not for security-sensitive purposes.
154 */
155 std::string ShellQuote(const std::string& s)
156 {
157 std::string result;
158 result.reserve(s.size() * 2);
159 for (const char ch: s) {
160 if (ch == '\'') {
161 result += "'\''";
162 } else {
163 result += ch;
164 }
165 }
166 return "'" + result + "'";
167 }
168
169 /**
170 * Shell-quotes the argument if it needs quoting, else returns it literally, to save typing.
171 *
172 * @note This is intended for help, not for security-sensitive purposes.
173 */
174 std::string ShellQuoteIfNeeded(const std::string& s)
175 {
176 for (const char ch: s) {
177 if (ch == ' ' || ch == '\'' || ch == '"') {
178 return ShellQuote(s);
179 }
180 }
181
182 return s;
183 }
184
185 }
186
187 std::string HelpExampleCli(const std::string& methodname, const std::string& args)
188 {
189 return "> limenka-cli " + methodname + " " + args + "\n";
190 }
191
192 std::string HelpExampleCliNamed(const std::string& methodname, const RPCArgList& args)
193 {
194 std::string result = "> limenka-cli -named " + methodname;
195 for (const auto& argpair: args) {
196 const auto& value = argpair.second.isStr()
197 ? argpair.second.get_str()
198 : argpair.second.write();
199 result += " " + argpair.first + "=" + ShellQuoteIfNeeded(value);
200 }
201 result += "\n";
202 return result;
203 }
204
205 std::string HelpExampleRpc(const std::string& methodname, const std::string& args)
206 {
207 return "> curl --user myusername --data-binary '{\"jsonrpc\": \"2.0\", \"id\": \"curltest\", "
208 "\"method\": \"" + methodname + "\", \"params\": [" + args + "]}' -H 'content-type: application/json' http://127.0.0.1:8332/\n";
209 }
210
211 std::string HelpExampleRpcNamed(const std::string& methodname, const RPCArgList& args)
212 {
213 UniValue params(UniValue::VOBJ);
214 for (const auto& param: args) {
215 params.pushKV(param.first, param.second);
216 }
217
218 return "> curl --user myusername --data-binary '{\"jsonrpc\": \"2.0\", \"id\": \"curltest\", "
219 "\"method\": \"" + methodname + "\", \"params\": " + params.write() + "}' -H 'content-type: application/json' http://127.0.0.1:8332/\n";
220 }
221
222 // Converts a hex string to a public key if possible
223 CPubKey HexToPubKey(const std::string& hex_in)
224 {
225 if (!IsHex(hex_in)) {
226 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey \"" + hex_in + "\" must be a hex string");
227 }
228 if (hex_in.length() != 66 && hex_in.length() != 130) {
229 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey \"" + hex_in + "\" must have a length of either 33 or 65 bytes");
230 }
231 CPubKey vchPubKey(ParseHex(hex_in));
232 if (!vchPubKey.IsFullyValid()) {
233 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey \"" + hex_in + "\" must be cryptographically valid.");
234 }
235 return vchPubKey;
236 }
237
238 // Retrieves a public key for an address from the given FillableSigningProvider
239 CPubKey AddrToPubKey(const FillableSigningProvider& keystore, const std::string& addr_in)
240 {
241 CTxDestination dest = DecodeDestination(addr_in);
242 if (!IsValidDestination(dest)) {
243 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address: " + addr_in);
244 }
245 CKeyID key = GetKeyForDestination(keystore, dest);
246 if (key.IsNull()) {
247 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("'%s' does not refer to a key", addr_in));
248 }
249 CPubKey vchPubKey;
250 if (!keystore.GetPubKey(key, vchPubKey)) {
251 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("no full public key for address %s", addr_in));
252 }
253 if (!vchPubKey.IsFullyValid()) {
254 throw JSONRPCError(RPC_INTERNAL_ERROR, "Wallet contains an invalid public key");
255 }
256 return vchPubKey;
257 }
258
259 // Creates a multisig address from a given list of public keys, number of signatures required, and the address type
260 CTxDestination AddAndGetMultisigDestination(const int required, const std::vector<CPubKey>& pubkeys, OutputType type, FlatSigningProvider& keystore, CScript& script_out, bool sort)
261 {
262 // Gather public keys
263 if (required < 1) {
264 throw JSONRPCError(RPC_INVALID_PARAMETER, "a multisignature address must require at least one key to redeem");
265 }
266 if ((int)pubkeys.size() < required) {
267 throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("not enough keys supplied (got %u keys, but need at least %d to redeem)", pubkeys.size(), required));
268 }
269 if (pubkeys.size() > MAX_PUBKEYS_PER_MULTISIG) {
270 throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Number of keys involved in the multisignature address creation > %d\nReduce the number", MAX_PUBKEYS_PER_MULTISIG));
271 }
272
273 script_out = GetScriptForMultisig(required, pubkeys, sort);
274
275 // Check if any keys are uncompressed. If so, the type is legacy
276 for (const CPubKey& pk : pubkeys) {
277 if (!pk.IsCompressed()) {
278 type = OutputType::LEGACY;
279 break;
280 }
281 }
282
283 if (type == OutputType::LEGACY && script_out.size() > MAX_SCRIPT_ELEMENT_SIZE) {
284 throw JSONRPCError(RPC_INVALID_PARAMETER, (strprintf("redeemScript exceeds size limit: %d > %d", script_out.size(), MAX_SCRIPT_ELEMENT_SIZE)));
285 }
286
287 // Make the address
288 CTxDestination dest = AddAndGetDestinationForScript(keystore, script_out, type);
289
290 return dest;
291 }
292
293 class DescribeAddressVisitor
294 {
295 public:
296 explicit DescribeAddressVisitor() = default;
297
298 UniValue operator()(const CNoDestination& dest) const
299 {
300 return UniValue(UniValue::VOBJ);
301 }
302
303 UniValue operator()(const PubKeyDestination& dest) const
304 {
305 return UniValue(UniValue::VOBJ);
306 }
307
308 UniValue operator()(const PKHash& keyID) const
309 {
310 UniValue obj(UniValue::VOBJ);
311 obj.pushKV("isscript", false);
312 obj.pushKV("iswitness", false);
313 return obj;
314 }
315
316 UniValue operator()(const ScriptHash& scriptID) const
317 {
318 UniValue obj(UniValue::VOBJ);
319 obj.pushKV("isscript", true);
320 obj.pushKV("iswitness", false);
321 return obj;
322 }
323
324 UniValue operator()(const WitnessV0KeyHash& id) const
325 {
326 UniValue obj(UniValue::VOBJ);
327 obj.pushKV("isscript", false);
328 obj.pushKV("iswitness", true);
329 obj.pushKV("witness_version", 0);
330 obj.pushKV("witness_program", HexStr(id));
331 return obj;
332 }
333
334 UniValue operator()(const WitnessV0ScriptHash& id) const
335 {
336 UniValue obj(UniValue::VOBJ);
337 obj.pushKV("isscript", true);
338 obj.pushKV("iswitness", true);
339 obj.pushKV("witness_version", 0);
340 obj.pushKV("witness_program", HexStr(id));
341 return obj;
342 }
343
344 UniValue operator()(const WitnessV1Taproot& tap) const
345 {
346 UniValue obj(UniValue::VOBJ);
347 obj.pushKV("isscript", true);
348 obj.pushKV("iswitness", true);
349 obj.pushKV("witness_version", 1);
350 obj.pushKV("witness_program", HexStr(tap));
351 return obj;
352 }
353
354 UniValue operator()(const WitnessV3SpkHash& id) const
355 {
356 UniValue obj(UniValue::VOBJ);
357 obj.pushKV("isscript", true);
358 obj.pushKV("iswitness", true);
359 obj.pushKV("witness_version", 3);
360 obj.pushKV("witness_program", HexStr(id));
361 return obj;
362 }
363
364 UniValue operator()(const PayToAnchor& anchor) const
365 {
366 UniValue obj(UniValue::VOBJ);
367 obj.pushKV("isscript", true);
368 obj.pushKV("iswitness", true);
369 return obj;
370 }
371
372 UniValue operator()(const WitnessV4StealthAddress& id) const
373 {
374 UniValue obj(UniValue::VOBJ);
375 obj.pushKV("isscript", false);
376 obj.pushKV("iswitness", true);
377 obj.pushKV("witness_version", 4);
378 obj.pushKV("view_key", HexStr(id.view));
379 obj.pushKV("spend_key", HexStr(id.spend));
380 return obj;
381 }
382
383 UniValue operator()(const WitnessUnknown& id) const
384 {
385 UniValue obj(UniValue::VOBJ);
386 obj.pushKV("iswitness", true);
387 obj.pushKV("witness_version", id.GetWitnessVersion());
388 obj.pushKV("witness_program", HexStr(id.GetWitnessProgram()));
389 return obj;
390 }
391 };
392
393 UniValue DescribeAddress(const CTxDestination& dest)
394 {
395 return std::visit(DescribeAddressVisitor(), dest);
396 }
397
398 /**
399 * Returns a sighash value corresponding to the passed in argument.
400 *
401 * @pre The sighash argument should be string or null.
402 */
403 int ParseSighashString(const UniValue& sighash)
404 {
405 if (sighash.isNull()) {
406 return SIGHASH_DEFAULT;
407 }
408 const auto result{SighashFromStr(sighash.get_str())};
409 if (!result) {
410 throw JSONRPCError(RPC_INVALID_PARAMETER, util::ErrorString(result).original);
411 }
412 return result.value();
413 }
414
415 unsigned int ParseConfirmTarget(const UniValue& value, unsigned int max_target)
416 {
417 const int target{value.getInt<int>()};
418 const unsigned int unsigned_target{static_cast<unsigned int>(target)};
419 if (target < 1 || unsigned_target > max_target) {
420 throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid conf_target, must be between %u and %u", 1, max_target));
421 }
422 return unsigned_target;
423 }
424
425 RPCErrorCode RPCErrorFromPSBTError(PSBTError err)
426 {
427 switch (err) {
428 case PSBTError::UNSUPPORTED:
429 return RPC_INVALID_PARAMETER;
430 case PSBTError::SIGHASH_MISMATCH:
431 return RPC_DESERIALIZATION_ERROR;
432 default: break;
433 }
434 return RPC_TRANSACTION_ERROR;
435 }
436
437 RPCErrorCode RPCErrorFromTransactionError(TransactionError terr)
438 {
439 switch (terr) {
440 case TransactionError::MEMPOOL_REJECTED:
441 return RPC_TRANSACTION_REJECTED;
442 case TransactionError::ALREADY_IN_UTXO_SET:
443 return RPC_VERIFY_ALREADY_IN_UTXO_SET;
444 default: break;
445 }
446 return RPC_TRANSACTION_ERROR;
447 }
448
449 UniValue JSONRPCPSBTError(PSBTError err)
450 {
451 return JSONRPCError(RPCErrorFromPSBTError(err), PSBTErrorString(err).original);
452 }
453
454 UniValue JSONRPCTransactionError(TransactionError terr, const std::string& err_string)
455 {
456 if (err_string.length() > 0) {
457 return JSONRPCError(RPCErrorFromTransactionError(terr), err_string);
458 } else {
459 return JSONRPCError(RPCErrorFromTransactionError(terr), TransactionErrorString(terr).original);
460 }
461 }
462
463 /**
464 * A pair of strings that can be aligned (through padding) with other Sections
465 * later on
466 */
467 struct Section {
468 Section(const std::string& left, const std::string& right)
469 : m_left{left}, m_right{right} {}
470 std::string m_left;
471 const std::string m_right;
472 };
473
474 /**
475 * Keeps track of RPCArgs by transforming them into sections for the purpose
476 * of serializing everything to a single string
477 */
478 struct Sections {
479 std::vector<Section> m_sections;
480 size_t m_max_pad{0};
481
482 void PushSection(const Section& s)
483 {
484 m_max_pad = std::max(m_max_pad, s.m_left.size());
485 m_sections.push_back(s);
486 }
487
488 /**
489 * Recursive helper to translate an RPCArg into sections
490 */
491 // NOLINTNEXTLINE(misc-no-recursion)
492 void Push(const RPCArg& arg, const size_t current_indent = 5, const OuterType outer_type = OuterType::NONE)
493 {
494 const auto indent = std::string(current_indent, ' ');
495 const auto indent_next = std::string(current_indent + 2, ' ');
496 const bool push_name{outer_type == OuterType::OBJ}; // Dictionary keys must have a name
497 const bool is_top_level_arg{outer_type == OuterType::NONE}; // True on the first recursion
498
499 switch (arg.m_type) {
500 case RPCArg::Type::STR_HEX:
501 case RPCArg::Type::STR:
502 case RPCArg::Type::NUM:
503 case RPCArg::Type::AMOUNT:
504 case RPCArg::Type::RANGE:
505 case RPCArg::Type::BOOL:
506 case RPCArg::Type::OBJ_NAMED_PARAMS: {
507 if (is_top_level_arg) return; // Nothing more to do for non-recursive types on first recursion
508 auto left = indent;
509 if (arg.m_opts.type_str.size() != 0 && push_name) {
510 left += "\"" + arg.GetName() + "\": " + arg.m_opts.type_str.at(0);
511 } else {
512 left += push_name ? arg.ToStringObj(/*oneline=*/false) : arg.ToString(/*oneline=*/false);
513 }
514 left += ",";
515 PushSection({left, arg.ToDescriptionString(/*is_named_arg=*/push_name)});
516 break;
517 }
518 case RPCArg::Type::OBJ:
519 case RPCArg::Type::OBJ_USER_KEYS: {
520 const auto right = is_top_level_arg ? "" : arg.ToDescriptionString(/*is_named_arg=*/push_name);
521 PushSection({indent + (push_name ? "\"" + arg.GetName() + "\": " : "") + "{", right});
522 for (const auto& arg_inner : arg.m_inner) {
523 Push(arg_inner, current_indent + 2, OuterType::OBJ);
524 }
525 if (arg.m_type != RPCArg::Type::OBJ) {
526 PushSection({indent_next + "...", ""});
527 }
528 PushSection({indent + "}" + (is_top_level_arg ? "" : ","), ""});
529 break;
530 }
531 case RPCArg::Type::ARR: {
532 auto left = indent;
533 left += push_name ? "\"" + arg.GetName() + "\": " : "";
534 left += "[";
535 const auto right = is_top_level_arg ? "" : arg.ToDescriptionString(/*is_named_arg=*/push_name);
536 PushSection({left, right});
537 for (const auto& arg_inner : arg.m_inner) {
538 Push(arg_inner, current_indent + 2, OuterType::ARR);
539 }
540 PushSection({indent_next + "...", ""});
541 PushSection({indent + "]" + (is_top_level_arg ? "" : ","), ""});
542 break;
543 }
544 } // no default case, so the compiler can warn about missing cases
545 }
546
547 /**
548 * Concatenate all sections with proper padding
549 */
550 std::string ToString() const
551 {
552 std::string ret;
553 const size_t pad = m_max_pad + 4;
554 for (const auto& s : m_sections) {
555 // The left part of a section is assumed to be a single line, usually it is the name of the JSON struct or a
556 // brace like {, }, [, or ]
557 CHECK_NONFATAL(s.m_left.find('\n') == std::string::npos);
558 if (s.m_right.empty()) {
559 ret += s.m_left;
560 ret += "\n";
561 continue;
562 }
563
564 std::string left = s.m_left;
565 left.resize(pad, ' ');
566 ret += left;
567
568 // Properly pad after newlines
569 std::string right;
570 size_t begin = 0;
571 size_t new_line_pos = s.m_right.find_first_of('\n');
572 while (true) {
573 right += s.m_right.substr(begin, new_line_pos - begin);
574 if (new_line_pos == std::string::npos) {
575 break; //No new line
576 }
577 right += "\n" + std::string(pad, ' ');
578 begin = s.m_right.find_first_not_of(' ', new_line_pos + 1);
579 if (begin == std::string::npos) {
580 break; // Empty line
581 }
582 new_line_pos = s.m_right.find_first_of('\n', begin + 1);
583 }
584 ret += right;
585 ret += "\n";
586 }
587 return ret;
588 }
589 };
590
591 RPCHelpMan::RPCHelpMan(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples)
592 : RPCHelpMan{std::move(name), std::move(description), std::move(args), std::move(results), std::move(examples), nullptr} {}
593
594 RPCHelpMan::RPCHelpMan(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples, RPCMethodImpl fun)
595 : m_name{std::move(name)},
596 m_fun{std::move(fun)},
597 m_description{std::move(description)},
598 m_args{std::move(args)},
599 m_results{std::move(results)},
600 m_examples{std::move(examples)}
601 {
602 // Map of parameter names and types just used to check whether the names are
603 // unique. Parameter names always need to be unique, with the exception that
604 // there can be pairs of POSITIONAL and NAMED parameters with the same name.
605 enum ParamType { POSITIONAL = 1, NAMED = 2, NAMED_ONLY = 4 };
606 std::map<std::string, int> param_names;
607
608 for (const auto& arg : m_args) {
609 std::vector<std::string> names = SplitString(arg.m_names, '|');
610 // Should have unique named arguments
611 for (const std::string& name : names) {
612 auto& param_type = param_names[name];
613 CHECK_NONFATAL(!(param_type & POSITIONAL));
614 CHECK_NONFATAL(!(param_type & NAMED_ONLY));
615 param_type |= POSITIONAL;
616 }
617 if (arg.m_type == RPCArg::Type::OBJ_NAMED_PARAMS) {
618 for (const auto& inner : arg.m_inner) {
619 std::vector<std::string> inner_names = SplitString(inner.m_names, '|');
620 for (const std::string& inner_name : inner_names) {
621 auto& param_type = param_names[inner_name];
622 CHECK_NONFATAL(!(param_type & POSITIONAL) || inner.m_opts.also_positional);
623 CHECK_NONFATAL(!(param_type & NAMED));
624 CHECK_NONFATAL(!(param_type & NAMED_ONLY));
625 param_type |= inner.m_opts.also_positional ? NAMED : NAMED_ONLY;
626 }
627 }
628 }
629 // Default value type should match argument type only when defined
630 if (arg.m_fallback.index() == 2) {
631 const RPCArg::Type type = arg.m_type;
632 switch (std::get<RPCArg::Default>(arg.m_fallback).getType()) {
633 case UniValue::VOBJ:
634 CHECK_NONFATAL(type == RPCArg::Type::OBJ);
635 break;
636 case UniValue::VARR:
637 CHECK_NONFATAL(type == RPCArg::Type::ARR);
638 break;
639 case UniValue::VSTR:
640 CHECK_NONFATAL(type == RPCArg::Type::STR || type == RPCArg::Type::STR_HEX || type == RPCArg::Type::AMOUNT);
641 break;
642 case UniValue::VNUM:
643 CHECK_NONFATAL(type == RPCArg::Type::NUM || type == RPCArg::Type::AMOUNT || type == RPCArg::Type::RANGE);
644 break;
645 case UniValue::VBOOL:
646 CHECK_NONFATAL(type == RPCArg::Type::BOOL);
647 break;
648 case UniValue::VNULL:
649 // Null values are accepted in all arguments
650 break;
651 default:
652 NONFATAL_UNREACHABLE();
653 break;
654 }
655 }
656 }
657 }
658
659 std::string RPCResults::ToDescriptionString() const
660 {
661 std::string result;
662 for (const auto& r : m_results) {
663 if (r.m_type == RPCResult::Type::ANY) continue; // for testing only
664 if (r.m_cond.empty()) {
665 result += "\nResult:\n";
666 } else {
667 result += "\nResult (" + r.m_cond + "):\n";
668 }
669 Sections sections;
670 r.ToSections(sections);
671 result += sections.ToString();
672 }
673 return result;
674 }
675
676 std::string RPCExamples::ToDescriptionString() const
677 {
678 return m_examples.empty() ? m_examples : "\nExamples:\n" + m_examples;
679 }
680
681 UniValue RPCHelpMan::HandleRequest(const JSONRPCRequest& request) const
682 {
683 if (request.mode == JSONRPCRequest::GET_ARGS) {
684 return GetArgMap();
685 }
686 /*
687 * Check if the given request is valid according to this command or if
688 * the user is asking for help information, and throw help when appropriate.
689 */
690 if (request.mode == JSONRPCRequest::GET_HELP || !IsValidNumArgs(request.params.size())) {
691 std::string help_format = "default";
692 if (request.strMethod == "format") {
693 help_format = request.params[1].get_str();
694 }
695 throw std::runtime_error(ToString(help_format));
696 }
697 UniValue arg_mismatch{UniValue::VOBJ};
698 for (size_t i{0}; i < m_args.size(); ++i) {
699 const auto& arg{m_args.at(i)};
700 UniValue match{arg.MatchesType(request.params[i])};
701 if (!match.isTrue()) {
702 arg_mismatch.pushKV(strprintf("Position %s (%s)", i + 1, arg.m_names), std::move(match));
703 }
704 }
705 if (!arg_mismatch.empty()) {
706 throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Wrong type passed:\n%s", arg_mismatch.write(4)));
707 }
708 CHECK_NONFATAL(m_req == nullptr);
709 m_req = &request;
710 UniValue ret = m_fun(*this, request);
711 m_req = nullptr;
712 if (gArgs.GetBoolArg("-rpcdoccheck", DEFAULT_RPC_DOC_CHECK)) {
713 UniValue mismatch{UniValue::VARR};
714 for (const auto& res : m_results.m_results) {
715 UniValue match{res.MatchesType(ret)};
716 if (match.isTrue()) {
717 mismatch.setNull();
718 break;
719 }
720 mismatch.push_back(std::move(match));
721 }
722 if (!mismatch.isNull()) {
723 std::string explain{
724 mismatch.empty() ? "no possible results defined" :
725 mismatch.size() == 1 ? mismatch[0].write(4) :
726 mismatch.write(4)};
727 throw std::runtime_error{
728 strprintf("Internal bug detected: RPC call \"%s\" returned incorrect type:\n%s\n%s %s\nPlease report this issue here: %s\n",
729 m_name, explain,
730 CLIENT_NAME, FormatFullVersion(),
731 CLIENT_BUGREPORT)};
732 }
733 }
734 return ret;
735 }
736
737 using CheckFn = void(const RPCArg&);
738 static const UniValue* DetailMaybeArg(CheckFn* check, const std::vector<RPCArg>& params, const JSONRPCRequest* req, size_t i)
739 {
740 CHECK_NONFATAL(i < params.size());
741 const UniValue& arg{CHECK_NONFATAL(req)->params[i]};
742 const RPCArg& param{params.at(i)};
743 if (check) check(param);
744
745 if (!arg.isNull()) return &arg;
746 if (!std::holds_alternative<RPCArg::Default>(param.m_fallback)) return nullptr;
747 return &std::get<RPCArg::Default>(param.m_fallback);
748 }
749
750 static void CheckRequiredOrDefault(const RPCArg& param)
751 {
752 // Must use `Arg<Type>(key)` to get the argument or its default value.
753 const bool required{
754 std::holds_alternative<RPCArg::Optional>(param.m_fallback) && RPCArg::Optional::NO == std::get<RPCArg::Optional>(param.m_fallback),
755 };
756 CHECK_NONFATAL(required || std::holds_alternative<RPCArg::Default>(param.m_fallback));
757 }
758
759 #define TMPL_INST(check_param, ret_type, return_code) \
760 template <> \
761 ret_type RPCHelpMan::ArgValue<ret_type>(size_t i) const \
762 { \
763 const UniValue* maybe_arg{ \
764 DetailMaybeArg(check_param, m_args, m_req, i), \
765 }; \
766 return return_code \
767 } \
768 void force_semicolon(ret_type)
769
770 // Optional arg (without default). Can also be called on required args, if needed.
771 TMPL_INST(nullptr, const UniValue*, maybe_arg;);
772 TMPL_INST(nullptr, std::optional<double>, maybe_arg ? std::optional{maybe_arg->get_real()} : std::nullopt;);
773 TMPL_INST(nullptr, std::optional<bool>, maybe_arg ? std::optional{maybe_arg->get_bool()} : std::nullopt;);
774 TMPL_INST(nullptr, const std::string*, maybe_arg ? &maybe_arg->get_str() : nullptr;);
775
776 // Required arg or optional arg with default value.
777 TMPL_INST(CheckRequiredOrDefault, const UniValue&, *CHECK_NONFATAL(maybe_arg););
778 TMPL_INST(CheckRequiredOrDefault, bool, CHECK_NONFATAL(maybe_arg)->get_bool(););
779 TMPL_INST(CheckRequiredOrDefault, int, CHECK_NONFATAL(maybe_arg)->getInt<int>(););
780 TMPL_INST(CheckRequiredOrDefault, uint64_t, CHECK_NONFATAL(maybe_arg)->getInt<uint64_t>(););
781 TMPL_INST(CheckRequiredOrDefault, const std::string&, CHECK_NONFATAL(maybe_arg)->get_str(););
782
783 bool RPCHelpMan::IsValidNumArgs(size_t num_args) const
784 {
785 size_t num_required_args = 0;
786 for (size_t n = m_args.size(); n > 0; --n) {
787 if (!m_args.at(n - 1).IsOptional()) {
788 num_required_args = n;
789 break;
790 }
791 }
792 return num_required_args <= num_args && num_args <= m_args.size();
793 }
794
795 std::vector<std::pair<std::string, bool>> RPCHelpMan::GetArgNames() const
796 {
797 std::vector<std::pair<std::string, bool>> ret;
798 ret.reserve(m_args.size());
799 for (const auto& arg : m_args) {
800 if (arg.m_type == RPCArg::Type::OBJ_NAMED_PARAMS) {
801 for (const auto& inner : arg.m_inner) {
802 ret.emplace_back(inner.m_names, /*named_only=*/true);
803 }
804 }
805 ret.emplace_back(arg.m_names, /*named_only=*/false);
806 }
807 return ret;
808 }
809
810 size_t RPCHelpMan::GetParamIndex(std::string_view key) const
811 {
812 auto it{std::find_if(
813 m_args.begin(), m_args.end(), [&key](const auto& arg) { return arg.GetFirstName() == key;}
814 )};
815
816 CHECK_NONFATAL(it != m_args.end()); // TODO: ideally this is checked at compile time
817 return std::distance(m_args.begin(), it);
818 }
819
820 std::string RPCHelpMan::ToString() const
821 {
822 std::string ret;
823
824 // Oneline summary
825 ret += m_name;
826 bool was_optional{false};
827 for (const auto& arg : m_args) {
828 if (arg.m_opts.hidden) break; // Any arg that follows is also hidden
829 const bool optional = arg.IsOptional();
830 ret += " ";
831 if (optional) {
832 if (!was_optional) ret += "( ";
833 was_optional = true;
834 } else {
835 if (was_optional) ret += ") ";
836 was_optional = false;
837 }
838 ret += arg.ToString(/*oneline=*/true);
839 }
840 if (was_optional) ret += " )";
841
842 // Description
843 ret += "\n\n" + TrimString(m_description) + "\n";
844
845 // Arguments
846 Sections sections;
847 Sections named_only_sections;
848 for (size_t i{0}; i < m_args.size(); ++i) {
849 const auto& arg = m_args.at(i);
850 if (arg.m_opts.hidden) break; // Any arg that follows is also hidden
851
852 // Push named argument name and description
853 sections.m_sections.emplace_back(util::ToString(i + 1) + ". " + arg.GetFirstName(), arg.ToDescriptionString(/*is_named_arg=*/true));
854 sections.m_max_pad = std::max(sections.m_max_pad, sections.m_sections.back().m_left.size());
855
856 // Recursively push nested args
857 sections.Push(arg);
858
859 // Push named-only argument sections
860 if (arg.m_type == RPCArg::Type::OBJ_NAMED_PARAMS) {
861 for (const auto& arg_inner : arg.m_inner) {
862 named_only_sections.PushSection({arg_inner.GetFirstName(), arg_inner.ToDescriptionString(/*is_named_arg=*/true)});
863 named_only_sections.Push(arg_inner);
864 }
865 }
866 }
867
868 if (!sections.m_sections.empty()) ret += "\nArguments:\n";
869 ret += sections.ToString();
870 if (!named_only_sections.m_sections.empty()) ret += "\nNamed Arguments:\n";
871 ret += named_only_sections.ToString();
872
873 // Result
874 ret += m_results.ToDescriptionString();
875
876 // Examples
877 ret += m_examples.ToDescriptionString();
878
879 return ret;
880 }
881
882 std::string RPCHelpMan::ToStringArgsCli() const
883 {
884 std::string res;
885 for (const auto& arg : m_args) {
886 const bool is_file = ToLower(arg.m_description).find("file") != std::string::npos;
887 res += arg.m_names + ":" + (is_file ? "file" : arg.ToTypeString()) + ",";
888 }
889
890 if (res.size() > 0) {
891 res.pop_back();
892 }
893
894 return res;
895 }
896
897 std::string RPCHelpMan::ToString(const std::string& format) const
898 {
899 if (format == "default") {
900 return this->ToString();
901 }
902
903 if (format == "args_cli") {
904 return this->ToStringArgsCli();
905 }
906
907 throw std::runtime_error("unrecogonized help format");
908 }
909
910 UniValue RPCHelpMan::GetArgMap() const
911 {
912 UniValue arr{UniValue::VARR};
913
914 auto push_back_arg_info = [&arr](const std::string& rpc_name, int pos, const std::string& arg_name, const RPCArg::Type& type) {
915 UniValue map{UniValue::VARR};
916 map.push_back(rpc_name);
917 map.push_back(pos);
918 map.push_back(arg_name);
919 map.push_back(type == RPCArg::Type::STR ||
920 type == RPCArg::Type::STR_HEX);
921 arr.push_back(std::move(map));
922 };
923
924 for (int i{0}; i < int(m_args.size()); ++i) {
925 const auto& arg = m_args.at(i);
926 std::vector<std::string> arg_names = SplitString(arg.m_names, '|');
927 RPCArg::Type argtype = arg.m_type;
928 size_t arg_num = 0;
929 for (const auto& arg_name : arg_names) {
930 if (!arg.m_type_per_name.empty()) {
931 argtype = arg.m_type_per_name.at(arg_num++);
932 }
933
934 push_back_arg_info(m_name, i, arg_name, argtype);
935 if (argtype == RPCArg::Type::OBJ_NAMED_PARAMS) {
936 for (const auto& inner : arg.m_inner) {
937 std::vector<std::string> inner_names = SplitString(inner.m_names, '|');
938 for (const std::string& inner_name : inner_names) {
939 push_back_arg_info(m_name, i, inner_name, inner.m_type);
940 }
941 }
942 }
943 }
944 }
945 return arr;
946 }
947
948 static std::optional<UniValue::VType> ExpectedType(RPCArg::Type type)
949 {
950 using Type = RPCArg::Type;
951 switch (type) {
952 case Type::STR_HEX:
953 case Type::STR: {
954 return UniValue::VSTR;
955 }
956 case Type::NUM: {
957 return UniValue::VNUM;
958 }
959 case Type::AMOUNT: {
960 // VNUM or VSTR, checked inside AmountFromValue()
961 return std::nullopt;
962 }
963 case Type::RANGE: {
964 // VNUM or VARR, checked inside ParseRange()
965 return std::nullopt;
966 }
967 case Type::BOOL: {
968 return UniValue::VBOOL;
969 }
970 case Type::OBJ:
971 case Type::OBJ_NAMED_PARAMS:
972 case Type::OBJ_USER_KEYS: {
973 return UniValue::VOBJ;
974 }
975 case Type::ARR: {
976 return UniValue::VARR;
977 }
978 } // no default case, so the compiler can warn about missing cases
979 NONFATAL_UNREACHABLE();
980 }
981
982 UniValue RPCArg::MatchesType(const UniValue& request) const
983 {
984 if (m_opts.skip_type_check) return true;
985 if (IsOptional() && request.isNull()) return true;
986 for (auto type : m_type_per_name.empty() ? std::vector<RPCArg::Type>{m_type} : m_type_per_name) {
987 const auto exp_type{ExpectedType(type)};
988 if (!exp_type) return true; // nothing to check
989
990 if (*exp_type == request.getType()) {
991 return true;
992 }
993 }
994 return strprintf("JSON value of type %s is not of expected type %s", uvTypeName(request.getType()), uvTypeName(*ExpectedType(m_type)));
995 }
996
997 std::string RPCArg::GetFirstName() const
998 {
999 return m_names.substr(0, m_names.find('|'));
1000 }
1001
1002 std::string RPCArg::GetName() const
1003 {
1004 CHECK_NONFATAL(std::string::npos == m_names.find('|'));
1005 return m_names;
1006 }
1007
1008 bool RPCArg::IsOptional() const
1009 {
1010 if (m_fallback.index() != 0) {
1011 return true;
1012 } else {
1013 return RPCArg::Optional::NO != std::get<RPCArg::Optional>(m_fallback);
1014 }
1015 }
1016
1017 std::string RPCArg::ToTypeString() const
1018 {
1019 switch (m_type) {
1020 case Type::STR_HEX:
1021 case Type::STR:
1022 return "string";
1023 case Type::NUM:
1024 return "numeric";
1025 case Type::AMOUNT:
1026 return "numeric or string";
1027 case Type::RANGE:
1028 return "numeric or array";
1029 case Type::BOOL:
1030 return "boolean";
1031 case Type::OBJ:
1032 case Type::OBJ_NAMED_PARAMS:
1033 case Type::OBJ_USER_KEYS:
1034 return "json object";
1035 case Type::ARR:
1036 return"json array";
1037 } // no default case, so the compiler can warn about missing cases
1038
1039 //gcc and msvc might complain we don't return anything even if we handle all cases
1040 throw std::runtime_error("unknown argument type");
1041 }
1042
1043 std::string RPCArg::ToDescriptionString(bool is_named_arg) const
1044 {
1045 std::string ret;
1046 ret += "(";
1047 if (m_opts.type_str.size() != 0) {
1048 ret += m_opts.type_str.at(1);
1049 } else {
1050 ret += this->ToTypeString();
1051 }
1052 if (m_fallback.index() == 1) {
1053 ret += ", optional, default=" + std::get<RPCArg::DefaultHint>(m_fallback);
1054 } else if (m_fallback.index() == 2) {
1055 ret += ", optional, default=" + std::get<RPCArg::Default>(m_fallback).write();
1056 } else {
1057 switch (std::get<RPCArg::Optional>(m_fallback)) {
1058 case RPCArg::Optional::OMITTED: {
1059 if (is_named_arg) ret += ", optional"; // Default value is "null" in dicts. Otherwise,
1060 // nothing to do. Element is treated as if not present and has no default value
1061 break;
1062 }
1063 case RPCArg::Optional::NO: {
1064 ret += ", required";
1065 break;
1066 }
1067 } // no default case, so the compiler can warn about missing cases
1068 }
1069 ret += ")";
1070 if (m_type == Type::OBJ_NAMED_PARAMS) ret += " Options object that can be used to pass named arguments, listed below.";
1071 ret += m_description.empty() ? "" : " " + m_description;
1072 return ret;
1073 }
1074
1075 // NOLINTNEXTLINE(misc-no-recursion)
1076 void RPCResult::ToSections(Sections& sections, const OuterType outer_type, const int current_indent) const
1077 {
1078 // Indentation
1079 const std::string indent(current_indent, ' ');
1080 const std::string indent_next(current_indent + 2, ' ');
1081
1082 // Elements in a JSON structure (dictionary or array) are separated by a comma
1083 const std::string maybe_separator{outer_type != OuterType::NONE ? "," : ""};
1084
1085 // The key name if recursed into a dictionary
1086 const std::string maybe_key{
1087 outer_type == OuterType::OBJ ?
1088 "\"" + this->m_key_name + "\" : " :
1089 ""};
1090
1091 // Format description with type
1092 const auto Description = [&](const std::string& type) {
1093 return "(" + type + (this->m_optional ? ", optional" : "") + ")" +
1094 (this->m_description.empty() ? "" : " " + this->m_description);
1095 };
1096
1097 switch (m_type) {
1098 case Type::ELISION: {
1099 // If the inner result is empty, use three dots for elision
1100 sections.PushSection({indent + "..." + maybe_separator, m_description});
1101 return;
1102 }
1103 case Type::ANY: {
1104 NONFATAL_UNREACHABLE(); // Only for testing
1105 }
1106 case Type::NONE: {
1107 sections.PushSection({indent + "null" + maybe_separator, Description("json null")});
1108 return;
1109 }
1110 case Type::STR: {
1111 sections.PushSection({indent + maybe_key + "\"str\"" + maybe_separator, Description("string")});
1112 return;
1113 }
1114 case Type::STR_AMOUNT: {
1115 sections.PushSection({indent + maybe_key + "n" + maybe_separator, Description("numeric")});
1116 return;
1117 }
1118 case Type::STR_HEX: {
1119 sections.PushSection({indent + maybe_key + "\"hex\"" + maybe_separator, Description("string")});
1120 return;
1121 }
1122 case Type::NUM: {
1123 sections.PushSection({indent + maybe_key + "n" + maybe_separator, Description("numeric")});
1124 return;
1125 }
1126 case Type::NUM_TIME: {
1127 sections.PushSection({indent + maybe_key + "xxx" + maybe_separator, Description("numeric")});
1128 return;
1129 }
1130 case Type::BOOL: {
1131 sections.PushSection({indent + maybe_key + "true|false" + maybe_separator, Description("boolean")});
1132 return;
1133 }
1134 case Type::ARR_FIXED:
1135 case Type::ARR: {
1136 sections.PushSection({indent + maybe_key + "[", Description("json array")});
1137 for (const auto& i : m_inner) {
1138 i.ToSections(sections, OuterType::ARR, current_indent + 2);
1139 }
1140 CHECK_NONFATAL(!m_inner.empty());
1141 if (m_type == Type::ARR && m_inner.back().m_type != Type::ELISION) {
1142 sections.PushSection({indent_next + "...", ""});
1143 } else {
1144 // Remove final comma, which would be invalid JSON
1145 sections.m_sections.back().m_left.pop_back();
1146 }
1147 sections.PushSection({indent + "]" + maybe_separator, ""});
1148 return;
1149 }
1150 case Type::OBJ_DYN:
1151 case Type::OBJ: {
1152 if (m_inner.empty()) {
1153 sections.PushSection({indent + maybe_key + "{}", Description("empty JSON object")});
1154 return;
1155 }
1156 sections.PushSection({indent + maybe_key + "{", Description("json object")});
1157 for (const auto& i : m_inner) {
1158 i.ToSections(sections, OuterType::OBJ, current_indent + 2);
1159 }
1160 if (m_type == Type::OBJ_DYN && m_inner.back().m_type != Type::ELISION) {
1161 // If the dictionary keys are dynamic, use three dots for continuation
1162 sections.PushSection({indent_next + "...", ""});
1163 } else {
1164 // Remove final comma, which would be invalid JSON
1165 sections.m_sections.back().m_left.pop_back();
1166 }
1167 sections.PushSection({indent + "}" + maybe_separator, ""});
1168 return;
1169 }
1170 } // no default case, so the compiler can warn about missing cases
1171 NONFATAL_UNREACHABLE();
1172 }
1173
1174 static std::optional<UniValue::VType> ExpectedType(RPCResult::Type type)
1175 {
1176 using Type = RPCResult::Type;
1177 switch (type) {
1178 case Type::ELISION:
1179 case Type::ANY: {
1180 return std::nullopt;
1181 }
1182 case Type::NONE: {
1183 return UniValue::VNULL;
1184 }
1185 case Type::STR:
1186 case Type::STR_HEX: {
1187 return UniValue::VSTR;
1188 }
1189 case Type::NUM:
1190 case Type::STR_AMOUNT:
1191 case Type::NUM_TIME: {
1192 return UniValue::VNUM;
1193 }
1194 case Type::BOOL: {
1195 return UniValue::VBOOL;
1196 }
1197 case Type::ARR_FIXED:
1198 case Type::ARR: {
1199 return UniValue::VARR;
1200 }
1201 case Type::OBJ_DYN:
1202 case Type::OBJ: {
1203 return UniValue::VOBJ;
1204 }
1205 } // no default case, so the compiler can warn about missing cases
1206 NONFATAL_UNREACHABLE();
1207 }
1208
1209 // NOLINTNEXTLINE(misc-no-recursion)
1210 UniValue RPCResult::MatchesType(const UniValue& result) const
1211 {
1212 if (m_skip_type_check) {
1213 return true;
1214 }
1215
1216 const auto exp_type = ExpectedType(m_type);
1217 if (!exp_type) return true; // can be any type, so nothing to check
1218
1219 if (*exp_type != result.getType()) {
1220 return strprintf("returned type is %s, but declared as %s in doc", uvTypeName(result.getType()), uvTypeName(*exp_type));
1221 }
1222
1223 if (UniValue::VARR == result.getType()) {
1224 UniValue errors(UniValue::VOBJ);
1225 for (size_t i{0}; i < result.get_array().size(); ++i) {
1226 // If there are more results than documented, reuse the last doc_inner.
1227 const RPCResult& doc_inner{m_inner.at(std::min(m_inner.size() - 1, i))};
1228 UniValue match{doc_inner.MatchesType(result.get_array()[i])};
1229 if (!match.isTrue()) errors.pushKV(strprintf("%d", i), std::move(match));
1230 }
1231 if (errors.empty()) return true; // empty result array is valid
1232 return errors;
1233 }
1234
1235 if (UniValue::VOBJ == result.getType()) {
1236 if (!m_inner.empty() && m_inner.at(0).m_type == Type::ELISION) return true;
1237 UniValue errors(UniValue::VOBJ);
1238 if (m_type == Type::OBJ_DYN) {
1239 const RPCResult& doc_inner{m_inner.at(0)}; // Assume all types are the same, randomly pick the first
1240 for (size_t i{0}; i < result.get_obj().size(); ++i) {
1241 UniValue match{doc_inner.MatchesType(result.get_obj()[i])};
1242 if (!match.isTrue()) errors.pushKV(result.getKeys()[i], std::move(match));
1243 }
1244 if (errors.empty()) return true; // empty result obj is valid
1245 return errors;
1246 }
1247 std::set<std::string> doc_keys;
1248 for (const auto& doc_entry : m_inner) {
1249 doc_keys.insert(doc_entry.m_key_name);
1250 }
1251 std::map<std::string, UniValue> result_obj;
1252 result.getObjMap(result_obj);
1253 for (const auto& result_entry : result_obj) {
1254 if (doc_keys.find(result_entry.first) == doc_keys.end()) {
1255 errors.pushKV(result_entry.first, "key returned that was not in doc");
1256 }
1257 }
1258
1259 for (const auto& doc_entry : m_inner) {
1260 const auto result_it{result_obj.find(doc_entry.m_key_name)};
1261 if (result_it == result_obj.end()) {
1262 if (!doc_entry.m_optional) {
1263 errors.pushKV(doc_entry.m_key_name, "key missing, despite not being optional in doc");
1264 }
1265 continue;
1266 }
1267 UniValue match{doc_entry.MatchesType(result_it->second)};
1268 if (!match.isTrue()) errors.pushKV(doc_entry.m_key_name, std::move(match));
1269 }
1270 if (errors.empty()) return true;
1271 return errors;
1272 }
1273
1274 return true;
1275 }
1276
1277 void RPCResult::CheckInnerDoc() const
1278 {
1279 if (m_type == Type::OBJ) {
1280 // May or may not be empty
1281 return;
1282 }
1283 // Everything else must either be empty or not
1284 const bool inner_needed{m_type == Type::ARR || m_type == Type::ARR_FIXED || m_type == Type::OBJ_DYN};
1285 CHECK_NONFATAL(inner_needed != m_inner.empty());
1286 }
1287
1288 // NOLINTNEXTLINE(misc-no-recursion)
1289 std::string RPCArg::ToStringObj(const bool oneline) const
1290 {
1291 std::string res;
1292 res += "\"";
1293 res += GetFirstName();
1294 if (oneline) {
1295 res += "\":";
1296 } else {
1297 res += "\": ";
1298 }
1299 switch (m_type) {
1300 case Type::STR:
1301 return res + "\"str\"";
1302 case Type::STR_HEX:
1303 return res + "\"hex\"";
1304 case Type::NUM:
1305 return res + "n";
1306 case Type::RANGE:
1307 return res + "n or [n,n]";
1308 case Type::AMOUNT:
1309 return res + "amount";
1310 case Type::BOOL:
1311 return res + "bool";
1312 case Type::ARR:
1313 res += "[";
1314 for (const auto& i : m_inner) {
1315 res += i.ToString(oneline) + ",";
1316 }
1317 return res + "...]";
1318 case Type::OBJ:
1319 case Type::OBJ_NAMED_PARAMS:
1320 case Type::OBJ_USER_KEYS:
1321 // Currently unused, so avoid writing dead code
1322 NONFATAL_UNREACHABLE();
1323 } // no default case, so the compiler can warn about missing cases
1324 NONFATAL_UNREACHABLE();
1325 }
1326
1327 // NOLINTNEXTLINE(misc-no-recursion)
1328 std::string RPCArg::ToString(const bool oneline) const
1329 {
1330 if (oneline && !m_opts.oneline_description.empty()) {
1331 if (m_opts.oneline_description[0] == '\"' && m_type != Type::STR_HEX && m_type != Type::STR && gArgs.GetBoolArg("-rpcdoccheck", DEFAULT_RPC_DOC_CHECK)) {
1332 throw std::runtime_error{
1333 STR_INTERNAL_BUG(strprintf("non-string RPC arg \"%s\" quotes oneline_description:\n%s",
1334 m_names, m_opts.oneline_description)
1335 )};
1336 }
1337 return m_opts.oneline_description;
1338 }
1339
1340 switch (m_type) {
1341 case Type::STR_HEX:
1342 case Type::STR: {
1343 return "\"" + GetFirstName() + "\"";
1344 }
1345 case Type::NUM:
1346 case Type::RANGE:
1347 case Type::AMOUNT:
1348 case Type::BOOL: {
1349 return GetFirstName();
1350 }
1351 case Type::OBJ:
1352 case Type::OBJ_NAMED_PARAMS:
1353 case Type::OBJ_USER_KEYS: {
1354 // NOLINTNEXTLINE(misc-no-recursion)
1355 const std::string res = Join(m_inner, ",", [&](const RPCArg& i) { return i.ToStringObj(oneline); });
1356 if (m_type == Type::OBJ) {
1357 return "{" + res + "}";
1358 } else {
1359 return "{" + res + ",...}";
1360 }
1361 }
1362 case Type::ARR: {
1363 std::string res;
1364 for (const auto& i : m_inner) {
1365 res += i.ToString(oneline) + ",";
1366 }
1367 return "[" + res + "...]";
1368 }
1369 } // no default case, so the compiler can warn about missing cases
1370 NONFATAL_UNREACHABLE();
1371 }
1372
1373 static std::pair<int64_t, int64_t> ParseRange(const UniValue& value)
1374 {
1375 if (value.isNum()) {
1376 return {0, value.getInt<int64_t>()};
1377 }
1378 if (value.isArray() && value.size() == 2 && value[0].isNum() && value[1].isNum()) {
1379 int64_t low = value[0].getInt<int64_t>();
1380 int64_t high = value[1].getInt<int64_t>();
1381 if (low > high) throw JSONRPCError(RPC_INVALID_PARAMETER, "Range specified as [begin,end] must not have begin after end");
1382 return {low, high};
1383 }
1384 throw JSONRPCError(RPC_INVALID_PARAMETER, "Range must be specified as end or as [begin,end]");
1385 }
1386
1387 std::pair<int64_t, int64_t> ParseDescriptorRange(const UniValue& value)
1388 {
1389 int64_t low, high;
1390 std::tie(low, high) = ParseRange(value);
1391 if (low < 0) {
1392 throw JSONRPCError(RPC_INVALID_PARAMETER, "Range should be greater or equal than 0");
1393 }
1394 if ((high >> 31) != 0) {
1395 throw JSONRPCError(RPC_INVALID_PARAMETER, "End of range is too high");
1396 }
1397 if (high >= low + 1000000) {
1398 throw JSONRPCError(RPC_INVALID_PARAMETER, "Range is too large");
1399 }
1400 return {low, high};
1401 }
1402
1403 std::vector<CScript> EvalDescriptorStringOrObject(const UniValue& scanobject, FlatSigningProvider& provider, const bool expand_priv)
1404 {
1405 std::string desc_str;
1406 std::pair<int64_t, int64_t> range = {0, 1000};
1407 if (scanobject.isStr()) {
1408 desc_str = scanobject.get_str();
1409 } else if (scanobject.isObject()) {
1410 const UniValue& desc_uni{scanobject.find_value("desc")};
1411 if (desc_uni.isNull()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Descriptor needs to be provided in scan object");
1412 desc_str = desc_uni.get_str();
1413 const UniValue& range_uni{scanobject.find_value("range")};
1414 if (!range_uni.isNull()) {
1415 range = ParseDescriptorRange(range_uni);
1416 }
1417 } else {
1418 throw JSONRPCError(RPC_INVALID_PARAMETER, "Scan object needs to be either a string or an object");
1419 }
1420
1421 std::string error;
1422 auto descs = Parse(desc_str, provider, error);
1423 if (descs.empty()) {
1424 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error);
1425 }
1426 if (!descs.at(0)->IsRange()) {
1427 range.first = 0;
1428 range.second = 0;
1429 }
1430 std::vector<CScript> ret;
1431 for (int i = range.first; i <= range.second; ++i) {
1432 for (const auto& desc : descs) {
1433 std::vector<CScript> scripts;
1434 if (!desc->Expand(i, provider, scripts, provider)) {
1435 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Cannot derive script without private keys: '%s'", desc_str));
1436 }
1437 if (expand_priv) {
1438 desc->ExpandPrivate(/*pos=*/i, provider, /*out=*/provider);
1439 }
1440 std::move(scripts.begin(), scripts.end(), std::back_inserter(ret));
1441 }
1442 }
1443 return ret;
1444 }
1445
1446 std::vector<CTransactionRef> ParseTransactionVector(const UniValue txns_param)
1447 {
1448 std::vector<CTransactionRef> txns;
1449 const UniValue& raw_transactions = txns_param.get_array();
1450 txns.reserve(raw_transactions.size());
1451
1452 for (const auto& rawtx : raw_transactions.getValues()) {
1453 CMutableTransaction mtx;
1454 if (!DecodeHexTx(mtx, rawtx.get_str())) {
1455 throw JSONRPCError(RPC_DESERIALIZATION_ERROR,
1456 "TX decode failed: " + rawtx.get_str() + " Make sure the prev tx has at least one input.");
1457 }
1458 txns.emplace_back(MakeTransactionRef(std::move(mtx)));
1459 }
1460 return txns;
1461 }
1462
1463 /** Convert a vector of bilingual strings to a UniValue::VARR containing their original untranslated values. */
1464 [[nodiscard]] static UniValue BilingualStringsToUniValue(const std::vector<bilingual_str>& bilingual_strings)
1465 {
1466 CHECK_NONFATAL(!bilingual_strings.empty());
1467 UniValue result{UniValue::VARR};
1468 for (const auto& s : bilingual_strings) {
1469 result.push_back(s.original);
1470 }
1471 return result;
1472 }
1473
1474 void PushWarnings(const UniValue& warnings, UniValue& obj)
1475 {
1476 if (warnings.empty()) return;
1477 obj.pushKV("warnings", warnings);
1478 }
1479
1480 void PushWarnings(const std::vector<bilingual_str>& warnings, UniValue& obj)
1481 {
1482 if (warnings.empty()) return;
1483 obj.pushKV("warnings", BilingualStringsToUniValue(warnings));
1484 }
1485
1486 bool GetWalletRestrictionFromJSONRPCRequest(const JSONRPCRequest& request, std::string& out_wallet_allowed)
1487 {
1488 if (request.m_wallet_restriction.empty()) return false;
1489 out_wallet_allowed = request.m_wallet_restriction;
1490 return true;
1491 }
1492
1493 void EnsureNotWalletRestricted(const JSONRPCRequest& request)
1494 {
1495 std::string authorized_wallet_name;
1496 const bool have_wallet_restriction = GetWalletRestrictionFromJSONRPCRequest(request, authorized_wallet_name);
1497 if (have_wallet_restriction) {
1498 throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not available for wallet-restricted RPC users");
1499 }
1500 }
1501
1502 std::vector<RPCResult> ScriptPubKeyDoc() {
1503 return
1504 {
1505 {RPCResult::Type::STR, "asm", "Disassembly of the output script"},
1506 {RPCResult::Type::STR, "desc", "Inferred descriptor for the output"},
1507 {RPCResult::Type::STR_HEX, "hex", "The raw output script bytes, hex-encoded"},
1508 {RPCResult::Type::STR, "address", /*optional=*/true, "The Limenka address (only if a well-defined address exists)"},
1509 {RPCResult::Type::STR, "type", "The type (one of: " + GetAllOutputTypes() + ")"},
1510 };
1511 }
1512
1513 uint256 GetTarget(const CBlockIndex& blockindex, const uint256 pow_limit)
1514 {
1515 arith_uint256 target{*CHECK_NONFATAL(DeriveTarget(blockindex.nBits, pow_limit))};
1516 return ArithToUint256(target);
1517 }
1518