8#include <chainparams.h>
40#ifdef HAVE_MALLOC_INFO
49 "Return information about the given bitcoin address.\n",
52 "The bitcoin address to validate"},
60 "If the address is valid or not. If not, this is the only "
61 "property returned."},
63 "The bitcoin address validated"},
65 "The hex-encoded scriptPubKey generated by the address"},
73 config.GetChainParams());
77 ret.
pushKV(
"isvalid", isValid);
80 if (ret[
"address"].
isNull()) {
81 std::string currentAddress =
83 ret.
pushKV(
"address", currentAddress);
100 "Creates a multi-signature address with n signature of m keys "
102 "It returns a json object with the address and redeemScript.\n",
105 "The number of required signatures out of the n keys."},
109 "The hex-encoded public keys.",
112 "The hex-encoded public key"},
121 "The value of the new multisig address."},
123 "The string value of the hex-encoded redemption script."},
125 "The descriptor for this multisig"},
128 "\nCreate a multisig address from 2 public keys\n" +
132 "\\\"03789ed0bb717d88f7d321a368d905e7430207ebbd82bd3"
133 "42cf11ae157a7ace5fd\\\","
134 "\\\"03dbc6764b8884a92e871274b87583e6d5c2a58819473e1"
135 "7e107ef3f6aa5a61626\\\"]\"") +
136 "\nAs a JSON-RPC call\n" +
140 "\\\"03789ed0bb717d88f7d321a368d905e7430207ebbd82bd3"
141 "42cf11ae157a7ace5fd\\\","
142 "\\\"03dbc6764b8884a92e871274b87583e6d5c2a58819473e1"
143 "7e107ef3f6aa5a61626\\\"]\"")},
146 int required = request.params[0].
getInt<
int>();
150 std::vector<CPubKey> pubkeys;
151 for (
size_t i = 0; i < keys.size(); ++i) {
152 if ((keys[i].get_str().length() ==
155 IsHex(keys[i].get_str())) {
171 required, pubkeys, output_type, keystore, inner);
174 std::unique_ptr<Descriptor> descriptor =
180 result.
pushKV(
"descriptor", descriptor->ToString());
190 {
"Analyses a descriptor.\n"},
201 "The descriptor in canonical form, without private keys"},
203 "The checksum for the input descriptor"},
205 "Whether the descriptor is ranged"},
207 "Whether the descriptor is solvable"},
209 "Whether the input descriptor contained at least one private "
214 "\"pkh([d34db33f/84h/0h/"
216 "0279be667ef9dcbbac55a06295Ce870b07029Bfcdb2"
217 "dce28d959f2815b16f81798)\"")},
222 auto desc =
Parse(request.params[0].get_str(), provider, error);
228 result.
pushKV(
"descriptor", desc->ToString());
231 result.
pushKV(
"isrange", desc->IsRange());
232 result.
pushKV(
"issolvable", desc->IsSolvable());
233 result.
pushKV(
"hasprivatekeys", provider.
keys.size() > 0);
242 {
"Derives one or more addresses corresponding to an output "
244 "Examples of output descriptors are:\n"
245 " pkh(<pubkey>) P2PKH outputs for the given "
247 " sh(multi(<n>,<pubkey>,<pubkey>,...)) P2SH-multisig outputs for "
248 "the given threshold and pubkeys\n"
249 " raw(<hex script>) Outputs whose scriptPubKey "
250 "equals the specified hex scripts\n"
251 "\nIn the above, <pubkey> either refers to a fixed public key in "
252 "hexadecimal notation, or to an xpub/xprv optionally followed by one\n"
253 "or more path elements separated by \"/\", where \"h\" represents a "
254 "hardened child key.\n"
255 "For more information on output descriptors, see the documentation in "
256 "the doc/descriptors.md file.\n"},
261 "If a ranged descriptor is used, this specifies the end or the "
262 "range (in [begin,end] notation) to derive."},
271 RPCExamples{
"First three pkh receive addresses\n" +
274 "\"pkh([d34db33f/84h/0h/0h]"
275 "xpub6DJ2dNUysrn5Vt36jH2KLBT2i1auw1tTSSomg8P"
276 "hqNiUtx8QX2SvC9nrHu81fT41fvDUnhMjEzQgXnQjKE"
277 "u3oaqMSzhSrHMxyyoEAmUHQbY/0/*)#3vhfv5h5\" \"[0,2]\"")},
280 const std::string desc_str = request.params[0].
get_str();
282 int64_t range_begin = 0;
283 int64_t range_end = 0;
285 if (request.params.size() >= 2 && !request.params[1].isNull()) {
286 std::tie(range_begin, range_end) =
292 auto desc =
Parse(desc_str, key_provider, error,
298 if (!desc->IsRange() && request.params.size() > 1) {
300 "Range should not be specified for an "
301 "un-ranged descriptor");
304 if (desc->IsRange() && request.params.size() == 1) {
307 "Range must be specified for a ranged descriptor");
312 for (
int i = range_begin; i <= range_end; ++i) {
314 std::vector<CScript> scripts;
315 if (!desc->Expand(i, key_provider, scripts, provider)) {
318 strprintf(
"Cannot derive script without private keys"));
321 for (
const CScript &script : scripts) {
327 "corresponding address"));
335 if (addresses.
empty()) {
347 "Verify a signed message\n",
350 "The bitcoin address to use for the signature."},
352 "The signature provided by the signer in base 64 encoding (see "
355 "The message that was signed."},
358 "If the signature is verified or not."},
360 "\nUnlock the wallet for 30 seconds\n" +
362 "\nCreate the signature\n" +
365 "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"my message\"") +
366 "\nVerify the signature\n" +
367 HelpExampleCli(
"verifymessage",
"\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4"
368 "XX\" \"signature\" \"my "
370 "\nAs a JSON-RPC call\n" +
371 HelpExampleRpc(
"verifymessage",
"\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4"
372 "XX\", \"signature\", \"my "
378 std::string strAddress = self.
Arg<std::string>(
"address");
379 std::string strSign = self.
Arg<std::string>(
"signature");
380 std::string strMessage = self.
Arg<std::string>(
"message");
382 switch (
MessageVerify(config.GetChainParams(), strAddress, strSign,
388 "Address does not refer to key");
391 "Malformed base64 encoding");
406 "signmessagewithprivkey",
407 "Sign a message with the private key of an address\n",
410 "The private key to sign the message with."},
412 "The message to create a signature of."},
415 "The signature of the message encoded in base 64"},
418 "\"privkey\" \"my message\"") +
419 "\nVerify the signature\n" +
421 "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" "
422 "\"signature\" \"my message\"") +
423 "\nAs a JSON-RPC call\n" +
425 "\"privkey\", \"my message\"")},
428 std::string strPrivkey = request.params[0].
get_str();
429 std::string strMessage = request.params[1].get_str();
434 "Invalid private key");
437 std::string signature;
451 "Set the local time to given timestamp (-regtest only)\n",
455 "Pass 0 to go back to using the system time."},
461 if (!config.GetChainParams().IsMockableChain()) {
462 throw std::runtime_error(
463 "setmocktime for regression testing (-regtest mode) only");
473 const int64_t time{request.params[0].getInt<int64_t>()};
477 strprintf(
"Mocktime can not be negative: %s.", time));
480 auto node_context = util::AnyPtr<NodeContext>(request.context);
482 for (
const auto &chain_client : node_context->chain_clients) {
483 chain_client->setMockTime(time);
495 "Bump the scheduler into the future (-regtest only)\n",
498 "Number of seconds to forward the scheduler into the future."},
505 throw std::runtime_error(
"mockscheduler is for regression "
506 "testing (-regtest mode) only");
509 int64_t delta_seconds = request.params[0].getInt<int64_t>();
510 if ((delta_seconds <= 0) || (delta_seconds > 3600)) {
511 throw std::runtime_error(
512 "delta_time must be between 1 and 3600 seconds (1 hr)");
519 node_context->scheduler->MockForward(
520 std::chrono::seconds(delta_seconds));
539#ifdef HAVE_MALLOC_INFO
540static std::string RPCMallocInfo() {
543 FILE *f = open_memstream(&ptr, &size);
548 std::string rv(ptr, size);
563 "Returns an object containing information about memory usage.\n",
566 "determines what kind of information is returned.\n"
567 " - \"stats\" returns general statistics about memory usage in "
569 " - \"mallocinfo\" returns an XML string describing low-level "
570 "heap state (only available if compiled with glibc 2.10+)."},
581 "Information about locked memory manager",
585 "Number of bytes available in current arenas"},
587 "Total number of bytes managed"},
589 "Amount of bytes that succeeded locking. If this "
590 "number is smaller than total, locking pages failed "
591 "at some point and key data could be swapped to "
594 "Number allocated chunks"},
596 "Number unused chunks"},
600 "\"<malloc version=\"1\">...\""},
606 std::string mode = request.params[0].
isNull()
608 : request.params[0].get_str();
609 if (mode ==
"stats") {
613 }
else if (mode ==
"mallocinfo") {
614#ifdef HAVE_MALLOC_INFO
615 return RPCMallocInfo();
618 "mallocinfo is only available when compiled "
623 "unknown mode " + mode);
631 for (
size_t i = 0; i < cats.
size(); ++i) {
632 std::string cat = cats[i].
get_str();
643 "unknown logging category " + cat);
651 "Gets and sets the logging configuration.\n"
652 "When called without an argument, returns the list of categories with "
653 "status that are currently being debug logged or not.\n"
654 "When called with arguments, adds or removes categories from debug "
655 "logging and return the lists above.\n"
656 "The arguments are evaluated in order \"include\", \"exclude\".\n"
657 "If an item is both included and excluded, it will thus end up being "
659 "The valid logging categories are: " +
662 "In addition, the following are available as category names with "
663 "special meanings:\n"
664 " - \"all\", \"1\" : represent all logging categories.\n"
665 " - \"none\", \"0\" : even if other logging categories are "
666 "specified, ignore all of them.\n",
671 "The categories to add to debug logging",
679 "The categories to remove from debug logging",
688 "keys are the logging categories, and values indicates its status",
691 "if being debug logged or not. false:inactive, true:active"},
694 HelpExampleCli(
"logging",
"\"[\\\"all\\\"]\" \"[\\\"http\\\"]\"") +
699 if (request.params[0].isArray()) {
703 if (request.params[1].isArray()) {
708 uint32_t changed_log_categories =
709 original_log_categories ^ updated_log_categories;
718 for (
const auto &logCatActive :
LogInstance().LogCategoriesList()) {
719 result.
pushKV(logCatActive.category, logCatActive.active);
730 "Simply echo back the input arguments. This command is for "
732 "\nIt will return an internal bug report when "
733 "arg9='trigger_internal_bug' is passed.\n"
734 "\nThe difference between echo and echojson is that echojson has "
735 "argument conversion enabled in the client-side table in "
736 "bitcoin-cli and the GUI. There is no server-side difference.",
763 if (request.params[9].isStr()) {
765 "trigger_internal_bug");
768 return request.params;
777 return echo(
"echojson");
783 "Returns an object containing information about the currency.\n",
793 "Number of satoshis per base unit"},
795 "Number of digits to the right of the decimal point."},
814 std::string index_name) {
816 if (!index_name.empty() && index_name != summary.name) {
821 entry.
pushKV(
"synced", summary.synced);
822 entry.
pushKV(
"best_block_height", summary.best_block_height);
823 ret_summary.
pushKV(summary.name, std::move(entry));
830 "Returns the status of one or all available indices currently "
831 "running in the node.\n",
834 "Filter results for an index with a specific name."},
843 "The name of the index",
846 "Whether the index is synced or not"},
848 "The block height to which the index is synced"},
859 const std::string index_name =
860 request.params[0].isNull() ?
"" : request.params[0].get_str();
885 "Returns the node time information\n",
894 "The time offset gathered from the other nodes on the "
897 "The adjusted timestamp of this node"},
907 timeObj.
pushKV(
"adjusted", TicksSinceEpoch<std::chrono::seconds>(
917 "Returns basic information about the node\n",
925 "The version number"},
927 "The full version as a string"},
929 "Whether avalanche is enabled"},
931 "Whether avalanche staking rewards is enabled"},
933 "Whether avalanche staking rewards preconsensus is enabled"},
935 "Whether avalanche preconsensus is enabled"},
937 "Whether mining based on avalanche preconsensus is enabled"},
949 config.GetChainParams().GetConsensus();
957 if (
node.avalanche) {
958 infoObj.
pushKV(
"avalanche",
true);
959 infoObj.
pushKV(
"avalanche_staking_rewards",
962 "avalanche_staking_preconsensus",
963 node.avalanche->isStakingPreconsensusActivated(tip));
964 const bool fPreconsensus =
965 node.avalanche->isPreconsensusActivated(tip);
966 infoObj.
pushKV(
"avalanche_preconsensus", fPreconsensus);
967 infoObj.
pushKV(
"avalanche_mining_preconsensus",
970 "-avalanchepreconsensusmining",
973 infoObj.
pushKV(
"avalanche",
false);
974 infoObj.
pushKV(
"avalanche_staking_rewards",
false);
975 infoObj.
pushKV(
"avalanche_staking_preconsensus",
false);
976 infoObj.
pushKV(
"avalanche_preconsensus",
false);
977 infoObj.
pushKV(
"avalanche_mining_preconsensus",
false);
1005 {
"hidden",
echo, },
1009 for (
const auto &c : commands) {
static constexpr Amount SATOSHI
static constexpr bool DEFAULT_AVALANCHE_MINING_PRECONSENSUS
Default for -avalanchepreconsensusmining.
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.
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
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...
The block chain is a tree shaped structure starting with the genesis block at the root,...
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.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
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.
auto Arg(size_t i) const
Helper to get a required or default-valued request argument.
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::string FormatFullVersion()
static constexpr int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
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.
void 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()
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 RPCHelpMan getinfo()
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)
NodeContext & EnsureAnyNodeContext(const std::any &context)
ChainstateManager & EnsureChainman(const NodeContext &node)
ArgsManager & EnsureArgsman(const NodeContext &node)
bool IsStakingRewardsActivated(const Consensus::Params ¶ms, const CBlockIndex *pprev)
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.
Parameters that influence chain consensus.
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
Optional argument for which the default value is omitted from help text 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.
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
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.