Use the variable name _ for unused return values
[bitcoinplatinum.git] / src / rpc / misc.cpp
bloba6af24f7e12c907420026916440f66314c4b4ab5
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.
6 #include "base58.h"
7 #include "chain.h"
8 #include "clientversion.h"
9 #include "core_io.h"
10 #include "init.h"
11 #include "validation.h"
12 #include "httpserver.h"
13 #include "net.h"
14 #include "netbase.h"
15 #include "rpc/blockchain.h"
16 #include "rpc/server.h"
17 #include "timedata.h"
18 #include "util.h"
19 #include "utilstrencodings.h"
20 #ifdef ENABLE_WALLET
21 #include "wallet/rpcwallet.h"
22 #include "wallet/wallet.h"
23 #include "wallet/walletdb.h"
24 #endif
25 #include "warnings.h"
27 #include <stdint.h>
28 #ifdef HAVE_MALLOC_INFO
29 #include <malloc.h>
30 #endif
32 #include <univalue.h>
34 /**
35 * @note Do not add or change anything in the information returned by this
36 * method. `getinfo` exists for backwards-compatibility only. It combines
37 * information from wildly different sources in the program, which is a mess,
38 * and is thus planned to be deprecated eventually.
40 * Based on the source of the information, new information should be added to:
41 * - `getblockchaininfo`,
42 * - `getnetworkinfo` or
43 * - `getwalletinfo`
45 * Or alternatively, create a specific query method for the information.
46 **/
47 UniValue getinfo(const JSONRPCRequest& request)
49 if (request.fHelp || request.params.size() != 0)
50 throw std::runtime_error(
51 "getinfo\n"
52 "\nDEPRECATED. Returns an object containing various state info.\n"
53 "\nResult:\n"
54 "{\n"
55 " \"deprecation-warning\": \"...\" (string) warning that the getinfo command is deprecated and will be removed in 0.16\n"
56 " \"version\": xxxxx, (numeric) the server version\n"
57 " \"protocolversion\": xxxxx, (numeric) the protocol version\n"
58 " \"walletversion\": xxxxx, (numeric) the wallet version\n"
59 " \"balance\": xxxxxxx, (numeric) the total bitcoin balance of the wallet\n"
60 " \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n"
61 " \"timeoffset\": xxxxx, (numeric) the time offset\n"
62 " \"connections\": xxxxx, (numeric) the number of connections\n"
63 " \"proxy\": \"host:port\", (string, optional) the proxy used by the server\n"
64 " \"difficulty\": xxxxxx, (numeric) the current difficulty\n"
65 " \"testnet\": true|false, (boolean) if the server is using testnet or not\n"
66 " \"keypoololdest\": xxxxxx, (numeric) the timestamp (seconds since Unix epoch) of the oldest pre-generated key in the key pool\n"
67 " \"keypoolsize\": xxxx, (numeric) how many new keys are pre-generated\n"
68 " \"unlocked_until\": ttt, (numeric) the timestamp in seconds since epoch (midnight Jan 1 1970 GMT) that the wallet is unlocked for transfers, or 0 if the wallet is locked\n"
69 " \"paytxfee\": x.xxxx, (numeric) the transaction fee set in " + CURRENCY_UNIT + "/kB\n"
70 " \"relayfee\": x.xxxx, (numeric) minimum relay fee for transactions in " + CURRENCY_UNIT + "/kB\n"
71 " \"errors\": \"...\" (string) any error messages\n"
72 "}\n"
73 "\nExamples:\n"
74 + HelpExampleCli("getinfo", "")
75 + HelpExampleRpc("getinfo", "")
78 #ifdef ENABLE_WALLET
79 CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
81 LOCK2(cs_main, pwallet ? &pwallet->cs_wallet : nullptr);
82 #else
83 LOCK(cs_main);
84 #endif
86 proxyType proxy;
87 GetProxy(NET_IPV4, proxy);
89 UniValue obj(UniValue::VOBJ);
90 obj.push_back(Pair("deprecation-warning", "WARNING: getinfo is deprecated and will be fully removed in 0.16."
91 " Projects should transition to using getblockchaininfo, getnetworkinfo, and getwalletinfo before upgrading to 0.16"));
92 obj.push_back(Pair("version", CLIENT_VERSION));
93 obj.push_back(Pair("protocolversion", PROTOCOL_VERSION));
94 #ifdef ENABLE_WALLET
95 if (pwallet) {
96 obj.push_back(Pair("walletversion", pwallet->GetVersion()));
97 obj.push_back(Pair("balance", ValueFromAmount(pwallet->GetBalance())));
99 #endif
100 obj.push_back(Pair("blocks", (int)chainActive.Height()));
101 obj.push_back(Pair("timeoffset", GetTimeOffset()));
102 if(g_connman)
103 obj.push_back(Pair("connections", (int)g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL)));
104 obj.push_back(Pair("proxy", (proxy.IsValid() ? proxy.proxy.ToStringIPPort() : std::string())));
105 obj.push_back(Pair("difficulty", (double)GetDifficulty()));
106 obj.push_back(Pair("testnet", Params().NetworkIDString() == CBaseChainParams::TESTNET));
107 #ifdef ENABLE_WALLET
108 if (pwallet) {
109 obj.push_back(Pair("keypoololdest", pwallet->GetOldestKeyPoolTime()));
110 obj.push_back(Pair("keypoolsize", (int)pwallet->GetKeyPoolSize()));
112 if (pwallet && pwallet->IsCrypted()) {
113 obj.push_back(Pair("unlocked_until", pwallet->nRelockTime));
115 obj.push_back(Pair("paytxfee", ValueFromAmount(payTxFee.GetFeePerK())));
116 #endif
117 obj.push_back(Pair("relayfee", ValueFromAmount(::minRelayTxFee.GetFeePerK())));
118 obj.push_back(Pair("errors", GetWarnings("statusbar")));
119 return obj;
122 #ifdef ENABLE_WALLET
123 class DescribeAddressVisitor : public boost::static_visitor<UniValue>
125 public:
126 CWallet * const pwallet;
128 explicit DescribeAddressVisitor(CWallet *_pwallet) : pwallet(_pwallet) {}
130 UniValue operator()(const CNoDestination &dest) const { return UniValue(UniValue::VOBJ); }
132 UniValue operator()(const CKeyID &keyID) const {
133 UniValue obj(UniValue::VOBJ);
134 CPubKey vchPubKey;
135 obj.push_back(Pair("isscript", false));
136 if (pwallet && pwallet->GetPubKey(keyID, vchPubKey)) {
137 obj.push_back(Pair("pubkey", HexStr(vchPubKey)));
138 obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed()));
140 return obj;
143 UniValue operator()(const CScriptID &scriptID) const {
144 UniValue obj(UniValue::VOBJ);
145 CScript subscript;
146 obj.push_back(Pair("isscript", true));
147 if (pwallet && pwallet->GetCScript(scriptID, subscript)) {
148 std::vector<CTxDestination> addresses;
149 txnouttype whichType;
150 int nRequired;
151 ExtractDestinations(subscript, whichType, addresses, nRequired);
152 obj.push_back(Pair("script", GetTxnOutputType(whichType)));
153 obj.push_back(Pair("hex", HexStr(subscript.begin(), subscript.end())));
154 UniValue a(UniValue::VARR);
155 for (const CTxDestination& addr : addresses)
156 a.push_back(CBitcoinAddress(addr).ToString());
157 obj.push_back(Pair("addresses", a));
158 if (whichType == TX_MULTISIG)
159 obj.push_back(Pair("sigsrequired", nRequired));
161 return obj;
164 #endif
166 UniValue validateaddress(const JSONRPCRequest& request)
168 if (request.fHelp || request.params.size() != 1)
169 throw std::runtime_error(
170 "validateaddress \"address\"\n"
171 "\nReturn information about the given bitcoin address.\n"
172 "\nArguments:\n"
173 "1. \"address\" (string, required) The bitcoin address to validate\n"
174 "\nResult:\n"
175 "{\n"
176 " \"isvalid\" : true|false, (boolean) If the address is valid or not. If not, this is the only property returned.\n"
177 " \"address\" : \"address\", (string) The bitcoin address validated\n"
178 " \"scriptPubKey\" : \"hex\", (string) The hex encoded scriptPubKey generated by the address\n"
179 " \"ismine\" : true|false, (boolean) If the address is yours or not\n"
180 " \"iswatchonly\" : true|false, (boolean) If the address is watchonly\n"
181 " \"isscript\" : true|false, (boolean) If the key is a script\n"
182 " \"script\" : \"type\" (string, optional) The output script type. Possible types: nonstandard, pubkey, pubkeyhash, scripthash, multisig, nulldata, witness_v0_keyhash, witness_v0_scripthash\n"
183 " \"hex\" : \"hex\", (string, optional) The redeemscript for the p2sh address\n"
184 " \"addresses\" (string, optional) Array of addresses associated with the known redeemscript\n"
185 " [\n"
186 " \"address\"\n"
187 " ,...\n"
188 " ]\n"
189 " \"sigsrequired\" : xxxxx (numeric, optional) Number of signatures required to spend multisig output\n"
190 " \"pubkey\" : \"publickeyhex\", (string) The hex value of the raw public key\n"
191 " \"iscompressed\" : true|false, (boolean) If the address is compressed\n"
192 " \"account\" : \"account\" (string) DEPRECATED. The account associated with the address, \"\" is the default account\n"
193 " \"timestamp\" : timestamp, (number, optional) The creation time of the key if available in seconds since epoch (Jan 1 1970 GMT)\n"
194 " \"hdkeypath\" : \"keypath\" (string, optional) The HD keypath if the key is HD and available\n"
195 " \"hdmasterkeyid\" : \"<hash160>\" (string, optional) The Hash160 of the HD master pubkey\n"
196 "}\n"
197 "\nExamples:\n"
198 + HelpExampleCli("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"")
199 + HelpExampleRpc("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"")
202 #ifdef ENABLE_WALLET
203 CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
205 LOCK2(cs_main, pwallet ? &pwallet->cs_wallet : nullptr);
206 #else
207 LOCK(cs_main);
208 #endif
210 CBitcoinAddress address(request.params[0].get_str());
211 bool isValid = address.IsValid();
213 UniValue ret(UniValue::VOBJ);
214 ret.push_back(Pair("isvalid", isValid));
215 if (isValid)
217 CTxDestination dest = address.Get();
218 std::string currentAddress = address.ToString();
219 ret.push_back(Pair("address", currentAddress));
221 CScript scriptPubKey = GetScriptForDestination(dest);
222 ret.push_back(Pair("scriptPubKey", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
224 #ifdef ENABLE_WALLET
225 isminetype mine = pwallet ? IsMine(*pwallet, dest) : ISMINE_NO;
226 ret.push_back(Pair("ismine", bool(mine & ISMINE_SPENDABLE)));
227 ret.push_back(Pair("iswatchonly", bool(mine & ISMINE_WATCH_ONLY)));
228 UniValue detail = boost::apply_visitor(DescribeAddressVisitor(pwallet), dest);
229 ret.pushKVs(detail);
230 if (pwallet && pwallet->mapAddressBook.count(dest)) {
231 ret.push_back(Pair("account", pwallet->mapAddressBook[dest].name));
233 CKeyID keyID;
234 if (pwallet) {
235 const auto& meta = pwallet->mapKeyMetadata;
236 auto it = address.GetKeyID(keyID) ? meta.find(keyID) : meta.end();
237 if (it == meta.end()) {
238 it = meta.find(CScriptID(scriptPubKey));
240 if (it != meta.end()) {
241 ret.push_back(Pair("timestamp", it->second.nCreateTime));
242 if (!it->second.hdKeypath.empty()) {
243 ret.push_back(Pair("hdkeypath", it->second.hdKeypath));
244 ret.push_back(Pair("hdmasterkeyid", it->second.hdMasterKeyID.GetHex()));
248 #endif
250 return ret;
253 // Needed even with !ENABLE_WALLET, to pass (ignored) pointers around
254 class CWallet;
257 * Used by addmultisigaddress / createmultisig:
259 CScript _createmultisig_redeemScript(CWallet * const pwallet, const UniValue& params)
261 int nRequired = params[0].get_int();
262 const UniValue& keys = params[1].get_array();
264 // Gather public keys
265 if (nRequired < 1)
266 throw std::runtime_error("a multisignature address must require at least one key to redeem");
267 if ((int)keys.size() < nRequired)
268 throw std::runtime_error(
269 strprintf("not enough keys supplied "
270 "(got %u keys, but need at least %d to redeem)", keys.size(), nRequired));
271 if (keys.size() > 16)
272 throw std::runtime_error("Number of addresses involved in the multisignature address creation > 16\nReduce the number");
273 std::vector<CPubKey> pubkeys;
274 pubkeys.resize(keys.size());
275 for (unsigned int i = 0; i < keys.size(); i++)
277 const std::string& ks = keys[i].get_str();
278 #ifdef ENABLE_WALLET
279 // Case 1: Bitcoin address and we have full public key:
280 CBitcoinAddress address(ks);
281 if (pwallet && address.IsValid()) {
282 CKeyID keyID;
283 if (!address.GetKeyID(keyID))
284 throw std::runtime_error(
285 strprintf("%s does not refer to a key",ks));
286 CPubKey vchPubKey;
287 if (!pwallet->GetPubKey(keyID, vchPubKey)) {
288 throw std::runtime_error(
289 strprintf("no full public key for address %s",ks));
291 if (!vchPubKey.IsFullyValid())
292 throw std::runtime_error(" Invalid public key: "+ks);
293 pubkeys[i] = vchPubKey;
296 // Case 2: hex public key
297 else
298 #endif
299 if (IsHex(ks))
301 CPubKey vchPubKey(ParseHex(ks));
302 if (!vchPubKey.IsFullyValid())
303 throw std::runtime_error(" Invalid public key: "+ks);
304 pubkeys[i] = vchPubKey;
306 else
308 throw std::runtime_error(" Invalid public key: "+ks);
311 CScript result = GetScriptForMultisig(nRequired, pubkeys);
313 if (result.size() > MAX_SCRIPT_ELEMENT_SIZE)
314 throw std::runtime_error(
315 strprintf("redeemScript exceeds size limit: %d > %d", result.size(), MAX_SCRIPT_ELEMENT_SIZE));
317 return result;
320 UniValue createmultisig(const JSONRPCRequest& request)
322 #ifdef ENABLE_WALLET
323 CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
324 #else
325 CWallet * const pwallet = nullptr;
326 #endif
328 if (request.fHelp || request.params.size() < 2 || request.params.size() > 2)
330 std::string msg = "createmultisig nrequired [\"key\",...]\n"
331 "\nCreates a multi-signature address with n signature of m keys required.\n"
332 "It returns a json object with the address and redeemScript.\n"
334 "\nArguments:\n"
335 "1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n"
336 "2. \"keys\" (string, required) A json array of keys which are bitcoin addresses or hex-encoded public keys\n"
337 " [\n"
338 " \"key\" (string) bitcoin address or hex-encoded public key\n"
339 " ,...\n"
340 " ]\n"
342 "\nResult:\n"
343 "{\n"
344 " \"address\":\"multisigaddress\", (string) The value of the new multisig address.\n"
345 " \"redeemScript\":\"script\" (string) The string value of the hex-encoded redemption script.\n"
346 "}\n"
348 "\nExamples:\n"
349 "\nCreate a multisig address from 2 addresses\n"
350 + HelpExampleCli("createmultisig", "2 \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"") +
351 "\nAs a json rpc call\n"
352 + HelpExampleRpc("createmultisig", "2, \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"")
354 throw std::runtime_error(msg);
357 // Construct using pay-to-script-hash:
358 CScript inner = _createmultisig_redeemScript(pwallet, request.params);
359 CScriptID innerID(inner);
360 CBitcoinAddress address(innerID);
362 UniValue result(UniValue::VOBJ);
363 result.push_back(Pair("address", address.ToString()));
364 result.push_back(Pair("redeemScript", HexStr(inner.begin(), inner.end())));
366 return result;
369 UniValue verifymessage(const JSONRPCRequest& request)
371 if (request.fHelp || request.params.size() != 3)
372 throw std::runtime_error(
373 "verifymessage \"address\" \"signature\" \"message\"\n"
374 "\nVerify a signed message\n"
375 "\nArguments:\n"
376 "1. \"address\" (string, required) The bitcoin address to use for the signature.\n"
377 "2. \"signature\" (string, required) The signature provided by the signer in base 64 encoding (see signmessage).\n"
378 "3. \"message\" (string, required) The message that was signed.\n"
379 "\nResult:\n"
380 "true|false (boolean) If the signature is verified or not.\n"
381 "\nExamples:\n"
382 "\nUnlock the wallet for 30 seconds\n"
383 + HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") +
384 "\nCreate the signature\n"
385 + HelpExampleCli("signmessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"my message\"") +
386 "\nVerify the signature\n"
387 + HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"signature\" \"my message\"") +
388 "\nAs json rpc\n"
389 + HelpExampleRpc("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\", \"signature\", \"my message\"")
392 LOCK(cs_main);
394 std::string strAddress = request.params[0].get_str();
395 std::string strSign = request.params[1].get_str();
396 std::string strMessage = request.params[2].get_str();
398 CBitcoinAddress addr(strAddress);
399 if (!addr.IsValid())
400 throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
402 CKeyID keyID;
403 if (!addr.GetKeyID(keyID))
404 throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
406 bool fInvalid = false;
407 std::vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);
409 if (fInvalid)
410 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding");
412 CHashWriter ss(SER_GETHASH, 0);
413 ss << strMessageMagic;
414 ss << strMessage;
416 CPubKey pubkey;
417 if (!pubkey.RecoverCompact(ss.GetHash(), vchSig))
418 return false;
420 return (pubkey.GetID() == keyID);
423 UniValue signmessagewithprivkey(const JSONRPCRequest& request)
425 if (request.fHelp || request.params.size() != 2)
426 throw std::runtime_error(
427 "signmessagewithprivkey \"privkey\" \"message\"\n"
428 "\nSign a message with the private key of an address\n"
429 "\nArguments:\n"
430 "1. \"privkey\" (string, required) The private key to sign the message with.\n"
431 "2. \"message\" (string, required) The message to create a signature of.\n"
432 "\nResult:\n"
433 "\"signature\" (string) The signature of the message encoded in base 64\n"
434 "\nExamples:\n"
435 "\nCreate the signature\n"
436 + HelpExampleCli("signmessagewithprivkey", "\"privkey\" \"my message\"") +
437 "\nVerify the signature\n"
438 + HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"signature\" \"my message\"") +
439 "\nAs json rpc\n"
440 + HelpExampleRpc("signmessagewithprivkey", "\"privkey\", \"my message\"")
443 std::string strPrivkey = request.params[0].get_str();
444 std::string strMessage = request.params[1].get_str();
446 CBitcoinSecret vchSecret;
447 bool fGood = vchSecret.SetString(strPrivkey);
448 if (!fGood)
449 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
450 CKey key = vchSecret.GetKey();
451 if (!key.IsValid())
452 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
454 CHashWriter ss(SER_GETHASH, 0);
455 ss << strMessageMagic;
456 ss << strMessage;
458 std::vector<unsigned char> vchSig;
459 if (!key.SignCompact(ss.GetHash(), vchSig))
460 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
462 return EncodeBase64(&vchSig[0], vchSig.size());
465 UniValue setmocktime(const JSONRPCRequest& request)
467 if (request.fHelp || request.params.size() != 1)
468 throw std::runtime_error(
469 "setmocktime timestamp\n"
470 "\nSet the local time to given timestamp (-regtest only)\n"
471 "\nArguments:\n"
472 "1. timestamp (integer, required) Unix seconds-since-epoch timestamp\n"
473 " Pass 0 to go back to using the system time."
476 if (!Params().MineBlocksOnDemand())
477 throw std::runtime_error("setmocktime for regression testing (-regtest mode) only");
479 // For now, don't change mocktime if we're in the middle of validation, as
480 // this could have an effect on mempool time-based eviction, as well as
481 // IsCurrentForFeeEstimation() and IsInitialBlockDownload().
482 // TODO: figure out the right way to synchronize around mocktime, and
483 // ensure all call sites of GetTime() are accessing this safely.
484 LOCK(cs_main);
486 RPCTypeCheck(request.params, {UniValue::VNUM});
487 SetMockTime(request.params[0].get_int64());
489 return NullUniValue;
492 static UniValue RPCLockedMemoryInfo()
494 LockedPool::Stats stats = LockedPoolManager::Instance().stats();
495 UniValue obj(UniValue::VOBJ);
496 obj.push_back(Pair("used", uint64_t(stats.used)));
497 obj.push_back(Pair("free", uint64_t(stats.free)));
498 obj.push_back(Pair("total", uint64_t(stats.total)));
499 obj.push_back(Pair("locked", uint64_t(stats.locked)));
500 obj.push_back(Pair("chunks_used", uint64_t(stats.chunks_used)));
501 obj.push_back(Pair("chunks_free", uint64_t(stats.chunks_free)));
502 return obj;
505 #ifdef HAVE_MALLOC_INFO
506 static std::string RPCMallocInfo()
508 char *ptr = nullptr;
509 size_t size = 0;
510 FILE *f = open_memstream(&ptr, &size);
511 if (f) {
512 malloc_info(0, f);
513 fclose(f);
514 if (ptr) {
515 std::string rv(ptr, size);
516 free(ptr);
517 return rv;
520 return "";
522 #endif
524 UniValue getmemoryinfo(const JSONRPCRequest& request)
526 /* Please, avoid using the word "pool" here in the RPC interface or help,
527 * as users will undoubtedly confuse it with the other "memory pool"
529 if (request.fHelp || request.params.size() > 1)
530 throw std::runtime_error(
531 "getmemoryinfo (\"mode\")\n"
532 "Returns an object containing information about memory usage.\n"
533 "Arguments:\n"
534 "1. \"mode\" determines what kind of information is returned. This argument is optional, the default mode is \"stats\".\n"
535 " - \"stats\" returns general statistics about memory usage in the daemon.\n"
536 " - \"mallocinfo\" returns an XML string describing low-level heap state (only available if compiled with glibc 2.10+).\n"
537 "\nResult (mode \"stats\"):\n"
538 "{\n"
539 " \"locked\": { (json object) Information about locked memory manager\n"
540 " \"used\": xxxxx, (numeric) Number of bytes used\n"
541 " \"free\": xxxxx, (numeric) Number of bytes available in current arenas\n"
542 " \"total\": xxxxxxx, (numeric) Total number of bytes managed\n"
543 " \"locked\": xxxxxx, (numeric) Amount of bytes that succeeded locking. If this number is smaller than total, locking pages failed at some point and key data could be swapped to disk.\n"
544 " \"chunks_used\": xxxxx, (numeric) Number allocated chunks\n"
545 " \"chunks_free\": xxxxx, (numeric) Number unused chunks\n"
546 " }\n"
547 "}\n"
548 "\nResult (mode \"mallocinfo\"):\n"
549 "\"<malloc version=\"1\">...\"\n"
550 "\nExamples:\n"
551 + HelpExampleCli("getmemoryinfo", "")
552 + HelpExampleRpc("getmemoryinfo", "")
555 std::string mode = request.params[0].isNull() ? "stats" : request.params[0].get_str();
556 if (mode == "stats") {
557 UniValue obj(UniValue::VOBJ);
558 obj.push_back(Pair("locked", RPCLockedMemoryInfo()));
559 return obj;
560 } else if (mode == "mallocinfo") {
561 #ifdef HAVE_MALLOC_INFO
562 return RPCMallocInfo();
563 #else
564 throw JSONRPCError(RPC_INVALID_PARAMETER, "mallocinfo is only available when compiled with glibc 2.10+");
565 #endif
566 } else {
567 throw JSONRPCError(RPC_INVALID_PARAMETER, "unknown mode " + mode);
571 uint32_t getCategoryMask(UniValue cats) {
572 cats = cats.get_array();
573 uint32_t mask = 0;
574 for (unsigned int i = 0; i < cats.size(); ++i) {
575 uint32_t flag = 0;
576 std::string cat = cats[i].get_str();
577 if (!GetLogCategory(&flag, &cat)) {
578 throw JSONRPCError(RPC_INVALID_PARAMETER, "unknown logging category " + cat);
580 mask |= flag;
582 return mask;
585 UniValue logging(const JSONRPCRequest& request)
587 if (request.fHelp || request.params.size() > 2) {
588 throw std::runtime_error(
589 "logging [include,...] <exclude>\n"
590 "Gets and sets the logging configuration.\n"
591 "When called without an argument, returns the list of categories that are currently being debug logged.\n"
592 "When called with arguments, adds or removes categories from debug logging.\n"
593 "The valid logging categories are: " + ListLogCategories() + "\n"
594 "libevent logging is configured on startup and cannot be modified by this RPC during runtime."
595 "Arguments:\n"
596 "1. \"include\" (array of strings) add debug logging for these categories.\n"
597 "2. \"exclude\" (array of strings) remove debug logging for these categories.\n"
598 "\nResult: <categories> (string): a list of the logging categories that are active.\n"
599 "\nExamples:\n"
600 + HelpExampleCli("logging", "\"[\\\"all\\\"]\" \"[\\\"http\\\"]\"")
601 + HelpExampleRpc("logging", "[\"all\"], \"[libevent]\"")
605 uint32_t originalLogCategories = logCategories;
606 if (request.params[0].isArray()) {
607 logCategories |= getCategoryMask(request.params[0]);
610 if (request.params[1].isArray()) {
611 logCategories &= ~getCategoryMask(request.params[1]);
614 // Update libevent logging if BCLog::LIBEVENT has changed.
615 // If the library version doesn't allow it, UpdateHTTPServerLogging() returns false,
616 // in which case we should clear the BCLog::LIBEVENT flag.
617 // Throw an error if the user has explicitly asked to change only the libevent
618 // flag and it failed.
619 uint32_t changedLogCategories = originalLogCategories ^ logCategories;
620 if (changedLogCategories & BCLog::LIBEVENT) {
621 if (!UpdateHTTPServerLogging(logCategories & BCLog::LIBEVENT)) {
622 logCategories &= ~BCLog::LIBEVENT;
623 if (changedLogCategories == BCLog::LIBEVENT) {
624 throw JSONRPCError(RPC_INVALID_PARAMETER, "libevent logging cannot be updated when using libevent before v2.1.1.");
629 UniValue result(UniValue::VOBJ);
630 std::vector<CLogCategoryActive> vLogCatActive = ListActiveLogCategories();
631 for (const auto& logCatActive : vLogCatActive) {
632 result.pushKV(logCatActive.category, logCatActive.active);
635 return result;
638 UniValue echo(const JSONRPCRequest& request)
640 if (request.fHelp)
641 throw std::runtime_error(
642 "echo|echojson \"message\" ...\n"
643 "\nSimply echo back the input arguments. This command is for testing.\n"
644 "\nThe difference between echo and echojson is that echojson has argument conversion enabled in the client-side table in"
645 "bitcoin-cli and the GUI. There is no server-side difference."
648 return request.params;
651 static const CRPCCommand commands[] =
652 { // category name actor (function) okSafeMode
653 // --------------------- ------------------------ ----------------------- ----------
654 { "control", "getinfo", &getinfo, true, {} }, /* uses wallet if enabled */
655 { "control", "getmemoryinfo", &getmemoryinfo, true, {"mode"} },
656 { "util", "validateaddress", &validateaddress, true, {"address"} }, /* uses wallet if enabled */
657 { "util", "createmultisig", &createmultisig, true, {"nrequired","keys"} },
658 { "util", "verifymessage", &verifymessage, true, {"address","signature","message"} },
659 { "util", "signmessagewithprivkey", &signmessagewithprivkey, true, {"privkey","message"} },
661 /* Not shown in help */
662 { "hidden", "setmocktime", &setmocktime, true, {"timestamp"}},
663 { "hidden", "echo", &echo, true, {"arg0","arg1","arg2","arg3","arg4","arg5","arg6","arg7","arg8","arg9"}},
664 { "hidden", "echojson", &echo, true, {"arg0","arg1","arg2","arg3","arg4","arg5","arg6","arg7","arg8","arg9"}},
665 { "hidden", "logging", &logging, true, {"include", "exclude"}},
668 void RegisterMiscRPCCommands(CRPCTable &t)
670 for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
671 t.appendCommand(commands[vcidx].name, &commands[vcidx]);