Skip to content

Commit 251fb5e

Browse files
authored
Slightly optimize ApproximateBestSubset and its usage for PS txes (#3184)
* From 2 best sets with the same `nTotal` in ApproximateBestSubset prefer the one with less inputs * There is no reason to run ApproximateBestSubset again if nMinChange is 0 * Apply review suggestions
1 parent a55624b commit 251fb5e

File tree

1 file changed

+7
-2
lines changed

1 file changed

+7
-2
lines changed

src/wallet/wallet.cpp

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2863,13 +2863,15 @@ static void ApproximateBestSubset(const std::vector<CInputCoin>& vValue, const C
28632863

28642864
vfBest.assign(vValue.size(), true);
28652865
nBest = nTotalLower;
2866+
int nBestInputCount = 0;
28662867

28672868
FastRandomContext insecure_rand;
28682869

28692870
for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
28702871
{
28712872
vfIncluded.assign(vValue.size(), false);
28722873
CAmount nTotal = 0;
2874+
int nTotalInputCount = 0;
28732875
bool fReachedTarget = false;
28742876
for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
28752877
{
@@ -2884,16 +2886,19 @@ static void ApproximateBestSubset(const std::vector<CInputCoin>& vValue, const C
28842886
if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i])
28852887
{
28862888
nTotal += vValue[i].txout.nValue;
2889+
++nTotalInputCount;
28872890
vfIncluded[i] = true;
28882891
if (nTotal >= nTargetValue)
28892892
{
28902893
fReachedTarget = true;
2891-
if (nTotal < nBest)
2894+
if (nTotal < nBest || (nTotal == nBest && nTotalInputCount < nBestInputCount))
28922895
{
28932896
nBest = nTotal;
2897+
nBestInputCount = nTotalInputCount;
28942898
vfBest = vfIncluded;
28952899
}
28962900
nTotal -= vValue[i].txout.nValue;
2901+
--nTotalInputCount;
28972902
vfIncluded[i] = false;
28982903
}
28992904
}
@@ -3047,7 +3052,7 @@ bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const int nConfMin
30473052
CAmount nBest;
30483053

30493054
ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest);
3050-
if (nBest != nTargetValue && nTotalLower >= nTargetValue + nMinChange)
3055+
if (nBest != nTargetValue && nMinChange != 0 && nTotalLower >= nTargetValue + nMinChange)
30513056
ApproximateBestSubset(vValue, nTotalLower, nTargetValue + nMinChange, vfBest, nBest);
30523057

30533058
// If we have a bigger coin and (either the stochastic approximation didn't find a good solution,

0 commit comments

Comments
 (0)