Skip to content

Commit ef744c0

Browse files
committed
Merge bitcoin/bitcoin#25729: wallet: Check max transaction weight in CoinSelection
c7c7ee9 test: Check max transaction weight in CoinSelection (Aurèle Oulès) 6b563ca wallet: Check max tx weight in coin selector (Aurèle Oulès) Pull request description: This PR is an attempt to fix #5782. I have added 4 test scenarios, 3 of them provided here bitcoin/bitcoin#5782 (comment) (slightly modified to use a segwit wallet). Here are my benchmarks : ## PR | ns/op | op/s | err% | ins/op | cyc/op | IPC | bra/op | miss% | total | benchmark |--------------------:|--------------------:|--------:|----------------:|----------------:|-------:|---------------:|--------:|----------:|:---------- | 1,466,341.00 | 681.97 | 0.6% | 11,176,762.00 | 3,358,752.00 | 3.328 | 1,897,839.00 | 0.3% | 0.02 | `CoinSelection` ## Master | ns/op | op/s | err% | ins/op | cyc/op | IPC | bra/op | miss% | total | benchmark |--------------------:|--------------------:|--------:|----------------:|----------------:|-------:|---------------:|--------:|----------:|:---------- | 1,526,029.00 | 655.30 | 0.5% | 11,142,188.00 | 3,499,200.00 | 3.184 | 1,994,156.00 | 0.2% | 0.02 | `CoinSelection` ACKs for top commit: achow101: reACK c7c7ee9 w0xlt: ACK bitcoin/bitcoin@c7c7ee9 furszy: diff ACK c7c7ee9 Tree-SHA512: ef0b28576ff845174651ba494aa9adee234c96e6f886d0e032eceb7050296e45b099dda0039d1dfb9944469f067627b2101f3ff855c70353cf39d1fc7ee81828
2 parents 8ccab65 + c7c7ee9 commit ef744c0

File tree

5 files changed

+160
-11
lines changed

5 files changed

+160
-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

src/wallet/test/coinselector_tests.cpp

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
#include <consensus/amount.h>
66
#include <node/context.h>
7+
#include <policy/policy.h>
78
#include <primitives/transaction.h>
89
#include <random.h>
910
#include <test/util/setup_common.h>
@@ -930,6 +931,124 @@ BOOST_AUTO_TEST_CASE(effective_value_test)
930931
BOOST_CHECK_EQUAL(output5.GetEffectiveValue(), nValue); // The effective value should be equal to the absolute value if input_bytes is -1
931932
}
932933

