Skip to content

Commit fd5c996

Browse files
committed
wallet: GetAvailableBalance, remove double walk-through every available coin
Filtering `AvailableCoins` by spendable outputs only and using the retrieved total_amount.
1 parent 162d4ad commit fd5c996

File tree

2 files changed

+12
-12
lines changed

2 files changed

+12
-12
lines changed

src/wallet/spend.cpp

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,6 @@ CoinsResult AvailableCoins(const CWallet& wallet,
9696
AssertLockHeld(wallet.cs_wallet);
9797

9898
CoinsResult result;
99-
CAmount nTotal = 0;
10099
// Either the WALLET_FLAG_AVOID_REUSE flag is not set (in which case we always allow), or we default to avoiding, and only in the case where
101100
// a coin control object is provided, and has the avoid address reuse flag set to false, do we allow already used addresses
102101
bool allow_used_addresses = !wallet.IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE) || (coinControl && !coinControl->m_avoid_address_reuse);
@@ -206,12 +205,11 @@ CoinsResult AvailableCoins(const CWallet& wallet,
206205

207206
int input_bytes = GetTxSpendSize(wallet, wtx, i, (coinControl && coinControl->fAllowWatchOnly));
208207
result.coins.emplace_back(outpoint, output, nDepth, input_bytes, spendable, solvable, safeTx, wtx.GetTxTime(), tx_from_me, feerate);
208+
result.total_amount += output.nValue;
209209

210210
// Checks the sum amount of all UTXO's.
211211
if (nMinimumSumAmount != MAX_MONEY) {
212-
nTotal += output.nValue;
213-
214-
if (nTotal >= nMinimumSumAmount) {
212+
if (result.total_amount >= nMinimumSumAmount) {
215213
return result;
216214
}
217215
}
@@ -234,14 +232,14 @@ CoinsResult AvailableCoinsListUnspent(const CWallet& wallet, const CCoinControl*
234232
CAmount GetAvailableBalance(const CWallet& wallet, const CCoinControl* coinControl)
235233
{
236234
LOCK(wallet.cs_wallet);
237-
238-
CAmount balance = 0;
239-
for (const COutput& out : AvailableCoinsListUnspent(wallet, coinControl).coins) {
240-
if (out.spendable) {
241-
balance += out.txout.nValue;
242-
}
243-
}
244-
return balance;
235+
return AvailableCoins(wallet,
236+
coinControl,
237+
std::nullopt, /*feerate=*/
238+
1, /*nMinimumAmount*/
239+
MAX_MONEY, /*nMaximumAmount*/
240+
MAX_MONEY, /*nMinimumSumAmount*/
241+
0 /*nMaximumCount*/
242+
).total_amount;
245243
}
246244

247245
const CTxOut& FindNonChangeParentOutput(const CWallet& wallet, const CTransaction& tx, int output)

src/wallet/spend.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,8 @@ TxSize CalculateMaximumSignedTxSize(const CTransaction& tx, const CWallet* walle
3636

3737
struct CoinsResult {
3838
std::vector<COutput> coins;
39+
// Sum of all the coins amounts
40+
CAmount total_amount{0};
3941
};
4042
/**
4143
* Return vector of available COutputs.

0 commit comments

Comments
 (0)