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