Use list initialization (C++11) for maps/vectors instead of boost::assign::map_list_o...
[bitcoinplatinum.git] / src / rpc / misc.cpp
blobf6f01eef4b609db2f10e0c2a41cede6cdde5d8a1
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
25 #include <stdint.h>
26 #ifdef HAVE_MALLOC_INFO
27 #include <malloc.h>
28 #endif
30 #include <univalue.h>
32 /**
33 * @note Do not add or change anything in the information returned by this
34 * method. `getinfo` exists for backwards-compatibility only. It combines
35 * information from wildly different sources in the program, which is a mess,
36 * and is thus planned to be deprecated eventually.
38 * Based on the source of the information, new information should be added to:
39 * - `getblockchaininfo`,
40 * - `getnetworkinfo` or
41 * - `getwalletinfo`
43 * Or alternatively, create a specific query method for the information.
44 **/
45 UniValue getinfo(const JSONRPCRequest& request)
47 if (request.fHelp || request.params.size() != 0)
48 throw std::runtime_error(
49 "getinfo\n"
50 "\nDEPRECATED. Returns an object containing various state info.\n"
51 "\nResult:\n"
52 "{\n"
53 " \"version\": xxxxx, (numeric) the server version\n"
54 " \"protocolversion\": xxxxx, (numeric) the protocol version\n"
55 " \"walletversion\": xxxxx, (numeric) the wallet version\n"
56 " \"balance\": xxxxxxx, (numeric) the total bitcoin balance of the wallet\n"
57 " \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n"
58 " \"timeoffset\": xxxxx, (numeric) the time offset\n"
59 " \"connections\": xxxxx, (numeric) the number of connections\n"
60 " \"proxy\": \"host:port\", (string, optional) the proxy used by the server\n"
61 " \"difficulty\": xxxxxx, (numeric) the current difficulty\n"
62 " \"testnet\": true|false, (boolean) if the server is using testnet or not\n"
63 " \"keypoololdest\": xxxxxx, (numeric) the timestamp (seconds since Unix epoch) of the oldest pre-generated key in the key pool\n"
64 " \"keypoolsize\": xxxx, (numeric) how many new keys are pre-generated\n"
65 " \"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"
66 " \"paytxfee\": x.xxxx, (numeric) the transaction fee set in " + CURRENCY_UNIT + "/kB\n"
67 " \"relayfee\": x.xxxx, (numeric) minimum relay fee for transactions in " + CURRENCY_UNIT + "/kB\n"
68 " \"errors\": \"...\" (string) any error messages\n"
69 "}\n"
70 "\nExamples:\n"
71 + HelpExampleCli("getinfo", "")
72 + HelpExampleRpc("getinfo", "")
75 #ifdef ENABLE_WALLET
76 CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
78 LOCK2(cs_main, pwallet ? &pwallet->cs_wallet : NULL);
79 #else
80 LOCK(cs_main);
81 #endif
83 proxyType proxy;
84 GetProxy(NET_IPV4, proxy);
86 UniValue obj(UniValue::VOBJ);
87 obj.push_back(Pair("version", CLIENT_VERSION));
88 obj.push_back(Pair("protocolversion", PROTOCOL_VERSION));
89 #ifdef ENABLE_WALLET
90 if (pwallet) {
91 obj.push_back(Pair("walletversion", pwallet->GetVersion()));
92 obj.push_back(Pair("balance", ValueFromAmount(pwallet->GetBalance())));
94 #endif
95 obj.push_back(Pair("blocks", (int)chainActive.Height()));
96 obj.push_back(Pair("timeoffset", GetTimeOffset()));
97 if(g_connman)
98 obj.push_back(Pair("connections", (int)g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL)));
99 obj.push_back(Pair("proxy", (proxy.IsValid() ? proxy.proxy.ToStringIPPort() : std::string())));
100 obj.push_back(Pair("difficulty", (double)GetDifficulty()));
101 obj.push_back(Pair("testnet", Params().NetworkIDString() == CBaseChainParams::TESTNET));
102 #ifdef ENABLE_WALLET
103 if (pwallet) {
104 obj.push_back(Pair("keypoololdest", pwallet->GetOldestKeyPoolTime()));
105 obj.push_back(Pair("keypoolsize", (int)pwallet->GetKeyPoolSize()));
107 if (pwallet && pwallet->IsCrypted()) {
108 obj.push_back(Pair("unlocked_until", pwallet->nRelockTime));
110 obj.push_back(Pair("paytxfee", ValueFromAmount(payTxFee.GetFeePerK())));
111 #endif
112 obj.push_back(Pair("relayfee", ValueFromAmount(::minRelayTxFee.GetFeePerK())));
113 obj.push_back(Pair("errors", GetWarnings("statusbar")));
114 return obj;
117 #ifdef ENABLE_WALLET
118 class DescribeAddressVisitor : public boost::static_visitor<UniValue>
120 public:
121 CWallet * const pwallet;
123 DescribeAddressVisitor(CWallet *_pwallet) : pwallet(_pwallet) {}
125 UniValue operator()(const CNoDestination &dest) const { return UniValue(UniValue::VOBJ); }
127 UniValue operator()(const CKeyID &keyID) const {
128 UniValue obj(UniValue::VOBJ);
129 CPubKey vchPubKey;
130 obj.push_back(Pair("isscript", false));
131 if (pwallet && pwallet->GetPubKey(keyID, vchPubKey)) {
132 obj.push_back(Pair("pubkey", HexStr(vchPubKey)));
133 obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed()));
135 return obj;
138 UniValue operator()(const CScriptID &scriptID) const {
139 UniValue obj(UniValue::VOBJ);
140 CScript subscript;
141 obj.push_back(Pair("isscript", true));
142 if (pwallet && pwallet->GetCScript(scriptID, subscript)) {
143 std::vector<CTxDestination> addresses;
144 txnouttype whichType;
145 int nRequired;
146 ExtractDestinations(subscript, whichType, addresses, nRequired);
147 obj.push_back(Pair("script", GetTxnOutputType(whichType)));
148 obj.push_back(Pair("hex", HexStr(subscript.begin(), subscript.end())));
149 UniValue a(UniValue::VARR);
150 BOOST_FOREACH(const CTxDestination& addr, addresses)
151 a.push_back(CBitcoinAddress(addr).ToString());
152 obj.push_back(Pair("addresses", a));
153 if (whichType == TX_MULTISIG)
154 obj.push_back(Pair("sigsrequired", nRequired));
156 return obj;
159 #endif
161 UniValue validateaddress(const JSONRPCRequest& request)
163 if (request.fHelp || request.params.size() != 1)
164 throw std::runtime_error(
165 "validateaddress \"address\"\n"
166 "\nReturn information about the given bitcoin address.\n"
167 "\nArguments:\n"
168 "1. \"address\" (string, required) The bitcoin address to validate\n"
169 "\nResult:\n"
170 "{\n"
171 " \"isvalid\" : true|false, (boolean) If the address is valid or not. If not, this is the only property returned.\n"
172 " \"address\" : \"address\", (string) The bitcoin address validated\n"
173 " \"scriptPubKey\" : \"hex\", (string) The hex encoded scriptPubKey generated by the address\n"
174 " \"ismine\" : true|false, (boolean) If the address is yours or not\n"
175 " \"iswatchonly\" : true|false, (boolean) If the address is watchonly\n"
176 " \"isscript\" : true|false, (boolean) If the key is a script\n"
177 " \"pubkey\" : \"publickeyhex\", (string) The hex value of the raw public key\n"
178 " \"iscompressed\" : true|false, (boolean) If the address is compressed\n"
179 " \"account\" : \"account\" (string) DEPRECATED. The account associated with the address, \"\" is the default account\n"
180 " \"timestamp\" : timestamp, (number, optional) The creation time of the key if available in seconds since epoch (Jan 1 1970 GMT)\n"
181 " \"hdkeypath\" : \"keypath\" (string, optional) The HD keypath if the key is HD and available\n"
182 " \"hdmasterkeyid\" : \"<hash160>\" (string, optional) The Hash160 of the HD master pubkey\n"
183 "}\n"
184 "\nExamples:\n"
185 + HelpExampleCli("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"")
186 + HelpExampleRpc("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"")
189 #ifdef ENABLE_WALLET
190 CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
192 LOCK2(cs_main, pwallet ? &pwallet->cs_wallet : NULL);
193 #else
194 LOCK(cs_main);
195 #endif
197 CBitcoinAddress address(request.params[0].get_str());
198 bool isValid = address.IsValid();
200 UniValue ret(UniValue::VOBJ);
201 ret.push_back(Pair("isvalid", isValid));
202 if (isValid)
204 CTxDestination dest = address.Get();
205 std::string currentAddress = address.ToString();
206 ret.push_back(Pair("address", currentAddress));
208 CScript scriptPubKey = GetScriptForDestination(dest);
209 ret.push_back(Pair("scriptPubKey", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
211 #ifdef ENABLE_WALLET
212 isminetype mine = pwallet ? IsMine(*pwallet, dest) : ISMINE_NO;
213 ret.push_back(Pair("ismine", (mine & ISMINE_SPENDABLE) ? true : false));
214 ret.push_back(Pair("iswatchonly", (mine & ISMINE_WATCH_ONLY) ? true: false));
215 UniValue detail = boost::apply_visitor(DescribeAddressVisitor(pwallet), dest);
216 ret.pushKVs(detail);
217 if (pwallet && pwallet->mapAddressBook.count(dest)) {
218 ret.push_back(Pair("account", pwallet->mapAddressBook[dest].name));
220 CKeyID keyID;
221 if (pwallet) {
222 const auto& meta = pwallet->mapKeyMetadata;
223 auto it = address.GetKeyID(keyID) ? meta.find(keyID) : meta.end();
224 if (it == meta.end()) {
225 it = meta.find(CScriptID(scriptPubKey));
227 if (it != meta.end()) {
228 ret.push_back(Pair("timestamp", it->second.nCreateTime));
229 if (!it->second.hdKeypath.empty()) {
230 ret.push_back(Pair("hdkeypath", it->second.hdKeypath));
231 ret.push_back(Pair("hdmasterkeyid", it->second.hdMasterKeyID.GetHex()));
235 #endif
237 return ret;
240 // Needed even with !ENABLE_WALLET, to pass (ignored) pointers around
241 class CWallet;
244 * Used by addmultisigaddress / createmultisig:
246 CScript _createmultisig_redeemScript(CWallet * const pwallet, const UniValue& params)
248 int nRequired = params[0].get_int();
249 const UniValue& keys = params[1].get_array();
251 // Gather public keys
252 if (nRequired < 1)
253 throw std::runtime_error("a multisignature address must require at least one key to redeem");
254 if ((int)keys.size() < nRequired)
255 throw std::runtime_error(
256 strprintf("not enough keys supplied "
257 "(got %u keys, but need at least %d to redeem)", keys.size(), nRequired));
258 if (keys.size() > 16)
259 throw std::runtime_error("Number of addresses involved in the multisignature address creation > 16\nReduce the number");
260 std::vector<CPubKey> pubkeys;
261 pubkeys.resize(keys.size());
262 for (unsigned int i = 0; i < keys.size(); i++)
264 const std::string& ks = keys[i].get_str();
265 #ifdef ENABLE_WALLET
266 // Case 1: Bitcoin address and we have full public key:
267 CBitcoinAddress address(ks);
268 if (pwallet && address.IsValid()) {
269 CKeyID keyID;
270 if (!address.GetKeyID(keyID))
271 throw std::runtime_error(
272 strprintf("%s does not refer to a key",ks));
273 CPubKey vchPubKey;
274 if (!pwallet->GetPubKey(keyID, vchPubKey)) {
275 throw std::runtime_error(
276 strprintf("no full public key for address %s",ks));
278 if (!vchPubKey.IsFullyValid())
279 throw std::runtime_error(" Invalid public key: "+ks);
280 pubkeys[i] = vchPubKey;
283 // Case 2: hex public key
284 else
285 #endif
286 if (IsHex(ks))
288 CPubKey vchPubKey(ParseHex(ks));
289 if (!vchPubKey.IsFullyValid())
290 throw std::runtime_error(" Invalid public key: "+ks);
291 pubkeys[i] = vchPubKey;
293 else
295 throw std::runtime_error(" Invalid public key: "+ks);
298 CScript result = GetScriptForMultisig(nRequired, pubkeys);
300 if (result.size() > MAX_SCRIPT_ELEMENT_SIZE)
301 throw std::runtime_error(
302 strprintf("redeemScript exceeds size limit: %d > %d", result.size(), MAX_SCRIPT_ELEMENT_SIZE));
304 return result;
307 UniValue createmultisig(const JSONRPCRequest& request)
309 #ifdef ENABLE_WALLET
310 CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
311 #else
312 CWallet * const pwallet = NULL;
313 #endif
315 if (request.fHelp || request.params.size() < 2 || request.params.size() > 2)
317 std::string msg = "createmultisig nrequired [\"key\",...]\n"
318 "\nCreates a multi-signature address with n signature of m keys required.\n"
319 "It returns a json object with the address and redeemScript.\n"
321 "\nArguments:\n"
322 "1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n"
323 "2. \"keys\" (string, required) A json array of keys which are bitcoin addresses or hex-encoded public keys\n"
324 " [\n"
325 " \"key\" (string) bitcoin address or hex-encoded public key\n"
326 " ,...\n"
327 " ]\n"
329 "\nResult:\n"
330 "{\n"
331 " \"address\":\"multisigaddress\", (string) The value of the new multisig address.\n"
332 " \"redeemScript\":\"script\" (string) The string value of the hex-encoded redemption script.\n"
333 "}\n"
335 "\nExamples:\n"
336 "\nCreate a multisig address from 2 addresses\n"
337 + HelpExampleCli("createmultisig", "2 \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"") +
338 "\nAs a json rpc call\n"
339 + HelpExampleRpc("createmultisig", "2, \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"")
341 throw std::runtime_error(msg);
344 // Construct using pay-to-script-hash:
345 CScript inner = _createmultisig_redeemScript(pwallet, request.params);
346 CScriptID innerID(inner);
347 CBitcoinAddress address(innerID);
349 UniValue result(UniValue::VOBJ);
350 result.push_back(Pair("address", address.ToString()));
351 result.push_back(Pair("redeemScript", HexStr(inner.begin(), inner.end())));
353 return result;
356 UniValue verifymessage(const JSONRPCRequest& request)
358 if (request.fHelp || request.params.size() != 3)
359 throw std::runtime_error(
360 "verifymessage \"address\" \"signature\" \"message\"\n"
361 "\nVerify a signed message\n"
362 "\nArguments:\n"
363 "1. \"address\" (string, required) The bitcoin address to use for the signature.\n"
364 "2. \"signature\" (string, required) The signature provided by the signer in base 64 encoding (see signmessage).\n"
365 "3. \"message\" (string, required) The message that was signed.\n"
366 "\nResult:\n"
367 "true|false (boolean) If the signature is verified or not.\n"
368 "\nExamples:\n"
369 "\nUnlock the wallet for 30 seconds\n"
370 + HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") +
371 "\nCreate the signature\n"
372 + HelpExampleCli("signmessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"my message\"") +
373 "\nVerify the signature\n"
374 + HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"signature\" \"my message\"") +
375 "\nAs json rpc\n"
376 + HelpExampleRpc("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\", \"signature\", \"my message\"")
379 LOCK(cs_main);
381 std::string strAddress = request.params[0].get_str();
382 std::string strSign = request.params[1].get_str();
383 std::string strMessage = request.params[2].get_str();
385 CBitcoinAddress addr(strAddress);
386 if (!addr.IsValid())
387 throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
389 CKeyID keyID;
390 if (!addr.GetKeyID(keyID))
391 throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
393 bool fInvalid = false;
394 std::vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);
396 if (fInvalid)
397 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding");
399 CHashWriter ss(SER_GETHASH, 0);
400 ss << strMessageMagic;
401 ss << strMessage;
403 CPubKey pubkey;
404 if (!pubkey.RecoverCompact(ss.GetHash(), vchSig))
405 return false;
407 return (pubkey.GetID() == keyID);
410 UniValue signmessagewithprivkey(const JSONRPCRequest& request)
412 if (request.fHelp || request.params.size() != 2)
413 throw std::runtime_error(
414 "signmessagewithprivkey \"privkey\" \"message\"\n"
415 "\nSign a message with the private key of an address\n"
416 "\nArguments:\n"
417 "1. \"privkey\" (string, required) The private key to sign the message with.\n"
418 "2. \"message\" (string, required) The message to create a signature of.\n"
419 "\nResult:\n"
420 "\"signature\" (string) The signature of the message encoded in base 64\n"
421 "\nExamples:\n"
422 "\nCreate the signature\n"
423 + HelpExampleCli("signmessagewithprivkey", "\"privkey\" \"my message\"") +
424 "\nVerify the signature\n"
425 + HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"signature\" \"my message\"") +
426 "\nAs json rpc\n"
427 + HelpExampleRpc("signmessagewithprivkey", "\"privkey\", \"my message\"")
430 std::string strPrivkey = request.params[0].get_str();
431 std::string strMessage = request.params[1].get_str();
433 CBitcoinSecret vchSecret;
434 bool fGood = vchSecret.SetString(strPrivkey);
435 if (!fGood)
436 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
437 CKey key = vchSecret.GetKey();
438 if (!key.IsValid())
439 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
441 CHashWriter ss(SER_GETHASH, 0);
442 ss << strMessageMagic;
443 ss << strMessage;
445 std::vector<unsigned char> vchSig;
446 if (!key.SignCompact(ss.GetHash(), vchSig))
447 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
449 return EncodeBase64(&vchSig[0], vchSig.size());
452 UniValue setmocktime(const JSONRPCRequest& request)
454 if (request.fHelp || request.params.size() != 1)
455 throw std::runtime_error(
456 "setmocktime timestamp\n"
457 "\nSet the local time to given timestamp (-regtest only)\n"
458 "\nArguments:\n"
459 "1. timestamp (integer, required) Unix seconds-since-epoch timestamp\n"
460 " Pass 0 to go back to using the system time."
463 if (!Params().MineBlocksOnDemand())
464 throw std::runtime_error("setmocktime for regression testing (-regtest mode) only");
466 // For now, don't change mocktime if we're in the middle of validation, as
467 // this could have an effect on mempool time-based eviction, as well as
468 // IsCurrentForFeeEstimation() and IsInitialBlockDownload().
469 // TODO: figure out the right way to synchronize around mocktime, and
470 // ensure all call sites of GetTime() are accessing this safely.
471 LOCK(cs_main);
473 RPCTypeCheck(request.params, {UniValue::VNUM});
474 SetMockTime(request.params[0].get_int64());
476 return NullUniValue;
479 static UniValue RPCLockedMemoryInfo()
481 LockedPool::Stats stats = LockedPoolManager::Instance().stats();
482 UniValue obj(UniValue::VOBJ);
483 obj.push_back(Pair("used", uint64_t(stats.used)));
484 obj.push_back(Pair("free", uint64_t(stats.free)));
485 obj.push_back(Pair("total", uint64_t(stats.total)));
486 obj.push_back(Pair("locked", uint64_t(stats.locked)));
487 obj.push_back(Pair("chunks_used", uint64_t(stats.chunks_used)));
488 obj.push_back(Pair("chunks_free", uint64_t(stats.chunks_free)));
489 return obj;
492 #ifdef HAVE_MALLOC_INFO
493 static std::string RPCMallocInfo()
495 char *ptr = nullptr;
496 size_t size = 0;
497 FILE *f = open_memstream(&ptr, &size);
498 if (f) {
499 malloc_info(0, f);
500 fclose(f);
501 if (ptr) {
502 std::string rv(ptr, size);
503 free(ptr);
504 return rv;
507 return "";
509 #endif
511 UniValue getmemoryinfo(const JSONRPCRequest& request)
513 /* Please, avoid using the word "pool" here in the RPC interface or help,
514 * as users will undoubtedly confuse it with the other "memory pool"
516 if (request.fHelp || request.params.size() > 1)
517 throw std::runtime_error(
518 "getmemoryinfo (\"mode\")\n"
519 "Returns an object containing information about memory usage.\n"
520 "Arguments:\n"
521 "1. \"mode\" determines what kind of information is returned. This argument is optional, the default mode is \"stats\".\n"
522 " - \"stats\" returns general statistics about memory usage in the daemon.\n"
523 " - \"mallocinfo\" returns an XML string describing low-level heap state (only available if compiled with glibc 2.10+).\n"
524 "\nResult (mode \"stats\"):\n"
525 "{\n"
526 " \"locked\": { (json object) Information about locked memory manager\n"
527 " \"used\": xxxxx, (numeric) Number of bytes used\n"
528 " \"free\": xxxxx, (numeric) Number of bytes available in current arenas\n"
529 " \"total\": xxxxxxx, (numeric) Total number of bytes managed\n"
530 " \"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"
531 " \"chunks_used\": xxxxx, (numeric) Number allocated chunks\n"
532 " \"chunks_free\": xxxxx, (numeric) Number unused chunks\n"
533 " }\n"
534 "}\n"
535 "\nResult (mode \"mallocinfo\"):\n"
536 "\"<malloc version=\"1\">...\"\n"
537 "\nExamples:\n"
538 + HelpExampleCli("getmemoryinfo", "")
539 + HelpExampleRpc("getmemoryinfo", "")
542 std::string mode = (request.params.size() < 1 || request.params[0].isNull()) ? "stats" : request.params[0].get_str();
543 if (mode == "stats") {
544 UniValue obj(UniValue::VOBJ);
545 obj.push_back(Pair("locked", RPCLockedMemoryInfo()));
546 return obj;
547 } else if (mode == "mallocinfo") {
548 #ifdef HAVE_MALLOC_INFO
549 return RPCMallocInfo();
550 #else
551 throw JSONRPCError(RPC_INVALID_PARAMETER, "mallocinfo is only available when compiled with glibc 2.10+");
552 #endif
553 } else {
554 throw JSONRPCError(RPC_INVALID_PARAMETER, "unknown mode " + mode);
558 uint32_t getCategoryMask(UniValue cats) {
559 cats = cats.get_array();
560 uint32_t mask = 0;
561 for (unsigned int i = 0; i < cats.size(); ++i) {
562 uint32_t flag = 0;
563 std::string cat = cats[i].get_str();
564 if (!GetLogCategory(&flag, &cat)) {
565 throw JSONRPCError(RPC_INVALID_PARAMETER, "unknown logging category " + cat);
567 mask |= flag;
569 return mask;
572 UniValue logging(const JSONRPCRequest& request)
574 if (request.fHelp || request.params.size() > 2) {
575 throw std::runtime_error(
576 "logging [include,...] <exclude>\n"
577 "Gets and sets the logging configuration.\n"
578 "When called without an argument, returns the list of categories that are currently being debug logged.\n"
579 "When called with arguments, adds or removes categories from debug logging.\n"
580 "The valid logging categories are: " + ListLogCategories() + "\n"
581 "libevent logging is configured on startup and cannot be modified by this RPC during runtime."
582 "Arguments:\n"
583 "1. \"include\" (array of strings) add debug logging for these categories.\n"
584 "2. \"exclude\" (array of strings) remove debug logging for these categories.\n"
585 "\nResult: <categories> (string): a list of the logging categories that are active.\n"
586 "\nExamples:\n"
587 + HelpExampleCli("logging", "\"[\\\"all\\\"]\" \"[\\\"http\\\"]\"")
588 + HelpExampleRpc("logging", "[\"all\"], \"[libevent]\"")
592 uint32_t originalLogCategories = logCategories;
593 if (request.params.size() > 0 && request.params[0].isArray()) {
594 logCategories |= getCategoryMask(request.params[0]);
597 if (request.params.size() > 1 && request.params[1].isArray()) {
598 logCategories &= ~getCategoryMask(request.params[1]);
601 // Update libevent logging if BCLog::LIBEVENT has changed.
602 // If the library version doesn't allow it, UpdateHTTPServerLogging() returns false,
603 // in which case we should clear the BCLog::LIBEVENT flag.
604 // Throw an error if the user has explicitly asked to change only the libevent
605 // flag and it failed.
606 uint32_t changedLogCategories = originalLogCategories ^ logCategories;
607 if (changedLogCategories & BCLog::LIBEVENT) {
608 if (!UpdateHTTPServerLogging(logCategories & BCLog::LIBEVENT)) {
609 logCategories &= ~BCLog::LIBEVENT;
610 if (changedLogCategories == BCLog::LIBEVENT) {
611 throw JSONRPCError(RPC_INVALID_PARAMETER, "libevent logging cannot be updated when using libevent before v2.1.1.");
616 UniValue result(UniValue::VOBJ);
617 std::vector<CLogCategoryActive> vLogCatActive = ListActiveLogCategories();
618 for (const auto& logCatActive : vLogCatActive) {
619 result.pushKV(logCatActive.category, logCatActive.active);
622 return result;
625 UniValue echo(const JSONRPCRequest& request)
627 if (request.fHelp)
628 throw std::runtime_error(
629 "echo|echojson \"message\" ...\n"
630 "\nSimply echo back the input arguments. This command is for testing.\n"
631 "\nThe difference between echo and echojson is that echojson has argument conversion enabled in the client-side table in"
632 "bitcoin-cli and the GUI. There is no server-side difference."
635 return request.params;
638 static const CRPCCommand commands[] =
639 { // category name actor (function) okSafeMode
640 // --------------------- ------------------------ ----------------------- ----------
641 { "control", "getinfo", &getinfo, true, {} }, /* uses wallet if enabled */
642 { "control", "getmemoryinfo", &getmemoryinfo, true, {"mode"} },
643 { "util", "validateaddress", &validateaddress, true, {"address"} }, /* uses wallet if enabled */
644 { "util", "createmultisig", &createmultisig, true, {"nrequired","keys"} },
645 { "util", "verifymessage", &verifymessage, true, {"address","signature","message"} },
646 { "util", "signmessagewithprivkey", &signmessagewithprivkey, true, {"privkey","message"} },
648 /* Not shown in help */
649 { "hidden", "setmocktime", &setmocktime, true, {"timestamp"}},
650 { "hidden", "echo", &echo, true, {"arg0","arg1","arg2","arg3","arg4","arg5","arg6","arg7","arg8","arg9"}},
651 { "hidden", "echojson", &echo, true, {"arg0","arg1","arg2","arg3","arg4","arg5","arg6","arg7","arg8","arg9"}},
652 { "hidden", "logging", &logging, true, {"include", "exclude"}},
655 void RegisterMiscRPCCommands(CRPCTable &t)
657 for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
658 t.appendCommand(commands[vcidx].name, &commands[vcidx]);