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