20static void AddCoin(
const CAmount& value,
int n_input,
int n_input_bytes,
int locktime, std::vector<COutput>& coins,
CFeeRate fee_rate)
23 tx.
vout.resize(n_input + 1);
24 tx.
vout[n_input].nValue = value;
26 coins.emplace_back(
COutPoint(tx.
GetHash(), n_input), tx.
vout.at(n_input), 0, n_input_bytes,
true,
true, 0,
true, fee_rate);
33 bool valid_outputgroup{
false};
34 for (
auto& coin : coins) {
35 if (!positive_only || (positive_only && coin.GetEffectiveValue() > 0)) {
36 output_group.Insert(std::make_shared<COutput>(coin), 0, 0);
40 valid_outputgroup = !positive_only || output_group.GetSelectionAmount() > 0;
42 output_groups.push_back(output_group);
44 valid_outputgroup =
false;
47 if (valid_outputgroup) output_groups.push_back(output_group);
57 if (total_balance + amount >=
MAX_MONEY) {
61 total_balance += amount;
71 for (
const auto& utxo : utxos) {
72 utxo_pool.insert(std::make_shared<COutput>(utxo));
74 result.
AddInputs(utxo_pool, subtract_fee_outputs);
84 std::vector<COutput> utxo_pool;
95 coin_params.m_cost_of_change= coin_params.m_effective_feerate.GetFee(coin_params.change_output_size) + coin_params.m_long_term_feerate.GetFee(coin_params.change_spend_size);
96 coin_params.m_change_fee = coin_params.m_effective_feerate.GetFee(coin_params.change_output_size);
98 coin_params.m_min_change_target =
CHANGE_LOWER + coin_params.m_change_fee;
103 int next_locktime{0};
108 if (total_balance + amount >=
MAX_MONEY) {
111 AddCoin(amount, n_input, n_input_bytes, ++next_locktime, utxo_pool, coin_params.m_effective_feerate);
112 total_balance += amount;
113 CAmount eff_value = amount - coin_params.m_effective_feerate.GetFee(n_input_bytes);
114 max_spendable += eff_value;
117 std::vector<OutputGroup> group_pos;
122 if (target + coin_params.m_min_change_target > max_spendable ||
HasErrorMsg(result_cg))
return;
124 if (!result_cg->GetAlgoCompleted())
return;
127 if (result_srd && result_srd->GetChange(
CHANGE_LOWER, coin_params.m_change_fee) > 0) {
128 assert(result_srd->GetWeight() >= result_cg->GetWeight());
132 if (result_knapsack && result_knapsack->GetChange(
CHANGE_LOWER, coin_params.m_change_fee) > 0) {
133 assert(result_knapsack->GetWeight() >= result_cg->GetWeight());
150 int next_locktime{0};
151 static constexpr unsigned max_output_groups{16};
152 std::vector<OutputGroup> group_pos;
157 const CAmount input_fee = coin_params.m_effective_feerate.GetFee(n_input_bytes);
160 const CAmount amount{eff_value + input_fee};
161 std::vector<COutput> temp_utxo_pool;
163 AddCoin(amount, 0, n_input_bytes, ++next_locktime, temp_utxo_pool, coin_params.m_effective_feerate);
164 max_spendable += eff_value;
167 output_group.Insert(std::make_shared<COutput>(temp_utxo_pool.at(0)), 0, 0);
168 group_pos.push_back(output_group);
178 int best_weight{std::numeric_limits<int>::max()};
179 for (uint32_t pattern = 1; (pattern >>
num_groups) == 0; ++pattern) {
181 int subset_weight{0};
183 if ((pattern >> i) & 1) {
184 subset_amount += group_pos[i].GetSelectionAmount();
185 subset_weight += group_pos[i].m_weight;
188 if ((subset_amount >= target + coin_params.m_min_change_target) && (subset_weight < best_weight || (subset_weight == best_weight && subset_amount < best_amount))) {
189 best_weight = subset_weight;
190 best_amount = subset_amount;
194 if (best_weight < std::numeric_limits<int>::max()) {
198 auto result_cg =
CoinGrinder(group_pos, target, coin_params.m_min_change_target, high_max_selection_weight);
200 assert(result_cg->GetWeight() <= high_max_selection_weight);
201 assert(result_cg->GetSelectedEffectiveValue() >= target + coin_params.m_min_change_target);
202 assert(best_weight < result_cg->GetWeight() || (best_weight == result_cg->GetWeight() && best_amount <= result_cg->GetSelectedEffectiveValue()));
203 if (result_cg->GetAlgoCompleted()) {
205 assert(best_weight == result_cg->GetWeight());
206 assert(best_amount == result_cg->GetSelectedEffectiveValue());
212 auto result_cg =
CoinGrinder(group_pos, target, coin_params.m_min_change_target, low_max_selection_weight);
231 coin_params.m_change_fee = coin_params.m_effective_feerate.GetFee(coin_params.change_output_size);
233 const auto change_spend_fee{coin_params.m_discard_feerate.GetFee(coin_params.change_spend_size)};
234 coin_params.m_cost_of_change = coin_params.m_change_fee + change_spend_fee;
235 CScript change_out_script =
CScript() << std::vector<unsigned char>(coin_params.change_output_size,
OP_TRUE);
237 coin_params.min_viable_change = std::max(change_spend_fee + 1, dust);
241 int next_locktime{0};
248 static constexpr unsigned max_output_groups{16};
249 std::vector<OutputGroup> group_pos;
253 const CAmount input_fee = coin_params.m_effective_feerate.GetFee(n_input_bytes);
256 const CAmount amount{eff_value + input_fee};
257 std::vector<COutput> temp_utxo_pool;
259 AddCoin(amount, 0, n_input_bytes, ++next_locktime, temp_utxo_pool, coin_params.m_effective_feerate);
260 max_spendable += eff_value;
263 output_group.Insert(std::make_shared<COutput>(temp_utxo_pool.at(0)), 0, 0);
264 group_pos.push_back(output_group);
273 std::vector<uint32_t> solutions;
274 CAmount best_waste{std::numeric_limits<int64_t>::max()};
275 int best_weight{std::numeric_limits<int>::max()};
276 for (uint32_t pattern = 1; (pattern >>
num_groups) == 0; ++pattern) {
279 bool is_superset =
false;
280 for (uint32_t sol : solutions) {
281 if ((pattern & sol) == sol) {
292 int subset_weight{0};
294 if ((pattern >> i) & 1) {
295 subset_amount += group_pos[i].GetSelectionAmount();
296 subset_waste += group_pos[i].fee - group_pos[i].long_term_fee;
297 subset_weight += group_pos[i].m_weight;
300 if (subset_amount >= target && subset_amount <= target + coin_params.m_cost_of_change) {
301 solutions.push_back(pattern);
303 CAmount excess = subset_amount - target;
304 subset_waste += excess;
308 if ((pattern >> i) & 1) {
312 if (subset_waste < best_waste) {
313 best_waste = subset_waste;
314 result_bf.
RecalculateWaste(coin_params.min_viable_change, coin_params.m_cost_of_change, coin_params.m_change_fee);
316 best_weight = subset_weight;
322 auto result_bnb =
SelectCoinsBnB(group_pos, target, coin_params.m_cost_of_change, high_max_selection_weight);
324 if (!solutions.size() || !result_bnb) {
326 assert(!result_bnb == !solutions.size());
330 result_bnb->RecalculateWaste(coin_params.min_viable_change, coin_params.m_cost_of_change, coin_params.m_change_fee);
331 assert(result_bnb->GetWeight() <= high_max_selection_weight);
332 assert(result_bnb->GetSelectedEffectiveValue() >= target);
333 assert(result_bnb->GetSelectedEffectiveValue() <= target + coin_params.m_cost_of_change);
334 assert(best_waste <= result_bnb->GetWaste());
335 if (result_bnb->GetAlgoCompleted()) {
337 assert(best_waste == result_bnb->GetWaste());
348template<CoinSelectionAlgorithm Algorithm>
352 std::vector<COutput> utxo_pool;
364 coin_params.m_long_term_feerate = long_term_fee_rate;
365 coin_params.m_effective_feerate = effective_fee_rate;
367 coin_params.m_change_fee = effective_fee_rate.GetFee(coin_params.change_output_size);
368 coin_params.m_discard_feerate = discard_fee_rate;
370 const auto change_spend_fee{coin_params.m_discard_feerate.GetFee(coin_params.change_spend_size)};
371 coin_params.m_cost_of_change = coin_params.m_change_fee + change_spend_fee;
372 CScript change_out_script =
CScript() << std::vector<unsigned char>(coin_params.change_output_size,
OP_TRUE);
374 coin_params.min_viable_change = std::max(change_spend_fee + 1, dust);
376 int next_locktime{0};
379 std::vector<OutputGroup> group_pos;
384 std::optional<SelectionResult> result;
387 if (!coin_params.m_subtract_fee_outputs) {
388 auto result_bnb =
SelectCoinsBnB(group_pos, target, coin_params.m_cost_of_change, max_selection_weight);
390 result = *result_bnb;
391 assert(result_bnb->GetChange(coin_params.min_viable_change, coin_params.m_change_fee) == 0);
392 assert(result_bnb->GetSelectedValue() >= target);
393 assert(result_bnb->GetWeight() <= max_selection_weight);
394 (void)result_bnb->GetShuffledInputVector();
395 (void)result_bnb->GetInputSet();
401 auto result_srd =
SelectCoinsSRD(group_pos, target, coin_params.m_change_fee, fast_random_context, max_selection_weight);
403 result = *result_srd;
404 assert(result_srd->GetSelectedValue() >= target);
406 assert(result_srd->GetWeight() <= max_selection_weight);
408 result_srd->RecalculateWaste(coin_params.min_viable_change, coin_params.m_cost_of_change, coin_params.m_change_fee);
409 (void)result_srd->GetShuffledInputVector();
410 (void)result_srd->GetInputSet();
415 std::vector<OutputGroup> group_all;
420 (void)
group.EligibleForSpending(filter);
424 auto result_knapsack =
KnapsackSolver(group_all, target, change_target, fast_random_context, max_selection_weight);
427 if (total_balance >= target && subtract_fee_outputs && !
HasErrorMsg(result_knapsack)) {
430 if (result_knapsack) {
431 result = *result_knapsack;
432 assert(result_knapsack->GetSelectedValue() >= target);
433 assert(result_knapsack->GetWeight() <= max_selection_weight);
435 result_knapsack->RecalculateWaste(coin_params.min_viable_change, coin_params.m_cost_of_change, coin_params.m_change_fee);
436 (void)result_knapsack->GetShuffledInputVector();
437 (void)result_knapsack->GetInputSet();
441 std::vector<COutput> utxos;
443 if (new_total_balance > 0) {
445 for (
const auto& utxo : utxos) {
446 new_utxo_pool.insert(std::make_shared<COutput>(utxo));
449 const auto weight{result->GetWeight()};
450 result->AddInputs(new_utxo_pool, subtract_fee_outputs);
451 assert(result->GetWeight() > weight);
455 std::vector<COutput> manual_inputs;
457 if (manual_balance == 0)
return;
458 auto manual_selection{
ManualSelection(manual_inputs, manual_balance, coin_params.m_subtract_fee_outputs)};
461 const OutputSet input_set{result->GetInputSet()};
462 const int old_weight{result->GetWeight()};
463 result->Merge(manual_selection);
464 assert(result->GetInputSet().size() == input_set.size() + manual_inputs.size());
465 assert(result->GetTarget() == old_target + manual_selection.GetTarget());
466 assert(result->GetWeight() == old_weight + manual_selection.GetWeight());
471 FuzzCoinSelectionAlgorithm<CoinSelectionAlgorithm::BNB>(buffer);
475 FuzzCoinSelectionAlgorithm<CoinSelectionAlgorithm::SRD>(buffer);
479 FuzzCoinSelectionAlgorithm<CoinSelectionAlgorithm::KNAPSACK>(buffer);
static constexpr CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
int64_t CAmount
Amount in satoshis (Can be negative)
static constexpr CAmount COIN
The amount of satoshis in one BTC.
Fee rate in satoshis per virtualbyte: CAmount / vB the feerate is represented internally as FeeFrac.
An outpoint - a combination of a transaction hash and an index n into its vout.
Serialized script, used inside transaction inputs and outputs.
An output of a transaction.
T ConsumeIntegralInRange(T min, T max)
LIMITED_WHILE(provider.remaining_bytes(), 10000)
bilingual_str ErrorString(const Result< T > &result)
static CAmount CreateCoins(FuzzedDataProvider &fuzzed_data_provider, std::vector< COutput > &utxo_pool, CoinSelectionParams &coin_params, int &next_locktime)
static void AddCoin(const CAmount &value, int n_input, int n_input_bytes, int locktime, std::vector< COutput > &coins, CFeeRate fee_rate)
static constexpr CAmount CHANGE_LOWER
lower bound for randomly-chosen target change amount
util::Result< SelectionResult > SelectCoinsBnB(std::vector< OutputGroup > &utxo_pool, const CAmount &selection_target, const CAmount &cost_of_change, int max_selection_weight)
util::Result< SelectionResult > CoinGrinder(std::vector< OutputGroup > &utxo_pool, const CAmount &selection_target, CAmount change_target, int max_selection_weight)
std::vector< OutputGroup > & GroupCoins(const std::vector< COutput > &available_coins, bool subtract_fee_outputs=false)
void FuzzCoinSelectionAlgorithm(std::span< const uint8_t > buffer)
std::set< std::shared_ptr< COutput >, OutputPtrComparator > OutputSet
util::Result< SelectionResult > KnapsackSolver(std::vector< OutputGroup > &groups, const CAmount &nTargetValue, CAmount change_target, FastRandomContext &rng, int max_selection_weight)
static SelectionResult ManualSelection(std::vector< COutput > &utxos, const CAmount &total_amount, const bool &subtract_fee_outputs)
FUZZ_TARGET(coin_grinder)
CAmount GenerateChangeTarget(const CAmount payment_value, const CAmount change_fee, FastRandomContext &rng)
Choose a random change target for each transaction to make it harder to fingerprint the Core wallet b...
static bool HasErrorMsg(const util::Result< SelectionResult > &res)
util::Result< SelectionResult > SelectCoinsSRD(const std::vector< OutputGroup > &utxo_pool, CAmount target_value, CAmount change_fee, FastRandomContext &rng, int max_selection_weight)
Select coins by Single Random Draw (SRD).
CAmount GetDustThreshold(const CTxOut &txout, const CFeeRate &dustRelayFeeIn)
static constexpr unsigned int DUST_RELAY_TX_FEE
Min feerate for defining dust.
static constexpr int32_t MAX_STANDARD_TX_WEIGHT
The maximum weight for transactions we're willing to relay/mine.
static const int MAX_SCRIPT_SIZE
A mutable version of CTransaction.
std::vector< CTxOut > vout
Txid GetHash() const
Compute the hash of this CMutableTransaction.
Parameters for filtering which OutputGroups we may use in coin selection.
Parameters for one iteration of Coin Selection.
bool m_subtract_fee_outputs
Indicate that we are subtracting the fee from outputs.
CFeeRate m_effective_feerate
The targeted feerate of the transaction being built.
A group of UTXOs paid to the same output script.
void AddInputs(const OutputSet &inputs, bool subtract_fee_outputs)
void RecalculateWaste(CAmount min_viable_change, CAmount change_cost, CAmount change_fee)
Calculates and stores the waste for this result given the cost of change and the opportunity cost of ...
void AddInput(const OutputGroup &group)
CAmount GetTarget() const
SeedRandomStateForTest(SeedRand::ZEROS)
CAmount ConsumeMoney(FuzzedDataProvider &fuzzed_data_provider, const std::optional< CAmount > &max) noexcept
uint256 ConsumeUInt256(FuzzedDataProvider &fuzzed_data_provider) noexcept
@ ZEROS
Seed with a compile time constant of zeros.
FuzzedDataProvider & fuzzed_data_provider