6#include <chainparams.h>
35#ifdef HAVE_MALLOC_INFO
44 "Return information about the given bitcoin address.\n",
47 "The bitcoin address to validate"},
55 "If the address is valid or not. If not, this is the only "
56 "property returned."},
58 "The bitcoin address validated"},
60 "The hex-encoded scriptPubKey generated by the address"},
68 config.GetChainParams());
72 ret.
pushKV(
"isvalid", isValid);
75 if (ret[
"address"].
isNull()) {
76 std::string currentAddress =
78 ret.
pushKV(
"address", currentAddress);
95 "Creates a multi-signature address with n signature of m keys "
97 "It returns a json object with the address and redeemScript.\n",
100 "The number of required signatures out of the n keys."},
104 "The hex-encoded public keys.",
107 "The hex-encoded public key"},
116 "The value of the new multisig address."},
118 "The string value of the hex-encoded redemption script."},
120 "The descriptor for this multisig"},
123 "\nCreate a multisig address from 2 public keys\n" +
127 "\\\"03789ed0bb717d88f7d321a368d905e7430207ebbd82bd3"
128 "42cf11ae157a7ace5fd\\\","
129 "\\\"03dbc6764b8884a92e871274b87583e6d5c2a58819473e1"
130 "7e107ef3f6aa5a61626\\\"]\"") +
131 "\nAs a JSON-RPC call\n" +
135 "\\\"03789ed0bb717d88f7d321a368d905e7430207ebbd82bd3"
136 "42cf11ae157a7ace5fd\\\","
137 "\\\"03dbc6764b8884a92e871274b87583e6d5c2a58819473e1"
138 "7e107ef3f6aa5a61626\\\"]\"")},
141 int required = request.params[0].
getInt<
int>();
145 std::vector<CPubKey> pubkeys;
146 for (
size_t i = 0; i < keys.size(); ++i) {
147 if ((keys[i].get_str().length() ==
150 IsHex(keys[i].get_str())) {
166 required, pubkeys, output_type, keystore, inner);
169 std::unique_ptr<Descriptor> descriptor =
175 result.
pushKV(
"descriptor", descriptor->ToString());
185 {
"Analyses a descriptor.\n"},
196 "The descriptor in canonical form, without private keys"},
198 "The checksum for the input descriptor"},
200 "Whether the descriptor is ranged"},
202 "Whether the descriptor is solvable"},
204 "Whether the input descriptor contained at least one private "
209 "\"pkh([d34db33f/84h/0h/"
211 "0279be667ef9dcbbac55a06295Ce870b07029Bfcdb2"
212 "dce28d959f2815b16f81798)\"")},
217 auto desc =
Parse(request.params[0].get_str(), provider,
error);
223 result.
pushKV(
"descriptor", desc->ToString());
226 result.
pushKV(
"isrange", desc->IsRange());
227 result.
pushKV(
"issolvable", desc->IsSolvable());
228 result.
pushKV(
"hasprivatekeys", provider.
keys.size() > 0);
237 {
"Derives one or more addresses corresponding to an output "
239 "Examples of output descriptors are:\n"
240 " pkh(<pubkey>) P2PKH outputs for the given "
242 " sh(multi(<n>,<pubkey>,<pubkey>,...)) P2SH-multisig outputs for "
243 "the given threshold and pubkeys\n"
244 " raw(<hex script>) Outputs whose scriptPubKey "
245 "equals the specified hex scripts\n"
246 "\nIn the above, <pubkey> either refers to a fixed public key in "
247 "hexadecimal notation, or to an xpub/xprv optionally followed by one\n"
248 "or more path elements separated by \"/\", where \"h\" represents a "
249 "hardened child key.\n"
250 "For more information on output descriptors, see the documentation in "
251 "the doc/descriptors.md file.\n"},
256 "If a ranged descriptor is used, this specifies the end or the "
257 "range (in [begin,end] notation) to derive."},
266 RPCExamples{
"First three pkh receive addresses\n" +
269 "\"pkh([d34db33f/84h/0h/0h]"
270 "xpub6DJ2dNUysrn5Vt36jH2KLBT2i1auw1tTSSomg8P"
271 "hqNiUtx8QX2SvC9nrHu81fT41fvDUnhMjEzQgXnQjKE"
272 "u3oaqMSzhSrHMxyyoEAmUHQbY/0/*)#3vhfv5h5\" \"[0,2]\"")},
275 const std::string desc_str = request.params[0].
get_str();
277 int64_t range_begin = 0;
278 int64_t range_end = 0;
280 if (request.params.size() >= 2 && !request.params[1].isNull()) {
281 std::tie(range_begin, range_end) =
287 auto desc =
Parse(desc_str, key_provider,
error,
293 if (!desc->IsRange() && request.params.size() > 1) {
295 "Range should not be specified for an "
296 "un-ranged descriptor");
299 if (desc->IsRange() && request.params.size() == 1) {
302 "Range must be specified for a ranged descriptor");
307 for (
int i = range_begin; i <= range_end; ++i) {
309 std::vector<CScript> scripts;
310 if (!desc->Expand(i, key_provider, scripts, provider)) {
313 strprintf(
"Cannot derive script without private keys"));
316 for (
const CScript &script : scripts) {
322 "corresponding address"));
330 if (addresses.
empty()) {
342 "Verify a signed message\n",
345 "The bitcoin address to use for the signature."},
347 "The signature provided by the signer in base 64 encoding (see "
350 "The message that was signed."},
353 "If the signature is verified or not."},
355 "\nUnlock the wallet for 30 seconds\n" +
357 "\nCreate the signature\n" +
360 "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"my message\"") +
361 "\nVerify the signature\n" +
362 HelpExampleCli(
"verifymessage",
"\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4"
363 "XX\" \"signature\" \"my "
365 "\nAs a JSON-RPC call\n" +
366 HelpExampleRpc(
"verifymessage",
"\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4"
367 "XX\", \"signature\", \"my "
373 std::string strAddress = request.params[0].get_str();
374 std::string strSign = request.params[1].get_str();
375 std::string strMessage = request.params[2].get_str();
377 switch (
MessageVerify(config.GetChainParams(), strAddress, strSign,
383 "Address does not refer to key");
386 "Malformed base64 encoding");
401 "signmessagewithprivkey",
402 "Sign a message with the private key of an address\n",
405 "The private key to sign the message with."},
407 "The message to create a signature of."},
410 "The signature of the message encoded in base 64"},
413 "\"privkey\" \"my message\"") +
414 "\nVerify the signature\n" +
416 "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" "
417 "\"signature\" \"my message\"") +
418 "\nAs a JSON-RPC call\n" +
420 "\"privkey\", \"my message\"")},
423 std::string strPrivkey = request.params[0].
get_str();
424 std::string strMessage = request.params[1].get_str();
429 "Invalid private key");
432 std::string signature;
446 "Set the local time to given timestamp (-regtest only)\n",
450 "Pass 0 to go back to using the system time."},
456 if (!config.GetChainParams().IsMockableChain()) {
457 throw std::runtime_error(
458 "setmocktime for regression testing (-regtest mode) only");
468 const int64_t time{request.params[0].getInt<int64_t>()};
472 strprintf(
"Mocktime can not be negative: %s.", time));
475 auto node_context = util::AnyPtr<NodeContext>(request.context);
477 for (
const auto &chain_client : node_context->chain_clients) {
478 chain_client->setMockTime(time);
490 "Bump the scheduler into the future (-regtest only)\n",
493 "Number of seconds to forward the scheduler into the future."},
500 throw std::runtime_error(
"mockscheduler is for regression "
501 "testing (-regtest mode) only");
504 int64_t delta_seconds = request.params[0].getInt<int64_t>();
505 if ((delta_seconds <= 0) || (delta_seconds > 3600)) {
506 throw std::runtime_error(
507 "delta_time must be between 1 and 3600 seconds (1 hr)");
514 node_context->scheduler->MockForward(
515 std::chrono::seconds(delta_seconds));
534#ifdef HAVE_MALLOC_INFO
535static std::string RPCMallocInfo() {
538 FILE *f = open_memstream(&ptr, &size);
543 std::string rv(ptr, size);
558 "Returns an object containing information about memory usage.\n",
561 "determines what kind of information is returned.\n"
562 " - \"stats\" returns general statistics about memory usage in "
564 " - \"mallocinfo\" returns an XML string describing low-level "
565 "heap state (only available if compiled with glibc 2.10+)."},
576 "Information about locked memory manager",
580 "Number of bytes available in current arenas"},
582 "Total number of bytes managed"},
584 "Amount of bytes that succeeded locking. If this "
585 "number is smaller than total, locking pages failed "
586 "at some point and key data could be swapped to "
589 "Number allocated chunks"},
591 "Number unused chunks"},
595 "\"<malloc version=\"1\">...\""},
601 std::string mode = request.params[0].
isNull()
603 : request.params[0].get_str();
604 if (mode ==
"stats") {
608 }
else if (mode ==
"mallocinfo") {
609#ifdef HAVE_MALLOC_INFO
610 return RPCMallocInfo();
613 "mallocinfo is only available when compiled "
618 "unknown mode " + mode);
626 for (
size_t i = 0; i < cats.
size(); ++i) {
627 std::string cat = cats[i].
get_str();
638 "unknown logging category " + cat);
646 "Gets and sets the logging configuration.\n"
647 "When called without an argument, returns the list of categories with "
648 "status that are currently being debug logged or not.\n"
649 "When called with arguments, adds or removes categories from debug "
650 "logging and return the lists above.\n"
651 "The arguments are evaluated in order \"include\", \"exclude\".\n"
652 "If an item is both included and excluded, it will thus end up being "
654 "The valid logging categories are: " +
657 "In addition, the following are available as category names with "
658 "special meanings:\n"
659 " - \"all\", \"1\" : represent all logging categories.\n"
660 " - \"none\", \"0\" : even if other logging categories are "
661 "specified, ignore all of them.\n",
666 "The categories to add to debug logging",
674 "The categories to remove from debug logging",
683 "keys are the logging categories, and values indicates its status",
686 "if being debug logged or not. false:inactive, true:active"},
689 HelpExampleCli(
"logging",
"\"[\\\"all\\\"]\" \"[\\\"http\\\"]\"") +
694 if (request.params[0].isArray()) {
698 if (request.params[1].isArray()) {
703 uint32_t changed_log_categories =
704 original_log_categories ^ updated_log_categories;
720 "libevent logging cannot be updated when "
721 "using libevent before v2.1.1.");
727 for (
const auto &logCatActive :
LogInstance().LogCategoriesList()) {
728 result.
pushKV(logCatActive.category, logCatActive.active);
739 "Simply echo back the input arguments. This command is for "
741 "\nIt will return an internal bug report when "
742 "arg9='trigger_internal_bug' is passed.\n"
743 "\nThe difference between echo and echojson is that echojson has "
744 "argument conversion enabled in the client-side table in "
745 "bitcoin-cli and the GUI. There is no server-side difference.",
772 if (request.params[9].isStr()) {
774 "trigger_internal_bug");
777 return request.params;
786 return echo(
"echojson");
792 "Returns an object containing information about the currency.\n",
802 "Number of satoshis per base unit"},
804 "Number of digits to the right of the decimal point."},
823 std::string index_name) {
825 if (!index_name.empty() && index_name != summary.name) {
830 entry.
pushKV(
"synced", summary.synced);
831 entry.
pushKV(
"best_block_height", summary.best_block_height);
832 ret_summary.
pushKV(summary.name, entry);
839 "Returns the status of one or all available indices currently "
840 "running in the node.\n",
844 "Filter results for an index with a specific name."},
853 "The name of the index",
856 "Whether the index is synced or not"},
858 "The block height to which the index is synced"},
869 const std::string index_name =
870 request.params[0].isNull() ?
"" : request.params[0].get_str();
895 "Returns the node time information\n",
904 "The time offset gathered from the other nodes on the "
907 "The adjusted timestamp of this node"},
917 timeObj.
pushKV(
"adjusted", TicksSinceEpoch<std::chrono::seconds>(
948 for (
const auto &c : commands) {
static constexpr Amount SATOSHI
void ForEachBlockFilterIndex(std::function< void(BlockFilterIndex &)> fn)
Iterate over all running block filter indexes, invoking fn on each.
const CChainParams & Params()
Return the currently selected parameters.
#define CHECK_NONFATAL(condition)
Identity function.
void DisableCategory(LogFlags category)
void EnableCategory(LogFlags category)
uint32_t GetCategoryMask() const
std::string LogCategoriesString() const
Returns a string with the log categories in alphabetical order.
IndexSummary GetSummary() const
Get a summary of the index and its state.
BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of bloc...
bool IsMockableChain() const
If this chain allows time to be mocked.
An encapsulated secp256k1 private key.
bool IsValid() const
Check whether this private key is valid.
static constexpr unsigned int COMPRESSED_SIZE
static constexpr unsigned int SIZE
secp256k1:
void appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
Fillable signing provider that keeps keys in an address->secret map.
Stats stats() const
Get pool usage statistics.
static LockedPoolManager & Instance()
Return the current instance, or create it once.
void push_back(UniValue val)
const std::string & get_str() const
void pushKVs(UniValue obj)
const UniValue & get_array() const
void pushKV(std::string key, UniValue val)
static UniValue Parse(std::string_view raw)
Parse string to UniValue or throw runtime_error if string contains invalid JSON.
std::unique_ptr< CoinStatsIndex > g_coin_stats_index
The global UTXO set hash object.
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
std::unique_ptr< Descriptor > InferDescriptor(const CScript &script, const SigningProvider &provider)
Find a descriptor for the specified script, using information from provider where possible.
std::string GetDescriptorChecksum(const std::string &descriptor)
Get the checksum for a descriptor.
bool UpdateHTTPServerLogging(bool enable)
Change logging level for libevent.
std::string EncodeDestination(const CTxDestination &dest, const Config &config)
CTxDestination DecodeDestination(const std::string &addr, const CChainParams ¶ms)
CKey DecodeSecret(const std::string &str)
BCLog::Logger & LogInstance()
bool error(const char *fmt, const Args &...args)
MessageVerificationResult MessageVerify(const CChainParams ¶ms, const std::string &address, const std::string &signature, const std::string &message)
Verify a signed message.
bool MessageSign(const CKey &privkey, const std::string &message, std::string &signature)
Sign a message.
@ ERR_MALFORMED_SIGNATURE
The provided signature couldn't be parsed (maybe invalid base64).
@ ERR_INVALID_ADDRESS
The provided address is invalid.
@ ERR_ADDRESS_NO_KEY
The provided address is valid but does not refer to a public key.
@ ERR_NOT_SIGNED
The message was not signed with the private key of the provided address.
@ OK
The message verification was successful.
@ ERR_PUBKEY_NOT_RECOVERED
A public key could not be recovered from the provided signature and message.
static RPCHelpMan logging()
static RPCHelpMan setmocktime()
void RegisterMiscRPCCommands(CRPCTable &t)
static void EnableOrDisableLogCategories(UniValue cats, bool enable)
static UniValue RPCLockedMemoryInfo()
static RPCHelpMan mockscheduler()
static RPCHelpMan getmemoryinfo()
static RPCHelpMan getcurrencyinfo()
static RPCHelpMan getdescriptorinfo()
static RPCHelpMan echo(const std::string &name)
static UniValue SummaryToJSON(const IndexSummary &&summary, std::string index_name)
static RPCHelpMan gettime()
static RPCHelpMan echojson()
static RPCHelpMan deriveaddresses()
static RPCHelpMan signmessagewithprivkey()
static RPCHelpMan createmultisig()
static RPCHelpMan verifymessage()
static RPCHelpMan validateaddress()
static RPCHelpMan getindexinfo()
static bool isNull(const AnyVoteItem &item)
UniValue JSONRPCError(int code, const std::string &message)
@ RPC_MISC_ERROR
General application defined errors std::exception thrown in command handling.
@ RPC_TYPE_ERROR
Unexpected type was passed as parameter.
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
@ RPC_INVALID_ADDRESS_OR_KEY
Invalid address or key.
std::pair< int64_t, int64_t > ParseDescriptorRange(const UniValue &value)
Parse a JSON range specified as int64, or [int64, int64].
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
CTxDestination AddAndGetMultisigDestination(const int required, const std::vector< CPubKey > &pubkeys, OutputType type, FillableSigningProvider &keystore, CScript &script_out)
const std::string EXAMPLE_ADDRESS
Example CashAddr address used in multiple RPCExamples.
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency.
CPubKey HexToPubKey(const std::string &hex_in)
UniValue DescribeAddress(const CTxDestination &dest)
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
std::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
static const Currency & get()
std::map< CKeyID, CKey > keys
@ RANGE
Special type that is a NUM or [NUM,NUM].
@ STR_HEX
Special type that is a STR with only hex chars.
@ OMITTED
The arg is optional for one of two reasons:
@ ANY
Special type to disable type checks (for testing only)
@ OBJ_DYN
Special dictionary with keys that are not literals.
@ STR_HEX
Special string with only hex chars.
NodeContext struct containing references to chain state and connection state.
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
int64_t GetTimeOffset()
"Never go to sea with two chronometers; take one or three." Our three time sources are:
NodeClock::time_point GetAdjustedTime()
std::unique_ptr< TxIndex > g_txindex
The global transaction index, used in GetTransaction. May be null.
const UniValue NullUniValue
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
bool IsHex(std::string_view str)
Returns true if each character in str is a hex character, and has an even number of hex digits.