Bitcoin Core  22.99.0
P2P Digital Currency
util.cpp
Go to the documentation of this file.
1 // Copyright (c) 2017-2021 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #include <consensus/amount.h>
6 #include <key_io.h>
7 #include <outputtype.h>
8 #include <rpc/util.h>
9 #include <script/descriptor.h>
10 #include <script/signingprovider.h>
11 #include <tinyformat.h>
12 #include <util/strencodings.h>
13 #include <util/string.h>
14 #include <util/translation.h>
15 
16 #include <tuple>
17 
18 #include <boost/algorithm/string/classification.hpp>
19 #include <boost/algorithm/string/split.hpp>
20 
21 const std::string UNIX_EPOCH_TIME = "UNIX epoch time";
22 const std::string EXAMPLE_ADDRESS[2] = {"bc1q09vm5lfy0j5reeulh4x5752q25uqqvz34hufdl", "bc1q02ad21edsxd23d32dfgqqsz4vv4nmtfzuklhy3"};
23 
24 void RPCTypeCheck(const UniValue& params,
25  const std::list<UniValueType>& typesExpected,
26  bool fAllowNull)
27 {
28  unsigned int i = 0;
29  for (const UniValueType& t : typesExpected) {
30  if (params.size() <= i)
31  break;
32 
33  const UniValue& v = params[i];
34  if (!(fAllowNull && v.isNull())) {
36  }
37  i++;
38  }
39 }
40 
41 void RPCTypeCheckArgument(const UniValue& value, const UniValueType& typeExpected)
42 {
43  if (!typeExpected.typeAny && value.type() != typeExpected.type) {
44  throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Expected type %s, got %s", uvTypeName(typeExpected.type), uvTypeName(value.type())));
45  }
46 }
47 
48 void RPCTypeCheckObj(const UniValue& o,
49  const std::map<std::string, UniValueType>& typesExpected,
50  bool fAllowNull,
51  bool fStrict)
52 {
53  for (const auto& t : typesExpected) {
54  const UniValue& v = find_value(o, t.first);
55  if (!fAllowNull && v.isNull())
56  throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first));
57 
58  if (!(t.second.typeAny || v.type() == t.second.type || (fAllowNull && v.isNull()))) {
59  std::string err = strprintf("Expected type %s for %s, got %s",
60  uvTypeName(t.second.type), t.first, uvTypeName(v.type()));
61  throw JSONRPCError(RPC_TYPE_ERROR, err);
62  }
63  }
64 
65  if (fStrict)
66  {
67  for (const std::string& k : o.getKeys())
68  {
69  if (typesExpected.count(k) == 0)
70  {
71  std::string err = strprintf("Unexpected key %s", k);
72  throw JSONRPCError(RPC_TYPE_ERROR, err);
73  }
74  }
75  }
76 }
77 
78 CAmount AmountFromValue(const UniValue& value, int decimals)
79 {
80  if (!value.isNum() && !value.isStr())
81  throw JSONRPCError(RPC_TYPE_ERROR, "Amount is not a number or string");
82  CAmount amount;
83  if (!ParseFixedPoint(value.getValStr(), decimals, &amount))
84  throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
85  if (!MoneyRange(amount))
86  throw JSONRPCError(RPC_TYPE_ERROR, "Amount out of range");
87  return amount;
88 }
89 
90 uint256 ParseHashV(const UniValue& v, std::string strName)
91 {
92  std::string strHex(v.get_str());
93  if (64 != strHex.length())
94  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("%s must be of length %d (not %d, for '%s')", strName, 64, strHex.length(), strHex));
95  if (!IsHex(strHex)) // Note: IsHex("") is false
96  throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
97  return uint256S(strHex);
98 }
99 uint256 ParseHashO(const UniValue& o, std::string strKey)
100 {
101  return ParseHashV(find_value(o, strKey), strKey);
102 }
103 std::vector<unsigned char> ParseHexV(const UniValue& v, std::string strName)
104 {
105  std::string strHex;
106  if (v.isStr())
107  strHex = v.get_str();
108  if (!IsHex(strHex))
109  throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
110  return ParseHex(strHex);
111 }
112 std::vector<unsigned char> ParseHexO(const UniValue& o, std::string strKey)
113 {
114  return ParseHexV(find_value(o, strKey), strKey);
115 }
116 
117 namespace {
118 
124 std::string ShellQuote(const std::string& s)
125 {
126  std::string result;
127  result.reserve(s.size() * 2);
128  for (const char ch: s) {
129  if (ch == '\'') {
130  result += "'\''";
131  } else {
132  result += ch;
133  }
134  }
135  return "'" + result + "'";
136 }
137 
143 std::string ShellQuoteIfNeeded(const std::string& s)
144 {
145  for (const char ch: s) {
146  if (ch == ' ' || ch == '\'' || ch == '"') {
147  return ShellQuote(s);
148  }
149  }
150 
151  return s;
152 }
153 
154 }
155 
156 std::string HelpExampleCli(const std::string& methodname, const std::string& args)
157 {
158  return "> bitcoin-cli " + methodname + " " + args + "\n";
159 }
160 
161 std::string HelpExampleCliNamed(const std::string& methodname, const RPCArgList& args)
162 {
163  std::string result = "> bitcoin-cli -named " + methodname;
164  for (const auto& argpair: args) {
165  const auto& value = argpair.second.isStr()
166  ? argpair.second.get_str()
167  : argpair.second.write();
168  result += " " + argpair.first + "=" + ShellQuoteIfNeeded(value);
169  }
170  result += "\n";
171  return result;
172 }
173 
174 std::string HelpExampleRpc(const std::string& methodname, const std::string& args)
175 {
176  return "> curl --user myusername --data-binary '{\"jsonrpc\": \"1.0\", \"id\": \"curltest\", "
177  "\"method\": \"" + methodname + "\", \"params\": [" + args + "]}' -H 'content-type: text/plain;' http://127.0.0.1:8332/\n";
178 }
179 
180 std::string HelpExampleRpcNamed(const std::string& methodname, const RPCArgList& args)
181 {
182  UniValue params(UniValue::VOBJ);
183  for (const auto& param: args) {
184  params.pushKV(param.first, param.second);
185  }
186 
187  return "> curl --user myusername --data-binary '{\"jsonrpc\": \"1.0\", \"id\": \"curltest\", "
188  "\"method\": \"" + methodname + "\", \"params\": " + params.write() + "}' -H 'content-type: text/plain;' http://127.0.0.1:8332/\n";
189 }
190 
191 // Converts a hex string to a public key if possible
192 CPubKey HexToPubKey(const std::string& hex_in)
193 {
194  if (!IsHex(hex_in)) {
195  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid public key: " + hex_in);
196  }
197  CPubKey vchPubKey(ParseHex(hex_in));
198  if (!vchPubKey.IsFullyValid()) {
199  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid public key: " + hex_in);
200  }
201  return vchPubKey;
202 }
203 
204 // Retrieves a public key for an address from the given FillableSigningProvider
205 CPubKey AddrToPubKey(const FillableSigningProvider& keystore, const std::string& addr_in)
206 {
207  CTxDestination dest = DecodeDestination(addr_in);
208  if (!IsValidDestination(dest)) {
209  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address: " + addr_in);
210  }
211  CKeyID key = GetKeyForDestination(keystore, dest);
212  if (key.IsNull()) {
213  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("'%s' does not refer to a key", addr_in));
214  }
215  CPubKey vchPubKey;
216  if (!keystore.GetPubKey(key, vchPubKey)) {
217  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("no full public key for address %s", addr_in));
218  }
219  if (!vchPubKey.IsFullyValid()) {
220  throw JSONRPCError(RPC_INTERNAL_ERROR, "Wallet contains an invalid public key");
221  }
222  return vchPubKey;
223 }
224 
225 // Creates a multisig address from a given list of public keys, number of signatures required, and the address type
226 CTxDestination AddAndGetMultisigDestination(const int required, const std::vector<CPubKey>& pubkeys, OutputType type, FillableSigningProvider& keystore, CScript& script_out)
227 {
228  // Gather public keys
229  if (required < 1) {
230  throw JSONRPCError(RPC_INVALID_PARAMETER, "a multisignature address must require at least one key to redeem");
231  }
232  if ((int)pubkeys.size() < required) {
233  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("not enough keys supplied (got %u keys, but need at least %d to redeem)", pubkeys.size(), required));
234  }
235  if (pubkeys.size() > MAX_PUBKEYS_PER_MULTISIG) {
236  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Number of keys involved in the multisignature address creation > %d\nReduce the number", MAX_PUBKEYS_PER_MULTISIG));
237  }
238 
239  script_out = GetScriptForMultisig(required, pubkeys);
240 
241  // Check if any keys are uncompressed. If so, the type is legacy
242  for (const CPubKey& pk : pubkeys) {
243  if (!pk.IsCompressed()) {
244  type = OutputType::LEGACY;
245  break;
246  }
247  }
248 
249  if (type == OutputType::LEGACY && script_out.size() > MAX_SCRIPT_ELEMENT_SIZE) {
250  throw JSONRPCError(RPC_INVALID_PARAMETER, (strprintf("redeemScript exceeds size limit: %d > %d", script_out.size(), MAX_SCRIPT_ELEMENT_SIZE)));
251  }
252 
253  // Make the address
254  CTxDestination dest = AddAndGetDestinationForScript(keystore, script_out, type);
255 
256  return dest;
257 }
258 
260 {
261 public:
263 
264  UniValue operator()(const CNoDestination& dest) const
265  {
266  return UniValue(UniValue::VOBJ);
267  }
268 
269  UniValue operator()(const PKHash& keyID) const
270  {
272  obj.pushKV("isscript", false);
273  obj.pushKV("iswitness", false);
274  return obj;
275  }
276 
277  UniValue operator()(const ScriptHash& scriptID) const
278  {
280  obj.pushKV("isscript", true);
281  obj.pushKV("iswitness", false);
282  return obj;
283  }
284 
286  {
288  obj.pushKV("isscript", false);
289  obj.pushKV("iswitness", true);
290  obj.pushKV("witness_version", 0);
291  obj.pushKV("witness_program", HexStr(id));
292  return obj;
293  }
294 
296  {
298  obj.pushKV("isscript", true);
299  obj.pushKV("iswitness", true);
300  obj.pushKV("witness_version", 0);
301  obj.pushKV("witness_program", HexStr(id));
302  return obj;
303  }
304 
306  {
308  obj.pushKV("isscript", true);
309  obj.pushKV("iswitness", true);
310  obj.pushKV("witness_version", 1);
311  obj.pushKV("witness_program", HexStr(tap));
312  return obj;
313  }
314 
316  {
318  obj.pushKV("iswitness", true);
319  obj.pushKV("witness_version", (int)id.version);
320  obj.pushKV("witness_program", HexStr({id.program, id.length}));
321  return obj;
322  }
323 };
324 
326 {
327  return std::visit(DescribeAddressVisitor(), dest);
328 }
329 
330 unsigned int ParseConfirmTarget(const UniValue& value, unsigned int max_target)
331 {
332  const int target{value.get_int()};
333  const unsigned int unsigned_target{static_cast<unsigned int>(target)};
334  if (target < 1 || unsigned_target > max_target) {
335  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid conf_target, must be between %u and %u", 1, max_target));
336  }
337  return unsigned_target;
338 }
339 
341 {
342  switch (terr) {
351  return RPC_INVALID_PARAMETER;
354  default: break;
355  }
356  return RPC_TRANSACTION_ERROR;
357 }
358 
359 UniValue JSONRPCTransactionError(TransactionError terr, const std::string& err_string)
360 {
361  if (err_string.length() > 0) {
362  return JSONRPCError(RPCErrorFromTransactionError(terr), err_string);
363  } else {
365  }
366 }
367 
372 struct Section {
373  Section(const std::string& left, const std::string& right)
374  : m_left{left}, m_right{right} {}
375  std::string m_left;
376  const std::string m_right;
377 };
378 
383 struct Sections {
384  std::vector<Section> m_sections;
385  size_t m_max_pad{0};
386 
387  void PushSection(const Section& s)
388  {
389  m_max_pad = std::max(m_max_pad, s.m_left.size());
390  m_sections.push_back(s);
391  }
392 
396  void Push(const RPCArg& arg, const size_t current_indent = 5, const OuterType outer_type = OuterType::NONE)
397  {
398  const auto indent = std::string(current_indent, ' ');
399  const auto indent_next = std::string(current_indent + 2, ' ');
400  const bool push_name{outer_type == OuterType::OBJ}; // Dictionary keys must have a name
401 
402  switch (arg.m_type) {
404  case RPCArg::Type::STR:
405  case RPCArg::Type::NUM:
407  case RPCArg::Type::RANGE:
408  case RPCArg::Type::BOOL: {
409  if (outer_type == OuterType::NONE) return; // Nothing more to do for non-recursive types on first recursion
410  auto left = indent;
411  if (arg.m_type_str.size() != 0 && push_name) {
412  left += "\"" + arg.GetName() + "\": " + arg.m_type_str.at(0);
413  } else {
414  left += push_name ? arg.ToStringObj(/* oneline */ false) : arg.ToString(/* oneline */ false);
415  }
416  left += ",";
417  PushSection({left, arg.ToDescriptionString()});
418  break;
419  }
420  case RPCArg::Type::OBJ:
422  const auto right = outer_type == OuterType::NONE ? "" : arg.ToDescriptionString();
423  PushSection({indent + (push_name ? "\"" + arg.GetName() + "\": " : "") + "{", right});
424  for (const auto& arg_inner : arg.m_inner) {
425  Push(arg_inner, current_indent + 2, OuterType::OBJ);
426  }
427  if (arg.m_type != RPCArg::Type::OBJ) {
428  PushSection({indent_next + "...", ""});
429  }
430  PushSection({indent + "}" + (outer_type != OuterType::NONE ? "," : ""), ""});
431  break;
432  }
433  case RPCArg::Type::ARR: {
434  auto left = indent;
435  left += push_name ? "\"" + arg.GetName() + "\": " : "";
436  left += "[";
437  const auto right = outer_type == OuterType::NONE ? "" : arg.ToDescriptionString();
438  PushSection({left, right});
439  for (const auto& arg_inner : arg.m_inner) {
440  Push(arg_inner, current_indent + 2, OuterType::ARR);
441  }
442  PushSection({indent_next + "...", ""});
443  PushSection({indent + "]" + (outer_type != OuterType::NONE ? "," : ""), ""});
444  break;
445  }
446  } // no default case, so the compiler can warn about missing cases
447  }
448 
452  std::string ToString() const
453  {
454  std::string ret;
455  const size_t pad = m_max_pad + 4;
456  for (const auto& s : m_sections) {
457  // The left part of a section is assumed to be a single line, usually it is the name of the JSON struct or a
458  // brace like {, }, [, or ]
459  CHECK_NONFATAL(s.m_left.find('\n') == std::string::npos);
460  if (s.m_right.empty()) {
461  ret += s.m_left;
462  ret += "\n";
463  continue;
464  }
465 
466  std::string left = s.m_left;
467  left.resize(pad, ' ');
468  ret += left;
469 
470  // Properly pad after newlines
471  std::string right;
472  size_t begin = 0;
473  size_t new_line_pos = s.m_right.find_first_of('\n');
474  while (true) {
475  right += s.m_right.substr(begin, new_line_pos - begin);
476  if (new_line_pos == std::string::npos) {
477  break; //No new line
478  }
479  right += "\n" + std::string(pad, ' ');
480  begin = s.m_right.find_first_not_of(' ', new_line_pos + 1);
481  if (begin == std::string::npos) {
482  break; // Empty line
483  }
484  new_line_pos = s.m_right.find_first_of('\n', begin + 1);
485  }
486  ret += right;
487  ret += "\n";
488  }
489  return ret;
490  }
491 };
492 
493 RPCHelpMan::RPCHelpMan(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples)
494  : RPCHelpMan{std::move(name), std::move(description), std::move(args), std::move(results), std::move(examples), nullptr} {}
495 
496 RPCHelpMan::RPCHelpMan(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples, RPCMethodImpl fun)
497  : m_name{std::move(name)},
498  m_fun{std::move(fun)},
499  m_description{std::move(description)},
500  m_args{std::move(args)},
501  m_results{std::move(results)},
502  m_examples{std::move(examples)}
503 {
504  std::set<std::string> named_args;
505  for (const auto& arg : m_args) {
506  std::vector<std::string> names;
507  boost::split(names, arg.m_names, boost::is_any_of("|"));
508  // Should have unique named arguments
509  for (const std::string& name : names) {
510  CHECK_NONFATAL(named_args.insert(name).second);
511  }
512  // Default value type should match argument type only when defined
513  if (arg.m_fallback.index() == 2) {
514  const RPCArg::Type type = arg.m_type;
515  switch (std::get<RPCArg::Default>(arg.m_fallback).getType()) {
516  case UniValue::VOBJ:
518  break;
519  case UniValue::VARR:
521  break;
522  case UniValue::VSTR:
524  break;
525  case UniValue::VNUM:
527  break;
528  case UniValue::VBOOL:
530  break;
531  case UniValue::VNULL:
532  // Null values are accepted in all arguments
533  break;
534  default:
535  CHECK_NONFATAL(false);
536  break;
537  }
538  }
539  }
540 }
541 
543 {
544  std::string result;
545  for (const auto& r : m_results) {
546  if (r.m_type == RPCResult::Type::ANY) continue; // for testing only
547  if (r.m_cond.empty()) {
548  result += "\nResult:\n";
549  } else {
550  result += "\nResult (" + r.m_cond + "):\n";
551  }
552  Sections sections;
553  r.ToSections(sections);
554  result += sections.ToString();
555  }
556  return result;
557 }
558 
560 {
561  return m_examples.empty() ? m_examples : "\nExamples:\n" + m_examples;
562 }
563 
565 {
566  if (request.mode == JSONRPCRequest::GET_ARGS) {
567  return GetArgMap();
568  }
569  /*
570  * Check if the given request is valid according to this command or if
571  * the user is asking for help information, and throw help when appropriate.
572  */
573  if (request.mode == JSONRPCRequest::GET_HELP || !IsValidNumArgs(request.params.size())) {
574  throw std::runtime_error(ToString());
575  }
576  const UniValue ret = m_fun(*this, request);
577  CHECK_NONFATAL(std::any_of(m_results.m_results.begin(), m_results.m_results.end(), [ret](const RPCResult& res) { return res.MatchesType(ret); }));
578  return ret;
579 }
580 
581 bool RPCHelpMan::IsValidNumArgs(size_t num_args) const
582 {
583  size_t num_required_args = 0;
584  for (size_t n = m_args.size(); n > 0; --n) {
585  if (!m_args.at(n - 1).IsOptional()) {
586  num_required_args = n;
587  break;
588  }
589  }
590  return num_required_args <= num_args && num_args <= m_args.size();
591 }
592 
593 std::vector<std::string> RPCHelpMan::GetArgNames() const
594 {
595  std::vector<std::string> ret;
596  for (const auto& arg : m_args) {
597  ret.emplace_back(arg.m_names);
598  }
599  return ret;
600 }
601 
602 std::string RPCHelpMan::ToString() const
603 {
604  std::string ret;
605 
606  // Oneline summary
607  ret += m_name;
608  bool was_optional{false};
609  for (const auto& arg : m_args) {
610  if (arg.m_hidden) break; // Any arg that follows is also hidden
611  const bool optional = arg.IsOptional();
612  ret += " ";
613  if (optional) {
614  if (!was_optional) ret += "( ";
615  was_optional = true;
616  } else {
617  if (was_optional) ret += ") ";
618  was_optional = false;
619  }
620  ret += arg.ToString(/* oneline */ true);
621  }
622  if (was_optional) ret += " )";
623 
624  // Description
625  ret += "\n\n" + TrimString(m_description) + "\n";
626 
627  // Arguments
628  Sections sections;
629  for (size_t i{0}; i < m_args.size(); ++i) {
630  const auto& arg = m_args.at(i);
631  if (arg.m_hidden) break; // Any arg that follows is also hidden
632 
633  if (i == 0) ret += "\nArguments:\n";
634 
635  // Push named argument name and description
636  sections.m_sections.emplace_back(::ToString(i + 1) + ". " + arg.GetFirstName(), arg.ToDescriptionString());
637  sections.m_max_pad = std::max(sections.m_max_pad, sections.m_sections.back().m_left.size());
638 
639  // Recursively push nested args
640  sections.Push(arg);
641  }
642  ret += sections.ToString();
643 
644  // Result
646 
647  // Examples
649 
650  return ret;
651 }
652 
654 {
656  for (int i{0}; i < int(m_args.size()); ++i) {
657  const auto& arg = m_args.at(i);
658  std::vector<std::string> arg_names;
659  boost::split(arg_names, arg.m_names, boost::is_any_of("|"));
660  for (const auto& arg_name : arg_names) {
662  map.push_back(m_name);
663  map.push_back(i);
664  map.push_back(arg_name);
665  map.push_back(arg.m_type == RPCArg::Type::STR ||
666  arg.m_type == RPCArg::Type::STR_HEX);
667  arr.push_back(map);
668  }
669  }
670  return arr;
671 }
672 
673 std::string RPCArg::GetFirstName() const
674 {
675  return m_names.substr(0, m_names.find("|"));
676 }
677 
678 std::string RPCArg::GetName() const
679 {
680  CHECK_NONFATAL(std::string::npos == m_names.find("|"));
681  return m_names;
682 }
683 
684 bool RPCArg::IsOptional() const
685 {
686  if (m_fallback.index() != 0) {
687  return true;
688  } else {
689  return RPCArg::Optional::NO != std::get<RPCArg::Optional>(m_fallback);
690  }
691 }
692 
693 std::string RPCArg::ToDescriptionString() const
694 {
695  std::string ret;
696  ret += "(";
697  if (m_type_str.size() != 0) {
698  ret += m_type_str.at(1);
699  } else {
700  switch (m_type) {
701  case Type::STR_HEX:
702  case Type::STR: {
703  ret += "string";
704  break;
705  }
706  case Type::NUM: {
707  ret += "numeric";
708  break;
709  }
710  case Type::AMOUNT: {
711  ret += "numeric or string";
712  break;
713  }
714  case Type::RANGE: {
715  ret += "numeric or array";
716  break;
717  }
718  case Type::BOOL: {
719  ret += "boolean";
720  break;
721  }
722  case Type::OBJ:
723  case Type::OBJ_USER_KEYS: {
724  ret += "json object";
725  break;
726  }
727  case Type::ARR: {
728  ret += "json array";
729  break;
730  }
731  } // no default case, so the compiler can warn about missing cases
732  }
733  if (m_fallback.index() == 1) {
734  ret += ", optional, default=" + std::get<RPCArg::DefaultHint>(m_fallback);
735  } else if (m_fallback.index() == 2) {
736  ret += ", optional, default=" + std::get<RPCArg::Default>(m_fallback).write();
737  } else {
738  switch (std::get<RPCArg::Optional>(m_fallback)) {
740  // nothing to do. Element is treated as if not present and has no default value
741  break;
742  }
744  ret += ", optional"; // Default value is "null"
745  break;
746  }
747  case RPCArg::Optional::NO: {
748  ret += ", required";
749  break;
750  }
751  } // no default case, so the compiler can warn about missing cases
752  }
753  ret += ")";
754  ret += m_description.empty() ? "" : " " + m_description;
755  return ret;
756 }
757 
758 void RPCResult::ToSections(Sections& sections, const OuterType outer_type, const int current_indent) const
759 {
760  // Indentation
761  const std::string indent(current_indent, ' ');
762  const std::string indent_next(current_indent + 2, ' ');
763 
764  // Elements in a JSON structure (dictionary or array) are separated by a comma
765  const std::string maybe_separator{outer_type != OuterType::NONE ? "," : ""};
766 
767  // The key name if recursed into an dictionary
768  const std::string maybe_key{
769  outer_type == OuterType::OBJ ?
770  "\"" + this->m_key_name + "\" : " :
771  ""};
772 
773  // Format description with type
774  const auto Description = [&](const std::string& type) {
775  return "(" + type + (this->m_optional ? ", optional" : "") + ")" +
776  (this->m_description.empty() ? "" : " " + this->m_description);
777  };
778 
779  switch (m_type) {
780  case Type::ELISION: {
781  // If the inner result is empty, use three dots for elision
782  sections.PushSection({indent + "..." + maybe_separator, m_description});
783  return;
784  }
785  case Type::ANY: {
786  CHECK_NONFATAL(false); // Only for testing
787  }
788  case Type::NONE: {
789  sections.PushSection({indent + "null" + maybe_separator, Description("json null")});
790  return;
791  }
792  case Type::STR: {
793  sections.PushSection({indent + maybe_key + "\"str\"" + maybe_separator, Description("string")});
794  return;
795  }
796  case Type::STR_AMOUNT: {
797  sections.PushSection({indent + maybe_key + "n" + maybe_separator, Description("numeric")});
798  return;
799  }
800  case Type::STR_HEX: {
801  sections.PushSection({indent + maybe_key + "\"hex\"" + maybe_separator, Description("string")});
802  return;
803  }
804  case Type::NUM: {
805  sections.PushSection({indent + maybe_key + "n" + maybe_separator, Description("numeric")});
806  return;
807  }
808  case Type::NUM_TIME: {
809  sections.PushSection({indent + maybe_key + "xxx" + maybe_separator, Description("numeric")});
810  return;
811  }
812  case Type::BOOL: {
813  sections.PushSection({indent + maybe_key + "true|false" + maybe_separator, Description("boolean")});
814  return;
815  }
816  case Type::ARR_FIXED:
817  case Type::ARR: {
818  sections.PushSection({indent + maybe_key + "[", Description("json array")});
819  for (const auto& i : m_inner) {
820  i.ToSections(sections, OuterType::ARR, current_indent + 2);
821  }
822  CHECK_NONFATAL(!m_inner.empty());
823  if (m_type == Type::ARR && m_inner.back().m_type != Type::ELISION) {
824  sections.PushSection({indent_next + "...", ""});
825  } else {
826  // Remove final comma, which would be invalid JSON
827  sections.m_sections.back().m_left.pop_back();
828  }
829  sections.PushSection({indent + "]" + maybe_separator, ""});
830  return;
831  }
832  case Type::OBJ_DYN:
833  case Type::OBJ: {
834  if (m_inner.empty()) {
835  sections.PushSection({indent + maybe_key + "{}", Description("empty JSON object")});
836  return;
837  }
838  sections.PushSection({indent + maybe_key + "{", Description("json object")});
839  for (const auto& i : m_inner) {
840  i.ToSections(sections, OuterType::OBJ, current_indent + 2);
841  }
842  if (m_type == Type::OBJ_DYN && m_inner.back().m_type != Type::ELISION) {
843  // If the dictionary keys are dynamic, use three dots for continuation
844  sections.PushSection({indent_next + "...", ""});
845  } else {
846  // Remove final comma, which would be invalid JSON
847  sections.m_sections.back().m_left.pop_back();
848  }
849  sections.PushSection({indent + "}" + maybe_separator, ""});
850  return;
851  }
852  } // no default case, so the compiler can warn about missing cases
853  CHECK_NONFATAL(false);
854 }
855 
856 bool RPCResult::MatchesType(const UniValue& result) const
857 {
858  switch (m_type) {
859  case Type::ELISION: {
860  return false;
861  }
862  case Type::ANY: {
863  return true;
864  }
865  case Type::NONE: {
866  return UniValue::VNULL == result.getType();
867  }
868  case Type::STR:
869  case Type::STR_HEX: {
870  return UniValue::VSTR == result.getType();
871  }
872  case Type::NUM:
873  case Type::STR_AMOUNT:
874  case Type::NUM_TIME: {
875  return UniValue::VNUM == result.getType();
876  }
877  case Type::BOOL: {
878  return UniValue::VBOOL == result.getType();
879  }
880  case Type::ARR_FIXED:
881  case Type::ARR: {
882  return UniValue::VARR == result.getType();
883  }
884  case Type::OBJ_DYN:
885  case Type::OBJ: {
886  return UniValue::VOBJ == result.getType();
887  }
888  } // no default case, so the compiler can warn about missing cases
889  CHECK_NONFATAL(false);
890 }
891 
893 {
894  if (m_type == Type::OBJ) {
895  // May or may not be empty
896  return;
897  }
898  // Everything else must either be empty or not
899  const bool inner_needed{m_type == Type::ARR || m_type == Type::ARR_FIXED || m_type == Type::OBJ_DYN};
900  CHECK_NONFATAL(inner_needed != m_inner.empty());
901 }
902 
903 std::string RPCArg::ToStringObj(const bool oneline) const
904 {
905  std::string res;
906  res += "\"";
907  res += GetFirstName();
908  if (oneline) {
909  res += "\":";
910  } else {
911  res += "\": ";
912  }
913  switch (m_type) {
914  case Type::STR:
915  return res + "\"str\"";
916  case Type::STR_HEX:
917  return res + "\"hex\"";
918  case Type::NUM:
919  return res + "n";
920  case Type::RANGE:
921  return res + "n or [n,n]";
922  case Type::AMOUNT:
923  return res + "amount";
924  case Type::BOOL:
925  return res + "bool";
926  case Type::ARR:
927  res += "[";
928  for (const auto& i : m_inner) {
929  res += i.ToString(oneline) + ",";
930  }
931  return res + "...]";
932  case Type::OBJ:
933  case Type::OBJ_USER_KEYS:
934  // Currently unused, so avoid writing dead code
935  CHECK_NONFATAL(false);
936  } // no default case, so the compiler can warn about missing cases
937  CHECK_NONFATAL(false);
938 }
939 
940 std::string RPCArg::ToString(const bool oneline) const
941 {
942  if (oneline && !m_oneline_description.empty()) return m_oneline_description;
943 
944  switch (m_type) {
945  case Type::STR_HEX:
946  case Type::STR: {
947  return "\"" + GetFirstName() + "\"";
948  }
949  case Type::NUM:
950  case Type::RANGE:
951  case Type::AMOUNT:
952  case Type::BOOL: {
953  return GetFirstName();
954  }
955  case Type::OBJ:
956  case Type::OBJ_USER_KEYS: {
957  const std::string res = Join(m_inner, ",", [&](const RPCArg& i) { return i.ToStringObj(oneline); });
958  if (m_type == Type::OBJ) {
959  return "{" + res + "}";
960  } else {
961  return "{" + res + ",...}";
962  }
963  }
964  case Type::ARR: {
965  std::string res;
966  for (const auto& i : m_inner) {
967  res += i.ToString(oneline) + ",";
968  }
969  return "[" + res + "...]";
970  }
971  } // no default case, so the compiler can warn about missing cases
972  CHECK_NONFATAL(false);
973 }
974 
975 static std::pair<int64_t, int64_t> ParseRange(const UniValue& value)
976 {
977  if (value.isNum()) {
978  return {0, value.get_int64()};
979  }
980  if (value.isArray() && value.size() == 2 && value[0].isNum() && value[1].isNum()) {
981  int64_t low = value[0].get_int64();
982  int64_t high = value[1].get_int64();
983  if (low > high) throw JSONRPCError(RPC_INVALID_PARAMETER, "Range specified as [begin,end] must not have begin after end");
984  return {low, high};
985  }
986  throw JSONRPCError(RPC_INVALID_PARAMETER, "Range must be specified as end or as [begin,end]");
987 }
988 
989 std::pair<int64_t, int64_t> ParseDescriptorRange(const UniValue& value)
990 {
991  int64_t low, high;
992  std::tie(low, high) = ParseRange(value);
993  if (low < 0) {
994  throw JSONRPCError(RPC_INVALID_PARAMETER, "Range should be greater or equal than 0");
995  }
996  if ((high >> 31) != 0) {
997  throw JSONRPCError(RPC_INVALID_PARAMETER, "End of range is too high");
998  }
999  if (high >= low + 1000000) {
1000  throw JSONRPCError(RPC_INVALID_PARAMETER, "Range is too large");
1001  }
1002  return {low, high};
1003 }
1004 
1005 std::vector<CScript> EvalDescriptorStringOrObject(const UniValue& scanobject, FlatSigningProvider& provider)
1006 {
1007  std::string desc_str;
1008  std::pair<int64_t, int64_t> range = {0, 1000};
1009  if (scanobject.isStr()) {
1010  desc_str = scanobject.get_str();
1011  } else if (scanobject.isObject()) {
1012  UniValue desc_uni = find_value(scanobject, "desc");
1013  if (desc_uni.isNull()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Descriptor needs to be provided in scan object");
1014  desc_str = desc_uni.get_str();
1015  UniValue range_uni = find_value(scanobject, "range");
1016  if (!range_uni.isNull()) {
1017  range = ParseDescriptorRange(range_uni);
1018  }
1019  } else {
1020  throw JSONRPCError(RPC_INVALID_PARAMETER, "Scan object needs to be either a string or an object");
1021  }
1022 
1023  std::string error;
1024  auto desc = Parse(desc_str, provider, error);
1025  if (!desc) {
1027  }
1028  if (!desc->IsRange()) {
1029  range.first = 0;
1030  range.second = 0;
1031  }
1032  std::vector<CScript> ret;
1033  for (int i = range.first; i <= range.second; ++i) {
1034  std::vector<CScript> scripts;
1035  if (!desc->Expand(i, provider, scripts, provider)) {
1036  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Cannot derive script without private keys: '%s'", desc_str));
1037  }
1038  std::move(scripts.begin(), scripts.end(), std::back_inserter(ret));
1039  }
1040  return ret;
1041 }
1042 
1044 {
1045  UniValue servicesNames(UniValue::VARR);
1046 
1047  for (const auto& flag : serviceFlagsToStr(services)) {
1048  servicesNames.push_back(flag);
1049  }
1050 
1051  return servicesNames;
1052 }
DescribeAddressVisitor::operator()
UniValue operator()(const WitnessV0ScriptHash &id) const
Definition: util.cpp:295
RPCHelpMan::m_fun
const RPCMethodImpl m_fun
Definition: util.h:364
RPCResult::Type::ELISION
@ ELISION
Special type to denote elision (...)
Parse
std::unique_ptr< Descriptor > Parse(const std::string &descriptor, FlatSigningProvider &out, std::string &error, bool require_checksum)
Parse a descriptor string.
Definition: descriptor.cpp:1394
DescribeAddressVisitor::operator()
UniValue operator()(const WitnessV0KeyHash &id) const
Definition: util.cpp:285
RPCArg::ToStringObj
std::string ToStringObj(bool oneline) const
Return the type string of the argument when it is in an object (dict).
Definition: util.cpp:903
HelpExampleCli
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:156
OutputType
OutputType
Definition: outputtype.h:18
ParseHex
std::vector< unsigned char > ParseHex(const char *psz)
Definition: strencodings.cpp:84
WitnessUnknown
CTxDestination subtype to encode any future Witness version.
Definition: standard.h:125
UniValue::VOBJ
@ VOBJ
Definition: univalue.h:19
RPCArg::m_oneline_description
const std::string m_oneline_description
Should be empty unless it is supposed to override the auto-generated summary line.
Definition: util.h:164
ParseHexO
std::vector< unsigned char > ParseHexO(const UniValue &o, std::string strKey)
Definition: util.cpp:112
DescribeAddressVisitor::DescribeAddressVisitor
DescribeAddressVisitor()
Definition: util.cpp:262
ParseConfirmTarget
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:330
ParseFixedPoint
bool ParseFixedPoint(const std::string &val, int decimals, int64_t *amount_out)
Parse number as fixed point according to JSON number syntax.
Definition: strencodings.cpp:398
RPC_INTERNAL_ERROR
@ RPC_INTERNAL_ERROR
Definition: protocol.h:35
CHECK_NONFATAL
#define CHECK_NONFATAL(condition)
Throw a NonFatalCheckError when the condition evaluates to false.
Definition: check.h:32
OuterType::NONE
@ NONE
TransactionError::MEMPOOL_REJECTED
@ MEMPOOL_REJECTED
RPCResult::CheckInnerDoc
void CheckInnerDoc() const
Definition: util.cpp:892
RPCHelpMan::m_results
const RPCResults m_results
Definition: util.h:367
TransactionErrorString
bilingual_str TransactionErrorString(const TransactionError err)
Definition: error.cpp:11
RPC_CLIENT_P2P_DISABLED
@ RPC_CLIENT_P2P_DISABLED
No valid connection manager instance found.
Definition: protocol.h:64
key_io.h
RPC_TRANSACTION_REJECTED
@ RPC_TRANSACTION_REJECTED
Definition: protocol.h:54
DescribeAddressVisitor::operator()
UniValue operator()(const CNoDestination &dest) const
Definition: util.cpp:264
OutputType::LEGACY
@ LEGACY
RPCHelpMan
Definition: util.h:346
FillableSigningProvider
Fillable signing provider that keeps keys in an address->secret map.
Definition: signingprovider.h:90
AddAndGetDestinationForScript
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:82
string.h
RPC_INVALID_PARAMETER
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
Definition: protocol.h:43
outputtype.h
IsHex
bool IsHex(const std::string &str)
Definition: strencodings.cpp:61
GetServicesNames
UniValue GetServicesNames(ServiceFlags services)
Returns, given services flags, a list of humanly readable (known) network services.
Definition: util.cpp:1043
RPCHelpMan::RPCMethodImpl
std::function< UniValue(const RPCHelpMan &, const JSONRPCRequest &)> RPCMethodImpl
Definition: util.h:350
serviceFlagsToStr
std::vector< std::string > serviceFlagsToStr(uint64_t flags)
Convert service flags (a bitmask of NODE_*) to human readable strings.
Definition: protocol.cpp:210
ParseHashV
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded Values (throws error if not hex).
Definition: util.cpp:90
RPCArg::Optional::NO
@ NO
Required arg.
RPCResults
Definition: util.h:317
RPCArg::Type::STR
@ STR
UniValueType::type
UniValue::VType type
Definition: util.h:48
RPCArg::Type::ARR
@ ARR
RPCResult::m_type
const Type m_type
Definition: util.h:248
RPCArg::Type
Type
Definition: util.h:127
Section::m_left
std::string m_left
Definition: util.cpp:375
RPCArg::m_fallback
const Fallback m_fallback
Definition: util.h:162
MoneyRange
bool MoneyRange(const CAmount &nValue)
Definition: amount.h:27
RPCResult::m_key_name
const std::string m_key_name
Only used for dicts.
Definition: util.h:249
RPCResult::Type::NUM
@ NUM
HexToPubKey
CPubKey HexToPubKey(const std::string &hex_in)
Definition: util.cpp:192
TransactionError::PSBT_MISMATCH
@ PSBT_MISMATCH
ServiceFlags
ServiceFlags
nServices flags
Definition: protocol.h:271
UniValue::isNull
bool isNull() const
Definition: univalue.h:75
CKeyID
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:23
TrimString
std::string TrimString(const std::string &str, const std::string &pattern=" \f\n\r\t\v")
Definition: string.h:18
RPCExamples::m_examples
const std::string m_examples
Definition: util.h:337
RPCTypeCheckObj
void RPCTypeCheckObj(const UniValue &o, const std::map< std::string, UniValueType > &typesExpected, bool fAllowNull, bool fStrict)
Definition: util.cpp:48
RPCArg::m_inner
const std::vector< RPCArg > m_inner
Only used for arrays or dicts.
Definition: util.h:161
UniValue::write
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
Definition: univalue_write.cpp:28
RPCArg::Type::OBJ_USER_KEYS
@ OBJ_USER_KEYS
Special type where the user must set the keys e.g. to define multiple addresses; as opposed to e....
Section::m_right
const std::string m_right
Definition: util.cpp:376
UniValue::isNum
bool isNum() const
Definition: univalue.h:80
UniValue::getType
enum VType getType() const
Definition: univalue.h:62
RPCTypeCheckArgument
void RPCTypeCheckArgument(const UniValue &value, const UniValueType &typeExpected)
Type-check one argument; throws JSONRPCError if wrong type given.
Definition: util.cpp:41
MAX_PUBKEYS_PER_MULTISIG
static const int MAX_PUBKEYS_PER_MULTISIG
Definition: script.h:30
UniValueType::typeAny
bool typeAny
Definition: util.h:47
RPCResult::m_inner
const std::vector< RPCResult > m_inner
Only used for arrays or dicts.
Definition: util.h:250
UniValue::pushKV
bool pushKV(const std::string &key, const UniValue &val)
Definition: univalue.cpp:133
DescribeAddressVisitor::operator()
UniValue operator()(const PKHash &keyID) const
Definition: util.cpp:269
RPCArg
Definition: util.h:126
RPCHelpMan::m_args
const std::vector< RPCArg > m_args
Definition: util.h:366
RPC_TRANSACTION_ALREADY_IN_CHAIN
@ RPC_TRANSACTION_ALREADY_IN_CHAIN
Definition: protocol.h:55
UniValue
Definition: univalue.h:17
tinyformat.h
OuterType
OuterType
Serializing JSON objects depends on the outer type.
Definition: util.h:120
WitnessV0KeyHash
Definition: standard.h:109
RPCResult::ToSections
void ToSections(Sections &sections, OuterType outer_type=OuterType::NONE, const int current_indent=0) const
Append the sections of the result.
Definition: util.cpp:758
RPCResult::Type::ARR_FIXED
@ ARR_FIXED
Special array that has a fixed number of entries.
RPCArg::Type::NUM
@ NUM
UniValue::type
enum VType type() const
Definition: univalue.h:179
RPCArg::IsOptional
bool IsOptional() const
Definition: util.cpp:684
signingprovider.h
RPCHelpMan::m_examples
const RPCExamples m_examples
Definition: util.h:368
RPCHelpMan::GetArgMap
UniValue GetArgMap() const
Return the named args that need to be converted from string to another JSON type.
Definition: util.cpp:653
UniValue::get_str
const std::string & get_str() const
Definition: univalue_get.cpp:98
RPC_DESERIALIZATION_ERROR
@ RPC_DESERIALIZATION_ERROR
Error parsing or validating structure in raw format.
Definition: protocol.h:45
UniValueType
Wrapper for UniValue::VType, which includes typeAny: Used to denote don't care type.
Definition: util.h:44
strencodings.h
UniValue::isStr
bool isStr() const
Definition: univalue.h:79
TransactionError
TransactionError
Definition: error.h:22
RPCErrorFromTransactionError
RPCErrorCode RPCErrorFromTransactionError(TransactionError terr)
Definition: util.cpp:340
Section::Section
Section(const std::string &left, const std::string &right)
Definition: util.cpp:373
RPCHelpMan::ToString
std::string ToString() const
Definition: util.cpp:602
UniValue::get_int64
int64_t get_int64() const
Definition: univalue_get.cpp:115
RPCArg::Type::OBJ
@ OBJ
CTxDestination
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:157
RPCHelpMan::IsValidNumArgs
bool IsValidNumArgs(size_t num_args) const
If the supplied number of args is neither too small nor too high.
Definition: util.cpp:581
ParseRange
static std::pair< int64_t, int64_t > ParseRange(const UniValue &value)
Definition: util.cpp:975
IsValidDestination
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition: standard.cpp:332
RPCArg::Optional::OMITTED_NAMED_ARG
@ OMITTED_NAMED_ARG
Optional arg that is a named argument and has a default value of null.
FillableSigningProvider::GetPubKey
virtual bool GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const override
Definition: signingprovider.cpp:108
RPCArg::Type::STR_HEX
@ STR_HEX
Special type that is a STR with only hex chars.
RPCResult::Type::OBJ
@ OBJ
RPCResult::Type::NONE
@ NONE
ParseHexV
std::vector< unsigned char > ParseHexV(const UniValue &v, std::string strName)
Definition: util.cpp:103
RPCHelpMan::HandleRequest
UniValue HandleRequest(const JSONRPCRequest &request) const
Definition: util.cpp:564
GetScriptForMultisig
CScript GetScriptForMultisig(int nRequired, const std::vector< CPubKey > &keys)
Generate a multisig script.
Definition: standard.cpp:320
RPCHelpMan::m_description
const std::string m_description
Definition: util.h:365
RPCResults::ToDescriptionString
std::string ToDescriptionString() const
Return the description string.
Definition: util.cpp:542
RPCArg::m_description
const std::string m_description
Definition: util.h:163
UniValue::VBOOL
@ VBOOL
Definition: univalue.h:19
Sections
Keeps track of RPCArgs by transforming them into sections for the purpose of serializing everything t...
Definition: util.cpp:383
RPCResult::Type::STR_HEX
@ STR_HEX
Special string with only hex chars.
AddAndGetMultisigDestination
CTxDestination AddAndGetMultisigDestination(const int required, const std::vector< CPubKey > &pubkeys, OutputType type, FillableSigningProvider &keystore, CScript &script_out)
Definition: util.cpp:226
TransactionError::INVALID_PSBT
@ INVALID_PSBT
MAX_SCRIPT_ELEMENT_SIZE
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
Definition: script.h:24
TransactionError::SIGHASH_MISMATCH
@ SIGHASH_MISMATCH
DescribeAddress
UniValue DescribeAddress(const CTxDestination &dest)
Definition: util.cpp:325
CAmount
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
RPCExamples
Definition: util.h:336
Sections::m_max_pad
size_t m_max_pad
Definition: util.cpp:385
GetKeyForDestination
CKeyID GetKeyForDestination(const SigningProvider &store, const CTxDestination &dest)
Return the CKeyID of the key involved in a script (if there is a unique one).
Definition: signingprovider.cpp:191
JSONRPCRequest::mode
enum JSONRPCRequest::Mode mode
TransactionError::P2P_DISABLED
@ P2P_DISABLED
RPCResult::MatchesType
bool MatchesType(const UniValue &result) const
Check whether the result JSON type matches.
Definition: util.cpp:856
UniValue::getKeys
const std::vector< std::string > & getKeys() const
Definition: univalue_get.cpp:77
uvTypeName
const char * uvTypeName(UniValue::VType t)
Definition: univalue.cpp:221
Sections::m_sections
std::vector< Section > m_sections
Definition: util.cpp:384
RPCResult::Type::STR
@ STR
EvalDescriptorStringOrObject
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:1005
RPCHelpMan::RPCHelpMan
RPCHelpMan(std::string name, std::string description, std::vector< RPCArg > args, RPCResults results, RPCExamples examples)
Definition: util.cpp:493
UniValue::VNUM
@ VNUM
Definition: univalue.h:19
RPCExamples::ToDescriptionString
std::string ToDescriptionString() const
Definition: util.cpp:559
uint256
256-bit opaque blob.
Definition: uint256.h:126
uint256S
uint256 uint256S(const char *str)
Definition: uint256.h:139
DescribeAddressVisitor::operator()
UniValue operator()(const ScriptHash &scriptID) const
Definition: util.cpp:277
RPCResult::Type::NUM_TIME
@ NUM_TIME
Special numeric to denote unix epoch time.
RPCResult::Type::ARR
@ ARR
RPCArg::m_names
const std::string m_names
The name of the arg (can be empty for inner args, can contain multiple aliases separated by | for nam...
Definition: util.h:158
RPCArg::GetName
std::string GetName() const
Return the name, throws when there are aliases.
Definition: util.cpp:678
RPCResult::Type::ANY
@ ANY
Special type to disable type checks (for testing only)
CScript
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:405
HelpExampleRpc
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:174
UniValue::isArray
bool isArray() const
Definition: univalue.h:81
HelpExampleRpcNamed
std::string HelpExampleRpcNamed(const std::string &methodname, const RPCArgList &args)
Definition: util.cpp:180
RPCArg::m_type_str
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:165
RPCResult::m_optional
const bool m_optional
Definition: util.h:251
RPCArg::Type::RANGE
@ RANGE
Special type that is a NUM or [NUM,NUM].
CNoDestination
Definition: standard.h:73
DescribeAddressVisitor::operator()
UniValue operator()(const WitnessUnknown &id) const
Definition: util.cpp:315
JSONRPCTransactionError
UniValue JSONRPCTransactionError(TransactionError terr, const std::string &err_string)
Definition: util.cpp:359
RPCArg::GetFirstName
std::string GetFirstName() const
Return the first of all aliases.
Definition: util.cpp:673
RPCHelpMan::GetArgNames
std::vector< std::string > GetArgNames() const
Definition: util.cpp:593
JSONRPCRequest::params
UniValue params
Definition: request.h:33
RPC_INVALID_ADDRESS_OR_KEY
@ RPC_INVALID_ADDRESS_OR_KEY
Invalid address or key.
Definition: protocol.h:41
name
const char * name
Definition: rest.cpp:52
JSONRPCRequest::GET_HELP
@ GET_HELP
Definition: request.h:34
PKHash
Definition: standard.h:79
strprintf
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
UniValue::getValStr
const std::string & getValStr() const
Definition: univalue.h:63
ParseDescriptorRange
std::pair< int64_t, int64_t > ParseDescriptorRange(const UniValue &value)
Parse a JSON range specified as int64, or [int64, int64].
Definition: util.cpp:989
Join
auto Join(const std::vector< T > &list, const BaseType &separator, UnaryOp unary_op) -> decltype(unary_op(list.at(0)))
Join a list of items.
Definition: string.h:44
DescribeAddressVisitor::operator()
UniValue operator()(const WitnessV1Taproot &tap) const
Definition: util.cpp:305
RPCArg::m_type
const Type m_type
Definition: util.h:159
ParseHashO
uint256 ParseHashO(const UniValue &o, std::string strKey)
Definition: util.cpp:99
CPubKey
An encapsulated public key.
Definition: pubkey.h:33
base_blob::IsNull
bool IsNull() const
Definition: uint256.h:33
Sections::PushSection
void PushSection(const Section &s)
Definition: util.cpp:387
Sections::Push
void Push(const RPCArg &arg, const size_t current_indent=5, const OuterType outer_type=OuterType::NONE)
Recursive helper to translate an RPCArg into sections.
Definition: util.cpp:396
RPCResult::Type::BOOL
@ BOOL
UniValue::get_int
int get_int() const
Definition: univalue_get.cpp:105
RPCArgList
std::vector< std::pair< std::string, UniValue > > RPCArgList
Definition: util.h:89
translation.h
RPCTypeCheck
void RPCTypeCheck(const UniValue &params, const std::list< UniValueType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.
Definition: util.cpp:24
Sections::ToString
std::string ToString() const
Concatenate all sections with proper padding.
Definition: util.cpp:452
JSONRPCError
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:56
RPCErrorCode
RPCErrorCode
Bitcoin RPC error codes.
Definition: protocol.h:23
RPCArg::Type::BOOL
@ BOOL
RPCResults::m_results
const std::vector< RPCResult > m_results
Definition: util.h:318
RPCArg::Optional::OMITTED
@ OMITTED
Optional argument with default value omitted because they are implicitly clear.
RPCArg::ToDescriptionString
std::string ToDescriptionString() const
Return the description string, including the argument type and whether the argument is required.
Definition: util.cpp:693
DecodeDestination
CTxDestination DecodeDestination(const std::string &str, std::string &error_msg, std::vector< int > *error_locations)
Definition: key_io.cpp:281
prevector::size
size_type size() const
Definition: prevector.h:282
UniValue::push_back
bool push_back(const UniValue &val)
Definition: univalue.cpp:108
OuterType::ARR
@ ARR
CPubKey::IsFullyValid
bool IsFullyValid() const
fully validate whether this is a valid public key (more expensive than IsValid())
Definition: pubkey.cpp:292
EXAMPLE_ADDRESS
const std::string EXAMPLE_ADDRESS[2]
Example bech32 addresses for the RPCExamples help documentation.
Definition: util.cpp:22
AmountFromValue
CAmount AmountFromValue(const UniValue &value, int decimals)
Validate and return a CAmount from a UniValue number or string.
Definition: util.cpp:78
OuterType::OBJ
@ OBJ
JSONRPCRequest::GET_ARGS
@ GET_ARGS
Definition: request.h:34
RPCResult::Type::OBJ_DYN
@ OBJ_DYN
Special dictionary with keys that are not literals.
UniValue::size
size_t size() const
Definition: univalue.h:66
RPCArg::Type::AMOUNT
@ AMOUNT
Special type representing a floating point amount (can be either NUM or STR)
JSONRPCRequest
Definition: request.h:28
RPCResult
Definition: util.h:231
RPCArg::ToString
std::string ToString(bool oneline) const
Return the type string of the argument.
Definition: util.cpp:940
HelpExampleCliNamed
std::string HelpExampleCliNamed(const std::string &methodname, const RPCArgList &args)
Definition: util.cpp:161
find_value
const UniValue & find_value(const UniValue &obj, const std::string &name)
Definition: univalue.cpp:236
RPC_TYPE_ERROR
@ RPC_TYPE_ERROR
Unexpected type was passed as parameter.
Definition: protocol.h:40
error
bool error(const char *fmt, const Args &... args)
Definition: system.h:49
RPCResult::Type::STR_AMOUNT
@ STR_AMOUNT
Special string to represent a floating point amount.
UniValue::VARR
@ VARR
Definition: univalue.h:19
UniValue::VNULL
@ VNULL
Definition: univalue.h:19
WitnessV0ScriptHash
Definition: standard.h:102
HexStr
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: strencodings.cpp:511
RPCResult::m_description
const std::string m_description
Definition: util.h:252
UniValue::VSTR
@ VSTR
Definition: univalue.h:19
amount.h
AddrToPubKey
CPubKey AddrToPubKey(const FillableSigningProvider &keystore, const std::string &addr_in)
Definition: util.cpp:205
RPCHelpMan::m_name
const std::string m_name
Definition: util.h:361
ByteUnit::k
@ k
ScriptHash
Definition: standard.h:89
UNIX_EPOCH_TIME
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
DescribeAddressVisitor
Definition: util.cpp:259
FlatSigningProvider
Definition: signingprovider.h:72
descriptor.h
ByteUnit::t
@ t
RPC_TRANSACTION_ERROR
@ RPC_TRANSACTION_ERROR
Aliases for backward compatibility.
Definition: protocol.h:53
Section
A pair of strings that can be aligned (through padding) with other Sections later on.
Definition: util.cpp:372
args
ArgsManager args
Definition: notifications.cpp:36
UniValue::isObject
bool isObject() const
Definition: univalue.h:82
TransactionError::ALREADY_IN_CHAIN
@ ALREADY_IN_CHAIN
WitnessV1Taproot
Definition: standard.h:118