Bitcoin ABC 0.34.5
P2P Digital Currency
Loading...
Searching...
No Matches
util.cpp
Go to the documentation of this file.
1// Copyright (c) 2017-2021 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 <clientversion.h>
8#include <common/args.h>
9#include <common/messages.h>
10#include <common/types.h>
11#include <consensus/amount.h>
12#include <key_io.h>
13#include <node/types.h>
14#include <script/descriptor.h>
16#include <script/solver.h>
17#include <tinyformat.h>
18#include <util/check.h>
19#include <util/strencodings.h>
20#include <util/string.h>
21#include <util/translation.h>
22
23#include <algorithm>
24#include <iterator>
25#include <string_view>
26#include <tuple>
27#include <variant>
28
33using util::Join;
35
36const std::string UNIX_EPOCH_TIME = "UNIX epoch time";
37const std::string EXAMPLE_ADDRESS =
38 "\"qrmzys48glkpevp2l4t24jtcltc9hyzx9cep2qffm4\"";
39
41 const std::map<std::string, UniValueType> &typesExpected,
42 bool fAllowNull, bool fStrict) {
43 for (const auto &t : typesExpected) {
44 const UniValue &v = o.find_value(t.first);
45 if (!fAllowNull && v.isNull()) {
47 strprintf("Missing %s", t.first));
48 }
49
50 if (!(t.second.typeAny || v.type() == t.second.type ||
51 (fAllowNull && v.isNull()))) {
52 std::string err = strprintf("Expected type %s for %s, got %s",
53 uvTypeName(t.second.type), t.first,
54 uvTypeName(v.type()));
55 throw JSONRPCError(RPC_TYPE_ERROR, err);
56 }
57 }
58
59 if (fStrict) {
60 for (const std::string &k : o.getKeys()) {
61 if (typesExpected.count(k) == 0) {
62 std::string err = strprintf("Unexpected key %s", k);
63 throw JSONRPCError(RPC_TYPE_ERROR, err);
64 }
65 }
66 }
67}
68
70 if (!value.isNum() && !value.isStr()) {
71 throw JSONRPCError(RPC_TYPE_ERROR, "Amount is not a number or string");
72 }
73
74 int64_t n;
75 if (!ParseFixedPoint(value.getValStr(), Currency::get().decimals, &n)) {
76 throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
77 }
78
79 Amount amt = n * SATOSHI;
80 if (!MoneyRange(amt)) {
81 throw JSONRPCError(RPC_TYPE_ERROR, "Amount out of range");
82 }
83
84 return amt;
85}
86
87uint256 ParseHashV(const UniValue &v, std::string strName) {
88 const std::string &strHex(v.get_str());
89 if (64 != strHex.length()) {
90 throw JSONRPCError(
92 strprintf("%s must be of length %d (not %d, for '%s')", strName, 64,
93 strHex.length(), strHex));
94 }
95 // Note: IsHex("") is false
96 if (!IsHex(strHex)) {
98 strName + " must be hexadecimal string (not '" +
99 strHex + "')");
100 }
101 return uint256S(strHex);
102}
103
104uint256 ParseHashO(const UniValue &o, std::string strKey) {
105 return ParseHashV(o.find_value(strKey), strKey);
106}
107
108std::vector<uint8_t> ParseHexV(const UniValue &v, std::string strName) {
109 std::string strHex;
110 if (v.isStr()) {
111 strHex = v.get_str();
112 }
113 if (!IsHex(strHex)) {
115 strName + " must be hexadecimal string (not '" +
116 strHex + "')");
117 }
118
119 return ParseHex(strHex);
120}
121
122std::vector<uint8_t> ParseHexO(const UniValue &o, std::string strKey) {
123 return ParseHexV(o.find_value(strKey), strKey);
124}
125
126int ParseVerbosity(const UniValue &arg, int default_verbosity,
127 bool allow_bool) {
128 if (!arg.isNull()) {
129 if (arg.isBool()) {
130 if (!allow_bool) {
131 throw JSONRPCError(
133 "Verbosity was boolean but only integer allowed");
134 }
135 // true = 1
136 return arg.get_bool();
137 } else {
138 return arg.getInt<int>();
139 }
140 }
141 return default_verbosity;
142}
143
144namespace {
145
151std::string ShellQuote(const std::string &s) {
152 std::string result;
153 result.reserve(s.size() * 2);
154 for (const char ch : s) {
155 if (ch == '\'') {
156 result += "'\''";
157 } else {
158 result += ch;
159 }
160 }
161 return "'" + result + "'";
162}
163
170std::string ShellQuoteIfNeeded(const std::string &s) {
171 for (const char ch : s) {
172 if (ch == ' ' || ch == '\'' || ch == '"') {
173 return ShellQuote(s);
174 }
175 }
176
177 return s;
178}
179
180} // namespace
181
182std::string HelpExampleCli(const std::string &methodname,
183 const std::string &args) {
184 return "> bitcoin-cli " + methodname + " " + args + "\n";
185}
186
187std::string HelpExampleCliNamed(const std::string &methodname,
188 const RPCArgList &args) {
189 std::string result = "> bitcoin-cli -named " + methodname;
190 for (const auto &argpair : args) {
191 const auto &value = argpair.second.isStr() ? argpair.second.get_str()
192 : argpair.second.write();
193 result += " " + argpair.first + "=" + ShellQuoteIfNeeded(value);
194 }
195 result += "\n";
196 return result;
197}
198
199std::string HelpExampleRpc(const std::string &methodname,
200 const std::string &args) {
201 return "> curl --user myusername --data-binary '{\"jsonrpc\": \"1.0\", "
202 "\"id\": \"curltest\", "
203 "\"method\": \"" +
204 methodname + "\", \"params\": [" + args +
205 "]}' -H 'content-type: text/plain;' http://127.0.0.1:8332/\n";
206}
207
208std::string HelpExampleRpcNamed(const std::string &methodname,
209 const RPCArgList &args) {
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\": \"1.0\", "
216 "\"id\": \"curltest\", "
217 "\"method\": \"" +
218 methodname + "\", \"params\": " + params.write() +
219 "}' -H 'content-type: text/plain;' http://127.0.0.1:8332/\n";
220}
221
222// Converts a hex string to a public key if possible
223CPubKey HexToPubKey(const std::string &hex_in) {
224 if (!IsHex(hex_in)) {
226 "Invalid public key: " + hex_in);
227 }
228 CPubKey vchPubKey(ParseHex(hex_in));
229 if (!vchPubKey.IsFullyValid()) {
231 "Invalid public key: " + hex_in);
232 }
233 return vchPubKey;
234}
235
236// Retrieves a public key for an address from the given FillableSigningProvider
238 const FillableSigningProvider &keystore,
239 const std::string &addr_in) {
240 CTxDestination dest = DecodeDestination(addr_in, chainparams);
241 if (!IsValidDestination(dest)) {
243 "Invalid address: " + addr_in);
244 }
245 CKeyID key = GetKeyForDestination(keystore, dest);
246 if (key.IsNull()) {
248 strprintf("%s does not refer to a key", addr_in));
249 }
250 CPubKey vchPubKey;
251 if (!keystore.GetPubKey(key, vchPubKey)) {
252 throw JSONRPCError(
254 strprintf("no full public key for address %s", addr_in));
255 }
256 if (!vchPubKey.IsFullyValid()) {
258 "Wallet contains an invalid public key");
259 }
260 return vchPubKey;
261}
262
263// Creates a multisig address from a given list of public keys, number of
264// signatures required, and the address type
266 const std::vector<CPubKey> &pubkeys,
267 OutputType type,
268 FillableSigningProvider &keystore,
269 CScript &script_out) {
270 // Gather public keys
271 if (required < 1) {
272 throw JSONRPCError(
274 "a multisignature address must require at least one key to redeem");
275 }
276 if ((int)pubkeys.size() < required) {
278 strprintf("not enough keys supplied (got %u keys, "
279 "but need at least %d to redeem)",
280 pubkeys.size(), required));
281 }
282 if (pubkeys.size() > 16) {
284 "Number of keys involved in the multisignature "
285 "address creation > 16\nReduce the number");
286 }
287
288 script_out = GetScriptForMultisig(required, pubkeys);
289
290 if (script_out.size() > MAX_SCRIPT_ELEMENT_SIZE) {
291 throw JSONRPCError(
293 (strprintf("redeemScript exceeds size limit: %d > %d",
294 script_out.size(), MAX_SCRIPT_ELEMENT_SIZE)));
295 }
296
297 // Check if any keys are uncompressed. If so, the type is legacy
298 for (const CPubKey &pk : pubkeys) {
299 if (!pk.IsCompressed()) {
300 type = OutputType::LEGACY;
301 break;
302 }
303 }
304
305 // Make the address
306 CTxDestination dest =
307 AddAndGetDestinationForScript(keystore, script_out, type);
308
309 return dest;
310}
311
313public:
314 explicit DescribeAddressVisitor() = default;
315
316 UniValue operator()(const CNoDestination &dest) const {
317 return UniValue(UniValue::VOBJ);
318 }
319
320 UniValue operator()(const PKHash &keyID) const {
322 obj.pushKV("isscript", false);
323 return obj;
324 }
325
326 UniValue operator()(const ScriptHash &scriptID) const {
328 obj.pushKV("isscript", true);
329 return obj;
330 }
331};
332
334 return std::visit(DescribeAddressVisitor(), dest);
335}
336
337std::string GetAllOutputTypes() {
338 std::vector<std::string> ret;
339 using U = std::underlying_type<TxoutType>::type;
340 for (U i = (U)TxoutType::NONSTANDARD; i <= (U)TxoutType::NULL_DATA; ++i) {
341 ret.emplace_back(GetTxnOutputType(static_cast<TxoutType>(i)));
342 }
343 return Join(ret, ", ");
344}
345
347 switch (err) {
348 case PSBTError::UNSUPPORTED:
350 case PSBTError::SIGHASH_MISMATCH:
352 default:
353 break;
354 }
356}
357
359 switch (terr) {
360 case TransactionError::MEMPOOL_REJECTED:
362 case TransactionError::ALREADY_IN_CHAIN:
364 default:
365 break;
366 }
368}
369
372 PSBTErrorString(err).original);
373}
374
375UniValue JSONRPCTransactionError(TransactionError terr,
376 const std::string &err_string) {
377 if (err_string.length() > 0) {
378 return JSONRPCError(RPCErrorFromTransactionError(terr), err_string);
379 } else {
381 TransactionErrorString(terr).original);
382 }
383}
384
389struct Section {
390 Section(const std::string &left, const std::string &right)
391 : m_left{left}, m_right{right} {}
392 std::string m_left;
393 const std::string m_right;
394};
395
400struct Sections {
401 std::vector<Section> m_sections;
402 size_t m_max_pad{0};
403
404 void PushSection(const Section &s) {
405 m_max_pad = std::max(m_max_pad, s.m_left.size());
406 m_sections.push_back(s);
407 }
408
412 void Push(const RPCArg &arg, const size_t current_indent = 5,
413 const OuterType outer_type = OuterType::NONE) {
414 const auto indent = std::string(current_indent, ' ');
415 const auto indent_next = std::string(current_indent + 2, ' ');
416 // Dictionary keys must have a name
417 const bool push_name{outer_type == OuterType::OBJ};
418 // True on the first recursion
419 const bool is_top_level_arg{outer_type == OuterType::NONE};
420
421 switch (arg.m_type) {
429 // Nothing more to do for non-recursive types on first recursion
430 if (is_top_level_arg) {
431 return;
432 }
433 auto left = indent;
434 if (arg.m_opts.type_str.size() != 0 && push_name) {
435 left += "\"" + arg.GetName() +
436 "\": " + arg.m_opts.type_str.at(0);
437 } else {
438 left += push_name ? arg.ToStringObj(/* oneline */ false)
439 : arg.ToString(/* oneline */ false);
440 }
441 left += ",";
443 /*is_named_arg=*/push_name)});
444 break;
445 }
448 const auto right =
449 is_top_level_arg
450 ? ""
451 : arg.ToDescriptionString(/*is_named_arg=*/push_name);
453 {indent + (push_name ? "\"" + arg.GetName() + "\": " : "") +
454 "{",
455 right});
456 for (const auto &arg_inner : arg.m_inner) {
457 Push(arg_inner, current_indent + 2, OuterType::OBJ);
458 }
459 if (arg.m_type != RPCArg::Type::OBJ) {
460 PushSection({indent_next + "...", ""});
461 }
462 PushSection({indent + "}" + (is_top_level_arg ? "" : ","), ""});
463 break;
464 }
465 case RPCArg::Type::ARR: {
466 auto left = indent;
467 left += push_name ? "\"" + arg.GetName() + "\": " : "";
468 left += "[";
469 const auto right =
470 is_top_level_arg
471 ? ""
472 : arg.ToDescriptionString(/*is_named_arg=*/push_name);
473 PushSection({left, right});
474 for (const auto &arg_inner : arg.m_inner) {
475 Push(arg_inner, current_indent + 2, OuterType::ARR);
476 }
477 PushSection({indent_next + "...", ""});
478 PushSection({indent + "]" + (is_top_level_arg ? "" : ","), ""});
479 break;
480 } // no default case, so the compiler can warn about missing cases
481 }
482 }
483
487 std::string ToString() const {
488 std::string ret;
489 const size_t pad = m_max_pad + 4;
490 for (const auto &s : m_sections) {
491 // The left part of a section is assumed to be a single line,
492 // usually it is the name of the JSON struct or a brace like
493 // {, }, [, or ]
494 CHECK_NONFATAL(s.m_left.find('\n') == std::string::npos);
495 if (s.m_right.empty()) {
496 ret += s.m_left;
497 ret += "\n";
498 continue;
499 }
500
501 std::string left = s.m_left;
502 left.resize(pad, ' ');
503 ret += left;
504
505 // Properly pad after newlines
506 std::string right;
507 size_t begin = 0;
508 size_t new_line_pos = s.m_right.find_first_of('\n');
509 while (true) {
510 right += s.m_right.substr(begin, new_line_pos - begin);
511 if (new_line_pos == std::string::npos) {
512 // No new line
513 break;
514 }
515 right += "\n" + std::string(pad, ' ');
516 begin = s.m_right.find_first_not_of(' ', new_line_pos + 1);
517 if (begin == std::string::npos) {
518 break; // Empty line
519 }
520 new_line_pos = s.m_right.find_first_of('\n', begin + 1);
521 }
522 ret += right;
523 ret += "\n";
524 }
525 return ret;
526 }
527};
528
529RPCHelpMan::RPCHelpMan(std::string name_, std::string description,
530 std::vector<RPCArg> args, RPCResults results,
531 RPCExamples examples)
532 : RPCHelpMan{std::move(name_), std::move(description), std::move(args),
533 std::move(results), std::move(examples), nullptr} {}
534
535RPCHelpMan::RPCHelpMan(std::string name_, std::string description,
536 std::vector<RPCArg> args, RPCResults results,
537 RPCExamples examples, RPCMethodImpl fun)
538 : m_name{std::move(name_)}, m_fun{std::move(fun)},
539 m_description{std::move(description)}, m_args{std::move(args)},
540 m_results{std::move(results)}, m_examples{std::move(examples)} {
541 // Map of parameter names and types just used to check whether the names are
542 // unique. Parameter names always need to be unique, with the exception that
543 // there can be pairs of POSITIONAL and NAMED parameters with the same name.
544 enum ParamType { POSITIONAL = 1, NAMED = 2, NAMED_ONLY = 4 };
545 std::map<std::string, int> param_names;
546
547 for (const auto &arg : m_args) {
548 std::vector<std::string> names = SplitString(arg.m_names, '|');
549 // Should have unique named arguments
550 for (const std::string &name : names) {
551 auto &param_type = param_names[name];
552 CHECK_NONFATAL(!(param_type & POSITIONAL));
553 CHECK_NONFATAL(!(param_type & NAMED_ONLY));
554 param_type |= POSITIONAL;
555 }
556 if (arg.m_type == RPCArg::Type::OBJ_NAMED_PARAMS) {
557 for (const auto &inner : arg.m_inner) {
558 std::vector<std::string> inner_names =
559 SplitString(inner.m_names, '|');
560 for (const std::string &inner_name : inner_names) {
561 auto &param_type = param_names[inner_name];
562 CHECK_NONFATAL(!(param_type & POSITIONAL) ||
563 inner.m_opts.also_positional);
564 CHECK_NONFATAL(!(param_type & NAMED));
565 CHECK_NONFATAL(!(param_type & NAMED_ONLY));
566 param_type |=
567 inner.m_opts.also_positional ? NAMED : NAMED_ONLY;
568 }
569 }
570 }
571 // Default value type should match argument type only when defined
572 if (arg.m_fallback.index() == 2) {
573 const RPCArg::Type type = arg.m_type;
574 switch (std::get<RPCArg::Default>(arg.m_fallback).getType()) {
575 case UniValue::VOBJ:
577 break;
578 case UniValue::VARR:
580 break;
581 case UniValue::VSTR:
583 type == RPCArg::Type::STR_HEX ||
584 type == RPCArg::Type::AMOUNT);
585 break;
586 case UniValue::VNUM:
588 type == RPCArg::Type::AMOUNT ||
589 type == RPCArg::Type::RANGE);
590 break;
591 case UniValue::VBOOL:
593 break;
594 case UniValue::VNULL:
595 // Null values are accepted in all arguments
596 break;
597 default:
598 CHECK_NONFATAL(false);
599 break;
600 }
601 }
602 }
603}
604
606 std::string result;
607
608 for (const auto &r : m_results) {
609 if (r.m_type == RPCResult::Type::ANY) {
610 // for testing only
611 continue;
612 }
613 if (r.m_cond.empty()) {
614 result += "\nResult:\n";
615 } else {
616 result += "\nResult (" + r.m_cond + "):\n";
617 }
618 Sections sections;
619 r.ToSections(sections);
620 result += sections.ToString();
621 }
622 return result;
623}
624
626 return m_examples.empty() ? m_examples : "\nExamples:\n" + m_examples;
627}
628
630 const JSONRPCRequest &request) const {
631 if (request.mode == JSONRPCRequest::GET_ARGS) {
632 return GetArgMap();
633 }
634 /*
635 * Check if the given request is valid according to this command or if
636 * the user is asking for help information, and throw help when appropriate.
637 */
638 if (request.mode == JSONRPCRequest::GET_HELP ||
639 !IsValidNumArgs(request.params.size())) {
640 throw std::runtime_error(ToString());
641 }
642 UniValue arg_mismatch{UniValue::VOBJ};
643 for (size_t i{0}; i < m_args.size(); ++i) {
644 const auto &arg{m_args.at(i)};
645 UniValue match{arg.MatchesType(request.params[i])};
646 if (!match.isTrue()) {
647 arg_mismatch.pushKV(
648 strprintf("Position %s (%s)", i + 1, arg.m_names),
649 std::move(match));
650 }
651 }
652 if (!arg_mismatch.empty()) {
653 throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Wrong type passed:\n%s",
654 arg_mismatch.write(4)));
655 }
656 CHECK_NONFATAL(m_req == nullptr);
657 m_req = &request;
658 UniValue ret = m_fun(*this, config, request);
659 m_req = nullptr;
660 if (gArgs.GetBoolArg("-rpcdoccheck", DEFAULT_RPC_DOC_CHECK)) {
661 UniValue mismatch{UniValue::VARR};
662 for (const auto &res : m_results.m_results) {
663 UniValue match{res.MatchesType(ret)};
664 if (match.isTrue()) {
665 mismatch.setNull();
666 break;
667 }
668 mismatch.push_back(std::move(match));
669 }
670 if (!mismatch.isNull()) {
671 std::string explain{mismatch.empty() ? "no possible results defined"
672 : mismatch.size() == 1 ? mismatch[0].write(4)
673 : mismatch.write(4)};
674 throw std::runtime_error{strprintf(
675 "Internal bug detected: RPC call \"%s\" returned incorrect "
676 "type:\n%s\n%s %s\nPlease report this issue here: %s\n",
677 m_name, explain, PACKAGE_NAME, FormatFullVersion(),
678 PACKAGE_BUGREPORT)};
679 }
680 }
681 return ret;
682}
683
684using CheckFn = void(const RPCArg &);
685static const UniValue *DetailMaybeArg(CheckFn *check,
686 const std::vector<RPCArg> &params,
687 const JSONRPCRequest *req, size_t i) {
688 CHECK_NONFATAL(i < params.size());
689 const UniValue &arg{CHECK_NONFATAL(req)->params[i]};
690 const RPCArg &param{params.at(i)};
691 if (check) {
692 check(param);
693 }
694
695 if (!arg.isNull()) {
696 return &arg;
697 }
698 if (!std::holds_alternative<RPCArg::Default>(param.m_fallback)) {
699 return nullptr;
700 }
701 return &std::get<RPCArg::Default>(param.m_fallback);
702}
703
704static void CheckRequiredOrDefault(const RPCArg &param) {
705 // Must use `Arg<Type>(i)` to get the argument or its default value.
706 const bool required{
707 std::holds_alternative<RPCArg::Optional>(param.m_fallback) &&
709 std::get<RPCArg::Optional>(param.m_fallback),
710 };
711 CHECK_NONFATAL(required ||
712 std::holds_alternative<RPCArg::Default>(param.m_fallback));
713}
714
715#define TMPL_INST(check_param, ret_type, return_code) \
716 template <> ret_type RPCHelpMan::ArgValue<ret_type>(size_t i) const { \
717 const UniValue *maybe_arg{ \
718 DetailMaybeArg(check_param, m_args, m_req, i), \
719 }; \
720 return return_code \
721 } \
722 void force_semicolon(ret_type)
723
724// Optional arg (without default). Can also be called on required args, if
725// needed.
726TMPL_INST(nullptr, std::optional<double>,
727 maybe_arg ? std::optional{maybe_arg->get_real()} : std::nullopt;);
728TMPL_INST(nullptr, std::optional<bool>,
729 maybe_arg ? std::optional{maybe_arg->get_bool()} : std::nullopt;);
730TMPL_INST(nullptr, const std::string *,
731 maybe_arg ? &maybe_arg->get_str() : nullptr;);
732
733// Required arg or optional arg with default value.
734TMPL_INST(CheckRequiredOrDefault, bool, CHECK_NONFATAL(maybe_arg)->get_bool(););
736 CHECK_NONFATAL(maybe_arg)->getInt<int>(););
738 CHECK_NONFATAL(maybe_arg)->getInt<uint64_t>(););
740 CHECK_NONFATAL(maybe_arg)->get_str(););
741
742bool RPCHelpMan::IsValidNumArgs(size_t num_args) const {
743 size_t num_required_args = 0;
744 for (size_t n = m_args.size(); n > 0; --n) {
745 if (!m_args.at(n - 1).IsOptional()) {
746 num_required_args = n;
747 break;
748 }
749 }
750 return num_required_args <= num_args && num_args <= m_args.size();
751}
752
753std::vector<std::pair<std::string, bool>> RPCHelpMan::GetArgNames() const {
754 std::vector<std::pair<std::string, bool>> ret;
755 ret.reserve(m_args.size());
756 for (const auto &arg : m_args) {
757 if (arg.m_type == RPCArg::Type::OBJ_NAMED_PARAMS) {
758 for (const auto &inner : arg.m_inner) {
759 ret.emplace_back(inner.m_names, /*named_only=*/true);
760 }
761 }
762 ret.emplace_back(arg.m_names, /*named_only=*/false);
763 }
764 return ret;
765}
766
767size_t RPCHelpMan::GetParamIndex(std::string_view key) const {
768 auto it{std::find_if(m_args.begin(), m_args.end(), [&key](const auto &arg) {
769 return arg.GetName() == key;
770 })};
771
772 // TODO: ideally this is checked at compile time
773 CHECK_NONFATAL(it != m_args.end());
774 return std::distance(m_args.begin(), it);
775}
776
777std::string RPCHelpMan::ToString() const {
778 std::string ret;
779
780 // Oneline summary
781 ret += m_name;
782 bool was_optional{false};
783 for (const auto &arg : m_args) {
784 if (arg.m_opts.hidden) {
785 // Any arg that follows is also hidden
786 break;
787 }
788 const bool optional = arg.IsOptional();
789 ret += " ";
790 if (optional) {
791 if (!was_optional) {
792 ret += "( ";
793 }
794 was_optional = true;
795 } else {
796 if (was_optional) {
797 ret += ") ";
798 }
799 was_optional = false;
800 }
801 ret += arg.ToString(/* oneline */ true);
802 }
803 if (was_optional) {
804 ret += " )";
805 }
806 ret += "\n\n";
807
808 // Description
809 ret += m_description;
810
811 // Arguments
812 Sections sections;
813 Sections named_only_sections;
814 for (size_t i{0}; i < m_args.size(); ++i) {
815 const auto &arg = m_args.at(i);
816 if (arg.m_opts.hidden) {
817 // Any arg that follows is also hidden
818 break;
819 }
820
821 // Push named argument name and description
822 sections.m_sections.emplace_back(
823 util::ToString(i + 1) + ". " + arg.GetFirstName(),
824 arg.ToDescriptionString(/*is_named_arg=*/true));
825 sections.m_max_pad = std::max(sections.m_max_pad,
826 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(
835 {arg_inner.GetFirstName(),
836 arg_inner.ToDescriptionString(/*is_named_arg=*/true)});
837 named_only_sections.Push(arg_inner);
838 }
839 }
840 }
841
842 if (!sections.m_sections.empty()) {
843 ret += "\nArguments:\n";
844 }
845 ret += sections.ToString();
846 if (!named_only_sections.m_sections.empty()) {
847 ret += "\nNamed Arguments:\n";
848 }
849 ret += named_only_sections.ToString();
850
851 // Result
853
854 // Examples
856
857 return ret;
858}
859
862
863 auto push_back_arg_info = [&arr](const std::string &rpc_name, int pos,
864 const std::string &arg_name,
865 const RPCArg::Type &type) {
867 map.push_back(rpc_name);
868 map.push_back(pos);
869 map.push_back(arg_name);
870 map.push_back(type == RPCArg::Type::STR ||
871 type == RPCArg::Type::STR_HEX);
872 arr.push_back(std::move(map));
873 };
874
875 for (int i{0}; i < int(m_args.size()); ++i) {
876 const auto &arg = m_args.at(i);
877 std::vector<std::string> arg_names = SplitString(arg.m_names, '|');
878 for (const auto &arg_name : arg_names) {
879 push_back_arg_info(m_name, i, arg_name, arg.m_type);
880 if (arg.m_type == RPCArg::Type::OBJ_NAMED_PARAMS) {
881 for (const auto &inner : arg.m_inner) {
882 std::vector<std::string> inner_names =
883 SplitString(inner.m_names, '|');
884 for (const std::string &inner_name : inner_names) {
885 push_back_arg_info(m_name, i, inner_name, inner.m_type);
886 }
887 }
888 }
889 }
890 }
891 return arr;
892}
893
894static std::optional<UniValue::VType> ExpectedType(RPCArg::Type type) {
895 using Type = RPCArg::Type;
896 switch (type) {
897 case Type::STR_HEX:
898 case Type::STR: {
899 return UniValue::VSTR;
900 }
901 case Type::NUM: {
902 return UniValue::VNUM;
903 }
904 case Type::AMOUNT: {
905 // VNUM or VSTR, checked inside AmountFromValue()
906 return std::nullopt;
907 }
908 case Type::RANGE: {
909 // VNUM or VARR, checked inside ParseRange()
910 return std::nullopt;
911 }
912 case Type::BOOL: {
913 return UniValue::VBOOL;
914 }
915 case Type::OBJ:
916 case Type::OBJ_NAMED_PARAMS:
917 case Type::OBJ_USER_KEYS: {
918 return UniValue::VOBJ;
919 }
920 case Type::ARR: {
921 return UniValue::VARR;
922 }
923 } // no default case, so the compiler can warn about missing cases
925}
926
927UniValue RPCArg::MatchesType(const UniValue &request) const {
929 return true;
930 }
931 if (IsOptional() && request.isNull()) {
932 return true;
933 }
934 const auto exp_type{ExpectedType(m_type)};
935 if (!exp_type) {
936 // nothing to check
937 return true;
938 }
939
940 if (*exp_type != request.getType()) {
941 return strprintf("JSON value of type %s is not of expected type %s",
942 uvTypeName(request.getType()), uvTypeName(*exp_type));
943 }
944 return true;
945}
946
947std::string RPCArg::GetFirstName() const {
948 return m_names.substr(0, m_names.find('|'));
949}
950
951std::string RPCArg::GetName() const {
952 CHECK_NONFATAL(std::string::npos == m_names.find('|'));
953 return m_names;
954}
955
956bool RPCArg::IsOptional() const {
957 if (m_fallback.index() != 0) {
958 return true;
959 } else {
960 return RPCArg::Optional::NO != std::get<RPCArg::Optional>(m_fallback);
961 }
962}
963
964std::string RPCArg::ToDescriptionString(bool is_named_arg) const {
965 std::string ret;
966 ret += "(";
967 if (m_opts.type_str.size() != 0) {
968 ret += m_opts.type_str.at(1);
969 } else {
970 switch (m_type) {
971 case Type::STR_HEX:
972 case Type::STR: {
973 ret += "string";
974 break;
975 }
976 case Type::NUM: {
977 ret += "numeric";
978 break;
979 }
980 case Type::AMOUNT: {
981 ret += "numeric or string";
982 break;
983 }
984 case Type::RANGE: {
985 ret += "numeric or array";
986 break;
987 }
988 case Type::BOOL: {
989 ret += "boolean";
990 break;
991 }
992 case Type::OBJ:
994 case Type::OBJ_USER_KEYS: {
995 ret += "json object";
996 break;
997 }
998 case Type::ARR: {
999 ret += "json array";
1000 break;
1001 } // no default case, so the compiler can warn about missing cases
1002 }
1003 }
1004 if (m_fallback.index() == 1) {
1005 ret +=
1006 ", optional, default=" + std::get<RPCArg::DefaultHint>(m_fallback);
1007 } else if (m_fallback.index() == 2) {
1008 ret += ", optional, default=" +
1009 std::get<RPCArg::Default>(m_fallback).write();
1010 } else {
1011 switch (std::get<RPCArg::Optional>(m_fallback)) {
1013 // Default value is "null" in dicts. Otherwise, nothing to do.
1014 // Element is treated as if not present and has no default value
1015 if (is_named_arg) {
1016 ret += ", optional";
1017 }
1018 break;
1019 }
1020 case RPCArg::Optional::NO: {
1021 ret += ", required";
1022 break;
1023 } // no default case, so the compiler can warn about missing cases
1024 }
1025 }
1026 ret += ")";
1028 ret += " Options object that can be used to pass named arguments, "
1029 "listed below.";
1030 }
1031 ret += m_description.empty() ? "" : " " + m_description;
1032 return ret;
1033}
1034
1035void RPCResult::ToSections(Sections &sections, const OuterType outer_type,
1036 const int current_indent) const {
1037 // Indentation
1038 const std::string indent(current_indent, ' ');
1039 const std::string indent_next(current_indent + 2, ' ');
1040
1041 // Elements in a JSON structure (dictionary or array) are separated by a
1042 // comma
1043 const std::string maybe_separator{outer_type != OuterType::NONE ? "," : ""};
1044
1045 // The key name if recursed into a dictionary
1046 const std::string maybe_key{
1047 outer_type == OuterType::OBJ ? "\"" + this->m_key_name + "\" : " : ""};
1048
1049 // Format description with type
1050 const auto Description = [&](const std::string &type) {
1051 return "(" + type + (this->m_optional ? ", optional" : "") + ")" +
1052 (this->m_description.empty() ? "" : " " + this->m_description);
1053 };
1054
1055 switch (m_type) {
1056 case Type::ELISION: {
1057 // If the inner result is empty, use three dots for elision
1058 sections.PushSection(
1059 {indent + "..." + maybe_separator, m_description});
1060 return;
1061 }
1062 case Type::ANY: {
1063 // Only for testing
1065 }
1066 case Type::NONE: {
1067 sections.PushSection(
1068 {indent + "null" + maybe_separator, Description("json null")});
1069 return;
1070 }
1071 case Type::STR: {
1072 sections.PushSection(
1073 {indent + maybe_key + "\"str\"" + maybe_separator,
1074 Description("string")});
1075 return;
1076 }
1077 case Type::STR_AMOUNT: {
1078 sections.PushSection({indent + maybe_key + "n" + maybe_separator,
1079 Description("numeric")});
1080 return;
1081 }
1082 case Type::STR_HEX: {
1083 sections.PushSection(
1084 {indent + maybe_key + "\"hex\"" + maybe_separator,
1085 Description("string")});
1086 return;
1087 }
1088 case Type::NUM: {
1089 sections.PushSection({indent + maybe_key + "n" + maybe_separator,
1090 Description("numeric")});
1091 return;
1092 }
1093 case Type::NUM_TIME: {
1094 sections.PushSection({indent + maybe_key + "xxx" + maybe_separator,
1095 Description("numeric")});
1096 return;
1097 }
1098 case Type::BOOL: {
1099 sections.PushSection(
1100 {indent + maybe_key + "true|false" + maybe_separator,
1101 Description("boolean")});
1102 return;
1103 }
1104 case Type::ARR_FIXED:
1105 case Type::ARR: {
1106 sections.PushSection(
1107 {indent + maybe_key + "[", Description("json array")});
1108 for (const auto &i : m_inner) {
1109 i.ToSections(sections, OuterType::ARR, current_indent + 2);
1110 }
1111 CHECK_NONFATAL(!m_inner.empty());
1112 if (m_type == Type::ARR && m_inner.back().m_type != Type::ELISION) {
1113 sections.PushSection({indent_next + "...", ""});
1114 } else {
1115 // Remove final comma, which would be invalid JSON
1116 sections.m_sections.back().m_left.pop_back();
1117 }
1118 sections.PushSection({indent + "]" + maybe_separator, ""});
1119 return;
1120 }
1121 case Type::OBJ_DYN:
1122 case Type::OBJ: {
1123 if (m_inner.empty()) {
1124 sections.PushSection({indent + maybe_key + "{}",
1125 Description("empty JSON object")});
1126 return;
1127 }
1128 sections.PushSection(
1129 {indent + maybe_key + "{", Description("json object")});
1130 for (const auto &i : m_inner) {
1131 i.ToSections(sections, OuterType::OBJ, current_indent + 2);
1132 }
1133 if (m_type == Type::OBJ_DYN &&
1134 m_inner.back().m_type != Type::ELISION) {
1135 // If the dictionary keys are dynamic, use three dots for
1136 // continuation
1137 sections.PushSection({indent_next + "...", ""});
1138 } else {
1139 // Remove final comma, which would be invalid JSON
1140 sections.m_sections.back().m_left.pop_back();
1141 }
1142 sections.PushSection({indent + "}" + maybe_separator, ""});
1143 return;
1144 } // no default case, so the compiler can warn about missing cases
1145 }
1147}
1148
1149static std::optional<UniValue::VType> ExpectedType(RPCResult::Type type) {
1150 using Type = RPCResult::Type;
1151 switch (type) {
1152 case Type::ELISION:
1153 case Type::ANY: {
1154 return std::nullopt;
1155 }
1156 case Type::NONE: {
1157 return UniValue::VNULL;
1158 }
1159 case Type::STR:
1160 case Type::STR_HEX: {
1161 return UniValue::VSTR;
1162 }
1163 case Type::NUM:
1164 case Type::STR_AMOUNT:
1165 case Type::NUM_TIME: {
1166 return UniValue::VNUM;
1167 }
1168 case Type::BOOL: {
1169 return UniValue::VBOOL;
1170 }
1171 case Type::ARR_FIXED:
1172 case Type::ARR: {
1173 return UniValue::VARR;
1174 }
1175 case Type::OBJ_DYN:
1176 case Type::OBJ: {
1177 return UniValue::VOBJ;
1178 }
1179 } // no default case, so the compiler can warn about missing cases
1181}
1182
1184 if (m_skip_type_check) {
1185 return true;
1186 }
1187
1188 const auto exp_type = ExpectedType(m_type);
1189 if (!exp_type) {
1190 // can be any type, so nothing to check
1191 return true;
1192 }
1193
1194 if (*exp_type != result.getType()) {
1195 return strprintf("returned type is %s, but declared as %s in doc",
1196 uvTypeName(result.getType()), uvTypeName(*exp_type));
1197 }
1198
1199 if (UniValue::VARR == result.getType()) {
1200 UniValue errors(UniValue::VOBJ);
1201 for (size_t i{0}; i < result.get_array().size(); ++i) {
1202 // If there are more results than documented, re-use the last
1203 // doc_inner.
1204 const RPCResult &doc_inner{
1205 m_inner.at(std::min(m_inner.size() - 1, i))};
1206 UniValue match{doc_inner.MatchesType(result.get_array()[i])};
1207 if (!match.isTrue()) {
1208 errors.pushKV(strprintf("%d", i), std::move(match));
1209 }
1210 }
1211 if (errors.empty()) {
1212 // empty result array is valid
1213 return true;
1214 }
1215 return errors;
1216 }
1217
1218 if (UniValue::VOBJ == result.getType()) {
1219 if (!m_inner.empty() && m_inner.at(0).m_type == Type::ELISION) {
1220 return true;
1221 }
1222 UniValue errors(UniValue::VOBJ);
1223 if (m_type == Type::OBJ_DYN) {
1224 // Assume all types are the same, randomly pick the first
1225 const RPCResult &doc_inner{m_inner.at(0)};
1226 for (size_t i{0}; i < result.get_obj().size(); ++i) {
1227 UniValue match{doc_inner.MatchesType(result.get_obj()[i])};
1228 if (!match.isTrue()) {
1229 errors.pushKV(result.getKeys()[i], std::move(match));
1230 }
1231 }
1232 if (errors.empty()) {
1233 // empty result obj is valid
1234 return true;
1235 }
1236 return errors;
1237 }
1238 std::set<std::string> doc_keys;
1239 for (const auto &doc_entry : m_inner) {
1240 doc_keys.insert(doc_entry.m_key_name);
1241 }
1242 std::map<std::string, UniValue> result_obj;
1243 result.getObjMap(result_obj);
1244 for (const auto &result_entry : result_obj) {
1245 if (doc_keys.find(result_entry.first) == doc_keys.end()) {
1246 errors.pushKV(result_entry.first,
1247 "key returned that was not in doc");
1248 }
1249 }
1250
1251 for (const auto &doc_entry : m_inner) {
1252 const auto result_it{result_obj.find(doc_entry.m_key_name)};
1253 if (result_it == result_obj.end()) {
1254 if (!doc_entry.m_optional) {
1255 errors.pushKV(
1256 doc_entry.m_key_name,
1257 "key missing, despite not being optional in doc");
1258 }
1259 continue;
1260 }
1261 UniValue match{doc_entry.MatchesType(result_it->second)};
1262 if (!match.isTrue()) {
1263 errors.pushKV(doc_entry.m_key_name, std::move(match));
1264 }
1265 }
1266 if (errors.empty()) {
1267 return true;
1268 }
1269 return errors;
1270 }
1271
1272 return true;
1273}
1274
1276 if (m_type == Type::OBJ) {
1277 // May or may not be empty
1278 return;
1279 }
1280 // Everything else must either be empty or not
1281 const bool inner_needed{m_type == Type::ARR || m_type == Type::ARR_FIXED ||
1283 CHECK_NONFATAL(inner_needed != m_inner.empty());
1284}
1285
1286std::string RPCArg::ToStringObj(const bool oneline) const {
1287 std::string res;
1288 res += "\"";
1289 res += GetFirstName();
1290 if (oneline) {
1291 res += "\":";
1292 } else {
1293 res += "\": ";
1294 }
1295 switch (m_type) {
1296 case Type::STR:
1297 return res + "\"str\"";
1298 case Type::STR_HEX:
1299 return res + "\"hex\"";
1300 case Type::NUM:
1301 return res + "n";
1302 case Type::RANGE:
1303 return res + "n or [n,n]";
1304 case Type::AMOUNT:
1305 return res + "amount";
1306 case Type::BOOL:
1307 return res + "bool";
1308 case Type::ARR:
1309 res += "[";
1310 for (const auto &i : m_inner) {
1311 res += i.ToString(oneline) + ",";
1312 }
1313 return res + "...]";
1314 case Type::OBJ:
1317 // Currently unused, so avoid writing dead code
1319
1320 // no default case, so the compiler can warn about missing cases
1321 }
1323 return res + "unknown";
1324}
1325
1326std::string RPCArg::ToString(const bool oneline) const {
1327 if (oneline && !m_opts.oneline_description.empty()) {
1329 }
1330
1331 switch (m_type) {
1332 case Type::STR_HEX:
1333 case Type::STR: {
1334 return "\"" + GetFirstName() + "\"";
1335 }
1336 case Type::NUM:
1337 case Type::RANGE:
1338 case Type::AMOUNT:
1339 case Type::BOOL: {
1340 return GetFirstName();
1341 }
1342 case Type::OBJ:
1344 case Type::OBJ_USER_KEYS: {
1345 const std::string res = Join(m_inner, ",", [&](const RPCArg &i) {
1346 return i.ToStringObj(oneline);
1347 });
1348 if (m_type == Type::OBJ) {
1349 return "{" + res + "}";
1350 } else {
1351 return "{" + res + ",...}";
1352 }
1353 }
1354 case Type::ARR: {
1355 std::string res;
1356 for (const auto &i : m_inner) {
1357 res += i.ToString(oneline) + ",";
1358 }
1359 return "[" + res + "...]";
1360 } // no default case, so the compiler can warn about missing cases
1361 }
1363}
1364
1365static std::pair<int64_t, int64_t> ParseRange(const UniValue &value) {
1366 if (value.isNum()) {
1367 return {0, value.getInt<int64_t>()};
1368 }
1369 if (value.isArray() && value.size() == 2 && value[0].isNum() &&
1370 value[1].isNum()) {
1371 int64_t low = value[0].getInt<int64_t>();
1372 int64_t high = value[1].getInt<int64_t>();
1373 if (low > high) {
1374 throw JSONRPCError(
1376 "Range specified as [begin,end] must not have begin after end");
1377 }
1378 return {low, high};
1379 }
1381 "Range must be specified as end or as [begin,end]");
1382}
1383
1384std::pair<int64_t, int64_t> ParseDescriptorRange(const UniValue &value) {
1385 int64_t low, high;
1386 std::tie(low, high) = ParseRange(value);
1387 if (low < 0) {
1389 "Range should be greater or equal than 0");
1390 }
1391 if ((high >> 31) != 0) {
1392 throw JSONRPCError(RPC_INVALID_PARAMETER, "End of range is too high");
1393 }
1394 if (high >= low + 1000000) {
1395 throw JSONRPCError(RPC_INVALID_PARAMETER, "Range is too large");
1396 }
1397 return {low, high};
1398}
1399
1400std::vector<CScript>
1402 FlatSigningProvider &provider) {
1403 std::string desc_str;
1404 std::pair<int64_t, int64_t> range = {0, 1000};
1405 if (scanobject.isStr()) {
1406 desc_str = scanobject.get_str();
1407 } else if (scanobject.isObject()) {
1408 const UniValue &desc_uni{scanobject.find_value("desc")};
1409 if (desc_uni.isNull()) {
1410 throw JSONRPCError(
1412 "Descriptor needs to be provided in scan object");
1413 }
1414 desc_str = desc_uni.get_str();
1415 const UniValue &range_uni{scanobject.find_value("range")};
1416 if (!range_uni.isNull()) {
1417 range = ParseDescriptorRange(range_uni);
1418 }
1419 } else {
1420 throw JSONRPCError(
1422 "Scan object needs to be either a string or an object");
1423 }
1424
1425 std::string error;
1426 auto desc = Parse(desc_str, provider, error);
1427 if (!desc) {
1429 }
1430 if (!desc->IsRange()) {
1431 range.first = 0;
1432 range.second = 0;
1433 }
1434 std::vector<CScript> ret;
1435 for (int i = range.first; i <= range.second; ++i) {
1436 std::vector<CScript> scripts;
1437 if (!desc->Expand(i, provider, scripts, provider)) {
1438 throw JSONRPCError(
1440 strprintf("Cannot derive script without private keys: '%s'",
1441 desc_str));
1442 }
1443 std::move(scripts.begin(), scripts.end(), std::back_inserter(ret));
1444 }
1445 return ret;
1446}
1447
1449 UniValue servicesNames(UniValue::VARR);
1450
1451 for (const auto &flag : serviceFlagsToStr(services)) {
1452 servicesNames.push_back(flag);
1453 }
1454
1455 return servicesNames;
1456}
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
std::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
Definition addresstype.h:54
bool MoneyRange(const Amount nValue)
Definition amount.h:177
static constexpr Amount SATOSHI
Definition amount.h:153
ArgsManager gArgs
Definition args.cpp:39
#define CHECK_NONFATAL(condition)
Identity function.
Definition check.h:83
#define NONFATAL_UNREACHABLE()
NONFATAL_UNREACHABLE() is a macro that is used to mark unreachable code.
Definition check.h:109
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition args.cpp:524
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition chainparams.h:86
A reference to a CKey: the Hash160 of its serialized public key.
Definition pubkey.h:22
An encapsulated public key.
Definition pubkey.h:31
bool IsFullyValid() const
fully validate whether this is a valid public key (more expensive than IsValid())
Definition pubkey.cpp:261
Serialized script, used inside transaction inputs and outputs.
Definition script.h:434
DescribeAddressVisitor()=default
UniValue operator()(const CNoDestination &dest) const
Definition util.cpp:316
UniValue operator()(const ScriptHash &scriptID) const
Definition util.cpp:326
UniValue operator()(const PKHash &keyID) const
Definition util.cpp:320
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:34
enum JSONRPCRequest::Mode mode
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:767
RPCHelpMan(std::string name, std::string description, std::vector< RPCArg > args, RPCResults results, RPCExamples examples)
Definition util.cpp:529
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:742
std::function< UniValue(const RPCHelpMan &, const Config &config, const JSONRPCRequest &)> RPCMethodImpl
Definition util.h:397
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
UniValue HandleRequest(const Config &config, const JSONRPCRequest &request) const
Definition util.cpp:629
const std::vector< RPCArg > m_args
Definition util.h:498
std::string ToString() const
Definition util.cpp:777
UniValue GetArgMap() const
Return the named args that need to be converted from string to another JSON type.
Definition util.cpp:860
std::vector< std::pair< std::string, bool > > GetArgNames() const
Return list of arguments and whether they are named-only.
Definition util.cpp:753
const JSONRPCRequest * m_req
A pointer to the request for the duration of m_fun()
Definition util.h:502
void push_back(UniValue val)
Definition univalue.cpp:96
const std::string & get_str() const
bool isArray() const
Definition univalue.h:110
const UniValue & find_value(std::string_view key) const
Definition univalue.cpp:229
enum VType getType() const
Definition univalue.h:88
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
bool isNull() const
Definition univalue.h:104
const std::string & getValStr() const
Definition univalue.h:89
const UniValue & get_obj() const
void setNull()
Definition univalue.cpp:25
size_t size() const
Definition univalue.h:92
enum VType type() const
Definition univalue.h:147
const std::vector< std::string > & getKeys() const
bool empty() const
Definition univalue.h:90
bool isStr() const
Definition univalue.h:108
bool isBool() const
Definition univalue.h:107
Int getInt() const
Definition univalue.h:157
const UniValue & get_array() const
bool isNum() const
Definition univalue.h:109
void pushKV(std::string key, UniValue val)
Definition univalue.cpp:115
void getObjMap(std::map< std::string, UniValue > &kv) const
Definition univalue.cpp:135
bool get_bool() const
bool isObject() const
Definition univalue.h:111
constexpr bool IsNull() const
Definition uint256.h:44
size_type size() const
Definition prevector.h:398
256-bit opaque blob.
Definition uint256.h:199
static UniValue Parse(std::string_view raw)
Parse string to UniValue or throw runtime_error if string contains invalid JSON.
Definition client.cpp:235
std::string FormatFullVersion()
is a home for simple enum and struct type definitions that can be used internally by functions in the...
CTxDestination DecodeDestination(const std::string &addr, const CChainParams &params)
Definition key_io.cpp:174
PSBTError
Definition types.h:17
bilingual_str PSBTErrorString(PSBTError err)
Definition messages.cpp:22
bilingual_str TransactionErrorString(const TransactionError error)
Definition messages.cpp:36
TransactionError
Definition types.h:17
Implement std::hash so RCUPtr can be used as a key for maps or sets.
Definition rcu.h:259
std::vector< std::string > SplitString(std::string_view str, char sep)
Definition string.h:63
auto Join(const std::vector< T > &list, const BaseType &separator, UnaryOp unary_op) -> decltype(unary_op(list.at(0)))
Join a list of items.
Definition string.h:109
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition string.h:156
is a home for public enum and struct type definitions that are used by internally by node code,...
CTxDestination AddAndGetDestinationForScript(FillableSigningProvider &keystore, const CScript &script, OutputType type)
Get a destination of the requested type (if possible) to the specified script.
OutputType
Definition outputtype.h:16
std::vector< std::string > serviceFlagsToStr(const uint64_t flags)
Convert service flags (a bitmask of NODE_*) to human readable strings.
Definition protocol.cpp:236
ServiceFlags
nServices flags.
Definition protocol.h:335
UniValue JSONRPCError(int code, const std::string &message)
Definition request.cpp:58
const char * name
Definition rest.cpp:46
RPCErrorCode
Bitcoin RPC error codes.
Definition protocol.h:22
@ RPC_TRANSACTION_ALREADY_IN_CHAIN
Definition protocol.h:65
@ RPC_TYPE_ERROR
Unexpected type was passed as parameter.
Definition protocol.h:40
@ RPC_TRANSACTION_REJECTED
Definition protocol.h:64
@ RPC_TRANSACTION_ERROR
Aliases for backward compatibility.
Definition protocol.h:63
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
Definition protocol.h:46
@ RPC_INTERNAL_ERROR
Definition protocol.h:33
@ RPC_DESERIALIZATION_ERROR
Error parsing or validating structure in raw format.
Definition protocol.h:50
@ 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:685
std::pair< int64_t, int64_t > ParseDescriptorRange(const UniValue &value)
Parse a JSON range specified as int64, or [int64, int64].
Definition util.cpp:1384
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition util.cpp:182
UniValue GetServicesNames(ServiceFlags services)
Returns, given services flags, a list of humanly readable (known) network services.
Definition util.cpp:1448
CTxDestination AddAndGetMultisigDestination(const int required, const std::vector< CPubKey > &pubkeys, OutputType type, FillableSigningProvider &keystore, CScript &script_out)
Definition util.cpp:265
std::string HelpExampleRpcNamed(const std::string &methodname, const RPCArgList &args)
Definition util.cpp:208
RPCErrorCode RPCErrorFromPSBTError(PSBTError err)
Definition util.cpp:346
UniValue JSONRPCTransactionError(TransactionError terr, const std::string &err_string)
Definition util.cpp:375
Amount AmountFromValue(const UniValue &value)
Definition util.cpp:69
#define TMPL_INST(check_param, ret_type, return_code)
Definition util.cpp:715
std::vector< uint8_t > ParseHexV(const UniValue &v, std::string strName)
Definition util.cpp:108
UniValue JSONRPCPSBTError(PSBTError err)
Definition util.cpp:370
RPCErrorCode RPCErrorFromTransactionError(TransactionError terr)
Definition util.cpp:358
void(const RPCArg &) CheckFn
Definition util.cpp:684
const std::string EXAMPLE_ADDRESS
Example CashAddr address used in multiple RPCExamples.
Definition util.cpp:37
static std::optional< UniValue::VType > ExpectedType(RPCArg::Type type)
Definition util.cpp:894
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition util.cpp:199
std::vector< CScript > EvalDescriptorStringOrObject(const UniValue &scanobject, FlatSigningProvider &provider)
Evaluate a descriptor given as a string, or as a {"desc":...,"range":...} object, with default range ...
Definition util.cpp:1401
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:36
std::string GetAllOutputTypes()
Definition util.cpp:337
int ParseVerbosity(const UniValue &arg, int default_verbosity, bool allow_bool)
Parses verbosity from provided UniValue.
Definition util.cpp:126
CPubKey HexToPubKey(const std::string &hex_in)
Definition util.cpp:223
CPubKey AddrToPubKey(const CChainParams &chainparams, const FillableSigningProvider &keystore, const std::string &addr_in)
Definition util.cpp:237
uint256 ParseHashO(const UniValue &o, std::string strKey)
Definition util.cpp:104
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded values (throws error if not hex).
Definition util.cpp:87
static std::pair< int64_t, int64_t > ParseRange(const UniValue &value)
Definition util.cpp:1365
void RPCTypeCheckObj(const UniValue &o, const std::map< std::string, UniValueType > &typesExpected, bool fAllowNull, bool fStrict)
Check for expected keys/value types in an Object.
Definition util.cpp:40
std::string HelpExampleCliNamed(const std::string &methodname, const RPCArgList &args)
Definition util.cpp:187
static void CheckRequiredOrDefault(const RPCArg &param)
Definition util.cpp:704
UniValue DescribeAddress(const CTxDestination &dest)
Definition util.cpp:333
std::vector< uint8_t > ParseHexO(const UniValue &o, std::string strKey)
Definition util.cpp:122
std::vector< std::pair< std::string, UniValue > > RPCArgList
Definition util.h:103
static constexpr bool DEFAULT_RPC_DOC_CHECK
Definition util.h:49
OuterType
Serializing JSON objects depends on the outer type.
Definition util.h:152
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
Definition script.h:27
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:148
std::string GetTxnOutputType(TxoutType t)
Get the name of a TxoutType as a string.
Definition solver.cpp:14
TxoutType
Definition solver.h:15
static const Currency & get()
Definition amount.cpp:25
uint8_t decimals
Definition amount.h:159
Definition util.h:184
Type
Definition util.h:185
@ RANGE
Special type that is a NUM or [NUM,NUM].
@ OBJ_USER_KEYS
Special type where the user must set the keys e.g.
@ 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:235
const RPCArgOptions m_opts
Definition util.h:238
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:232
const Fallback m_fallback
Definition util.h:236
std::string ToString(bool oneline) const
Return the type string of the argument.
Definition util.cpp:1326
UniValue MatchesType(const UniValue &request) const
Check whether the request JSON type matches.
Definition util.cpp:927
const std::string m_description
Definition util.h:237
bool IsOptional() const
Definition util.cpp:956
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:964
const Type m_type
Definition util.h:233
std::string GetName() const
Return the name, throws when there are aliases.
Definition util.cpp:951
std::string GetFirstName() const
Return the first of all aliases.
Definition util.cpp:947
std::string ToStringObj(bool oneline) const
Return the type string of the argument when it is in an object (dict).
Definition util.cpp:1286
@ 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:168
std::string oneline_description
Should be empty unless it is supposed to override the auto-generated summary line.
Definition util.h:162
bool skip_type_check
Definition util.h:159
std::string ToDescriptionString() const
Definition util.cpp:625
const std::string m_examples
Definition util.h:384
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:1035
@ 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:1183
void CheckInnerDoc() const
Definition util.cpp:1275
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:605
const std::vector< RPCResult > m_results
Definition util.h:371
A pair of strings that can be aligned (through padding) with other Sections later on.
Definition util.cpp:389
std::string m_left
Definition util.cpp:392
Section(const std::string &left, const std::string &right)
Definition util.cpp:390
const std::string m_right
Definition util.cpp:393
Keeps track of RPCArgs by transforming them into sections for the purpose of serializing everything t...
Definition util.cpp:400
void PushSection(const Section &s)
Definition util.cpp:404
std::vector< Section > m_sections
Definition util.cpp:401
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:412
size_t m_max_pad
Definition util.cpp:402
std::string ToString() const
Concatenate all sections with proper padding.
Definition util.cpp:487
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
uint256 uint256S(std::string_view str)
DEPRECATED.
Definition uint256.h:221
const char * uvTypeName(UniValue::VType t)
Definition univalue.cpp:209
template std::vector< std::byte > ParseHex(std::string_view)
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)
Returns true if each character in str is a hex character, and has an even number of hex digits.