Skip to content

Instantly share code, notes, and snippets.

@itsN1X
Last active May 8, 2019 17:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itsN1X/25506da6c201f9052831a4233ee9e7c3 to your computer and use it in GitHub Desktop.
Save itsN1X/25506da6c201f9052831a4233ee9e7c3 to your computer and use it in GitHub Desktop.
/*
z
src/rpc/misc.cpp
*
*/
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <base58.h>
#include <chain.h>
#include <clientversion.h>
#include <core_io.h>
#include <crypto/ripemd160.h>
#include <init.h>
#include <validation.h>
#include <httpserver.h>
#include <net.h>
#include <netbase.h>
#include <rpc/blockchain.h>
#include <rpc/server.h>
#include <rpc/util.h>
#include <timedata.h>
#include <util.h>
#include <utilstrencodings.h>
#include "ghostnode/ghostnode-sync.h"
#ifdef ENABLE_WALLET
#include <wallet/rpcwallet.h>
#include <wallet/wallet.h>
#include <wallet/walletdb.h>
#endif
#include <warnings.h>
#include "txmempool.h"
#include <uint256.h>
#include <stdint.h>
#ifdef HAVE_MALLOC_INFO
#include <malloc.h>
#endif
#include <univalue.h>
#ifdef ENABLE_WALLET
class DescribeAddressVisitor : public boost::static_visitor<UniValue>
{
public:
CWallet * const pwallet;
explicit DescribeAddressVisitor(CWallet *_pwallet) : pwallet(_pwallet) {}
void ProcessSubScript(const CScript& subscript, UniValue& obj, bool include_addresses = false) const
{
// Always present: script type and redeemscript
txnouttype which_type;
std::vector<std::vector<unsigned char>> solutions_data;
Solver(subscript, which_type, solutions_data, false);
obj.pushKV("script", GetTxnOutputType(which_type));
obj.pushKV("hex", HexStr(subscript.begin(), subscript.end()));
CTxDestination embedded;
UniValue a(UniValue::VARR);
if (ExtractDestination(subscript, embedded)) {
// Only when the script corresponds to an address.
UniValue subobj = boost::apply_visitor(*this, embedded);
subobj.pushKV("address", EncodeDestination(embedded));
subobj.pushKV("scriptPubKey", HexStr(subscript.begin(), subscript.end()));
// Always report the pubkey at the top level, so that `getnewaddress()['pubkey']` always works.
if (subobj.exists("pubkey")) obj.pushKV("pubkey", subobj["pubkey"]);
obj.pushKV("embedded", std::move(subobj));
if (include_addresses) a.push_back(EncodeDestination(embedded));
} else if (which_type == TX_MULTISIG) {
// Also report some information on multisig scripts (which do not have a corresponding address).
// TODO: abstract out the common functionality between this logic and ExtractDestinations.
obj.pushKV("sigsrequired", solutions_data[0][0]);
UniValue pubkeys(UniValue::VARR);
for (size_t i = 1; i < solutions_data.size() - 1; ++i) {
CPubKey key(solutions_data[i].begin(), solutions_data[i].end());
if (include_addresses) a.push_back(EncodeDestination(key.GetID()));
pubkeys.push_back(HexStr(key.begin(), key.end()));
}
obj.pushKV("pubkeys", std::move(pubkeys));
}
// The "addresses" field is confusing because it refers to public keys using their P2PKH address.
// For that reason, only add the 'addresses' field when needed for backward compatibility. New applications
// can use the 'embedded'->'address' field for P2SH or P2WSH wrapped addresses, and 'pubkeys' for
// inspecting multisig participants.
if (include_addresses) obj.pushKV("addresses", std::move(a));
}
UniValue operator()(const CNoDestination &dest) const { return UniValue(UniValue::VOBJ); }
UniValue operator()(const CKeyID &keyID) const {
UniValue obj(UniValue::VOBJ);
CPubKey vchPubKey;
obj.push_back(Pair("isscript", false));
obj.push_back(Pair("iswitness", false));
if (pwallet && pwallet->GetPubKey(keyID, vchPubKey)) {
obj.push_back(Pair("pubkey", HexStr(vchPubKey)));
obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed()));
}
return obj;
}
UniValue operator()(const CScriptID &scriptID) const {
UniValue obj(UniValue::VOBJ);
CScript subscript;
obj.push_back(Pair("isscript", true));
obj.push_back(Pair("iswitness", false));
if (pwallet && pwallet->GetCScript(scriptID, subscript)) {
ProcessSubScript(subscript, obj, true);
}
return obj;
}
UniValue operator()(const WitnessV0KeyHash& id) const
{
UniValue obj(UniValue::VOBJ);
CPubKey pubkey;
obj.push_back(Pair("isscript", false));
obj.push_back(Pair("iswitness", true));
obj.push_back(Pair("witness_version", 0));
obj.push_back(Pair("witness_program", HexStr(id.begin(), id.end())));
if (pwallet && pwallet->GetPubKey(CKeyID(id), pubkey)) {
obj.push_back(Pair("pubkey", HexStr(pubkey)));
}
return obj;
}
UniValue operator()(const CExtKeyPair &ekp) const {
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("isextkey", true));
return obj;
}
UniValue operator()(const CStealthAddress &sxAddr) const {
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("isstealthaddress", true));
obj.push_back(Pair("prefix_num_bits", sxAddr.prefix.number_bits));
obj.push_back(Pair("prefix_bitfield", strprintf("0x%04x", sxAddr.prefix.bitfield)));
return obj;
}
UniValue operator()(const CGhostAddress &sxAddr) const {
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("isghostaddress", true));
obj.push_back(Pair("prefix_num_bits", sxAddr.prefix.number_bits));
obj.push_back(Pair("prefix_bitfield", strprintf("0x%04x", sxAddr.prefix.bitfield)));
return obj;
}
UniValue operator()(const WitnessV0ScriptHash& id) const
{
UniValue obj(UniValue::VOBJ);
CScript subscript;
obj.push_back(Pair("isscript", true));
obj.push_back(Pair("iswitness", true));
obj.push_back(Pair("witness_version", 0));
obj.push_back(Pair("witness_program", HexStr(id.begin(), id.end())));
CRIPEMD160 hasher;
uint160 hash;
hasher.Write(id.begin(), 32).Finalize(hash.begin());
if (pwallet && pwallet->GetCScript(CScriptID(hash), subscript)) {
ProcessSubScript(subscript, obj);
}
return obj;
}
UniValue operator()(const WitnessUnknown& id) const
{
UniValue obj(UniValue::VOBJ);
CScript subscript;
obj.push_back(Pair("iswitness", true));
obj.push_back(Pair("witness_version", (int)id.version));
obj.push_back(Pair("witness_program", HexStr(id.program, id.program + id.length)));
return obj;
}
UniValue operator()(const CKeyID256 &idk256) const {
UniValue obj(UniValue::VOBJ);
CPubKey vchPubKey;
obj.push_back(Pair("isscript", false));
CKeyID id160(idk256);
if (pwallet && pwallet->GetPubKey(id160, vchPubKey)) {
obj.push_back(Pair("pubkey", HexStr(vchPubKey)));
obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed()));
}
return obj;
}
UniValue operator()(const CScriptID256 &scriptID256) const {
UniValue obj(UniValue::VOBJ);
CScript subscript;
obj.push_back(Pair("isscript", true));
CScriptID scriptID;
scriptID.Set(scriptID256);
if (pwallet && pwallet->GetCScript(scriptID, subscript)) {
std::vector<CTxDestination> addresses;
txnouttype whichType;
int nRequired;
ExtractDestinations(subscript, whichType, addresses, nRequired);
obj.push_back(Pair("script", GetTxnOutputType(whichType)));
obj.push_back(Pair("hex", HexStr(subscript.begin(), subscript.end())));
UniValue a(UniValue::VARR);
for (const CTxDestination& addr : addresses)
a.push_back(CBitcoinAddress(addr).ToString());
obj.push_back(Pair("addresses", a));
if (whichType == TX_MULTISIG)
obj.push_back(Pair("sigsrequired", nRequired));
}
return obj;
}
};
#endif
//Ghostnode
UniValue ghostnodesync(const JSONRPCRequest& req)
{
UniValue params = req.params;
bool fHelp = req.fHelp;
if (fHelp || params.size() != 1)
throw runtime_error(
"ghostnodesync [status|next|reset]\n"
"Returns the sync status, updates to the next step or resets it entirely.\n"
);
std::string strMode = params[0].get_str();
if(strMode == "status") {
UniValue objStatus(UniValue::VOBJ);
objStatus.push_back(Pair("AssetID", ghostnodeSync.GetAssetID()));
objStatus.push_back(Pair("AssetName", ghostnodeSync.GetAssetName()));
objStatus.push_back(Pair("Attempt", ghostnodeSync.GetAttempt()));
objStatus.push_back(Pair("IsBlockchainSynced", ghostnodeSync.IsBlockchainSynced()));
objStatus.push_back(Pair("IsGhostnodeListSynced", ghostnodeSync.IsGhostnodeListSynced()));
objStatus.push_back(Pair("IsWinnersListSynced", ghostnodeSync.IsWinnersListSynced()));
objStatus.push_back(Pair("IsSynced", ghostnodeSync.IsSynced()));
objStatus.push_back(Pair("IsFailed", ghostnodeSync.IsFailed()));
return objStatus;
}
if(strMode == "next")
{
ghostnodeSync.SwitchToNextAsset();
return "sync updated to " + ghostnodeSync.GetAssetName();
}
if(strMode == "reset")
{
ghostnodeSync.Reset();
return "success";
}
return "failure";
}
UniValue validateaddress(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"validateaddress \"address\"\n"
"\nReturn information about the given nix address.\n"
"\nArguments:\n"
"1. \"address\" (string, required) The nix address to validate\n"
"\nResult:\n"
"{\n"
" \"isvalid\" : true|false, (boolean) If the address is valid or not. If not, this is the only property returned.\n"
" \"address\" : \"address\", (string) The nix address validated\n"
" \"scriptPubKey\" : \"hex\", (string) The hex encoded scriptPubKey generated by the address\n"
" \"ismine\" : true|false, (boolean) If the address is yours or not\n"
" \"iswatchonly\" : true|false, (boolean) If the address is watchonly\n"
" \"isscript\" : true|false, (boolean, optional) If the address is P2SH or P2WSH. Not included for unknown witness types.\n"
" \"iswitness\" : true|false, (boolean) If the address is P2WPKH, P2WSH, or an unknown witness version\n"
" \"witness_version\" : version (number, optional) For all witness output types, gives the version number.\n"
" \"witness_program\" : \"hex\" (string, optional) For all witness output types, gives the script or key hash present in the address.\n"
" \"script\" : \"type\" (string, optional) The output script type. Only if \"isscript\" is true and the redeemscript is known. Possible types: nonstandard, pubkey, pubkeyhash, scripthash, multisig, nulldata, witness_v0_keyhash, witness_v0_scripthash, witness_unknown\n"
" \"hex\" : \"hex\", (string, optional) The redeemscript for the P2SH or P2WSH address\n"
" \"addresses\" (string, optional) Array of addresses associated with the known redeemscript (only if \"iswitness\" is false). This field is superseded by the \"pubkeys\" field and the address inside \"embedded\".\n"
" [\n"
" \"address\"\n"
" ,...\n"
" ]\n"
" \"pubkeys\" (string, optional) Array of pubkeys associated with the known redeemscript (only if \"script\" is \"multisig\")\n"
" [\n"
" \"pubkey\"\n"
" ,...\n"
" ]\n"
" \"sigsrequired\" : xxxxx (numeric, optional) Number of signatures required to spend multisig output (only if \"script\" is \"multisig\")\n"
" \"pubkey\" : \"publickeyhex\", (string, optional) The hex value of the raw public key, for single-key addresses (possibly embedded in P2SH or P2WSH)\n"
" \"embedded\" : {...}, (object, optional) information about the address embedded in P2SH or P2WSH, if relevant and known. It includes all validateaddress output fields for the embedded address, excluding \"isvalid\", metadata (\"timestamp\", \"hdkeypath\", \"hdmasterkeyid\") and relation to the wallet (\"ismine\", \"iswatchonly\", \"account\").\n"
" \"iscompressed\" : true|false, (boolean) If the address is compressed\n"
" \"account\" : \"account\" (string) DEPRECATED. The account associated with the address, \"\" is the default account\n"
" \"timestamp\" : timestamp, (number, optional) The creation time of the key if available in seconds since epoch (Jan 1 1970 GMT)\n"
" \"hdkeypath\" : \"keypath\" (string, optional) The HD keypath if the key is HD and available\n"
" \"hdmasterkeyid\" : \"<hash160>\" (string, optional) The Hash160 of the HD master pubkey\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"")
+ HelpExampleRpc("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"")
);
#ifdef ENABLE_WALLET
CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
LOCK2(cs_main, pwallet ? &pwallet->cs_wallet : nullptr);
#else
LOCK(cs_main);
#endif
CTxDestination dest = DecodeDestination(request.params[0].get_str());
bool isValid = IsValidDestination(dest);
UniValue ret(UniValue::VOBJ);
ret.push_back(Pair("isvalid", isValid));
if (isValid)
{
std::string currentAddress = EncodeDestination(dest);
ret.push_back(Pair("address", currentAddress));
CScript scriptPubKey = GetScriptForDestination(dest);
ret.push_back(Pair("scriptPubKey", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
#ifdef ENABLE_WALLET
isminetype mine = pwallet ? IsMine(*pwallet, dest) : ISMINE_NO;
ret.push_back(Pair("ismine", bool(mine & ISMINE_SPENDABLE)));
ret.push_back(Pair("iswatchonly", bool(mine & ISMINE_WATCH_ONLY)));
UniValue detail = boost::apply_visitor(DescribeAddressVisitor(pwallet), dest);
ret.pushKVs(detail);
if (pwallet && pwallet->mapAddressBook.count(dest)) {
ret.push_back(Pair("account", pwallet->mapAddressBook[dest].name));
}
if (pwallet) {
const CKeyMetadata* meta = nullptr;
CKeyID key_id = GetKeyForDestination(*pwallet, dest);
if (!key_id.IsNull()) {
auto it = pwallet->mapKeyMetadata.find(key_id);
if (it != pwallet->mapKeyMetadata.end()) {
meta = &it->second;
}
}
if (!meta) {
auto it = pwallet->m_script_metadata.find(CScriptID(scriptPubKey));
if (it != pwallet->m_script_metadata.end()) {
meta = &it->second;
}
}
if (meta) {
ret.push_back(Pair("timestamp", meta->nCreateTime));
if (!meta->hdKeypath.empty()) {
ret.push_back(Pair("hdkeypath", meta->hdKeypath));
ret.push_back(Pair("hdmasterkeyid", meta->hdMasterKeyID.GetHex()));
}
}
}
#endif
}
return ret;
}
// Needed even with !ENABLE_WALLET, to pass (ignored) pointers around
class CWallet;
UniValue createmultisig(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 2 || request.params.size() > 2)
{
std::string msg = "createmultisig nrequired [\"key\",...]\n"
"\nCreates a multi-signature address with n signature of m keys required.\n"
"It returns a json object with the address and redeemScript.\n"
"DEPRECATION WARNING: Using addresses with createmultisig is deprecated. Clients must\n"
"transition to using addmultisigaddress to create multisig addresses with addresses known\n"
"to the wallet before upgrading to v0.17. To use the deprecated functionality, start nixd with -deprecatedrpc=createmultisig\n"
"\nArguments:\n"
"1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n"
"2. \"keys\" (string, required) A json array of hex-encoded public keys\n"
" [\n"
" \"key\" (string) The hex-encoded public key\n"
" ,...\n"
" ]\n"
"\nResult:\n"
"{\n"
" \"address\":\"multisigaddress\", (string) The value of the new multisig address.\n"
" \"redeemScript\":\"script\" (string) The string value of the hex-encoded redemption script.\n"
"}\n"
"\nExamples:\n"
"\nCreate a multisig address from 2 public keys\n"
+ HelpExampleCli("createmultisig", "2 \"[\\\"03789ed0bb717d88f7d321a368d905e7430207ebbd82bd342cf11ae157a7ace5fd\\\",\\\"03dbc6764b8884a92e871274b87583e6d5c2a58819473e17e107ef3f6aa5a61626\\\"]\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("createmultisig", "2, \"[\\\"03789ed0bb717d88f7d321a368d905e7430207ebbd82bd342cf11ae157a7ace5fd\\\",\\\"03dbc6764b8884a92e871274b87583e6d5c2a58819473e17e107ef3f6aa5a61626\\\"]\"")
;
throw std::runtime_error(msg);
}
int required = request.params[0].get_int();
// Get the public keys
const UniValue& keys = request.params[1].get_array();
std::vector<CPubKey> pubkeys;
for (unsigned int i = 0; i < keys.size(); ++i) {
if (IsHex(keys[i].get_str()) && (keys[i].get_str().length() == 66 || keys[i].get_str().length() == 130)) {
pubkeys.push_back(HexToPubKey(keys[i].get_str()));
} else {
#ifdef ENABLE_WALLET
CWallet* const pwallet = GetWalletForJSONRPCRequest(request);
if (IsDeprecatedRPCEnabled("createmultisig") && EnsureWalletIsAvailable(pwallet, false)) {
pubkeys.push_back(AddrToPubKey(pwallet, keys[i].get_str()));
} else
#endif
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Invalid public key: %s\nNote that from v0.16, createmultisig no longer accepts addresses."
" Clients must transition to using addmultisigaddress to create multisig addresses with addresses known to the wallet before upgrading to v0.17."
" To use the deprecated functionality, start nixd with -deprecatedrpc=createmultisig", keys[i].get_str()));
}
}
// Construct using pay-to-script-hash:
CScript inner = CreateMultisigRedeemscript(required, pubkeys);
CScriptID innerID(inner);
UniValue result(UniValue::VOBJ);
result.push_back(Pair("address", EncodeDestination(innerID)));
result.push_back(Pair("redeemScript", HexStr(inner.begin(), inner.end())));
return result;
}
UniValue verifymessage(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 3)
throw std::runtime_error(
"verifymessage \"address\" \"signature\" \"message\"\n"
"\nVerify a signed message\n"
"\nArguments:\n"
"1. \"address\" (string, required) The nix address to use for the signature.\n"
"2. \"signature\" (string, required) The signature provided by the signer in base 64 encoding (see signmessage).\n"
"3. \"message\" (string, required) The message that was signed.\n"
"\nResult:\n"
"true|false (boolean) If the signature is verified or not.\n"
"\nExamples:\n"
"\nUnlock the wallet for 30 seconds\n"
+ HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") +
"\nCreate the signature\n"
+ HelpExampleCli("signmessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"my message\"") +
"\nVerify the signature\n"
+ HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"signature\" \"my message\"") +
"\nAs json rpc\n"
+ HelpExampleRpc("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\", \"signature\", \"my message\"")
);
LOCK(cs_main);
std::string strAddress = request.params[0].get_str();
std::string strSign = request.params[1].get_str();
std::string strMessage = request.params[2].get_str();
CTxDestination destination = DecodeDestination(strAddress);
if (!IsValidDestination(destination)) {
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
}
CKeyID *tempKey;
if (auto id = boost::get<CKeyID>(&destination)) {
tempKey = id;
}
else if (auto witness_id = boost::get<WitnessV0KeyHash>(&destination)) {
tempKey = new CKeyID;
*tempKey = CKeyID(*witness_id);
}
else
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
const CKeyID *keyID = tempKey;
if (!keyID) {
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
}
/*
const CKeyID *keyID = boost::get<CKeyID>(&destination);
if (!keyID) {
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
}
*/
bool fInvalid = false;
std::vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);
if (fInvalid)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding");
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
CPubKey pubkey;
if (!pubkey.RecoverCompact(ss.GetHash(), vchSig))
return false;
return (pubkey.GetID() == *keyID);
}
UniValue signmessagewithprivkey(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 2)
throw std::runtime_error(
"signmessagewithprivkey \"privkey\" \"message\"\n"
"\nSign a message with the private key of an address\n"
"\nArguments:\n"
"1. \"privkey\" (string, required) The private key to sign the message with.\n"
"2. \"message\" (string, required) The message to create a signature of.\n"
"\nResult:\n"
"\"signature\" (string) The signature of the message encoded in base 64\n"
"\nExamples:\n"
"\nCreate the signature\n"
+ HelpExampleCli("signmessagewithprivkey", "\"privkey\" \"my message\"") +
"\nVerify the signature\n"
+ HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"signature\" \"my message\"") +
"\nAs json rpc\n"
+ HelpExampleRpc("signmessagewithprivkey", "\"privkey\", \"my message\"")
);
std::string strPrivkey = request.params[0].get_str();
std::string strMessage = request.params[1].get_str();
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(strPrivkey);
if (!fGood)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
CKey key = vchSecret.GetKey();
if (!key.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
std::vector<unsigned char> vchSig;
if (!key.SignCompact(ss.GetHash(), vchSig))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
return EncodeBase64(vchSig.data(), vchSig.size());
}
UniValue setmocktime(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"setmocktime timestamp\n"
"\nSet the local time to given timestamp (-regtest only)\n"
"\nArguments:\n"
"1. timestamp (integer, required) Unix seconds-since-epoch timestamp\n"
" Pass 0 to go back to using the system time."
);
if (!Params().MineBlocksOnDemand())
throw std::runtime_error("setmocktime for regression testing (-regtest mode) only");
// For now, don't change mocktime if we're in the middle of validation, as
// this could have an effect on mempool time-based eviction, as well as
// IsCurrentForFeeEstimation() and IsInitialBlockDownload().
// TODO: figure out the right way to synchronize around mocktime, and
// ensure all call sites of GetTime() are accessing this safely.
LOCK(cs_main);
RPCTypeCheck(request.params, {UniValue::VNUM});
SetMockTime(request.params[0].get_int64());
return NullUniValue;
}
static UniValue RPCLockedMemoryInfo()
{
LockedPool::Stats stats = LockedPoolManager::Instance().stats();
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("used", uint64_t(stats.used)));
obj.push_back(Pair("free", uint64_t(stats.free)));
obj.push_back(Pair("total", uint64_t(stats.total)));
obj.push_back(Pair("locked", uint64_t(stats.locked)));
obj.push_back(Pair("chunks_used", uint64_t(stats.chunks_used)));
obj.push_back(Pair("chunks_free", uint64_t(stats.chunks_free)));
return obj;
}
#ifdef HAVE_MALLOC_INFO
static std::string RPCMallocInfo()
{
char *ptr = nullptr;
size_t size = 0;
FILE *f = open_memstream(&ptr, &size);
if (f) {
malloc_info(0, f);
fclose(f);
if (ptr) {
std::string rv(ptr, size);
free(ptr);
return rv;
}
}
return "";
}
#endif
UniValue getmemoryinfo(const JSONRPCRequest& request)
{
/* Please, avoid using the word "pool" here in the RPC interface or help,
* as users will undoubtedly confuse it with the other "memory pool"
*/
if (request.fHelp || request.params.size() > 1)
throw std::runtime_error(
"getmemoryinfo (\"mode\")\n"
"Returns an object containing information about memory usage.\n"
"Arguments:\n"
"1. \"mode\" determines what kind of information is returned. This argument is optional, the default mode is \"stats\".\n"
" - \"stats\" returns general statistics about memory usage in the daemon.\n"
" - \"mallocinfo\" returns an XML string describing low-level heap state (only available if compiled with glibc 2.10+).\n"
"\nResult (mode \"stats\"):\n"
"{\n"
" \"locked\": { (json object) Information about locked memory manager\n"
" \"used\": xxxxx, (numeric) Number of bytes used\n"
" \"free\": xxxxx, (numeric) Number of bytes available in current arenas\n"
" \"total\": xxxxxxx, (numeric) Total number of bytes managed\n"
" \"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"
" \"chunks_used\": xxxxx, (numeric) Number allocated chunks\n"
" \"chunks_free\": xxxxx, (numeric) Number unused chunks\n"
" }\n"
"}\n"
"\nResult (mode \"mallocinfo\"):\n"
"\"<malloc version=\"1\">...\"\n"
"\nExamples:\n"
+ HelpExampleCli("getmemoryinfo", "")
+ HelpExampleRpc("getmemoryinfo", "")
);
std::string mode = request.params[0].isNull() ? "stats" : request.params[0].get_str();
if (mode == "stats") {
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("locked", RPCLockedMemoryInfo()));
return obj;
} else if (mode == "mallocinfo") {
#ifdef HAVE_MALLOC_INFO
return RPCMallocInfo();
#else
throw JSONRPCError(RPC_INVALID_PARAMETER, "mallocinfo is only available when compiled with glibc 2.10+");
#endif
} else {
throw JSONRPCError(RPC_INVALID_PARAMETER, "unknown mode " + mode);
}
}
uint32_t getCategoryMask(UniValue cats) {
cats = cats.get_array();
uint32_t mask = 0;
for (unsigned int i = 0; i < cats.size(); ++i) {
uint32_t flag = 0;
std::string cat = cats[i].get_str();
if (!GetLogCategory(&flag, &cat)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "unknown logging category " + cat);
}
if (flag == BCLog::NONE) {
return 0;
}
mask |= flag;
}
return mask;
}
UniValue logging(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() > 2) {
throw std::runtime_error(
"logging ( <include> <exclude> )\n"
"Gets and sets the logging configuration.\n"
"When called without an argument, returns the list of categories with status that are currently being debug logged or not.\n"
"When called with arguments, adds or removes categories from debug logging and return the lists above.\n"
"The arguments are evaluated in order \"include\", \"exclude\".\n"
"If an item is both included and excluded, it will thus end up being excluded.\n"
"The valid logging categories are: " + ListLogCategories() + "\n"
"In addition, the following are available as category names with special meanings:\n"
" - \"all\", \"1\" : represent all logging categories.\n"
" - \"none\", \"0\" : even if other logging categories are specified, ignore all of them.\n"
"\nArguments:\n"
"1. \"include\" (array of strings, optional) A json array of categories to add debug logging\n"
" [\n"
" \"category\" (string) the valid logging category\n"
" ,...\n"
" ]\n"
"2. \"exclude\" (array of strings, optional) A json array of categories to remove debug logging\n"
" [\n"
" \"category\" (string) the valid logging category\n"
" ,...\n"
" ]\n"
"\nResult:\n"
"{ (json object where keys are the logging categories, and values indicates its status\n"
" \"category\": 0|1, (numeric) if being debug logged or not. 0:inactive, 1:active\n"
" ...\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("logging", "\"[\\\"all\\\"]\" \"[\\\"http\\\"]\"")
+ HelpExampleRpc("logging", "[\"all\"], \"[libevent]\"")
);
}
uint32_t originalLogCategories = logCategories;
if (request.params[0].isArray()) {
logCategories |= getCategoryMask(request.params[0]);
}
if (request.params[1].isArray()) {
logCategories &= ~getCategoryMask(request.params[1]);
}
// Update libevent logging if BCLog::LIBEVENT has changed.
// If the library version doesn't allow it, UpdateHTTPServerLogging() returns false,
// in which case we should clear the BCLog::LIBEVENT flag.
// Throw an error if the user has explicitly asked to change only the libevent
// flag and it failed.
uint32_t changedLogCategories = originalLogCategories ^ logCategories;
if (changedLogCategories & BCLog::LIBEVENT) {
if (!UpdateHTTPServerLogging(logCategories & BCLog::LIBEVENT)) {
logCategories &= ~BCLog::LIBEVENT;
if (changedLogCategories == BCLog::LIBEVENT) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "libevent logging cannot be updated when using libevent before v2.1.1.");
}
}
}
UniValue result(UniValue::VOBJ);
std::vector<CLogCategoryActive> vLogCatActive = ListActiveLogCategories();
for (const auto& logCatActive : vLogCatActive) {
result.pushKV(logCatActive.category, logCatActive.active);
}
return result;
}
UniValue echo(const JSONRPCRequest& request)
{
if (request.fHelp)
throw std::runtime_error(
"echo|echojson \"message\" ...\n"
"\nSimply echo back the input arguments. This command is for testing.\n"
"\nThe difference between echo and echojson is that echojson has argument conversion enabled in the client-side table in"
"nix-cli and the GUI. There is no server-side difference."
);
return request.params;
}
static UniValue getinfo_deprecated(const JSONRPCRequest& request)
{
throw JSONRPCError(RPC_METHOD_NOT_FOUND,
"getinfo\n"
"\nThis call was removed in version 0.16.0. Use the appropriate fields from:\n"
"- getblockchaininfo: blocks, difficulty, chain\n"
"- getnetworkinfo: version, protocolversion, timeoffset, connections, proxy, relayfee, warnings\n"
"- getwalletinfo: balance, keypoololdest, keypoolsize, paytxfee, unlocked_until, walletversion\n"
"\nnix-cli has the option -getinfo to collect and format these in the old format."
);
}
bool getAddressFromIndex(const int &type, const uint256 &hash, std::string &address)
{
if (type == ADDR_INDT_SCRIPT_ADDRESS) {
address = EncodeDestination(CScriptID(uint160(hash.begin(), 20)));
} else if (type == ADDR_INDT_PUBKEY_ADDRESS) {
address = EncodeDestination(CKeyID(uint160(hash.begin(), 20)));
} else if (type == ADDR_INDT_WITNESS_KEY_HASH) {
address = EncodeDestination(WitnessV0KeyHash(uint160(hash.begin(), 20)), true);
} else {
return false;
}
return true;
}
bool getAddressesFromParams(const UniValue& params, std::vector<std::pair<uint256, int> > &addresses)
{
if (params[0].isStr()) {
CTxDestination des = DecodeDestination(params[0].get_str());
if(des.type() == typeid(WitnessV0KeyHash)){
CScript desScript = GetScriptForDestination(des);
std::vector<uint8_t> hashBytes;
hashBytes.assign(desScript.begin()+2, desScript.begin()+22);
uint256 hashByte = uint256(hashBytes.data(), hashBytes.size());
int type = ADDR_INDT_WITNESS_KEY_HASH;
addresses.push_back(std::make_pair(hashByte, type));
}
else{
CBitcoinAddress address(params[0].get_str());
uint256 hashBytes;
int type = 0;
if (!address.GetIndexKey(hashBytes, type)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
}
addresses.push_back(std::make_pair(hashBytes, type));
}
} else if (params[0].isObject()) {
UniValue addressValues = find_value(params[0].get_obj(), "addresses");
if (!addressValues.isArray()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Addresses is expected to be an array");
}
std::vector<UniValue> values = addressValues.getValues();
for (std::vector<UniValue>::iterator it = values.begin(); it != values.end(); ++it) {
CTxDestination des = DecodeDestination(it->get_str());
if(des.type() == typeid(WitnessV0KeyHash)){
CScript desScript = GetScriptForDestination(des);
std::vector<uint8_t> hashBytes;
hashBytes.assign(desScript.begin()+2, desScript.begin()+22);
uint256 hashByte = uint256(hashBytes.data(), hashBytes.size());
int type = ADDR_INDT_WITNESS_KEY_HASH;
addresses.push_back(std::make_pair(hashByte, type));
}
else{
CBitcoinAddress address(it->get_str());
uint256 hashBytes;
int type = 0;
if (!address.GetIndexKey(hashBytes, type)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
}
addresses.push_back(std::make_pair(hashBytes, type));
}
}
} else {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
}
return true;
}
bool heightSort(std::pair<CAddressUnspentKey, CAddressUnspentValue> a,
std::pair<CAddressUnspentKey, CAddressUnspentValue> b) {
return a.second.blockHeight < b.second.blockHeight;
}
bool timestampSort(std::pair<CMempoolAddressDeltaKey, CMempoolAddressDelta> a,
std::pair<CMempoolAddressDeltaKey, CMempoolAddressDelta> b) {
return a.second.time < b.second.time;
}
UniValue getaddressmempool(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw runtime_error(
"getaddressmempool\n"
"\nReturns all mempool deltas for an address (requires addressindex to be enabled).\n"
"\nArguments:\n"
"{\n"
" \"addresses\"\n"
" [\n"
" \"address\" (string) The base58check encoded address\n"
" ,...\n"
" ]\n"
"}\n"
"\nResult:\n"
"[\n"
" {\n"
" \"address\" (string) The base58check encoded address\n"
" \"txid\" (string) The related txid\n"
" \"index\" (number) The related input or output index\n"
" \"satoshis\" (number) The difference of duffs\n"
" \"timestamp\" (number) The time the transaction entered the mempool (seconds)\n"
" \"prevtxid\" (string) The previous txid (if spending)\n"
" \"prevout\" (string) The previous transaction output index (if spending)\n"
" }\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("getaddressmempool", "'{\"addresses\": [\"NwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"]}'")
+ HelpExampleRpc("getaddressmempool", "{\"addresses\": [\"NwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"]}")
);
std::vector<std::pair<uint256, int> > addresses;
if (!getAddressesFromParams(request.params, addresses)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
}
std::vector<std::pair<CMempoolAddressDeltaKey, CMempoolAddressDelta> > indexes;
if (!mempool.getAddressIndex(addresses, indexes)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available for address");
}
std::sort(indexes.begin(), indexes.end(), timestampSort);
UniValue result(UniValue::VARR);
for (std::vector<std::pair<CMempoolAddressDeltaKey, CMempoolAddressDelta> >::iterator it = indexes.begin(); it != indexes.end(); it++) {
std::string address;
if (!getAddressFromIndex(it->first.type, it->first.addressBytes, address)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unknown address type");
}
UniValue delta(UniValue::VOBJ);
delta.push_back(Pair("address", address));
delta.push_back(Pair("txid", it->first.txhash.GetHex()));
delta.push_back(Pair("index", (int)it->first.index));
delta.push_back(Pair("satoshis", it->second.amount));
delta.push_back(Pair("timestamp", it->second.time));
if (it->second.amount < 0) {
delta.push_back(Pair("prevtxid", it->second.prevhash.GetHex()));
delta.push_back(Pair("prevout", (int)it->second.prevout));
}
result.push_back(delta);
}
return result;
}
UniValue getaddressutxos(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw runtime_error(
"getaddressutxos\n"
"\nReturns all unspent outputs for an address (requires addressindex to be enabled).\n"
"\nArguments:\n"
"{\n"
" \"addresses\"\n"
" [\n"
" \"address\" (string) The base58check encoded address\n"
" ,...\n"
" ]\n"
"}\n"
"\nResult\n"
"[\n"
" {\n"
" \"address\" (string) The address base58check encoded\n"
" \"txid\" (string) The output txid\n"
" \"outputIndex\" (number) The output index\n"
" \"script\" (string) The script hex encoded\n"
" \"satoshis\" (number) The number of duffs of the output\n"
" \"height\" (number) The block height\n"
" }\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("getaddressutxos", "'{\"addresses\": [\"NwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"]}'")
+ HelpExampleRpc("getaddressutxos", "{\"addresses\": [\"NwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"]}")
);
std::vector<std::pair<uint256, int> > addresses;
if (!getAddressesFromParams(request.params, addresses)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
}
std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > unspentOutputs;
for (std::vector<std::pair<uint256, int> >::iterator it = addresses.begin(); it != addresses.end(); it++) {
if (!GetAddressUnspent((*it).first, (*it).second, unspentOutputs)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available for address");
}
}
std::sort(unspentOutputs.begin(), unspentOutputs.end(), heightSort);
UniValue result(UniValue::VARR);
for (std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) {
UniValue output(UniValue::VOBJ);
std::string address;
if (!getAddressFromIndex(it->first.type, it->first.hashBytes, address)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unknown address type");
}
output.push_back(Pair("address", address));
output.push_back(Pair("txid", it->first.txhash.GetHex()));
output.push_back(Pair("outputIndex", (int)it->first.index));
output.push_back(Pair("script", HexStr(it->second.script.begin(), it->second.script.end())));
output.push_back(Pair("satoshis", it->second.satoshis));
output.push_back(Pair("height", it->second.blockHeight));
result.push_back(output);
}
return result;
}
UniValue getaddressdeltas(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1 || !request.params[0].isObject())
throw runtime_error(
"getaddressdeltas\n"
"\nReturns all changes for an address (requires addressindex to be enabled).\n"
"\nArguments:\n"
"{\n"
" \"addresses\"\n"
" [\n"
" \"address\" (string) The base58check encoded address\n"
" ,...\n"
" ]\n"
" \"start\" (number) The start block height\n"
" \"end\" (number) The end block height\n"
"}\n"
"\nResult:\n"
"[\n"
" {\n"
" \"satoshis\" (number) The difference of duffs\n"
" \"txid\" (string) The related txid\n"
" \"index\" (number) The related input or output index\n"
" \"blockindex\" (number) The related block index\n"
" \"height\" (number) The block height\n"
" \"address\" (string) The base58check encoded address\n"
" }\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("getaddressdeltas", "'{\"addresses\": [\"NwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"]}'")
+ HelpExampleRpc("getaddressdeltas", "{\"addresses\": [\"NwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"]}")
);
UniValue startValue = find_value(request.params[0].get_obj(), "start");
UniValue endValue = find_value(request.params[0].get_obj(), "end");
int start = 0;
int end = 0;
if (startValue.isNum() && endValue.isNum()) {
start = startValue.get_int();
end = endValue.get_int();
if (end < start) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "End value is expected to be greater than start");
}
}
std::vector<std::pair<uint256, int> > addresses;
if (!getAddressesFromParams(request.params, addresses)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
}
std::vector<std::pair<CAddressIndexKey, CAmount> > addressIndex;
for (std::vector<std::pair<uint256, int> >::iterator it = addresses.begin(); it != addresses.end(); it++) {
if (start > 0 && end > 0) {
if (!GetAddressIndex((*it).first, (*it).second, addressIndex, start, end)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available for address");
}
} else {
if (!GetAddressIndex((*it).first, (*it).second, addressIndex)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available for address");
}
}
}
UniValue result(UniValue::VARR);
for (std::vector<std::pair<CAddressIndexKey, CAmount> >::const_iterator it=addressIndex.begin(); it!=addressIndex.end(); it++) {
std::string address;
if (!getAddressFromIndex(it->first.type, it->first.hashBytes, address)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unknown address type");
}
UniValue delta(UniValue::VOBJ);
delta.push_back(Pair("satoshis", it->second));
delta.push_back(Pair("txid", it->first.txhash.GetHex()));
delta.push_back(Pair("index", (int)it->first.index));
delta.push_back(Pair("blockindex", (int)it->first.txindex));
delta.push_back(Pair("height", it->first.blockHeight));
delta.push_back(Pair("address", address));
result.push_back(delta);
}
return result;
}
UniValue getaddressbalance(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw runtime_error(
"getaddressbalance\n"
"\nReturns the balance for an address(es) (requires addressindex to be enabled).\n"
"\nArguments:\n"
"{\n"
" \"addresses\"\n"
" [\n"
" \"address\" (string) The base58check encoded address\n"
" ,...\n"
" ]\n"
"}\n"
"\nResult:\n"
"{\n"
" \"balance\" (string) The current balance in duffs\n"
" \"received\" (string) The total number of duffs received (including change)\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getaddressbalance", "'{\"addresses\": [\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"]}'")
+ HelpExampleRpc("getaddressbalance", "{\"addresses\": [\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"]}")
);
std::vector<std::pair<uint256, int> > addresses;
if (!getAddressesFromParams(request.params, addresses)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
}
std::vector<std::pair<CAddressIndexKey, CAmount> > addressIndex;
for (std::vector<std::pair<uint256, int> >::iterator it = addresses.begin(); it != addresses.end(); it++) {
if (!GetAddressIndex((*it).first, (*it).second, addressIndex)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available for address");
}
}
CAmount balance = 0;
CAmount received = 0;
for (std::vector<std::pair<CAddressIndexKey, CAmount> >::const_iterator it=addressIndex.begin(); it!=addressIndex.end(); it++) {
if (it->second > 0) {
received += it->second;
}
balance += it->second;
}
UniValue result(UniValue::VOBJ);
result.push_back(Pair("balance", balance));
result.push_back(Pair("received", received));
return result;
}
UniValue getaddresstxids(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw runtime_error(
"getaddresstxids\n"
"\nReturns the txids for an address(es) (requires addressindex to be enabled).\n"
"\nArguments:\n"
"{\n"
" \"addresses\"\n"
" [\n"
" \"address\" (string) The base58check encoded address\n"
" ,...\n"
" ]\n"
" \"start\" (number) The start block height\n"
" \"end\" (number) The end block height\n"
"}\n"
"\nResult:\n"
"[\n"
" \"transactionid\" (string) The transaction id\n"
" ,...\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("getaddresstxids", "'{\"addresses\": [\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"]}'")
+ HelpExampleRpc("getaddresstxids", "{\"addresses\": [\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"]}")
);
std::vector<std::pair<uint256, int> > addresses;
if (!getAddressesFromParams(request.params, addresses)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
}
int start = 0;
int end = 0;
if (request.params[0].isObject()) {
UniValue startValue = find_value(request.params[0].get_obj(), "start");
UniValue endValue = find_value(request.params[0].get_obj(), "end");
if (startValue.isNum() && endValue.isNum()) {
start = startValue.get_int();
end = endValue.get_int();
}
}
std::vector<std::pair<CAddressIndexKey, CAmount> > addressIndex;
for (std::vector<std::pair<uint256, int> >::iterator it = addresses.begin(); it != addresses.end(); it++) {
if (start > 0 && end > 0) {
if (!GetAddressIndex((*it).first, (*it).second, addressIndex, start, end)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available for address");
}
} else {
if (!GetAddressIndex((*it).first, (*it).second, addressIndex)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available for address");
}
}
}
std::set<std::pair<int, std::string> > txids;
UniValue result(UniValue::VARR);
for (std::vector<std::pair<CAddressIndexKey, CAmount> >::const_iterator it=addressIndex.begin(); it!=addressIndex.end(); it++) {
int height = it->first.blockHeight;
std::string txid = it->first.txhash.GetHex();
if (addresses.size() > 1) {
txids.insert(std::make_pair(height, txid));
} else {
if (txids.insert(std::make_pair(height, txid)).second) {
result.push_back(txid);
}
}
}
if (addresses.size() > 1) {
for (std::set<std::pair<int, std::string> >::const_iterator it=txids.begin(); it!=txids.end(); it++) {
result.push_back(it->second);
}
}
return result;
}
UniValue getaddressvoteweight(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1 || !request.params[0].isObject())
throw runtime_error(
"getaddressvoteweight\n"
"\nReturns vote weight for an address (requires addressindex to be enabled).\n"
"\nArguments:\n"
"{\n"
" \"addresses\"\n"
" [\n"
" \"address\" (string) The base58check encoded address\n"
" ,...\n"
" ]\n"
" \"start\" (number) The start time of the vote weight period\n"
" \"end\" (number) The end time of the vote weight period\n"
"}\n"
"\nResult:\n"
"[\n"
" {\n"
" \"voteweight\" (number) The vote weight of the address\n"
" }\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("getaddressvoteweight", "'{\"addresses\": [\"NwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"], \"start\": 10, \"end\": 20}'")
+ HelpExampleRpc("getaddressvoteweight", "'{\"addresses\": [\"NwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"]}'")
);
// using chainactive
LOCK(cs_main);
UniValue result(UniValue::VOBJ);
UniValue startValue = find_value(request.params[0].get_obj(), "start");
UniValue endValue = find_value(request.params[0].get_obj(), "end");
int start = 0;
int end = 0;
if (startValue.isNum() && endValue.isNum()) {
start = startValue.get_int();
end = endValue.get_int();
if (end < start) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "End value is expected to be greater than start");
}
}
int start_block = -1;
int end_block = -1;
CBlockIndex *activeTip = chainActive.Tip();
CBlockIndex *lastBlock = activeTip->pprev;
// find start and end blocks
while(lastBlock){
// match end block
if(activeTip->GetBlockTime() >= end && lastBlock->GetBlockTime() < end && end_block == -1)
end_block = activeTip->nHeight;
else if(activeTip->GetBlockTime() >= end && lastBlock->GetBlockTime() <= end && end_block == -1)
end_block = lastBlock->nHeight;
// match start block
if(activeTip->GetBlockTime() >= start && lastBlock->GetBlockTime() < start && start_block == -1)
start_block = activeTip->nHeight;
if(activeTip->GetBlockTime() >= start && lastBlock->GetBlockTime() <= start && start_block == -1)
start_block = lastBlock->nHeight;
activeTip = lastBlock;
lastBlock = lastBlock->pprev;
if(start_block != -1 && end_block != -1)
break;
}
if(end_block == -1)
end_block = chainActive.Height();
start = start_block;
end = end_block;
std::vector<std::pair<uint256, int> > addresses;
if (!getAddressesFromParams(request.params, addresses)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
}
std::vector<std::pair<CAddressIndexKey, CAmount> > addressIndex;
for (std::vector<std::pair<uint256, int> >::iterator it = addresses.begin(); it != addresses.end(); it++) {
if (start > 0 && end > 0) {
if (!GetAddressIndex((*it).first, (*it).second, addressIndex, start, end)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available for address");
}
} else {
if (!GetAddressIndex((*it).first, (*it).second, addressIndex)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available for address");
}
}
}
CAmount totalWeight = 0;
int k = 0;
for (std::vector<std::pair<CAddressIndexKey, CAmount> >::const_iterator it=addressIndex.begin(); it!=addressIndex.end(); it++) {
std::string address;
if (!getAddressFromIndex(it->first.type, it->first.hashBytes, address)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unknown address type");
}
k++;
// check for coinstake
if(it->first.txindex != 0) continue;
// check for staking bypass
if(it->first.type == ADDR_INDT_WITNESS_KEY_HASH){
if(k == 1)
continue;
}
totalWeight += it->second;
}
result.pushKV("address_weight", ValueFromAmount(totalWeight));
result.pushKV("block_start", std::to_string(start));
result.pushKV("block_end", std::to_string(end));
return result;
}
UniValue getspentinfo(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1 || !request.params[0].isObject())
throw runtime_error(
"getspentinfo\n"
"\nReturns the txid and index where an output is spent.\n"
"\nArguments:\n"
"{\n"
" \"txid\" (string) The hex string of the txid\n"
" \"index\" (number) The start block height\n"
"}\n"
"\nResult:\n"
"{\n"
" \"txid\" (string) The transaction id\n"
" \"index\" (number) The spending input index\n"
" ,...\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getspentinfo", "'{\"txid\": \"0437cd7f8525ceed2324359c2d0ba26006d92d856a9c20fa0241106ee5a597c9\", \"index\": 0}'")
+ HelpExampleRpc("getspentinfo", "{\"txid\": \"0437cd7f8525ceed2324359c2d0ba26006d92d856a9c20fa0241106ee5a597c9\", \"index\": 0}")
);
UniValue txidValue = find_value(request.params[0].get_obj(), "txid");
UniValue indexValue = find_value(request.params[0].get_obj(), "index");
if (!txidValue.isStr() || !indexValue.isNum()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid txid or index");
}
uint256 txid = ParseHashV(txidValue, "txid");
int outputIndex = indexValue.get_int();
CSpentIndexKey key(txid, outputIndex);
CSpentIndexValue value;
if (!GetSpentIndex(key, value)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to get spent info");
}
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("txid", value.txid.GetHex()));
obj.push_back(Pair("index", (int)value.inputIndex));
obj.push_back(Pair("height", value.blockHeight));
return obj;
}
static const CRPCCommand commands[] =
{ // category name actor (function) argNames
// --------------------- ------------------------ ----------------------- ----------
{ "control", "getmemoryinfo", &getmemoryinfo, {"mode"} },
{ "control", "logging", &logging, {"include", "exclude"}},
{ "util", "validateaddress", &validateaddress, {"address"} }, /* uses wallet if enabled */
{ "util", "createmultisig", &createmultisig, {"nrequired","keys"} },
{ "util", "verifymessage", &verifymessage, {"address","signature","message"} },
{ "util", "signmessagewithprivkey", &signmessagewithprivkey, {"privkey","message"} },
/* Address index */
{ "addressindex", "getaddressmempool", &getaddressmempool, {"addresses"} },
{ "addressindex", "getaddressutxos", &getaddressutxos, {"addresses"} },
{ "addressindex", "getaddressdeltas", &getaddressdeltas, {"addresses"} },
{ "addressindex", "getaddresstxids", &getaddresstxids, {"addresses"} },
{ "addressindex", "getaddressbalance", &getaddressbalance, {"addresses"} },
{ "NIX Governance", "getaddressvoteweight", &getaddressvoteweight, {"address", "start_time", "end_time"} },
/* Not shown in help */
{ "hidden", "setmocktime", &setmocktime, {"timestamp"}},
{ "hidden", "echo", &echo, {"arg0","arg1","arg2","arg3","arg4","arg5","arg6","arg7","arg8","arg9"}},
{ "hidden", "echojson", &echo, {"arg0","arg1","arg2","arg3","arg4","arg5","arg6","arg7","arg8","arg9"}},
{ "hidden", "getinfo", &getinfo_deprecated, {}},
};
void RegisterMiscRPCCommands(CRPCTable &t)
{
for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
t.appendCommand(commands[vcidx].name, &commands[vcidx]);
}
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <base58.h>
#include <chain.h>
#include <clientversion.h>
#include <core_io.h>
#include <crypto/ripemd160.h>
#include <init.h>
#include <validation.h>
#include <httpserver.h>
#include <net.h>
#include <netbase.h>
#include <rpc/blockchain.h>
#include <rpc/server.h>
#include <rpc/util.h>
#include <timedata.h>
#include <util.h>
#include <utilstrencodings.h>
#include "ghostnode/ghostnode-sync.h"
#ifdef ENABLE_WALLET
#include <wallet/rpcwallet.h>
#include <wallet/wallet.h>
#include <wallet/walletdb.h>
#endif
#include <warnings.h>
#include "txmempool.h"
#include <uint256.h>
#include <stdint.h>
#ifdef HAVE_MALLOC_INFO
#include <malloc.h>
#endif
#include <univalue.h>
#ifdef ENABLE_WALLET
class DescribeAddressVisitor : public boost::static_visitor<UniValue>
{
public:
CWallet * const pwallet;
explicit DescribeAddressVisitor(CWallet *_pwallet) : pwallet(_pwallet) {}
void ProcessSubScript(const CScript& subscript, UniValue& obj, bool include_addresses = false) const
{
// Always present: script type and redeemscript
txnouttype which_type;
std::vector<std::vector<unsigned char>> solutions_data;
Solver(subscript, which_type, solutions_data, false);
obj.pushKV("script", GetTxnOutputType(which_type));
obj.pushKV("hex", HexStr(subscript.begin(), subscript.end()));
CTxDestination embedded;
UniValue a(UniValue::VARR);
if (ExtractDestination(subscript, embedded)) {
// Only when the script corresponds to an address.
UniValue subobj = boost::apply_visitor(*this, embedded);
subobj.pushKV("address", EncodeDestination(embedded));
subobj.pushKV("scriptPubKey", HexStr(subscript.begin(), subscript.end()));
// Always report the pubkey at the top level, so that `getnewaddress()['pubkey']` always works.
if (subobj.exists("pubkey")) obj.pushKV("pubkey", subobj["pubkey"]);
obj.pushKV("embedded", std::move(subobj));
if (include_addresses) a.push_back(EncodeDestination(embedded));
} else if (which_type == TX_MULTISIG) {
// Also report some information on multisig scripts (which do not have a corresponding address).
// TODO: abstract out the common functionality between this logic and ExtractDestinations.
obj.pushKV("sigsrequired", solutions_data[0][0]);
UniValue pubkeys(UniValue::VARR);
for (size_t i = 1; i < solutions_data.size() - 1; ++i) {
CPubKey key(solutions_data[i].begin(), solutions_data[i].end());
if (include_addresses) a.push_back(EncodeDestination(key.GetID()));
pubkeys.push_back(HexStr(key.begin(), key.end()));
}
obj.pushKV("pubkeys", std::move(pubkeys));
}
// The "addresses" field is confusing because it refers to public keys using their P2PKH address.
// For that reason, only add the 'addresses' field when needed for backward compatibility. New applications
// can use the 'embedded'->'address' field for P2SH or P2WSH wrapped addresses, and 'pubkeys' for
// inspecting multisig participants.
if (include_addresses) obj.pushKV("addresses", std::move(a));
}
UniValue operator()(const CNoDestination &dest) const { return UniValue(UniValue::VOBJ); }
UniValue operator()(const CKeyID &keyID) const {
UniValue obj(UniValue::VOBJ);
CPubKey vchPubKey;
obj.push_back(Pair("isscript", false));
obj.push_back(Pair("iswitness", false));
if (pwallet && pwallet->GetPubKey(keyID, vchPubKey)) {
obj.push_back(Pair("pubkey", HexStr(vchPubKey)));
obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed()));
}
return obj;
}
UniValue operator()(const CScriptID &scriptID) const {
UniValue obj(UniValue::VOBJ);
CScript subscript;
obj.push_back(Pair("isscript", true));
obj.push_back(Pair("iswitness", false));
if (pwallet && pwallet->GetCScript(scriptID, subscript)) {
ProcessSubScript(subscript, obj, true);
}
return obj;
}
UniValue operator()(const WitnessV0KeyHash& id) const
{
UniValue obj(UniValue::VOBJ);
CPubKey pubkey;
obj.push_back(Pair("isscript", false));
obj.push_back(Pair("iswitness", true));
obj.push_back(Pair("witness_version", 0));
obj.push_back(Pair("witness_program", HexStr(id.begin(), id.end())));
if (pwallet && pwallet->GetPubKey(CKeyID(id), pubkey)) {
obj.push_back(Pair("pubkey", HexStr(pubkey)));
}
return obj;
}
UniValue operator()(const CExtKeyPair &ekp) const {
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("isextkey", true));
return obj;
}
UniValue operator()(const CStealthAddress &sxAddr) const {
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("isstealthaddress", true));
obj.push_back(Pair("prefix_num_bits", sxAddr.prefix.number_bits));
obj.push_back(Pair("prefix_bitfield", strprintf("0x%04x", sxAddr.prefix.bitfield)));
return obj;
}
UniValue operator()(const CGhostAddress &sxAddr) const {
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("isghostaddress", true));
obj.push_back(Pair("prefix_num_bits", sxAddr.prefix.number_bits));
obj.push_back(Pair("prefix_bitfield", strprintf("0x%04x", sxAddr.prefix.bitfield)));
return obj;
}
UniValue operator()(const WitnessV0ScriptHash& id) const
{
UniValue obj(UniValue::VOBJ);
CScript subscript;
obj.push_back(Pair("isscript", true));
obj.push_back(Pair("iswitness", true));
obj.push_back(Pair("witness_version", 0));
obj.push_back(Pair("witness_program", HexStr(id.begin(), id.end())));
CRIPEMD160 hasher;
uint160 hash;
hasher.Write(id.begin(), 32).Finalize(hash.begin());
if (pwallet && pwallet->GetCScript(CScriptID(hash), subscript)) {
ProcessSubScript(subscript, obj);
}
return obj;
}
UniValue operator()(const WitnessUnknown& id) const
{
UniValue obj(UniValue::VOBJ);
CScript subscript;
obj.push_back(Pair("iswitness", true));
obj.push_back(Pair("witness_version", (int)id.version));
obj.push_back(Pair("witness_program", HexStr(id.program, id.program + id.length)));
return obj;
}
UniValue operator()(const CKeyID256 &idk256) const {
UniValue obj(UniValue::VOBJ);
CPubKey vchPubKey;
obj.push_back(Pair("isscript", false));
CKeyID id160(idk256);
if (pwallet && pwallet->GetPubKey(id160, vchPubKey)) {
obj.push_back(Pair("pubkey", HexStr(vchPubKey)));
obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed()));
}
return obj;
}
UniValue operator()(const CScriptID256 &scriptID256) const {
UniValue obj(UniValue::VOBJ);
CScript subscript;
obj.push_back(Pair("isscript", true));
CScriptID scriptID;
scriptID.Set(scriptID256);
if (pwallet && pwallet->GetCScript(scriptID, subscript)) {
std::vector<CTxDestination> addresses;
txnouttype whichType;
int nRequired;
ExtractDestinations(subscript, whichType, addresses, nRequired);
obj.push_back(Pair("script", GetTxnOutputType(whichType)));
obj.push_back(Pair("hex", HexStr(subscript.begin(), subscript.end())));
UniValue a(UniValue::VARR);
for (const CTxDestination& addr : addresses)
a.push_back(CBitcoinAddress(addr).ToString());
obj.push_back(Pair("addresses", a));
if (whichType == TX_MULTISIG)
obj.push_back(Pair("sigsrequired", nRequired));
}
return obj;
}
};
#endif
//Ghostnode
UniValue ghostnodesync(const JSONRPCRequest& req)
{
UniValue params = req.params;
bool fHelp = req.fHelp;
if (fHelp || params.size() != 1)
throw runtime_error(
"ghostnodesync [status|next|reset]\n"
"Returns the sync status, updates to the next step or resets it entirely.\n"
);
std::string strMode = params[0].get_str();
if(strMode == "status") {
UniValue objStatus(UniValue::VOBJ);
objStatus.push_back(Pair("AssetID", ghostnodeSync.GetAssetID()));
objStatus.push_back(Pair("AssetName", ghostnodeSync.GetAssetName()));
objStatus.push_back(Pair("Attempt", ghostnodeSync.GetAttempt()));
objStatus.push_back(Pair("IsBlockchainSynced", ghostnodeSync.IsBlockchainSynced()));
objStatus.push_back(Pair("IsGhostnodeListSynced", ghostnodeSync.IsGhostnodeListSynced()));
objStatus.push_back(Pair("IsWinnersListSynced", ghostnodeSync.IsWinnersListSynced()));
objStatus.push_back(Pair("IsSynced", ghostnodeSync.IsSynced()));
objStatus.push_back(Pair("IsFailed", ghostnodeSync.IsFailed()));
return objStatus;
}
if(strMode == "next")
{
ghostnodeSync.SwitchToNextAsset();
return "sync updated to " + ghostnodeSync.GetAssetName();
}
if(strMode == "reset")
{
ghostnodeSync.Reset();
return "success";
}
return "failure";
}
UniValue validateaddress(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"validateaddress \"address\"\n"
"\nReturn information about the given nix address.\n"
"\nArguments:\n"
"1. \"address\" (string, required) The nix address to validate\n"
"\nResult:\n"
"{\n"
" \"isvalid\" : true|false, (boolean) If the address is valid or not. If not, this is the only property returned.\n"
" \"address\" : \"address\", (string) The nix address validated\n"
" \"scriptPubKey\" : \"hex\", (string) The hex encoded scriptPubKey generated by the address\n"
" \"ismine\" : true|false, (boolean) If the address is yours or not\n"
" \"iswatchonly\" : true|false, (boolean) If the address is watchonly\n"
" \"isscript\" : true|false, (boolean, optional) If the address is P2SH or P2WSH. Not included for unknown witness types.\n"
" \"iswitness\" : true|false, (boolean) If the address is P2WPKH, P2WSH, or an unknown witness version\n"
" \"witness_version\" : version (number, optional) For all witness output types, gives the version number.\n"
" \"witness_program\" : \"hex\" (string, optional) For all witness output types, gives the script or key hash present in the address.\n"
" \"script\" : \"type\" (string, optional) The output script type. Only if \"isscript\" is true and the redeemscript is known. Possible types: nonstandard, pubkey, pubkeyhash, scripthash, multisig, nulldata, witness_v0_keyhash, witness_v0_scripthash, witness_unknown\n"
" \"hex\" : \"hex\", (string, optional) The redeemscript for the P2SH or P2WSH address\n"
" \"addresses\" (string, optional) Array of addresses associated with the known redeemscript (only if \"iswitness\" is false). This field is superseded by the \"pubkeys\" field and the address inside \"embedded\".\n"
" [\n"
" \"address\"\n"
" ,...\n"
" ]\n"
" \"pubkeys\" (string, optional) Array of pubkeys associated with the known redeemscript (only if \"script\" is \"multisig\")\n"
" [\n"
" \"pubkey\"\n"
" ,...\n"
" ]\n"
" \"sigsrequired\" : xxxxx (numeric, optional) Number of signatures required to spend multisig output (only if \"script\" is \"multisig\")\n"
" \"pubkey\" : \"publickeyhex\", (string, optional) The hex value of the raw public key, for single-key addresses (possibly embedded in P2SH or P2WSH)\n"
" \"embedded\" : {...}, (object, optional) information about the address embedded in P2SH or P2WSH, if relevant and known. It includes all validateaddress output fields for the embedded address, excluding \"isvalid\", metadata (\"timestamp\", \"hdkeypath\", \"hdmasterkeyid\") and relation to the wallet (\"ismine\", \"iswatchonly\", \"account\").\n"
" \"iscompressed\" : true|false, (boolean) If the address is compressed\n"
" \"account\" : \"account\" (string) DEPRECATED. The account associated with the address, \"\" is the default account\n"
" \"timestamp\" : timestamp, (number, optional) The creation time of the key if available in seconds since epoch (Jan 1 1970 GMT)\n"
" \"hdkeypath\" : \"keypath\" (string, optional) The HD keypath if the key is HD and available\n"
" \"hdmasterkeyid\" : \"<hash160>\" (string, optional) The Hash160 of the HD master pubkey\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"")
+ HelpExampleRpc("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"")
);
#ifdef ENABLE_WALLET
CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
LOCK2(cs_main, pwallet ? &pwallet->cs_wallet : nullptr);
#else
LOCK(cs_main);
#endif
CTxDestination dest = DecodeDestination(request.params[0].get_str());
bool isValid = IsValidDestination(dest);
UniValue ret(UniValue::VOBJ);
ret.push_back(Pair("isvalid", isValid));
if (isValid)
{
std::string currentAddress = EncodeDestination(dest);
ret.push_back(Pair("address", currentAddress));
CScript scriptPubKey = GetScriptForDestination(dest);
ret.push_back(Pair("scriptPubKey", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
#ifdef ENABLE_WALLET
isminetype mine = pwallet ? IsMine(*pwallet, dest) : ISMINE_NO;
ret.push_back(Pair("ismine", bool(mine & ISMINE_SPENDABLE)));
ret.push_back(Pair("iswatchonly", bool(mine & ISMINE_WATCH_ONLY)));
UniValue detail = boost::apply_visitor(DescribeAddressVisitor(pwallet), dest);
ret.pushKVs(detail);
if (pwallet && pwallet->mapAddressBook.count(dest)) {
ret.push_back(Pair("account", pwallet->mapAddressBook[dest].name));
}
if (pwallet) {
const CKeyMetadata* meta = nullptr;
CKeyID key_id = GetKeyForDestination(*pwallet, dest);
if (!key_id.IsNull()) {
auto it = pwallet->mapKeyMetadata.find(key_id);
if (it != pwallet->mapKeyMetadata.end()) {
meta = &it->second;
}
}
if (!meta) {
auto it = pwallet->m_script_metadata.find(CScriptID(scriptPubKey));
if (it != pwallet->m_script_metadata.end()) {
meta = &it->second;
}
}
if (meta) {
ret.push_back(Pair("timestamp", meta->nCreateTime));
if (!meta->hdKeypath.empty()) {
ret.push_back(Pair("hdkeypath", meta->hdKeypath));
ret.push_back(Pair("hdmasterkeyid", meta->hdMasterKeyID.GetHex()));
}
}
}
#endif
}
return ret;
}
// Needed even with !ENABLE_WALLET, to pass (ignored) pointers around
class CWallet;
UniValue createmultisig(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 2 || request.params.size() > 2)
{
std::string msg = "createmultisig nrequired [\"key\",...]\n"
"\nCreates a multi-signature address with n signature of m keys required.\n"
"It returns a json object with the address and redeemScript.\n"
"DEPRECATION WARNING: Using addresses with createmultisig is deprecated. Clients must\n"
"transition to using addmultisigaddress to create multisig addresses with addresses known\n"
"to the wallet before upgrading to v0.17. To use the deprecated functionality, start nixd with -deprecatedrpc=createmultisig\n"
"\nArguments:\n"
"1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n"
"2. \"keys\" (string, required) A json array of hex-encoded public keys\n"
" [\n"
" \"key\" (string) The hex-encoded public key\n"
" ,...\n"
" ]\n"
"\nResult:\n"
"{\n"
" \"address\":\"multisigaddress\", (string) The value of the new multisig address.\n"
" \"redeemScript\":\"script\" (string) The string value of the hex-encoded redemption script.\n"
"}\n"
"\nExamples:\n"
"\nCreate a multisig address from 2 public keys\n"
+ HelpExampleCli("createmultisig", "2 \"[\\\"03789ed0bb717d88f7d321a368d905e7430207ebbd82bd342cf11ae157a7ace5fd\\\",\\\"03dbc6764b8884a92e871274b87583e6d5c2a58819473e17e107ef3f6aa5a61626\\\"]\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("createmultisig", "2, \"[\\\"03789ed0bb717d88f7d321a368d905e7430207ebbd82bd342cf11ae157a7ace5fd\\\",\\\"03dbc6764b8884a92e871274b87583e6d5c2a58819473e17e107ef3f6aa5a61626\\\"]\"")
;
throw std::runtime_error(msg);
}
int required = request.params[0].get_int();
// Get the public keys
const UniValue& keys = request.params[1].get_array();
std::vector<CPubKey> pubkeys;
for (unsigned int i = 0; i < keys.size(); ++i) {
if (IsHex(keys[i].get_str()) && (keys[i].get_str().length() == 66 || keys[i].get_str().length() == 130)) {
pubkeys.push_back(HexToPubKey(keys[i].get_str()));
} else {
#ifdef ENABLE_WALLET
CWallet* const pwallet = GetWalletForJSONRPCRequest(request);
if (IsDeprecatedRPCEnabled("createmultisig") && EnsureWalletIsAvailable(pwallet, false)) {
pubkeys.push_back(AddrToPubKey(pwallet, keys[i].get_str()));
} else
#endif
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Invalid public key: %s\nNote that from v0.16, createmultisig no longer accepts addresses."
" Clients must transition to using addmultisigaddress to create multisig addresses with addresses known to the wallet before upgrading to v0.17."
" To use the deprecated functionality, start nixd with -deprecatedrpc=createmultisig", keys[i].get_str()));
}
}
// Construct using pay-to-script-hash:
CScript inner = CreateMultisigRedeemscript(required, pubkeys);
CScriptID innerID(inner);
UniValue result(UniValue::VOBJ);
result.push_back(Pair("address", EncodeDestination(innerID)));
result.push_back(Pair("redeemScript", HexStr(inner.begin(), inner.end())));
return result;
}
UniValue verifymessage(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 3)
throw std::runtime_error(
"verifymessage \"address\" \"signature\" \"message\"\n"
"\nVerify a signed message\n"
"\nArguments:\n"
"1. \"address\" (string, required) The nix address to use for the signature.\n"
"2. \"signature\" (string, required) The signature provided by the signer in base 64 encoding (see signmessage).\n"
"3. \"message\" (string, required) The message that was signed.\n"
"\nResult:\n"
"true|false (boolean) If the signature is verified or not.\n"
"\nExamples:\n"
"\nUnlock the wallet for 30 seconds\n"
+ HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") +
"\nCreate the signature\n"
+ HelpExampleCli("signmessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"my message\"") +
"\nVerify the signature\n"
+ HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"signature\" \"my message\"") +
"\nAs json rpc\n"
+ HelpExampleRpc("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\", \"signature\", \"my message\"")
);
LOCK(cs_main);
std::string strAddress = request.params[0].get_str();
std::string strSign = request.params[1].get_str();
std::string strMessage = request.params[2].get_str();
CTxDestination destination = DecodeDestination(strAddress);
if (!IsValidDestination(destination)) {
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
}
CKeyID *tempKey;
if (auto id = boost::get<CKeyID>(&destination)) {
tempKey = id;
}
else if (auto witness_id = boost::get<WitnessV0KeyHash>(&destination)) {
tempKey = new CKeyID;
*tempKey = CKeyID(*witness_id);
}
else
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
const CKeyID *keyID = tempKey;
if (!keyID) {
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
}
/*
const CKeyID *keyID = boost::get<CKeyID>(&destination);
if (!keyID) {
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
}
*/
bool fInvalid = false;
std::vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);
if (fInvalid)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding");
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
CPubKey pubkey;
if (!pubkey.RecoverCompact(ss.GetHash(), vchSig))
return false;
return (pubkey.GetID() == *keyID);
}
UniValue signmessagewithprivkey(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 2)
throw std::runtime_error(
"signmessagewithprivkey \"privkey\" \"message\"\n"
"\nSign a message with the private key of an address\n"
"\nArguments:\n"
"1. \"privkey\" (string, required) The private key to sign the message with.\n"
"2. \"message\" (string, required) The message to create a signature of.\n"
"\nResult:\n"
"\"signature\" (string) The signature of the message encoded in base 64\n"
"\nExamples:\n"
"\nCreate the signature\n"
+ HelpExampleCli("signmessagewithprivkey", "\"privkey\" \"my message\"") +
"\nVerify the signature\n"
+ HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"signature\" \"my message\"") +
"\nAs json rpc\n"
+ HelpExampleRpc("signmessagewithprivkey", "\"privkey\", \"my message\"")
);
std::string strPrivkey = request.params[0].get_str();
std::string strMessage = request.params[1].get_str();
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(strPrivkey);
if (!fGood)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
CKey key = vchSecret.GetKey();
if (!key.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
std::vector<unsigned char> vchSig;
if (!key.SignCompact(ss.GetHash(), vchSig))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
return EncodeBase64(vchSig.data(), vchSig.size());
}
UniValue setmocktime(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"setmocktime timestamp\n"
"\nSet the local time to given timestamp (-regtest only)\n"
"\nArguments:\n"
"1. timestamp (integer, required) Unix seconds-since-epoch timestamp\n"
" Pass 0 to go back to using the system time."
);
if (!Params().MineBlocksOnDemand())
throw std::runtime_error("setmocktime for regression testing (-regtest mode) only");
// For now, don't change mocktime if we're in the middle of validation, as
// this could have an effect on mempool time-based eviction, as well as
// IsCurrentForFeeEstimation() and IsInitialBlockDownload().
// TODO: figure out the right way to synchronize around mocktime, and
// ensure all call sites of GetTime() are accessing this safely.
LOCK(cs_main);
RPCTypeCheck(request.params, {UniValue::VNUM});
SetMockTime(request.params[0].get_int64());
return NullUniValue;
}
static UniValue RPCLockedMemoryInfo()
{
LockedPool::Stats stats = LockedPoolManager::Instance().stats();
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("used", uint64_t(stats.used)));
obj.push_back(Pair("free", uint64_t(stats.free)));
obj.push_back(Pair("total", uint64_t(stats.total)));
obj.push_back(Pair("locked", uint64_t(stats.locked)));
obj.push_back(Pair("chunks_used", uint64_t(stats.chunks_used)));
obj.push_back(Pair("chunks_free", uint64_t(stats.chunks_free)));
return obj;
}
#ifdef HAVE_MALLOC_INFO
static std::string RPCMallocInfo()
{
char *ptr = nullptr;
size_t size = 0;
FILE *f = open_memstream(&ptr, &size);
if (f) {
malloc_info(0, f);
fclose(f);
if (ptr) {
std::string rv(ptr, size);
free(ptr);
return rv;
}
}
return "";
}
#endif
UniValue getmemoryinfo(const JSONRPCRequest& request)
{
/* Please, avoid using the word "pool" here in the RPC interface or help,
* as users will undoubtedly confuse it with the other "memory pool"
*/
if (request.fHelp || request.params.size() > 1)
throw std::runtime_error(
"getmemoryinfo (\"mode\")\n"
"Returns an object containing information about memory usage.\n"
"Arguments:\n"
"1. \"mode\" determines what kind of information is returned. This argument is optional, the default mode is \"stats\".\n"
" - \"stats\" returns general statistics about memory usage in the daemon.\n"
" - \"mallocinfo\" returns an XML string describing low-level heap state (only available if compiled with glibc 2.10+).\n"
"\nResult (mode \"stats\"):\n"
"{\n"
" \"locked\": { (json object) Information about locked memory manager\n"
" \"used\": xxxxx, (numeric) Number of bytes used\n"
" \"free\": xxxxx, (numeric) Number of bytes available in current arenas\n"
" \"total\": xxxxxxx, (numeric) Total number of bytes managed\n"
" \"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"
" \"chunks_used\": xxxxx, (numeric) Number allocated chunks\n"
" \"chunks_free\": xxxxx, (numeric) Number unused chunks\n"
" }\n"
"}\n"
"\nResult (mode \"mallocinfo\"):\n"
"\"<malloc version=\"1\">...\"\n"
"\nExamples:\n"
+ HelpExampleCli("getmemoryinfo", "")
+ HelpExampleRpc("getmemoryinfo", "")
);
std::string mode = request.params[0].isNull() ? "stats" : request.params[0].get_str();
if (mode == "stats") {
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("locked", RPCLockedMemoryInfo()));
return obj;
} else if (mode == "mallocinfo") {
#ifdef HAVE_MALLOC_INFO
return RPCMallocInfo();
#else
throw JSONRPCError(RPC_INVALID_PARAMETER, "mallocinfo is only available when compiled with glibc 2.10+");
#endif
} else {
throw JSONRPCError(RPC_INVALID_PARAMETER, "unknown mode " + mode);
}
}
uint32_t getCategoryMask(UniValue cats) {
cats = cats.get_array();
uint32_t mask = 0;
for (unsigned int i = 0; i < cats.size(); ++i) {
uint32_t flag = 0;
std::string cat = cats[i].get_str();
if (!GetLogCategory(&flag, &cat)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "unknown logging category " + cat);
}
if (flag == BCLog::NONE) {
return 0;
}
mask |= flag;
}
return mask;
}
UniValue logging(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() > 2) {
throw std::runtime_error(
"logging ( <include> <exclude> )\n"
"Gets and sets the logging configuration.\n"
"When called without an argument, returns the list of categories with status that are currently being debug logged or not.\n"
"When called with arguments, adds or removes categories from debug logging and return the lists above.\n"
"The arguments are evaluated in order \"include\", \"exclude\".\n"
"If an item is both included and excluded, it will thus end up being excluded.\n"
"The valid logging categories are: " + ListLogCategories() + "\n"
"In addition, the following are available as category names with special meanings:\n"
" - \"all\", \"1\" : represent all logging categories.\n"
" - \"none\", \"0\" : even if other logging categories are specified, ignore all of them.\n"
"\nArguments:\n"
"1. \"include\" (array of strings, optional) A json array of categories to add debug logging\n"
" [\n"
" \"category\" (string) the valid logging category\n"
" ,...\n"
" ]\n"
"2. \"exclude\" (array of strings, optional) A json array of categories to remove debug logging\n"
" [\n"
" \"category\" (string) the valid logging category\n"
" ,...\n"
" ]\n"
"\nResult:\n"
"{ (json object where keys are the logging categories, and values indicates its status\n"
" \"category\": 0|1, (numeric) if being debug logged or not. 0:inactive, 1:active\n"
" ...\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("logging", "\"[\\\"all\\\"]\" \"[\\\"http\\\"]\"")
+ HelpExampleRpc("logging", "[\"all\"], \"[libevent]\"")
);
}
uint32_t originalLogCategories = logCategories;
if (request.params[0].isArray()) {
logCategories |= getCategoryMask(request.params[0]);
}
if (request.params[1].isArray()) {
logCategories &= ~getCategoryMask(request.params[1]);
}
// Update libevent logging if BCLog::LIBEVENT has changed.
// If the library version doesn't allow it, UpdateHTTPServerLogging() returns false,
// in which case we should clear the BCLog::LIBEVENT flag.
// Throw an error if the user has explicitly asked to change only the libevent
// flag and it failed.
uint32_t changedLogCategories = originalLogCategories ^ logCategories;
if (changedLogCategories & BCLog::LIBEVENT) {
if (!UpdateHTTPServerLogging(logCategories & BCLog::LIBEVENT)) {
logCategories &= ~BCLog::LIBEVENT;
if (changedLogCategories == BCLog::LIBEVENT) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "libevent logging cannot be updated when using libevent before v2.1.1.");
}
}
}
UniValue result(UniValue::VOBJ);
std::vector<CLogCategoryActive> vLogCatActive = ListActiveLogCategories();
for (const auto& logCatActive : vLogCatActive) {
result.pushKV(logCatActive.category, logCatActive.active);
}
return result;
}
UniValue echo(const JSONRPCRequest& request)
{
if (request.fHelp)
throw std::runtime_error(
"echo|echojson \"message\" ...\n"
"\nSimply echo back the input arguments. This command is for testing.\n"
"\nThe difference between echo and echojson is that echojson has argument conversion enabled in the client-side table in"
"nix-cli and the GUI. There is no server-side difference."
);
return request.params;
}
static UniValue getinfo_deprecated(const JSONRPCRequest& request)
{
throw JSONRPCError(RPC_METHOD_NOT_FOUND,
"getinfo\n"
"\nThis call was removed in version 0.16.0. Use the appropriate fields from:\n"
"- getblockchaininfo: blocks, difficulty, chain\n"
"- getnetworkinfo: version, protocolversion, timeoffset, connections, proxy, relayfee, warnings\n"
"- getwalletinfo: balance, keypoololdest, keypoolsize, paytxfee, unlocked_until, walletversion\n"
"\nnix-cli has the option -getinfo to collect and format these in the old format."
);
}
bool getAddressFromIndex(const int &type, const uint256 &hash, std::string &address)
{
if (type == ADDR_INDT_SCRIPT_ADDRESS) {
address = EncodeDestination(CScriptID(uint160(hash.begin(), 20)));
} else if (type == ADDR_INDT_PUBKEY_ADDRESS) {
address = EncodeDestination(CKeyID(uint160(hash.begin(), 20)));
} else if (type == ADDR_INDT_WITNESS_KEY_HASH) {
address = EncodeDestination(WitnessV0KeyHash(uint160(hash.begin(), 20)), true);
} else {
return false;
}
return true;
}
bool getAddressesFromParams(const UniValue& params, std::vector<std::pair<uint256, int> > &addresses)
{
if (params[0].isStr()) {
CTxDestination des = DecodeDestination(params[0].get_str());
if(des.type() == typeid(WitnessV0KeyHash)){
CScript desScript = GetScriptForDestination(des);
std::vector<uint8_t> hashBytes;
hashBytes.assign(desScript.begin()+2, desScript.begin()+22);
uint256 hashByte = uint256(hashBytes.data(), hashBytes.size());
int type = ADDR_INDT_WITNESS_KEY_HASH;
addresses.push_back(std::make_pair(hashByte, type));
}
else{
CBitcoinAddress address(params[0].get_str());
uint256 hashBytes;
int type = 0;
if (!address.GetIndexKey(hashBytes, type)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
}
addresses.push_back(std::make_pair(hashBytes, type));
}
} else if (params[0].isObject()) {
UniValue addressValues = find_value(params[0].get_obj(), "addresses");
if (!addressValues.isArray()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Addresses is expected to be an array");
}
std::vector<UniValue> values = addressValues.getValues();
for (std::vector<UniValue>::iterator it = values.begin(); it != values.end(); ++it) {
CTxDestination des = DecodeDestination(it->get_str());
if(des.type() == typeid(WitnessV0KeyHash)){
CScript desScript = GetScriptForDestination(des);
std::vector<uint8_t> hashBytes;
hashBytes.assign(desScript.begin()+2, desScript.begin()+22);
uint256 hashByte = uint256(hashBytes.data(), hashBytes.size());
int type = ADDR_INDT_WITNESS_KEY_HASH;
addresses.push_back(std::make_pair(hashByte, type));
}
else{
CBitcoinAddress address(it->get_str());
uint256 hashBytes;
int type = 0;
if (!address.GetIndexKey(hashBytes, type)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
}
addresses.push_back(std::make_pair(hashBytes, type));
}
}
} else {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
}
return true;
}
bool heightSort(std::pair<CAddressUnspentKey, CAddressUnspentValue> a,
std::pair<CAddressUnspentKey, CAddressUnspentValue> b) {
return a.second.blockHeight < b.second.blockHeight;
}
bool timestampSort(std::pair<CMempoolAddressDeltaKey, CMempoolAddressDelta> a,
std::pair<CMempoolAddressDeltaKey, CMempoolAddressDelta> b) {
return a.second.time < b.second.time;
}
UniValue getaddressmempool(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw runtime_error(
"getaddressmempool\n"
"\nReturns all mempool deltas for an address (requires addressindex to be enabled).\n"
"\nArguments:\n"
"{\n"
" \"addresses\"\n"
" [\n"
" \"address\" (string) The base58check encoded address\n"
" ,...\n"
" ]\n"
"}\n"
"\nResult:\n"
"[\n"
" {\n"
" \"address\" (string) The base58check encoded address\n"
" \"txid\" (string) The related txid\n"
" \"index\" (number) The related input or output index\n"
" \"satoshis\" (number) The difference of duffs\n"
" \"timestamp\" (number) The time the transaction entered the mempool (seconds)\n"
" \"prevtxid\" (string) The previous txid (if spending)\n"
" \"prevout\" (string) The previous transaction output index (if spending)\n"
" }\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("getaddressmempool", "'{\"addresses\": [\"NwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"]}'")
+ HelpExampleRpc("getaddressmempool", "{\"addresses\": [\"NwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"]}")
);
std::vector<std::pair<uint256, int> > addresses;
if (!getAddressesFromParams(request.params, addresses)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
}
std::vector<std::pair<CMempoolAddressDeltaKey, CMempoolAddressDelta> > indexes;
if (!mempool.getAddressIndex(addresses, indexes)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available for address");
}
std::sort(indexes.begin(), indexes.end(), timestampSort);
UniValue result(UniValue::VARR);
for (std::vector<std::pair<CMempoolAddressDeltaKey, CMempoolAddressDelta> >::iterator it = indexes.begin(); it != indexes.end(); it++) {
std::string address;
if (!getAddressFromIndex(it->first.type, it->first.addressBytes, address)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unknown address type");
}
UniValue delta(UniValue::VOBJ);
delta.push_back(Pair("address", address));
delta.push_back(Pair("txid", it->first.txhash.GetHex()));
delta.push_back(Pair("index", (int)it->first.index));
delta.push_back(Pair("satoshis", it->second.amount));
delta.push_back(Pair("timestamp", it->second.time));
if (it->second.amount < 0) {
delta.push_back(Pair("prevtxid", it->second.prevhash.GetHex()));
delta.push_back(Pair("prevout", (int)it->second.prevout));
}
result.push_back(delta);
}
return result;
}
UniValue getaddressutxos(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw runtime_error(
"getaddressutxos\n"
"\nReturns all unspent outputs for an address (requires addressindex to be enabled).\n"
"\nArguments:\n"
"{\n"
" \"addresses\"\n"
" [\n"
" \"address\" (string) The base58check encoded address\n"
" ,...\n"
" ]\n"
"}\n"
"\nResult\n"
"[\n"
" {\n"
" \"address\" (string) The address base58check encoded\n"
" \"txid\" (string) The output txid\n"
" \"outputIndex\" (number) The output index\n"
" \"script\" (string) The script hex encoded\n"
" \"satoshis\" (number) The number of duffs of the output\n"
" \"height\" (number) The block height\n"
" }\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("getaddressutxos", "'{\"addresses\": [\"NwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"]}'")
+ HelpExampleRpc("getaddressutxos", "{\"addresses\": [\"NwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"]}")
);
std::vector<std::pair<uint256, int> > addresses;
if (!getAddressesFromParams(request.params, addresses)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
}
std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > unspentOutputs;
for (std::vector<std::pair<uint256, int> >::iterator it = addresses.begin(); it != addresses.end(); it++) {
if (!GetAddressUnspent((*it).first, (*it).second, unspentOutputs)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available for address");
}
}
std::sort(unspentOutputs.begin(), unspentOutputs.end(), heightSort);
UniValue result(UniValue::VARR);
for (std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) {
UniValue output(UniValue::VOBJ);
std::string address;
if (!getAddressFromIndex(it->first.type, it->first.hashBytes, address)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unknown address type");
}
output.push_back(Pair("address", address));
output.push_back(Pair("txid", it->first.txhash.GetHex()));
output.push_back(Pair("outputIndex", (int)it->first.index));
output.push_back(Pair("script", HexStr(it->second.script.begin(), it->second.script.end())));
output.push_back(Pair("satoshis", it->second.satoshis));
output.push_back(Pair("height", it->second.blockHeight));
result.push_back(output);
}
return result;
}
UniValue getaddressdeltas(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1 || !request.params[0].isObject())
throw runtime_error(
"getaddressdeltas\n"
"\nReturns all changes for an address (requires addressindex to be enabled).\n"
"\nArguments:\n"
"{\n"
" \"addresses\"\n"
" [\n"
" \"address\" (string) The base58check encoded address\n"
" ,...\n"
" ]\n"
" \"start\" (number) The start block height\n"
" \"end\" (number) The end block height\n"
"}\n"
"\nResult:\n"
"[\n"
" {\n"
" \"satoshis\" (number) The difference of duffs\n"
" \"txid\" (string) The related txid\n"
" \"index\" (number) The related input or output index\n"
" \"blockindex\" (number) The related block index\n"
" \"height\" (number) The block height\n"
" \"address\" (string) The base58check encoded address\n"
" }\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("getaddressdeltas", "'{\"addresses\": [\"NwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"]}'")
+ HelpExampleRpc("getaddressdeltas", "{\"addresses\": [\"NwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"]}")
);
UniValue startValue = find_value(request.params[0].get_obj(), "start");
UniValue endValue = find_value(request.params[0].get_obj(), "end");
int start = 0;
int end = 0;
if (startValue.isNum() && endValue.isNum()) {
start = startValue.get_int();
end = endValue.get_int();
if (end < start) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "End value is expected to be greater than start");
}
}
std::vector<std::pair<uint256, int> > addresses;
if (!getAddressesFromParams(request.params, addresses)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
}
std::vector<std::pair<CAddressIndexKey, CAmount> > addressIndex;
for (std::vector<std::pair<uint256, int> >::iterator it = addresses.begin(); it != addresses.end(); it++) {
if (start > 0 && end > 0) {
if (!GetAddressIndex((*it).first, (*it).second, addressIndex, start, end)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available for address");
}
} else {
if (!GetAddressIndex((*it).first, (*it).second, addressIndex)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available for address");
}
}
}
UniValue result(UniValue::VARR);
for (std::vector<std::pair<CAddressIndexKey, CAmount> >::const_iterator it=addressIndex.begin(); it!=addressIndex.end(); it++) {
std::string address;
if (!getAddressFromIndex(it->first.type, it->first.hashBytes, address)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unknown address type");
}
UniValue delta(UniValue::VOBJ);
delta.push_back(Pair("satoshis", it->second));
delta.push_back(Pair("txid", it->first.txhash.GetHex()));
delta.push_back(Pair("index", (int)it->first.index));
delta.push_back(Pair("blockindex", (int)it->first.txindex));
delta.push_back(Pair("height", it->first.blockHeight));
delta.push_back(Pair("address", address));
result.push_back(delta);
}
return result;
}
UniValue getaddressbalance(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw runtime_error(
"getaddressbalance\n"
"\nReturns the balance for an address(es) (requires addressindex to be enabled).\n"
"\nArguments:\n"
"{\n"
" \"addresses\"\n"
" [\n"
" \"address\" (string) The base58check encoded address\n"
" ,...\n"
" ]\n"
"}\n"
"\nResult:\n"
"{\n"
" \"balance\" (string) The current balance in duffs\n"
" \"received\" (string) The total number of duffs received (including change)\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getaddressbalance", "'{\"addresses\": [\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"]}'")
+ HelpExampleRpc("getaddressbalance", "{\"addresses\": [\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"]}")
);
std::vector<std::pair<uint256, int> > addresses;
if (!getAddressesFromParams(request.params, addresses)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
}
std::vector<std::pair<CAddressIndexKey, CAmount> > addressIndex;
for (std::vector<std::pair<uint256, int> >::iterator it = addresses.begin(); it != addresses.end(); it++) {
if (!GetAddressIndex((*it).first, (*it).second, addressIndex)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available for address");
}
}
CAmount balance = 0;
CAmount received = 0;
for (std::vector<std::pair<CAddressIndexKey, CAmount> >::const_iterator it=addressIndex.begin(); it!=addressIndex.end(); it++) {
if (it->second > 0) {
received += it->second;
}
balance += it->second;
}
UniValue result(UniValue::VOBJ);
result.push_back(Pair("balance", balance));
result.push_back(Pair("received", received));
return result;
}
UniValue getaddresstxids(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw runtime_error(
"getaddresstxids\n"
"\nReturns the txids for an address(es) (requires addressindex to be enabled).\n"
"\nArguments:\n"
"{\n"
" \"addresses\"\n"
" [\n"
" \"address\" (string) The base58check encoded address\n"
" ,...\n"
" ]\n"
" \"start\" (number) The start block height\n"
" \"end\" (number) The end block height\n"
"}\n"
"\nResult:\n"
"[\n"
" \"transactionid\" (string) The transaction id\n"
" ,...\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("getaddresstxids", "'{\"addresses\": [\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"]}'")
+ HelpExampleRpc("getaddresstxids", "{\"addresses\": [\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"]}")
);
std::vector<std::pair<uint256, int> > addresses;
if (!getAddressesFromParams(request.params, addresses)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
}
int start = 0;
int end = 0;
if (request.params[0].isObject()) {
UniValue startValue = find_value(request.params[0].get_obj(), "start");
UniValue endValue = find_value(request.params[0].get_obj(), "end");
if (startValue.isNum() && endValue.isNum()) {
start = startValue.get_int();
end = endValue.get_int();
}
}
std::vector<std::pair<CAddressIndexKey, CAmount> > addressIndex;
for (std::vector<std::pair<uint256, int> >::iterator it = addresses.begin(); it != addresses.end(); it++) {
if (start > 0 && end > 0) {
if (!GetAddressIndex((*it).first, (*it).second, addressIndex, start, end)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available for address");
}
} else {
if (!GetAddressIndex((*it).first, (*it).second, addressIndex)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available for address");
}
}
}
std::set<std::pair<int, std::string> > txids;
UniValue result(UniValue::VARR);
for (std::vector<std::pair<CAddressIndexKey, CAmount> >::const_iterator it=addressIndex.begin(); it!=addressIndex.end(); it++) {
int height = it->first.blockHeight;
std::string txid = it->first.txhash.GetHex();
if (addresses.size() > 1) {
txids.insert(std::make_pair(height, txid));
} else {
if (txids.insert(std::make_pair(height, txid)).second) {
result.push_back(txid);
}
}
}
if (addresses.size() > 1) {
for (std::set<std::pair<int, std::string> >::const_iterator it=txids.begin(); it!=txids.end(); it++) {
result.push_back(it->second);
}
}
return result;
}
UniValue getaddressvoteweight(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1 || !request.params[0].isObject())
throw runtime_error(
"getaddressvoteweight\n"
"\nReturns vote weight for an address (requires addressindex to be enabled).\n"
"\nArguments:\n"
"{\n"
" \"addresses\"\n"
" [\n"
" \"address\" (string) The base58check encoded address\n"
" ,...\n"
" ]\n"
" \"start\" (number) The start time of the vote weight period\n"
" \"end\" (number) The end time of the vote weight period\n"
"}\n"
"\nResult:\n"
"[\n"
" {\n"
" \"voteweight\" (number) The vote weight of the address\n"
" }\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("getaddressvoteweight", "'{\"addresses\": [\"NwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"], \"start\": 10, \"end\": 20}'")
+ HelpExampleRpc("getaddressvoteweight", "'{\"addresses\": [\"NwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"]}'")
);
// using chainactive
LOCK(cs_main);
UniValue result(UniValue::VOBJ);
UniValue startValue = find_value(request.params[0].get_obj(), "start");
UniValue endValue = find_value(request.params[0].get_obj(), "end");
int start = 0;
int end = 0;
if (startValue.isNum() && endValue.isNum()) {
start = startValue.get_int();
end = endValue.get_int();
if (end < start) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "End value is expected to be greater than start");
}
}
int start_block = -1;
int end_block = -1;
CBlockIndex *activeTip = chainActive.Tip();
CBlockIndex *lastBlock = activeTip->pprev;
// find start and end blocks
while(lastBlock){
// match end block
if(activeTip->GetBlockTime() >= end && lastBlock->GetBlockTime() < end && end_block == -1)
end_block = activeTip->nHeight;
else if(activeTip->GetBlockTime() >= end && lastBlock->GetBlockTime() <= end && end_block == -1)
end_block = lastBlock->nHeight;
// match start block
if(activeTip->GetBlockTime() >= start && lastBlock->GetBlockTime() < start && start_block == -1)
start_block = activeTip->nHeight;
if(activeTip->GetBlockTime() >= start && lastBlock->GetBlockTime() <= start && start_block == -1)
start_block = lastBlock->nHeight;
activeTip = lastBlock;
lastBlock = lastBlock->pprev;
if(start_block != -1 && end_block != -1)
break;
}
if(end_block == -1)
end_block = chainActive.Height();
start = start_block;
end = end_block;
std::vector<std::pair<uint256, int> > addresses;
if (!getAddressesFromParams(request.params, addresses)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
}
std::vector<std::pair<CAddressIndexKey, CAmount> > addressIndex;
for (std::vector<std::pair<uint256, int> >::iterator it = addresses.begin(); it != addresses.end(); it++) {
if (start > 0 && end > 0) {
if (!GetAddressIndex((*it).first, (*it).second, addressIndex, start, end)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available for address");
}
} else {
if (!GetAddressIndex((*it).first, (*it).second, addressIndex)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available for address");
}
}
}
CAmount totalWeight = 0;
int k = 0;
for (std::vector<std::pair<CAddressIndexKey, CAmount> >::const_iterator it=addressIndex.begin(); it!=addressIndex.end(); it++) {
std::string address;
if (!getAddressFromIndex(it->first.type, it->first.hashBytes, address)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unknown address type");
}
k++;
// check for coinstake
if(it->first.txindex != 0) continue;
// check for staking bypass
if(it->first.type == ADDR_INDT_WITNESS_KEY_HASH){
if(k == 1)
continue;
}
totalWeight += it->second;
}
result.pushKV("address_weight", ValueFromAmount(totalWeight));
result.pushKV("block_start", std::to_string(start));
result.pushKV("block_end", std::to_string(end));
return result;
}
UniValue getspentinfo(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1 || !request.params[0].isObject())
throw runtime_error(
"getspentinfo\n"
"\nReturns the txid and index where an output is spent.\n"
"\nArguments:\n"
"{\nï\\/x\n"
" \"txid\" (string) The hex string of the txid\n"
" \"index\" (number) The start block height\n"
"}\n"
"\nResult:\n"
"{\n"
" \"txid\" (string) The transaction id\n"
" \"index\" (number) The spending input index\n"
" ,...\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getspentinfo", "'{\"txid\": \"0437cd7f8525ceed2324359c2d0ba26006d92d856a9c20fa0241106ee5a597c9\", \"index\": 0}'")
+ HelpExampleRpc("getspentinfo", "{\"txid\": \"0437cd7f8525ceed2324359c2d0ba26006d92d856a9c20fa0241106ee5a597c9\", \"index\": 0}")
);
UniValue txidValue = find_value(request.params[0].get_obj(), "txid");
UniValue indexValue = find_value(request.params[0].get_obj(), "index");
if (!txidValue.isStr() || !indexValue.isNum()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid txid or index");
}
uint256 txid = ParseHashV(txidValue, "txid");
int outputIndex = indexValue.get_int();
CSpentIndexKey key(txid, outputIndex);
CSpentIndexValue value;
if (!GetSpentIndex(key, value)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to get spent info");
}
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("txid", value.txid.GetHex()));
obj.push_back(Pair("index", (int)value.inputIndex));
obj.push_back(Pair("height", value.blockHeight));
return obj;
}
static const CRPCCommand commands[] =
{ // category name actor (function) argNames
// --------------------- ------------------------ ----------------------- ----------
{ "control", "getmemoryinfo", &getmemoryinfo, {"mode"} },
{ "control", "logging", &logging, {"include", "exclude"}},
{ "util", "validateaddress", &validateaddress, {"address"} }, /* uses wallet if enabled */
{ "util", "createmultisig", &createmultisig, {"nrequired","keys"} },
{ "util", "verifymessage", &verifymessage, {"address","signature","message"} },
{ "util", "signmessagewithprivkey", &signmessagewithprivkey, {"privkey","message"} },
/* Address index */
{ "addressindex", "getaddressmempool", &getaddressmempool, {"addresses"} },
{ "addressindex", "getaddressutxos", &getaddressutxos, {"addresses"} },
{ "addressindex", "getaddressdeltas", &getaddressdeltas, {"addresses"} },
{ "addressindex", "getaddresstxids", &getaddresstxids, {"addresses"} },
{ "addressindex", "getaddressbalance", &getaddressbalance, {"addresses"} },
{ "NIX Governance", "getaddressvoteweight", &getaddressvoteweight, {"address", "start_time", "end_time"} },
/* Not shown in help */
{ "hidden", "setmocktime", &setmocktime, {"timestamp"}},
{ "hidden", "echo", &echo, {"arg0","arg1","arg2","arg3","arg4","arg5","arg6","arg7","arg8","arg9"}},
{ "hidden", "echojson", &echo, {"arg0","arg1","arg2","arg3","arg4","arg5","arg6","arg7","arg8","arg9"}},
{ "hidden", "getinfo", &getinfo_deprecated, {}},
};
void RegisterMiscRPCCommands(CRPCTable &t)
{
for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
t.appendCommand(commands[vcidx].name, &commands[vcidx]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment