PageRenderTime 1020ms CodeModel.GetById 37ms RepoModel.GetById 0ms app.codeStats 0ms

/src/rpc/output_script.cpp

https://github.com/bitcoin/bitcoin
C++ | 319 lines | 275 code | 34 blank | 10 comment | 34 complexity | 26dbf3d2c751c7e951dcd07f81c147a0 MD5 | raw file
  1. // Copyright (c) 2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2022 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 <key_io.h>
  6. #include <outputtype.h>
  7. #include <pubkey.h>
  8. #include <rpc/protocol.h>
  9. #include <rpc/request.h>
  10. #include <rpc/server.h>
  11. #include <rpc/util.h>
  12. #include <script/descriptor.h>
  13. #include <script/script.h>
  14. #include <script/signingprovider.h>
  15. #include <script/standard.h>
  16. #include <tinyformat.h>
  17. #include <univalue.h>
  18. #include <util/check.h>
  19. #include <util/strencodings.h>
  20. #include <cstdint>
  21. #include <memory>
  22. #include <optional>
  23. #include <string>
  24. #include <tuple>
  25. #include <vector>
  26. namespace node {
  27. struct NodeContext;
  28. }
  29. using node::NodeContext;
  30. static RPCHelpMan validateaddress()
  31. {
  32. return RPCHelpMan{
  33. "validateaddress",
  34. "\nReturn information about the given bitcoin address.\n",
  35. {
  36. {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The bitcoin address to validate"},
  37. },
  38. RPCResult{
  39. RPCResult::Type::OBJ, "", "",
  40. {
  41. {RPCResult::Type::BOOL, "isvalid", "If the address is valid or not"},
  42. {RPCResult::Type::STR, "address", /*optional=*/true, "The bitcoin address validated"},
  43. {RPCResult::Type::STR_HEX, "scriptPubKey", /*optional=*/true, "The hex-encoded scriptPubKey generated by the address"},
  44. {RPCResult::Type::BOOL, "isscript", /*optional=*/true, "If the key is a script"},
  45. {RPCResult::Type::BOOL, "iswitness", /*optional=*/true, "If the address is a witness address"},
  46. {RPCResult::Type::NUM, "witness_version", /*optional=*/true, "The version number of the witness program"},
  47. {RPCResult::Type::STR_HEX, "witness_program", /*optional=*/true, "The hex value of the witness program"},
  48. {RPCResult::Type::STR, "error", /*optional=*/true, "Error message, if any"},
  49. {RPCResult::Type::ARR, "error_locations", /*optional=*/true, "Indices of likely error locations in address, if known (e.g. Bech32 errors)",
  50. {
  51. {RPCResult::Type::NUM, "index", "index of a potential error"},
  52. }},
  53. }
  54. },
  55. RPCExamples{
  56. HelpExampleCli("validateaddress", "\"" + EXAMPLE_ADDRESS[0] + "\"") +
  57. HelpExampleRpc("validateaddress", "\"" + EXAMPLE_ADDRESS[0] + "\"")
  58. },
  59. [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
  60. {
  61. std::string error_msg;
  62. std::vector<int> error_locations;
  63. CTxDestination dest = DecodeDestination(request.params[0].get_str(), error_msg, &error_locations);
  64. const bool isValid = IsValidDestination(dest);
  65. CHECK_NONFATAL(isValid == error_msg.empty());
  66. UniValue ret(UniValue::VOBJ);
  67. ret.pushKV("isvalid", isValid);
  68. if (isValid) {
  69. std::string currentAddress = EncodeDestination(dest);
  70. ret.pushKV("address", currentAddress);
  71. CScript scriptPubKey = GetScriptForDestination(dest);
  72. ret.pushKV("scriptPubKey", HexStr(scriptPubKey));
  73. UniValue detail = DescribeAddress(dest);
  74. ret.pushKVs(detail);
  75. } else {
  76. UniValue error_indices(UniValue::VARR);
  77. for (int i : error_locations) error_indices.push_back(i);
  78. ret.pushKV("error_locations", error_indices);
  79. ret.pushKV("error", error_msg);
  80. }
  81. return ret;
  82. },
  83. };
  84. }
  85. static RPCHelpMan createmultisig()
  86. {
  87. return RPCHelpMan{"createmultisig",
  88. "\nCreates a multi-signature address with n signature of m keys required.\n"
  89. "It returns a json object with the address and redeemScript.\n",
  90. {
  91. {"nrequired", RPCArg::Type::NUM, RPCArg::Optional::NO, "The number of required signatures out of the n keys."},
  92. {"keys", RPCArg::Type::ARR, RPCArg::Optional::NO, "The hex-encoded public keys.",
  93. {
  94. {"key", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "The hex-encoded public key"},
  95. }},
  96. {"address_type", RPCArg::Type::STR, RPCArg::Default{"legacy"}, "The address type to use. Options are \"legacy\", \"p2sh-segwit\", and \"bech32\"."},
  97. },
  98. RPCResult{
  99. RPCResult::Type::OBJ, "", "",
  100. {
  101. {RPCResult::Type::STR, "address", "The value of the new multisig address."},
  102. {RPCResult::Type::STR_HEX, "redeemScript", "The string value of the hex-encoded redemption script."},
  103. {RPCResult::Type::STR, "descriptor", "The descriptor for this multisig"},
  104. {RPCResult::Type::ARR, "warnings", /*optional=*/true, "Any warnings resulting from the creation of this multisig",
  105. {
  106. {RPCResult::Type::STR, "", ""},
  107. }},
  108. }
  109. },
  110. RPCExamples{
  111. "\nCreate a multisig address from 2 public keys\n"
  112. + HelpExampleCli("createmultisig", "2 \"[\\\"03789ed0bb717d88f7d321a368d905e7430207ebbd82bd342cf11ae157a7ace5fd\\\",\\\"03dbc6764b8884a92e871274b87583e6d5c2a58819473e17e107ef3f6aa5a61626\\\"]\"") +
  113. "\nAs a JSON-RPC call\n"
  114. + HelpExampleRpc("createmultisig", "2, [\"03789ed0bb717d88f7d321a368d905e7430207ebbd82bd342cf11ae157a7ace5fd\",\"03dbc6764b8884a92e871274b87583e6d5c2a58819473e17e107ef3f6aa5a61626\"]")
  115. },
  116. [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
  117. {
  118. int required = request.params[0].getInt<int>();
  119. // Get the public keys
  120. const UniValue& keys = request.params[1].get_array();
  121. std::vector<CPubKey> pubkeys;
  122. for (unsigned int i = 0; i < keys.size(); ++i) {
  123. if (IsHex(keys[i].get_str()) && (keys[i].get_str().length() == 66 || keys[i].get_str().length() == 130)) {
  124. pubkeys.push_back(HexToPubKey(keys[i].get_str()));
  125. } else {
  126. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Invalid public key: %s\n.", keys[i].get_str()));
  127. }
  128. }
  129. // Get the output type
  130. OutputType output_type = OutputType::LEGACY;
  131. if (!request.params[2].isNull()) {
  132. std::optional<OutputType> parsed = ParseOutputType(request.params[2].get_str());
  133. if (!parsed) {
  134. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Unknown address type '%s'", request.params[2].get_str()));
  135. } else if (parsed.value() == OutputType::BECH32M) {
  136. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "createmultisig cannot create bech32m multisig addresses");
  137. }
  138. output_type = parsed.value();
  139. }
  140. // Construct using pay-to-script-hash:
  141. FillableSigningProvider keystore;
  142. CScript inner;
  143. const CTxDestination dest = AddAndGetMultisigDestination(required, pubkeys, output_type, keystore, inner);
  144. // Make the descriptor
  145. std::unique_ptr<Descriptor> descriptor = InferDescriptor(GetScriptForDestination(dest), keystore);
  146. UniValue result(UniValue::VOBJ);
  147. result.pushKV("address", EncodeDestination(dest));
  148. result.pushKV("redeemScript", HexStr(inner));
  149. result.pushKV("descriptor", descriptor->ToString());
  150. UniValue warnings(UniValue::VARR);
  151. if (descriptor->GetOutputType() != output_type) {
  152. // Only warns if the user has explicitly chosen an address type we cannot generate
  153. warnings.push_back("Unable to make chosen address type, please ensure no uncompressed public keys are present.");
  154. }
  155. if (!warnings.empty()) result.pushKV("warnings", warnings);
  156. return result;
  157. },
  158. };
  159. }
  160. static RPCHelpMan getdescriptorinfo()
  161. {
  162. const std::string EXAMPLE_DESCRIPTOR = "wpkh([d34db33f/84h/0h/0h]0279be667ef9dcbbac55a06295Ce870b07029Bfcdb2dce28d959f2815b16f81798)";
  163. return RPCHelpMan{"getdescriptorinfo",
  164. {"\nAnalyses a descriptor.\n"},
  165. {
  166. {"descriptor", RPCArg::Type::STR, RPCArg::Optional::NO, "The descriptor."},
  167. },
  168. RPCResult{
  169. RPCResult::Type::OBJ, "", "",
  170. {
  171. {RPCResult::Type::STR, "descriptor", "The descriptor in canonical form, without private keys"},
  172. {RPCResult::Type::STR, "checksum", "The checksum for the input descriptor"},
  173. {RPCResult::Type::BOOL, "isrange", "Whether the descriptor is ranged"},
  174. {RPCResult::Type::BOOL, "issolvable", "Whether the descriptor is solvable"},
  175. {RPCResult::Type::BOOL, "hasprivatekeys", "Whether the input descriptor contained at least one private key"},
  176. }
  177. },
  178. RPCExamples{
  179. "Analyse a descriptor\n" +
  180. HelpExampleCli("getdescriptorinfo", "\"" + EXAMPLE_DESCRIPTOR + "\"") +
  181. HelpExampleRpc("getdescriptorinfo", "\"" + EXAMPLE_DESCRIPTOR + "\"")
  182. },
  183. [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
  184. {
  185. RPCTypeCheck(request.params, {UniValue::VSTR});
  186. FlatSigningProvider provider;
  187. std::string error;
  188. auto desc = Parse(request.params[0].get_str(), provider, error);
  189. if (!desc) {
  190. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error);
  191. }
  192. UniValue result(UniValue::VOBJ);
  193. result.pushKV("descriptor", desc->ToString());
  194. result.pushKV("checksum", GetDescriptorChecksum(request.params[0].get_str()));
  195. result.pushKV("isrange", desc->IsRange());
  196. result.pushKV("issolvable", desc->IsSolvable());
  197. result.pushKV("hasprivatekeys", provider.keys.size() > 0);
  198. return result;
  199. },
  200. };
  201. }
  202. static RPCHelpMan deriveaddresses()
  203. {
  204. const std::string EXAMPLE_DESCRIPTOR = "wpkh([d34db33f/84h/0h/0h]xpub6DJ2dNUysrn5Vt36jH2KLBT2i1auw1tTSSomg8PhqNiUtx8QX2SvC9nrHu81fT41fvDUnhMjEzQgXnQjKEu3oaqMSzhSrHMxyyoEAmUHQbY/0/*)#cjjspncu";
  205. return RPCHelpMan{"deriveaddresses",
  206. {"\nDerives one or more addresses corresponding to an output descriptor.\n"
  207. "Examples of output descriptors are:\n"
  208. " pkh(<pubkey>) P2PKH outputs for the given pubkey\n"
  209. " wpkh(<pubkey>) Native segwit P2PKH outputs for the given pubkey\n"
  210. " sh(multi(<n>,<pubkey>,<pubkey>,...)) P2SH-multisig outputs for the given threshold and pubkeys\n"
  211. " raw(<hex script>) Outputs whose scriptPubKey equals the specified hex scripts\n"
  212. "\nIn the above, <pubkey> either refers to a fixed public key in hexadecimal notation, or to an xpub/xprv optionally followed by one\n"
  213. "or more path elements separated by \"/\", where \"h\" represents a hardened child key.\n"
  214. "For more information on output descriptors, see the documentation in the doc/descriptors.md file.\n"},
  215. {
  216. {"descriptor", RPCArg::Type::STR, RPCArg::Optional::NO, "The descriptor."},
  217. {"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."},
  218. },
  219. RPCResult{
  220. RPCResult::Type::ARR, "", "",
  221. {
  222. {RPCResult::Type::STR, "address", "the derived addresses"},
  223. }
  224. },
  225. RPCExamples{
  226. "First three native segwit receive addresses\n" +
  227. HelpExampleCli("deriveaddresses", "\"" + EXAMPLE_DESCRIPTOR + "\" \"[0,2]\"") +
  228. HelpExampleRpc("deriveaddresses", "\"" + EXAMPLE_DESCRIPTOR + "\", \"[0,2]\"")
  229. },
  230. [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
  231. {
  232. RPCTypeCheck(request.params, {UniValue::VSTR, UniValueType()}); // Range argument is checked later
  233. const std::string desc_str = request.params[0].get_str();
  234. int64_t range_begin = 0;
  235. int64_t range_end = 0;
  236. if (request.params.size() >= 2 && !request.params[1].isNull()) {
  237. std::tie(range_begin, range_end) = ParseDescriptorRange(request.params[1]);
  238. }
  239. FlatSigningProvider key_provider;
  240. std::string error;
  241. auto desc = Parse(desc_str, key_provider, error, /* require_checksum = */ true);
  242. if (!desc) {
  243. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error);
  244. }
  245. if (!desc->IsRange() && request.params.size() > 1) {
  246. throw JSONRPCError(RPC_INVALID_PARAMETER, "Range should not be specified for an un-ranged descriptor");
  247. }
  248. if (desc->IsRange() && request.params.size() == 1) {
  249. throw JSONRPCError(RPC_INVALID_PARAMETER, "Range must be specified for a ranged descriptor");
  250. }
  251. UniValue addresses(UniValue::VARR);
  252. for (int i = range_begin; i <= range_end; ++i) {
  253. FlatSigningProvider provider;
  254. std::vector<CScript> scripts;
  255. if (!desc->Expand(i, key_provider, scripts, provider)) {
  256. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Cannot derive script without private keys");
  257. }
  258. for (const CScript& script : scripts) {
  259. CTxDestination dest;
  260. if (!ExtractDestination(script, dest)) {
  261. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Descriptor does not have a corresponding address");
  262. }
  263. addresses.push_back(EncodeDestination(dest));
  264. }
  265. }
  266. // This should not be possible, but an assert seems overkill:
  267. if (addresses.empty()) {
  268. throw JSONRPCError(RPC_MISC_ERROR, "Unexpected empty result");
  269. }
  270. return addresses;
  271. },
  272. };
  273. }
  274. void RegisterOutputScriptRPCCommands(CRPCTable& t)
  275. {
  276. static const CRPCCommand commands[]{
  277. {"util", &validateaddress},
  278. {"util", &createmultisig},
  279. {"util", &deriveaddresses},
  280. {"util", &getdescriptorinfo},
  281. };
  282. for (const auto& c : commands) {
  283. t.appendCommand(c.name, &c);
  284. }
  285. }