Skip to content

Commit 20449ef

Browse files
committed
Don't overpay fee if we have selected new coins that result in a smaller transaction.
On repeated calls to SelectCoins we try to meet the fee necessary for the last transaction, the new fee required might be smaller, so increase our change by the difference if we can.
1 parent 42f5ce4 commit 20449ef

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

src/wallet/wallet.cpp

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2534,8 +2534,25 @@ bool CWallet::CreateTransaction(const vector<CRecipient>& vecSend, CWalletTx& wt
25342534
return false;
25352535
}
25362536

2537-
if (nFeeRet >= nFeeNeeded)
2537+
if (nFeeRet >= nFeeNeeded) {
2538+
// Reduce fee to only the needed amount if we have change
2539+
// output to increase. This prevents potential overpayment
2540+
// in fees if the coins selected to meet nFeeNeeded result
2541+
// in a transaction that requires less fee than the prior
2542+
// iteration.
2543+
// TODO: The case where nSubtractFeeFromAmount > 0 remains
2544+
// to be addressed because it requires returning the fee to
2545+
// the payees and not the change output.
2546+
// TODO: The case where there is no change output remains
2547+
// to be addressed so we avoid creating too small an output.
2548+
if (nFeeRet > nFeeNeeded && nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2549+
CAmount extraFeePaid = nFeeRet - nFeeNeeded;
2550+
vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2551+
change_position->nValue += extraFeePaid;
2552+
nFeeRet -= extraFeePaid;
2553+
}
25382554
break; // Done, enough fee included.
2555+
}
25392556

25402557
// Try to reduce change to include necessary fee
25412558
if (nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {

0 commit comments

Comments
 (0)