1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
7 #include "clientversion.h"
9 #include "validation.h"
12 #include "rpc/server.h"
15 #include "utilstrencodings.h"
17 #include "wallet/rpcwallet.h"
18 #include "wallet/wallet.h"
19 #include "wallet/walletdb.h"
24 #include <boost/assign/list_of.hpp>
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.
36 * Based on the source of the information, new information should be added to:
37 * - `getblockchaininfo`,
38 * - `getnetworkinfo` or
41 * Or alternatively, create a specific query method for the information.
43 UniValue
getinfo(const JSONRPCRequest
& request
)
45 if (request
.fHelp
|| request
.params
.size() != 0)
48 "\nDEPRECATED. Returns an object containing various state info.\n"
51 " \"version\": xxxxx, (numeric) the server version\n"
52 " \"protocolversion\": xxxxx, (numeric) the protocol version\n"
53 " \"walletversion\": xxxxx, (numeric) the wallet version\n"
54 " \"balance\": xxxxxxx, (numeric) the total bitcoin balance of the wallet\n"
55 " \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n"
56 " \"timeoffset\": xxxxx, (numeric) the time offset\n"
57 " \"connections\": xxxxx, (numeric) the number of connections\n"
58 " \"proxy\": \"host:port\", (string, optional) the proxy used by the server\n"
59 " \"difficulty\": xxxxxx, (numeric) the current difficulty\n"
60 " \"testnet\": true|false, (boolean) if the server is using testnet or not\n"
61 " \"keypoololdest\": xxxxxx, (numeric) the timestamp (seconds since Unix epoch) of the oldest pre-generated key in the key pool\n"
62 " \"keypoolsize\": xxxx, (numeric) how many new keys are pre-generated\n"
63 " \"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"
64 " \"paytxfee\": x.xxxx, (numeric) the transaction fee set in " + CURRENCY_UNIT
+ "/kB\n"
65 " \"relayfee\": x.xxxx, (numeric) minimum relay fee for non-free transactions in " + CURRENCY_UNIT
+ "/kB\n"
66 " \"errors\": \"...\" (string) any error messages\n"
69 + HelpExampleCli("getinfo", "")
70 + HelpExampleRpc("getinfo", "")
74 CWallet
* const pwallet
= GetWalletForJSONRPCRequest(request
);
76 LOCK2(cs_main
, pwallet
? &pwallet
->cs_wallet
: NULL
);
82 GetProxy(NET_IPV4
, proxy
);
84 UniValue
obj(UniValue::VOBJ
);
85 obj
.push_back(Pair("version", CLIENT_VERSION
));
86 obj
.push_back(Pair("protocolversion", PROTOCOL_VERSION
));
89 obj
.push_back(Pair("walletversion", pwallet
->GetVersion()));
90 obj
.push_back(Pair("balance", ValueFromAmount(pwallet
->GetBalance())));
93 obj
.push_back(Pair("blocks", (int)chainActive
.Height()));
94 obj
.push_back(Pair("timeoffset", GetTimeOffset()));
96 obj
.push_back(Pair("connections", (int)g_connman
->GetNodeCount(CConnman::CONNECTIONS_ALL
)));
97 obj
.push_back(Pair("proxy", (proxy
.IsValid() ? proxy
.proxy
.ToStringIPPort() : string())));
98 obj
.push_back(Pair("difficulty", (double)GetDifficulty()));
99 obj
.push_back(Pair("testnet", Params().NetworkIDString() == CBaseChainParams::TESTNET
));
102 obj
.push_back(Pair("keypoololdest", pwallet
->GetOldestKeyPoolTime()));
103 obj
.push_back(Pair("keypoolsize", (int)pwallet
->GetKeyPoolSize()));
105 if (pwallet
&& pwallet
->IsCrypted()) {
106 obj
.push_back(Pair("unlocked_until", pwallet
->nRelockTime
));
108 obj
.push_back(Pair("paytxfee", ValueFromAmount(payTxFee
.GetFeePerK())));
110 obj
.push_back(Pair("relayfee", ValueFromAmount(::minRelayTxFee
.GetFeePerK())));
111 obj
.push_back(Pair("errors", GetWarnings("statusbar")));
116 class DescribeAddressVisitor
: public boost::static_visitor
<UniValue
>
119 CWallet
* const pwallet
;
121 DescribeAddressVisitor(CWallet
*_pwallet
) : pwallet(_pwallet
) {}
123 UniValue
operator()(const CNoDestination
&dest
) const { return UniValue(UniValue::VOBJ
); }
125 UniValue
operator()(const CKeyID
&keyID
) const {
126 UniValue
obj(UniValue::VOBJ
);
128 obj
.push_back(Pair("isscript", false));
129 if (pwallet
&& pwallet
->GetPubKey(keyID
, vchPubKey
)) {
130 obj
.push_back(Pair("pubkey", HexStr(vchPubKey
)));
131 obj
.push_back(Pair("iscompressed", vchPubKey
.IsCompressed()));
136 UniValue
operator()(const CScriptID
&scriptID
) const {
137 UniValue
obj(UniValue::VOBJ
);
139 obj
.push_back(Pair("isscript", true));
140 if (pwallet
&& pwallet
->GetCScript(scriptID
, subscript
)) {
141 std::vector
<CTxDestination
> addresses
;
142 txnouttype whichType
;
144 ExtractDestinations(subscript
, whichType
, addresses
, nRequired
);
145 obj
.push_back(Pair("script", GetTxnOutputType(whichType
)));
146 obj
.push_back(Pair("hex", HexStr(subscript
.begin(), subscript
.end())));
147 UniValue
a(UniValue::VARR
);
148 BOOST_FOREACH(const CTxDestination
& addr
, addresses
)
149 a
.push_back(CBitcoinAddress(addr
).ToString());
150 obj
.push_back(Pair("addresses", a
));
151 if (whichType
== TX_MULTISIG
)
152 obj
.push_back(Pair("sigsrequired", nRequired
));
159 UniValue
validateaddress(const JSONRPCRequest
& request
)
161 if (request
.fHelp
|| request
.params
.size() != 1)
163 "validateaddress \"address\"\n"
164 "\nReturn information about the given bitcoin address.\n"
166 "1. \"address\" (string, required) The bitcoin address to validate\n"
169 " \"isvalid\" : true|false, (boolean) If the address is valid or not. If not, this is the only property returned.\n"
170 " \"address\" : \"address\", (string) The bitcoin address validated\n"
171 " \"scriptPubKey\" : \"hex\", (string) The hex encoded scriptPubKey generated by the address\n"
172 " \"ismine\" : true|false, (boolean) If the address is yours or not\n"
173 " \"iswatchonly\" : true|false, (boolean) If the address is watchonly\n"
174 " \"isscript\" : true|false, (boolean) If the key is a script\n"
175 " \"pubkey\" : \"publickeyhex\", (string) The hex value of the raw public key\n"
176 " \"iscompressed\" : true|false, (boolean) If the address is compressed\n"
177 " \"account\" : \"account\" (string) DEPRECATED. The account associated with the address, \"\" is the default account\n"
178 " \"timestamp\" : timestamp, (number, optional) The creation time of the key if available in seconds since epoch (Jan 1 1970 GMT)\n"
179 " \"hdkeypath\" : \"keypath\" (string, optional) The HD keypath if the key is HD and available\n"
180 " \"hdmasterkeyid\" : \"<hash160>\" (string, optional) The Hash160 of the HD master pubkey\n"
183 + HelpExampleCli("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"")
184 + HelpExampleRpc("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"")
188 CWallet
* const pwallet
= GetWalletForJSONRPCRequest(request
);
190 LOCK2(cs_main
, pwallet
? &pwallet
->cs_wallet
: NULL
);
195 CBitcoinAddress
address(request
.params
[0].get_str());
196 bool isValid
= address
.IsValid();
198 UniValue
ret(UniValue::VOBJ
);
199 ret
.push_back(Pair("isvalid", isValid
));
202 CTxDestination dest
= address
.Get();
203 string currentAddress
= address
.ToString();
204 ret
.push_back(Pair("address", currentAddress
));
206 CScript scriptPubKey
= GetScriptForDestination(dest
);
207 ret
.push_back(Pair("scriptPubKey", HexStr(scriptPubKey
.begin(), scriptPubKey
.end())));
210 isminetype mine
= pwallet
? IsMine(*pwallet
, dest
) : ISMINE_NO
;
211 ret
.push_back(Pair("ismine", (mine
& ISMINE_SPENDABLE
) ? true : false));
212 ret
.push_back(Pair("iswatchonly", (mine
& ISMINE_WATCH_ONLY
) ? true: false));
213 UniValue detail
= boost::apply_visitor(DescribeAddressVisitor(pwallet
), dest
);
215 if (pwallet
&& pwallet
->mapAddressBook
.count(dest
)) {
216 ret
.push_back(Pair("account", pwallet
->mapAddressBook
[dest
].name
));
220 const auto& meta
= pwallet
->mapKeyMetadata
;
221 auto it
= address
.GetKeyID(keyID
) ? meta
.find(keyID
) : meta
.end();
222 if (it
== meta
.end()) {
223 it
= meta
.find(CScriptID(scriptPubKey
));
225 if (it
!= meta
.end()) {
226 ret
.push_back(Pair("timestamp", it
->second
.nCreateTime
));
227 if (!it
->second
.hdKeypath
.empty()) {
228 ret
.push_back(Pair("hdkeypath", it
->second
.hdKeypath
));
229 ret
.push_back(Pair("hdmasterkeyid", it
->second
.hdMasterKeyID
.GetHex()));
238 // Needed even with !ENABLE_WALLET, to pass (ignored) pointers around
242 * Used by addmultisigaddress / createmultisig:
244 CScript
_createmultisig_redeemScript(CWallet
* const pwallet
, const UniValue
& params
)
246 int nRequired
= params
[0].get_int();
247 const UniValue
& keys
= params
[1].get_array();
249 // Gather public keys
251 throw runtime_error("a multisignature address must require at least one key to redeem");
252 if ((int)keys
.size() < nRequired
)
254 strprintf("not enough keys supplied "
255 "(got %u keys, but need at least %d to redeem)", keys
.size(), nRequired
));
256 if (keys
.size() > 16)
257 throw runtime_error("Number of addresses involved in the multisignature address creation > 16\nReduce the number");
258 std::vector
<CPubKey
> pubkeys
;
259 pubkeys
.resize(keys
.size());
260 for (unsigned int i
= 0; i
< keys
.size(); i
++)
262 const std::string
& ks
= keys
[i
].get_str();
264 // Case 1: Bitcoin address and we have full public key:
265 CBitcoinAddress
address(ks
);
266 if (pwallet
&& address
.IsValid()) {
268 if (!address
.GetKeyID(keyID
))
270 strprintf("%s does not refer to a key",ks
));
272 if (!pwallet
->GetPubKey(keyID
, vchPubKey
)) {
274 strprintf("no full public key for address %s",ks
));
276 if (!vchPubKey
.IsFullyValid())
277 throw runtime_error(" Invalid public key: "+ks
);
278 pubkeys
[i
] = vchPubKey
;
281 // Case 2: hex public key
286 CPubKey
vchPubKey(ParseHex(ks
));
287 if (!vchPubKey
.IsFullyValid())
288 throw runtime_error(" Invalid public key: "+ks
);
289 pubkeys
[i
] = vchPubKey
;
293 throw runtime_error(" Invalid public key: "+ks
);
296 CScript result
= GetScriptForMultisig(nRequired
, pubkeys
);
298 if (result
.size() > MAX_SCRIPT_ELEMENT_SIZE
)
300 strprintf("redeemScript exceeds size limit: %d > %d", result
.size(), MAX_SCRIPT_ELEMENT_SIZE
));
305 UniValue
createmultisig(const JSONRPCRequest
& request
)
308 CWallet
* const pwallet
= GetWalletForJSONRPCRequest(request
);
310 CWallet
* const pwallet
= NULL
;
313 if (request
.fHelp
|| request
.params
.size() < 2 || request
.params
.size() > 2)
315 string msg
= "createmultisig nrequired [\"key\",...]\n"
316 "\nCreates a multi-signature address with n signature of m keys required.\n"
317 "It returns a json object with the address and redeemScript.\n"
320 "1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n"
321 "2. \"keys\" (string, required) A json array of keys which are bitcoin addresses or hex-encoded public keys\n"
323 " \"key\" (string) bitcoin address or hex-encoded public key\n"
329 " \"address\":\"multisigaddress\", (string) The value of the new multisig address.\n"
330 " \"redeemScript\":\"script\" (string) The string value of the hex-encoded redemption script.\n"
334 "\nCreate a multisig address from 2 addresses\n"
335 + HelpExampleCli("createmultisig", "2 \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"") +
336 "\nAs a json rpc call\n"
337 + HelpExampleRpc("createmultisig", "2, \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"")
339 throw runtime_error(msg
);
342 // Construct using pay-to-script-hash:
343 CScript inner
= _createmultisig_redeemScript(pwallet
, request
.params
);
344 CScriptID
innerID(inner
);
345 CBitcoinAddress
address(innerID
);
347 UniValue
result(UniValue::VOBJ
);
348 result
.push_back(Pair("address", address
.ToString()));
349 result
.push_back(Pair("redeemScript", HexStr(inner
.begin(), inner
.end())));
354 UniValue
verifymessage(const JSONRPCRequest
& request
)
356 if (request
.fHelp
|| request
.params
.size() != 3)
358 "verifymessage \"address\" \"signature\" \"message\"\n"
359 "\nVerify a signed message\n"
361 "1. \"address\" (string, required) The bitcoin address to use for the signature.\n"
362 "2. \"signature\" (string, required) The signature provided by the signer in base 64 encoding (see signmessage).\n"
363 "3. \"message\" (string, required) The message that was signed.\n"
365 "true|false (boolean) If the signature is verified or not.\n"
367 "\nUnlock the wallet for 30 seconds\n"
368 + HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") +
369 "\nCreate the signature\n"
370 + HelpExampleCli("signmessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" \"my message\"") +
371 "\nVerify the signature\n"
372 + HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" \"signature\" \"my message\"") +
374 + HelpExampleRpc("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\", \"signature\", \"my message\"")
379 string strAddress
= request
.params
[0].get_str();
380 string strSign
= request
.params
[1].get_str();
381 string strMessage
= request
.params
[2].get_str();
383 CBitcoinAddress
addr(strAddress
);
385 throw JSONRPCError(RPC_TYPE_ERROR
, "Invalid address");
388 if (!addr
.GetKeyID(keyID
))
389 throw JSONRPCError(RPC_TYPE_ERROR
, "Address does not refer to key");
391 bool fInvalid
= false;
392 vector
<unsigned char> vchSig
= DecodeBase64(strSign
.c_str(), &fInvalid
);
395 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY
, "Malformed base64 encoding");
397 CHashWriter
ss(SER_GETHASH
, 0);
398 ss
<< strMessageMagic
;
402 if (!pubkey
.RecoverCompact(ss
.GetHash(), vchSig
))
405 return (pubkey
.GetID() == keyID
);
408 UniValue
signmessagewithprivkey(const JSONRPCRequest
& request
)
410 if (request
.fHelp
|| request
.params
.size() != 2)
412 "signmessagewithprivkey \"privkey\" \"message\"\n"
413 "\nSign a message with the private key of an address\n"
415 "1. \"privkey\" (string, required) The private key to sign the message with.\n"
416 "2. \"message\" (string, required) The message to create a signature of.\n"
418 "\"signature\" (string) The signature of the message encoded in base 64\n"
420 "\nCreate the signature\n"
421 + HelpExampleCli("signmessagewithprivkey", "\"privkey\" \"my message\"") +
422 "\nVerify the signature\n"
423 + HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" \"signature\" \"my message\"") +
425 + HelpExampleRpc("signmessagewithprivkey", "\"privkey\", \"my message\"")
428 string strPrivkey
= request
.params
[0].get_str();
429 string strMessage
= request
.params
[1].get_str();
431 CBitcoinSecret vchSecret
;
432 bool fGood
= vchSecret
.SetString(strPrivkey
);
434 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY
, "Invalid private key");
435 CKey key
= vchSecret
.GetKey();
437 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY
, "Private key outside allowed range");
439 CHashWriter
ss(SER_GETHASH
, 0);
440 ss
<< strMessageMagic
;
443 vector
<unsigned char> vchSig
;
444 if (!key
.SignCompact(ss
.GetHash(), vchSig
))
445 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY
, "Sign failed");
447 return EncodeBase64(&vchSig
[0], vchSig
.size());
450 UniValue
setmocktime(const JSONRPCRequest
& request
)
452 if (request
.fHelp
|| request
.params
.size() != 1)
454 "setmocktime timestamp\n"
455 "\nSet the local time to given timestamp (-regtest only)\n"
457 "1. timestamp (integer, required) Unix seconds-since-epoch timestamp\n"
458 " Pass 0 to go back to using the system time."
461 if (!Params().MineBlocksOnDemand())
462 throw runtime_error("setmocktime for regression testing (-regtest mode) only");
464 // For now, don't change mocktime if we're in the middle of validation, as
465 // this could have an effect on mempool time-based eviction, as well as
466 // IsCurrentForFeeEstimation() and IsInitialBlockDownload().
467 // TODO: figure out the right way to synchronize around mocktime, and
468 // ensure all call sites of GetTime() are accessing this safely.
471 RPCTypeCheck(request
.params
, boost::assign::list_of(UniValue::VNUM
));
472 SetMockTime(request
.params
[0].get_int64());
477 static UniValue
RPCLockedMemoryInfo()
479 LockedPool::Stats stats
= LockedPoolManager::Instance().stats();
480 UniValue
obj(UniValue::VOBJ
);
481 obj
.push_back(Pair("used", uint64_t(stats
.used
)));
482 obj
.push_back(Pair("free", uint64_t(stats
.free
)));
483 obj
.push_back(Pair("total", uint64_t(stats
.total
)));
484 obj
.push_back(Pair("locked", uint64_t(stats
.locked
)));
485 obj
.push_back(Pair("chunks_used", uint64_t(stats
.chunks_used
)));
486 obj
.push_back(Pair("chunks_free", uint64_t(stats
.chunks_free
)));
490 UniValue
getmemoryinfo(const JSONRPCRequest
& request
)
492 /* Please, avoid using the word "pool" here in the RPC interface or help,
493 * as users will undoubtedly confuse it with the other "memory pool"
495 if (request
.fHelp
|| request
.params
.size() != 0)
498 "Returns an object containing information about memory usage.\n"
501 " \"locked\": { (json object) Information about locked memory manager\n"
502 " \"used\": xxxxx, (numeric) Number of bytes used\n"
503 " \"free\": xxxxx, (numeric) Number of bytes available in current arenas\n"
504 " \"total\": xxxxxxx, (numeric) Total number of bytes managed\n"
505 " \"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"
506 " \"chunks_used\": xxxxx, (numeric) Number allocated chunks\n"
507 " \"chunks_free\": xxxxx, (numeric) Number unused chunks\n"
511 + HelpExampleCli("getmemoryinfo", "")
512 + HelpExampleRpc("getmemoryinfo", "")
514 UniValue
obj(UniValue::VOBJ
);
515 obj
.push_back(Pair("locked", RPCLockedMemoryInfo()));
519 UniValue
echo(const JSONRPCRequest
& request
)
523 "echo|echojson \"message\" ...\n"
524 "\nSimply echo back the input arguments. This command is for testing.\n"
525 "\nThe difference between echo and echojson is that echojson has argument conversion enabled in the client-side table in"
526 "bitcoin-cli and the GUI. There is no server-side difference."
529 return request
.params
;
532 static const CRPCCommand commands
[] =
533 { // category name actor (function) okSafeMode
534 // --------------------- ------------------------ ----------------------- ----------
535 { "control", "getinfo", &getinfo
, true, {} }, /* uses wallet if enabled */
536 { "control", "getmemoryinfo", &getmemoryinfo
, true, {} },
537 { "util", "validateaddress", &validateaddress
, true, {"address"} }, /* uses wallet if enabled */
538 { "util", "createmultisig", &createmultisig
, true, {"nrequired","keys"} },
539 { "util", "verifymessage", &verifymessage
, true, {"address","signature","message"} },
540 { "util", "signmessagewithprivkey", &signmessagewithprivkey
, true, {"privkey","message"} },
542 /* Not shown in help */
543 { "hidden", "setmocktime", &setmocktime
, true, {"timestamp"}},
544 { "hidden", "echo", &echo
, true, {"arg0","arg1","arg2","arg3","arg4","arg5","arg6","arg7","arg8","arg9"}},
545 { "hidden", "echojson", &echo
, true, {"arg0","arg1","arg2","arg3","arg4","arg5","arg6","arg7","arg8","arg9"}},
548 void RegisterMiscRPCCommands(CRPCTable
&t
)
550 for (unsigned int vcidx
= 0; vcidx
< ARRAYLEN(commands
); vcidx
++)
551 t
.appendCommand(commands
[vcidx
].name
, &commands
[vcidx
]);