Bitcoin ABC  0.22.12
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(), 8, &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 
268  switch (terr) {
277  return RPC_INVALID_PARAMETER;
280  default:
281  break;
282  }
283  return RPC_TRANSACTION_ERROR;
284 }
285 
287  const std::string &err_string) {
288  if (err_string.length() > 0) {
289  return JSONRPCError(RPCErrorFromTransactionError(terr), err_string);
290  } else {
292  TransactionErrorString(terr).original);
293  }
294 }
295 
300 struct Section {
301  Section(const std::string &left, const std::string &right)
302  : m_left{left}, m_right{right} {}
303  std::string m_left;
304  const std::string m_right;
305 };
306 
311 struct Sections {
312  std::vector<Section> m_sections;
313  size_t m_max_pad{0};
314 
315  void PushSection(const Section &s) {
316  m_max_pad = std::max(m_max_pad, s.m_left.size());
317  m_sections.push_back(s);
318  }
319 
323  void Push(const RPCArg &arg, const size_t current_indent = 5,
324  const OuterType outer_type = OuterType::NONE) {
325  const auto indent = std::string(current_indent, ' ');
326  const auto indent_next = std::string(current_indent + 2, ' ');
327  // Dictionary keys must have a name
328  const bool push_name{outer_type == OuterType::OBJ};
329 
330  switch (arg.m_type) {
332  case RPCArg::Type::STR:
333  case RPCArg::Type::NUM:
335  case RPCArg::Type::RANGE:
336  case RPCArg::Type::BOOL: {
337  // Nothing more to do for non-recursive types on first recursion
338  if (outer_type == OuterType::NONE) {
339  return;
340  }
341  auto left = indent;
342  if (arg.m_type_str.size() != 0 && push_name) {
343  left +=
344  "\"" + arg.GetName() + "\": " + arg.m_type_str.at(0);
345  } else {
346  left += push_name ? arg.ToStringObj(/* oneline */ false)
347  : arg.ToString(/* oneline */ false);
348  }
349  left += ",";
350  PushSection({left, arg.ToDescriptionString()});
351  break;
352  }
353  case RPCArg::Type::OBJ:
355  const auto right = outer_type == OuterType::NONE
356  ? ""
357  : arg.ToDescriptionString();
358  PushSection(
359  {indent + (push_name ? "\"" + arg.GetName() + "\": " : "") +
360  "{",
361  right});
362  for (const auto &arg_inner : arg.m_inner) {
363  Push(arg_inner, current_indent + 2, OuterType::OBJ);
364  }
365  if (arg.m_type != RPCArg::Type::OBJ) {
366  PushSection({indent_next + "...", ""});
367  }
368  PushSection(
369  {indent + "}" + (outer_type != OuterType::NONE ? "," : ""),
370  ""});
371  break;
372  }
373  case RPCArg::Type::ARR: {
374  auto left = indent;
375  left += push_name ? "\"" + arg.GetName() + "\": " : "";
376  left += "[";
377  const auto right = outer_type == OuterType::NONE
378  ? ""
379  : arg.ToDescriptionString();
380  PushSection({left, right});
381  for (const auto &arg_inner : arg.m_inner) {
382  Push(arg_inner, current_indent + 2, OuterType::ARR);
383  }
384  PushSection({indent_next + "...", ""});
385  PushSection(
386  {indent + "]" + (outer_type != OuterType::NONE ? "," : ""),
387  ""});
388  break;
389  }
390 
391  // no default case, so the compiler can warn about missing cases
392  }
393  }
394 
398  std::string ToString() const {
399  std::string ret;
400  const size_t pad = m_max_pad + 4;
401  for (const auto &s : m_sections) {
402  if (s.m_right.empty()) {
403  ret += s.m_left;
404  ret += "\n";
405  continue;
406  }
407 
408  std::string left = s.m_left;
409  left.resize(pad, ' ');
410  ret += left;
411 
412  // Properly pad after newlines
413  std::string right;
414  size_t begin = 0;
415  size_t new_line_pos = s.m_right.find_first_of('\n');
416  while (true) {
417  right += s.m_right.substr(begin, new_line_pos - begin);
418  if (new_line_pos == std::string::npos) {
419  // No new line
420  break;
421  }
422  right += "\n" + std::string(pad, ' ');
423  begin = s.m_right.find_first_not_of(' ', new_line_pos + 1);
424  if (begin == std::string::npos) {
425  break; // Empty line
426  }
427  new_line_pos = s.m_right.find_first_of('\n', begin + 1);
428  }
429  ret += right;
430  ret += "\n";
431  }
432  return ret;
433  }
434 };
435 
436 RPCHelpMan::RPCHelpMan(std::string name_, std::string description,
437  std::vector<RPCArg> args, RPCResults results,
438  RPCExamples examples)
439  : m_name{std::move(name_)}, m_description{std::move(description)},
440  m_args{std::move(args)}, m_results{std::move(results)},
441  m_examples{std::move(examples)} {
442  std::set<std::string> named_args;
443  for (const auto &arg : m_args) {
444  std::vector<std::string> names;
445  boost::split(names, arg.m_names, boost::is_any_of("|"));
446  // Should have unique named arguments
447  for (const std::string &name : names) {
448  CHECK_NONFATAL(named_args.insert(name).second);
449  }
450  }
451 }
452 
453 std::string RPCResults::ToDescriptionString() const {
454  std::string result;
455  for (const auto &r : m_results) {
456  if (r.m_cond.empty()) {
457  result += "\nResult:\n";
458  } else {
459  result += "\nResult (" + r.m_cond + "):\n";
460  }
461  Sections sections;
462  r.ToSections(sections);
463  result += sections.ToString();
464  }
465  return result;
466 }
467 
468 std::string RPCExamples::ToDescriptionString() const {
469  return m_examples.empty() ? m_examples : "\nExamples:\n" + m_examples;
470 }
471 
472 bool RPCHelpMan::IsValidNumArgs(size_t num_args) const {
473  size_t num_required_args = 0;
474  for (size_t n = m_args.size(); n > 0; --n) {
475  if (!m_args.at(n - 1).IsOptional()) {
476  num_required_args = n;
477  break;
478  }
479  }
480  return num_required_args <= num_args && num_args <= m_args.size();
481 }
482 std::string RPCHelpMan::ToString() const {
483  std::string ret;
484 
485  // Oneline summary
486  ret += m_name;
487  bool was_optional{false};
488  for (const auto &arg : m_args) {
489  const bool optional = arg.IsOptional();
490  ret += " ";
491  if (optional) {
492  if (!was_optional) {
493  ret += "( ";
494  }
495  was_optional = true;
496  } else {
497  if (was_optional) {
498  ret += ") ";
499  }
500  was_optional = false;
501  }
502  ret += arg.ToString(/* oneline */ true);
503  }
504  if (was_optional) {
505  ret += " )";
506  }
507  ret += "\n\n";
508 
509  // Description
510  ret += m_description;
511 
512  // Arguments
513  Sections sections;
514  for (size_t i{0}; i < m_args.size(); ++i) {
515  const auto &arg = m_args.at(i);
516 
517  if (i == 0) {
518  ret += "\nArguments:\n";
519  }
520 
521  // Push named argument name and description
522  sections.m_sections.emplace_back(::ToString(i + 1) + ". " +
523  arg.GetFirstName(),
524  arg.ToDescriptionString());
525  sections.m_max_pad = std::max(sections.m_max_pad,
526  sections.m_sections.back().m_left.size());
527 
528  // Recursively push nested args
529  sections.Push(arg);
530  }
531  ret += sections.ToString();
532 
533  // Result
535 
536  // Examples
538 
539  return ret;
540 }
541 
542 std::string RPCArg::GetFirstName() const {
543  return m_names.substr(0, m_names.find("|"));
544 }
545 
546 std::string RPCArg::GetName() const {
547  CHECK_NONFATAL(std::string::npos == m_names.find("|"));
548  return m_names;
549 }
550 
551 bool RPCArg::IsOptional() const {
552  if (m_fallback.which() == 1) {
553  return true;
554  } else {
555  return RPCArg::Optional::NO != boost::get<RPCArg::Optional>(m_fallback);
556  }
557 }
558 
559 std::string RPCArg::ToDescriptionString() const {
560  std::string ret;
561  ret += "(";
562  if (m_type_str.size() != 0) {
563  ret += m_type_str.at(1);
564  } else {
565  switch (m_type) {
566  case Type::STR_HEX:
567  case Type::STR: {
568  ret += "string";
569  break;
570  }
571  case Type::NUM: {
572  ret += "numeric";
573  break;
574  }
575  case Type::AMOUNT: {
576  ret += "numeric or string";
577  break;
578  }
579  case Type::RANGE: {
580  ret += "numeric or array";
581  break;
582  }
583  case Type::BOOL: {
584  ret += "boolean";
585  break;
586  }
587  case Type::OBJ:
588  case Type::OBJ_USER_KEYS: {
589  ret += "json object";
590  break;
591  }
592  case Type::ARR: {
593  ret += "json array";
594  break;
595  }
596 
597  // no default case, so the compiler can warn about missing cases
598  }
599  }
600  if (m_fallback.which() == 1) {
601  ret += ", optional, default=" + boost::get<std::string>(m_fallback);
602  } else {
603  switch (boost::get<RPCArg::Optional>(m_fallback)) {
605  // nothing to do. Element is treated as if not present and has
606  // no default value
607  break;
608  }
610  ret += ", optional"; // Default value is "null"
611  break;
612  }
613  case RPCArg::Optional::NO: {
614  ret += ", required";
615  break;
616  }
617 
618  // no default case, so the compiler can warn about missing cases
619  }
620  }
621  ret += ")";
622  ret += m_description.empty() ? "" : " " + m_description;
623  return ret;
624 }
625 
626 void RPCResult::ToSections(Sections &sections, const OuterType outer_type,
627  const int current_indent) const {
628  // Indentation
629  const std::string indent(current_indent, ' ');
630  const std::string indent_next(current_indent + 2, ' ');
631 
632  // Elements in a JSON structure (dictionary or array) are separated by a
633  // comma
634  const std::string maybe_separator{outer_type != OuterType::NONE ? "," : ""};
635 
636  // The key name if recursed into an dictionary
637  const std::string maybe_key{
638  outer_type == OuterType::OBJ ? "\"" + this->m_key_name + "\" : " : ""};
639 
640  // Format description with type
641  const auto Description = [&](const std::string &type) {
642  return "(" + type + (this->m_optional ? ", optional" : "") + ")" +
643  (this->m_description.empty() ? "" : " " + this->m_description);
644  };
645 
646  switch (m_type) {
647  case Type::ELISION: {
648  // If the inner result is empty, use three dots for elision
649  sections.PushSection(
650  {indent + "..." + maybe_separator, m_description});
651  return;
652  }
653  case Type::NONE: {
654  sections.PushSection(
655  {indent + "null" + maybe_separator, Description("json null")});
656  return;
657  }
658  case Type::STR: {
659  sections.PushSection(
660  {indent + maybe_key + "\"str\"" + maybe_separator,
661  Description("string")});
662  return;
663  }
664  case Type::STR_AMOUNT: {
665  sections.PushSection({indent + maybe_key + "n" + maybe_separator,
666  Description("numeric")});
667  return;
668  }
669  case Type::STR_HEX: {
670  sections.PushSection(
671  {indent + maybe_key + "\"hex\"" + maybe_separator,
672  Description("string")});
673  return;
674  }
675  case Type::NUM: {
676  sections.PushSection({indent + maybe_key + "n" + maybe_separator,
677  Description("numeric")});
678  return;
679  }
680  case Type::NUM_TIME: {
681  sections.PushSection({indent + maybe_key + "xxx" + maybe_separator,
682  Description("numeric")});
683  return;
684  }
685  case Type::BOOL: {
686  sections.PushSection(
687  {indent + maybe_key + "true|false" + maybe_separator,
688  Description("boolean")});
689  return;
690  }
691  case Type::ARR_FIXED:
692  case Type::ARR: {
693  sections.PushSection(
694  {indent + maybe_key + "[", Description("json array")});
695  for (const auto &i : m_inner) {
696  i.ToSections(sections, OuterType::ARR, current_indent + 2);
697  }
698  CHECK_NONFATAL(!m_inner.empty());
699  if (m_type == Type::ARR && m_inner.back().m_type != Type::ELISION) {
700  sections.PushSection({indent_next + "...", ""});
701  } else {
702  // Remove final comma, which would be invalid JSON
703  sections.m_sections.back().m_left.pop_back();
704  }
705  sections.PushSection({indent + "]" + maybe_separator, ""});
706  return;
707  }
708  case Type::OBJ_DYN:
709  case Type::OBJ: {
710  sections.PushSection(
711  {indent + maybe_key + "{", Description("json object")});
712  for (const auto &i : m_inner) {
713  i.ToSections(sections, OuterType::OBJ, current_indent + 2);
714  }
715  CHECK_NONFATAL(!m_inner.empty());
716  if (m_type == Type::OBJ_DYN &&
717  m_inner.back().m_type != Type::ELISION) {
718  // If the dictionary keys are dynamic, use three dots for
719  // continuation
720  sections.PushSection({indent_next + "...", ""});
721  } else {
722  // Remove final comma, which would be invalid JSON
723  sections.m_sections.back().m_left.pop_back();
724  }
725  sections.PushSection({indent + "}" + maybe_separator, ""});
726  return;
727  }
728 
729  // no default case, so the compiler can warn about missing cases
730  }
731 
732  CHECK_NONFATAL(false);
733 }
734 
735 std::string RPCArg::ToStringObj(const bool oneline) const {
736  std::string res;
737  res += "\"";
738  res += GetFirstName();
739  if (oneline) {
740  res += "\":";
741  } else {
742  res += "\": ";
743  }
744  switch (m_type) {
745  case Type::STR:
746  return res + "\"str\"";
747  case Type::STR_HEX:
748  return res + "\"hex\"";
749  case Type::NUM:
750  return res + "n";
751  case Type::RANGE:
752  return res + "n or [n,n]";
753  case Type::AMOUNT:
754  return res + "amount";
755  case Type::BOOL:
756  return res + "bool";
757  case Type::ARR:
758  res += "[";
759  for (const auto &i : m_inner) {
760  res += i.ToString(oneline) + ",";
761  }
762  return res + "...]";
763  case Type::OBJ:
764  case Type::OBJ_USER_KEYS:
765  // Currently unused, so avoid writing dead code
766  CHECK_NONFATAL(false);
767 
768  // no default case, so the compiler can warn about missing cases
769  }
770  CHECK_NONFATAL(false);
771 }
772 
773 std::string RPCArg::ToString(const bool oneline) const {
774  if (oneline && !m_oneline_description.empty()) {
775  return m_oneline_description;
776  }
777 
778  switch (m_type) {
779  case Type::STR_HEX:
780  case Type::STR: {
781  return "\"" + GetFirstName() + "\"";
782  }
783  case Type::NUM:
784  case Type::RANGE:
785  case Type::AMOUNT:
786  case Type::BOOL: {
787  return GetFirstName();
788  }
789  case Type::OBJ:
790  case Type::OBJ_USER_KEYS: {
791  const std::string res = Join(m_inner, ",", [&](const RPCArg &i) {
792  return i.ToStringObj(oneline);
793  });
794  if (m_type == Type::OBJ) {
795  return "{" + res + "}";
796  } else {
797  return "{" + res + ",...}";
798  }
799  }
800  case Type::ARR: {
801  std::string res;
802  for (const auto &i : m_inner) {
803  res += i.ToString(oneline) + ",";
804  }
805  return "[" + res + "...]";
806  }
807 
808  // no default case, so the compiler can warn about missing cases
809  }
810  CHECK_NONFATAL(false);
811 }
812 
813 static std::pair<int64_t, int64_t> ParseRange(const UniValue &value) {
814  if (value.isNum()) {
815  return {0, value.get_int64()};
816  }
817  if (value.isArray() && value.size() == 2 && value[0].isNum() &&
818  value[1].isNum()) {
819  int64_t low = value[0].get_int64();
820  int64_t high = value[1].get_int64();
821  if (low > high) {
822  throw JSONRPCError(
824  "Range specified as [begin,end] must not have begin after end");
825  }
826  return {low, high};
827  }
829  "Range must be specified as end or as [begin,end]");
830 }
831 
832 std::pair<int64_t, int64_t> ParseDescriptorRange(const UniValue &value) {
833  int64_t low, high;
834  std::tie(low, high) = ParseRange(value);
835  if (low < 0) {
837  "Range should be greater or equal than 0");
838  }
839  if ((high >> 31) != 0) {
840  throw JSONRPCError(RPC_INVALID_PARAMETER, "End of range is too high");
841  }
842  if (high >= low + 1000000) {
843  throw JSONRPCError(RPC_INVALID_PARAMETER, "Range is too large");
844  }
845  return {low, high};
846 }
847 
848 std::vector<CScript>
850  FlatSigningProvider &provider) {
851  std::string desc_str;
852  std::pair<int64_t, int64_t> range = {0, 1000};
853  if (scanobject.isStr()) {
854  desc_str = scanobject.get_str();
855  } else if (scanobject.isObject()) {
856  UniValue desc_uni = find_value(scanobject, "desc");
857  if (desc_uni.isNull()) {
858  throw JSONRPCError(
860  "Descriptor needs to be provided in scan object");
861  }
862  desc_str = desc_uni.get_str();
863  UniValue range_uni = find_value(scanobject, "range");
864  if (!range_uni.isNull()) {
865  range = ParseDescriptorRange(range_uni);
866  }
867  } else {
868  throw JSONRPCError(
870  "Scan object needs to be either a string or an object");
871  }
872 
873  std::string error;
874  auto desc = Parse(desc_str, provider, error);
875  if (!desc) {
877  }
878  if (!desc->IsRange()) {
879  range.first = 0;
880  range.second = 0;
881  }
882  std::vector<CScript> ret;
883  for (int i = range.first; i <= range.second; ++i) {
884  std::vector<CScript> scripts;
885  if (!desc->Expand(i, provider, scripts, provider)) {
886  throw JSONRPCError(
888  strprintf("Cannot derive script without private keys: '%s'",
889  desc_str));
890  }
891  std::move(scripts.begin(), scripts.end(), std::back_inserter(ret));
892  }
893  return ret;
894 }
895 
897  UniValue servicesNames(UniValue::VARR);
898 
899  for (const auto &flag : serviceFlagsToStr(services)) {
900  servicesNames.push_back(flag);
901  }
902 
903  return servicesNames;
904 }
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:849
virtual bool GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const override
Aliases for backward compatibility.
Definition: protocol.h:63
bool isObject() const
Definition: univalue.h:96
std::vector< uint8_t > ParseHexO(const UniValue &o, std::string strKey)
Definition: util.cpp:134
ServiceFlags
nServices flags.
Definition: protocol.h:320
std::string ToDescriptionString() const
Return the description string.
Definition: util.cpp:453
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
Required arg.
RPCErrorCode RPCErrorFromTransactionError(TransactionError terr)
Definition: util.cpp:267
Keeps track of RPCArgs by transforming them into sections for the purpose of serializing everything t...
Definition: util.cpp:311
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:34
static std::pair< int64_t, int64_t > ParseRange(const UniValue &value)
Definition: util.cpp:813
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1201
bool typeAny
Definition: util.h:48
UniValue GetServicesNames(ServiceFlags services)
Returns, given services flags, a list of humanly readable (known) network services.
Definition: util.cpp:896
const std::string EXAMPLE_ADDRESS
Example CashAddr address used in multiple RPCExamples.
Definition: util.cpp:22
void ToSections(Sections &sections, OuterType outer_type=OuterType::NONE, const int current_indent=0) const
Append the sections of the result.
Definition: util.cpp:626
#define CHECK_NONFATAL(condition)
Throw a NonFatalCheckError when the condition evaluates to false.
Definition: check.h:34
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition: standard.cpp:269
std::string ToDescriptionString() const
Definition: util.cpp:468
Definition: amount.h:17
const std::string m_right
Definition: util.cpp:304
CPubKey HexToPubKey(const std::string &hex_in)
Definition: util.cpp:153
UniValue DescribeAddress(const CTxDestination &dest)
Definition: util.cpp:263
const RPCExamples m_examples
Definition: util.h:352
const std::string & get_str() const
static constexpr Amount SATOSHI
Definition: amount.h:151
CKeyID GetKeyForDestination(const SigningProvider &store, const CTxDestination &dest)
Return the CKeyID of the key involved in a script (if there is a unique one).
bool isNum() const
Definition: univalue.h:94
bool isStr() const
Definition: univalue.h:93
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
Definition: chainparams.h:47
int64_t get_int64() const
std::vector< uint8_t > ParseHexV(const UniValue &v, std::string strName)
Definition: util.cpp:120
bool IsValidNumArgs(size_t num_args) const
If the supplied number of args is neither too small nor too high.
Definition: util.cpp:472
const std::vector< std::string > & getKeys() const
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
Definition: script.h:23
const std::string & getValStr() const
Definition: univalue.h:77
std::string ToString() const
Definition: util.cpp:482
bool ParseFixedPoint(const std::string &val, int decimals, int64_t *amount_out)
Parse number as fixed point according to JSON number syntax.
bool IsNull() const
Definition: uint256.h:26
const std::vector< RPCArg > m_inner
Only used for arrays or dicts.
Definition: util.h:176
OutputType
Definition: outputtype.h:17
Invalid, missing or duplicate parameter.
Definition: protocol.h:46
const UniValue & find_value(const UniValue &obj, const std::string &name)
Definition: univalue.cpp:234
size_t m_max_pad
Definition: util.cpp:313
UniValue::VType type
Definition: util.h:49
const std::string m_description
Definition: util.h:349
std::pair< int64_t, int64_t > ParseDescriptorRange(const UniValue &value)
Parse a JSON range specified as int64, or [int64, int64].
Definition: util.cpp:832
CTxDestination AddAndGetMultisigDestination(const int required, const std::vector< CPubKey > &pubkeys, OutputType type, FillableSigningProvider &keystore, CScript &script_out)
Definition: util.cpp:195
bool MoneyRange(const Amount nValue)
Definition: amount.h:166
void RPCTypeCheckArgument(const UniValue &value, const UniValueType &typeExpected)
Type-check one argument; throws JSONRPCError if wrong type given.
Definition: util.cpp:42
std::unique_ptr< Descriptor > Parse(const std::string &descriptor, FlatSigningProvider &out, std::string &error, bool require_checksum)
Parse a descriptor string.
Special type that is a STR with only hex chars.
std::string GetName() const
Return the name, throws when there are aliases.
Definition: util.cpp:546
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:143
const char * uvTypeName(UniValue::VType t)
Definition: univalue.cpp:219
UniValue operator()(const PKHash &keyID) const
Definition: util.cpp:250
uint256 ParseHashO(const UniValue &o, std::string strKey)
Definition: util.cpp:116
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:52
bool push_back(const UniValue &val)
Definition: univalue.cpp:108
Definition: util.h:131
UniValue operator()(const CNoDestination &dest) const
Definition: util.cpp:246
UniValue operator()(const ScriptHash &scriptID) const
Definition: util.cpp:256
bool IsFullyValid() const
fully validate whether this is a valid public key (more expensive than IsValid()) ...
Definition: pubkey.cpp:257
std::vector< std::string > serviceFlagsToStr(const uint64_t flags)
Convert service flags (a bitmask of NODE_*) to human readable strings.
Definition: protocol.cpp:292
const char * name
Definition: rest.cpp:43
bool IsOptional() const
Definition: util.cpp:551
uint256 uint256S(const char *str)
uint256 from const char *.
Definition: uint256.h:131
An encapsulated public key.
Definition: pubkey.h:31
Fillable signing provider that keeps keys in an address->secret map.
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...
Unexpected type was passed as parameter.
Definition: protocol.h:40
Special type where the user must set the keys e.g.
Amount AmountFromValue(const UniValue &value)
Definition: util.cpp:81
bool pushKV(const std::string &key, const UniValue &val)
Definition: univalue.cpp:133
std::string GetFirstName() const
Return the first of all aliases.
Definition: util.cpp:542
const std::vector< RPCArg > m_args
Definition: util.h:350
CTxDestination DecodeDestination(const std::string &addr, const CChainParams &params)
Definition: key_io.cpp:177
CPubKey AddrToPubKey(const CChainParams &chainparams, const FillableSigningProvider &keystore, const std::string &addr_in)
Definition: util.cpp:167
Invalid address or key.
Definition: protocol.h:42
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:138
bool isNull() const
Definition: univalue.h:89
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:51
Optional arg that is a named argument and has a default value of null.
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded values (throws error if not hex).
Definition: util.cpp:99
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:188
const RPCResults m_results
Definition: util.h:351
Special type that is a NUM or [NUM,NUM].
OuterType
Serializing JSON objects depends on the outer type.
Definition: util.h:125
RPCHelpMan(std::string name, std::string description, std::vector< RPCArg > args, RPCResults results, RPCExamples examples)
Definition: util.cpp:436
256-bit opaque blob.
Definition: uint256.h:120
Optional argument with default value omitted because they are implicitly clear.
enum VType type() const
Definition: univalue.h:135
std::string ToDescriptionString() const
Return the description string, including the argument type and whether the argument is required...
Definition: util.cpp:559
std::vector< Section > m_sections
Definition: util.cpp:312
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:429
std::string m_left
Definition: util.cpp:303
Section(const std::string &left, const std::string &right)
Definition: util.cpp:301
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:323
std::vector< uint8_t > ParseHex(const char *psz)
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:22
Special type representing a floating point amount (can be either NUM or STR)
TransactionError
Definition: error.h:22
const Type m_type
Definition: util.h:174
size_type size() const
Definition: prevector.h:384
CScript GetScriptForMultisig(int nRequired, const std::vector< CPubKey > &keys)
Generate a multisig script.
Definition: standard.cpp:258
No valid connection manager instance found.
Definition: protocol.h:81
size_t size() const
Definition: univalue.h:80
void PushSection(const Section &s)
Definition: util.cpp:315
const std::string m_name
Definition: util.h:348
UniValue JSONRPCTransactionError(TransactionError terr, const std::string &err_string)
Definition: util.cpp:286
RPCErrorCode
Bitcoin RPC error codes.
Definition: protocol.h:22
std::string ToString() const
Concatenate all sections with proper padding.
Definition: util.cpp:398
bilingual_str TransactionErrorString(const TransactionError error)
Definition: error.cpp:11
std::string ToString(bool oneline) const
Return the type string of the argument.
Definition: util.cpp:773
A pair of strings that can be aligned (through padding) with other Sections later on...
Definition: util.cpp:300
bool error(const char *fmt, const Args &... args)
Definition: system.h:47
bool isArray() const
Definition: univalue.h:95
Wrapper for UniValue::VType, which includes typeAny: used to denote don&#39;t care type.
Definition: util.h:45
boost::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:87
Error parsing or validating structure in raw format.
Definition: protocol.h:50
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
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 ToStringObj(bool oneline) const
Return the type string of the argument when it is in an object (dict).
Definition: util.cpp:735