Skip to content

Commit 6b563ca

Browse files
aureleoulesachow101
andcommitted
wallet: Check max tx weight in coin selector
Co-authored-by: Andrew Chow <[email protected]>
1 parent 7734a01 commit 6b563ca

File tree

4 files changed

+41
-11
lines changed

4 files changed

+41
-11
lines changed

src/wallet/coinselection.cpp

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
#include <wallet/coinselection.h>
66

77
#include <consensus/amount.h>
8+
#include <consensus/consensus.h>
89
#include <policy/feerate.h>
910
#include <util/check.h>
1011
#include <util/system.h>
@@ -354,6 +355,10 @@ void OutputGroup::Insert(const COutput& output, size_t ancestors, size_t descend
354355
// descendants is the count as seen from the top ancestor, not the descendants as seen from the
355356
// coin itself; thus, this value is counted as the max, not the sum
356357
m_descendants = std::max(m_descendants, descendants);
358+
359+
if (output.input_bytes > 0) {
360+
m_weight += output.input_bytes * WITNESS_SCALE_FACTOR;
361+
}
357362
}
358363

359364
bool OutputGroup::EligibleForSpending(const CoinEligibilityFilter& eligibility_filter) const
@@ -436,18 +441,25 @@ void SelectionResult::Clear()
436441
{
437442
m_selected_inputs.clear();
438443
m_waste.reset();
444+
m_weight = 0;
439445
}
440446

441447
void SelectionResult::AddInput(const OutputGroup& group)
442448
{
443449
util::insert(m_selected_inputs, group.m_outputs);
444450
m_use_effective = !group.m_subtract_fee_outputs;
451+
452+
m_weight += group.m_weight;
445453
}
446454

447455
void SelectionResult::AddInputs(const std::set<COutput>& inputs, bool subtract_fee_outputs)
448456
{
449457
util::insert(m_selected_inputs, inputs);
450458
m_use_effective = !subtract_fee_outputs;
459+
460+
m_weight += std::accumulate(inputs.cbegin(), inputs.cend(), 0, [](int sum, const auto& coin) {
461+
return sum + std::max(coin.input_bytes, 0) * WITNESS_SCALE_FACTOR;
462+
});
451463
}
452464

453465
void SelectionResult::Merge(const SelectionResult& other)
@@ -462,6 +474,8 @@ void SelectionResult::Merge(const SelectionResult& other)
462474
}
463475
util::insert(m_selected_inputs, other.m_selected_inputs);
464476
assert(m_selected_inputs.size() == expected_count);
477+
478+
m_weight += other.m_weight;
465479
}
466480

467481
const std::set<COutput>& SelectionResult::GetInputSet() const

src/wallet/coinselection.h

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
#define BITCOIN_WALLET_COINSELECTION_H
77

88
#include <consensus/amount.h>
9+
#include <consensus/consensus.h>
910
#include <policy/feerate.h>
1011
#include <primitives/transaction.h>
1112
#include <random.h>
@@ -223,6 +224,8 @@ struct OutputGroup
223224
/** Indicate that we are subtracting the fee from outputs.
224225
* When true, the value that is used for coin selection is the UTXO's real value rather than effective value */
225226
bool m_subtract_fee_outputs{false};
227+
/** Total weight of the UTXOs in this group. */
228+
int m_weight{0};
226229

227230
OutputGroup() {}
228231
OutputGroup(const CoinSelectionParams& params) :
@@ -295,6 +298,8 @@ struct SelectionResult
295298
bool m_use_effective{false};
296299
/** The computed waste */
297300
std::optional<CAmount> m_waste;
301+
/** Total weight of the selected inputs */
302+
int m_weight{0};
298303

299304
public:
300305
explicit SelectionResult(const CAmount target, SelectionAlgorithm algo)
@@ -353,6 +358,8 @@ struct SelectionResult
353358
CAmount GetTarget() const { return m_target; }
354359

355360
SelectionAlgorithm GetAlgo() const { return m_algo; }
361+
362+
int GetWeight() const { return m_weight; }
356363
};
357364

358365
std::optional<SelectionResult> SelectCoinsBnB(std::vector<OutputGroup>& utxo_pool, const CAmount& selection_target, const CAmount& cost_of_change);

src/wallet/spend.cpp

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@
22
// Distributed under the MIT software license, see the accompanying
33
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
44

