Avoid redundant redeclaration of GetWarnings(const string&)
[bitcoinplatinum.git] / src / rpc / misc.cpp
blob3c4f071fcf04b11fac95bef72bee4e47bc29ac6b
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 " \"version\": xxxxx, (numeric) the server version\n"
55 " \"protocolversion\": xxxxx, (numeric) the protocol version\n"
56 " \"walletversion\": xxxxx, (numeric) the wallet version\n"
57 " \"balance\": xxxxxxx, (numeric) the total bitcoin balance of the wallet\n"
58 " \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n"
59 " \"timeoffset\": xxxxx, (numeric) the time offset\n"
60 " \"connections\": xxxxx, (numeric) the number of connections\n"
61 " \"proxy\": \"host:port\", (string, optional) the proxy used by the server\n"
62 " \"difficulty\": xxxxxx, (numeric) the current difficulty\n"
63 " \"testnet\": true|false, (boolean) if the server is using testnet or not\n"
64 " \"keypoololdest\": xxxxxx, (numeric) the timestamp (seconds since Unix epoch) of the oldest pre-generated key in the key pool\n"
65 " \"keypoolsize\": xxxx, (numeric) how many new keys are pre-generated\n"
66 " \"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"
67 " \"paytxfee\": x.xxxx, (numeric) the transaction fee set in " + CURRENCY_UNIT + "/kB\n"
68 " \"relayfee\": x.xxxx, (numeric) minimum relay fee for transactions in " + CURRENCY_UNIT + "/kB\n"
69 " \"errors\": \"...\" (string) any error messages\n"
70 "}\n"
71 "\nExamples:\n"
72 + HelpExampleCli("getinfo", "")
73 + HelpExampleRpc("getinfo", "")
76 #ifdef ENABLE_WALLET
77 CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
79 LOCK2(cs_main, pwallet ? &pwallet->cs_wallet : NULL);
80 #else
81 LOCK(cs_main);
82 #endif
84 proxyType proxy;
85 GetProxy(NET_IPV4, proxy);
87 UniValue obj(UniValue::VOBJ);
88 obj.push_back(Pair("version", CLIENT_VERSION));
89 obj.push_back(Pair("protocolversion", PROTOCOL_VERSION));
90 #ifdef ENABLE_WALLET
91 if (pwallet) {
92 obj.push_back(Pair("walletversion", pwallet->GetVersion()));
93 obj.push_back(Pair("balance", ValueFromAmount(pwallet->GetBalance())));
95 #endif
96 obj.push_back(Pair("blocks", (int)chainActive.Height()));
97 obj.push_back(Pair("timeoffset", GetTimeOffset()));
98 if(g_connman)
99 obj.push_back(Pair("connections", (int)g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL)));
100 obj.push_back(Pair("proxy", (proxy.IsValid() ? proxy.proxy.ToStringIPPort() : std::string())));
101 obj.push_back(Pair("difficulty", (double)GetDifficulty()));
102 obj.push_back(Pair("testnet", Params().NetworkIDString() == CBaseChainParams::TESTNET));
103 #ifdef ENABLE_WALLET
104 if (pwallet) {
105 obj.push_back(Pair("keypoololdest", pwallet->GetOldestKeyPoolTime()));
106 obj.push_back(Pair("keypoolsize", (int)pwallet->GetKeyPoolSize()));
108 if (pwallet && pwallet->IsCrypted()) {
109 obj.push_back(Pair("unlocked_until", pwallet->nRelockTime));
111 obj.push_back(Pair("paytxfee", ValueFromAmount(payTxFee.GetFeePerK())));
112 #endif
113 obj.push_back(Pair("relayfee", ValueFromAmount(::minRelayTxFee.GetFeePerK())));
114 obj.push_back(Pair("errors", GetWarnings("statusbar")));
115 return obj;
118 #ifdef ENABLE_WALLET
119 class DescribeAddressVisitor : public boost::static_visitor<UniValue>
121 public:
122 CWallet * const pwallet;
124 DescribeAddressVisitor(CWallet *_pwallet) : pwallet(_pwallet) {}
126 UniValue operator()(const CNoDestination &dest) const { return UniValue(UniValue::VOBJ); }
128 UniValue operator()(const CKeyID &keyID) const {
129 UniValue obj(UniValue::VOBJ);
130 CPubKey vchPubKey;
131 obj.push_back(Pair("isscript", false));
132 if (pwallet && pwallet->GetPubKey(keyID, vchPubKey)) {
133 obj.push_back(Pair("pubkey", HexStr(vchPubKey)));
134 obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed()));
136 return obj;
139 UniValue operator()(const CScriptID &scriptID) const {
140 UniValue obj(UniValue::VOBJ);
141 CScript subscript;
142 obj.push_back(Pair("isscript", true));
143 if (pwallet && pwallet->GetCScript(scriptID, subscript)) {
144 std::vector<CTxDestination> addresses;
145 txnouttype whichType;
146 int nRequired;
147 ExtractDestinations(subscript, whichType, addresses, nRequired);
148 obj.push_back(Pair("script", GetTxnOutputType(whichType)));
149 obj.push_back(Pair("hex", HexStr(subscript.begin(), subscript.end())));
150 UniValue a(UniValue::VARR);
151 for (const CTxDestination& addr : addresses)
152 a.push_back(CBitcoinAddress(addr).ToString());
153 obj.push_back(Pair("addresses", a));
154 if (whichType == TX_MULTISIG)
155 obj.push_back(Pair("sigsrequired", nRequired));
157 return obj;
160 #endif
162 UniValue validateaddress(const JSONRPCRequest& request)
164 if (request.fHelp || request.params.size() != 1)
165 throw std::runtime_error(
166 "validateaddress \"address\"\n"
167 "\nReturn information about the given bitcoin address.\n"
168 "\nArguments:\n"
169 "1. \"address\" (string, required) The bitcoin address to validate\n"
170 "\nResult:\n"
171 "{\n"
172 " \"isvalid\" : true|false, (boolean) If the address is valid or not. If not, this is the only property returned.\n"
173 " \"address\" : \"address\", (string) The bitcoin address validated\n"
174 " \"scriptPubKey\" : \"hex\", (string) The hex encoded scriptPubKey generated by the address\n"
175 " \"ismine\" : true|false, (boolean) If the address is yours or not\n"
176 " \"iswatchonly\" : true|false, (boolean) If the address is watchonly\n"
177 " \"isscript\" : true|false, (boolean) If the key is a script\n"
178 " \"script\" : \"type\" (string, optional) The output script type. Possible types: nonstandard, pubkey, pubkeyhash, scripthash, multisig, nulldata, witness_v0_keyhash, witness_v0_scripthash\n"
179 " \"hex\" : \"hex\", (string, optional) The redeemscript for the p2sh address\n"
180 " \"addresses\" (string, optional) Array of addresses associated with the known redeemscript\n"
181 " [\n"
182 " \"address\"\n"
183 " ,...\n"
184 " ]\n"
185 " \"sigsrequired\" : xxxxx (numeric, optional) Number of signatures required to spend multisig output\n"
186 " \"pubkey\" : \"publickeyhex\", (string) The hex value of the raw public key\n"
187 " \"iscompressed\" : true|false, (boolean) If the address is compressed\n"
188 " \"account\" : \"account\" (string) DEPRECATED. The account associated with the address, \"\" is the default account\n"
189 " \"timestamp\" : timestamp, (number, optional) The creation time of the key if available in seconds since epoch (Jan 1 1970 GMT)\n"
190 " \"hdkeypath\" : \"keypath\" (string, optional) The HD keypath if the key is HD and available\n"
191 " \"hdmasterkeyid\" : \"<hash160>\" (string, optional) The Hash160 of the HD master pubkey\n"
192 "}\n"
193 "\nExamples:\n"
194 + HelpExampleCli("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"")
195 + HelpExampleRpc("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"")
198 #ifdef ENABLE_WALLET
199 CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
201 LOCK2(cs_main, pwallet ? &pwallet->cs_wallet : NULL);
202 #else
203 LOCK(cs_main);
204 #endif
206 CBitcoinAddress address(request.params[0].get_str());
207 bool isValid = address.IsValid();
209 UniValue ret(UniValue::VOBJ);
210 ret.push_back(Pair("isvalid", isValid));
211 if (isValid)
213 CTxDestination dest = address.Get();
214 std::string currentAddress = address.ToString();
215 ret.push_back(Pair("address", currentAddress));
217 CScript scriptPubKey = GetScriptForDestination(dest);
218 ret.push_back(Pair("scriptPubKey", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
220 #ifdef ENABLE_WALLET
221 isminetype mine = pwallet ? IsMine(*pwallet, dest) : ISMINE_NO;
222 ret.push_back(Pair("ismine", bool(mine & ISMINE_SPENDABLE)));
223 ret.push_back(Pair("iswatchonly", bool(mine & ISMINE_WATCH_ONLY)));
224 UniValue detail = boost::apply_visitor(DescribeAddressVisitor(pwallet), dest);
225 ret.pushKVs(detail);
226 if (pwallet && pwallet->mapAddressBook.count(dest)) {
227 ret.push_back(Pair("account", pwallet->mapAddressBook[dest].name));
229 CKeyID keyID;
230 if (pwallet) {
231 const auto& meta = pwallet->mapKeyMetadata;
232 auto it = address.GetKeyID(keyID) ? meta.find(keyID) : meta.end();
233 if (it == meta.end()) {
234 it = meta.find(CScriptID(scriptPubKey));
236 if (it != meta.end()) {
237 ret.push_back(Pair("timestamp", it->second.nCreateTime));
238 if (!it->second.hdKeypath.empty()) {
239 ret.push_back(Pair("hdkeypath", it->second.hdKeypath));
240 ret.push_back(Pair("hdmasterkeyid", it->second.hdMasterKeyID.GetHex()));
244 #endif
246 return ret;
249 // Needed even with !ENABLE_WALLET, to pass (ignored) pointers around
250 class CWallet;
253 * Used by addmultisigaddress / createmultisig:
255 CScript _createmultisig_redeemScript(CWallet * const pwallet, const UniValue& params)
257 int nRequired = params[0].get_int();
258 const UniValue& keys = params[1].get_array();
260 // Gather public keys
261 if (nRequired < 1)
262 throw std::runtime_error("a multisignature address must require at least one key to redeem");
263 if ((int)keys.size() < nRequired)
264 throw std::runtime_error(
265 strprintf("not enough keys supplied "
266 "(got %u keys, but need at least %d to redeem)", keys.size(), nRequired));
267 if (keys.size() > 16)
268 throw std::runtime_error("Number of addresses involved in the multisignature address creation > 16\nReduce the number");
269 std::vector<CPubKey> pubkeys;
270 pubkeys.resize(keys.size());
271 for (unsigned int i = 0; i < keys.size(); i++)
273 const std::string& ks = keys[i].get_str();
274 #ifdef ENABLE_WALLET
275 // Case 1: Bitcoin address and we have full public key:
276 CBitcoinAddress address(ks);
277 if (pwallet && address.IsValid()) {
278 CKeyID keyID;
279 if (!address.GetKeyID(keyID))
280 throw std::runtime_error(
281 strprintf("%s does not refer to a key",ks));
282 CPubKey vchPubKey;
283 if (!pwallet->GetPubKey(keyID, vchPubKey)) {
284 throw std::runtime_error(
285 strprintf("no full public key for address %s",ks));
287 if (!vchPubKey.IsFullyValid())
288 throw std::runtime_error(" Invalid public key: "+ks);
289 pubkeys[i] = vchPubKey;
292 // Case 2: hex public key
293 else
294 #endif
295 if (IsHex(ks))
297 CPubKey vchPubKey(ParseHex(ks));
298 if (!vchPubKey.IsFullyValid())
299 throw std::runtime_error(" Invalid public key: "+ks);
300 pubkeys[i] = vchPubKey;
302 else
304 throw std::runtime_error(" Invalid public key: "+ks);
307 CScript result = GetScriptForMultisig(nRequired, pubkeys);
309 if (result.size() > MAX_SCRIPT_ELEMENT_SIZE)
310 throw std::runtime_error(
311 strprintf("redeemScript exceeds size limit: %d > %d", result.size(), MAX_SCRIPT_ELEMENT_SIZE));
313 return result;
316 UniValue createmultisig(const JSONRPCRequest& request)
318 #ifdef ENABLE_WALLET
319 CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
320 #else
321 CWallet * const pwallet = NULL;
322 #endif
324 if (request.fHelp || request.params.size() < 2 || request.params.size() > 2)
326 std::string msg = "createmultisig nrequired [\"key\",...]\n"
327 "\nCreates a multi-signature address with n signature of m keys required.\n"
328 "It returns a json object with the address and redeemScript.\n"
330 "\nArguments:\n"
331 "1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n"
332 "2. \"keys\" (string, required) A json array of keys which are bitcoin addresses or hex-encoded public keys\n"
333 " [\n"
334 " \"key\" (string) bitcoin address or hex-encoded public key\n"
335 " ,...\n"
336 " ]\n"
338 "\nResult:\n"
339 "{\n"
340 " \"address\":\"multisigaddress\", (string) The value of the new multisig address.\n"
341 " \"redeemScript\":\"script\" (string) The string value of the hex-encoded redemption script.\n"
342 "}\n"
344 "\nExamples:\n"
345 "\nCreate a multisig address from 2 addresses\n"
346 + HelpExampleCli("createmultisig", "2 \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"") +
347 "\nAs a json rpc call\n"
348 + HelpExampleRpc("createmultisig", "2, \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"")
350 throw std::runtime_error(msg);
353 // Construct using pay-to-script-hash:
354 CScript inner = _createmultisig_redeemScript(pwallet, request.params);
355 CScriptID innerID(inner);
356 CBitcoinAddress address(innerID);
358 UniValue result(UniValue::VOBJ);
359 result.push_back(Pair("address", address.ToString()));
360 result.push_back(Pair("redeemScript", HexStr(inner.begin(), inner.end())));
362 return result;
365 UniValue verifymessage(const JSONRPCRequest& request)
367 if (request.fHelp || request.params.size() != 3)
368 throw std::runtime_error(
369 "verifymessage \"address\" \"signature\" \"message\"\n"
370 "\nVerify a signed message\n"
371 "\nArguments:\n"
372 "1. \"address\" (string, required) The bitcoin address to use for the signature.\n"
373 "2. \"signature\" (string, required) The signature provided by the signer in base 64 encoding (see signmessage).\n"
374 "3. \"message\" (string, required) The message that was signed.\n"
375 "\nResult:\n"
376 "true|false (boolean) If the signature is verified or not.\n"
377 "\nExamples:\n"
378 "\nUnlock the wallet for 30 seconds\n"
379 + HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") +
380 "\nCreate the signature\n"
381 + HelpExampleCli("signmessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"my message\"") +
382 "\nVerify the signature\n"
383 + HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"signature\" \"my message\"") +
384 "\nAs json rpc\n"
385 + HelpExampleRpc("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\", \"signature\", \"my message\"")
388 LOCK(cs_main);
390 std::string strAddress = request.params[0].get_str();
391 std::string strSign = request.params[1].get_str();
392 std::string strMessage = request.params[2].get_str();
394 CBitcoinAddress addr(strAddress);
395 if (!addr.IsValid())
396 throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
398 CKeyID keyID;
399 if (!addr.GetKeyID(keyID))
400 throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
402 bool fInvalid = false;
403 std::vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);
405 if (fInvalid)
406 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding");
408 CHashWriter ss(SER_GETHASH, 0);
409 ss << strMessageMagic;
410 ss << strMessage;
412 CPubKey pubkey;
413 if (!pubkey.RecoverCompact(ss.GetHash(), vchSig))
414 return false;
416 return (pubkey.GetID() == keyID);
419 UniValue signmessagewithprivkey(const JSONRPCRequest& request)
421 if (request.fHelp || request.params.size() != 2)
422 throw std::runtime_error(
423 "signmessagewithprivkey \"privkey\" \"message\"\n"
424 "\nSign a message with the private key of an address\n"
425 "\nArguments:\n"
426 "1. \"privkey\" (string, required) The private key to sign the message with.\n"
427 "2. \"message\" (string, required) The message to create a signature of.\n"
428 "\nResult:\n"
429 "\"signature\" (string) The signature of the message encoded in base 64\n"
430 "\nExamples:\n"
431 "\nCreate the signature\n"
432 + HelpExampleCli("signmessagewithprivkey", "\"privkey\" \"my message\"") +
433 "\nVerify the signature\n"
434 + HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"signature\" \"my message\"") +
435 "\nAs json rpc\n"
436 + HelpExampleRpc("signmessagewithprivkey", "\"privkey\", \"my message\"")
439 std::string strPrivkey = request.params[0].get_str();
440 std::string strMessage = request.params[1].get_str();
442 CBitcoinSecret vchSecret;
443 bool fGood = vchSecret.SetString(strPrivkey);
444 if (!fGood)
445 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
446 CKey key = vchSecret.GetKey();
447 if (!key.IsValid())
448 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
450 CHashWriter ss(SER_GETHASH, 0);
451 ss << strMessageMagic;
452 ss << strMessage;
454 std::vector<unsigned char> vchSig;
455 if (!key.SignCompact(ss.GetHash(), vchSig))
456 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
458 return EncodeBase64(&vchSig[0], vchSig.size());
461 UniValue setmocktime(const JSONRPCRequest& request)
463 if (request.fHelp || request.params.size() != 1)
464 throw std::runtime_error(
465 "setmocktime timestamp\n"
466 "\nSet the local time to given timestamp (-regtest only)\n"
467 "\nArguments:\n"
468 "1. timestamp (integer, required) Unix seconds-since-epoch timestamp\n"
469 " Pass 0 to go back to using the system time."
472 if (!Params().MineBlocksOnDemand())
473 throw std::runtime_error("setmocktime for regression testing (-regtest mode) only");
475 // For now, don't change mocktime if we're in the middle of validation, as
476 // this could have an effect on mempool time-based eviction, as well as
477 // IsCurrentForFeeEstimation() and IsInitialBlockDownload().
478 // TODO: figure out the right way to synchronize around mocktime, and
479 // ensure all call sites of GetTime() are accessing this safely.
480 LOCK(cs_main);
482 RPCTypeCheck(request.params, {UniValue::VNUM});
483 SetMockTime(request.params[0].get_int64());
485 return NullUniValue;
488 static UniValue RPCLockedMemoryInfo()
490 LockedPool::Stats stats = LockedPoolManager::Instance().stats();
491 UniValue obj(UniValue::VOBJ);
492 obj.push_back(Pair("used", uint64_t(stats.used)));
493 obj.push_back(Pair("free", uint64_t(stats.free)));
494 obj.push_back(Pair("total", uint64_t(stats.total)));
495 obj.push_back(Pair("locked", uint64_t(stats.locked)));
496 obj.push_back(Pair("chunks_used", uint64_t(stats.chunks_used)));
497 obj.push_back(Pair("chunks_free", uint64_t(stats.chunks_free)));
498 return obj;
501 #ifdef HAVE_MALLOC_INFO
502 static std::string RPCMallocInfo()
504 char *ptr = nullptr;
505 size_t size = 0;
506 FILE *f = open_memstream(&ptr, &size);
507 if (f) {
508 malloc_info(0, f);
509 fclose(f);
510 if (ptr) {
511 std::string rv(ptr, size);
512 free(ptr);
513 return rv;
516 return "";
518 #endif
520 UniValue getmemoryinfo(const JSONRPCRequest& request)
522 /* Please, avoid using the word "pool" here in the RPC interface or help,
523 * as users will undoubtedly confuse it with the other "memory pool"
525 if (request.fHelp || request.params.size() > 1)
526 throw std::runtime_error(
527 "getmemoryinfo (\"mode\")\n"
528 "Returns an object containing information about memory usage.\n"
529 "Arguments:\n"
530 "1. \"mode\" determines what kind of information is returned. This argument is optional, the default mode is \"stats\".\n"
531 " - \"stats\" returns general statistics about memory usage in the daemon.\n"
532 " - \"mallocinfo\" returns an XML string describing low-level heap state (only available if compiled with glibc 2.10+).\n"
533 "\nResult (mode \"stats\"):\n"
534 "{\n"
535 " \"locked\": { (json object) Information about locked memory manager\n"
536 " \"used\": xxxxx, (numeric) Number of bytes used\n"
537 " \"free\": xxxxx, (numeric) Number of bytes available in current arenas\n"
538 " \"total\": xxxxxxx, (numeric) Total number of bytes managed\n"
539 " \"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"
540 " \"chunks_used\": xxxxx, (numeric) Number allocated chunks\n"
541 " \"chunks_free\": xxxxx, (numeric) Number unused chunks\n"
542 " }\n"
543 "}\n"
544 "\nResult (mode \"mallocinfo\"):\n"
545 "\"<malloc version=\"1\">...\"\n"
546 "\nExamples:\n"
547 + HelpExampleCli("getmemoryinfo", "")
548 + HelpExampleRpc("getmemoryinfo", "")
551 std::string mode = (request.params.size() < 1 || request.params[0].isNull()) ? "stats" : request.params[0].get_str();
552 if (mode == "stats") {
553 UniValue obj(UniValue::VOBJ);
554 obj.push_back(Pair("locked", RPCLockedMemoryInfo()));
555 return obj;
556 } else if (mode == "mallocinfo") {
557 #ifdef HAVE_MALLOC_INFO
558 return RPCMallocInfo();
559 #else
560 throw JSONRPCError(RPC_INVALID_PARAMETER, "mallocinfo is only available when compiled with glibc 2.10+");
561 #endif
562 } else {
563 throw JSONRPCError(RPC_INVALID_PARAMETER, "unknown mode " + mode);
567 uint32_t getCategoryMask(UniValue cats) {
568 cats = cats.get_array();
569 uint32_t mask = 0;
570 for (unsigned int i = 0; i < cats.size(); ++i) {
571 uint32_t flag = 0;
572 std::string cat = cats[i].get_str();
573 if (!GetLogCategory(&flag, &cat)) {
574 throw JSONRPCError(RPC_INVALID_PARAMETER, "unknown logging category " + cat);
576 mask |= flag;
578 return mask;
581 UniValue logging(const JSONRPCRequest& request)
583 if (request.fHelp || request.params.size() > 2) {
584 throw std::runtime_error(
585 "logging [include,...] <exclude>\n"
586 "Gets and sets the logging configuration.\n"
587 "When called without an argument, returns the list of categories that are currently being debug logged.\n"
588 "When called with arguments, adds or removes categories from debug logging.\n"
589 "The valid logging categories are: " + ListLogCategories() + "\n"
590 "libevent logging is configured on startup and cannot be modified by this RPC during runtime."
591 "Arguments:\n"
592 "1. \"include\" (array of strings) add debug logging for these categories.\n"
593 "2. \"exclude\" (array of strings) remove debug logging for these categories.\n"
594 "\nResult: <categories> (string): a list of the logging categories that are active.\n"
595 "\nExamples:\n"
596 + HelpExampleCli("logging", "\"[\\\"all\\\"]\" \"[\\\"http\\\"]\"")
597 + HelpExampleRpc("logging", "[\"all\"], \"[libevent]\"")
601 uint32_t originalLogCategories = logCategories;
602 if (request.params.size() > 0 && request.params[0].isArray()) {
603 logCategories |= getCategoryMask(request.params[0]);
606 if (request.params.size() > 1 && request.params[1].isArray()) {
607 logCategories &= ~getCategoryMask(request.params[1]);
610 // Update libevent logging if BCLog::LIBEVENT has changed.
611 // If the library version doesn't allow it, UpdateHTTPServerLogging() returns false,
612 // in which case we should clear the BCLog::LIBEVENT flag.
613 // Throw an error if the user has explicitly asked to change only the libevent
614 // flag and it failed.
615 uint32_t changedLogCategories = originalLogCategories ^ logCategories;
616 if (changedLogCategories & BCLog::LIBEVENT) {
617 if (!UpdateHTTPServerLogging(logCategories & BCLog::LIBEVENT)) {
618 logCategories &= ~BCLog::LIBEVENT;
619 if (changedLogCategories == BCLog::LIBEVENT) {
620 throw JSONRPCError(RPC_INVALID_PARAMETER, "libevent logging cannot be updated when using libevent before v2.1.1.");
625 UniValue result(UniValue::VOBJ);
626 std::vector<CLogCategoryActive> vLogCatActive = ListActiveLogCategories();
627 for (const auto& logCatActive : vLogCatActive) {
628 result.pushKV(logCatActive.category, logCatActive.active);
631 return result;
634 UniValue echo(const JSONRPCRequest& request)
636 if (request.fHelp)
637 throw std::runtime_error(
638 "echo|echojson \"message\" ...\n"
639 "\nSimply echo back the input arguments. This command is for testing.\n"
640 "\nThe difference between echo and echojson is that echojson has argument conversion enabled in the client-side table in"
641 "bitcoin-cli and the GUI. There is no server-side difference."
644 return request.params;
647 static const CRPCCommand commands[] =
648 { // category name actor (function) okSafeMode
649 // --------------------- ------------------------ ----------------------- ----------
650 { "control", "getinfo", &getinfo, true, {} }, /* uses wallet if enabled */
651 { "control", "getmemoryinfo", &getmemoryinfo, true, {"mode"} },
652 { "util", "validateaddress", &validateaddress, true, {"address"} }, /* uses wallet if enabled */
653 { "util", "createmultisig", &createmultisig, true, {"nrequired","keys"} },
654 { "util", "verifymessage", &verifymessage, true, {"address","signature","message"} },
655 { "util", "signmessagewithprivkey", &signmessagewithprivkey, true, {"privkey","message"} },
657 /* Not shown in help */
658 { "hidden", "setmocktime", &setmocktime, true, {"timestamp"}},
659 { "hidden", "echo", &echo, true, {"arg0","arg1","arg2","arg3","arg4","arg5","arg6","arg7","arg8","arg9"}},
660 { "hidden", "echojson", &echo, true, {"arg0","arg1","arg2","arg3","arg4","arg5","arg6","arg7","arg8","arg9"}},
661 { "hidden", "logging", &logging, true, {"include", "exclude"}},
664 void RegisterMiscRPCCommands(CRPCTable &t)
666 for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
667 t.appendCommand(commands[vcidx].name, &commands[vcidx]);