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