What changed, and why it matters
This commit is a performance optimization for the Monero wallet's RPC interface. It changes how account balances are calculated so that all accounts are scanned in a single pass instead of scanning the entire transaction history separately for each account. The commit also adds tests to verify that the new batch calculation produces the same results as the old individual calculation. There is no indication this fixes a security vulnerability; it appears to be a correctness-preserving efficiency improvement.
No security action required. Treat as a normal performance/correctness improvement. Reviewers may want to confirm the new function's behavior remains identical to the old balance()/unlocked_balance() pair across edge cases such as ignored output thresholds, frozen outputs, and unlock heights.
Security signals we found
No security-relevant keywords in commit title or message
Change is a performance optimization with added regression tests
Logic preserves existing strict and unlocked balance rules
No input parsing changes, no memory allocation changes beyond vector sizing, no cryptographic changes
Evidence from the diff
The patch introduces wallet2::balances_per_account(), which iterates m_transfers once and builds per-account balance/unlocked_balance totals, applying the same strict/non-strict rules, ignore-output thresholds, spent/frozen filters, and unlock-time checks as the existing balance() and unlocked_balance() methods. The wallet RPC server is updated to collect matching account indices first, call balances_per_account() once, and then populate the response. A unit test confirms the batched results match the existing per-account methods for both strict and non-strict modes, including pending change, failed transactions, and incoming pool payments.
Changed components
src/wallet/wallet2.cppsrc/wallet/wallet2.hsrc/wallet/wallet_rpc_server.cpptests/unit_tests/wallet_storage.cppInspect captured patch +165 / −16
### src/wallet/wallet2.cpp
@@ -7369,6 +7369,54 @@ uint64_t wallet2::balance(uint32_t index_major, bool strict) const
return amount;
}
//----------------------------------------------------------------------------------------------------
+std::vector<wallet2::account_balance> wallet2::balances_per_account(const std::vector<uint32_t>& account_indices, bool strict)
+{
+ std::vector<account_balance> balances(get_num_subaddress_accounts());
+ std::vector<bool> selected(balances.size(), false);
+ for (uint32_t index: account_indices)
+ selected.at(index) = true;
+
+ for (const transfer_details& td: m_transfers)
+ {
+ if (td.amount() > m_ignore_outputs_above || td.amount() < m_ignore_outputs_below ||
+ td.m_subaddr_index.major >= balances.size() || !selected[td.m_subaddr_index.major] ||
+ is_spent(td, strict) || td.m_frozen)
+ continue;
+
+ account_balance& account = balances[td.m_subaddr_index.major];
+ account.balance += td.amount();
+ if (is_transfer_unlocked(td))
+ account.unlocked_balance += td.amount();
+ }
+
+ 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() ||
+ !selected[tx.m_subaddr_account])
+ continue;
+
+ balances[tx.m_subaddr_account].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)
+ balances[index->major].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() && selected[payment.m_subaddr_index.major])
+ balances[payment.m_subaddr_index.major].balance += payment.m_amount;
+ }
+ }
+ 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
@@ -916,6 +916,12 @@ namespace tools
// locked & unlocked balance of given or current subaddress account
uint64_t balance(uint32_t subaddr_index_major, bool strict) const;
uint64_t unlocked_balance(uint32_t subaddr_index_major, bool strict, uint64_t *blocks_to_unlock = NULL, uint64_t *time_to_unlock = NULL);
+ struct account_balance
+ {
+ uint64_t balance = 0;
+ uint64_t unlocked_balance = 0;
+ };
+ std::vector<account_balance> balances_per_account(const std::vector<uint32_t>& account_indices, 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
@@ -898,37 +898,45 @@ namespace tools
{
res.total_balance = 0;
res.total_unlocked_balance = 0;
- cryptonote::subaddress_index subaddr_index = {0,0};
const std::pair<std::map<std::string, std::string>, std::vector<std::string>> account_tags = m_wallet->get_account_tags();
if (!req.tag.empty() && account_tags.first.count(req.tag) == 0 && !req.regexp)
{
er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
er.message = (boost::format(tr("Tag %s is unregistered.")) % req.tag).str();
return false;
}
- for (; subaddr_index.major < m_wallet->get_num_subaddress_accounts(); ++subaddr_index.major)
+ std::vector<uint32_t> account_indices;
+ for (uint32_t index = 0; index < m_wallet->get_num_subaddress_accounts(); ++index)
{
- bool no_match = !req.regexp ? (!req.tag.empty() && req.tag != account_tags.second[subaddr_index.major])
- : (!req.tag.empty() && !boost::regex_match(account_tags.second[subaddr_index.major], boost::regex(req.tag)));
- if (no_match)
- continue;
+ bool no_match = !req.regexp ? (!req.tag.empty() && req.tag != account_tags.second[index])
+ : (!req.tag.empty() && !boost::regex_match(account_tags.second[index], boost::regex(req.tag)));
+ if (!no_match)
+ account_indices.push_back(index);
+ }
+ if (account_indices.empty() && req.regexp)
+ {
+ er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
+ er.message = (boost::format(tr("No matches for regex filter %s .")) % req.tag).str();
+ return false;
+ }
+ if (account_indices.empty())
+ return true;
+
+ const auto balances = m_wallet->balances_per_account(account_indices, req.strict_balances);
+ for (uint32_t index: account_indices)
+ {
+ const cryptonote::subaddress_index subaddr_index = {index, 0};
wallet_rpc::COMMAND_RPC_GET_ACCOUNTS::subaddress_account_info info;
- info.account_index = subaddr_index.major;
+ info.account_index = index;
info.base_address = m_wallet->get_subaddress_as_str(subaddr_index);
- info.balance = m_wallet->balance(subaddr_index.major, req.strict_balances);
- info.unlocked_balance = m_wallet->unlocked_balance(subaddr_index.major, req.strict_balances);
+ info.balance = balances[index].balance;
+ info.unlocked_balance = balances[index].unlocked_balance;
info.label = m_wallet->get_subaddress_label(subaddr_index);
- info.tag = account_tags.second[subaddr_index.major];
+ info.tag = account_tags.second[index];
res.subaddress_accounts.push_back(info);
res.total_balance += info.balance;
res.total_unlocked_balance += info.unlocked_balance;
}
- if (res.subaddress_accounts.size() == 0 && req.regexp)
- {
- er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
- er.message = (boost::format(tr("No matches for regex filter %s .")) % req.tag).str();
- return false;
- }
}
catch (const std::exception& e)
{
### tests/unit_tests/wallet_storage.cpp
@@ -75,6 +75,56 @@ class wallet_accessor_test
return contains_key;
}
+ static void set_balance_test_data(tools::wallet2 &wallet)
+ {
+ while (wallet.m_blockchain.size() <= CRYPTONOTE_DEFAULT_TX_SPENDABLE_AGE)
+ wallet.m_blockchain.push_back(crypto::null_hash);
+ wallet.m_transfers.clear();
+ wallet.m_unconfirmed_txs.clear();
+ wallet.m_unconfirmed_payments.clear();
+
+ const auto add_transfer = [&](uint32_t major, uint32_t minor, uint64_t amount,
+ bool spent = false, uint64_t spent_height = 0,
+ bool frozen = false, uint64_t block_height = 0)
+ {
+ tools::wallet2::transfer_details td{};
+ td.m_subaddr_index = {major, minor};
+ td.m_amount = amount;
+ td.m_spent = spent;
+ td.m_spent_height = spent_height;
+ td.m_frozen = frozen;
+ td.m_block_height = block_height;
+ wallet.m_transfers.push_back(td);
+ };
+
+ add_transfer(0, 0, 100);
+ add_transfer(0, 1, 40, true);
+ add_transfer(0, 0, 30, true, 1);
+ add_transfer(0, 0, 20, false, 0, true);
+ add_transfer(0, 0, 5);
+ add_transfer(0, 0, 500);
+ add_transfer(1, 1, 70, false, 0, false, wallet.get_blockchain_current_height());
+
+ tools::wallet2::unconfirmed_transfer_details pending{};
+ pending.m_subaddr_account = 1;
+ pending.m_change = 9;
+ pending.m_state = tools::wallet2::unconfirmed_transfer_details::pending;
+ pending.m_dests.emplace_back(7, wallet.get_subaddress({1, 0}), true);
+ pending.m_dests.emplace_back(11, wallet.get_subaddress({2, 0}), true);
+ wallet.m_unconfirmed_txs.emplace(crypto::null_hash, pending);
+
+ crypto::hash failed_hash = crypto::null_hash;
+ failed_hash.data[0] = 1;
+ pending.m_change = 25;
+ pending.m_state = tools::wallet2::unconfirmed_transfer_details::failed;
+ wallet.m_unconfirmed_txs.emplace(failed_hash, pending);
+
+ tools::wallet2::pool_payment_details incoming{};
+ incoming.m_pd.m_amount = 13;
+ incoming.m_pd.m_subaddr_index = {2, 0};
+ wallet.m_unconfirmed_payments.emplace(crypto::null_hash, incoming);
+ }
+
static void forget_cached_key_image(tools::wallet2 &wallet, const size_t index)
{
crypto::key_image stale_key_image = AUTO_VAL_INIT(stale_key_image);
@@ -91,6 +141,43 @@ class wallet_accessor_test
}
};
+TEST(wallet_balance, batched_account_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);
+ ASSERT_GT(wallet.get_blockchain_current_height(), CRYPTONOTE_DEFAULT_TX_SPENDABLE_AGE);
+
+ for (bool strict: {false, true})
+ {
+ const auto balances = wallet.balances_per_account({0, 1, 2}, strict);
+ ASSERT_EQ(3, balances.size());
+ for (uint32_t account = 0; account < balances.size(); ++account)
+ {
+ EXPECT_EQ(wallet.balance(account, strict), balances[account].balance) << account << ", strict=" << strict;
+ EXPECT_EQ(wallet.unlocked_balance(account, strict), balances[account].unlocked_balance) << account << ", strict=" << strict;
+ }
+ EXPECT_EQ(strict ? 140 : 100, balances[0].balance);
+ EXPECT_EQ(strict ? 140 : 100, balances[0].unlocked_balance);
+ EXPECT_EQ(strict ? 70 : 86, balances[1].balance);
+ EXPECT_EQ(0, balances[1].unlocked_balance);
+ EXPECT_EQ(strict ? 0 : 13, balances[2].balance);
+ EXPECT_EQ(0, balances[2].unlocked_balance);
+
+ const auto filtered = wallet.balances_per_account({1}, strict);
+ EXPECT_EQ(0, filtered[0].balance);
+ EXPECT_EQ(wallet.balance(1, strict), filtered[1].balance);
+ EXPECT_EQ(wallet.unlocked_balance(1, strict), filtered[1].unlocked_balance);
+ EXPECT_EQ(0, filtered[2].balance);
+ }
+}
+
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.