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