You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

misc.cpp 29KB

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