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