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