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