What changed, and why it matters
This commit refactors how the Monero wallet RPC server reports balances when a user asks for all accounts at once. It introduces a single batched helper that computes per-subaddress balances across all accounts in one pass, instead of looping over each account separately. The change is primarily a performance and consistency improvement; it does not appear intended to fix a security bug, and no security relevance is stated in the commit or supplied references.
No security action required. Treat as a normal code-quality/performance improvement. Reviewers may optionally verify that the new batched aggregation produces identical totals to the previous per-account loop under all edge cases, as the added tests intend to demonstrate.
Security signals we found
No security-relevant keywords in commit title or message
No CVE, advisory, or bug-bounty attribution in commit or supplied references
Change is a refactoring/optimization with added test coverage
No input validation, parsing, or cryptographic code changes observed
No memory safety, authorization, or consensus changes observed
Evidence from the diff
The patch adds wallet2::balances_per_subaddress_all(), which returns a vector of maps containing balance, unlocked_balance, blocks_to_unlock, time_to_unlock, and num_unspent_outputs for every subaddress across all accounts. The wallet RPC get_balance handler is updated so that when req.all_accounts is true it uses this batched method, aggregates totals, and populates per_subaddress results in one code path. The single-account path is left largely unchanged. Functional and unit tests are added to verify that batched results match the older per-account methods.
Changed components
src/wallet/wallet2.cppsrc/wallet/wallet2.hsrc/wallet/wallet_rpc_server.cpptests/functional_tests/transfer.pytests/unit_tests/wallet_storage.cppInspect captured patch +195 / −14
### src/wallet/wallet2.cpp
@@ -7439,6 +7439,81 @@ std::vector<wallet2::account_balance> wallet2::balances_per_account(const std::v
return balances;
}
//----------------------------------------------------------------------------------------------------
+std::vector<std::map<uint32_t, wallet2::subaddress_balance>> wallet2::balances_per_subaddress_all(bool strict)
+{
+ std::vector<std::map<uint32_t, subaddress_balance>> balances(get_num_subaddress_accounts());
+ const uint64_t blockchain_height = get_blockchain_current_height();
+ const uint64_t now = time(NULL);
+
+ for (const transfer_details& td: m_transfers)
+ {
+ if (td.m_subaddr_index.major >= balances.size())
+ continue;
+
+ if (td.amount() > m_ignore_outputs_above || td.amount() < m_ignore_outputs_below ||
+ is_spent(td, strict) || td.m_frozen)
+ continue;
+
+ subaddress_balance& subaddress = balances[td.m_subaddr_index.major][td.m_subaddr_index.minor];
+ subaddress.balance += td.amount();
+ if (is_transfer_unlocked(td))
+ {
+ subaddress.unlocked_balance += td.amount();
+ }
+ else
+ {
+ uint64_t unlock_height = td.m_block_height + std::max<uint64_t>(CRYPTONOTE_DEFAULT_TX_SPENDABLE_AGE, CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_BLOCKS);
+ if (td.m_tx.unlock_time < CRYPTONOTE_MAX_BLOCK_NUMBER && td.m_tx.unlock_time > unlock_height)
+ unlock_height = td.m_tx.unlock_time;
+ const uint64_t unlock_time = td.m_tx.unlock_time >= CRYPTONOTE_MAX_BLOCK_NUMBER ? td.m_tx.unlock_time : 0;
+ subaddress.blocks_to_unlock = std::max(subaddress.blocks_to_unlock, unlock_height > blockchain_height ? unlock_height - blockchain_height : 0);
+ subaddress.time_to_unlock = std::max(subaddress.time_to_unlock, unlock_time > now ? unlock_time - now : 0);
+ }
+ }
+
+ if (!strict)
+ {
+ for (const auto& utx: m_unconfirmed_txs)
+ {
+ const unconfirmed_transfer_details& tx = utx.second;
+ if (tx.m_state == unconfirmed_transfer_details::failed || tx.m_subaddr_account >= balances.size())
+ continue;
+
+ subaddress_balance& change = balances[tx.m_subaddr_account][0];
+ change.balance += tx.m_change;
+ for (const auto& dest: tx.m_dests)
+ {
+ const auto index = get_subaddress_index(dest.addr);
+ if (index && index->major == tx.m_subaddr_account)
+ {
+ subaddress_balance& subaddress = balances[index->major][index->minor];
+ subaddress.balance += dest.amount;
+ }
+ }
+ }
+
+ for (const auto& utx: m_unconfirmed_payments)
+ {
+ const auto& payment = utx.second.m_pd;
+ if (payment.m_subaddr_index.major < balances.size())
+ {
+ subaddress_balance& subaddress = balances[payment.m_subaddr_index.major][payment.m_subaddr_index.minor];
+ subaddress.balance += payment.m_amount;
+ }
+ }
+ }
+ for (const transfer_details& td: m_transfers)
+ {
+ if (td.m_spent || td.m_subaddr_index.major >= balances.size())
+ continue;
+ auto& account = balances[td.m_subaddr_index.major];
+ const auto subaddress = account.find(td.m_subaddr_index.minor);
+ if (subaddress != account.end())
+ ++subaddress->second.num_unspent_outputs;
+ }
+ return balances;
+}
+//----------------------------------------------------------------------------------------------------
uint64_t wallet2::unlocked_balance(uint32_t index_major, bool strict, uint64_t *blocks_to_unlock, uint64_t *time_to_unlock)
{
uint64_t amount = 0;
### src/wallet/wallet2.h
@@ -926,6 +926,15 @@ namespace tools
uint64_t unlocked_balance = 0;
};
std::vector<account_balance> balances_per_account(const std::vector<uint32_t>& account_indices, bool strict);
+ struct subaddress_balance
+ {
+ uint64_t balance = 0;
+ uint64_t unlocked_balance = 0;
+ uint64_t blocks_to_unlock = 0;
+ uint64_t time_to_unlock = 0;
+ uint64_t num_unspent_outputs = 0;
+ };
+ std::vector<std::map<uint32_t, subaddress_balance>> balances_per_subaddress_all(bool strict);
// locked & unlocked balance per subaddress of given or current subaddress account
std::map<uint32_t, uint64_t> balance_per_subaddress(uint32_t subaddr_index_major, bool strict) const;
std::map<uint32_t, std::pair<uint64_t, std::pair<uint64_t, uint64_t>>> unlocked_balance_per_subaddress(uint32_t subaddr_index_major, bool strict);
### src/wallet/wallet_rpc_server.cpp
@@ -695,24 +695,48 @@ namespace tools
if (!m_wallet) return not_open(er);
try
{
- res.balance = req.all_accounts ? m_wallet->balance_all(req.strict) : m_wallet->balance(req.account_index, req.strict);
- res.unlocked_balance = req.all_accounts ? m_wallet->unlocked_balance_all(req.strict, &res.blocks_to_unlock, &res.time_to_unlock) : m_wallet->unlocked_balance(req.account_index, req.strict, &res.blocks_to_unlock, &res.time_to_unlock);
- res.multisig_import_needed = m_wallet->get_multisig_status().multisig_is_active && m_wallet->has_multisig_partial_key_images();
- std::map<uint32_t, std::map<uint32_t, uint64_t>> balance_per_subaddress_per_account;
- std::map<uint32_t, std::map<uint32_t, std::pair<uint64_t, std::pair<uint64_t, uint64_t>>>> unlocked_balance_per_subaddress_per_account;
if (req.all_accounts)
{
- for (uint32_t account_index = 0; account_index < m_wallet->get_num_subaddress_accounts(); ++account_index)
+ res.balance = 0;
+ res.unlocked_balance = 0;
+ res.blocks_to_unlock = 0;
+ res.time_to_unlock = 0;
+ res.multisig_import_needed = m_wallet->get_multisig_status().multisig_is_active && m_wallet->has_multisig_partial_key_images();
+ const auto balances = m_wallet->balances_per_subaddress_all(req.strict);
+ for (uint32_t account_index = 0; account_index < balances.size(); ++account_index)
{
- balance_per_subaddress_per_account[account_index] = m_wallet->balance_per_subaddress(account_index, req.strict);
- unlocked_balance_per_subaddress_per_account[account_index] = m_wallet->unlocked_balance_per_subaddress(account_index, req.strict);
+ for (const auto& entry: balances[account_index])
+ {
+ const auto& subaddress = entry.second;
+ res.balance += subaddress.balance;
+ res.unlocked_balance += subaddress.unlocked_balance;
+ res.blocks_to_unlock = std::max(res.blocks_to_unlock, subaddress.blocks_to_unlock);
+ res.time_to_unlock = std::max(res.time_to_unlock, subaddress.time_to_unlock);
+
+ wallet_rpc::COMMAND_RPC_GET_BALANCE::per_subaddress_info info;
+ info.account_index = account_index;
+ info.address_index = entry.first;
+ const cryptonote::subaddress_index index = {account_index, entry.first};
+ info.address = m_wallet->get_subaddress_as_str(index);
+ info.balance = subaddress.balance;
+ info.unlocked_balance = subaddress.unlocked_balance;
+ info.blocks_to_unlock = subaddress.blocks_to_unlock;
+ info.time_to_unlock = subaddress.time_to_unlock;
+ info.label = m_wallet->get_subaddress_label(index);
+ info.num_unspent_outputs = subaddress.num_unspent_outputs;
+ res.per_subaddress.emplace_back(std::move(info));
+ }
}
+ return true;
}
- else
- {
- balance_per_subaddress_per_account[req.account_index] = m_wallet->balance_per_subaddress(req.account_index, req.strict);
- unlocked_balance_per_subaddress_per_account[req.account_index] = m_wallet->unlocked_balance_per_subaddress(req.account_index, req.strict);
- }
+
+ res.balance = m_wallet->balance(req.account_index, req.strict);
+ res.unlocked_balance = m_wallet->unlocked_balance(req.account_index, req.strict, &res.blocks_to_unlock, &res.time_to_unlock);
+ res.multisig_import_needed = m_wallet->get_multisig_status().multisig_is_active && m_wallet->has_multisig_partial_key_images();
+ std::map<uint32_t, std::map<uint32_t, uint64_t>> balance_per_subaddress_per_account;
+ std::map<uint32_t, std::map<uint32_t, std::pair<uint64_t, std::pair<uint64_t, uint64_t>>>> unlocked_balance_per_subaddress_per_account;
+ balance_per_subaddress_per_account[req.account_index] = m_wallet->balance_per_subaddress(req.account_index, req.strict);
+ unlocked_balance_per_subaddress_per_account[req.account_index] = m_wallet->unlocked_balance_per_subaddress(req.account_index, req.strict);
std::vector<tools::wallet2::transfer_details> transfers;
m_wallet->get_transfers(transfers);
for (const auto& p : balance_per_subaddress_per_account)
@@ -721,7 +745,7 @@ namespace tools
std::map<uint32_t, uint64_t> balance_per_subaddress = p.second;
std::map<uint32_t, std::pair<uint64_t, std::pair<uint64_t, uint64_t>>> unlocked_balance_per_subaddress = unlocked_balance_per_subaddress_per_account[account_index];
std::set<uint32_t> address_indices;
- if (!req.all_accounts && !req.address_indices.empty())
+ if (!req.address_indices.empty())
{
address_indices = req.address_indices;
}
### tests/functional_tests/transfer.py
@@ -1661,9 +1661,22 @@ def check_transfer_by_txid_all_accounts(self):
daemon = Daemon()
account = self.wallet[1].create_account('second account')
assert account.account_index == 1
+
+ def check_all_account_balances():
+ for strict in (False, True):
+ first = self.wallet[1].get_balance(account_index = 0, strict = strict)
+ second = self.wallet[1].get_balance(account_index = 1, strict = strict)
+ all_accounts = self.wallet[1].get_balance(account_index = 1, address_indices = [999], all_accounts = True, strict = strict)
+ assert all_accounts.balance == first.balance + second.balance
+ assert all_accounts.unlocked_balance == first.unlocked_balance + second.unlocked_balance
+ assert all_accounts.blocks_to_unlock == max(first.blocks_to_unlock, second.blocks_to_unlock)
+ assert all_accounts.time_to_unlock == max(first.time_to_unlock, second.time_to_unlock)
+ assert all_accounts.get('per_subaddress', []) == first.get('per_subaddress', []) + second.get('per_subaddress', [])
+
dst = {'address': account.address, 'amount': 100000000000}
incoming_txid = self.wallet[0].transfer([dst]).tx_hash
self.wallet[1].refresh()
+ check_all_account_balances()
def check_transfer(txid, expected_type):
try:
@@ -1685,11 +1698,13 @@ def check_transfer(txid, expected_type):
daemon.generateblocks('42ey1afDFnn4886T7196doS9GPMzexD9gXpsZJDwVjeRVdFCSoHnv7KPbBeGpzJBzHRCAs9UxqeoyFQMYbqSWYTfJJQAWDm', 10)
self.wallet[1].refresh()
+ check_all_account_balances()
check_transfer(incoming_txid, 'in')
assert self.wallet[1].get_balance(account_index = 1).unlocked_balance >= 50000000000
dst = {'address': self.wallet[0].get_address().address, 'amount': 50000000000}
outgoing_txid = self.wallet[1].transfer([dst], account_index = 1).tx_hash
+ check_all_account_balances()
check_transfer(outgoing_txid, 'pending')
daemon.generateblocks('42ey1afDFnn4886T7196doS9GPMzexD9gXpsZJDwVjeRVdFCSoHnv7KPbBeGpzJBzHRCAs9UxqeoyFQMYbqSWYTfJJQAWDm', 1)
### tests/unit_tests/wallet_storage.cpp
@@ -109,6 +109,8 @@ class wallet_accessor_test
add_transfer(0, 0, 5);
add_transfer(0, 0, 500);
add_transfer(1, 1, 70, false, 0, false, wallet.get_blockchain_current_height());
+ add_transfer(2, 1, 5);
+ add_transfer(2, 2, 15, false, 0, true);
tools::wallet2::unconfirmed_transfer_details pending{};
pending.m_subaddr_account = 1;
@@ -269,6 +271,62 @@ TEST(wallet_storage, upgrade_legacy_unencrypted_keys)
}
}
+TEST(wallet_balance, batched_subaddress_balances_match_individual_balances)
+{
+ const path wallet_file = unit_test::data_dir / "wallet_9svHk1";
+ tools::wallet2 wallet(cryptonote::TESTNET);
+ wallet.load(wallet_file.string(), epee::wipeable_string("test"));
+ wallet.set_subaddress_lookahead(1, 1);
+ wallet.add_subaddress_account("second");
+ wallet.add_subaddress_account("third");
+ wallet.ignore_outputs_below(10);
+ wallet.ignore_outputs_above(200);
+ wallet_accessor_test::set_balance_test_data(wallet);
+ tools::wallet2::transfer_container transfers;
+ wallet.get_transfers(transfers);
+
+ for (bool strict: {false, true})
+ {
+ const auto batched = wallet.balances_per_subaddress_all(strict);
+ ASSERT_EQ(wallet.get_num_subaddress_accounts(), batched.size());
+ uint64_t total_balance = 0, total_unlocked_balance = 0;
+ uint64_t blocks_to_unlock = 0, time_to_unlock = 0;
+ for (uint32_t major = 0; major < batched.size(); ++major)
+ {
+ const auto balances = wallet.balance_per_subaddress(major, strict);
+ const auto unlocked = wallet.unlocked_balance_per_subaddress(major, strict);
+ std::vector<uint32_t> emitted_indices;
+ for (const auto& entry: batched[major])
+ {
+ emitted_indices.push_back(entry.first);
+ const auto found = balances.find(entry.first);
+ ASSERT_NE(balances.end(), found);
+ EXPECT_EQ(found->second, entry.second.balance);
+ const auto unlocked_entry = unlocked.find(entry.first);
+ EXPECT_EQ(unlocked_entry == unlocked.end() ? 0 : unlocked_entry->second.first, entry.second.unlocked_balance);
+ EXPECT_EQ(unlocked_entry == unlocked.end() ? 0 : unlocked_entry->second.second.first, entry.second.blocks_to_unlock);
+ EXPECT_EQ(unlocked_entry == unlocked.end() ? 0 : unlocked_entry->second.second.second, entry.second.time_to_unlock);
+ EXPECT_EQ(std::count_if(transfers.begin(), transfers.end(), [&](const tools::wallet2::transfer_details& td) {
+ return !td.m_spent && td.m_subaddr_index.major == major && td.m_subaddr_index.minor == entry.first;
+ }), entry.second.num_unspent_outputs);
+ total_balance += entry.second.balance;
+ total_unlocked_balance += entry.second.unlocked_balance;
+ blocks_to_unlock = std::max(blocks_to_unlock, entry.second.blocks_to_unlock);
+ time_to_unlock = std::max(time_to_unlock, entry.second.time_to_unlock);
+ }
+ std::vector<uint32_t> expected_indices;
+ for (const auto& entry: balances)
+ expected_indices.push_back(entry.first);
+ EXPECT_EQ(expected_indices, emitted_indices);
+ }
+ EXPECT_EQ(wallet.balance_all(strict), total_balance);
+ uint64_t expected_blocks = 0, expected_time = 0;
+ EXPECT_EQ(wallet.unlocked_balance_all(strict, &expected_blocks, &expected_time), total_unlocked_balance);
+ EXPECT_EQ(expected_blocks, blocks_to_unlock);
+ EXPECT_EQ(expected_time, time_to_unlock);
+ }
+}
+
TEST(wallet_storage, store_to_file2file)
{
const path source_wallet_file = unit_test::data_dir / "wallet_00fd416a";Why this scored 19/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.