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