Bitcoin Core 28.99.0
P2P Digital Currency
util.cpp
Go to the documentation of this file.
1// Copyright (c) 2017-2022 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 <clientversion.h>
8#include <common/args.h>
9#include <common/messages.h>
10#include <common/types.h>
11#include <consensus/amount.h>
12#include <core_io.h>
13#include <key_io.h>
14#include <node/types.h>
15#include <outputtype.h>
16#include <rpc/util.h>
17#include <script/descriptor.h>
18#include <script/interpreter.h>
20#include <script/solver.h>
21#include <tinyformat.h>
22#include <uint256.h>
23#include <univalue.h>
24#include <util/check.h>
25#include <util/result.h>
26#include <util/strencodings.h>
27#include <util/string.h>
28#include <util/translation.h>
29
30#include <algorithm>
31#include <iterator>
32#include <string_view>
33#include <tuple>
34#include <utility>
35
40using util::Join;
43
44const std::string UNIX_EPOCH_TIME = "UNIX epoch time";
45const std::string EXAMPLE_ADDRESS[2] = {"bc1q09vm5lfy0j5reeulh4x5752q25uqqvz34hufdl", "bc1q02ad21edsxd23d32dfgqqsz4vv4nmtfzuklhy3"};
46
47std::string GetAllOutputTypes()
48{
49 std::vector<std::string> ret;
50 using U = std::underlying_type<TxoutType>::type;
51 for (U i = (U)TxoutType::NONSTANDARD; i <= (U)TxoutType::WITNESS_UNKNOWN; ++i) {
52 ret.emplace_back(GetTxnOutputType(static_cast<TxoutType>(i)));
53 }
54 return Join(ret, ", ");
55}
56
58 const std::map<std::string, UniValueType>& typesExpected,
59 bool fAllowNull,
60 bool fStrict)
61{
62 for (const auto& t : typesExpected) {
63 const UniValue& v = o.find_value(t.first);
64 if (!fAllowNull && v.isNull())
65 throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first));
66
67 if (!(t.second.typeAny || v.type() == t.second.type || (fAllowNull && v.isNull())))
68 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)));
69 }
70
71 if (fStrict)
72 {
73 for (const std::string& k : o.getKeys())
74 {
75 if (typesExpected.count(k) == 0)
76 {
77 std::string err = strprintf("Unexpected key %s", k);
78 throw JSONRPCError(RPC_TYPE_ERROR, err);
79 }
80 }
81 }
82}
83
84int ParseVerbosity(const UniValue& arg, int default_verbosity, bool allow_bool)
85{
86 if (!arg.isNull()) {
87 if (arg.isBool()) {
88 if (!allow_bool) {
89 throw JSONRPCError(RPC_TYPE_ERROR, "Verbosity was boolean but only integer allowed");
90 }
91 return arg.get_bool(); // true = 1
92 } else {
93 return arg.getInt<int>();
94 }
95 }
96 return default_verbosity;
97}
98
99CAmount AmountFromValue(const UniValue& value, int decimals)
100{
101 if (!value.isNum() && !value.isStr())
102 throw JSONRPCError(RPC_TYPE_ERROR, "Amount is not a number or string");
103 CAmount amount;
104 if (!ParseFixedPoint(value.getValStr(), decimals, &amount))
105 throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
106 if (!MoneyRange(amount))
107 throw JSONRPCError(RPC_TYPE_ERROR, "Amount out of range");
108 return amount;
109}
110
112{
114 if (val >= COIN) throw JSONRPCError(RPC_INVALID_PARAMETER, "Fee rates larger than or equal to 1BTC/kvB are not accepted");
115 return CFeeRate{val};
116}
117
118uint256 ParseHashV(const UniValue& v, std::string_view name)
119{
120 const std::string& strHex(v.get_str());
121 if (auto rv{uint256::FromHex(strHex)}) return *rv;
122 if (auto expected_len{uint256::size() * 2}; strHex.length() != expected_len) {
123 throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("%s must be of length %d (not %d, for '%s')", name, expected_len, strHex.length(), strHex));
124 }
125 throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("%s must be hexadecimal string (not '%s')", name, strHex));
126}
127uint256 ParseHashO(const UniValue& o, std::string_view strKey)
128{
129 return ParseHashV(o.find_value(strKey), strKey);
130}
131std::vector<unsigned char> ParseHexV(const UniValue& v, std::string_view name)
132{
133 std::string strHex;
134 if (v.isStr())
135 strHex = v.get_str();
136 if (!IsHex(strHex))
137 throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("%s must be hexadecimal string (not '%s')", name, strHex));
138 return ParseHex(strHex);
139}
140std::vector<unsigned char> ParseHexO(const UniValue& o, std::string_view strKey)
141{
142 return ParseHexV(o.find_value(strKey), strKey);
143}
144
145namespace {
146
152std::string ShellQuote(const std::string& s)
153{
154 std::string result;
155 result.reserve(s.size() * 2);
156 for (const char ch: s) {
157 if (ch == '\'') {
158 result += "'\''";
159 } else {
160 result += ch;
161 }
162 }
163 return "'" + result + "'";
164}
165
171std::string ShellQuoteIfNeeded(const std::string& s)
172{
173 for (const char ch: s) {
174 if (ch == ' ' || ch == '\'' || ch == '"') {
175 return ShellQuote(s);
176 }
177 }
178
179 return s;
180}
181
182}
183
184std::string HelpExampleCli(const std::string& methodname, const std::string& args)
185{
186 return "> bitcoin-cli " + methodname + " " + args + "\n";
187}
188
189std::string HelpExampleCliNamed(const std::string& methodname, const RPCArgList& args)
190{
191 std::string result = "> bitcoin-cli -named " + methodname;
192 for (const auto& argpair: args) {
193 const auto& value = argpair.second.isStr()
194 ? argpair.second.get_str()
195 : argpair.second.write();
196 result += " " + argpair.first + "=" + ShellQuoteIfNeeded(value);
197 }
198 result += "\n";
199 return result;
200}
201
202std::string HelpExampleRpc(const std::string& methodname, const std::string& args)
203{
204 return "> curl --user myusername --data-binary '{\"jsonrpc\": \"2.0\", \"id\": \"curltest\", "
205 "\"method\": \"" + methodname + "\", \"params\": [" + args + "]}' -H 'content-type: application/json' http://127.0.0.1:8332/\n";
206}
207
208std::string HelpExampleRpcNamed(const std::string& methodname, const RPCArgList& args)
209{
210 UniValue params(UniValue::VOBJ);
211 for (const auto& param: args) {
212 params.pushKV(param.first, param.second);
213 }
214
215 return "> curl --user myusername --data-binary '{\"jsonrpc\": \"2.0\", \"id\": \"curltest\", "
216 "\"method\": \"" + methodname + "\", \"params\": " + params.write() + "}' -H 'content-type: application/json' http://127.0.0.1:8332/\n";
217}
218
219// Converts a hex string to a public key if possible
220CPubKey HexToPubKey(const std::string& hex_in)
221{
222 if (!IsHex(hex_in)) {
223 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey \"" + hex_in + "\" must be a hex string");
224 }
225 if (hex_in.length() != 66 && hex_in.length() != 130) {
226 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey \"" + hex_in + "\" must have a length of either 33 or 65 bytes");
227 }
228 CPubKey vchPubKey(ParseHex(hex_in));
229 if (!vchPubKey.IsFullyValid()) {
230 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey \"" + hex_in + "\" must be cryptographically valid.");
231 }
232 return vchPubKey;
233}
234
235// Retrieves a public key for an address from the given FillableSigningProvider
236CPubKey AddrToPubKey(const FillableSigningProvider& keystore, const std::string& addr_in)
237{
238 CTxDestination dest = DecodeDestination(addr_in);
239 if (!IsValidDestination(dest)) {
240 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address: " + addr_in);
241 }
242 CKeyID key = GetKeyForDestination(keystore, dest);
243 if (key.IsNull()) {
244 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("'%s' does not refer to a key", addr_in));
245 }
246 CPubKey vchPubKey;
247 if (!keystore.GetPubKey(key, vchPubKey)) {
248 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("no full public key for address %s", addr_in));
249 }
250 if (!vchPubKey.IsFullyValid()) {
251 throw JSONRPCError(RPC_INTERNAL_ERROR, "Wallet contains an invalid public key");
252 }
253 return vchPubKey;
254}
255
256// Creates a multisig address from a given list of public keys, number of signatures required, and the address type
257CTxDestination AddAndGetMultisigDestination(const int required, const std::vector<CPubKey>& pubkeys, OutputType type, FlatSigningProvider& keystore, CScript& script_out)
258{
259 // Gather public keys
260 if (required < 1) {
261 throw JSONRPCError(RPC_INVALID_PARAMETER, "a multisignature address must require at least one key to redeem");
262 }
263 if ((int)pubkeys.size() < required) {
264 throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("not enough keys supplied (got %u keys, but need at least %d to redeem)", pubkeys.size(), required));
265 }
266 if (pubkeys.size() > MAX_PUBKEYS_PER_MULTISIG) {
267 throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Number of keys involved in the multisignature address creation > %d\nReduce the number", MAX_PUBKEYS_PER_MULTISIG));
268 }
269
270 script_out = GetScriptForMultisig(required, pubkeys);
271
272 // Check if any keys are uncompressed. If so, the type is legacy
273 for (const CPubKey& pk : pubkeys) {
274 if (!pk.IsCompressed()) {
275 type = OutputType::LEGACY;
276 break;
277 }
278 }
279
280 if (type == OutputType::LEGACY && script_out.size() > MAX_SCRIPT_ELEMENT_SIZE) {
281 throw JSONRPCError(RPC_INVALID_PARAMETER, (strprintf("redeemScript exceeds size limit: %d > %d", script_out.size(), MAX_SCRIPT_ELEMENT_SIZE)));
282 }
283
284 // Make the address
285 CTxDestination dest = AddAndGetDestinationForScript(keystore, script_out, type);
286
287 return dest;
288}
289
291{
292public:
293 explicit DescribeAddressVisitor() = default;
294
296 {
297 return UniValue(UniValue::VOBJ);
298 }
299
301 {
302 return UniValue(UniValue::VOBJ);
303 }
304
305 UniValue operator()(const PKHash& keyID) const
306 {
308 obj.pushKV("isscript", false);
309 obj.pushKV("iswitness", false);
310 return obj;
311 }
312
313 UniValue operator()(const ScriptHash& scriptID) const
314 {
316 obj.pushKV("isscript", true);
317 obj.pushKV("iswitness", false);
318 return obj;
319 }
320
322 {
324 obj.pushKV("isscript", false);
325 obj.pushKV("iswitness", true);
326 obj.pushKV("witness_version", 0);
327 obj.pushKV("witness_program", HexStr(id));
328 return obj;
329 }
330
332 {
334 obj.pushKV("isscript", true);
335 obj.pushKV("iswitness", true);
336 obj.pushKV("witness_version", 0);
337 obj.pushKV("witness_program", HexStr(id));
338 return obj;
339 }
340
342 {
344 obj.pushKV("isscript", true);
345 obj.pushKV("iswitness", true);
346 obj.pushKV("witness_version", 1);
347 obj.pushKV("witness_program", HexStr(tap));
348 return obj;
349 }
350
351 UniValue operator()(const PayToAnchor& anchor) const
352 {
354 obj.pushKV("isscript", true);
355 obj.pushKV("iswitness", true);
356 return obj;
357 }
358
360 {
362 obj.pushKV("iswitness", true);
363 obj.pushKV("witness_version", id.GetWitnessVersion());
364 obj.pushKV("witness_program", HexStr(id.GetWitnessProgram()));
365 return obj;
366 }
367};
368
370{
371 return std::visit(DescribeAddressVisitor(), dest);
372}
373
379int ParseSighashString(const UniValue& sighash)
380{
381 if (sighash.isNull()) {
382 return SIGHASH_DEFAULT;
383 }
384 const auto result{SighashFromStr(sighash.get_str())};
385 if (!result) {
387 }
388 return result.value();
389}
390
391unsigned int ParseConfirmTarget(const UniValue& value, unsigned int max_target)
392{
393 const int target{value.getInt<int>()};
394 const unsigned int unsigned_target{static_cast<unsigned int>(target)};
395 if (target < 1 || unsigned_target > max_target) {
396 throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid conf_target, must be between %u and %u", 1, max_target));
397 }
398 return unsigned_target;
399}
400
402{
403 switch (err) {
404 case PSBTError::UNSUPPORTED:
406 case PSBTError::SIGHASH_MISMATCH:
408 default: break;
409 }
411}
412
414{
415 switch (terr) {
416 case TransactionError::MEMPOOL_REJECTED:
418 case TransactionError::ALREADY_IN_UTXO_SET:
420 default: break;
421 }
423}
424
426{
427 return JSONRPCError(RPCErrorFromPSBTError(err), PSBTErrorString(err).original);
428}
429
430UniValue JSONRPCTransactionError(TransactionError terr, const std::string& err_string)
431{
432 if (err_string.length() > 0) {
433 return JSONRPCError(RPCErrorFromTransactionError(terr), err_string);
434 } else {
436 }
437}
438
443struct Section {
444 Section(const std::string& left, const std::string& right)
445 : m_left{left}, m_right{right} {}
446 std::string m_left;
447 const std::string m_right;
448};
449
454struct Sections {
455 std::vector<Section> m_sections;
456 size_t m_max_pad{0};
457
458 void PushSection(const Section& s)
459 {
460 m_max_pad = std::max(m_max_pad, s.m_left.size());
461 m_sections.push_back(s);
462 }
463
467 // NOLINTNEXTLINE(misc-no-recursion)
468 void Push(const RPCArg& arg, const size_t current_indent = 5, const OuterType outer_type = OuterType::NONE)
469 {
470 const auto indent = std::string(current_indent, ' ');
471 const auto indent_next = std::string(current_indent + 2, ' ');
472 const bool push_name{outer_type == OuterType::OBJ}; // Dictionary keys must have a name
473 const bool is_top_level_arg{outer_type == OuterType::NONE}; // True on the first recursion
474
475 switch (arg.m_type) {
483 if (is_top_level_arg) return; // Nothing more to do for non-recursive types on first recursion
484 auto left = indent;
485 if (arg.m_opts.type_str.size() != 0 && push_name) {
486 left += "\"" + arg.GetName() + "\": " + arg.m_opts.type_str.at(0);
487 } else {
488 left += push_name ? arg.ToStringObj(/*oneline=*/false) : arg.ToString(/*oneline=*/false);
489 }
490 left += ",";
491 PushSection({left, arg.ToDescriptionString(/*is_named_arg=*/push_name)});
492 break;
493 }
496 const auto right = is_top_level_arg ? "" : arg.ToDescriptionString(/*is_named_arg=*/push_name);
497 PushSection({indent + (push_name ? "\"" + arg.GetName() + "\": " : "") + "{", right});
498 for (const auto& arg_inner : arg.m_inner) {
499 Push(arg_inner, current_indent + 2, OuterType::OBJ);
500 }
501 if (arg.m_type != RPCArg::Type::OBJ) {
502 PushSection({indent_next + "...", ""});
503 }
504 PushSection({indent + "}" + (is_top_level_arg ? "" : ","), ""});
505 break;
506 }
507 case RPCArg::Type::ARR: {
508 auto left = indent;
509 left += push_name ? "\"" + arg.GetName() + "\": " : "";
510 left += "[";
511 const auto right = is_top_level_arg ? "" : arg.ToDescriptionString(/*is_named_arg=*/push_name);
512 PushSection({left, right});
513 for (const auto& arg_inner : arg.m_inner) {
514 Push(arg_inner, current_indent + 2, OuterType::ARR);
515 }
516 PushSection({indent_next + "...", ""});
517 PushSection({indent + "]" + (is_top_level_arg ? "" : ","), ""});
518 break;
519 }
520 } // no default case, so the compiler can warn about missing cases
521 }
522
526 std::string ToString() const
527 {
528 std::string ret;
529 const size_t pad = m_max_pad + 4;
530 for (const auto& s : m_sections) {
531 // The left part of a section is assumed to be a single line, usually it is the name of the JSON struct or a
532 // brace like {, }, [, or ]
533 CHECK_NONFATAL(s.m_left.find('\n') == std::string::npos);
534 if (s.m_right.empty()) {
535 ret += s.m_left;
536 ret += "\n";
537 continue;
538 }
539
540 std::string left = s.m_left;
541 left.resize(pad, ' ');
542 ret += left;
543
544 // Properly pad after newlines
545 std::string right;
546 size_t begin = 0;
547 size_t new_line_pos = s.m_right.find_first_of('\n');
548 while (true) {
549 right += s.m_right.substr(begin, new_line_pos - begin);
550 if (new_line_pos == std::string::npos) {
551 break; //No new line
552 }
553 right += "\n" + std::string(pad, ' ');
554 begin = s.m_right.find_first_not_of(' ', new_line_pos + 1);
555 if (begin == std::string::npos) {
556 break; // Empty line
557 }
558 new_line_pos = s.m_right.find_first_of('\n', begin + 1);
559 }
560 ret += right;
561 ret += "\n";
562 }
563 return ret;
564 }
565};
566
567RPCHelpMan::RPCHelpMan(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples)
568 : RPCHelpMan{std::move(name), std::move(description), std::move(args), std::move(results), std::move(examples), nullptr} {}
569
570RPCHelpMan::RPCHelpMan(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples, RPCMethodImpl fun)
571 : m_name{std::move(name)},
572 m_fun{std::move(fun)},
573 m_description{std::move(description)},
574 m_args{std::move(args)},
575 m_results{std::move(results)},
576 m_examples{std::move(examples)}
577{
578 // Map of parameter names and types just used to check whether the names are
579 // unique. Parameter names always need to be unique, with the exception that
580 // there can be pairs of POSITIONAL and NAMED parameters with the same name.
581 enum ParamType { POSITIONAL = 1, NAMED = 2, NAMED_ONLY = 4 };
582 std::map<std::string, int> param_names;
583
584 for (const auto& arg : m_args) {
585 std::vector<std::string> names = SplitString(arg.m_names, '|');
586 // Should have unique named arguments
587 for (const std::string& name : names) {
588 auto& param_type = param_names[name];
589 CHECK_NONFATAL(!(param_type & POSITIONAL));
590 CHECK_NONFATAL(!(param_type & NAMED_ONLY));
591 param_type |= POSITIONAL;
592 }
593 if (arg.m_type == RPCArg::Type::OBJ_NAMED_PARAMS) {
594 for (const auto& inner : arg.m_inner) {
595 std::vector<std::string> inner_names = SplitString(inner.m_names, '|');
596 for (const std::string& inner_name : inner_names) {
597 auto& param_type = param_names[inner_name];
598 CHECK_NONFATAL(!(param_type & POSITIONAL) || inner.m_opts.also_positional);
599 CHECK_NONFATAL(!(param_type & NAMED));
600 CHECK_NONFATAL(!(param_type & NAMED_ONLY));
601 param_type |= inner.m_opts.also_positional ? NAMED : NAMED_ONLY;
602 }
603 }
604 }
605 // Default value type should match argument type only when defined
606 if (arg.m_fallback.index() == 2) {
607 const RPCArg::Type type = arg.m_type;
608 switch (std::get<RPCArg::Default>(arg.m_fallback).getType()) {
609 case UniValue::VOBJ:
611 break;
612 case UniValue::VARR:
614 break;
615 case UniValue::VSTR:
617 break;
618 case UniValue::VNUM:
620 break;
621 case UniValue::VBOOL:
623 break;
624 case UniValue::VNULL:
625 // Null values are accepted in all arguments
626 break;
627 default:
629 break;
630 }
631 }
632 }
633}
634
636{
637 std::string result;
638 for (const auto& r : m_results) {
639 if (r.m_type == RPCResult::Type::ANY) continue; // for testing only
640 if (r.m_cond.empty()) {
641 result += "\nResult:\n";
642 } else {
643 result += "\nResult (" + r.m_cond + "):\n";
644 }
645 Sections sections;
646 r.ToSections(sections);
647 result += sections.ToString();
648 }
649 return result;
650}
651
653{
654 return m_examples.empty() ? m_examples : "\nExamples:\n" + m_examples;
655}
656
658{
659 if (request.mode == JSONRPCRequest::GET_ARGS) {
660 return GetArgMap();
661 }
662 /*
663 * Check if the given request is valid according to this command or if
664 * the user is asking for help information, and throw help when appropriate.
665 */
666 if (request.mode == JSONRPCRequest::GET_HELP || !IsValidNumArgs(request.params.size())) {
667 throw std::runtime_error(ToString());
668 }
669 UniValue arg_mismatch{UniValue::VOBJ};
670 for (size_t i{0}; i < m_args.size(); ++i) {
671 const auto& arg{m_args.at(i)};
672 UniValue match{arg.MatchesType(request.params[i])};
673 if (!match.isTrue()) {
674 arg_mismatch.pushKV(strprintf("Position %s (%s)", i + 1, arg.m_names), std::move(match));
675 }
676 }
677 if (!arg_mismatch.empty()) {
678 throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Wrong type passed:\n%s", arg_mismatch.write(4)));
679 }
680 CHECK_NONFATAL(m_req == nullptr);
681 m_req = &request;
682 UniValue ret = m_fun(*this, request);
683 m_req = nullptr;
684 if (gArgs.GetBoolArg("-rpcdoccheck", DEFAULT_RPC_DOC_CHECK)) {
685 UniValue mismatch{UniValue::VARR};
686 for (const auto& res : m_results.m_results) {
687 UniValue match{res.MatchesType(ret)};
688 if (match.isTrue()) {
689 mismatch.setNull();
690 break;
691 }
692 mismatch.push_back(std::move(match));
693 }
694 if (!mismatch.isNull()) {
695 std::string explain{
696 mismatch.empty() ? "no possible results defined" :
697 mismatch.size() == 1 ? mismatch[0].write(4) :
698 mismatch.write(4)};
699 throw std::runtime_error{
700 strprintf("Internal bug detected: RPC call \"%s\" returned incorrect type:\n%s\n%s %s\nPlease report this issue here: %s\n",
701 m_name, explain,
702 CLIENT_NAME, FormatFullVersion(),
703 CLIENT_BUGREPORT)};
704 }
705 }
706 return ret;
707}
708
709using CheckFn = void(const RPCArg&);
710static const UniValue* DetailMaybeArg(CheckFn* check, const std::vector<RPCArg>& params, const JSONRPCRequest* req, size_t i)
711{
712 CHECK_NONFATAL(i < params.size());
713 const UniValue& arg{CHECK_NONFATAL(req)->params[i]};
714 const RPCArg& param{params.at(i)};
715 if (check) check(param);
716
717 if (!arg.isNull()) return &arg;
718 if (!std::holds_alternative<RPCArg::Default>(param.m_fallback)) return nullptr;
719 return &std::get<RPCArg::Default>(param.m_fallback);
720}
721
722static void CheckRequiredOrDefault(const RPCArg& param)
723{
724 // Must use `Arg<Type>(key)` to get the argument or its default value.
725 const bool required{
726 std::holds_alternative<RPCArg::Optional>(param.m_fallback) && RPCArg::Optional::NO == std::get<RPCArg::Optional>(param.m_fallback),
727 };
728 CHECK_NONFATAL(required || std::holds_alternative<RPCArg::Default>(param.m_fallback));
729}
730
731#define TMPL_INST(check_param, ret_type, return_code) \
732 template <> \
733 ret_type RPCHelpMan::ArgValue<ret_type>(size_t i) const \
734 { \
735 const UniValue* maybe_arg{ \
736 DetailMaybeArg(check_param, m_args, m_req, i), \
737 }; \
738 return return_code \
739 } \
740 void force_semicolon(ret_type)
741
742// Optional arg (without default). Can also be called on required args, if needed.
743TMPL_INST(nullptr, const UniValue*, maybe_arg;);
744TMPL_INST(nullptr, std::optional<double>, maybe_arg ? std::optional{maybe_arg->get_real()} : std::nullopt;);
745TMPL_INST(nullptr, std::optional<bool>, maybe_arg ? std::optional{maybe_arg->get_bool()} : std::nullopt;);
746TMPL_INST(nullptr, const std::string*, maybe_arg ? &maybe_arg->get_str() : nullptr;);
747
748// Required arg or optional arg with default value.
750TMPL_INST(CheckRequiredOrDefault, bool, CHECK_NONFATAL(maybe_arg)->get_bool(););
751TMPL_INST(CheckRequiredOrDefault, int, CHECK_NONFATAL(maybe_arg)->getInt<int>(););
752TMPL_INST(CheckRequiredOrDefault, uint64_t, CHECK_NONFATAL(maybe_arg)->getInt<uint64_t>(););
753TMPL_INST(CheckRequiredOrDefault, const std::string&, CHECK_NONFATAL(maybe_arg)->get_str(););
754
755bool RPCHelpMan::IsValidNumArgs(size_t num_args) const
756{
757 size_t num_required_args = 0;
758 for (size_t n = m_args.size(); n > 0; --n) {
759 if (!m_args.at(n - 1).IsOptional()) {
760 num_required_args = n;
761 break;
762 }
763 }
764 return num_required_args <= num_args && num_args <= m_args.size();
765}
766
767std::vector<std::pair<std::string, bool>> RPCHelpMan::GetArgNames() const
768{
769 std::vector<std::pair<std::string, bool>> ret;
770 ret.reserve(m_args.size());
771 for (const auto& arg : m_args) {
772 if (arg.m_type == RPCArg::Type::OBJ_NAMED_PARAMS) {
773 for (const auto& inner : arg.m_inner) {
774 ret.emplace_back(inner.m_names, /*named_only=*/true);
775 }
776 }
777 ret.emplace_back(arg.m_names, /*named_only=*/false);
778 }
779 return ret;
780}
781
782size_t RPCHelpMan::GetParamIndex(std::string_view key) const
783{
784 auto it{std::find_if(
785 m_args.begin(), m_args.end(), [&key](const auto& arg) { return arg.GetName() == key;}
786 )};
787
788 CHECK_NONFATAL(it != m_args.end()); // TODO: ideally this is checked at compile time
789 return std::distance(m_args.begin(), it);
790}
791
792std::string RPCHelpMan::ToString() const
793{
794 std::string ret;
795
796 // Oneline summary
797 ret += m_name;
798 bool was_optional{false};
799 for (const auto& arg : m_args) {
800 if (arg.m_opts.hidden) break; // Any arg that follows is also hidden
801 const bool optional = arg.IsOptional();
802 ret += " ";
803 if (optional) {
804 if (!was_optional) ret += "( ";
805 was_optional = true;
806 } else {
807 if (was_optional) ret += ") ";
808 was_optional = false;
809 }
810 ret += arg.ToString(/*oneline=*/true);
811 }
812 if (was_optional) ret += " )";
813
814 // Description
815 ret += "\n\n" + TrimString(m_description) + "\n";
816
817 // Arguments
818 Sections sections;
819 Sections named_only_sections;
820 for (size_t i{0}; i < m_args.size(); ++i) {
821 const auto& arg = m_args.at(i);
822 if (arg.m_opts.hidden) break; // Any arg that follows is also hidden
823
824 // Push named argument name and description
825 sections.m_sections.emplace_back(util::ToString(i + 1) + ". " + arg.GetFirstName(), arg.ToDescriptionString(/*is_named_arg=*/true));
826 sections.m_max_pad = std::max(sections.m_max_pad, sections.m_sections.back().m_left.size());
827
828 // Recursively push nested args
829 sections.Push(arg);
830
831 // Push named-only argument sections
832 if (arg.m_type == RPCArg::Type::OBJ_NAMED_PARAMS) {
833 for (const auto& arg_inner : arg.m_inner) {
834 named_only_sections.PushSection({arg_inner.GetFirstName(), arg_inner.ToDescriptionString(/*is_named_arg=*/true)});
835 named_only_sections.Push(arg_inner);
836 }
837 }
838 }
839
840 if (!sections.m_sections.empty()) ret += "\nArguments:\n";
841 ret += sections.ToString();
842 if (!named_only_sections.m_sections.empty()) ret += "\nNamed Arguments:\n";
843 ret += named_only_sections.ToString();
844
845 // Result
847
848 // Examples
850
851 return ret;
852}
853
855{
857
858 auto push_back_arg_info = [&arr](const std::string& rpc_name, int pos, const std::string& arg_name, const RPCArg::Type& type) {
860 map.push_back(rpc_name);
861 map.push_back(pos);
862 map.push_back(arg_name);
863 map.push_back(type == RPCArg::Type::STR ||
864 type == RPCArg::Type::STR_HEX);
865 arr.push_back(std::move(map));
866 };
867
868 for (int i{0}; i < int(m_args.size()); ++i) {
869 const auto& arg = m_args.at(i);
870 std::vector<std::string> arg_names = SplitString(arg.m_names, '|');
871 for (const auto& arg_name : arg_names) {
872 push_back_arg_info(m_name, i, arg_name, arg.m_type);
873 if (arg.m_type == RPCArg::Type::OBJ_NAMED_PARAMS) {
874 for (const auto& inner : arg.m_inner) {
875 std::vector<std::string> inner_names = SplitString(inner.m_names, '|');
876 for (const std::string& inner_name : inner_names) {
877 push_back_arg_info(m_name, i, inner_name, inner.m_type);
878 }
879 }
880 }
881 }
882 }
883 return arr;
884}
885
886static std::optional<UniValue::VType> ExpectedType(RPCArg::Type type)
887{
888 using Type = RPCArg::Type;
889 switch (type) {
890 case Type::STR_HEX:
891 case Type::STR: {
892 return UniValue::VSTR;
893 }
894 case Type::NUM: {
895 return UniValue::VNUM;
896 }
897 case Type::AMOUNT: {
898 // VNUM or VSTR, checked inside AmountFromValue()
899 return std::nullopt;
900 }
901 case Type::RANGE: {
902 // VNUM or VARR, checked inside ParseRange()
903 return std::nullopt;
904 }
905 case Type::BOOL: {
906 return UniValue::VBOOL;
907 }
908 case Type::OBJ:
909 case Type::OBJ_NAMED_PARAMS:
910 case Type::OBJ_USER_KEYS: {
911 return UniValue::VOBJ;
912 }
913 case Type::ARR: {
914 return UniValue::VARR;
915 }
916 } // no default case, so the compiler can warn about missing cases
918}
919
921{
922 if (m_opts.skip_type_check) return true;
923 if (IsOptional() && request.isNull()) return true;
924 const auto exp_type{ExpectedType(m_type)};
925 if (!exp_type) return true; // nothing to check
926
927 if (*exp_type != request.getType()) {
928 return strprintf("JSON value of type %s is not of expected type %s", uvTypeName(request.getType()), uvTypeName(*exp_type));
929 }
930 return true;
931}
932
933std::string RPCArg::GetFirstName() const
934{
935 return m_names.substr(0, m_names.find('|'));
936}
937
938std::string RPCArg::GetName() const
939{
940 CHECK_NONFATAL(std::string::npos == m_names.find('|'));
941 return m_names;
942}
943
945{
946 if (m_fallback.index() != 0) {
947 return true;
948 } else {
949 return RPCArg::Optional::NO != std::get<RPCArg::Optional>(m_fallback);
950 }
951}
952
953std::string RPCArg::ToDescriptionString(bool is_named_arg) const
954{
955 std::string ret;
956 ret += "(";
957 if (m_opts.type_str.size() != 0) {
958 ret += m_opts.type_str.at(1);
959 } else {
960 switch (m_type) {
961 case Type::STR_HEX:
962 case Type::STR: {
963 ret += "string";
964 break;
965 }
966 case Type::NUM: {
967 ret += "numeric";
968 break;
969 }
970 case Type::AMOUNT: {
971 ret += "numeric or string";
972 break;
973 }
974 case Type::RANGE: {
975 ret += "numeric or array";
976 break;
977 }
978 case Type::BOOL: {
979 ret += "boolean";
980 break;
981 }
982 case Type::OBJ:
984 case Type::OBJ_USER_KEYS: {
985 ret += "json object";
986 break;
987 }
988 case Type::ARR: {
989 ret += "json array";
990 break;
991 }
992 } // no default case, so the compiler can warn about missing cases
993 }
994 if (m_fallback.index() == 1) {
995 ret += ", optional, default=" + std::get<RPCArg::DefaultHint>(m_fallback);
996 } else if (m_fallback.index() == 2) {
997 ret += ", optional, default=" + std::get<RPCArg::Default>(m_fallback).write();
998 } else {
999 switch (std::get<RPCArg::Optional>(m_fallback)) {
1001 if (is_named_arg) ret += ", optional"; // Default value is "null" in dicts. Otherwise,
1002 // nothing to do. Element is treated as if not present and has no default value
1003 break;
1004 }
1005 case RPCArg::Optional::NO: {
1006 ret += ", required";
1007 break;
1008 }
1009 } // no default case, so the compiler can warn about missing cases
1010 }
1011 ret += ")";
1012 if (m_type == Type::OBJ_NAMED_PARAMS) ret += " Options object that can be used to pass named arguments, listed below.";
1013 ret += m_description.empty() ? "" : " " + m_description;
1014 return ret;
1015}
1016
1017// NOLINTNEXTLINE(misc-no-recursion)
1018void RPCResult::ToSections(Sections& sections, const OuterType outer_type, const int current_indent) const
1019{
1020 // Indentation
1021 const std::string indent(current_indent, ' ');
1022 const std::string indent_next(current_indent + 2, ' ');
1023
1024 // Elements in a JSON structure (dictionary or array) are separated by a comma
1025 const std::string maybe_separator{outer_type != OuterType::NONE ? "," : ""};
1026
1027 // The key name if recursed into a dictionary
1028 const std::string maybe_key{
1029 outer_type == OuterType::OBJ ?
1030 "\"" + this->m_key_name + "\" : " :
1031 ""};
1032
1033 // Format description with type
1034 const auto Description = [&](const std::string& type) {
1035 return "(" + type + (this->m_optional ? ", optional" : "") + ")" +
1036 (this->m_description.empty() ? "" : " " + this->m_description);
1037 };
1038
1039 switch (m_type) {
1040 case Type::ELISION: {
1041 // If the inner result is empty, use three dots for elision
1042 sections.PushSection({indent + "..." + maybe_separator, m_description});
1043 return;
1044 }
1045 case Type::ANY: {
1046 NONFATAL_UNREACHABLE(); // Only for testing
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 if (m_type == Type::ARR && m_inner.back().m_type != Type::ELISION) {
1084 sections.PushSection({indent_next + "...", ""});
1085 } else {
1086 // Remove final comma, which would be invalid JSON
1087 sections.m_sections.back().m_left.pop_back();
1088 }
1089 sections.PushSection({indent + "]" + maybe_separator, ""});
1090 return;
1091 }
1092 case Type::OBJ_DYN:
1093 case Type::OBJ: {
1094 if (m_inner.empty()) {
1095 sections.PushSection({indent + maybe_key + "{}", Description("empty JSON object")});
1096 return;
1097 }
1098 sections.PushSection({indent + maybe_key + "{", Description("json object")});
1099 for (const auto& i : m_inner) {
1100 i.ToSections(sections, OuterType::OBJ, current_indent + 2);
1101 }
1102 if (m_type == Type::OBJ_DYN && m_inner.back().m_type != Type::ELISION) {
1103 // If the dictionary keys are dynamic, use three dots for continuation
1104 sections.PushSection({indent_next + "...", ""});
1105 } else {
1106 // Remove final comma, which would be invalid JSON
1107 sections.m_sections.back().m_left.pop_back();
1108 }
1109 sections.PushSection({indent + "}" + maybe_separator, ""});
1110 return;
1111 }
1112 } // no default case, so the compiler can warn about missing cases
1114}
1115
1116static std::optional<UniValue::VType> ExpectedType(RPCResult::Type type)
1117{
1118 using Type = RPCResult::Type;
1119 switch (type) {
1120 case Type::ELISION:
1121 case Type::ANY: {
1122 return std::nullopt;
1123 }
1124 case Type::NONE: {
1125 return UniValue::VNULL;
1126 }
1127 case Type::STR:
1128 case Type::STR_HEX: {
1129 return UniValue::VSTR;
1130 }
1131 case Type::NUM:
1132 case Type::STR_AMOUNT:
1133 case Type::NUM_TIME: {
1134 return UniValue::VNUM;
1135 }
1136 case Type::BOOL: {
1137 return UniValue::VBOOL;
1138 }
1139 case Type::ARR_FIXED:
1140 case Type::ARR: {
1141 return UniValue::VARR;
1142 }
1143 case Type::OBJ_DYN:
1144 case Type::OBJ: {
1145 return UniValue::VOBJ;
1146 }
1147 } // no default case, so the compiler can warn about missing cases
1149}
1150
1151// NOLINTNEXTLINE(misc-no-recursion)
1153{
1154 if (m_skip_type_check) {
1155 return true;
1156 }
1157
1158 const auto exp_type = ExpectedType(m_type);
1159 if (!exp_type) return true; // can be any type, so nothing to check
1160
1161 if (*exp_type != result.getType()) {
1162 return strprintf("returned type is %s, but declared as %s in doc", uvTypeName(result.getType()), uvTypeName(*exp_type));
1163 }
1164
1165 if (UniValue::VARR == result.getType()) {
1166 UniValue errors(UniValue::VOBJ);
1167 for (size_t i{0}; i < result.get_array().size(); ++i) {
1168 // If there are more results than documented, reuse the last doc_inner.
1169 const RPCResult& doc_inner{m_inner.at(std::min(m_inner.size() - 1, i))};
1170 UniValue match{doc_inner.MatchesType(result.get_array()[i])};
1171 if (!match.isTrue()) errors.pushKV(strprintf("%d", i), std::move(match));
1172 }
1173 if (errors.empty()) return true; // empty result array is valid
1174 return errors;
1175 }
1176
1177 if (UniValue::VOBJ == result.getType()) {
1178 if (!m_inner.empty() && m_inner.at(0).m_type == Type::ELISION) return true;
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.find(result_entry.first) == doc_keys.end()) {
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 if (low > high) throw JSONRPCError(RPC_INVALID_PARAMETER, "Range specified as [begin,end] must not have begin after end");
1324 return {low, high};
1325 }
1326 throw JSONRPCError(RPC_INVALID_PARAMETER, "Range must be specified as end or as [begin,end]");
1327}
1328
1329std::pair<int64_t, int64_t> ParseDescriptorRange(const UniValue& value)
1330{
1331 int64_t low, high;
1332 std::tie(low, high) = ParseRange(value);
1333 if (low < 0) {
1334 throw JSONRPCError(RPC_INVALID_PARAMETER, "Range should be greater or equal than 0");
1335 }
1336 if ((high >> 31) != 0) {
1337 throw JSONRPCError(RPC_INVALID_PARAMETER, "End of range is too high");
1338 }
1339 if (high >= low + 1000000) {
1340 throw JSONRPCError(RPC_INVALID_PARAMETER, "Range is too large");
1341 }
1342 return {low, high};
1343}
1344
1345std::vector<CScript> EvalDescriptorStringOrObject(const UniValue& scanobject, FlatSigningProvider& provider, const bool expand_priv)
1346{
1347 std::string desc_str;
1348 std::pair<int64_t, int64_t> range = {0, 1000};
1349 if (scanobject.isStr()) {
1350 desc_str = scanobject.get_str();
1351 } else if (scanobject.isObject()) {
1352 const UniValue& desc_uni{scanobject.find_value("desc")};
1353 if (desc_uni.isNull()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Descriptor needs to be provided in scan object");
1354 desc_str = desc_uni.get_str();
1355 const UniValue& range_uni{scanobject.find_value("range")};
1356 if (!range_uni.isNull()) {
1357 range = ParseDescriptorRange(range_uni);
1358 }
1359 } else {
1360 throw JSONRPCError(RPC_INVALID_PARAMETER, "Scan object needs to be either a string or an object");
1361 }
1362
1363 std::string error;
1364 auto descs = Parse(desc_str, provider, error);
1365 if (descs.empty()) {
1367 }
1368 if (!descs.at(0)->IsRange()) {
1369 range.first = 0;
1370 range.second = 0;
1371 }
1372 std::vector<CScript> ret;
1373 for (int i = range.first; i <= range.second; ++i) {
1374 for (const auto& desc : descs) {
1375 std::vector<CScript> scripts;
1376 if (!desc->Expand(i, provider, scripts, provider)) {
1377 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Cannot derive script without private keys: '%s'", desc_str));
1378 }
1379 if (expand_priv) {
1380 desc->ExpandPrivate(/*pos=*/i, provider, /*out=*/provider);
1381 }
1382 std::move(scripts.begin(), scripts.end(), std::back_inserter(ret));
1383 }
1384 }
1385 return ret;
1386}
1387
1389[[nodiscard]] static UniValue BilingualStringsToUniValue(const std::vector<bilingual_str>& bilingual_strings)
1390{
1391 CHECK_NONFATAL(!bilingual_strings.empty());
1392 UniValue result{UniValue::VARR};
1393 for (const auto& s : bilingual_strings) {
1394 result.push_back(s.original);
1395 }
1396 return result;
1397}
1398
1399void PushWarnings(const UniValue& warnings, UniValue& obj)
1400{
1401 if (warnings.empty()) return;
1402 obj.pushKV("warnings", warnings);
1403}
1404
1405void PushWarnings(const std::vector<bilingual_str>& warnings, UniValue& obj)
1406{
1407 if (warnings.empty()) return;
1408 obj.pushKV("warnings", BilingualStringsToUniValue(warnings));
1409}
1410
1411std::vector<RPCResult> ScriptPubKeyDoc() {
1412 return
1413 {
1414 {RPCResult::Type::STR, "asm", "Disassembly of the output script"},
1415 {RPCResult::Type::STR, "desc", "Inferred descriptor for the output"},
1416 {RPCResult::Type::STR_HEX, "hex", "The raw output script bytes, hex-encoded"},
1417 {RPCResult::Type::STR, "address", /*optional=*/true, "The Bitcoin address (only if a well-defined address exists)"},
1418 {RPCResult::Type::STR, "type", "The type (one of: " + GetAllOutputTypes() + ")"},
1419 };
1420}
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination corresponds to one with an address.
std::variant< CNoDestination, PubKeyDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, PayToAnchor, WitnessUnknown > CTxDestination
A txout script categorized into standard templates.
Definition: addresstype.h:140
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
int ret
ArgsManager & args
Definition: bitcoind.cpp:277
#define CHECK_NONFATAL(condition)
Identity function.
Definition: check.h:81
#define NONFATAL_UNREACHABLE()
NONFATAL_UNREACHABLE() is a macro that is used to mark unreachable code.
Definition: check.h:102
#define STR_INTERNAL_BUG(msg)
Definition: check.h:68
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: args.cpp:507
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
Definition: feerate.h:33
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:24
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:314
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:415
UniValue operator()(const WitnessUnknown &id) const
Definition: util.cpp:359
UniValue operator()(const WitnessV0KeyHash &id) const
Definition: util.cpp:321
UniValue operator()(const WitnessV0ScriptHash &id) const
Definition: util.cpp:331
DescribeAddressVisitor()=default
UniValue operator()(const CNoDestination &dest) const
Definition: util.cpp:295
UniValue operator()(const PubKeyDestination &dest) const
Definition: util.cpp:300
UniValue operator()(const WitnessV1Taproot &tap) const
Definition: util.cpp:341
UniValue operator()(const ScriptHash &scriptID) const
Definition: util.cpp:313
UniValue operator()(const PKHash &keyID) const
Definition: util.cpp:305
UniValue operator()(const PayToAnchor &anchor) const
Definition: util.cpp:351
Fillable signing provider that keeps keys in an address->secret map.
virtual bool GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const override
UniValue params
Definition: request.h:40
enum JSONRPCRequest::Mode mode
std::function< UniValue(const RPCHelpMan &, const JSONRPCRequest &)> RPCMethodImpl
Definition: util.h:419
const RPCExamples m_examples
Definition: util.h:500
size_t GetParamIndex(std::string_view key) const
Return positional index of a parameter using its name as key.
Definition: util.cpp:782
RPCHelpMan(std::string name, std::string description, std::vector< RPCArg > args, RPCResults results, RPCExamples examples)
Definition: util.cpp:567
const std::string m_description
Definition: util.h:497
bool IsValidNumArgs(size_t num_args) const
If the supplied number of args is neither too small nor too high.
Definition: util.cpp:755
const RPCMethodImpl m_fun
Definition: util.h:496
const std::string m_name
Definition: util.h:493
const RPCResults m_results
Definition: util.h:499
const std::vector< RPCArg > m_args
Definition: util.h:498
std::string ToString() const
Definition: util.cpp:792
UniValue GetArgMap() const
Return the named args that need to be converted from string to another JSON type.
Definition: util.cpp:854
std::vector< std::pair< std::string, bool > > GetArgNames() const
Return list of arguments and whether they are named-only.
Definition: util.cpp:767
const JSONRPCRequest * m_req
Definition: util.h:501
UniValue HandleRequest(const JSONRPCRequest &request) const
Definition: util.cpp:657
const std::string & get_str() const
bool isArray() const
Definition: univalue.h:85
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:79
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:126
const std::vector< std::string > & getKeys() const
bool empty() const
Definition: univalue.h:69
bool isStr() const
Definition: univalue.h:83
bool isBool() const
Definition: univalue.h:82
Int getInt() const
Definition: univalue.h:138
const UniValue & get_array() const
bool isNum() const
Definition: univalue.h:84
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:86
constexpr bool IsNull() const
Definition: uint256.h:48
static constexpr unsigned int size()
Definition: uint256.h:110
size_type size() const
Definition: prevector.h:294
256-bit opaque blob.
Definition: uint256.h:190
static std::optional< uint256 > FromHex(std::string_view str)
Definition: uint256.h:192
static UniValue Parse(std::string_view raw)
Parse string to UniValue or throw runtime_error if string contains invalid JSON.
Definition: client.cpp:327
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 Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: hex_base.cpp:29
@ SIGHASH_DEFAULT
Taproot only; implied when sighash byte is missing, and equivalent to SIGHASH_ALL.
Definition: interpreter.h:35
CTxDestination DecodeDestination(const std::string &str, std::string &error_msg, std::vector< int > *error_locations)
Definition: key_io.cpp:299
is a home for simple string functions returning descriptive messages that are used in RPC and GUI int...
@ NONE
Definition: logging.h:42
char const * json() noexcept
Template to generate JSON data.
PSBTError
Definition: types.h:17
bilingual_str PSBTErrorString(PSBTError err)
Definition: messages.cpp:106
bilingual_str TransactionErrorString(const TransactionError err)
Definition: messages.cpp:124
TransactionError
Definition: types.h:20
std::vector< std::string > SplitString(std::string_view str, char sep)
Definition: string.h:136
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:233
std::string TrimString(std::string_view str, std::string_view pattern=" \f\n\r\t\v")
Definition: string.h:156
auto Join(const C &container, const S &separator, UnaryOp unary_op)
Join all container items.
Definition: string.h:192
is a home for public enum and struct type definitions that are used by 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:84
OutputType
Definition: outputtype.h:17
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:70
const char * name
Definition: rest.cpp:49
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_INTERNAL_ERROR
Definition: protocol.h:36
@ 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:710
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:1345
void(const RPCArg &) CheckFn
Definition: util.cpp:709
std::pair< int64_t, int64_t > ParseDescriptorRange(const UniValue &value)
Parse a JSON range specified as int64, or [int64, int64].
Definition: util.cpp:1329
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:184
std::string HelpExampleRpcNamed(const std::string &methodname, const RPCArgList &args)
Definition: util.cpp:208
CAmount AmountFromValue(const UniValue &value, int decimals)
Validate and return a CAmount from a UniValue number or string.
Definition: util.cpp:99
RPCErrorCode RPCErrorFromPSBTError(PSBTError err)
Definition: util.cpp:401
std::vector< unsigned char > ParseHexV(const UniValue &v, std::string_view name)
Definition: util.cpp:131
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:1389
void PushWarnings(const UniValue &warnings, UniValue &obj)
Push warning messages to an RPC "warnings" field as a JSON array of strings.
Definition: util.cpp:1399
int ParseSighashString(const UniValue &sighash)
Returns a sighash value corresponding to the passed in argument.
Definition: util.cpp:379
UniValue JSONRPCTransactionError(TransactionError terr, const std::string &err_string)
Definition: util.cpp:430
#define TMPL_INST(check_param, ret_type, return_code)
Definition: util.cpp:731
std::vector< unsigned char > ParseHexO(const UniValue &o, std::string_view strKey)
Definition: util.cpp:140
UniValue JSONRPCPSBTError(PSBTError err)
Definition: util.cpp:425
RPCErrorCode RPCErrorFromTransactionError(TransactionError terr)
Definition: util.cpp:413
CFeeRate ParseFeeRate(const UniValue &json)
Parse a json number or string, denoting BTC/kvB, into a CFeeRate (sat/kvB).
Definition: util.cpp:111
static std::optional< UniValue::VType > ExpectedType(RPCArg::Type type)
Definition: util.cpp:886
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:202
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:44
std::string GetAllOutputTypes()
Gets all existing output types formatted for RPC help sections.
Definition: util.cpp:47
int ParseVerbosity(const UniValue &arg, int default_verbosity, bool allow_bool)
Parses verbosity from provided UniValue.
Definition: util.cpp:84
CPubKey HexToPubKey(const std::string &hex_in)
Definition: util.cpp:220
const std::string EXAMPLE_ADDRESS[2]
Example bech32 addresses for the RPCExamples help documentation.
Definition: util.cpp:45
CTxDestination AddAndGetMultisigDestination(const int required, const std::vector< CPubKey > &pubkeys, OutputType type, FlatSigningProvider &keystore, CScript &script_out)
Definition: util.cpp:257
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:127
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:391
void RPCTypeCheckObj(const UniValue &o, const std::map< std::string, UniValueType > &typesExpected, bool fAllowNull, bool fStrict)
Definition: util.cpp:57
std::string HelpExampleCliNamed(const std::string &methodname, const RPCArgList &args)
Definition: util.cpp:189
uint256 ParseHashV(const UniValue &v, std::string_view name)
Utilities: convert hex-encoded Values (throws error if not hex).
Definition: util.cpp:118
static void CheckRequiredOrDefault(const RPCArg &param)
Definition: util.cpp:722
CPubKey AddrToPubKey(const FillableSigningProvider &keystore, const std::string &addr_in)
Definition: util.cpp:236
UniValue DescribeAddress(const CTxDestination &dest)
Definition: util.cpp:369
std::vector< RPCResult > ScriptPubKeyDoc()
Definition: util.cpp:1411
std::vector< std::pair< std::string, UniValue > > RPCArgList
Definition: util.h:128
static constexpr bool DEFAULT_RPC_DOC_CHECK
Definition: util.h:46
OuterType
Serializing JSON objects depends on the outer type.
Definition: util.h:160
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
CKeyID GetKeyForDestination(const SigningProvider &store, const CTxDestination &dest)
Return the CKeyID of the key involved in a script (if there is a unique one).
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:183
Type
Definition: util.h:184
@ 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:224
const RPCArgOptions m_opts
Definition: util.h:227
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:222
const Fallback m_fallback
Definition: util.h:225
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:920
const std::string m_description
Definition: util.h:226
bool IsOptional() const
Definition: util.cpp:944
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:953
const Type m_type
Definition: util.h:223
std::string GetName() const
Return the name, throws when there are aliases.
Definition: util.cpp:938
std::string GetFirstName() const
Return the first of all aliases.
Definition: util.cpp:933
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:169
std::string oneline_description
Should be empty unless it is supposed to override the auto-generated summary line.
Definition: util.h:168
bool skip_type_check
Definition: util.h:167
std::string ToDescriptionString() const
Definition: util.cpp:652
const std::string m_examples
Definition: util.h:406
const std::string m_description
Definition: util.h:315
void ToSections(Sections &sections, OuterType outer_type=OuterType::NONE, const int current_indent=0) const
Append the sections of the result.
Definition: util.cpp:1018
@ 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:312
UniValue MatchesType(const UniValue &result) const
Check whether the result JSON type matches.
Definition: util.cpp:1152
void CheckInnerDoc() const
Definition: util.cpp:1219
const bool m_optional
Definition: util.h:313
const std::string m_key_name
Only used for dicts.
Definition: util.h:311
const Type m_type
Definition: util.h:310
const bool m_skip_type_check
Definition: util.h:314
std::string ToDescriptionString() const
Return the description string.
Definition: util.cpp:635
const std::vector< RPCResult > m_results
Definition: util.h:387
A pair of strings that can be aligned (through padding) with other Sections later on.
Definition: util.cpp:443
std::string m_left
Definition: util.cpp:446
Section(const std::string &left, const std::string &right)
Definition: util.cpp:444
const std::string m_right
Definition: util.cpp:447
Keeps track of RPCArgs by transforming them into sections for the purpose of serializing everything t...
Definition: util.cpp:454
void PushSection(const Section &s)
Definition: util.cpp:458
std::vector< Section > m_sections
Definition: util.cpp:455
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:468
size_t m_max_pad
Definition: util.cpp:456
std::string ToString() const
Concatenate all sections with proper padding.
Definition: util.cpp:526
CTxDestination subtype to encode any future Witness version.
Definition: addresstype.h:96
#define NUM
Definition: tests.c:3597
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1165
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)