5+
#include <algorithm>
56
#include <consensus/amount.h>
67
#include <consensus/validation.h>
78
#include <interfaces/chain.h>
9+
#include <numeric>
810
#include <policy/policy.h>
911
#include <script/signingprovider.h>
1012
#include <util/check.h>
@@ -555,14 +557,24 @@ std::optional<SelectionResult> ChooseSelectionResult(const CWallet& wallet, cons
555557
results.push_back(*srd_result);
556558
}
557559

558-
if (results.size() == 0) {
560+
if (results.empty()) {
559561
// No solution found
560562
return std::nullopt;
561563
}
562564

565+
std::vector<SelectionResult> eligible_results;
566+
std::copy_if(results.begin(), results.end(), std::back_inserter(eligible_results), [coin_selection_params](const SelectionResult& result) {
567+
const auto initWeight{coin_selection_params.tx_noinputs_size * WITNESS_SCALE_FACTOR};
568+
return initWeight + result.GetWeight() <= static_cast<int>(MAX_STANDARD_TX_WEIGHT);
569+
});
570+
571+
if (eligible_results.empty()) {
572+
return std::nullopt;
573+
}
574+
563575
// Choose the result with the least waste
564576
// If the waste is the same, choose the one which spends more inputs.
565-
auto& best_result = *std::min_element(results.begin(), results.end());
577+
auto& best_result = *std::min_element(eligible_results.begin(), eligible_results.end());
566578
return best_result;
567579
}
568580

@@ -867,19 +879,16 @@ static util::Result<CreatedTransactionResult> CreateTransactionInternal(
867879
const auto change_spend_fee = coin_selection_params.m_discard_feerate.GetFee(coin_selection_params.change_spend_size);
868880
coin_selection_params.min_viable_change = std::max(change_spend_fee + 1, dust);
869881

882+
// Static vsize overhead + outputs vsize. 4 nVersion, 4 nLocktime, 1 input count, 1 witness overhead (dummy, flag, stack size)
883+
coin_selection_params.tx_noinputs_size = 10 + GetSizeOfCompactSize(vecSend.size()); // bytes for output count
884+
870885
// vouts to the payees
871-
if (!coin_selection_params.m_subtract_fee_outputs) {
872-
coin_selection_params.tx_noinputs_size = 10; // Static vsize overhead + outputs vsize. 4 nVersion, 4 nLocktime, 1 input count, 1 witness overhead (dummy, flag, stack size)
873-
coin_selection_params.tx_noinputs_size += GetSizeOfCompactSize(vecSend.size()); // bytes for output count
874-
}
875886
for (const auto& recipient : vecSend)
876887
{
877888
CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
878889

879890
// Include the fee cost for outputs.
880-
if (!coin_selection_params.m_subtract_fee_outputs) {
881-
coin_selection_params.tx_noinputs_size += ::GetSerializeSize(txout, PROTOCOL_VERSION);
882-
}
891+
coin_selection_params.tx_noinputs_size += ::GetSerializeSize(txout, PROTOCOL_VERSION);
883892

884893
if (IsDust(txout, wallet.chain().relayDustFee())) {
885894
return util::Error{_("Transaction amount too small")};
@@ -888,7 +897,7 @@ static util::Result<CreatedTransactionResult> CreateTransactionInternal(
888897
}
889898

890899
// Include the fees for things that aren't inputs, excluding the change output
891-
const CAmount not_input_fees = coin_selection_params.m_effective_feerate.GetFee(coin_selection_params.tx_noinputs_size);
900+
const CAmount not_input_fees = coin_selection_params.m_effective_feerate.GetFee(coin_selection_params.m_subtract_fee_outputs ? 0 : coin_selection_params.tx_noinputs_size);
892901
CAmount selection_target = recipients_sum + not_input_fees;
893902

894903
// Fetch manually selected coins

test/functional/rpc_fundrawtransaction.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -987,7 +987,7 @@ def test_transaction_too_large(self):
987987
outputs[recipient.getnewaddress()] = 0.1
988988
wallet.sendmany("", outputs)
989989
self.generate(self.nodes[0], 10)
990-
assert_raises_rpc_error(-4, "Transaction too large", recipient.fundrawtransaction, rawtx)
990+
assert_raises_rpc_error(-4, "Insufficient funds", recipient.fundrawtransaction, rawtx)
991991
self.nodes[0].unloadwallet("large")
992992

993993
def test_external_inputs(self):

0 commit comments

Comments
 (0)