rpc: Tweak getaddressbalance to also show spendable and immature balances (#4098)

* rpc: Tweak getaddressbalance to also show spendable and immature balances

* tests: Check `balance_immature` and `balance_spendable`
This commit is contained in:
UdjinM6 2021-04-15 20:30:14 +03:00 committed by pasta
parent 68caf300a9
commit 4a883a7307
2 changed files with 26 additions and 3 deletions

View File

@ -6,6 +6,7 @@
#include <chain.h>
#include <clientversion.h>
#include <consensus/consensus.h>
#include <core_io.h>
#include <evo/mnauth.h>
#include <init.h>
@ -770,8 +771,10 @@ UniValue getaddressbalance(const JSONRPCRequest& request)
"}\n"
"\nResult:\n"
"{\n"
" \"balance\" (string) The current balance in duffs\n"
" \"received\" (string) The total number of duffs received (including change)\n"
" \"balance\": xxxxx, (numeric) The current total balance in duffs\n"
" \"balance_immature\": xxxxx, (numeric) The current immature balance in duffs\n"
" \"balance_spendable\": xxxxx, (numeric) The current spendable balance in duffs\n"
" \"received\": xxxxx (numeric) The total number of duffs received (including change)\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getaddressbalance", "'{\"addresses\": [\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"]}'")
@ -792,18 +795,33 @@ UniValue getaddressbalance(const JSONRPCRequest& request)
}
}
int nHeight;
{
LOCK(cs_main);
nHeight = chainActive.Height();
}
CAmount balance = 0;
CAmount balance_spendable = 0;
CAmount balance_immature = 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;
}
if (it->first.txindex == 0 && nHeight - it->first.blockHeight < COINBASE_MATURITY) {
balance_immature += it->second;
} else {
balance_spendable += it->second;
}
balance += it->second;
}
UniValue result(UniValue::VOBJ);
result.pushKV("balance", balance);
result.pushKV("balance_immature", balance_immature);
result.pushKV("balance_spendable", balance_spendable);
result.pushKV("received", received);
return result;

View File

@ -48,7 +48,8 @@ class AddressIndexTest(BitcoinTestFramework):
self.sync_all()
self.log.info("Mining blocks...")
self.nodes[0].generate(105)
mining_address = self.nodes[0].getnewaddress()
self.nodes[0].generatetoaddress(105, mining_address)
self.sync_all()
chain_height = self.nodes[1].getblockcount()
@ -58,7 +59,11 @@ class AddressIndexTest(BitcoinTestFramework):
# Check that balances are correct
balance0 = self.nodes[1].getaddressbalance("93bVhahvUKmQu8gu9g3QnPPa2cxFK98pMB")
balance_mining = self.nodes[1].getaddressbalance(mining_address)
assert_equal(balance0["balance"], 0)
assert_equal(balance_mining["balance"], 105 * 500 * COIN)
assert_equal(balance_mining["balance_immature"], 100 * 500 * COIN)
assert_equal(balance_mining["balance_spendable"], 5 * 500 * COIN)
# Check p2pkh and p2sh address indexes
self.log.info("Testing p2pkh and p2sh address index...")