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.

rpcmisc.cpp 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. // Copyright (c) 2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2014 The Bitcoin developers
  3. // Distributed under the MIT/X11 software license, see the accompanying
  4. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. #include "base58.h"
  6. #include "init.h"
  7. #include "main.h"
  8. #include "net.h"
  9. #include "netbase.h"
  10. #include "rpcserver.h"
  11. #include "timedata.h"
  12. #include "util.h"
  13. #ifdef ENABLE_WALLET
  14. #include "wallet.h"
  15. #include "walletdb.h"
  16. #endif
  17. #include <stdint.h>
  18. #include <boost/assign/list_of.hpp>
  19. #include "json/json_spirit_utils.h"
  20. #include "json/json_spirit_value.h"
  21. using namespace boost;
  22. using namespace boost::assign;
  23. using namespace json_spirit;
  24. using namespace std;
  25. /**
  26. * @note Do not add or change anything in the information returned by this
  27. * method. `getinfo` exists for backwards-compatibilty only. It combines
  28. * information from wildly different sources in the program, which is a mess,
  29. * and is thus planned to be deprecated eventually.
  30. *
  31. * Based on the source of the information, new information should be added to:
  32. * - `getblockchaininfo`,
  33. * - `getnetworkinfo` or
  34. * - `getwalletinfo`
  35. *
  36. * Or alternatively, create a specific query method for the information.
  37. **/
  38. Value getinfo(const Array& params, bool fHelp)
  39. {
  40. if (fHelp || params.size() != 0)
  41. throw runtime_error(
  42. "getinfo\n"
  43. "Returns an object containing various state info.\n"
  44. "\nResult:\n"
  45. "{\n"
  46. " \"version\": xxxxx, (numeric) the server version\n"
  47. " \"protocolversion\": xxxxx, (numeric) the protocol version\n"
  48. " \"walletversion\": xxxxx, (numeric) the wallet version\n"
  49. " \"balance\": xxxxxxx, (numeric) the total bitcoin balance of the wallet\n"
  50. " \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n"
  51. " \"timeoffset\": xxxxx, (numeric) the time offset\n"
  52. " \"connections\": xxxxx, (numeric) the number of connections\n"
  53. " \"proxy\": \"host:port\", (string, optional) the proxy used by the server\n"
  54. " \"difficulty\": xxxxxx, (numeric) the current difficulty\n"
  55. " \"testnet\": true|false, (boolean) if the server is using testnet or not\n"
  56. " \"keypoololdest\": xxxxxx, (numeric) the timestamp (seconds since GMT epoch) of the oldest pre-generated key in the key pool\n"
  57. " \"keypoolsize\": xxxx, (numeric) how many new keys are pre-generated\n"
  58. " \"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"
  59. " \"paytxfee\": x.xxxx, (numeric) the transaction fee set in btc/kb\n"
  60. " \"relayfee\": x.xxxx, (numeric) minimum relay fee for non-free transactions in btc/kb\n"
  61. " \"errors\": \"...\" (string) any error messages\n"
  62. "}\n"
  63. "\nExamples:\n"
  64. + HelpExampleCli("getinfo", "")
  65. + HelpExampleRpc("getinfo", "")
  66. );
  67. proxyType proxy;
  68. GetProxy(NET_IPV4, proxy);
  69. Object obj;
  70. obj.push_back(Pair("version", CLIENT_VERSION));
  71. obj.push_back(Pair("protocolversion", PROTOCOL_VERSION));
  72. #ifdef ENABLE_WALLET
  73. if (pwalletMain) {
  74. obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
  75. obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
  76. }
  77. #endif
  78. obj.push_back(Pair("blocks", (int)chainActive.Height()));
  79. obj.push_back(Pair("timeoffset", GetTimeOffset()));
  80. obj.push_back(Pair("connections", (int)vNodes.size()));
  81. obj.push_back(Pair("proxy", (proxy.IsValid() ? proxy.ToStringIPPort() : string())));
  82. obj.push_back(Pair("difficulty", (double)GetDifficulty()));
  83. obj.push_back(Pair("testnet", Params().TestnetToBeDeprecatedFieldRPC()));
  84. #ifdef ENABLE_WALLET
  85. if (pwalletMain) {
  86. obj.push_back(Pair("keypoololdest", pwalletMain->GetOldestKeyPoolTime()));
  87. obj.push_back(Pair("keypoolsize", (int)pwalletMain->GetKeyPoolSize()));
  88. }
  89. if (pwalletMain && pwalletMain->IsCrypted())
  90. obj.push_back(Pair("unlocked_until", nWalletUnlockTime));
  91. obj.push_back(Pair("paytxfee", ValueFromAmount(payTxFee.GetFeePerK())));
  92. #endif
  93. obj.push_back(Pair("relayfee", ValueFromAmount(::minRelayTxFee.GetFeePerK())));
  94. obj.push_back(Pair("errors", GetWarnings("statusbar")));
  95. return obj;
  96. }
  97. #ifdef ENABLE_WALLET
  98. class DescribeAddressVisitor : public boost::static_visitor<Object>
  99. {
  100. private:
  101. isminetype mine;
  102. public:
  103. DescribeAddressVisitor(isminetype mineIn) : mine(mineIn) {}
  104. Object operator()(const CNoDestination &dest) const { return Object(); }
  105. Object operator()(const CKeyID &keyID) const {
  106. Object obj;
  107. CPubKey vchPubKey;
  108. obj.push_back(Pair("isscript", false));
  109. if (mine == ISMINE_SPENDABLE) {
  110. pwalletMain->GetPubKey(keyID, vchPubKey);
  111. obj.push_back(Pair("pubkey", HexStr(vchPubKey)));
  112. obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed()));
  113. }
  114. return obj;
  115. }
  116. Object operator()(const CScriptID &scriptID) const {
  117. Object obj;
  118. obj.push_back(Pair("isscript", true));
  119. if (mine != ISMINE_NO) {
  120. CScript subscript;
  121. pwalletMain->GetCScript(scriptID, subscript);
  122. std::vector<CTxDestination> addresses;
  123. txnouttype whichType;
  124. int nRequired;
  125. ExtractDestinations(subscript, whichType, addresses, nRequired);
  126. obj.push_back(Pair("script", GetTxnOutputType(whichType)));
  127. obj.push_back(Pair("hex", HexStr(subscript.begin(), subscript.end())));
  128. Array a;
  129. BOOST_FOREACH(const CTxDestination& addr, addresses)
  130. a.push_back(CBitcoinAddress(addr).ToString());
  131. obj.push_back(Pair("addresses", a));
  132. if (whichType == TX_MULTISIG)
  133. obj.push_back(Pair("sigsrequired", nRequired));
  134. }
  135. return obj;
  136. }
  137. };
  138. #endif
  139. Value validateaddress(const Array& params, bool fHelp)
  140. {
  141. if (fHelp || params.size() != 1)
  142. throw runtime_error(
  143. "validateaddress \"bitcoinaddress\"\n"
  144. "\nReturn information about the given bitcoin address.\n"
  145. "\nArguments:\n"
  146. "1. \"bitcoinaddress\" (string, required) The bitcoin address to validate\n"
  147. "\nResult:\n"
  148. "{\n"
  149. " \"isvalid\" : true|false, (boolean) If the address is valid or not. If not, this is the only property returned.\n"
  150. " \"address\" : \"bitcoinaddress\", (string) The bitcoin address validated\n"
  151. " \"ismine\" : true|false, (boolean) If the address is yours or not\n"
  152. " \"isscript\" : true|false, (boolean) If the key is a script\n"
  153. " \"pubkey\" : \"publickeyhex\", (string) The hex value of the raw public key\n"
  154. " \"iscompressed\" : true|false, (boolean) If the address is compressed\n"
  155. " \"account\" : \"account\" (string) The account associated with the address, \"\" is the default account\n"
  156. "}\n"
  157. "\nExamples:\n"
  158. + HelpExampleCli("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"")
  159. + HelpExampleRpc("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"")
  160. );
  161. CBitcoinAddress address(params[0].get_str());
  162. bool isValid = address.IsValid();
  163. Object ret;
  164. ret.push_back(Pair("isvalid", isValid));
  165. if (isValid)
  166. {
  167. CTxDestination dest = address.Get();
  168. string currentAddress = address.ToString();
  169. ret.push_back(Pair("address", currentAddress));
  170. #ifdef ENABLE_WALLET
  171. isminetype mine = pwalletMain ? IsMine(*pwalletMain, dest) : ISMINE_NO;
  172. ret.push_back(Pair("ismine", (mine & ISMINE_SPENDABLE) ? true : false));
  173. if (mine != ISMINE_NO) {
  174. ret.push_back(Pair("iswatchonly", (mine & ISMINE_WATCH_ONLY) ? true: false));
  175. Object detail = boost::apply_visitor(DescribeAddressVisitor(mine), dest);
  176. ret.insert(ret.end(), detail.begin(), detail.end());
  177. }
  178. if (pwalletMain && pwalletMain->mapAddressBook.count(dest))
  179. ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest].name));
  180. #endif
  181. }
  182. return ret;
  183. }
  184. //
  185. // Used by addmultisigaddress / createmultisig:
  186. //
  187. CScript _createmultisig_redeemScript(const Array& params)
  188. {
  189. int nRequired = params[0].get_int();
  190. const Array& keys = params[1].get_array();
  191. // Gather public keys
  192. if (nRequired < 1)
  193. throw runtime_error("a multisignature address must require at least one key to redeem");
  194. if ((int)keys.size() < nRequired)
  195. throw runtime_error(
  196. strprintf("not enough keys supplied "
  197. "(got %u keys, but need at least %d to redeem)", keys.size(), nRequired));
  198. std::vector<CPubKey> pubkeys;
  199. pubkeys.resize(keys.size());
  200. for (unsigned int i = 0; i < keys.size(); i++)
  201. {
  202. const std::string& ks = keys[i].get_str();
  203. #ifdef ENABLE_WALLET
  204. // Case 1: Bitcoin address and we have full public key:
  205. CBitcoinAddress address(ks);
  206. if (pwalletMain && address.IsValid())
  207. {
  208. CKeyID keyID;
  209. if (!address.GetKeyID(keyID))
  210. throw runtime_error(
  211. strprintf("%s does not refer to a key",ks));
  212. CPubKey vchPubKey;
  213. if (!pwalletMain->GetPubKey(keyID, vchPubKey))
  214. throw runtime_error(
  215. strprintf("no full public key for address %s",ks));
  216. if (!vchPubKey.IsFullyValid())
  217. throw runtime_error(" Invalid public key: "+ks);
  218. pubkeys[i] = vchPubKey;
  219. }
  220. // Case 2: hex public key
  221. else
  222. #endif
  223. if (IsHex(ks))
  224. {
  225. CPubKey vchPubKey(ParseHex(ks));
  226. if (!vchPubKey.IsFullyValid())
  227. throw runtime_error(" Invalid public key: "+ks);
  228. pubkeys[i] = vchPubKey;
  229. }
  230. else
  231. {
  232. throw runtime_error(" Invalid public key: "+ks);
  233. }
  234. }
  235. CScript result = GetScriptForMultisig(nRequired, pubkeys);
  236. if (result.size() > MAX_SCRIPT_ELEMENT_SIZE)
  237. throw runtime_error(
  238. strprintf("redeemScript exceeds size limit: %d > %d", result.size(), MAX_SCRIPT_ELEMENT_SIZE));
  239. return result;
  240. }
  241. Value createmultisig(const Array& params, bool fHelp)
  242. {
  243. if (fHelp || params.size() < 2 || params.size() > 2)
  244. {
  245. string msg = "createmultisig nrequired [\"key\",...]\n"
  246. "\nCreates a multi-signature address with n signature of m keys required.\n"
  247. "It returns a json object with the address and redeemScript.\n"
  248. "\nArguments:\n"
  249. "1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n"
  250. "2. \"keys\" (string, required) A json array of keys which are bitcoin addresses or hex-encoded public keys\n"
  251. " [\n"
  252. " \"key\" (string) bitcoin address or hex-encoded public key\n"
  253. " ,...\n"
  254. " ]\n"
  255. "\nResult:\n"
  256. "{\n"
  257. " \"address\":\"multisigaddress\", (string) The value of the new multisig address.\n"
  258. " \"redeemScript\":\"script\" (string) The string value of the hex-encoded redemption script.\n"
  259. "}\n"
  260. "\nExamples:\n"
  261. "\nCreate a multisig address from 2 addresses\n"
  262. + HelpExampleCli("createmultisig", "2 \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"") +
  263. "\nAs a json rpc call\n"
  264. + HelpExampleRpc("createmultisig", "2, \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"")
  265. ;
  266. throw runtime_error(msg);
  267. }
  268. // Construct using pay-to-script-hash:
  269. CScript inner = _createmultisig_redeemScript(params);
  270. CScriptID innerID = inner.GetID();
  271. CBitcoinAddress address(innerID);
  272. Object result;
  273. result.push_back(Pair("address", address.ToString()));
  274. result.push_back(Pair("redeemScript", HexStr(inner.begin(), inner.end())));
  275. return result;
  276. }
  277. Value verifymessage(const Array& params, bool fHelp)
  278. {
  279. if (fHelp || params.size() != 3)
  280. throw runtime_error(
  281. "verifymessage \"bitcoinaddress\" \"signature\" \"message\"\n"
  282. "\nVerify a signed message\n"
  283. "\nArguments:\n"
  284. "1. \"bitcoinaddress\" (string, required) The bitcoin address to use for the signature.\n"
  285. "2. \"signature\" (string, required) The signature provided by the signer in base 64 encoding (see signmessage).\n"
  286. "3. \"message\" (string, required) The message that was signed.\n"
  287. "\nResult:\n"
  288. "true|false (boolean) If the signature is verified or not.\n"
  289. "\nExamples:\n"
  290. "\nUnlock the wallet for 30 seconds\n"
  291. + HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") +
  292. "\nCreate the signature\n"
  293. + HelpExampleCli("signmessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" \"my message\"") +
  294. "\nVerify the signature\n"
  295. + HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" \"signature\" \"my message\"") +
  296. "\nAs json rpc\n"
  297. + HelpExampleRpc("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\", \"signature\", \"my message\"")
  298. );
  299. string strAddress = params[0].get_str();
  300. string strSign = params[1].get_str();
  301. string strMessage = params[2].get_str();
  302. CBitcoinAddress addr(strAddress);
  303. if (!addr.IsValid())
  304. throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
  305. CKeyID keyID;
  306. if (!addr.GetKeyID(keyID))
  307. throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
  308. bool fInvalid = false;
  309. vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);
  310. if (fInvalid)
  311. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding");
  312. CHashWriter ss(SER_GETHASH, 0);
  313. ss << strMessageMagic;
  314. ss << strMessage;
  315. CPubKey pubkey;
  316. if (!pubkey.RecoverCompact(ss.GetHash(), vchSig))
  317. return false;
  318. return (pubkey.GetID() == keyID);
  319. }