Bitcoin ABC  0.29.4
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 <rpc/util.h>
6 
7 #include <common/args.h>
8 #include <consensus/amount.h>
9 #include <key_io.h>
10 #include <script/descriptor.h>
11 #include <script/signingprovider.h>
12 #include <tinyformat.h>
13 #include <util/check.h>
14 #include <util/strencodings.h>
15 #include <util/string.h>
16 #include <util/translation.h>
17 
18 #include <tuple>
19 #include <variant>
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 = o.find_value(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(o.find_value(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(o.find_value(strKey), strKey);
136 }
137 
138 namespace {
139 
145 std::string ShellQuote(const std::string &s) {
146  std::string result;
147  result.reserve(s.size() * 2);
148  for (const char ch : s) {
149  if (ch == '\'') {
150  result += "'\''";
151  } else {
152  result += ch;
153  }
154  }
155  return "'" + result + "'";
156 }
157 
164 std::string ShellQuoteIfNeeded(const std::string &s) {
165  for (const char ch : s) {
166  if (ch == ' ' || ch == '\'' || ch == '"') {
167  return ShellQuote(s);
168  }
169  }
170 
171  return s;
172 }
173 
174 } // namespace
175 
176 std::string HelpExampleCli(const std::string &methodname,
177  const std::string &args) {
178  return "> bitcoin-cli " + methodname + " " + args + "\n";
179 }
180 
181 std::string HelpExampleCliNamed(const std::string &methodname,
182  const RPCArgList &args) {
183  std::string result = "> bitcoin-cli -named " + methodname;
184  for (const auto &argpair : args) {
185  const auto &value = argpair.second.isStr() ? argpair.second.get_str()
186  : argpair.second.write();
187  result += " " + argpair.first + "=" + ShellQuoteIfNeeded(value);
188  }
189  result += "\n";
190  return result;
191 }
192 
193 std::string HelpExampleRpc(const std::string &methodname,
194  const std::string &args) {
195  return "> curl --user myusername --data-binary '{\"jsonrpc\": \"1.0\", "
196  "\"id\": \"curltest\", "
197  "\"method\": \"" +
198  methodname + "\", \"params\": [" + args +
199  "]}' -H 'content-type: text/plain;' http://127.0.0.1:8332/\n";
200 }
201 
202 std::string HelpExampleRpcNamed(const std::string &methodname,
203  const RPCArgList &args) {
204  UniValue params(UniValue::VOBJ);
205  for (const auto &param : args) {
206  params.pushKV(param.first, param.second);
207  }
208 
209  return "> curl --user myusername --data-binary '{\"jsonrpc\": \"1.0\", "
210  "\"id\": \"curltest\", "
211  "\"method\": \"" +
212  methodname + "\", \"params\": " + params.write() +
213  "}' -H 'content-type: text/plain;' http://127.0.0.1:8332/\n";
214 }
215 
216 // Converts a hex string to a public key if possible
217 CPubKey HexToPubKey(const std::string &hex_in) {
218  if (!IsHex(hex_in)) {
220  "Invalid public key: " + hex_in);
221  }
222  CPubKey vchPubKey(ParseHex(hex_in));
223  if (!vchPubKey.IsFullyValid()) {
225  "Invalid public key: " + hex_in);
226  }
227  return vchPubKey;
228 }
229 
230 // Retrieves a public key for an address from the given FillableSigningProvider
231 CPubKey AddrToPubKey(const CChainParams &chainparams,
232  const FillableSigningProvider &keystore,
233  const std::string &addr_in) {
234  CTxDestination dest = DecodeDestination(addr_in, chainparams);
235  if (!IsValidDestination(dest)) {
237  "Invalid address: " + addr_in);
238  }
239  CKeyID key = GetKeyForDestination(keystore, dest);
240  if (key.IsNull()) {
242  strprintf("%s does not refer to a key", addr_in));
243  }
244  CPubKey vchPubKey;
245  if (!keystore.GetPubKey(key, vchPubKey)) {
246  throw JSONRPCError(
248  strprintf("no full public key for address %s", addr_in));
249  }
250  if (!vchPubKey.IsFullyValid()) {
252  "Wallet contains an invalid public key");
253  }
254  return vchPubKey;
255 }
256 
257 // Creates a multisig address from a given list of public keys, number of
258 // signatures required, and the address type
260  const std::vector<CPubKey> &pubkeys,
261  OutputType type,
262  FillableSigningProvider &keystore,
263  CScript &script_out) {
264  // Gather public keys
265  if (required < 1) {
266  throw JSONRPCError(
268  "a multisignature address must require at least one key to redeem");
269  }
270  if ((int)pubkeys.size() < required) {
272  strprintf("not enough keys supplied (got %u keys, "
273  "but need at least %d to redeem)",
274  pubkeys.size(), required));
275  }
276  if (pubkeys.size() > 16) {
278  "Number of keys involved in the multisignature "
279  "address creation > 16\nReduce the number");
280  }
281 
282  script_out = GetScriptForMultisig(required, pubkeys);
283 
284  if (script_out.size() > MAX_SCRIPT_ELEMENT_SIZE) {
285  throw JSONRPCError(
287  (strprintf("redeemScript exceeds size limit: %d > %d",
288  script_out.size(), MAX_SCRIPT_ELEMENT_SIZE)));
289  }
290 
291  // Check if any keys are uncompressed. If so, the type is legacy
292  for (const CPubKey &pk : pubkeys) {
293  if (!pk.IsCompressed()) {
294  type = OutputType::LEGACY;
295  break;
296  }
297  }
298 
299  // Make the address
300  CTxDestination dest =
301  AddAndGetDestinationForScript(keystore, script_out, type);
302 
303  return dest;
304 }
305 
307 public:
309 
310  UniValue operator()(const CNoDestination &dest) const {
311  return UniValue(UniValue::VOBJ);
312  }
313 
314  UniValue operator()(const PKHash &keyID) const {
316  obj.pushKV("isscript", false);
317  return obj;
318  }
319 
320  UniValue operator()(const ScriptHash &scriptID) const {
322  obj.pushKV("isscript", true);
323  return obj;
324  }
325 };
326 
328  return std::visit(DescribeAddressVisitor(), dest);
329 }
330 
331 std::string GetAllOutputTypes() {
332  std::vector<std::string> ret;
333  using U = std::underlying_type<TxoutType>::type;
334  for (U i = (U)TxoutType::NONSTANDARD; i <= (U)TxoutType::NULL_DATA; ++i) {
335  ret.emplace_back(GetTxnOutputType(static_cast<TxoutType>(i)));
336  }
337  return Join(ret, ", ");
338 }
339 
341  switch (terr) {
350  return RPC_INVALID_PARAMETER;
353  default:
354  break;
355  }
356  return RPC_TRANSACTION_ERROR;
357 }
358 
360  const std::string &err_string) {
361  if (err_string.length() > 0) {
362  return JSONRPCError(RPCErrorFromTransactionError(terr), err_string);
363  } else {
365  TransactionErrorString(terr).original);
366  }
367 }
368 
373 struct Section {
374  Section(const std::string &left, const std::string &right)
375  : m_left{left}, m_right{right} {}
376  std::string m_left;
377  const std::string m_right;
378 };
379 
384 struct Sections {
385  std::vector<Section> m_sections;
386  size_t m_max_pad{0};
387 
388  void PushSection(const Section &s) {
389  m_max_pad = std::max(m_max_pad, s.m_left.size());
390  m_sections.push_back(s);
391  }
392 
396  void Push(const RPCArg &arg, const size_t current_indent = 5,
397  const OuterType outer_type = OuterType::NONE) {
398  const auto indent = std::string(current_indent, ' ');
399  const auto indent_next = std::string(current_indent + 2, ' ');
400  // Dictionary keys must have a name
401  const bool push_name{outer_type == OuterType::OBJ};
402 
403  switch (arg.m_type) {
405  case RPCArg::Type::STR:
406  case RPCArg::Type::NUM:
408  case RPCArg::Type::RANGE:
409  case RPCArg::Type::BOOL: {
410  // Nothing more to do for non-recursive types on first recursion
411  if (outer_type == OuterType::NONE) {
412  return;
413  }
414  auto left = indent;
415  if (arg.m_type_str.size() != 0 && push_name) {
416  left +=
417  "\"" + arg.GetName() + "\": " + arg.m_type_str.at(0);
418  } else {
419  left += push_name ? arg.ToStringObj(/* oneline */ false)
420  : arg.ToString(/* oneline */ false);
421  }
422  left += ",";
423  PushSection({left, arg.ToDescriptionString()});
424  break;
425  }
426  case RPCArg::Type::OBJ:
428  const auto right = outer_type == OuterType::NONE
429  ? ""
430  : arg.ToDescriptionString();
431  PushSection(
432  {indent + (push_name ? "\"" + arg.GetName() + "\": " : "") +
433  "{",
434  right});
435  for (const auto &arg_inner : arg.m_inner) {
436  Push(arg_inner, current_indent + 2, OuterType::OBJ);
437  }
438  if (arg.m_type != RPCArg::Type::OBJ) {
439  PushSection({indent_next + "...", ""});
440  }
441  PushSection(
442  {indent + "}" + (outer_type != OuterType::NONE ? "," : ""),
443  ""});
444  break;
445  }
446  case RPCArg::Type::ARR: {
447  auto left = indent;
448  left += push_name ? "\"" + arg.GetName() + "\": " : "";
449  left += "[";
450  const auto right = outer_type == OuterType::NONE
451  ? ""
452  : arg.ToDescriptionString();
453  PushSection({left, right});
454  for (const auto &arg_inner : arg.m_inner) {
455  Push(arg_inner, current_indent + 2, OuterType::ARR);
456  }
457  PushSection({indent_next + "...", ""});
458  PushSection(
459  {indent + "]" + (outer_type != OuterType::NONE ? "," : ""),
460  ""});
461  break;
462  } // no default case, so the compiler can warn about missing cases
463  }
464  }
465 
469  std::string ToString() const {
470  std::string ret;
471  const size_t pad = m_max_pad + 4;
472  for (const auto &s : m_sections) {
473  // The left part of a section is assumed to be a single line,
474  // usually it is the name of the JSON struct or a brace like
475  // {, }, [, or ]
476  CHECK_NONFATAL(s.m_left.find('\n') == std::string::npos);
477  if (s.m_right.empty()) {
478  ret += s.m_left;
479  ret += "\n";
480  continue;
481  }
482 
483  std::string left = s.m_left;
484  left.resize(pad, ' ');
485  ret += left;
486 
487  // Properly pad after newlines
488  std::string right;
489  size_t begin = 0;
490  size_t new_line_pos = s.m_right.find_first_of('\n');
491  while (true) {
492  right += s.m_right.substr(begin, new_line_pos - begin);
493  if (new_line_pos == std::string::npos) {
494  // No new line
495  break;
496  }
497  right += "\n" + std::string(pad, ' ');
498  begin = s.m_right.find_first_not_of(' ', new_line_pos + 1);
499  if (begin == std::string::npos) {
500  break; // Empty line
501  }
502  new_line_pos = s.m_right.find_first_of('\n', begin + 1);
503  }
504  ret += right;
505  ret += "\n";
506  }
507  return ret;
508  }
509 };
510 
511 RPCHelpMan::RPCHelpMan(std::string name_, std::string description,
512  std::vector<RPCArg> args, RPCResults results,
513  RPCExamples examples)
514  : RPCHelpMan{std::move(name_), std::move(description), std::move(args),
515  std::move(results), std::move(examples), nullptr} {}
516 
517 RPCHelpMan::RPCHelpMan(std::string name_, std::string description,
518  std::vector<RPCArg> args, RPCResults results,
519  RPCExamples examples, RPCMethodImpl fun)
520  : m_name{std::move(name_)}, m_fun{std::move(fun)},
521  m_description{std::move(description)}, m_args{std::move(args)},
522  m_results{std::move(results)}, m_examples{std::move(examples)} {
523  std::set<std::string> named_args;
524  for (const auto &arg : m_args) {
525  std::vector<std::string> names = SplitString(arg.m_names, '|');
526  // Should have unique named arguments
527  for (const std::string &name : names) {
528  CHECK_NONFATAL(named_args.insert(name).second);
529  }
530  // Default value type should match argument type only when defined
531  if (arg.m_fallback.index() == 2) {
532  const RPCArg::Type type = arg.m_type;
533  switch (std::get<RPCArg::Default>(arg.m_fallback).getType()) {
534  case UniValue::VOBJ:
536  break;
537  case UniValue::VARR:
539  break;
540  case UniValue::VSTR:
542  type == RPCArg::Type::STR_HEX ||
543  type == RPCArg::Type::AMOUNT);
544  break;
545  case UniValue::VNUM:
547  type == RPCArg::Type::AMOUNT ||
548  type == RPCArg::Type::RANGE);
549  break;
550  case UniValue::VBOOL:
552  break;
553  case UniValue::VNULL:
554  // Null values are accepted in all arguments
555  break;
556  default:
557  CHECK_NONFATAL(false);
558  break;
559  }
560  }
561  }
562 }
563 
564 std::string RPCResults::ToDescriptionString() const {
565  std::string result;
566 
567  for (const auto &r : m_results) {
568  if (r.m_type == RPCResult::Type::ANY) {
569  // for testing only
570  continue;
571  }
572  if (r.m_cond.empty()) {
573  result += "\nResult:\n";
574  } else {
575  result += "\nResult (" + r.m_cond + "):\n";
576  }
577  Sections sections;
578  r.ToSections(sections);
579  result += sections.ToString();
580  }
581  return result;
582 }
583 
584 std::string RPCExamples::ToDescriptionString() const {
585  return m_examples.empty() ? m_examples : "\nExamples:\n" + m_examples;
586 }
587 
589  const JSONRPCRequest &request) const {
590  if (request.mode == JSONRPCRequest::GET_ARGS) {
591  return GetArgMap();
592  }
593  /*
594  * Check if the given request is valid according to this command or if
595  * the user is asking for help information, and throw help when appropriate.
596  */
597  if (request.mode == JSONRPCRequest::GET_HELP ||
598  !IsValidNumArgs(request.params.size())) {
599  throw std::runtime_error(ToString());
600  }
601  const UniValue ret = m_fun(*this, config, request);
602  CHECK_NONFATAL(std::any_of(
603  m_results.m_results.begin(), m_results.m_results.end(),
604  [ret](const RPCResult &res) { return res.MatchesType(ret); }));
605  return ret;
606 }
607 
608 bool RPCHelpMan::IsValidNumArgs(size_t num_args) const {
609  size_t num_required_args = 0;
610  for (size_t n = m_args.size(); n > 0; --n) {
611  if (!m_args.at(n - 1).IsOptional()) {
612  num_required_args = n;
613  break;
614  }
615  }
616  return num_required_args <= num_args && num_args <= m_args.size();
617 }
618 
619 std::vector<std::string> RPCHelpMan::GetArgNames() const {
620  std::vector<std::string> ret;
621  for (const auto &arg : m_args) {
622  ret.emplace_back(arg.m_names);
623  }
624  return ret;
625 }
626 
627 std::string RPCHelpMan::ToString() const {
628  std::string ret;
629 
630  // Oneline summary
631  ret += m_name;
632  bool was_optional{false};
633  for (const auto &arg : m_args) {
634  if (arg.m_hidden) {
635  // Any arg that follows is also hidden
636  break;
637  }
638  const bool optional = arg.IsOptional();
639  ret += " ";
640  if (optional) {
641  if (!was_optional) {
642  ret += "( ";
643  }
644  was_optional = true;
645  } else {
646  if (was_optional) {
647  ret += ") ";
648  }
649  was_optional = false;
650  }
651  ret += arg.ToString(/* oneline */ true);
652  }
653  if (was_optional) {
654  ret += " )";
655  }
656  ret += "\n\n";
657 
658  // Description
659  ret += m_description;
660 
661  // Arguments
662  Sections sections;
663  for (size_t i{0}; i < m_args.size(); ++i) {
664  const auto &arg = m_args.at(i);
665  if (arg.m_hidden) {
666  // Any arg that follows is also hidden
667  break;
668  }
669 
670  if (i == 0) {
671  ret += "\nArguments:\n";
672  }
673 
674  // Push named argument name and description
675  sections.m_sections.emplace_back(::ToString(i + 1) + ". " +
676  arg.GetFirstName(),
677  arg.ToDescriptionString());
678  sections.m_max_pad = std::max(sections.m_max_pad,
679  sections.m_sections.back().m_left.size());
680 
681  // Recursively push nested args
682  sections.Push(arg);
683  }
684  ret += sections.ToString();
685 
686  // Result
688 
689  // Examples
691 
692  return ret;
693 }
694 
697  for (int i{0}; i < int(m_args.size()); ++i) {
698  const auto &arg = m_args.at(i);
699  std::vector<std::string> arg_names = SplitString(arg.m_names, '|');
700  for (const auto &arg_name : arg_names) {
702  map.push_back(m_name);
703  map.push_back(i);
704  map.push_back(arg_name);
705  map.push_back(arg.m_type == RPCArg::Type::STR ||
706  arg.m_type == RPCArg::Type::STR_HEX);
707  arr.push_back(map);
708  }
709  }
710  return arr;
711 }
712 
713 std::string RPCArg::GetFirstName() const {
714  return m_names.substr(0, m_names.find("|"));
715 }
716 
717 std::string RPCArg::GetName() const {
718  CHECK_NONFATAL(std::string::npos == m_names.find("|"));
719  return m_names;
720 }
721 
722 bool RPCArg::IsOptional() const {
723  if (m_fallback.index() != 0) {
724  return true;
725  } else {
726  return RPCArg::Optional::NO != std::get<RPCArg::Optional>(m_fallback);
727  }
728 }
729 
730 std::string RPCArg::ToDescriptionString() const {
731  std::string ret;
732  ret += "(";
733  if (m_type_str.size() != 0) {
734  ret += m_type_str.at(1);
735  } else {
736  switch (m_type) {
737  case Type::STR_HEX:
738  case Type::STR: {
739  ret += "string";
740  break;
741  }
742  case Type::NUM: {
743  ret += "numeric";
744  break;
745  }
746  case Type::AMOUNT: {
747  ret += "numeric or string";
748  break;
749  }
750  case Type::RANGE: {
751  ret += "numeric or array";
752  break;
753  }
754  case Type::BOOL: {
755  ret += "boolean";
756  break;
757  }
758  case Type::OBJ:
759  case Type::OBJ_USER_KEYS: {
760  ret += "json object";
761  break;
762  }
763  case Type::ARR: {
764  ret += "json array";
765  break;
766  } // no default case, so the compiler can warn about missing cases
767  }
768  }
769  if (m_fallback.index() == 1) {
770  ret +=
771  ", optional, default=" + std::get<RPCArg::DefaultHint>(m_fallback);
772  } else if (m_fallback.index() == 2) {
773  ret += ", optional, default=" +
774  std::get<RPCArg::Default>(m_fallback).write();
775  } else {
776  switch (std::get<RPCArg::Optional>(m_fallback)) {
778  // nothing to do. Element is treated as if not present and has
779  // no default value
780  break;
781  }
783  ret += ", optional"; // Default value is "null"
784  break;
785  }
786  case RPCArg::Optional::NO: {
787  ret += ", required";
788  break;
789  } // no default case, so the compiler can warn about missing cases
790  }
791  }
792  ret += ")";
793  ret += m_description.empty() ? "" : " " + m_description;
794  return ret;
795 }
796 
797 void RPCResult::ToSections(Sections &sections, const OuterType outer_type,
798  const int current_indent) const {
799  // Indentation
800  const std::string indent(current_indent, ' ');
801  const std::string indent_next(current_indent + 2, ' ');
802 
803  // Elements in a JSON structure (dictionary or array) are separated by a
804  // comma
805  const std::string maybe_separator{outer_type != OuterType::NONE ? "," : ""};
806 
807  // The key name if recursed into an dictionary
808  const std::string maybe_key{
809  outer_type == OuterType::OBJ ? "\"" + this->m_key_name + "\" : " : ""};
810 
811  // Format description with type
812  const auto Description = [&](const std::string &type) {
813  return "(" + type + (this->m_optional ? ", optional" : "") + ")" +
814  (this->m_description.empty() ? "" : " " + this->m_description);
815  };
816 
817  switch (m_type) {
818  case Type::ELISION: {
819  // If the inner result is empty, use three dots for elision
820  sections.PushSection(
821  {indent + "..." + maybe_separator, m_description});
822  return;
823  }
824  case Type::ANY: {
825  // Only for testing
827  }
828  case Type::NONE: {
829  sections.PushSection(
830  {indent + "null" + maybe_separator, Description("json null")});
831  return;
832  }
833  case Type::STR: {
834  sections.PushSection(
835  {indent + maybe_key + "\"str\"" + maybe_separator,
836  Description("string")});
837  return;
838  }
839  case Type::STR_AMOUNT: {
840  sections.PushSection({indent + maybe_key + "n" + maybe_separator,
841  Description("numeric")});
842  return;
843  }
844  case Type::STR_HEX: {
845  sections.PushSection(
846  {indent + maybe_key + "\"hex\"" + maybe_separator,
847  Description("string")});
848  return;
849  }
850  case Type::NUM: {
851  sections.PushSection({indent + maybe_key + "n" + maybe_separator,
852  Description("numeric")});
853  return;
854  }
855  case Type::NUM_TIME: {
856  sections.PushSection({indent + maybe_key + "xxx" + maybe_separator,
857  Description("numeric")});
858  return;
859  }
860  case Type::BOOL: {
861  sections.PushSection(
862  {indent + maybe_key + "true|false" + maybe_separator,
863  Description("boolean")});
864  return;
865  }
866  case Type::ARR_FIXED:
867  case Type::ARR: {
868  sections.PushSection(
869  {indent + maybe_key + "[", Description("json array")});
870  for (const auto &i : m_inner) {
871  i.ToSections(sections, OuterType::ARR, current_indent + 2);
872  }
873  CHECK_NONFATAL(!m_inner.empty());
874  if (m_type == Type::ARR && m_inner.back().m_type != Type::ELISION) {
875  sections.PushSection({indent_next + "...", ""});
876  } else {
877  // Remove final comma, which would be invalid JSON
878  sections.m_sections.back().m_left.pop_back();
879  }
880  sections.PushSection({indent + "]" + maybe_separator, ""});
881  return;
882  }
883  case Type::OBJ_DYN:
884  case Type::OBJ_EMPTY: {
885  sections.PushSection(
886  {indent + maybe_key + "{}", Description("empty JSON object")});
887  return;
888  }
889  case Type::OBJ: {
890  sections.PushSection(
891  {indent + maybe_key + "{", Description("json object")});
892  for (const auto &i : m_inner) {
893  i.ToSections(sections, OuterType::OBJ, current_indent + 2);
894  }
895  CHECK_NONFATAL(!m_inner.empty());
896  if (m_type == Type::OBJ_DYN &&
897  m_inner.back().m_type != Type::ELISION) {
898  // If the dictionary keys are dynamic, use three dots for
899  // continuation
900  sections.PushSection({indent_next + "...", ""});
901  } else {
902  // Remove final comma, which would be invalid JSON
903  sections.m_sections.back().m_left.pop_back();
904  }
905  sections.PushSection({indent + "}" + maybe_separator, ""});
906  return;
907  } // no default case, so the compiler can warn about missing cases
908  }
910 }
911 
912 bool RPCResult::MatchesType(const UniValue &result) const {
913  switch (m_type) {
914  case Type::ELISION: {
915  return false;
916  }
917  case Type::ANY: {
918  return true;
919  }
920  case Type::NONE: {
921  return UniValue::VNULL == result.getType();
922  }
923  case Type::STR:
924  case Type::STR_HEX: {
925  return UniValue::VSTR == result.getType();
926  }
927  case Type::NUM:
928  case Type::STR_AMOUNT:
929  case Type::NUM_TIME: {
930  return UniValue::VNUM == result.getType();
931  }
932  case Type::BOOL: {
933  return UniValue::VBOOL == result.getType();
934  }
935  case Type::ARR_FIXED:
936  case Type::ARR: {
937  return UniValue::VARR == result.getType();
938  }
939  case Type::OBJ_DYN:
940  case Type::OBJ_EMPTY:
941  case Type::OBJ: {
942  return UniValue::VOBJ == result.getType();
943  }
944  } // no default case, so the compiler can warn about missing cases
946 }
947 
948 std::string RPCArg::ToStringObj(const bool oneline) const {
949  std::string res;
950  res += "\"";
951  res += GetFirstName();
952  if (oneline) {
953  res += "\":";
954  } else {
955  res += "\": ";
956  }
957  switch (m_type) {
958  case Type::STR:
959  return res + "\"str\"";
960  case Type::STR_HEX:
961  return res + "\"hex\"";
962  case Type::NUM:
963  return res + "n";
964  case Type::RANGE:
965  return res + "n or [n,n]";
966  case Type::AMOUNT:
967  return res + "amount";
968  case Type::BOOL:
969  return res + "bool";
970  case Type::ARR:
971  res += "[";
972  for (const auto &i : m_inner) {
973  res += i.ToString(oneline) + ",";
974  }
975  return res + "...]";
976  case Type::OBJ:
977  case Type::OBJ_USER_KEYS:
978  // Currently unused, so avoid writing dead code
980 
981  // no default case, so the compiler can warn about missing cases
982  }
984  return res + "unknown";
985 }
986 
987 std::string RPCArg::ToString(const bool oneline) const {
988  if (oneline && !m_oneline_description.empty()) {
989  return m_oneline_description;
990  }
991 
992  switch (m_type) {
993  case Type::STR_HEX:
994  case Type::STR: {
995  return "\"" + GetFirstName() + "\"";
996  }
997  case Type::NUM:
998  case Type::RANGE:
999  case Type::AMOUNT:
1000  case Type::BOOL: {
1001  return GetFirstName();
1002  }
1003  case Type::OBJ:
1004  case Type::OBJ_USER_KEYS: {
1005  const std::string res = Join(m_inner, ",", [&](const RPCArg &i) {
1006  return i.ToStringObj(oneline);
1007  });
1008  if (m_type == Type::OBJ) {
1009  return "{" + res + "}";
1010  } else {
1011  return "{" + res + ",...}";
1012  }
1013  }
1014  case Type::ARR: {
1015  std::string res;
1016  for (const auto &i : m_inner) {
1017  res += i.ToString(oneline) + ",";
1018  }
1019  return "[" + res + "...]";
1020  } // no default case, so the compiler can warn about missing cases
1021  }
1023 }
1024 
1025 static std::pair<int64_t, int64_t> ParseRange(const UniValue &value) {
1026  if (value.isNum()) {
1027  return {0, value.get_int64()};
1028  }
1029  if (value.isArray() && value.size() == 2 && value[0].isNum() &&
1030  value[1].isNum()) {
1031  int64_t low = value[0].get_int64();
1032  int64_t high = value[1].get_int64();
1033  if (low > high) {
1034  throw JSONRPCError(
1036  "Range specified as [begin,end] must not have begin after end");
1037  }
1038  return {low, high};
1039  }
1041  "Range must be specified as end or as [begin,end]");
1042 }
1043 
1044 std::pair<int64_t, int64_t> ParseDescriptorRange(const UniValue &value) {
1045  int64_t low, high;
1046  std::tie(low, high) = ParseRange(value);
1047  if (low < 0) {
1049  "Range should be greater or equal than 0");
1050  }
1051  if ((high >> 31) != 0) {
1052  throw JSONRPCError(RPC_INVALID_PARAMETER, "End of range is too high");
1053  }
1054  if (high >= low + 1000000) {
1055  throw JSONRPCError(RPC_INVALID_PARAMETER, "Range is too large");
1056  }
1057  return {low, high};
1058 }
1059 
1060 std::vector<CScript>
1062  FlatSigningProvider &provider) {
1063  std::string desc_str;
1064  std::pair<int64_t, int64_t> range = {0, 1000};
1065  if (scanobject.isStr()) {
1066  desc_str = scanobject.get_str();
1067  } else if (scanobject.isObject()) {
1068  const UniValue &desc_uni{scanobject.find_value("desc")};
1069  if (desc_uni.isNull()) {
1070  throw JSONRPCError(
1072  "Descriptor needs to be provided in scan object");
1073  }
1074  desc_str = desc_uni.get_str();
1075  const UniValue &range_uni{scanobject.find_value("range")};
1076  if (!range_uni.isNull()) {
1077  range = ParseDescriptorRange(range_uni);
1078  }
1079  } else {
1080  throw JSONRPCError(
1082  "Scan object needs to be either a string or an object");
1083  }
1084 
1085  std::string error;
1086  auto desc = Parse(desc_str, provider, error);
1087  if (!desc) {
1089  }
1090  if (!desc->IsRange()) {
1091  range.first = 0;
1092  range.second = 0;
1093  }
1094  std::vector<CScript> ret;
1095  for (int i = range.first; i <= range.second; ++i) {
1096  std::vector<CScript> scripts;
1097  if (!desc->Expand(i, provider, scripts, provider)) {
1098  throw JSONRPCError(
1100  strprintf("Cannot derive script without private keys: '%s'",
1101  desc_str));
1102  }
1103  std::move(scripts.begin(), scripts.end(), std::back_inserter(ret));
1104  }
1105  return ret;
1106 }
1107 
1109  UniValue servicesNames(UniValue::VARR);
1110 
1111  for (const auto &flag : serviceFlagsToStr(services)) {
1112  servicesNames.push_back(flag);
1113  }
1114 
1115  return servicesNames;
1116 }
bool MoneyRange(const Amount nValue)
Definition: amount.h:166
static constexpr Amount SATOSHI
Definition: amount.h:143
#define CHECK_NONFATAL(condition)
Identity function.
Definition: check.h:53
#define NONFATAL_UNREACHABLE()
NONFATAL_UNREACHABLE() is a macro that is used to mark unreachable code.
Definition: check.h:106
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:80
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:256
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:431
Definition: config.h:19
UniValue operator()(const CNoDestination &dest) const
Definition: util.cpp:310
UniValue operator()(const ScriptHash &scriptID) const
Definition: util.cpp:320
UniValue operator()(const PKHash &keyID) const
Definition: util.cpp:314
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:370
std::vector< std::string > GetArgNames() const
Definition: util.cpp:619
RPCHelpMan(std::string name, std::string description, std::vector< RPCArg > args, RPCResults results, RPCExamples examples)
Definition: util.cpp:511
const std::string m_description
Definition: util.h:367
bool IsValidNumArgs(size_t num_args) const
If the supplied number of args is neither too small nor too high.
Definition: util.cpp:608
std::function< UniValue(const RPCHelpMan &, const Config &config, const JSONRPCRequest &)> RPCMethodImpl
Definition: util.h:346
const RPCMethodImpl m_fun
Definition: util.h:366
const std::string m_name
Definition: util.h:363
const RPCResults m_results
Definition: util.h:369
UniValue HandleRequest(const Config &config, const JSONRPCRequest &request) const
Definition: util.cpp:588
const std::vector< RPCArg > m_args
Definition: util.h:368
std::string ToString() const
Definition: util.cpp:627
UniValue GetArgMap() const
Return the named args that need to be converted from string to another JSON type.
Definition: util.cpp:695
const std::string & get_str() const
bool isArray() const
Definition: univalue.h:95
const UniValue & find_value(std::string_view key) const
Definition: univalue.cpp:234
enum VType getType() const
Definition: univalue.h:76
@ VNULL
Definition: univalue.h:27
@ VOBJ
Definition: univalue.h:27
@ VSTR
Definition: univalue.h:27
@ VARR
Definition: univalue.h:27
@ VNUM
Definition: univalue.h:27
@ VBOOL
Definition: univalue.h:27
int64_t get_int64() const
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) 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:32
size_type size() const
Definition: prevector.h:386
256-bit opaque blob.
Definition: uint256.h:129
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:174
bool error(const char *fmt, const Args &...args)
Definition: logging.h:225
Implement std::hash so RCUPtr can be used as a key for maps or sets.
Definition: rcu.h:257
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:16
std::vector< std::string > serviceFlagsToStr(const uint64_t flags)
Convert service flags (a bitmask of NODE_*) to human readable strings.
Definition: protocol.cpp:284
ServiceFlags
nServices flags.
Definition: protocol.h:335
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:58
const char * name
Definition: rest.cpp:47
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:1044
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:176
UniValue GetServicesNames(ServiceFlags services)
Returns, given services flags, a list of humanly readable (known) network services.
Definition: util.cpp:1108
CTxDestination AddAndGetMultisigDestination(const int required, const std::vector< CPubKey > &pubkeys, OutputType type, FillableSigningProvider &keystore, CScript &script_out)
Definition: util.cpp:259
std::string HelpExampleRpcNamed(const std::string &methodname, const RPCArgList &args)
Definition: util.cpp:202
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:359
Amount AmountFromValue(const UniValue &value)
Definition: util.cpp:81
RPCErrorCode RPCErrorFromTransactionError(TransactionError terr)
Definition: util.cpp:340
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:1061
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:193
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:331
CPubKey HexToPubKey(const std::string &hex_in)
Definition: util.cpp:217
CPubKey AddrToPubKey(const CChainParams &chainparams, const FillableSigningProvider &keystore, const std::string &addr_in)
Definition: util.cpp:231
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:1025
std::string HelpExampleCliNamed(const std::string &methodname, const RPCArgList &args)
Definition: util.cpp:181
UniValue DescribeAddress(const CTxDestination &dest)
Definition: util.cpp:327
std::vector< std::pair< std::string, UniValue > > RPCArgList
Definition: util.h:83
OuterType
Serializing JSON objects depends on the outer type.
Definition: util.h:131
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
Definition: script.h:24
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:249
std::string GetTxnOutputType(TxoutType t)
Get the name of a TxoutType as a string.
Definition: standard.cpp:29
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition: standard.cpp:260
TxoutType
Definition: standard.h:38
std::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:85
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:54
std::vector< std::string > SplitString(std::string_view str, char sep)
Definition: string.h:23
Definition: amount.h:19
static const Currency & get()
Definition: amount.cpp:18
uint8_t decimals
Definition: amount.h:149
Definition: util.h:137
Type
Definition: util.h:138
@ 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:184
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:180
const Fallback m_fallback
Definition: util.h:185
std::string ToString(bool oneline) const
Return the type string of the argument.
Definition: util.cpp:987
const std::string m_description
Definition: util.h:186
bool IsOptional() const
Definition: util.cpp:722
const Type m_type
Definition: util.h:181
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:196
std::string GetName() const
Return the name, throws when there are aliases.
Definition: util.cpp:717
std::string GetFirstName() const
Return the first of all aliases.
Definition: util.cpp:713
const std::string m_oneline_description
Should be empty unless it is supposed to override the auto-generated summary line.
Definition: util.h:189
std::string ToStringObj(bool oneline) const
Return the type string of the argument when it is in an object (dict).
Definition: util.cpp:948
std::string ToDescriptionString() const
Return the description string, including the argument type and whether the argument is required.
Definition: util.cpp:730
@ 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:584
const std::string m_examples
Definition: util.h:333
const std::string m_description
Definition: util.h:271
void ToSections(Sections &sections, OuterType outer_type=OuterType::NONE, const int current_indent=0) const
Append the sections of the result.
Definition: util.cpp:797
@ ELISION
Special type to denote elision (...)
@ NUM_TIME
Special numeric to denote unix epoch time.
@ ANY
Special type to disable type checks (for testing only)
@ ARR_FIXED
Special array that has a fixed number of entries.
@ OBJ_DYN
Special dictionary with keys that are not literals.
@ STR_HEX
Special string with only hex chars.
@ STR_AMOUNT
Special string to represent a floating point amount.
@ OBJ_EMPTY
Special type to allow empty OBJ.
const std::vector< RPCResult > m_inner
Only used for arrays or dicts.
Definition: util.h:269
const bool m_optional
Definition: util.h:270
const std::string m_key_name
Only used for dicts.
Definition: util.h:268
bool MatchesType(const UniValue &result) const
Check whether the result JSON type matches.
Definition: util.cpp:912
const Type m_type
Definition: util.h:267
std::string ToDescriptionString() const
Return the description string.
Definition: util.cpp:564
const std::vector< RPCResult > m_results
Definition: util.h:320
A pair of strings that can be aligned (through padding) with other Sections later on.
Definition: util.cpp:373
std::string m_left
Definition: util.cpp:376
Section(const std::string &left, const std::string &right)
Definition: util.cpp:374
const std::string m_right
Definition: util.cpp:377
Keeps track of RPCArgs by transforming them into sections for the purpose of serializing everything t...
Definition: util.cpp:384
void PushSection(const Section &s)
Definition: util.cpp:388
std::vector< Section > m_sections
Definition: util.cpp:385
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:396
size_t m_max_pad
Definition: util.cpp:386
std::string ToString() const
Concatenate all sections with proper padding.
Definition: util.cpp:469
Wrapper for UniValue::VType, which includes typeAny: used to denote don't care type.
Definition: util.h:44
bool typeAny
Definition: util.h:47
UniValue::VType type
Definition: util.h:48
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1202
uint256 uint256S(const char *str)
uint256 from const char *.
Definition: uint256.h:143
const char * uvTypeName(UniValue::VType t)
Definition: univalue.cpp:219