934+
static std::optional<SelectionResult> select_coins(const CAmount& target, const CoinSelectionParams& cs_params, const CCoinControl& cc, std::function<CoinsResult(CWallet&)> coin_setup, interfaces::Chain* chain, const ArgsManager& args)
935+
{
936+
std::unique_ptr<CWallet> wallet = std::make_unique<CWallet>(chain, "", args, CreateMockWalletDatabase());
937+
wallet->LoadWallet();
938+
LOCK(wallet->cs_wallet);
939+
wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
940+
wallet->SetupDescriptorScriptPubKeyMans();
941+
942+
auto available_coins = coin_setup(*wallet);
943+
944+
const auto result = SelectCoins(*wallet, available_coins, /*pre_set_inputs=*/ {}, target, cc, cs_params);
945+
if (result) {
946+
const auto signedTxSize = 10 + 34 + 68 * result->GetInputSet().size(); // static header size + output size + inputs size (P2WPKH)
947+
BOOST_CHECK_LE(signedTxSize * WITNESS_SCALE_FACTOR, MAX_STANDARD_TX_WEIGHT);
948+
949+
BOOST_CHECK_GE(result->GetSelectedValue(), target);
950+
}
951+
return result;
952+
}
953+
954+
static bool has_coin(const CoinSet& set, CAmount amount)
955+
{
956+
return std::any_of(set.begin(), set.end(), [&](const auto& coin) { return coin.GetEffectiveValue() == amount; });
957+
}
958+
959+
BOOST_AUTO_TEST_CASE(check_max_weight)
960+
{
961+
const CAmount target = 49.5L * COIN;
962+
CCoinControl cc;
963+
964+
FastRandomContext rand;
965+
CoinSelectionParams cs_params{
966+
rand,
967+
/*change_output_size=*/34,
968+
/*change_spend_size=*/68,
969+
/*min_change_target=*/CENT,
970+
/*effective_feerate=*/CFeeRate(0),
971+
/*long_term_feerate=*/CFeeRate(0),
972+
/*discard_feerate=*/CFeeRate(0),
973+
/*tx_noinputs_size=*/10 + 34, // static header size + output size
974+
/*avoid_partial=*/false,
975+
};
976+
977+
auto chain{m_node.chain.get()};
978+
979+
{
980+
// Scenario 1:
981+
// The actor starts with 1x 50.0 BTC and 1515x 0.033 BTC (~100.0 BTC total) unspent outputs
982+
// Then tries to spend 49.5 BTC
983+
// The 50.0 BTC output should be selected, because the transaction would otherwise be too large
984+
985+
// Perform selection
986+
987+
const auto result = select_coins(
988+
target, cs_params, cc, [&](CWallet& wallet) {
989+
CoinsResult available_coins;
990+
for (int j = 0; j < 1515; ++j) {
991+
add_coin(available_coins, wallet, CAmount(0.033 * COIN), CFeeRate(0), 144, false, 0, true);
992+
}
993+
994+
add_coin(available_coins, wallet, CAmount(50 * COIN), CFeeRate(0), 144, false, 0, true);
995+
return available_coins;
996+
},
997+
chain, m_args);
998+
999+
BOOST_CHECK(result);
1000+
BOOST_CHECK(has_coin(result->GetInputSet(), CAmount(50 * COIN)));
1001+
}
1002+
1003+
{
1004+
// Scenario 2:
1005+
1006+
// The actor starts with 400x 0.0625 BTC and 2000x 0.025 BTC (75.0 BTC total) unspent outputs
1007+
// Then tries to spend 49.5 BTC
1008+
// A combination of coins should be selected, such that the created transaction is not too large
1009+
1010+
// Perform selection
1011+
const auto result = select_coins(
1012+
target, cs_params, cc, [&](CWallet& wallet) {
1013+
CoinsResult available_coins;
1014+
for (int j = 0; j < 400; ++j) {
1015+
add_coin(available_coins, wallet, CAmount(0.0625 * COIN), CFeeRate(0), 144, false, 0, true);
1016+
}
1017+
for (int j = 0; j < 2000; ++j) {
1018+
add_coin(available_coins, wallet, CAmount(0.025 * COIN), CFeeRate(0), 144, false, 0, true);
1019+
}
1020+
return available_coins;
1021+
},
1022+
chain, m_args);
1023+
1024+
BOOST_CHECK(has_coin(result->GetInputSet(), CAmount(0.0625 * COIN)));
1025+
BOOST_CHECK(has_coin(result->GetInputSet(), CAmount(0.025 * COIN)));
1026+
}
1027+
1028+
{
1029+
// Scenario 3:
1030+
1031+
// The actor starts with 1515x 0.033 BTC (49.995 BTC total) unspent outputs
1032+
// No results should be returned, because the transaction would be too large
1033+
1034+
// Perform selection
1035+
const auto result = select_coins(
1036+
target, cs_params, cc, [&](CWallet& wallet) {
1037+
CoinsResult available_coins;
1038+
for (int j = 0; j < 1515; ++j) {
1039+
add_coin(available_coins, wallet, CAmount(0.033 * COIN), CFeeRate(0), 144, false, 0, true);
1040+
}
1041+
return available_coins;
1042+
},
1043+
chain, m_args);
1044+
1045+
// No results
1046+
// 1515 inputs * 68 bytes = 103,020 bytes
1047+
// 103,020 bytes * 4 = 412,080 weight, which is above the MAX_STANDARD_TX_WEIGHT of 400,000
1048+
BOOST_CHECK(!result);
1049+
}
1050+
}
1051+
9331052
BOOST_AUTO_TEST_CASE(SelectCoins_effective_value_test)
9341053
{
9351054
// Test that the effective value is used to check whether preset inputs provide sufficient funds when subtract_fee_outputs is not used.

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)