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