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