Bitcoin ABC  0.22.12
P2P Digital Currency
misc.cpp
Go to the documentation of this file.
1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #include <chainparams.h>
7 #include <config.h>
8 #include <httpserver.h>
9 #include <interfaces/chain.h>
10 #include <key_io.h>
11 #include <logging.h>
12 #include <node/context.h>
13 #include <outputtype.h>
14 #include <rpc/blockchain.h>
15 #include <rpc/server.h>
16 #include <rpc/util.h>
17 #include <scheduler.h>
18 #include <script/descriptor.h>
19 #include <util/check.h>
20 #include <util/message.h> // For MessageSign(), MessageVerify()
21 #include <util/ref.h>
22 #include <util/strencodings.h>
23 #include <util/system.h>
24 
25 #include <univalue.h>
26 
27 #include <cstdint>
28 #include <tuple>
29 #ifdef HAVE_MALLOC_INFO
30 #include <malloc.h>
31 #endif
32 
33 static UniValue validateaddress(const Config &config,
34  const JSONRPCRequest &request) {
35  RPCHelpMan{
36  "validateaddress",
37  "Return information about the given bitcoin address.\n",
38  {
40  "The bitcoin address to validate"},
41  },
42  RPCResult{
44  "",
45  "",
46  {
47  {RPCResult::Type::BOOL, "isvalid",
48  "If the address is valid or not. If not, this is the only "
49  "property returned."},
50  {RPCResult::Type::STR, "address",
51  "The bitcoin address validated"},
52  {RPCResult::Type::STR_HEX, "scriptPubKey",
53  "The hex-encoded scriptPubKey generated by the address"},
54  {RPCResult::Type::BOOL, "isscript", "If the key is a script"},
55  }},
56  RPCExamples{HelpExampleCli("validateaddress", EXAMPLE_ADDRESS) +
57  HelpExampleRpc("validateaddress", EXAMPLE_ADDRESS)},
58  }
59  .Check(request);
60 
61  CTxDestination dest =
62  DecodeDestination(request.params[0].get_str(), config.GetChainParams());
63  bool isValid = IsValidDestination(dest);
64 
66  ret.pushKV("isvalid", isValid);
67 
68  if (isValid) {
69  if (ret["address"].isNull()) {
70  std::string currentAddress = EncodeDestination(dest, config);
71  ret.pushKV("address", currentAddress);
72 
73  CScript scriptPubKey = GetScriptForDestination(dest);
74  ret.pushKV("scriptPubKey",
75  HexStr(scriptPubKey.begin(), scriptPubKey.end()));
76 
77  UniValue detail = DescribeAddress(dest);
78  ret.pushKVs(detail);
79  }
80  }
81  return ret;
82 }
83 
84 static UniValue createmultisig(const Config &config,
85  const JSONRPCRequest &request) {
86  RPCHelpMan{
87  "createmultisig",
88  "Creates a multi-signature address with n signature of m keys "
89  "required.\n"
90  "It returns a json object with the address and redeemScript.\n",
91  {
93  "The number of required signatures out of the n keys."},
94  {"keys",
97  "The hex-encoded public keys.",
98  {
100  "The hex-encoded public key"},
101  }},
102  },
103  RPCResult{
105  "",
106  "",
107  {
108  {RPCResult::Type::STR, "address",
109  "The value of the new multisig address."},
110  {RPCResult::Type::STR_HEX, "redeemScript",
111  "The string value of the hex-encoded redemption script."},
112  {RPCResult::Type::STR, "descriptor",
113  "The descriptor for this multisig"},
114  }},
115  RPCExamples{
116  "\nCreate a multisig address from 2 public keys\n" +
117  HelpExampleCli("createmultisig",
118  "2 "
119  "\"["
120  "\\\"03789ed0bb717d88f7d321a368d905e7430207ebbd82bd3"
121  "42cf11ae157a7ace5fd\\\","
122  "\\\"03dbc6764b8884a92e871274b87583e6d5c2a58819473e1"
123  "7e107ef3f6aa5a61626\\\"]\"") +
124  "\nAs a JSON-RPC call\n" +
125  HelpExampleRpc("createmultisig",
126  "2, "
127  "\"["
128  "\\\"03789ed0bb717d88f7d321a368d905e7430207ebbd82bd3"
129  "42cf11ae157a7ace5fd\\\","
130  "\\\"03dbc6764b8884a92e871274b87583e6d5c2a58819473e1"
131  "7e107ef3f6aa5a61626\\\"]\"")},
132  }
133  .Check(request);
134 
135  int required = request.params[0].get_int();
136 
137  // Get the public keys
138  const UniValue &keys = request.params[1].get_array();
139  std::vector<CPubKey> pubkeys;
140  for (size_t i = 0; i < keys.size(); ++i) {
141  if ((keys[i].get_str().length() == 2 * CPubKey::COMPRESSED_SIZE ||
142  keys[i].get_str().length() == 2 * CPubKey::SIZE) &&
143  IsHex(keys[i].get_str())) {
144  pubkeys.push_back(HexToPubKey(keys[i].get_str()));
145  } else {
146  throw JSONRPCError(
148  strprintf("Invalid public key: %s\n", keys[i].get_str()));
149  }
150  }
151 
152  // Get the output type
153  OutputType output_type = OutputType::LEGACY;
154 
155  // Construct using pay-to-script-hash:
156  FillableSigningProvider keystore;
157  CScript inner;
159  required, pubkeys, output_type, keystore, inner);
160 
161  // Make the descriptor
162  std::unique_ptr<Descriptor> descriptor =
163  InferDescriptor(GetScriptForDestination(dest), keystore);
164 
165  UniValue result(UniValue::VOBJ);
166  result.pushKV("address", EncodeDestination(dest, config));
167  result.pushKV("redeemScript", HexStr(inner.begin(), inner.end()));
168  result.pushKV("descriptor", descriptor->ToString());
169 
170  return result;
171 }
172 
174  const JSONRPCRequest &request) {
175  RPCHelpMan{
176  "getdescriptorinfo",
177  {"Analyses a descriptor.\n"},
178  {
179  {"descriptor", RPCArg::Type::STR, RPCArg::Optional::NO,
180  "The descriptor."},
181  },
182  RPCResult{
184  "",
185  "",
186  {
187  {RPCResult::Type::STR, "descriptor",
188  "The descriptor in canonical form, without private keys"},
189  {RPCResult::Type::STR, "checksum",
190  "The checksum for the input descriptor"},
191  {RPCResult::Type::BOOL, "isrange",
192  "Whether the descriptor is ranged"},
193  {RPCResult::Type::BOOL, "issolvable",
194  "Whether the descriptor is solvable"},
195  {RPCResult::Type::BOOL, "hasprivatekeys",
196  "Whether the input descriptor contained at least one private "
197  "key"},
198  }},
199  RPCExamples{"Analyse a descriptor\n" +
200  HelpExampleCli("getdescriptorinfo",
201  "\"pkh([d34db33f/84h/0h/"
202  "0h]"
203  "0279be667ef9dcbbac55a06295Ce870b07029Bfcdb2"
204  "dce28d959f2815b16f81798)\"")}}
205  .Check(request);
206 
207  RPCTypeCheck(request.params, {UniValue::VSTR});
208 
209  FlatSigningProvider provider;
210  std::string error;
211  auto desc = Parse(request.params[0].get_str(), provider, error);
212  if (!desc) {
214  }
215 
216  UniValue result(UniValue::VOBJ);
217  result.pushKV("descriptor", desc->ToString());
218  result.pushKV("checksum",
219  GetDescriptorChecksum(request.params[0].get_str()));
220  result.pushKV("isrange", desc->IsRange());
221  result.pushKV("issolvable", desc->IsSolvable());
222  result.pushKV("hasprivatekeys", provider.keys.size() > 0);
223  return result;
224 }
225 
226 UniValue deriveaddresses(const Config &config, const JSONRPCRequest &request) {
227  RPCHelpMan{
228  "deriveaddresses",
229  {"Derives one or more addresses corresponding to an output "
230  "descriptor.\n"
231  "Examples of output descriptors are:\n"
232  " pkh(<pubkey>) P2PKH outputs for the given "
233  "pubkey\n"
234  " sh(multi(<n>,<pubkey>,<pubkey>,...)) P2SH-multisig outputs for "
235  "the given threshold and pubkeys\n"
236  " raw(<hex script>) Outputs whose scriptPubKey "
237  "equals the specified hex scripts\n"
238  "\nIn the above, <pubkey> either refers to a fixed public key in "
239  "hexadecimal notation, or to an xpub/xprv optionally followed by one\n"
240  "or more path elements separated by \"/\", where \"h\" represents a "
241  "hardened child key.\n"
242  "For more information on output descriptors, see the documentation in "
243  "the doc/descriptors.md file.\n"},
244  {
245  {"descriptor", RPCArg::Type::STR, RPCArg::Optional::NO,
246  "The descriptor."},
248  "If a ranged descriptor is used, this specifies the end or the "
249  "range (in [begin,end] notation) to derive."},
250  },
251  RPCResult{
253  "",
254  "",
255  {
256  {RPCResult::Type::STR, "address", "the derived addresses"},
257  }},
258  RPCExamples{"First three pkh receive addresses\n" +
260  "deriveaddresses",
261  "\"pkh([d34db33f/84h/0h/0h]"
262  "xpub6DJ2dNUysrn5Vt36jH2KLBT2i1auw1tTSSomg8P"
263  "hqNiUtx8QX2SvC9nrHu81fT41fvDUnhMjEzQgXnQjKE"
264  "u3oaqMSzhSrHMxyyoEAmUHQbY/0/*)#3vhfv5h5\" \"[0,2]\"")}}
265  .Check(request);
266 
267  // Range argument is checked later
268  RPCTypeCheck(request.params, {UniValue::VSTR, UniValueType()});
269  const std::string desc_str = request.params[0].get_str();
270 
271  int64_t range_begin = 0;
272  int64_t range_end = 0;
273 
274  if (request.params.size() >= 2 && !request.params[1].isNull()) {
275  std::tie(range_begin, range_end) =
276  ParseDescriptorRange(request.params[1]);
277  }
278 
279  FlatSigningProvider key_provider;
280  std::string error;
281  auto desc =
282  Parse(desc_str, key_provider, error, /* require_checksum = */ true);
283  if (!desc) {
285  }
286 
287  if (!desc->IsRange() && request.params.size() > 1) {
288  throw JSONRPCError(
290  "Range should not be specified for an un-ranged descriptor");
291  }
292 
293  if (desc->IsRange() && request.params.size() == 1) {
295  "Range must be specified for a ranged descriptor");
296  }
297 
298  UniValue addresses(UniValue::VARR);
299 
300  for (int i = range_begin; i <= range_end; ++i) {
301  FlatSigningProvider provider;
302  std::vector<CScript> scripts;
303  if (!desc->Expand(i, key_provider, scripts, provider)) {
304  throw JSONRPCError(
306  strprintf("Cannot derive script without private keys"));
307  }
308 
309  for (const CScript &script : scripts) {
310  CTxDestination dest;
311  if (!ExtractDestination(script, dest)) {
312  throw JSONRPCError(
314  strprintf(
315  "Descriptor does not have a corresponding address"));
316  }
317 
318  addresses.push_back(EncodeDestination(dest, config));
319  }
320  }
321 
322  // This should not be possible, but an assert seems overkill:
323  if (addresses.empty()) {
324  throw JSONRPCError(RPC_MISC_ERROR, "Unexpected empty result");
325  }
326 
327  return addresses;
328 }
329 
330 static UniValue verifymessage(const Config &config,
331  const JSONRPCRequest &request) {
332  RPCHelpMan{
333  "verifymessage",
334  "Verify a signed message\n",
335  {
337  "The bitcoin address to use for the signature."},
339  "The signature provided by the signer in base 64 encoding (see "
340  "signmessage)."},
342  "The message that was signed."},
343  },
345  "If the signature is verified or not."},
346  RPCExamples{
347  "\nUnlock the wallet for 30 seconds\n" +
348  HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") +
349  "\nCreate the signature\n" +
351  "signmessage",
352  "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"my message\"") +
353  "\nVerify the signature\n" +
354  HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4"
355  "XX\" \"signature\" \"my "
356  "message\"") +
357  "\nAs a JSON-RPC call\n" +
358  HelpExampleRpc("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4"
359  "XX\", \"signature\", \"my "
360  "message\"")},
361  }
362  .Check(request);
363 
364  LOCK(cs_main);
365 
366  std::string strAddress = request.params[0].get_str();
367  std::string strSign = request.params[1].get_str();
368  std::string strMessage = request.params[2].get_str();
369 
370  switch (MessageVerify(config.GetChainParams(), strAddress, strSign,
371  strMessage)) {
373  throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
375  throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
378  "Malformed base64 encoding");
381  return false;
383  return true;
384  }
385 
386  return false;
387 }
388 
390  const JSONRPCRequest &request) {
391  RPCHelpMan{
392  "signmessagewithprivkey",
393  "Sign a message with the private key of an address\n",
394  {
396  "The private key to sign the message with."},
398  "The message to create a signature of."},
399  },
400  RPCResult{RPCResult::Type::STR, "signature",
401  "The signature of the message encoded in base 64"},
402  RPCExamples{"\nCreate the signature\n" +
403  HelpExampleCli("signmessagewithprivkey",
404  "\"privkey\" \"my message\"") +
405  "\nVerify the signature\n" +
406  HelpExampleCli("verifymessage",
407  "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" "
408  "\"signature\" \"my message\"") +
409  "\nAs a JSON-RPC call\n" +
410  HelpExampleRpc("signmessagewithprivkey",
411  "\"privkey\", \"my message\"")},
412  }
413  .Check(request);
414 
415  std::string strPrivkey = request.params[0].get_str();
416  std::string strMessage = request.params[1].get_str();
417 
418  CKey key = DecodeSecret(strPrivkey);
419  if (!key.IsValid()) {
420  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
421  }
422 
423  std::string signature;
424 
425  if (!MessageSign(key, strMessage, signature)) {
426  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
427  }
428 
429  return signature;
430 }
431 
432 static UniValue setmocktime(const Config &config,
433  const JSONRPCRequest &request) {
434  RPCHelpMan{
435  "setmocktime",
436  "Set the local time to given timestamp (-regtest only)\n",
437  {
440  "\n"
441  " Pass 0 to go back to using the system time."},
442  },
444  RPCExamples{""},
445  }
446  .Check(request);
447 
448  if (!config.GetChainParams().IsMockableChain()) {
449  throw std::runtime_error(
450  "setmocktime for regression testing (-regtest mode) only");
451  }
452 
453  // For now, don't change mocktime if we're in the middle of validation, as
454  // this could have an effect on mempool time-based eviction, as well as
455  // IsInitialBlockDownload().
456  // TODO: figure out the right way to synchronize around mocktime, and
457  // ensure all call sites of GetTime() are accessing this safely.
458  LOCK(cs_main);
459 
460  RPCTypeCheck(request.params, {UniValue::VNUM});
461  int64_t time = request.params[0].get_int64();
462  if (time < 0) {
464  "Timestamp must be 0 or greater");
465  }
466  SetMockTime(time);
467  if (request.context.Has<NodeContext>()) {
468  for (const auto &chain_client :
469  request.context.Get<NodeContext>().chain_clients) {
470  chain_client->setMockTime(time);
471  }
472  }
473 
474  return NullUniValue;
475 }
476 
477 static UniValue mockscheduler(const Config &config,
478  const JSONRPCRequest &request) {
479  RPCHelpMan{
480  "mockscheduler",
481  "Bump the scheduler into the future (-regtest only)\n",
482  {
483  {"delta_time", RPCArg::Type::NUM, RPCArg::Optional::NO,
484  "Number of seconds to forward the scheduler into the future."},
485  },
487  RPCExamples{""},
488  }
489  .Check(request);
490 
491  if (!Params().IsMockableChain()) {
492  throw std::runtime_error(
493  "mockscheduler is for regression testing (-regtest mode) only");
494  }
495 
496  // check params are valid values
497  RPCTypeCheck(request.params, {UniValue::VNUM});
498  int64_t delta_seconds = request.params[0].get_int64();
499  if ((delta_seconds <= 0) || (delta_seconds > 3600)) {
500  throw std::runtime_error(
501  "delta_time must be between 1 and 3600 seconds (1 hr)");
502  }
503 
504  // protect against null pointer dereference
506  NodeContext &node = request.context.Get<NodeContext>();
508  node.scheduler->MockForward(std::chrono::seconds(delta_seconds));
509 
510  return NullUniValue;
511 }
512 
516  obj.pushKV("used", uint64_t(stats.used));
517  obj.pushKV("free", uint64_t(stats.free));
518  obj.pushKV("total", uint64_t(stats.total));
519  obj.pushKV("locked", uint64_t(stats.locked));
520  obj.pushKV("chunks_used", uint64_t(stats.chunks_used));
521  obj.pushKV("chunks_free", uint64_t(stats.chunks_free));
522  return obj;
523 }
524 
525 #ifdef HAVE_MALLOC_INFO
526 static std::string RPCMallocInfo() {
527  char *ptr = nullptr;
528  size_t size = 0;
529  FILE *f = open_memstream(&ptr, &size);
530  if (f) {
531  malloc_info(0, f);
532  fclose(f);
533  if (ptr) {
534  std::string rv(ptr, size);
535  free(ptr);
536  return rv;
537  }
538  }
539  return "";
540 }
541 #endif
542 
543 static UniValue getmemoryinfo(const Config &config,
544  const JSONRPCRequest &request) {
545  /* Please, avoid using the word "pool" here in the RPC interface or help,
546  * as users will undoubtedly confuse it with the other "memory pool"
547  */
548  RPCHelpMan{
549  "getmemoryinfo",
550  "Returns an object containing information about memory usage.\n",
551  {
552  {"mode", RPCArg::Type::STR, /* default */ "\"stats\"",
553  "determines what kind of information is returned.\n"
554  " - \"stats\" returns general statistics about memory usage in "
555  "the daemon.\n"
556  " - \"mallocinfo\" returns an XML string describing low-level "
557  "heap state (only available if compiled with glibc 2.10+)."},
558  },
559  {
560  RPCResult{
561  "mode \"stats\"",
563  "",
564  "",
565  {
567  "locked",
568  "Information about locked memory manager",
569  {
570  {RPCResult::Type::NUM, "used", "Number of bytes used"},
571  {RPCResult::Type::NUM, "free",
572  "Number of bytes available in current arenas"},
573  {RPCResult::Type::NUM, "total",
574  "Total number of bytes managed"},
575  {RPCResult::Type::NUM, "locked",
576  "Amount of bytes that succeeded locking. If this "
577  "number is smaller than total, locking pages failed "
578  "at some point and key data could be swapped to "
579  "disk."},
580  {RPCResult::Type::NUM, "chunks_used",
581  "Number allocated chunks"},
582  {RPCResult::Type::NUM, "chunks_free",
583  "Number unused chunks"},
584  }},
585  }},
586  RPCResult{"mode \"mallocinfo\"", RPCResult::Type::STR, "",
587  "\"<malloc version=\"1\">...\""},
588  },
589  RPCExamples{HelpExampleCli("getmemoryinfo", "") +
590  HelpExampleRpc("getmemoryinfo", "")},
591  }
592  .Check(request);
593 
594  std::string mode =
595  request.params[0].isNull() ? "stats" : request.params[0].get_str();
596  if (mode == "stats") {
598  obj.pushKV("locked", RPCLockedMemoryInfo());
599  return obj;
600  } else if (mode == "mallocinfo") {
601 #ifdef HAVE_MALLOC_INFO
602  return RPCMallocInfo();
603 #else
604  throw JSONRPCError(
606  "mallocinfo is only available when compiled with glibc 2.10+");
607 #endif
608  } else {
609  throw JSONRPCError(RPC_INVALID_PARAMETER, "unknown mode " + mode);
610  }
611 }
612 
613 static void EnableOrDisableLogCategories(UniValue cats, bool enable) {
614  cats = cats.get_array();
615  for (size_t i = 0; i < cats.size(); ++i) {
616  std::string cat = cats[i].get_str();
617 
618  bool success;
619  if (enable) {
620  success = LogInstance().EnableCategory(cat);
621  } else {
622  success = LogInstance().DisableCategory(cat);
623  }
624 
625  if (!success) {
627  "unknown logging category " + cat);
628  }
629  }
630 }
631 
632 static UniValue logging(const Config &config, const JSONRPCRequest &request) {
633  RPCHelpMan{
634  "logging",
635  "Gets and sets the logging configuration.\n"
636  "When called without an argument, returns the list of categories with "
637  "status that are currently being debug logged or not.\n"
638  "When called with arguments, adds or removes categories from debug "
639  "logging and return the lists above.\n"
640  "The arguments are evaluated in order \"include\", \"exclude\".\n"
641  "If an item is both included and excluded, it will thus end up being "
642  "excluded.\n"
643  "The valid logging categories are: " +
645  "\n"
646  "In addition, the following are available as category names with "
647  "special meanings:\n"
648  " - \"all\", \"1\" : represent all logging categories.\n"
649  " - \"none\", \"0\" : even if other logging categories are "
650  "specified, ignore all of them.\n",
651  {
652  {"include",
655  "The categories to add to debug logging",
656  {
657  {"include_category", RPCArg::Type::STR,
658  RPCArg::Optional::OMITTED, "the valid logging category"},
659  }},
660  {"exclude",
663  "The categories to remove from debug logging",
664  {
665  {"exclude_category", RPCArg::Type::STR,
666  RPCArg::Optional::OMITTED, "the valid logging category"},
667  }},
668  },
669  RPCResult{
671  "",
672  "keys are the logging categories, and values indicates its status",
673  {
674  {RPCResult::Type::BOOL, "category",
675  "if being debug logged or not. false:inactive, true:active"},
676  }},
677  RPCExamples{
678  HelpExampleCli("logging", "\"[\\\"all\\\"]\" \"[\\\"http\\\"]\"") +
679  HelpExampleRpc("logging", "[\"all\"], [\"libevent\"]")},
680  }
681  .Check(request);
682 
683  uint32_t original_log_categories = LogInstance().GetCategoryMask();
684  if (request.params[0].isArray()) {
685  EnableOrDisableLogCategories(request.params[0], true);
686  }
687 
688  if (request.params[1].isArray()) {
689  EnableOrDisableLogCategories(request.params[1], false);
690  }
691 
692  uint32_t updated_log_categories = LogInstance().GetCategoryMask();
693  uint32_t changed_log_categories =
694  original_log_categories ^ updated_log_categories;
695 
703  if (changed_log_categories & BCLog::LIBEVENT) {
705  LogInstance().WillLogCategory(BCLog::LIBEVENT))) {
706  LogInstance().DisableCategory(BCLog::LIBEVENT);
707  if (changed_log_categories == BCLog::LIBEVENT) {
709  "libevent logging cannot be updated when "
710  "using libevent before v2.1.1.");
711  }
712  }
713  }
714 
715  UniValue result(UniValue::VOBJ);
716  std::vector<CLogCategoryActive> vLogCatActive = ListActiveLogCategories();
717  for (const auto &logCatActive : vLogCatActive) {
718  result.pushKV(logCatActive.category, logCatActive.active);
719  }
720 
721  return result;
722 }
723 
724 static UniValue echo(const Config &config, const JSONRPCRequest &request) {
725  if (request.fHelp) {
726  throw std::runtime_error(RPCHelpMan{
727  "echo|echojson ...",
728  "Simply echo back the input arguments. This command is for "
729  "testing.\n"
730  "\nThe difference between echo and echojson is that echojson has "
731  "argument conversion enabled in the client-side table in "
732  "bitcoin-cli and the GUI. There is no server-side difference.",
733  {},
735  "Returns whatever was passed in"},
736  RPCExamples{""},
737  }
738  .ToString());
739  }
740 
741  CHECK_NONFATAL(request.params.size() != 100);
742 
743  return request.params;
744 }
745 
747  // clang-format off
748  static const CRPCCommand commands[] = {
749  // category name actor (function) argNames
750  // ------------------- ------------------------ ---------------------- ----------
751  { "control", "getmemoryinfo", getmemoryinfo, {"mode"} },
752  { "control", "logging", logging, {"include", "exclude"} },
753  { "util", "validateaddress", validateaddress, {"address"} },
754  { "util", "createmultisig", createmultisig, {"nrequired","keys"} },
755  { "util", "deriveaddresses", deriveaddresses, {"descriptor", "range"} },
756  { "util", "getdescriptorinfo", getdescriptorinfo, {"descriptor"} },
757  { "util", "verifymessage", verifymessage, {"address","signature","message"} },
758  { "util", "signmessagewithprivkey", signmessagewithprivkey, {"privkey","message"} },
759 
760  /* Not shown in help */
761  { "hidden", "setmocktime", setmocktime, {"timestamp"}},
762  { "hidden", "mockscheduler", mockscheduler, {"delta_time"}},
763  { "hidden", "echo", echo, {"arg0","arg1","arg2","arg3","arg4","arg5","arg6","arg7","arg8","arg9"}},
764  { "hidden", "echojson", echo, {"arg0","arg1","arg2","arg3","arg4","arg5","arg6","arg7","arg8","arg9"}},
765  };
766  // clang-format on
767 
768  for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++) {
769  t.appendCommand(commands[vcidx].name, &commands[vcidx]);
770  }
771 }
const util::Ref & context
Definition: request.h:42
std::vector< std::unique_ptr< interfaces::ChainClient > > chain_clients
Definition: context.h:46
static constexpr unsigned int SIZE
secp256k1:
Definition: pubkey.h:36
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
Definition: standard.cpp:152
BCLog::Logger & LogInstance()
Definition: logging.cpp:15
Bitcoin RPC command dispatcher.
Definition: server.h:198
void EnableCategory(LogFlags category)
Definition: logging.cpp:312
Required arg.
The provided signature couldn&#39;t be parsed (maybe invalid base64).
static LockedPoolManager & Instance()
Return the current instance, or create it once.
Definition: lockedpool.h:236
static UniValue verifymessage(const Config &config, const JSONRPCRequest &request)
Definition: misc.cpp:330
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1201
std::map< CKeyID, CKey > keys
const std::string EXAMPLE_ADDRESS
Example CashAddr address used in multiple RPCExamples.
Definition: util.cpp:22
std::string ListLogCategories()
Returns a string with the log categories.
Definition: logging.cpp:142
std::string GetDescriptorChecksum(const std::string &descriptor)
Get the checksum for a descriptor.
#define ARRAYLEN(array)
Utilities for converting data from/to strings.
Definition: strencodings.h:19
#define CHECK_NONFATAL(condition)
Throw a NonFatalCheckError when the condition evaluates to false.
Definition: check.h:34
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition: standard.cpp:269
CPubKey HexToPubKey(const std::string &hex_in)
Definition: util.cpp:153
UniValue DescribeAddress(const CTxDestination &dest)
Definition: util.cpp:263
const std::string & get_str() const
const UniValue & get_array() const
std::string EncodeDestination(const CTxDestination &dest, const Config &config)
Definition: key_io.cpp:170
The message verification was successful.
int64_t get_int64() const
bool pushKVs(const UniValue &obj)
Definition: univalue.cpp:146
void DisableCategory(LogFlags category)
Definition: logging.cpp:325
bool appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
Definition: server.cpp:316
OutputType
Definition: outputtype.h:17
virtual const CChainParams & GetChainParams() const =0
Invalid, missing or duplicate parameter.
Definition: protocol.h:46
static UniValue logging(const Config &config, const JSONRPCRequest &request)
Definition: misc.cpp:632
std::pair< int64_t, int64_t > ParseDescriptorRange(const UniValue &value)
Parse a JSON range specified as int64, or [int64, int64].
Definition: util.cpp:832
void SetMockTime(int64_t nMockTimeIn)
For testing.
Definition: time.cpp:50
CTxDestination AddAndGetMultisigDestination(const int required, const std::vector< CPubKey > &pubkeys, OutputType type, FillableSigningProvider &keystore, CScript &script_out)
Definition: util.cpp:195
std::unique_ptr< Descriptor > Parse(const std::string &descriptor, FlatSigningProvider &out, std::string &error, bool require_checksum)
Parse a descriptor string.
iterator end()
Definition: prevector.h:390
Special type that is a STR with only hex chars.
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:143
bool MessageSign(const CKey &privkey, const std::string &message, std::string &signature)
Sign a message.
Definition: message.cpp:56
static constexpr unsigned int COMPRESSED_SIZE
Definition: pubkey.h:37
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:52
bool push_back(const UniValue &val)
Definition: univalue.cpp:108
Definition: config.h:19
Special string with only hex chars.
NodeContext struct containing references to chain state and connection state.
Definition: context.h:35
UniValue params
Definition: request.h:37
#define LOCK(cs)
Definition: sync.h:230
const char * name
Definition: rest.cpp:43
Fillable signing provider that keeps keys in an address->secret map.
bool IsHex(const std::string &str)
Returns true if each character in str is a hex character, and has an even number of hex digits...
Unexpected type was passed as parameter.
Definition: protocol.h:40
uint32_t GetCategoryMask() const
Definition: logging.h:135
bool empty() const
Definition: univalue.h:78
RecursiveMutex cs_main
Global state.
Definition: validation.cpp:90
bool Has() const
Definition: ref.h:33
General application defined errors std::exception thrown in command handling.
Definition: protocol.h:38
bool pushKV(const std::string &key, const UniValue &val)
Definition: univalue.cpp:133
static UniValue setmocktime(const Config &config, const JSONRPCRequest &request)
Definition: misc.cpp:432
CTxDestination DecodeDestination(const std::string &addr, const CChainParams &params)
Definition: key_io.cpp:177
int get_int() const
Invalid address or key.
Definition: protocol.h:42
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:246
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:138
bool isNull() const
Definition: univalue.h:89
T & Get() const
Definition: ref.h:25
static UniValue RPCLockedMemoryInfo()
Definition: misc.cpp:513
MessageVerificationResult MessageVerify(const CChainParams &params, const std::string &address, const std::string &signature, const std::string &message)
Verify a signed message.
Definition: message.cpp:24
Optional arg that is a named argument and has a default value of null.
The message was not signed with the private key of the provided address.
static void EnableOrDisableLogCategories(UniValue cats, bool enable)
Definition: misc.cpp:613
Special type that is a NUM or [NUM,NUM].
bool fHelp
Definition: request.h:38
static UniValue signmessagewithprivkey(const Config &config, const JSONRPCRequest &request)
Definition: misc.cpp:389
Optional argument with default value omitted because they are implicitly clear.
std::unique_ptr< Descriptor > InferDescriptor(const CScript &script, const SigningProvider &provider)
Find a descriptor for the specified script, using information from provider where possible...
static UniValue mockscheduler(const Config &config, const JSONRPCRequest &request)
Definition: misc.cpp:477
const CChainParams & Params()
Return the currently selected parameters.
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:429
void RegisterMiscRPCCommands(CRPCTable &t)
Register miscellaneous RPC commands.
Definition: misc.cpp:746
The provided address is invalid.
static UniValue createmultisig(const Config &config, const JSONRPCRequest &request)
Definition: misc.cpp:84
std::string HexStr(const T itbegin, const T itend)
Definition: strencodings.h:132
const UniValue NullUniValue
Definition: univalue.cpp:13
iterator begin()
Definition: prevector.h:388
static UniValue getmemoryinfo(const Config &config, const JSONRPCRequest &request)
Definition: misc.cpp:543
size_t size() const
Definition: univalue.h:80
An encapsulated secp256k1 private key.
Definition: key.h:25
Stats stats() const
Get pool usage statistics.
Definition: lockedpool.cpp:330
UniValue deriveaddresses(const Config &config, const JSONRPCRequest &request)
Definition: misc.cpp:226
Special dictionary with keys that are not literals.
CKey DecodeSecret(const std::string &str)
Definition: key_io.cpp:80
A public key could not be recovered from the provided signature and message.
bool IsMockableChain() const
If this chain allows time to be mocked.
Definition: chainparams.h:72
static UniValue validateaddress(const Config &config, const JSONRPCRequest &request)
Definition: misc.cpp:33
UniValue getdescriptorinfo(const Config &config, const JSONRPCRequest &request)
Definition: misc.cpp:173
bool error(const char *fmt, const Args &... args)
Definition: system.h:47
std::vector< CLogCategoryActive > ListActiveLogCategories()
Returns a vector of the active log categories.
Definition: logging.cpp:159
static UniValue echo(const Config &config, const JSONRPCRequest &request)
Definition: misc.cpp:724
bool isArray() const
Definition: univalue.h:95
The provided address is valid but does not refer to a public key.
boost::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:87
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
bool UpdateHTTPServerLogging(bool enable)
Change logging level for libevent.
Definition: httpserver.cpp:449
Memory statistics.
Definition: lockedpool.h:153
bool IsValid() const
Check whether this private key is valid.
Definition: key.h:87
std::unique_ptr< CScheduler > scheduler
Definition: context.h:47
void RPCTypeCheck(const UniValue &params, const std::list< UniValueType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.
Definition: util.cpp:25