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;
41 if (valid_outputgroup && fuzzed_data_provider.
ConsumeBool()) {
42 output_groups.push_back(output_group);
44 valid_outputgroup =
false;
47 if (valid_outputgroup) output_groups.push_back(output_group);
58 if (total_balance + amount >=
MAX_MONEY) {
62 total_balance += amount;
72 for (
const auto& utxo : utxos) {
73 utxo_pool.insert(std::make_shared<COutput>(utxo));
75 result.
AddInputs(utxo_pool, subtract_fee_outputs);
85 std::vector<COutput> utxo_pool;
104 int next_locktime{0};
110 if (total_balance + amount >=
MAX_MONEY) {
114 total_balance += amount;
116 max_spendable += eff_value;
119 std::vector<OutputGroup> group_pos;
120 GroupCoins(fuzzed_data_provider, utxo_pool, coin_params,
true, group_pos);
126 if (!result_cg->GetAlgoCompleted())
return;
130 assert(result_srd->GetWeight() >= result_cg->GetWeight());
135 assert(result_knapsack->GetWeight() >= result_cg->GetWeight());
152 int next_locktime{0};
153 static constexpr unsigned max_output_groups{16};
154 std::vector<OutputGroup> group_pos;
163 const CAmount amount{eff_value + input_fee};
164 std::vector<COutput> temp_utxo_pool;
167 max_spendable += eff_value;
170 output_group.Insert(std::make_shared<COutput>(temp_utxo_pool.at(0)), 0, 0);
171 group_pos.push_back(output_group);
173 size_t num_groups = group_pos.size();
174 assert(num_groups <= max_output_groups);
181 int best_weight{std::numeric_limits<int>::max()};
182 for (uint32_t pattern = 1; (pattern >> num_groups) == 0; ++pattern) {
184 int subset_weight{0};
185 for (
unsigned i = 0; i < num_groups; ++i) {
186 if ((pattern >> i) & 1) {
187 subset_amount += group_pos[i].GetSelectionAmount();
188 subset_weight += group_pos[i].m_weight;
191 if ((subset_amount >= target + coin_params.
m_min_change_target) && (subset_weight < best_weight || (subset_weight == best_weight && subset_amount < best_amount))) {
192 best_weight = subset_weight;
193 best_amount = subset_amount;
197 if (best_weight < std::numeric_limits<int>::max()) {
199 int high_max_selection_weight = fuzzed_data_provider.
ConsumeIntegralInRange<
int>(best_weight, std::numeric_limits<int>::max());
203 assert(result_cg->GetWeight() <= high_max_selection_weight);
205 assert(best_weight < result_cg->GetWeight() || (best_weight == result_cg->GetWeight() && best_amount <= result_cg->GetSelectedEffectiveValue()));
206 if (result_cg->GetAlgoCompleted()) {
208 assert(best_weight == result_cg->GetWeight());
209 assert(best_amount == result_cg->GetSelectedEffectiveValue());
244 int next_locktime{0};
251 static constexpr unsigned max_output_groups{16};
252 std::vector<OutputGroup> group_pos;
260 const CAmount amount{eff_value + input_fee};
261 std::vector<COutput> temp_utxo_pool;
264 max_spendable += eff_value;
267 output_group.Insert(std::make_shared<COutput>(temp_utxo_pool.at(0)), 0, 0);
268 group_pos.push_back(output_group);
270 size_t num_groups = group_pos.size();
271 assert(num_groups <= max_output_groups);
277 std::vector<uint32_t> solutions;
278 CAmount best_waste{std::numeric_limits<int64_t>::max()};
279 int best_weight{std::numeric_limits<int>::max()};
280 for (uint32_t pattern = 1; (pattern >> num_groups) == 0; ++pattern) {
283 bool is_superset =
false;
284 for (uint32_t sol : solutions) {
285 if ((pattern & sol) == sol) {
296 int subset_weight{0};
297 for (
unsigned i = 0; i < num_groups; ++i) {
298 if ((pattern >> i) & 1) {
299 subset_amount += group_pos[i].GetSelectionAmount();
300 subset_waste += group_pos[i].fee - group_pos[i].long_term_fee;
301 subset_weight += group_pos[i].m_weight;
304 if (subset_amount >= target && subset_amount <= target + coin_params.
m_cost_of_change) {
305 solutions.push_back(pattern);
307 CAmount excess = subset_amount - target;
308 subset_waste += excess;
311 for (
unsigned i = 0; i < num_groups; ++i) {
312 if ((pattern >> i) & 1) {
316 if (subset_waste < best_waste) {
317 best_waste = subset_waste;
320 best_weight = subset_weight;
325 int high_max_selection_weight = fuzzed_data_provider.
ConsumeIntegralInRange<
int>(best_weight, std::numeric_limits<int>::max());
328 if (!solutions.size() || !result_bnb) {
330 assert(!result_bnb == !solutions.size());
335 assert(result_bnb->GetWeight() <= high_max_selection_weight);
336 assert(result_bnb->GetSelectedEffectiveValue() >= target);
338 assert(best_waste <= result_bnb->GetWaste());
339 if (result_bnb->GetAlgoCompleted()) {
341 assert(best_waste == result_bnb->GetWaste());
352template<CoinSelectionAlgorithm Algorithm>
356 std::vector<COutput> utxo_pool;
363 const bool subtract_fee_outputs{fuzzed_data_provider.
ConsumeBool()};
380 int next_locktime{0};
381 CAmount total_balance{
CreateCoins(fuzzed_data_provider, utxo_pool, coin_params, next_locktime)};
383 std::vector<OutputGroup> group_pos;
384 GroupCoins(fuzzed_data_provider, utxo_pool, coin_params,
true, group_pos);
386 int max_selection_weight = fuzzed_data_provider.
ConsumeIntegralInRange<
int>(0, std::numeric_limits<int>::max());
388 std::optional<SelectionResult> result;
394 result = *result_bnb;
396 assert(result_bnb->GetSelectedValue() >= target);
397 assert(result_bnb->GetWeight() <= max_selection_weight);
398 (void)result_bnb->GetShuffledInputVector();
399 (void)result_bnb->GetInputSet();
407 result = *result_srd;
408 assert(result_srd->GetSelectedValue() >= target);
410 assert(result_srd->GetWeight() <= max_selection_weight);
411 result_srd->SetBumpFeeDiscount(
ConsumeMoney(fuzzed_data_provider));
413 (void)result_srd->GetShuffledInputVector();
414 (void)result_srd->GetInputSet();
419 std::vector<OutputGroup> group_all;
420 GroupCoins(fuzzed_data_provider, utxo_pool, coin_params,
false, group_all);
424 (void)group.EligibleForSpending(filter);
428 auto result_knapsack =
KnapsackSolver(group_all, target, change_target, fast_random_context, max_selection_weight);
431 if (total_balance >= target && subtract_fee_outputs && !
HasErrorMsg(result_knapsack)) {
434 if (result_knapsack) {
435 result = *result_knapsack;
436 assert(result_knapsack->GetSelectedValue() >= target);
437 assert(result_knapsack->GetWeight() <= max_selection_weight);
438 result_knapsack->SetBumpFeeDiscount(
ConsumeMoney(fuzzed_data_provider));
440 (void)result_knapsack->GetShuffledInputVector();
441 (void)result_knapsack->GetInputSet();
445 std::vector<COutput> utxos;
446 CAmount new_total_balance{
CreateCoins(fuzzed_data_provider, utxos, coin_params, next_locktime)};
447 if (new_total_balance > 0) {
449 for (
const auto& utxo : utxos) {
450 new_utxo_pool.insert(std::make_shared<COutput>(utxo));
453 const auto weight{result->GetWeight()};
454 result->AddInputs(new_utxo_pool, subtract_fee_outputs);
455 assert(result->GetWeight() > weight);
459 std::vector<COutput> manual_inputs;
460 CAmount manual_balance{
CreateCoins(fuzzed_data_provider, manual_inputs, coin_params, next_locktime)};
461 if (manual_balance == 0)
return;
464 const CAmount old_target{result->GetTarget()};
465 const OutputSet input_set{result->GetInputSet()};
466 const int old_weight{result->GetWeight()};
467 result->Merge(manual_selection);
468 assert(result->GetInputSet().size() == input_set.size() + manual_inputs.size());
469 assert(result->GetTarget() == old_target + manual_selection.GetTarget());
470 assert(result->GetWeight() == old_weight + manual_selection.GetWeight());
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.
CAmount GetFee(int32_t virtual_bytes) const
Return the fee in satoshis for the given vsize in vbytes.
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)
#define LIMITED_WHILE(condition, limit)
Can be used to limit a theoretically unbounded loop.
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)
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)
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)
std::set< std::shared_ptr< COutput >, OutputPtrComparator > OutputSet
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.
CAmount m_min_change_target
Mininmum change to target in Knapsack solver and CoinGrinder: select coins to cover the payment and a...
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.
CAmount min_viable_change
Minimum amount for creating a change output.
int change_spend_size
Size of the input to spend a change output in virtual bytes.
CAmount m_cost_of_change
Cost of creating the change output + cost of spending the change output in the future.
CAmount m_change_fee
Cost of creating the change output.
int change_output_size
Size of a change output in bytes, determined by the output type.
CFeeRate m_long_term_feerate
The feerate estimate used to estimate an upper bound on what should be sufficient to spend the change...
CFeeRate m_discard_feerate
If the cost to spend a change output at the discard feerate exceeds its value, drop it to fees.
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 ConsumeMoney(FuzzedDataProvider &fuzzed_data_provider, const std::optional< CAmount > &max) noexcept
uint256 ConsumeUInt256(FuzzedDataProvider &fuzzed_data_provider) noexcept
void SeedRandomStateForTest(SeedRand seedtype)
Seed the global RNG state for testing and log the seed value.
@ ZEROS
Seed with a compile time constant of zeros.