Bitcoin Core  0.18.99
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 <key_io.h>
6 #include <outputtype.h>
7 #include <rpc/util.h>
8 #include <script/descriptor.h>
10 #include <tinyformat.h>
11 #include <util/strencodings.h>
12 #include <util/string.h>
13 
14 #include <tuple>
15 
17 
18 void RPCTypeCheck(const UniValue& params,
19  const std::list<UniValueType>& typesExpected,
20  bool fAllowNull)
21 {
22  unsigned int i = 0;
23  for (const UniValueType& t : typesExpected) {
24  if (params.size() <= i)
25  break;
26 
27  const UniValue& v = params[i];
28  if (!(fAllowNull && v.isNull())) {
30  }
31  i++;
32  }
33 }
34 
35 void RPCTypeCheckArgument(const UniValue& value, const UniValueType& typeExpected)
36 {
37  if (!typeExpected.typeAny && value.type() != typeExpected.type) {
38  throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Expected type %s, got %s", uvTypeName(typeExpected.type), uvTypeName(value.type())));
39  }
40 }
41 
42 void RPCTypeCheckObj(const UniValue& o,
43  const std::map<std::string, UniValueType>& typesExpected,
44  bool fAllowNull,
45  bool fStrict)
46 {
47  for (const auto& t : typesExpected) {
48  const UniValue& v = find_value(o, t.first);
49  if (!fAllowNull && v.isNull())
50  throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first));
51 
52  if (!(t.second.typeAny || v.type() == t.second.type || (fAllowNull && v.isNull()))) {
53  std::string err = strprintf("Expected type %s for %s, got %s",
54  uvTypeName(t.second.type), t.first, uvTypeName(v.type()));
55  throw JSONRPCError(RPC_TYPE_ERROR, err);
56  }
57  }
58 
59  if (fStrict)
60  {
61  for (const std::string& k : o.getKeys())
62  {
63  if (typesExpected.count(k) == 0)
64  {
65  std::string err = strprintf("Unexpected key %s", k);
66  throw JSONRPCError(RPC_TYPE_ERROR, err);
67  }
68  }
69  }
70 }
71 
73 {
74  if (!value.isNum() && !value.isStr())
75  throw JSONRPCError(RPC_TYPE_ERROR, "Amount is not a number or string");
76  CAmount amount;
77  if (!ParseFixedPoint(value.getValStr(), 8, &amount))
78  throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
79  if (!MoneyRange(amount))
80  throw JSONRPCError(RPC_TYPE_ERROR, "Amount out of range");
81  return amount;
82 }
83 
84 uint256 ParseHashV(const UniValue& v, std::string strName)
85 {
86  std::string strHex(v.get_str());
87  if (64 != strHex.length())
88  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("%s must be of length %d (not %d, for '%s')", strName, 64, strHex.length(), strHex));
89  if (!IsHex(strHex)) // Note: IsHex("") is false
90  throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
91  return uint256S(strHex);
92 }
93 uint256 ParseHashO(const UniValue& o, std::string strKey)
94 {
95  return ParseHashV(find_value(o, strKey), strKey);
96 }
97 std::vector<unsigned char> ParseHexV(const UniValue& v, std::string strName)
98 {
99  std::string strHex;
100  if (v.isStr())
101  strHex = v.get_str();
102  if (!IsHex(strHex))
103  throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
104  return ParseHex(strHex);
105 }
106 std::vector<unsigned char> ParseHexO(const UniValue& o, std::string strKey)
107 {
108  return ParseHexV(find_value(o, strKey), strKey);
109 }
110 
111 std::string HelpExampleCli(const std::string& methodname, const std::string& args)
112 {
113  return "> bitcoin-cli " + methodname + " " + args + "\n";
114 }
115 
116 std::string HelpExampleRpc(const std::string& methodname, const std::string& args)
117 {
118  return "> curl --user myusername --data-binary '{\"jsonrpc\": \"1.0\", \"id\":\"curltest\", "
119  "\"method\": \"" + methodname + "\", \"params\": [" + args + "] }' -H 'content-type: text/plain;' http://127.0.0.1:8332/\n";
120 }
121 
122 // Converts a hex string to a public key if possible
123 CPubKey HexToPubKey(const std::string& hex_in)
124 {
125  if (!IsHex(hex_in)) {
126  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid public key: " + hex_in);
127  }
128  CPubKey vchPubKey(ParseHex(hex_in));
129  if (!vchPubKey.IsFullyValid()) {
130  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid public key: " + hex_in);
131  }
132  return vchPubKey;
133 }
134 
135 // Retrieves a public key for an address from the given FillableSigningProvider
136 CPubKey AddrToPubKey(FillableSigningProvider* const keystore, const std::string& addr_in)
137 {
138  CTxDestination dest = DecodeDestination(addr_in);
139  if (!IsValidDestination(dest)) {
140  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address: " + addr_in);
141  }
142  CKeyID key = GetKeyForDestination(*keystore, dest);
143  if (key.IsNull()) {
144  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("%s does not refer to a key", addr_in));
145  }
146  CPubKey vchPubKey;
147  if (!keystore->GetPubKey(key, vchPubKey)) {
148  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("no full public key for address %s", addr_in));
149  }
150  if (!vchPubKey.IsFullyValid()) {
151  throw JSONRPCError(RPC_INTERNAL_ERROR, "Wallet contains an invalid public key");
152  }
153  return vchPubKey;
154 }
155 
156 // Creates a multisig address from a given list of public keys, number of signatures required, and the address type
157 CTxDestination AddAndGetMultisigDestination(const int required, const std::vector<CPubKey>& pubkeys, OutputType type, FillableSigningProvider& keystore, CScript& script_out)
158 {
159  // Gather public keys
160  if (required < 1) {
161  throw JSONRPCError(RPC_INVALID_PARAMETER, "a multisignature address must require at least one key to redeem");
162  }
163  if ((int)pubkeys.size() < required) {
164  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("not enough keys supplied (got %u keys, but need at least %d to redeem)", pubkeys.size(), required));
165  }
166  if (pubkeys.size() > 16) {
167  throw JSONRPCError(RPC_INVALID_PARAMETER, "Number of keys involved in the multisignature address creation > 16\nReduce the number");
168  }
169 
170  script_out = GetScriptForMultisig(required, pubkeys);
171 
172  if (script_out.size() > MAX_SCRIPT_ELEMENT_SIZE) {
173  throw JSONRPCError(RPC_INVALID_PARAMETER, (strprintf("redeemScript exceeds size limit: %d > %d", script_out.size(), MAX_SCRIPT_ELEMENT_SIZE)));
174  }
175 
176  // Check if any keys are uncompressed. If so, the type is legacy
177  for (const CPubKey& pk : pubkeys) {
178  if (!pk.IsCompressed()) {
179  type = OutputType::LEGACY;
180  break;
181  }
182  }
183 
184  // Make the address
185  CTxDestination dest = AddAndGetDestinationForScript(keystore, script_out, type);
186 
187  return dest;
188 }
189 
190 class DescribeAddressVisitor : public boost::static_visitor<UniValue>
191 {
192 public:
194 
195  UniValue operator()(const CNoDestination& dest) const
196  {
197  return UniValue(UniValue::VOBJ);
198  }
199 
200  UniValue operator()(const PKHash& keyID) const
201  {
203  obj.pushKV("isscript", false);
204  obj.pushKV("iswitness", false);
205  return obj;
206  }
207 
208  UniValue operator()(const ScriptHash& scriptID) const
209  {
211  obj.pushKV("isscript", true);
212  obj.pushKV("iswitness", false);
213  return obj;
214  }
215 
217  {
219  obj.pushKV("isscript", false);
220  obj.pushKV("iswitness", true);
221  obj.pushKV("witness_version", 0);
222  obj.pushKV("witness_program", HexStr(id.begin(), id.end()));
223  return obj;
224  }
225 
227  {
229  obj.pushKV("isscript", true);
230  obj.pushKV("iswitness", true);
231  obj.pushKV("witness_version", 0);
232  obj.pushKV("witness_program", HexStr(id.begin(), id.end()));
233  return obj;
234  }
235 
237  {
239  obj.pushKV("iswitness", true);
240  obj.pushKV("witness_version", (int)id.version);
241  obj.pushKV("witness_program", HexStr(id.program, id.program + id.length));
242  return obj;
243  }
244 };
245 
247 {
248  return boost::apply_visitor(DescribeAddressVisitor(), dest);
249 }
250 
251 unsigned int ParseConfirmTarget(const UniValue& value, unsigned int max_target)
252 {
253  int target = value.get_int();
254  if (target < 1 || (unsigned int)target > max_target) {
255  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid conf_target, must be between %u - %u", 1, max_target));
256  }
257  return (unsigned int)target;
258 }
259 
261 {
262  switch (terr) {
271  return RPC_INVALID_PARAMETER;
274  default: break;
275  }
276  return RPC_TRANSACTION_ERROR;
277 }
278 
279 UniValue JSONRPCTransactionError(TransactionError terr, const std::string& err_string)
280 {
281  if (err_string.length() > 0) {
282  return JSONRPCError(RPCErrorFromTransactionError(terr), err_string);
283  } else {
285  }
286 }
287 
292 struct Section {
293  Section(const std::string& left, const std::string& right)
294  : m_left{left}, m_right{right} {}
295  const std::string m_left;
296  const std::string m_right;
297 };
298 
303 struct Sections {
304  std::vector<Section> m_sections;
305  size_t m_max_pad{0};
306 
307  void PushSection(const Section& s)
308  {
309  m_max_pad = std::max(m_max_pad, s.m_left.size());
310  m_sections.push_back(s);
311  }
312 
318  enum class OuterType {
319  ARR,
320  OBJ,
321  NAMED_ARG, // Only set on first recursion
322  };
323 
327  void Push(const RPCArg& arg, const size_t current_indent = 5, const OuterType outer_type = OuterType::NAMED_ARG)
328  {
329  const auto indent = std::string(current_indent, ' ');
330  const auto indent_next = std::string(current_indent + 2, ' ');
331  const bool push_name{outer_type == OuterType::OBJ}; // Dictionary keys must have a name
332 
333  switch (arg.m_type) {
335  case RPCArg::Type::STR:
336  case RPCArg::Type::NUM:
338  case RPCArg::Type::RANGE:
339  case RPCArg::Type::BOOL: {
340  if (outer_type == OuterType::NAMED_ARG) return; // Nothing more to do for non-recursive types on first recursion
341  auto left = indent;
342  if (arg.m_type_str.size() != 0 && push_name) {
343  left += "\"" + arg.m_name + "\": " + arg.m_type_str.at(0);
344  } else {
345  left += push_name ? arg.ToStringObj(/* oneline */ false) : arg.ToString(/* oneline */ false);
346  }
347  left += ",";
348  PushSection({left, arg.ToDescriptionString()});
349  break;
350  }
351  case RPCArg::Type::OBJ:
353  const auto right = outer_type == OuterType::NAMED_ARG ? "" : arg.ToDescriptionString();
354  PushSection({indent + (push_name ? "\"" + arg.m_name + "\": " : "") + "{", right});
355  for (const auto& arg_inner : arg.m_inner) {
356  Push(arg_inner, current_indent + 2, OuterType::OBJ);
357  }
358  if (arg.m_type != RPCArg::Type::OBJ) {
359  PushSection({indent_next + "...", ""});
360  }
361  PushSection({indent + "}" + (outer_type != OuterType::NAMED_ARG ? "," : ""), ""});
362  break;
363  }
364  case RPCArg::Type::ARR: {
365  auto left = indent;
366  left += push_name ? "\"" + arg.m_name + "\": " : "";
367  left += "[";
368  const auto right = outer_type == OuterType::NAMED_ARG ? "" : arg.ToDescriptionString();
369  PushSection({left, right});
370  for (const auto& arg_inner : arg.m_inner) {
371  Push(arg_inner, current_indent + 2, OuterType::ARR);
372  }
373  PushSection({indent_next + "...", ""});
374  PushSection({indent + "]" + (outer_type != OuterType::NAMED_ARG ? "," : ""), ""});
375  break;
376  }
377 
378  // no default case, so the compiler can warn about missing cases
379  }
380  }
381 
385  std::string ToString() const
386  {
387  std::string ret;
388  const size_t pad = m_max_pad + 4;
389  for (const auto& s : m_sections) {
390  if (s.m_right.empty()) {
391  ret += s.m_left;
392  ret += "\n";
393  continue;
394  }
395 
396  std::string left = s.m_left;
397  left.resize(pad, ' ');
398  ret += left;
399 
400  // Properly pad after newlines
401  std::string right;
402  size_t begin = 0;
403  size_t new_line_pos = s.m_right.find_first_of('\n');
404  while (true) {
405  right += s.m_right.substr(begin, new_line_pos - begin);
406  if (new_line_pos == std::string::npos) {
407  break; //No new line
408  }
409  right += "\n" + std::string(pad, ' ');
410  begin = s.m_right.find_first_not_of(' ', new_line_pos + 1);
411  if (begin == std::string::npos) {
412  break; // Empty line
413  }
414  new_line_pos = s.m_right.find_first_of('\n', begin + 1);
415  }
416  ret += right;
417  ret += "\n";
418  }
419  return ret;
420  }
421 };
422 
423 RPCHelpMan::RPCHelpMan(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples)
424  : m_name{std::move(name)},
425  m_description{std::move(description)},
426  m_args{std::move(args)},
427  m_results{std::move(results)},
428  m_examples{std::move(examples)}
429 {
430  std::set<std::string> named_args;
431  for (const auto& arg : m_args) {
432  // Should have unique named arguments
433  assert(named_args.insert(arg.m_name).second);
434  }
435 }
436 
438 {
439  std::string result;
440  for (const auto& r : m_results) {
441  if (r.m_cond.empty()) {
442  result += "\nResult:\n";
443  } else {
444  result += "\nResult (" + r.m_cond + "):\n";
445  }
446  result += r.m_result;
447  }
448  return result;
449 }
450 
452 {
453  return m_examples.empty() ? m_examples : "\nExamples:\n" + m_examples;
454 }
455 
456 bool RPCHelpMan::IsValidNumArgs(size_t num_args) const
457 {
458  size_t num_required_args = 0;
459  for (size_t n = m_args.size(); n > 0; --n) {
460  if (!m_args.at(n - 1).IsOptional()) {
461  num_required_args = n;
462  break;
463  }
464  }
465  return num_required_args <= num_args && num_args <= m_args.size();
466 }
467 std::string RPCHelpMan::ToString() const
468 {
469  std::string ret;
470 
471  // Oneline summary
472  ret += m_name;
473  bool was_optional{false};
474  for (const auto& arg : m_args) {
475  const bool optional = arg.IsOptional();
476  ret += " ";
477  if (optional) {
478  if (!was_optional) ret += "( ";
479  was_optional = true;
480  } else {
481  if (was_optional) ret += ") ";
482  was_optional = false;
483  }
484  ret += arg.ToString(/* oneline */ true);
485  }
486  if (was_optional) ret += " )";
487  ret += "\n";
488 
489  // Description
490  ret += m_description;
491 
492  // Arguments
493  Sections sections;
494  for (size_t i{0}; i < m_args.size(); ++i) {
495  const auto& arg = m_args.at(i);
496 
497  if (i == 0) ret += "\nArguments:\n";
498 
499  // Push named argument name and description
500  sections.m_sections.emplace_back(std::to_string(i + 1) + ". " + arg.m_name, arg.ToDescriptionString());
501  sections.m_max_pad = std::max(sections.m_max_pad, sections.m_sections.back().m_left.size());
502 
503  // Recursively push nested args
504  sections.Push(arg);
505  }
506  ret += sections.ToString();
507 
508  // Result
510 
511  // Examples
513 
514  return ret;
515 }
516 
517 bool RPCArg::IsOptional() const
518 {
519  if (m_fallback.which() == 1) {
520  return true;
521  } else {
522  return RPCArg::Optional::NO != boost::get<RPCArg::Optional>(m_fallback);
523  }
524 }
525 
526 std::string RPCArg::ToDescriptionString() const
527 {
528  std::string ret;
529  ret += "(";
530  if (m_type_str.size() != 0) {
531  ret += m_type_str.at(1);
532  } else {
533  switch (m_type) {
534  case Type::STR_HEX:
535  case Type::STR: {
536  ret += "string";
537  break;
538  }
539  case Type::NUM: {
540  ret += "numeric";
541  break;
542  }
543  case Type::AMOUNT: {
544  ret += "numeric or string";
545  break;
546  }
547  case Type::RANGE: {
548  ret += "numeric or array";
549  break;
550  }
551  case Type::BOOL: {
552  ret += "boolean";
553  break;
554  }
555  case Type::OBJ:
556  case Type::OBJ_USER_KEYS: {
557  ret += "json object";
558  break;
559  }
560  case Type::ARR: {
561  ret += "json array";
562  break;
563  }
564 
565  // no default case, so the compiler can warn about missing cases
566  }
567  }
568  if (m_fallback.which() == 1) {
569  ret += ", optional, default=" + boost::get<std::string>(m_fallback);
570  } else {
571  switch (boost::get<RPCArg::Optional>(m_fallback)) {
573  // nothing to do. Element is treated as if not present and has no default value
574  break;
575  }
577  ret += ", optional"; // Default value is "null"
578  break;
579  }
580  case RPCArg::Optional::NO: {
581  ret += ", required";
582  break;
583  }
584 
585  // no default case, so the compiler can warn about missing cases
586  }
587  }
588  ret += ")";
589  ret += m_description.empty() ? "" : " " + m_description;
590  return ret;
591 }
592 
593 std::string RPCArg::ToStringObj(const bool oneline) const
594 {
595  std::string res;
596  res += "\"";
597  res += m_name;
598  if (oneline) {
599  res += "\":";
600  } else {
601  res += "\": ";
602  }
603  switch (m_type) {
604  case Type::STR:
605  return res + "\"str\"";
606  case Type::STR_HEX:
607  return res + "\"hex\"";
608  case Type::NUM:
609  return res + "n";
610  case Type::RANGE:
611  return res + "n or [n,n]";
612  case Type::AMOUNT:
613  return res + "amount";
614  case Type::BOOL:
615  return res + "bool";
616  case Type::ARR:
617  res += "[";
618  for (const auto& i : m_inner) {
619  res += i.ToString(oneline) + ",";
620  }
621  return res + "...]";
622  case Type::OBJ:
623  case Type::OBJ_USER_KEYS:
624  // Currently unused, so avoid writing dead code
625  assert(false);
626 
627  // no default case, so the compiler can warn about missing cases
628  }
629  assert(false);
630 }
631 
632 std::string RPCArg::ToString(const bool oneline) const
633 {
634  if (oneline && !m_oneline_description.empty()) return m_oneline_description;
635 
636  switch (m_type) {
637  case Type::STR_HEX:
638  case Type::STR: {
639  return "\"" + m_name + "\"";
640  }
641  case Type::NUM:
642  case Type::RANGE:
643  case Type::AMOUNT:
644  case Type::BOOL: {
645  return m_name;
646  }
647  case Type::OBJ:
648  case Type::OBJ_USER_KEYS: {
649  const std::string res = Join(m_inner, ",", [&](const RPCArg& i) { return i.ToStringObj(oneline); });
650  if (m_type == Type::OBJ) {
651  return "{" + res + "}";
652  } else {
653  return "{" + res + ",...}";
654  }
655  }
656  case Type::ARR: {
657  std::string res;
658  for (const auto& i : m_inner) {
659  res += i.ToString(oneline) + ",";
660  }
661  return "[" + res + "...]";
662  }
663 
664  // no default case, so the compiler can warn about missing cases
665  }
666  assert(false);
667 }
668 
669 static std::pair<int64_t, int64_t> ParseRange(const UniValue& value)
670 {
671  if (value.isNum()) {
672  return {0, value.get_int64()};
673  }
674  if (value.isArray() && value.size() == 2 && value[0].isNum() && value[1].isNum()) {
675  int64_t low = value[0].get_int64();
676  int64_t high = value[1].get_int64();
677  if (low > high) throw JSONRPCError(RPC_INVALID_PARAMETER, "Range specified as [begin,end] must not have begin after end");
678  return {low, high};
679  }
680  throw JSONRPCError(RPC_INVALID_PARAMETER, "Range must be specified as end or as [begin,end]");
681 }
682 
683 std::pair<int64_t, int64_t> ParseDescriptorRange(const UniValue& value)
684 {
685  int64_t low, high;
686  std::tie(low, high) = ParseRange(value);
687  if (low < 0) {
688  throw JSONRPCError(RPC_INVALID_PARAMETER, "Range should be greater or equal than 0");
689  }
690  if ((high >> 31) != 0) {
691  throw JSONRPCError(RPC_INVALID_PARAMETER, "End of range is too high");
692  }
693  if (high >= low + 1000000) {
694  throw JSONRPCError(RPC_INVALID_PARAMETER, "Range is too large");
695  }
696  return {low, high};
697 }
698 
699 std::vector<CScript> EvalDescriptorStringOrObject(const UniValue& scanobject, FlatSigningProvider& provider)
700 {
701  std::string desc_str;
702  std::pair<int64_t, int64_t> range = {0, 1000};
703  if (scanobject.isStr()) {
704  desc_str = scanobject.get_str();
705  } else if (scanobject.isObject()) {
706  UniValue desc_uni = find_value(scanobject, "desc");
707  if (desc_uni.isNull()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Descriptor needs to be provided in scan object");
708  desc_str = desc_uni.get_str();
709  UniValue range_uni = find_value(scanobject, "range");
710  if (!range_uni.isNull()) {
711  range = ParseDescriptorRange(range_uni);
712  }
713  } else {
714  throw JSONRPCError(RPC_INVALID_PARAMETER, "Scan object needs to be either a string or an object");
715  }
716 
717  std::string error;
718  auto desc = Parse(desc_str, provider, error);
719  if (!desc) {
721  }
722  if (!desc->IsRange()) {
723  range.first = 0;
724  range.second = 0;
725  }
726  std::vector<CScript> ret;
727  for (int i = range.first; i <= range.second; ++i) {
728  std::vector<CScript> scripts;
729  if (!desc->Expand(i, provider, scripts, provider)) {
730  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Cannot derive script without private keys: '%s'", desc_str));
731  }
732  std::move(scripts.begin(), scripts.end(), std::back_inserter(ret));
733  }
734  return ret;
735 }
736 
738 {
739  UniValue servicesNames(UniValue::VARR);
740 
741  if (services & NODE_NETWORK)
742  servicesNames.push_back("NETWORK");
743  if (services & NODE_GETUTXO)
744  servicesNames.push_back("GETUTXO");
745  if (services & NODE_BLOOM)
746  servicesNames.push_back("BLOOM");
747  if (services & NODE_WITNESS)
748  servicesNames.push_back("WITNESS");
749  if (services & NODE_NETWORK_LIMITED)
750  servicesNames.push_back("NETWORK_LIMITED");
751 
752  return servicesNames;
753 }
virtual bool GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const override
Aliases for backward compatibility.
Definition: protocol.h:53
bool isObject() const
Definition: univalue.h:85
CAmount AmountFromValue(const UniValue &value)
Definition: util.cpp:72
void RPCTypeCheck(const UniValue &params, const std::list< UniValueType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.
Definition: util.cpp:18
OuterType
Serializing RPCArgs depends on the outer type.
Definition: util.cpp:318
ServiceFlags
nServices flags
Definition: protocol.h:247
std::string ToDescriptionString() const
Return the description string.
Definition: util.cpp:437
std::string TransactionErrorString(const TransactionError err)
Definition: error.cpp:11
Required arg.
std::vector< unsigned char > ParseHexO(const UniValue &o, std::string strKey)
Definition: util.cpp:106
Keeps track of RPCArgs by transforming them into sections for the purpose of serializing everything t...
Definition: util.cpp:303
const std::string m_name
The name of the arg (can be empty for inner args)
Definition: util.h:127
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1067
bool typeAny
Definition: util.h:39
InitInterfaces * g_rpc_interfaces
Pointers to interfaces that need to be accessible from RPC methods.
Definition: util.cpp:16
std::vector< unsigned char > ParseHexV(const UniValue &v, std::string strName)
Definition: util.cpp:97
RPCErrorCode RPCErrorFromTransactionError(TransactionError terr)
Definition: util.cpp:260
bool MoneyRange(const CAmount &nValue)
Definition: amount.h:26
std::vector< unsigned char > ParseHex(const char *psz)
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition: standard.cpp:325
std::string ToDescriptionString() const
Definition: util.cpp:451
const std::string m_right
Definition: util.cpp:296
void RPCTypeCheckArgument(const UniValue &value, const UniValueType &typeExpected)
Type-check one argument; throws JSONRPCError if wrong type given.
Definition: util.cpp:35
const RPCExamples m_examples
Definition: util.h:265
const std::string & get_str() const
CKeyID GetKeyForDestination(const SigningProvider &store, const CTxDestination &dest)
Return the CKeyID of the key involved in a script (if there is a unique one).
bool isNum() const
Definition: univalue.h:83
bool isStr() const
Definition: univalue.h:82
int64_t get_int64() const
bool IsValidNumArgs(size_t num_args) const
If the supplied number of args is neither too small nor too high.
Definition: util.cpp:456
const std::vector< std::string > & getKeys() const
CPubKey AddrToPubKey(FillableSigningProvider *const keystore, const std::string &addr_in)
Definition: util.cpp:136
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
Definition: script.h:23
UniValue operator()(const WitnessUnknown &id) const
Definition: util.cpp:236
const std::string & getValStr() const
Definition: univalue.h:66
UniValue operator()(const WitnessV0ScriptHash &id) const
Definition: util.cpp:226
std::string ToString() const
Definition: util.cpp:467
bool ParseFixedPoint(const std::string &val, int decimals, int64_t *amount_out)
Parse number as fixed point according to JSON number syntax.
bool IsNull() const
Definition: uint256.h:31
const std::vector< RPCArg > m_inner
Only used for arrays or dicts.
Definition: util.h:129
OutputType
Definition: outputtype.h:16
Invalid, missing or duplicate parameter.
Definition: protocol.h:43
void RPCTypeCheckObj(const UniValue &o, const std::map< std::string, UniValueType > &typesExpected, bool fAllowNull, bool fStrict)
Definition: util.cpp:42
const UniValue & find_value(const UniValue &obj, const std::string &name)
Definition: univalue.cpp:234
size_t m_max_pad
Definition: util.cpp:305
UniValue::VType type
Definition: util.h:40
const std::string m_description
Definition: util.h:262
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
std::unique_ptr< Descriptor > Parse(const std::string &descriptor, FlatSigningProvider &out, std::string &error, bool require_checksum)
Parse a descriptor string.
Special type that is a STR with only hex chars.
const char * uvTypeName(UniValue::VType t)
Definition: univalue.cpp:219
UniValue operator()(const PKHash &keyID) const
Definition: util.cpp:200
std::string Join(const std::vector< T > &list, const std::string &separator, UnaryOp unary_op)
Join a list of items.
Definition: string.h:20
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:51
bool push_back(const UniValue &val)
Definition: univalue.cpp:108
Definition: util.h:97
UniValue operator()(const CNoDestination &dest) const
Definition: util.cpp:195
UniValue operator()(const ScriptHash &scriptID) const
Definition: util.cpp:208
bool IsFullyValid() const
fully validate whether this is a valid public key (more expensive than IsValid()) ...
Definition: pubkey.cpp:206
CTxDestination subtype to encode any future Witness version.
Definition: standard.h:108
const char * name
Definition: rest.cpp:39
unsigned int ParseConfirmTarget(const UniValue &value, unsigned int max_target)
Parse a confirm target option and raise an RPC error if it is invalid.
Definition: util.cpp:251
bool IsOptional() const
Definition: util.cpp:517
uint256 uint256S(const char *str)
Definition: uint256.h:131
An encapsulated public key.
Definition: pubkey.h:30
Fillable signing provider that keeps keys in an address->secret map.
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:116
bool IsHex(const std::string &str)
Unexpected type was passed as parameter.
Definition: protocol.h:40
Special type where the user must set the keys e.g. to define multiple addresses; as opposed to e...
UniValue operator()(const WitnessV0KeyHash &id) const
Definition: util.cpp:216
static std::pair< int64_t, int64_t > ParseRange(const UniValue &value)
Definition: util.cpp:669
bool pushKV(const std::string &key, const UniValue &val)
Definition: univalue.cpp:133
const std::vector< RPCArg > m_args
Definition: util.h:263
int get_int() const
Invalid address or key.
Definition: protocol.h:41
CTxDestination AddAndGetMultisigDestination(const int required, const std::vector< CPubKey > &pubkeys, OutputType type, FillableSigningProvider &keystore, CScript &script_out)
Definition: util.cpp:157
bool isNull() const
Definition: univalue.h:78
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:77
Optional arg that is a named argument and has a default value of null.
const std::vector< std::string > m_type_str
Should be empty unless it is supposed to override the auto-generated type strings. Vector length is either 0 or 2, m_type_str.at(0) will override the type of the value in a key-value pair, m_type_str.at(1) will override the type in the argument description.
Definition: util.h:133
const RPCResults m_results
Definition: util.h:264
Special type that is a NUM or [NUM,NUM].
RPCHelpMan(std::string name, std::string description, std::vector< RPCArg > args, RPCResults results, RPCExamples examples)
Definition: util.cpp:423
256-bit opaque blob.
Definition: uint256.h:121
Optional argument with default value omitted because they are implicitly clear.
CTxDestination DecodeDestination(const std::string &str)
Definition: key_io.cpp:216
enum VType type() const
Definition: univalue.h:178
std::string ToDescriptionString() const
Return the description string, including the argument type and whether the argument is required...
Definition: util.cpp:526
std::vector< Section > m_sections
Definition: util.cpp:304
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:699
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:390
Section(const std::string &left, const std::string &right)
Definition: util.cpp:293
const std::string m_left
Definition: util.cpp:295
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:20
Special type representing a floating point amount (can be either NUM or STR)
std::string HexStr(const T itbegin, const T itend)
Definition: strencodings.h:125
TransactionError
Definition: error.h:22
UniValue GetServicesNames(ServiceFlags services)
Returns, given services flags, a list of humanly readable (known) network services.
Definition: util.cpp:737
std::pair< int64_t, int64_t > ParseDescriptorRange(const UniValue &value)
Parse a JSON range specified as int64, or [int64, int64].
Definition: util.cpp:683
const Type m_type
Definition: util.h:128
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:111
size_type size() const
Definition: prevector.h:277
CScript GetScriptForMultisig(int nRequired, const std::vector< CPubKey > &keys)
Generate a multisig script.
Definition: standard.cpp:302
UniValue JSONRPCTransactionError(TransactionError terr, const std::string &err_string)
Definition: util.cpp:279
No valid connection manager instance found.
Definition: protocol.h:64
size_t size() const
Definition: univalue.h:69
void PushSection(const Section &s)
Definition: util.cpp:307
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded Values (throws error if not hex).
Definition: util.cpp:84
const std::string m_name
Definition: util.h:261
RPCErrorCode
Bitcoin RPC error codes.
Definition: protocol.h:23
void Push(const RPCArg &arg, const size_t current_indent=5, const OuterType outer_type=OuterType::NAMED_ARG)
Recursive helper to translate an RPCArg into sections.
Definition: util.cpp:327
std::string ToString() const
Concatenate all sections with proper padding.
Definition: util.cpp:385
boost::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:139
std::string ToString(bool oneline) const
Return the type string of the argument.
Definition: util.cpp:632
Pointers to interfaces used during init and destroyed on shutdown.
Definition: init.h:19
A pair of strings that can be aligned (through padding) with other Sections later on...
Definition: util.cpp:292
UniValue DescribeAddress(const CTxDestination &dest)
Definition: util.cpp:246
bool error(const char *fmt, const Args &... args)
Definition: system.h:47
bool isArray() const
Definition: univalue.h:84
Wrapper for UniValue::VType, which includes typeAny: Used to denote don&#39;t care type.
Definition: util.h:36
CPubKey HexToPubKey(const std::string &hex_in)
Definition: util.cpp:123
Error parsing or validating structure in raw format.
Definition: protocol.h:45
std::string ToStringObj(bool oneline) const
Return the type string of the argument when it is in an object (dict).
Definition: util.cpp:593
uint256 ParseHashO(const UniValue &o, std::string strKey)
Definition: util.cpp:93