Bitcoin Core  21.99.0
P2P Digital Currency
util.cpp
Go to the documentation of this file.
1 // Copyright (c) 2017-2021 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #include <key_io.h>
6 #include <outputtype.h>
7 #include <rpc/util.h>
8 #include <script/descriptor.h>
10 #include <tinyformat.h>
11 #include <util/strencodings.h>
12 #include <util/string.h>
13 #include <util/translation.h>
14 
15 #include <tuple>
16 
17 #include <boost/algorithm/string/classification.hpp>
18 #include <boost/algorithm/string/split.hpp>
19 
20 const std::string UNIX_EPOCH_TIME = "UNIX epoch time";
21 const std::string EXAMPLE_ADDRESS[2] = {"bc1q09vm5lfy0j5reeulh4x5752q25uqqvz34hufdl", "bc1q02ad21edsxd23d32dfgqqsz4vv4nmtfzuklhy3"};
22 
23 void RPCTypeCheck(const UniValue& params,
24  const std::list<UniValueType>& typesExpected,
25  bool fAllowNull)
26 {
27  unsigned int i = 0;
28  for (const UniValueType& t : typesExpected) {
29  if (params.size() <= i)
30  break;
31 
32  const UniValue& v = params[i];
33  if (!(fAllowNull && v.isNull())) {
35  }
36  i++;
37  }
38 }
39 
40 void RPCTypeCheckArgument(const UniValue& value, const UniValueType& typeExpected)
41 {
42  if (!typeExpected.typeAny && value.type() != typeExpected.type) {
43  throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Expected type %s, got %s", uvTypeName(typeExpected.type), uvTypeName(value.type())));
44  }
45 }
46 
47 void RPCTypeCheckObj(const UniValue& o,
48  const std::map<std::string, UniValueType>& typesExpected,
49  bool fAllowNull,
50  bool fStrict)
51 {
52  for (const auto& t : typesExpected) {
53  const UniValue& v = find_value(o, t.first);
54  if (!fAllowNull && v.isNull())
55  throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first));
56 
57  if (!(t.second.typeAny || v.type() == t.second.type || (fAllowNull && v.isNull()))) {
58  std::string err = strprintf("Expected type %s for %s, got %s",
59  uvTypeName(t.second.type), t.first, uvTypeName(v.type()));
60  throw JSONRPCError(RPC_TYPE_ERROR, err);
61  }
62  }
63 
64  if (fStrict)
65  {
66  for (const std::string& k : o.getKeys())
67  {
68  if (typesExpected.count(k) == 0)
69  {
70  std::string err = strprintf("Unexpected key %s", k);
71  throw JSONRPCError(RPC_TYPE_ERROR, err);
72  }
73  }
74  }
75 }
76 
78 {
79  if (!value.isNum() && !value.isStr())
80  throw JSONRPCError(RPC_TYPE_ERROR, "Amount is not a number or string");
81  CAmount amount;
82  if (!ParseFixedPoint(value.getValStr(), 8, &amount))
83  throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
84  if (!MoneyRange(amount))
85  throw JSONRPCError(RPC_TYPE_ERROR, "Amount out of range");
86  return amount;
87 }
88 
89 uint256 ParseHashV(const UniValue& v, std::string strName)
90 {
91  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')", strName, 64, strHex.length(), strHex));
94  if (!IsHex(strHex)) // Note: IsHex("") is false
95  throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
96  return uint256S(strHex);
97 }
98 uint256 ParseHashO(const UniValue& o, std::string strKey)
99 {
100  return ParseHashV(find_value(o, strKey), strKey);
101 }
102 std::vector<unsigned char> ParseHexV(const UniValue& v, std::string strName)
103 {
104  std::string strHex;
105  if (v.isStr())
106  strHex = v.get_str();
107  if (!IsHex(strHex))
108  throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
109  return ParseHex(strHex);
110 }
111 std::vector<unsigned char> ParseHexO(const UniValue& o, std::string strKey)
112 {
113  return ParseHexV(find_value(o, strKey), strKey);
114 }
115 
117 {
118  if (param.isNull()) {
119  return default_type;
120  } else {
121  std::string hash_type_input = param.get_str();
122 
123  if (hash_type_input == "hash_serialized_2") {
125  } else if (hash_type_input == "none") {
127  } else {
128  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("%d is not a valid hash_type", hash_type_input));
129  }
130  }
131 }
132 
133 std::string HelpExampleCli(const std::string& methodname, const std::string& args)
134 {
135  return "> bitcoin-cli " + methodname + " " + args + "\n";
136 }
137 
138 std::string HelpExampleRpc(const std::string& methodname, const std::string& args)
139 {
140  return "> curl --user myusername --data-binary '{\"jsonrpc\": \"1.0\", \"id\": \"curltest\", "
141  "\"method\": \"" + methodname + "\", \"params\": [" + args + "]}' -H 'content-type: text/plain;' http://127.0.0.1:8332/\n";
142 }
143 
144 // Converts a hex string to a public key if possible
145 CPubKey HexToPubKey(const std::string& hex_in)
146 {
147  if (!IsHex(hex_in)) {
148  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid public key: " + hex_in);
149  }
150  CPubKey vchPubKey(ParseHex(hex_in));
151  if (!vchPubKey.IsFullyValid()) {
152  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid public key: " + hex_in);
153  }
154  return vchPubKey;
155 }
156 
157 // Retrieves a public key for an address from the given FillableSigningProvider
158 CPubKey AddrToPubKey(const FillableSigningProvider& keystore, const std::string& addr_in)
159 {
160  CTxDestination dest = DecodeDestination(addr_in);
161  if (!IsValidDestination(dest)) {
162  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address: " + addr_in);
163  }
164  CKeyID key = GetKeyForDestination(keystore, dest);
165  if (key.IsNull()) {
166  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("%s does not refer to a key", addr_in));
167  }
168  CPubKey vchPubKey;
169  if (!keystore.GetPubKey(key, vchPubKey)) {
170  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("no full public key for address %s", addr_in));
171  }
172  if (!vchPubKey.IsFullyValid()) {
173  throw JSONRPCError(RPC_INTERNAL_ERROR, "Wallet contains an invalid public key");
174  }
175  return vchPubKey;
176 }
177 
178 // Creates a multisig address from a given list of public keys, number of signatures required, and the address type
179 CTxDestination AddAndGetMultisigDestination(const int required, const std::vector<CPubKey>& pubkeys, OutputType type, FillableSigningProvider& keystore, CScript& script_out)
180 {
181  // Gather public keys
182  if (required < 1) {
183  throw JSONRPCError(RPC_INVALID_PARAMETER, "a multisignature address must require at least one key to redeem");
184  }
185  if ((int)pubkeys.size() < required) {
186  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("not enough keys supplied (got %u keys, but need at least %d to redeem)", pubkeys.size(), required));
187  }
188  if (pubkeys.size() > 16) {
189  throw JSONRPCError(RPC_INVALID_PARAMETER, "Number of keys involved in the multisignature address creation > 16\nReduce the number");
190  }
191 
192  script_out = GetScriptForMultisig(required, pubkeys);
193 
194  if (script_out.size() > MAX_SCRIPT_ELEMENT_SIZE) {
195  throw JSONRPCError(RPC_INVALID_PARAMETER, (strprintf("redeemScript exceeds size limit: %d > %d", script_out.size(), MAX_SCRIPT_ELEMENT_SIZE)));
196  }
197 
198  // Check if any keys are uncompressed. If so, the type is legacy
199  for (const CPubKey& pk : pubkeys) {
200  if (!pk.IsCompressed()) {
201  type = OutputType::LEGACY;
202  break;
203  }
204  }
205 
206  // Make the address
207  CTxDestination dest = AddAndGetDestinationForScript(keystore, script_out, type);
208 
209  return dest;
210 }
211 
213 {
214 public:
216 
217  UniValue operator()(const CNoDestination& dest) const
218  {
219  return UniValue(UniValue::VOBJ);
220  }
221 
222  UniValue operator()(const PKHash& keyID) const
223  {
225  obj.pushKV("isscript", false);
226  obj.pushKV("iswitness", false);
227  return obj;
228  }
229 
230  UniValue operator()(const ScriptHash& scriptID) const
231  {
233  obj.pushKV("isscript", true);
234  obj.pushKV("iswitness", false);
235  return obj;
236  }
237 
239  {
241  obj.pushKV("isscript", false);
242  obj.pushKV("iswitness", true);
243  obj.pushKV("witness_version", 0);
244  obj.pushKV("witness_program", HexStr(id));
245  return obj;
246  }
247 
249  {
251  obj.pushKV("isscript", true);
252  obj.pushKV("iswitness", true);
253  obj.pushKV("witness_version", 0);
254  obj.pushKV("witness_program", HexStr(id));
255  return obj;
256  }
257 
259  {
261  obj.pushKV("iswitness", true);
262  obj.pushKV("witness_version", (int)id.version);
263  obj.pushKV("witness_program", HexStr(Span<const unsigned char>(id.program, id.length)));
264  return obj;
265  }
266 };
267 
269 {
270  return std::visit(DescribeAddressVisitor(), dest);
271 }
272 
273 unsigned int ParseConfirmTarget(const UniValue& value, unsigned int max_target)
274 {
275  const int target{value.get_int()};
276  const unsigned int unsigned_target{static_cast<unsigned int>(target)};
277  if (target < 1 || unsigned_target > max_target) {
278  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid conf_target, must be between %u and %u", 1, max_target));
279  }
280  return unsigned_target;
281 }
282 
284 {
285  switch (terr) {
294  return RPC_INVALID_PARAMETER;
297  default: break;
298  }
299  return RPC_TRANSACTION_ERROR;
300 }
301 
302 UniValue JSONRPCTransactionError(TransactionError terr, const std::string& err_string)
303 {
304  if (err_string.length() > 0) {
305  return JSONRPCError(RPCErrorFromTransactionError(terr), err_string);
306  } else {
308  }
309 }
310 
315 struct Section {
316  Section(const std::string& left, const std::string& right)
317  : m_left{left}, m_right{right} {}
318  std::string m_left;
319  const std::string m_right;
320 };
321 
326 struct Sections {
327  std::vector<Section> m_sections;
328  size_t m_max_pad{0};
329 
330  void PushSection(const Section& s)
331  {
332  m_max_pad = std::max(m_max_pad, s.m_left.size());
333  m_sections.push_back(s);
334  }
335 
339  void Push(const RPCArg& arg, const size_t current_indent = 5, const OuterType outer_type = OuterType::NONE)
340  {
341  const auto indent = std::string(current_indent, ' ');
342  const auto indent_next = std::string(current_indent + 2, ' ');
343  const bool push_name{outer_type == OuterType::OBJ}; // Dictionary keys must have a name
344 
345  switch (arg.m_type) {
347  case RPCArg::Type::STR:
348  case RPCArg::Type::NUM:
350  case RPCArg::Type::RANGE:
351  case RPCArg::Type::BOOL: {
352  if (outer_type == OuterType::NONE) return; // Nothing more to do for non-recursive types on first recursion
353  auto left = indent;
354  if (arg.m_type_str.size() != 0 && push_name) {
355  left += "\"" + arg.GetName() + "\": " + arg.m_type_str.at(0);
356  } else {
357  left += push_name ? arg.ToStringObj(/* oneline */ false) : arg.ToString(/* oneline */ false);
358  }
359  left += ",";
360  PushSection({left, arg.ToDescriptionString()});
361  break;
362  }
363  case RPCArg::Type::OBJ:
365  const auto right = outer_type == OuterType::NONE ? "" : arg.ToDescriptionString();
366  PushSection({indent + (push_name ? "\"" + arg.GetName() + "\": " : "") + "{", right});
367  for (const auto& arg_inner : arg.m_inner) {
368  Push(arg_inner, current_indent + 2, OuterType::OBJ);
369  }
370  if (arg.m_type != RPCArg::Type::OBJ) {
371  PushSection({indent_next + "...", ""});
372  }
373  PushSection({indent + "}" + (outer_type != OuterType::NONE ? "," : ""), ""});
374  break;
375  }
376  case RPCArg::Type::ARR: {
377  auto left = indent;
378  left += push_name ? "\"" + arg.GetName() + "\": " : "";
379  left += "[";
380  const auto right = outer_type == OuterType::NONE ? "" : arg.ToDescriptionString();
381  PushSection({left, right});
382  for (const auto& arg_inner : arg.m_inner) {
383  Push(arg_inner, current_indent + 2, OuterType::ARR);
384  }
385  PushSection({indent_next + "...", ""});
386  PushSection({indent + "]" + (outer_type != OuterType::NONE ? "," : ""), ""});
387  break;
388  }
389  } // no default case, so the compiler can warn about missing cases
390  }
391 
395  std::string ToString() const
396  {
397  std::string ret;
398  const size_t pad = m_max_pad + 4;
399  for (const auto& s : m_sections) {
400  // The left part of a section is assumed to be a single line, usually it is the name of the JSON struct or a
401  // brace like {, }, [, or ]
402  CHECK_NONFATAL(s.m_left.find('\n') == std::string::npos);
403  if (s.m_right.empty()) {
404  ret += s.m_left;
405  ret += "\n";
406  continue;
407  }
408 
409  std::string left = s.m_left;
410  left.resize(pad, ' ');
411  ret += left;
412 
413  // Properly pad after newlines
414  std::string right;
415  size_t begin = 0;
416  size_t new_line_pos = s.m_right.find_first_of('\n');
417  while (true) {
418  right += s.m_right.substr(begin, new_line_pos - begin);
419  if (new_line_pos == std::string::npos) {
420  break; //No new line
421  }
422  right += "\n" + std::string(pad, ' ');
423  begin = s.m_right.find_first_not_of(' ', new_line_pos + 1);
424  if (begin == std::string::npos) {
425  break; // Empty line
426  }
427  new_line_pos = s.m_right.find_first_of('\n', begin + 1);
428  }
429  ret += right;
430  ret += "\n";
431  }
432  return ret;
433  }
434 };
435 
436 RPCHelpMan::RPCHelpMan(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples)
437  : RPCHelpMan{std::move(name), std::move(description), std::move(args), std::move(results), std::move(examples), nullptr} {}
438 
439 RPCHelpMan::RPCHelpMan(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples, RPCMethodImpl fun)
440  : m_name{std::move(name)},
441  m_fun{std::move(fun)},
442  m_description{std::move(description)},
443  m_args{std::move(args)},
444  m_results{std::move(results)},
445  m_examples{std::move(examples)}
446 {
447  std::set<std::string> named_args;
448  for (const auto& arg : m_args) {
449  std::vector<std::string> names;
450  boost::split(names, arg.m_names, boost::is_any_of("|"));
451  // Should have unique named arguments
452  for (const std::string& name : names) {
453  CHECK_NONFATAL(named_args.insert(name).second);
454  }
455  }
456 }
457 
459 {
460  std::string result;
461  for (const auto& r : m_results) {
462  if (r.m_cond.empty()) {
463  result += "\nResult:\n";
464  } else {
465  result += "\nResult (" + r.m_cond + "):\n";
466  }
467  Sections sections;
468  r.ToSections(sections);
469  result += sections.ToString();
470  }
471  return result;
472 }
473 
475 {
476  return m_examples.empty() ? m_examples : "\nExamples:\n" + m_examples;
477 }
478 
479 bool RPCHelpMan::IsValidNumArgs(size_t num_args) const
480 {
481  size_t num_required_args = 0;
482  for (size_t n = m_args.size(); n > 0; --n) {
483  if (!m_args.at(n - 1).IsOptional()) {
484  num_required_args = n;
485  break;
486  }
487  }
488  return num_required_args <= num_args && num_args <= m_args.size();
489 }
490 
491 std::vector<std::string> RPCHelpMan::GetArgNames() const
492 {
493  std::vector<std::string> ret;
494  for (const auto& arg : m_args) {
495  ret.emplace_back(arg.m_names);
496  }
497  return ret;
498 }
499 
500 std::string RPCHelpMan::ToString() const
501 {
502  std::string ret;
503 
504  // Oneline summary
505  ret += m_name;
506  bool was_optional{false};
507  for (const auto& arg : m_args) {
508  if (arg.m_hidden) break; // Any arg that follows is also hidden
509  const bool optional = arg.IsOptional();
510  ret += " ";
511  if (optional) {
512  if (!was_optional) ret += "( ";
513  was_optional = true;
514  } else {
515  if (was_optional) ret += ") ";
516  was_optional = false;
517  }
518  ret += arg.ToString(/* oneline */ true);
519  }
520  if (was_optional) ret += " )";
521  ret += "\n";
522 
523  // Description
524  ret += m_description;
525 
526  // Arguments
527  Sections sections;
528  for (size_t i{0}; i < m_args.size(); ++i) {
529  const auto& arg = m_args.at(i);
530  if (arg.m_hidden) break; // Any arg that follows is also hidden
531 
532  if (i == 0) ret += "\nArguments:\n";
533 
534  // Push named argument name and description
535  sections.m_sections.emplace_back(::ToString(i + 1) + ". " + arg.GetFirstName(), arg.ToDescriptionString());
536  sections.m_max_pad = std::max(sections.m_max_pad, sections.m_sections.back().m_left.size());
537 
538  // Recursively push nested args
539  sections.Push(arg);
540  }
541  ret += sections.ToString();
542 
543  // Result
545 
546  // Examples
548 
549  return ret;
550 }
551 
552 std::string RPCArg::GetFirstName() const
553 {
554  return m_names.substr(0, m_names.find("|"));
555 }
556 
557 std::string RPCArg::GetName() const
558 {
559  CHECK_NONFATAL(std::string::npos == m_names.find("|"));
560  return m_names;
561 }
562 
563 bool RPCArg::IsOptional() const
564 {
565  if (m_fallback.index() == 1) {
566  return true;
567  } else {
568  return RPCArg::Optional::NO != std::get<RPCArg::Optional>(m_fallback);
569  }
570 }
571 
572 std::string RPCArg::ToDescriptionString() const
573 {
574  std::string ret;
575  ret += "(";
576  if (m_type_str.size() != 0) {
577  ret += m_type_str.at(1);
578  } else {
579  switch (m_type) {
580  case Type::STR_HEX:
581  case Type::STR: {
582  ret += "string";
583  break;
584  }
585  case Type::NUM: {
586  ret += "numeric";
587  break;
588  }
589  case Type::AMOUNT: {
590  ret += "numeric or string";
591  break;
592  }
593  case Type::RANGE: {
594  ret += "numeric or array";
595  break;
596  }
597  case Type::BOOL: {
598  ret += "boolean";
599  break;
600  }
601  case Type::OBJ:
602  case Type::OBJ_USER_KEYS: {
603  ret += "json object";
604  break;
605  }
606  case Type::ARR: {
607  ret += "json array";
608  break;
609  }
610  } // no default case, so the compiler can warn about missing cases
611  }
612  if (m_fallback.index() == 1) {
613  ret += ", optional, default=" + std::get<std::string>(m_fallback);
614  } else {
615  switch (std::get<RPCArg::Optional>(m_fallback)) {
617  // nothing to do. Element is treated as if not present and has no default value
618  break;
619  }
621  ret += ", optional"; // Default value is "null"
622  break;
623  }
624  case RPCArg::Optional::NO: {
625  ret += ", required";
626  break;
627  }
628  } // no default case, so the compiler can warn about missing cases
629  }
630  ret += ")";
631  ret += m_description.empty() ? "" : " " + m_description;
632  return ret;
633 }
634 
635 void RPCResult::ToSections(Sections& sections, const OuterType outer_type, const int current_indent) const
636 {
637  // Indentation
638  const std::string indent(current_indent, ' ');
639  const std::string indent_next(current_indent + 2, ' ');
640 
641  // Elements in a JSON structure (dictionary or array) are separated by a comma
642  const std::string maybe_separator{outer_type != OuterType::NONE ? "," : ""};
643 
644  // The key name if recursed into an dictionary
645  const std::string maybe_key{
646  outer_type == OuterType::OBJ ?
647  "\"" + this->m_key_name + "\" : " :
648  ""};
649 
650  // Format description with type
651  const auto Description = [&](const std::string& type) {
652  return "(" + type + (this->m_optional ? ", optional" : "") + ")" +
653  (this->m_description.empty() ? "" : " " + this->m_description);
654  };
655 
656  switch (m_type) {
657  case Type::ELISION: {
658  // If the inner result is empty, use three dots for elision
659  sections.PushSection({indent + "..." + maybe_separator, m_description});
660  return;
661  }
662  case Type::NONE: {
663  sections.PushSection({indent + "null" + maybe_separator, Description("json null")});
664  return;
665  }
666  case Type::STR: {
667  sections.PushSection({indent + maybe_key + "\"str\"" + maybe_separator, Description("string")});
668  return;
669  }
670  case Type::STR_AMOUNT: {
671  sections.PushSection({indent + maybe_key + "n" + maybe_separator, Description("numeric")});
672  return;
673  }
674  case Type::STR_HEX: {
675  sections.PushSection({indent + maybe_key + "\"hex\"" + maybe_separator, Description("string")});
676  return;
677  }
678  case Type::NUM: {
679  sections.PushSection({indent + maybe_key + "n" + maybe_separator, Description("numeric")});
680  return;
681  }
682  case Type::NUM_TIME: {
683  sections.PushSection({indent + maybe_key + "xxx" + maybe_separator, Description("numeric")});
684  return;
685  }
686  case Type::BOOL: {
687  sections.PushSection({indent + maybe_key + "true|false" + maybe_separator, Description("boolean")});
688  return;
689  }
690  case Type::ARR_FIXED:
691  case Type::ARR: {
692  sections.PushSection({indent + maybe_key + "[", Description("json array")});
693  for (const auto& i : m_inner) {
694  i.ToSections(sections, OuterType::ARR, current_indent + 2);
695  }
696  CHECK_NONFATAL(!m_inner.empty());
697  if (m_type == Type::ARR && m_inner.back().m_type != Type::ELISION) {
698  sections.PushSection({indent_next + "...", ""});
699  } else {
700  // Remove final comma, which would be invalid JSON
701  sections.m_sections.back().m_left.pop_back();
702  }
703  sections.PushSection({indent + "]" + maybe_separator, ""});
704  return;
705  }
706  case Type::OBJ_DYN:
707  case Type::OBJ: {
708  sections.PushSection({indent + maybe_key + "{", Description("json object")});
709  for (const auto& i : m_inner) {
710  i.ToSections(sections, OuterType::OBJ, current_indent + 2);
711  }
712  CHECK_NONFATAL(!m_inner.empty());
713  if (m_type == Type::OBJ_DYN && m_inner.back().m_type != Type::ELISION) {
714  // If the dictionary keys are dynamic, use three dots for continuation
715  sections.PushSection({indent_next + "...", ""});
716  } else {
717  // Remove final comma, which would be invalid JSON
718  sections.m_sections.back().m_left.pop_back();
719  }
720  sections.PushSection({indent + "}" + maybe_separator, ""});
721  return;
722  }
723  } // no default case, so the compiler can warn about missing cases
724  CHECK_NONFATAL(false);
725 }
726 
727 std::string RPCArg::ToStringObj(const bool oneline) const
728 {
729  std::string res;
730  res += "\"";
731  res += GetFirstName();
732  if (oneline) {
733  res += "\":";
734  } else {
735  res += "\": ";
736  }
737  switch (m_type) {
738  case Type::STR:
739  return res + "\"str\"";
740  case Type::STR_HEX:
741  return res + "\"hex\"";
742  case Type::NUM:
743  return res + "n";
744  case Type::RANGE:
745  return res + "n or [n,n]";
746  case Type::AMOUNT:
747  return res + "amount";
748  case Type::BOOL:
749  return res + "bool";
750  case Type::ARR:
751  res += "[";
752  for (const auto& i : m_inner) {
753  res += i.ToString(oneline) + ",";
754  }
755  return res + "...]";
756  case Type::OBJ:
757  case Type::OBJ_USER_KEYS:
758  // Currently unused, so avoid writing dead code
759  CHECK_NONFATAL(false);
760  } // no default case, so the compiler can warn about missing cases
761  CHECK_NONFATAL(false);
762 }
763 
764 std::string RPCArg::ToString(const bool oneline) const
765 {
766  if (oneline && !m_oneline_description.empty()) return m_oneline_description;
767 
768  switch (m_type) {
769  case Type::STR_HEX:
770  case Type::STR: {
771  return "\"" + GetFirstName() + "\"";
772  }
773  case Type::NUM:
774  case Type::RANGE:
775  case Type::AMOUNT:
776  case Type::BOOL: {
777  return GetFirstName();
778  }
779  case Type::OBJ:
780  case Type::OBJ_USER_KEYS: {
781  const std::string res = Join(m_inner, ",", [&](const RPCArg& i) { return i.ToStringObj(oneline); });
782  if (m_type == Type::OBJ) {
783  return "{" + res + "}";
784  } else {
785  return "{" + res + ",...}";
786  }
787  }
788  case Type::ARR: {
789  std::string res;
790  for (const auto& i : m_inner) {
791  res += i.ToString(oneline) + ",";
792  }
793  return "[" + res + "...]";
794  }
795  } // no default case, so the compiler can warn about missing cases
796  CHECK_NONFATAL(false);
797 }
798 
799 static std::pair<int64_t, int64_t> ParseRange(const UniValue& value)
800 {
801  if (value.isNum()) {
802  return {0, value.get_int64()};
803  }
804  if (value.isArray() && value.size() == 2 && value[0].isNum() && value[1].isNum()) {
805  int64_t low = value[0].get_int64();
806  int64_t high = value[1].get_int64();
807  if (low > high) throw JSONRPCError(RPC_INVALID_PARAMETER, "Range specified as [begin,end] must not have begin after end");
808  return {low, high};
809  }
810  throw JSONRPCError(RPC_INVALID_PARAMETER, "Range must be specified as end or as [begin,end]");
811 }
812 
813 std::pair<int64_t, int64_t> ParseDescriptorRange(const UniValue& value)
814 {
815  int64_t low, high;
816  std::tie(low, high) = ParseRange(value);
817  if (low < 0) {
818  throw JSONRPCError(RPC_INVALID_PARAMETER, "Range should be greater or equal than 0");
819  }
820  if ((high >> 31) != 0) {
821  throw JSONRPCError(RPC_INVALID_PARAMETER, "End of range is too high");
822  }
823  if (high >= low + 1000000) {
824  throw JSONRPCError(RPC_INVALID_PARAMETER, "Range is too large");
825  }
826  return {low, high};
827 }
828 
829 std::vector<CScript> EvalDescriptorStringOrObject(const UniValue& scanobject, FlatSigningProvider& provider)
830 {
831  std::string desc_str;
832  std::pair<int64_t, int64_t> range = {0, 1000};
833  if (scanobject.isStr()) {
834  desc_str = scanobject.get_str();
835  } else if (scanobject.isObject()) {
836  UniValue desc_uni = find_value(scanobject, "desc");
837  if (desc_uni.isNull()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Descriptor needs to be provided in scan object");
838  desc_str = desc_uni.get_str();
839  UniValue range_uni = find_value(scanobject, "range");
840  if (!range_uni.isNull()) {
841  range = ParseDescriptorRange(range_uni);
842  }
843  } else {
844  throw JSONRPCError(RPC_INVALID_PARAMETER, "Scan object needs to be either a string or an object");
845  }
846 
847  std::string error;
848  auto desc = Parse(desc_str, provider, error);
849  if (!desc) {
851  }
852  if (!desc->IsRange()) {
853  range.first = 0;
854  range.second = 0;
855  }
856  std::vector<CScript> ret;
857  for (int i = range.first; i <= range.second; ++i) {
858  std::vector<CScript> scripts;
859  if (!desc->Expand(i, provider, scripts, provider)) {
860  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Cannot derive script without private keys: '%s'", desc_str));
861  }
862  std::move(scripts.begin(), scripts.end(), std::back_inserter(ret));
863  }
864  return ret;
865 }
866 
868 {
869  UniValue servicesNames(UniValue::VARR);
870 
871  for (const auto& flag : serviceFlagsToStr(services)) {
872  servicesNames.push_back(flag);
873  }
874 
875  return servicesNames;
876 }
virtual bool GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const override
CPubKey AddrToPubKey(const FillableSigningProvider &keystore, const std::string &addr_in)
Definition: util.cpp:158
Aliases for backward compatibility.
Definition: protocol.h:53
bool isObject() const
Definition: univalue.h:84
CAmount AmountFromValue(const UniValue &value)
Definition: util.cpp:77
void RPCTypeCheck(const UniValue &params, const std::list< UniValueType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.
Definition: util.cpp:23
ServiceFlags
nServices flags
Definition: protocol.h:269
std::vector< std::string > GetArgNames() const
Definition: util.cpp:491
std::string ToDescriptionString() const
Return the description string.
Definition: util.cpp:458
Required arg.
std::vector< unsigned char > ParseHexO(const UniValue &o, std::string strKey)
Definition: util.cpp:111
Keeps track of RPCArgs by transforming them into sections for the purpose of serializing everything t...
Definition: util.cpp:326
auto Join(const std::vector< T > &list, const BaseType &separator, UnaryOp unary_op) -> decltype(unary_op(list.at(0)))
Join a list of items.
Definition: string.h:36
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
bool typeAny
Definition: util.h:47
std::vector< unsigned char > ParseHexV(const UniValue &v, std::string strName)
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:20
RPCErrorCode RPCErrorFromTransactionError(TransactionError terr)
Definition: util.cpp:283
void ToSections(Sections &sections, OuterType outer_type=OuterType::NONE, const int current_indent=0) const
Append the sections of the result.
Definition: util.cpp:635
bool MoneyRange(const CAmount &nValue)
Definition: amount.h:26
#define CHECK_NONFATAL(condition)
Throw a NonFatalCheckError when the condition evaluates to false.
Definition: check.h:32
std::vector< unsigned char > ParseHex(const char *psz)
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition: standard.cpp:321
std::string ToDescriptionString() const
Definition: util.cpp:474
const std::string m_right
Definition: util.cpp:319
void RPCTypeCheckArgument(const UniValue &value, const UniValueType &typeExpected)
Type-check one argument; throws JSONRPCError if wrong type given.
Definition: util.cpp:40
const RPCExamples m_examples
Definition: util.h:365
const std::string & get_str() const
CKeyID GetKeyForDestination(const SigningProvider &store, const CTxDestination &dest)
Return the CKeyID of the key involved in a script (if there is a unique one).
bool isNum() const
Definition: univalue.h:82
bool isStr() const
Definition: univalue.h:81
bilingual_str TransactionErrorString(const TransactionError err)
Definition: error.cpp:11
std::vector< std::string > serviceFlagsToStr(uint64_t flags)
Convert service flags (a bitmask of NODE_*) to human readable strings.
Definition: protocol.cpp:221
const RPCMethodImpl m_fun
Definition: util.h:361
int64_t get_int64() const
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:212
bool IsValidNumArgs(size_t num_args) const
If the supplied number of args is neither too small nor too high.
Definition: util.cpp:479
const std::vector< std::string > & getKeys() const
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
Definition: script.h:23
UniValue operator()(const WitnessUnknown &id) const
Definition: util.cpp:258
const std::string & getValStr() const
Definition: univalue.h:65
UniValue operator()(const WitnessV0ScriptHash &id) const
Definition: util.cpp:248
std::string ToString() const
Definition: util.cpp:500
bool ParseFixedPoint(const std::string &val, int decimals, int64_t *amount_out)
Parse number as fixed point according to JSON number syntax.
bool IsNull() const
Definition: uint256.h:31
const std::vector< RPCArg > m_inner
Only used for arrays or dicts.
Definition: util.h:150
OutputType
Definition: outputtype.h:17
Invalid, missing or duplicate parameter.
Definition: protocol.h:43
void RPCTypeCheckObj(const UniValue &o, const std::map< std::string, UniValueType > &typesExpected, bool fAllowNull, bool fStrict)
Definition: util.cpp:47
const UniValue & find_value(const UniValue &obj, const std::string &name)
Definition: univalue.cpp:234
size_t m_max_pad
Definition: util.cpp:328
UniValue::VType type
Definition: util.h:48
const std::string m_description
Definition: util.h:362
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
std::unique_ptr< Descriptor > Parse(const std::string &descriptor, FlatSigningProvider &out, std::string &error, bool require_checksum)
Parse a descriptor string.
CoinStatsHashType
Definition: coinstats.h:17
Special type that is a STR with only hex chars.
std::string GetName() const
Return the name, throws when there are aliases.
Definition: util.cpp:557
const char * uvTypeName(UniValue::VType t)
Definition: univalue.cpp:219
UniValue operator()(const PKHash &keyID) const
Definition: util.cpp:222
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:51
bool push_back(const UniValue &val)
Definition: univalue.cpp:108
Definition: util.h:117
UniValue operator()(const CNoDestination &dest) const
Definition: util.cpp:217
UniValue operator()(const ScriptHash &scriptID) const
Definition: util.cpp:230
bool IsFullyValid() const
fully validate whether this is a valid public key (more expensive than IsValid()) ...
Definition: pubkey.cpp:230
CTxDestination subtype to encode any future Witness version.
Definition: standard.h:180
const char * name
Definition: rest.cpp:41
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:273
bool IsOptional() const
Definition: util.cpp:563
uint256 uint256S(const char *str)
Definition: uint256.h:137
An encapsulated public key.
Definition: pubkey.h:31
Fillable signing provider that keeps keys in an address->secret map.
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:138
bool IsHex(const std::string &str)
Unexpected type was passed as parameter.
Definition: protocol.h:40
Special type where the user must set the keys e.g. to define multiple addresses; as opposed to e...
std::function< UniValue(const RPCHelpMan &, const JSONRPCRequest &)> RPCMethodImpl
Definition: util.h:335
UniValue operator()(const WitnessV0KeyHash &id) const
Definition: util.cpp:238
static std::pair< int64_t, int64_t > ParseRange(const UniValue &value)
Definition: util.cpp:799
bool pushKV(const std::string &key, const UniValue &val)
Definition: univalue.cpp:133
std::string GetFirstName() const
Return the first of all aliases.
Definition: util.cpp:552
const std::vector< RPCArg > m_args
Definition: util.h:363
int get_int() const
Invalid address or key.
Definition: protocol.h:41
CTxDestination AddAndGetMultisigDestination(const int required, const std::vector< CPubKey > &pubkeys, OutputType type, FillableSigningProvider &keystore, CScript &script_out)
Definition: util.cpp:179
bool isNull() const
Definition: univalue.h:77
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:79
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Optional arg that is a named argument and has a default value of null.
const std::vector< std::string > m_type_str
Should be empty unless it is supposed to override the auto-generated type strings. Vector length is either 0 or 2, m_type_str.at(0) will override the type of the value in a key-value pair, m_type_str.at(1) will override the type in the argument description.
Definition: util.h:154
const RPCResults m_results
Definition: util.h:364
Special type that is a NUM or [NUM,NUM].
OuterType
Serializing JSON objects depends on the outer type.
Definition: util.h:111
RPCHelpMan(std::string name, std::string description, std::vector< RPCArg > args, RPCResults results, RPCExamples examples)
Definition: util.cpp:436
256-bit opaque blob.
Definition: uint256.h:124
Optional argument with default value omitted because they are implicitly clear.
CTxDestination DecodeDestination(const std::string &str)
Definition: key_io.cpp:211
enum VType type() const
Definition: univalue.h:181
std::string ToDescriptionString() const
Return the description string, including the argument type and whether the argument is required...
Definition: util.cpp:572
std::vector< Section > m_sections
Definition: util.cpp:327
std::vector< CScript > EvalDescriptorStringOrObject(const UniValue &scanobject, FlatSigningProvider &provider)
Evaluate a descriptor given as a string, or as a {"desc":...,"range":...} object, with default range ...
Definition: util.cpp:829
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:404
std::string m_left
Definition: util.cpp:318
Section(const std::string &left, const std::string &right)
Definition: util.cpp:316
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:339
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:21
Special type representing a floating point amount (can be either NUM or STR)
TransactionError
Definition: error.h:22
UniValue GetServicesNames(ServiceFlags services)
Returns, given services flags, a list of humanly readable (known) network services.
Definition: util.cpp:867
std::pair< int64_t, int64_t > ParseDescriptorRange(const UniValue &value)
Parse a JSON range specified as int64, or [int64, int64].
Definition: util.cpp:813
const Type m_type
Definition: util.h:148
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:133
size_type size() const
Definition: prevector.h:282
CScript GetScriptForMultisig(int nRequired, const std::vector< CPubKey > &keys)
Generate a multisig script.
Definition: standard.cpp:310
UniValue JSONRPCTransactionError(TransactionError terr, const std::string &err_string)
Definition: util.cpp:302
No valid connection manager instance found.
Definition: protocol.h:64
size_t size() const
Definition: univalue.h:68
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:92
void PushSection(const Section &s)
Definition: util.cpp:330
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded Values (throws error if not hex).
Definition: util.cpp:89
const std::string m_name
Definition: util.h:358
RPCErrorCode
Bitcoin RPC error codes.
Definition: protocol.h:23
std::string ToString() const
Concatenate all sections with proper padding.
Definition: util.cpp:395
std::string ToString(bool oneline) const
Return the type string of the argument.
Definition: util.cpp:764
A pair of strings that can be aligned (through padding) with other Sections later on...
Definition: util.cpp:315
UniValue DescribeAddress(const CTxDestination &dest)
Definition: util.cpp:268
bool error(const char *fmt, const Args &... args)
Definition: system.h:52
const std::string EXAMPLE_ADDRESS[2]
Example bech32 addresses for the RPCExamples help documentation.
Definition: util.cpp:21
bool isArray() const
Definition: univalue.h:83
Wrapper for UniValue::VType, which includes typeAny: Used to denote don&#39;t care type.
Definition: util.h:44
CPubKey HexToPubKey(const std::string &hex_in)
Definition: util.cpp:145
Error parsing or validating structure in raw format.
Definition: protocol.h:45
CoinStatsHashType ParseHashType(const UniValue &param, const CoinStatsHashType default_type)
Definition: util.cpp:116
std::string ToStringObj(bool oneline) const
Return the type string of the argument when it is in an object (dict).
Definition: util.cpp:727
uint256 ParseHashO(const UniValue &o, std::string strKey)
Definition: util.cpp:98