PageRenderTime 1079ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/src/rpc/misc.cpp

https://github.com/bitcoin/bitcoin
C++ | 833 lines | 716 code | 75 blank | 42 comment | 74 complexity | 9cd2997d1f1fc9664aab57244a7d7876 MD5 | raw file
  1. // Copyright (c) 2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2021 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.
  5. #include <httpserver.h>
  6. #include <index/blockfilterindex.h>
  7. #include <index/coinstatsindex.h>
  8. #include <index/txindex.h>
  9. #include <interfaces/chain.h>
  10. #include <interfaces/echo.h>
  11. #include <interfaces/init.h>
  12. #include <interfaces/ipc.h>
  13. #include <key_io.h>
  14. #include <node/context.h>
  15. #include <outputtype.h>
  16. #include <rpc/blockchain.h>
  17. #include <rpc/server.h>
  18. #include <rpc/server_util.h>
  19. #include <rpc/util.h>
  20. #include <scheduler.h>
  21. #include <script/descriptor.h>
  22. #include <util/check.h>
  23. #include <util/message.h> // For MessageSign(), MessageVerify()
  24. #include <util/strencodings.h>
  25. #include <util/syscall_sandbox.h>
  26. #include <util/system.h>
  27. #include <optional>
  28. #include <stdint.h>
  29. #include <tuple>
  30. #ifdef HAVE_MALLOC_INFO
  31. #include <malloc.h>
  32. #endif
  33. #include <univalue.h>
  34. using node::NodeContext;
  35. static RPCHelpMan validateaddress()
  36. {
  37. return RPCHelpMan{
  38. "validateaddress",
  39. "\nReturn information about the given bitcoin address.\n",
  40. {
  41. {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The bitcoin address to validate"},
  42. },
  43. RPCResult{
  44. RPCResult::Type::OBJ, "", "",
  45. {
  46. {RPCResult::Type::BOOL, "isvalid", "If the address is valid or not"},
  47. {RPCResult::Type::STR, "address", /*optional=*/true, "The bitcoin address validated"},
  48. {RPCResult::Type::STR_HEX, "scriptPubKey", /*optional=*/true, "The hex-encoded scriptPubKey generated by the address"},
  49. {RPCResult::Type::BOOL, "isscript", /*optional=*/true, "If the key is a script"},
  50. {RPCResult::Type::BOOL, "iswitness", /*optional=*/true, "If the address is a witness address"},
  51. {RPCResult::Type::NUM, "witness_version", /*optional=*/true, "The version number of the witness program"},
  52. {RPCResult::Type::STR_HEX, "witness_program", /*optional=*/true, "The hex value of the witness program"},
  53. {RPCResult::Type::STR, "error", /*optional=*/true, "Error message, if any"},
  54. {RPCResult::Type::ARR, "error_locations", /*optional=*/true, "Indices of likely error locations in address, if known (e.g. Bech32 errors)",
  55. {
  56. {RPCResult::Type::NUM, "index", "index of a potential error"},
  57. }},
  58. }
  59. },
  60. RPCExamples{
  61. HelpExampleCli("validateaddress", "\"" + EXAMPLE_ADDRESS[0] + "\"") +
  62. HelpExampleRpc("validateaddress", "\"" + EXAMPLE_ADDRESS[0] + "\"")
  63. },
  64. [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
  65. {
  66. std::string error_msg;
  67. std::vector<int> error_locations;
  68. CTxDestination dest = DecodeDestination(request.params[0].get_str(), error_msg, &error_locations);
  69. const bool isValid = IsValidDestination(dest);
  70. CHECK_NONFATAL(isValid == error_msg.empty());
  71. UniValue ret(UniValue::VOBJ);
  72. ret.pushKV("isvalid", isValid);
  73. if (isValid) {
  74. std::string currentAddress = EncodeDestination(dest);
  75. ret.pushKV("address", currentAddress);
  76. CScript scriptPubKey = GetScriptForDestination(dest);
  77. ret.pushKV("scriptPubKey", HexStr(scriptPubKey));
  78. UniValue detail = DescribeAddress(dest);
  79. ret.pushKVs(detail);
  80. } else {
  81. UniValue error_indices(UniValue::VARR);
  82. for (int i : error_locations) error_indices.push_back(i);
  83. ret.pushKV("error_locations", error_indices);
  84. ret.pushKV("error", error_msg);
  85. }
  86. return ret;
  87. },
  88. };
  89. }
  90. static RPCHelpMan createmultisig()
  91. {
  92. return RPCHelpMan{"createmultisig",
  93. "\nCreates a multi-signature address with n signature of m keys required.\n"
  94. "It returns a json object with the address and redeemScript.\n",
  95. {
  96. {"nrequired", RPCArg::Type::NUM, RPCArg::Optional::NO, "The number of required signatures out of the n keys."},
  97. {"keys", RPCArg::Type::ARR, RPCArg::Optional::NO, "The hex-encoded public keys.",
  98. {
  99. {"key", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "The hex-encoded public key"},
  100. }},
  101. {"address_type", RPCArg::Type::STR, RPCArg::Default{"legacy"}, "The address type to use. Options are \"legacy\", \"p2sh-segwit\", and \"bech32\"."},
  102. },
  103. RPCResult{
  104. RPCResult::Type::OBJ, "", "",
  105. {
  106. {RPCResult::Type::STR, "address", "The value of the new multisig address."},
  107. {RPCResult::Type::STR_HEX, "redeemScript", "The string value of the hex-encoded redemption script."},
  108. {RPCResult::Type::STR, "descriptor", "The descriptor for this multisig"},
  109. {RPCResult::Type::ARR, "warnings", /* optional */ true, "Any warnings resulting from the creation of this multisig",
  110. {
  111. {RPCResult::Type::STR, "", ""},
  112. }},
  113. }
  114. },
  115. RPCExamples{
  116. "\nCreate a multisig address from 2 public keys\n"
  117. + HelpExampleCli("createmultisig", "2 \"[\\\"03789ed0bb717d88f7d321a368d905e7430207ebbd82bd342cf11ae157a7ace5fd\\\",\\\"03dbc6764b8884a92e871274b87583e6d5c2a58819473e17e107ef3f6aa5a61626\\\"]\"") +
  118. "\nAs a JSON-RPC call\n"
  119. + HelpExampleRpc("createmultisig", "2, [\"03789ed0bb717d88f7d321a368d905e7430207ebbd82bd342cf11ae157a7ace5fd\",\"03dbc6764b8884a92e871274b87583e6d5c2a58819473e17e107ef3f6aa5a61626\"]")
  120. },
  121. [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
  122. {
  123. int required = request.params[0].get_int();
  124. // Get the public keys
  125. const UniValue& keys = request.params[1].get_array();
  126. std::vector<CPubKey> pubkeys;
  127. for (unsigned int i = 0; i < keys.size(); ++i) {
  128. if (IsHex(keys[i].get_str()) && (keys[i].get_str().length() == 66 || keys[i].get_str().length() == 130)) {
  129. pubkeys.push_back(HexToPubKey(keys[i].get_str()));
  130. } else {
  131. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Invalid public key: %s\n.", keys[i].get_str()));
  132. }
  133. }
  134. // Get the output type
  135. OutputType output_type = OutputType::LEGACY;
  136. if (!request.params[2].isNull()) {
  137. std::optional<OutputType> parsed = ParseOutputType(request.params[2].get_str());
  138. if (!parsed) {
  139. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Unknown address type '%s'", request.params[2].get_str()));
  140. } else if (parsed.value() == OutputType::BECH32M) {
  141. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "createmultisig cannot create bech32m multisig addresses");
  142. }
  143. output_type = parsed.value();
  144. }
  145. // Construct using pay-to-script-hash:
  146. FillableSigningProvider keystore;
  147. CScript inner;
  148. const CTxDestination dest = AddAndGetMultisigDestination(required, pubkeys, output_type, keystore, inner);
  149. // Make the descriptor
  150. std::unique_ptr<Descriptor> descriptor = InferDescriptor(GetScriptForDestination(dest), keystore);
  151. UniValue result(UniValue::VOBJ);
  152. result.pushKV("address", EncodeDestination(dest));
  153. result.pushKV("redeemScript", HexStr(inner));
  154. result.pushKV("descriptor", descriptor->ToString());
  155. UniValue warnings(UniValue::VARR);
  156. if (!request.params[2].isNull() && OutputTypeFromDestination(dest) != output_type) {
  157. // Only warns if the user has explicitly chosen an address type we cannot generate
  158. warnings.push_back("Unable to make chosen address type, please ensure no uncompressed public keys are present.");
  159. }
  160. if (warnings.size()) result.pushKV("warnings", warnings);
  161. return result;
  162. },
  163. };
  164. }
  165. static RPCHelpMan getdescriptorinfo()
  166. {
  167. const std::string EXAMPLE_DESCRIPTOR = "wpkh([d34db33f/84h/0h/0h]0279be667ef9dcbbac55a06295Ce870b07029Bfcdb2dce28d959f2815b16f81798)";
  168. return RPCHelpMan{"getdescriptorinfo",
  169. {"\nAnalyses a descriptor.\n"},
  170. {
  171. {"descriptor", RPCArg::Type::STR, RPCArg::Optional::NO, "The descriptor."},
  172. },
  173. RPCResult{
  174. RPCResult::Type::OBJ, "", "",
  175. {
  176. {RPCResult::Type::STR, "descriptor", "The descriptor in canonical form, without private keys"},
  177. {RPCResult::Type::STR, "checksum", "The checksum for the input descriptor"},
  178. {RPCResult::Type::BOOL, "isrange", "Whether the descriptor is ranged"},
  179. {RPCResult::Type::BOOL, "issolvable", "Whether the descriptor is solvable"},
  180. {RPCResult::Type::BOOL, "hasprivatekeys", "Whether the input descriptor contained at least one private key"},
  181. }
  182. },
  183. RPCExamples{
  184. "Analyse a descriptor\n" +
  185. HelpExampleCli("getdescriptorinfo", "\"" + EXAMPLE_DESCRIPTOR + "\"") +
  186. HelpExampleRpc("getdescriptorinfo", "\"" + EXAMPLE_DESCRIPTOR + "\"")
  187. },
  188. [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
  189. {
  190. RPCTypeCheck(request.params, {UniValue::VSTR});
  191. FlatSigningProvider provider;
  192. std::string error;
  193. auto desc = Parse(request.params[0].get_str(), provider, error);
  194. if (!desc) {
  195. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error);
  196. }
  197. UniValue result(UniValue::VOBJ);
  198. result.pushKV("descriptor", desc->ToString());
  199. result.pushKV("checksum", GetDescriptorChecksum(request.params[0].get_str()));
  200. result.pushKV("isrange", desc->IsRange());
  201. result.pushKV("issolvable", desc->IsSolvable());
  202. result.pushKV("hasprivatekeys", provider.keys.size() > 0);
  203. return result;
  204. },
  205. };
  206. }
  207. static RPCHelpMan deriveaddresses()
  208. {
  209. const std::string EXAMPLE_DESCRIPTOR = "wpkh([d34db33f/84h/0h/0h]xpub6DJ2dNUysrn5Vt36jH2KLBT2i1auw1tTSSomg8PhqNiUtx8QX2SvC9nrHu81fT41fvDUnhMjEzQgXnQjKEu3oaqMSzhSrHMxyyoEAmUHQbY/0/*)#cjjspncu";
  210. return RPCHelpMan{"deriveaddresses",
  211. {"\nDerives one or more addresses corresponding to an output descriptor.\n"
  212. "Examples of output descriptors are:\n"
  213. " pkh(<pubkey>) P2PKH outputs for the given pubkey\n"
  214. " wpkh(<pubkey>) Native segwit P2PKH outputs for the given pubkey\n"
  215. " sh(multi(<n>,<pubkey>,<pubkey>,...)) P2SH-multisig outputs for the given threshold and pubkeys\n"
  216. " raw(<hex script>) Outputs whose scriptPubKey equals the specified hex scripts\n"
  217. "\nIn the above, <pubkey> either refers to a fixed public key in hexadecimal notation, or to an xpub/xprv optionally followed by one\n"
  218. "or more path elements separated by \"/\", where \"h\" represents a hardened child key.\n"
  219. "For more information on output descriptors, see the documentation in the doc/descriptors.md file.\n"},
  220. {
  221. {"descriptor", RPCArg::Type::STR, RPCArg::Optional::NO, "The descriptor."},
  222. {"range", RPCArg::Type::RANGE, RPCArg::Optional::OMITTED_NAMED_ARG, "If a ranged descriptor is used, this specifies the end or the range (in [begin,end] notation) to derive."},
  223. },
  224. RPCResult{
  225. RPCResult::Type::ARR, "", "",
  226. {
  227. {RPCResult::Type::STR, "address", "the derived addresses"},
  228. }
  229. },
  230. RPCExamples{
  231. "First three native segwit receive addresses\n" +
  232. HelpExampleCli("deriveaddresses", "\"" + EXAMPLE_DESCRIPTOR + "\" \"[0,2]\"") +
  233. HelpExampleRpc("deriveaddresses", "\"" + EXAMPLE_DESCRIPTOR + "\", \"[0,2]\"")
  234. },
  235. [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
  236. {
  237. RPCTypeCheck(request.params, {UniValue::VSTR, UniValueType()}); // Range argument is checked later
  238. const std::string desc_str = request.params[0].get_str();
  239. int64_t range_begin = 0;
  240. int64_t range_end = 0;
  241. if (request.params.size() >= 2 && !request.params[1].isNull()) {
  242. std::tie(range_begin, range_end) = ParseDescriptorRange(request.params[1]);
  243. }
  244. FlatSigningProvider key_provider;
  245. std::string error;
  246. auto desc = Parse(desc_str, key_provider, error, /* require_checksum = */ true);
  247. if (!desc) {
  248. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error);
  249. }
  250. if (!desc->IsRange() && request.params.size() > 1) {
  251. throw JSONRPCError(RPC_INVALID_PARAMETER, "Range should not be specified for an un-ranged descriptor");
  252. }
  253. if (desc->IsRange() && request.params.size() == 1) {
  254. throw JSONRPCError(RPC_INVALID_PARAMETER, "Range must be specified for a ranged descriptor");
  255. }
  256. UniValue addresses(UniValue::VARR);
  257. for (int i = range_begin; i <= range_end; ++i) {
  258. FlatSigningProvider provider;
  259. std::vector<CScript> scripts;
  260. if (!desc->Expand(i, key_provider, scripts, provider)) {
  261. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Cannot derive script without private keys");
  262. }
  263. for (const CScript &script : scripts) {
  264. CTxDestination dest;
  265. if (!ExtractDestination(script, dest)) {
  266. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Descriptor does not have a corresponding address");
  267. }
  268. addresses.push_back(EncodeDestination(dest));
  269. }
  270. }
  271. // This should not be possible, but an assert seems overkill:
  272. if (addresses.empty()) {
  273. throw JSONRPCError(RPC_MISC_ERROR, "Unexpected empty result");
  274. }
  275. return addresses;
  276. },
  277. };
  278. }
  279. static RPCHelpMan verifymessage()
  280. {
  281. return RPCHelpMan{"verifymessage",
  282. "Verify a signed message.",
  283. {
  284. {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The bitcoin address to use for the signature."},
  285. {"signature", RPCArg::Type::STR, RPCArg::Optional::NO, "The signature provided by the signer in base 64 encoding (see signmessage)."},
  286. {"message", RPCArg::Type::STR, RPCArg::Optional::NO, "The message that was signed."},
  287. },
  288. RPCResult{
  289. RPCResult::Type::BOOL, "", "If the signature is verified or not."
  290. },
  291. RPCExamples{
  292. "\nUnlock the wallet for 30 seconds\n"
  293. + HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") +
  294. "\nCreate the signature\n"
  295. + HelpExampleCli("signmessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"my message\"") +
  296. "\nVerify the signature\n"
  297. + HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"signature\" \"my message\"") +
  298. "\nAs a JSON-RPC call\n"
  299. + HelpExampleRpc("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\", \"signature\", \"my message\"")
  300. },
  301. [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
  302. {
  303. LOCK(cs_main);
  304. std::string strAddress = request.params[0].get_str();
  305. std::string strSign = request.params[1].get_str();
  306. std::string strMessage = request.params[2].get_str();
  307. switch (MessageVerify(strAddress, strSign, strMessage)) {
  308. case MessageVerificationResult::ERR_INVALID_ADDRESS:
  309. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
  310. case MessageVerificationResult::ERR_ADDRESS_NO_KEY:
  311. throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
  312. case MessageVerificationResult::ERR_MALFORMED_SIGNATURE:
  313. throw JSONRPCError(RPC_TYPE_ERROR, "Malformed base64 encoding");
  314. case MessageVerificationResult::ERR_PUBKEY_NOT_RECOVERED:
  315. case MessageVerificationResult::ERR_NOT_SIGNED:
  316. return false;
  317. case MessageVerificationResult::OK:
  318. return true;
  319. }
  320. return false;
  321. },
  322. };
  323. }
  324. static RPCHelpMan signmessagewithprivkey()
  325. {
  326. return RPCHelpMan{"signmessagewithprivkey",
  327. "\nSign a message with the private key of an address\n",
  328. {
  329. {"privkey", RPCArg::Type::STR, RPCArg::Optional::NO, "The private key to sign the message with."},
  330. {"message", RPCArg::Type::STR, RPCArg::Optional::NO, "The message to create a signature of."},
  331. },
  332. RPCResult{
  333. RPCResult::Type::STR, "signature", "The signature of the message encoded in base 64"
  334. },
  335. RPCExamples{
  336. "\nCreate the signature\n"
  337. + HelpExampleCli("signmessagewithprivkey", "\"privkey\" \"my message\"") +
  338. "\nVerify the signature\n"
  339. + HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"signature\" \"my message\"") +
  340. "\nAs a JSON-RPC call\n"
  341. + HelpExampleRpc("signmessagewithprivkey", "\"privkey\", \"my message\"")
  342. },
  343. [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
  344. {
  345. std::string strPrivkey = request.params[0].get_str();
  346. std::string strMessage = request.params[1].get_str();
  347. CKey key = DecodeSecret(strPrivkey);
  348. if (!key.IsValid()) {
  349. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
  350. }
  351. std::string signature;
  352. if (!MessageSign(key, strMessage, signature)) {
  353. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
  354. }
  355. return signature;
  356. },
  357. };
  358. }
  359. static RPCHelpMan setmocktime()
  360. {
  361. return RPCHelpMan{"setmocktime",
  362. "\nSet the local time to given timestamp (-regtest only)\n",
  363. {
  364. {"timestamp", RPCArg::Type::NUM, RPCArg::Optional::NO, UNIX_EPOCH_TIME + "\n"
  365. "Pass 0 to go back to using the system time."},
  366. },
  367. RPCResult{RPCResult::Type::NONE, "", ""},
  368. RPCExamples{""},
  369. [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
  370. {
  371. if (!Params().IsMockableChain()) {
  372. throw std::runtime_error("setmocktime is for regression testing (-regtest mode) only");
  373. }
  374. // For now, don't change mocktime if we're in the middle of validation, as
  375. // this could have an effect on mempool time-based eviction, as well as
  376. // IsCurrentForFeeEstimation() and IsInitialBlockDownload().
  377. // TODO: figure out the right way to synchronize around mocktime, and
  378. // ensure all call sites of GetTime() are accessing this safely.
  379. LOCK(cs_main);
  380. RPCTypeCheck(request.params, {UniValue::VNUM});
  381. const int64_t time{request.params[0].get_int64()};
  382. if (time < 0) {
  383. throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Mocktime can not be negative: %s.", time));
  384. }
  385. SetMockTime(time);
  386. auto node_context = util::AnyPtr<NodeContext>(request.context);
  387. if (node_context) {
  388. for (const auto& chain_client : node_context->chain_clients) {
  389. chain_client->setMockTime(time);
  390. }
  391. }
  392. return NullUniValue;
  393. },
  394. };
  395. }
  396. #if defined(USE_SYSCALL_SANDBOX)
  397. static RPCHelpMan invokedisallowedsyscall()
  398. {
  399. return RPCHelpMan{
  400. "invokedisallowedsyscall",
  401. "\nInvoke a disallowed syscall to trigger a syscall sandbox violation. Used for testing purposes.\n",
  402. {},
  403. RPCResult{RPCResult::Type::NONE, "", ""},
  404. RPCExamples{
  405. HelpExampleCli("invokedisallowedsyscall", "") + HelpExampleRpc("invokedisallowedsyscall", "")},
  406. [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue {
  407. if (!Params().IsTestChain()) {
  408. throw std::runtime_error("invokedisallowedsyscall is used for testing only.");
  409. }
  410. TestDisallowedSandboxCall();
  411. return NullUniValue;
  412. },
  413. };
  414. }
  415. #endif // USE_SYSCALL_SANDBOX
  416. static RPCHelpMan mockscheduler()
  417. {
  418. return RPCHelpMan{"mockscheduler",
  419. "\nBump the scheduler into the future (-regtest only)\n",
  420. {
  421. {"delta_time", RPCArg::Type::NUM, RPCArg::Optional::NO, "Number of seconds to forward the scheduler into the future." },
  422. },
  423. RPCResult{RPCResult::Type::NONE, "", ""},
  424. RPCExamples{""},
  425. [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
  426. {
  427. if (!Params().IsMockableChain()) {
  428. throw std::runtime_error("mockscheduler is for regression testing (-regtest mode) only");
  429. }
  430. // check params are valid values
  431. RPCTypeCheck(request.params, {UniValue::VNUM});
  432. int64_t delta_seconds = request.params[0].get_int64();
  433. if (delta_seconds <= 0 || delta_seconds > 3600) {
  434. throw std::runtime_error("delta_time must be between 1 and 3600 seconds (1 hr)");
  435. }
  436. auto node_context = util::AnyPtr<NodeContext>(request.context);
  437. // protect against null pointer dereference
  438. CHECK_NONFATAL(node_context);
  439. CHECK_NONFATAL(node_context->scheduler);
  440. node_context->scheduler->MockForward(std::chrono::seconds(delta_seconds));
  441. return NullUniValue;
  442. },
  443. };
  444. }
  445. static UniValue RPCLockedMemoryInfo()
  446. {
  447. LockedPool::Stats stats = LockedPoolManager::Instance().stats();
  448. UniValue obj(UniValue::VOBJ);
  449. obj.pushKV("used", uint64_t(stats.used));
  450. obj.pushKV("free", uint64_t(stats.free));
  451. obj.pushKV("total", uint64_t(stats.total));
  452. obj.pushKV("locked", uint64_t(stats.locked));
  453. obj.pushKV("chunks_used", uint64_t(stats.chunks_used));
  454. obj.pushKV("chunks_free", uint64_t(stats.chunks_free));
  455. return obj;
  456. }
  457. #ifdef HAVE_MALLOC_INFO
  458. static std::string RPCMallocInfo()
  459. {
  460. char *ptr = nullptr;
  461. size_t size = 0;
  462. FILE *f = open_memstream(&ptr, &size);
  463. if (f) {
  464. malloc_info(0, f);
  465. fclose(f);
  466. if (ptr) {
  467. std::string rv(ptr, size);
  468. free(ptr);
  469. return rv;
  470. }
  471. }
  472. return "";
  473. }
  474. #endif
  475. static RPCHelpMan getmemoryinfo()
  476. {
  477. /* Please, avoid using the word "pool" here in the RPC interface or help,
  478. * as users will undoubtedly confuse it with the other "memory pool"
  479. */
  480. return RPCHelpMan{"getmemoryinfo",
  481. "Returns an object containing information about memory usage.\n",
  482. {
  483. {"mode", RPCArg::Type::STR, RPCArg::Default{"stats"}, "determines what kind of information is returned.\n"
  484. " - \"stats\" returns general statistics about memory usage in the daemon.\n"
  485. " - \"mallocinfo\" returns an XML string describing low-level heap state (only available if compiled with glibc 2.10+)."},
  486. },
  487. {
  488. RPCResult{"mode \"stats\"",
  489. RPCResult::Type::OBJ, "", "",
  490. {
  491. {RPCResult::Type::OBJ, "locked", "Information about locked memory manager",
  492. {
  493. {RPCResult::Type::NUM, "used", "Number of bytes used"},
  494. {RPCResult::Type::NUM, "free", "Number of bytes available in current arenas"},
  495. {RPCResult::Type::NUM, "total", "Total number of bytes managed"},
  496. {RPCResult::Type::NUM, "locked", "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."},
  497. {RPCResult::Type::NUM, "chunks_used", "Number allocated chunks"},
  498. {RPCResult::Type::NUM, "chunks_free", "Number unused chunks"},
  499. }},
  500. }
  501. },
  502. RPCResult{"mode \"mallocinfo\"",
  503. RPCResult::Type::STR, "", "\"<malloc version=\"1\">...\""
  504. },
  505. },
  506. RPCExamples{
  507. HelpExampleCli("getmemoryinfo", "")
  508. + HelpExampleRpc("getmemoryinfo", "")
  509. },
  510. [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
  511. {
  512. std::string mode = request.params[0].isNull() ? "stats" : request.params[0].get_str();
  513. if (mode == "stats") {
  514. UniValue obj(UniValue::VOBJ);
  515. obj.pushKV("locked", RPCLockedMemoryInfo());
  516. return obj;
  517. } else if (mode == "mallocinfo") {
  518. #ifdef HAVE_MALLOC_INFO
  519. return RPCMallocInfo();
  520. #else
  521. throw JSONRPCError(RPC_INVALID_PARAMETER, "mallocinfo mode not available");
  522. #endif
  523. } else {
  524. throw JSONRPCError(RPC_INVALID_PARAMETER, "unknown mode " + mode);
  525. }
  526. },
  527. };
  528. }
  529. static void EnableOrDisableLogCategories(UniValue cats, bool enable) {
  530. cats = cats.get_array();
  531. for (unsigned int i = 0; i < cats.size(); ++i) {
  532. std::string cat = cats[i].get_str();
  533. bool success;
  534. if (enable) {
  535. success = LogInstance().EnableCategory(cat);
  536. } else {
  537. success = LogInstance().DisableCategory(cat);
  538. }
  539. if (!success) {
  540. throw JSONRPCError(RPC_INVALID_PARAMETER, "unknown logging category " + cat);
  541. }
  542. }
  543. }
  544. static RPCHelpMan logging()
  545. {
  546. return RPCHelpMan{"logging",
  547. "Gets and sets the logging configuration.\n"
  548. "When called without an argument, returns the list of categories with status that are currently being debug logged or not.\n"
  549. "When called with arguments, adds or removes categories from debug logging and return the lists above.\n"
  550. "The arguments are evaluated in order \"include\", \"exclude\".\n"
  551. "If an item is both included and excluded, it will thus end up being excluded.\n"
  552. "The valid logging categories are: " + LogInstance().LogCategoriesString() + "\n"
  553. "In addition, the following are available as category names with special meanings:\n"
  554. " - \"all\", \"1\" : represent all logging categories.\n"
  555. " - \"none\", \"0\" : even if other logging categories are specified, ignore all of them.\n"
  556. ,
  557. {
  558. {"include", RPCArg::Type::ARR, RPCArg::Optional::OMITTED_NAMED_ARG, "The categories to add to debug logging",
  559. {
  560. {"include_category", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "the valid logging category"},
  561. }},
  562. {"exclude", RPCArg::Type::ARR, RPCArg::Optional::OMITTED_NAMED_ARG, "The categories to remove from debug logging",
  563. {
  564. {"exclude_category", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "the valid logging category"},
  565. }},
  566. },
  567. RPCResult{
  568. RPCResult::Type::OBJ_DYN, "", "keys are the logging categories, and values indicates its status",
  569. {
  570. {RPCResult::Type::BOOL, "category", "if being debug logged or not. false:inactive, true:active"},
  571. }
  572. },
  573. RPCExamples{
  574. HelpExampleCli("logging", "\"[\\\"all\\\"]\" \"[\\\"http\\\"]\"")
  575. + HelpExampleRpc("logging", "[\"all\"], [\"libevent\"]")
  576. },
  577. [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
  578. {
  579. uint32_t original_log_categories = LogInstance().GetCategoryMask();
  580. if (request.params[0].isArray()) {
  581. EnableOrDisableLogCategories(request.params[0], true);
  582. }
  583. if (request.params[1].isArray()) {
  584. EnableOrDisableLogCategories(request.params[1], false);
  585. }
  586. uint32_t updated_log_categories = LogInstance().GetCategoryMask();
  587. uint32_t changed_log_categories = original_log_categories ^ updated_log_categories;
  588. // Update libevent logging if BCLog::LIBEVENT has changed.
  589. // If the library version doesn't allow it, UpdateHTTPServerLogging() returns false,
  590. // in which case we should clear the BCLog::LIBEVENT flag.
  591. // Throw an error if the user has explicitly asked to change only the libevent
  592. // flag and it failed.
  593. if (changed_log_categories & BCLog::LIBEVENT) {
  594. if (!UpdateHTTPServerLogging(LogInstance().WillLogCategory(BCLog::LIBEVENT))) {
  595. LogInstance().DisableCategory(BCLog::LIBEVENT);
  596. if (changed_log_categories == BCLog::LIBEVENT) {
  597. throw JSONRPCError(RPC_INVALID_PARAMETER, "libevent logging cannot be updated when using libevent before v2.1.1.");
  598. }
  599. }
  600. }
  601. UniValue result(UniValue::VOBJ);
  602. for (const auto& logCatActive : LogInstance().LogCategoriesList()) {
  603. result.pushKV(logCatActive.category, logCatActive.active);
  604. }
  605. return result;
  606. },
  607. };
  608. }
  609. static RPCHelpMan echo(const std::string& name)
  610. {
  611. return RPCHelpMan{name,
  612. "\nSimply echo back the input arguments. This command is for testing.\n"
  613. "\nIt will return an internal bug report when arg9='trigger_internal_bug' is passed.\n"
  614. "\nThe difference between echo and echojson is that echojson has argument conversion enabled in the client-side table in "
  615. "bitcoin-cli and the GUI. There is no server-side difference.",
  616. {
  617. {"arg0", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, ""},
  618. {"arg1", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, ""},
  619. {"arg2", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, ""},
  620. {"arg3", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, ""},
  621. {"arg4", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, ""},
  622. {"arg5", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, ""},
  623. {"arg6", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, ""},
  624. {"arg7", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, ""},
  625. {"arg8", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, ""},
  626. {"arg9", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, ""},
  627. },
  628. RPCResult{RPCResult::Type::ANY, "", "Returns whatever was passed in"},
  629. RPCExamples{""},
  630. [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
  631. {
  632. if (request.params[9].isStr()) {
  633. CHECK_NONFATAL(request.params[9].get_str() != "trigger_internal_bug");
  634. }
  635. return request.params;
  636. },
  637. };
  638. }
  639. static RPCHelpMan echo() { return echo("echo"); }
  640. static RPCHelpMan echojson() { return echo("echojson"); }
  641. static RPCHelpMan echoipc()
  642. {
  643. return RPCHelpMan{
  644. "echoipc",
  645. "\nEcho back the input argument, passing it through a spawned process in a multiprocess build.\n"
  646. "This command is for testing.\n",
  647. {{"arg", RPCArg::Type::STR, RPCArg::Optional::NO, "The string to echo",}},
  648. RPCResult{RPCResult::Type::STR, "echo", "The echoed string."},
  649. RPCExamples{HelpExampleCli("echo", "\"Hello world\"") +
  650. HelpExampleRpc("echo", "\"Hello world\"")},
  651. [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue {
  652. interfaces::Init& local_init = *EnsureAnyNodeContext(request.context).init;
  653. std::unique_ptr<interfaces::Echo> echo;
  654. if (interfaces::Ipc* ipc = local_init.ipc()) {
  655. // Spawn a new bitcoin-node process and call makeEcho to get a
  656. // client pointer to a interfaces::Echo instance running in
  657. // that process. This is just for testing. A slightly more
  658. // realistic test spawning a different executable instead of
  659. // the same executable would add a new bitcoin-echo executable,
  660. // and spawn bitcoin-echo below instead of bitcoin-node. But
  661. // using bitcoin-node avoids the need to build and install a
  662. // new executable just for this one test.
  663. auto init = ipc->spawnProcess("bitcoin-node");
  664. echo = init->makeEcho();
  665. ipc->addCleanup(*echo, [init = init.release()] { delete init; });
  666. } else {
  667. // IPC support is not available because this is a bitcoind
  668. // process not a bitcoind-node process, so just create a local
  669. // interfaces::Echo object and return it so the `echoipc` RPC
  670. // method will work, and the python test calling `echoipc`
  671. // can expect the same result.
  672. echo = local_init.makeEcho();
  673. }
  674. return echo->echo(request.params[0].get_str());
  675. },
  676. };
  677. }
  678. static UniValue SummaryToJSON(const IndexSummary&& summary, std::string index_name)
  679. {
  680. UniValue ret_summary(UniValue::VOBJ);
  681. if (!index_name.empty() && index_name != summary.name) return ret_summary;
  682. UniValue entry(UniValue::VOBJ);
  683. entry.pushKV("synced", summary.synced);
  684. entry.pushKV("best_block_height", summary.best_block_height);
  685. ret_summary.pushKV(summary.name, entry);
  686. return ret_summary;
  687. }
  688. static RPCHelpMan getindexinfo()
  689. {
  690. return RPCHelpMan{"getindexinfo",
  691. "\nReturns the status of one or all available indices currently running in the node.\n",
  692. {
  693. {"index_name", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, "Filter results for an index with a specific name."},
  694. },
  695. RPCResult{
  696. RPCResult::Type::OBJ_DYN, "", "", {
  697. {
  698. RPCResult::Type::OBJ, "name", "The name of the index",
  699. {
  700. {RPCResult::Type::BOOL, "synced", "Whether the index is synced or not"},
  701. {RPCResult::Type::NUM, "best_block_height", "The block height to which the index is synced"},
  702. }
  703. },
  704. },
  705. },
  706. RPCExamples{
  707. HelpExampleCli("getindexinfo", "")
  708. + HelpExampleRpc("getindexinfo", "")
  709. + HelpExampleCli("getindexinfo", "txindex")
  710. + HelpExampleRpc("getindexinfo", "txindex")
  711. },
  712. [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
  713. {
  714. UniValue result(UniValue::VOBJ);
  715. const std::string index_name = request.params[0].isNull() ? "" : request.params[0].get_str();
  716. if (g_txindex) {
  717. result.pushKVs(SummaryToJSON(g_txindex->GetSummary(), index_name));
  718. }
  719. if (g_coin_stats_index) {
  720. result.pushKVs(SummaryToJSON(g_coin_stats_index->GetSummary(), index_name));
  721. }
  722. ForEachBlockFilterIndex([&result, &index_name](const BlockFilterIndex& index) {
  723. result.pushKVs(SummaryToJSON(index.GetSummary(), index_name));
  724. });
  725. return result;
  726. },
  727. };
  728. }
  729. void RegisterMiscRPCCommands(CRPCTable &t)
  730. {
  731. // clang-format off
  732. static const CRPCCommand commands[] =
  733. { // category actor (function)
  734. // --------------------- ------------------------
  735. { "control", &getmemoryinfo, },
  736. { "control", &logging, },
  737. { "util", &validateaddress, },
  738. { "util", &createmultisig, },
  739. { "util", &deriveaddresses, },
  740. { "util", &getdescriptorinfo, },
  741. { "util", &verifymessage, },
  742. { "util", &signmessagewithprivkey, },
  743. { "util", &getindexinfo, },
  744. /* Not shown in help */
  745. { "hidden", &setmocktime, },
  746. { "hidden", &mockscheduler, },
  747. { "hidden", &echo, },
  748. { "hidden", &echojson, },
  749. { "hidden", &echoipc, },
  750. #if defined(USE_SYSCALL_SANDBOX)
  751. { "hidden", &invokedisallowedsyscall, },
  752. #endif // USE_SYSCALL_SANDBOX
  753. };
  754. // clang-format on
  755. for (const auto& c : commands) {
  756. t.appendCommand(c.name, &c);
  757. }
  758. }