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