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