19static void AddCoin(
const CAmount& value,
int n_input,
int n_input_bytes,
int locktime, std::vector<COutput>& coins,
CFeeRate fee_rate)
22 tx.
vout.resize(n_input + 1);
23 tx.
vout[n_input].nValue = value;
25 coins.emplace_back(
COutPoint(tx.
GetHash(), n_input), tx.
vout.at(n_input), 0, n_input_bytes,
true,
true,
true, 0,
true, fee_rate);
32 bool valid_outputgroup{
false};
33 for (
auto& coin : coins) {
34 if (!positive_only || (positive_only && coin.GetEffectiveValue() > 0)) {
35 output_group.Insert(std::make_shared<COutput>(coin), 0, 0);
39 valid_outputgroup = !positive_only || output_group.GetSelectionAmount() > 0;
40 if (valid_outputgroup && fuzzed_data_provider.
ConsumeBool()) {
41 output_groups.push_back(output_group);
43 valid_outputgroup =
false;
46 if (valid_outputgroup) output_groups.push_back(output_group);
57 if (total_balance + amount >=
MAX_MONEY) {
61 total_balance += amount;
70 std::set<std::shared_ptr<COutput>> utxo_pool;
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;
93 coin_params.change_output_size = fuzzed_data_provider.ConsumeIntegralInRange<
int>(10, 1000);
94 coin_params.change_spend_size = fuzzed_data_provider.ConsumeIntegralInRange<
int>(10, 1000);
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};
106 const int n_input{fuzzed_data_provider.ConsumeIntegralInRange<
int>(0, 10)};
107 const int n_input_bytes{fuzzed_data_provider.ConsumeIntegralInRange<
int>(41, 10000)};
109 if (total_balance + amount >=
MAX_MONEY) {
112 AddCoin(amount, n_input, n_input_bytes, ++next_locktime, utxo_pool, coin_params.m_effective_feerate);
113 total_balance += amount;
114 CAmount eff_value = amount - coin_params.m_effective_feerate.GetFee(n_input_bytes);
115 max_spendable += eff_value;
118 std::vector<OutputGroup> group_pos;
119 GroupCoins(fuzzed_data_provider, utxo_pool, coin_params,
true, group_pos);
123 if (target + coin_params.m_min_change_target > max_spendable ||
HasErrorMsg(result_cg))
return;
125 if (!result_cg->GetAlgoCompleted())
return;
128 if (result_srd && result_srd->GetChange(
CHANGE_LOWER, coin_params.m_change_fee) > 0) {
129 assert(result_srd->GetWeight() >= result_cg->GetWeight());
133 if (result_knapsack && result_knapsack->GetChange(
CHANGE_LOWER, coin_params.m_change_fee) > 0) {
134 assert(result_knapsack->GetWeight() >= result_cg->GetWeight());
147 coin_params.m_min_change_target =
ConsumeMoney(fuzzed_data_provider);
151 int next_locktime{0};
152 static constexpr unsigned max_output_groups{16};
153 std::vector<OutputGroup> group_pos;
154 LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), max_output_groups)
157 const int n_input_bytes{fuzzed_data_provider.ConsumeIntegralInRange<
int>(1, 1'000'000)};
159 const CAmount input_fee = coin_params.m_effective_feerate.GetFee(n_input_bytes);
161 const CAmount eff_value{fuzzed_data_provider.ConsumeIntegralInRange<
CAmount>(1,
MAX_MONEY + group_pos.size() - max_spendable - max_output_groups)};
162 const CAmount amount{eff_value + input_fee};
163 std::vector<COutput> temp_utxo_pool;
165 AddCoin(amount, 0, n_input_bytes, ++next_locktime, temp_utxo_pool, coin_params.m_effective_feerate);
166 max_spendable += eff_value;
169 output_group.Insert(std::make_shared<COutput>(temp_utxo_pool.at(0)), 0, 0);
170 group_pos.push_back(output_group);
176 const CAmount target{fuzzed_data_provider.ConsumeIntegralInRange<
CAmount>(1, std::max(
CAmount{1}, max_spendable - coin_params.m_min_change_target))};
180 int best_weight{std::numeric_limits<int>::max()};
181 for (uint32_t pattern = 1; (pattern >>
num_groups) == 0; ++pattern) {
183 int subset_weight{0};
185 if ((pattern >> i) & 1) {
186 subset_amount += group_pos[i].GetSelectionAmount();
187 subset_weight += group_pos[i].m_weight;
190 if ((subset_amount >= target + coin_params.m_min_change_target) && (subset_weight < best_weight || (subset_weight == best_weight && subset_amount < best_amount))) {
191 best_weight = subset_weight;
192 best_amount = subset_amount;
196 if (best_weight < std::numeric_limits<int>::max()) {
198 int high_max_selection_weight = fuzzed_data_provider.ConsumeIntegralInRange<
int>(best_weight, std::numeric_limits<int>::max());
200 auto result_cg =
CoinGrinder(group_pos, target, coin_params.m_min_change_target, high_max_selection_weight);
202 assert(result_cg->GetWeight() <= high_max_selection_weight);
203 assert(result_cg->GetSelectedEffectiveValue() >= target + coin_params.m_min_change_target);
204 assert(best_weight < result_cg->GetWeight() || (best_weight == result_cg->GetWeight() && best_amount <= result_cg->GetSelectedEffectiveValue()));
205 if (result_cg->GetAlgoCompleted()) {
207 assert(best_weight == result_cg->GetWeight());
208 assert(best_amount == result_cg->GetSelectedEffectiveValue());
213 int low_max_selection_weight = fuzzed_data_provider.ConsumeIntegralInRange<
int>(0, best_weight - 1);
214 auto result_cg =
CoinGrinder(group_pos, target, coin_params.m_min_change_target, low_max_selection_weight);
223 std::vector<COutput> utxo_pool;
230 const bool subtract_fee_outputs{fuzzed_data_provider.ConsumeBool()};
235 coin_params.m_long_term_feerate = long_term_fee_rate;
236 coin_params.m_effective_feerate = effective_fee_rate;
237 coin_params.change_output_size = fuzzed_data_provider.ConsumeIntegralInRange(1,
MAX_SCRIPT_SIZE);
238 coin_params.m_change_fee = effective_fee_rate.GetFee(coin_params.change_output_size);
239 coin_params.m_discard_feerate = discard_fee_rate;
240 coin_params.change_spend_size = fuzzed_data_provider.ConsumeIntegralInRange<
int>(41, 1000);
241 const auto change_spend_fee{coin_params.m_discard_feerate.GetFee(coin_params.change_spend_size)};
242 coin_params.m_cost_of_change = coin_params.m_change_fee + change_spend_fee;
243 CScript change_out_script =
CScript() << std::vector<unsigned char>(coin_params.change_output_size,
OP_TRUE);
245 coin_params.min_viable_change = std::max(change_spend_fee + 1, dust);
247 int next_locktime{0};
248 CAmount total_balance{
CreateCoins(fuzzed_data_provider, utxo_pool, coin_params, next_locktime)};
250 std::vector<OutputGroup> group_pos;
251 GroupCoins(fuzzed_data_provider, utxo_pool, coin_params,
true, group_pos);
252 std::vector<OutputGroup> group_all;
253 GroupCoins(fuzzed_data_provider, utxo_pool, coin_params,
false, group_all);
256 const CoinEligibilityFilter filter{fuzzed_data_provider.ConsumeIntegral<
int>(), fuzzed_data_provider.ConsumeIntegral<
int>(), fuzzed_data_provider.ConsumeIntegral<uint64_t>()};
257 (void)
group.EligibleForSpending(filter);
260 int max_selection_weight = fuzzed_data_provider.ConsumeIntegralInRange<
int>(0, std::numeric_limits<int>::max());
263 auto result_bnb = coin_params.m_subtract_fee_outputs ?
util::Error{
Untranslated(
"BnB disabled when SFFO is enabled")} :
264 SelectCoinsBnB(group_pos, target, coin_params.m_cost_of_change, max_selection_weight);
266 assert(result_bnb->GetChange(coin_params.min_viable_change, coin_params.m_change_fee) == 0);
267 assert(result_bnb->GetSelectedValue() >= target);
268 assert(result_bnb->GetWeight() <= max_selection_weight);
269 (void)result_bnb->GetShuffledInputVector();
270 (void)result_bnb->GetInputSet();
273 auto result_srd =
SelectCoinsSRD(group_pos, target, coin_params.m_change_fee, fast_random_context, max_selection_weight);
275 assert(result_srd->GetSelectedValue() >= target);
277 assert(result_srd->GetWeight() <= max_selection_weight);
278 result_srd->RecalculateWaste(coin_params.min_viable_change, coin_params.m_cost_of_change, coin_params.m_change_fee);
279 (void)result_srd->GetShuffledInputVector();
280 (void)result_srd->GetInputSet();
284 auto result_knapsack =
KnapsackSolver(group_all, target, change_target, fast_random_context, max_selection_weight);
285 if (result_knapsack) {
286 assert(result_knapsack->GetSelectedValue() >= target);
287 assert(result_knapsack->GetWeight() <= max_selection_weight);
288 result_knapsack->RecalculateWaste(coin_params.min_viable_change, coin_params.m_cost_of_change, coin_params.m_change_fee);
289 (void)result_knapsack->GetShuffledInputVector();
290 (void)result_knapsack->GetInputSet();
295 if (total_balance >= target && subtract_fee_outputs && !
HasErrorMsg(result_knapsack)) {
299 std::vector<COutput> utxos;
300 std::vector<util::Result<SelectionResult>> results;
301 results.emplace_back(std::move(result_srd));
302 results.emplace_back(std::move(result_knapsack));
303 results.emplace_back(std::move(result_bnb));
304 CAmount new_total_balance{
CreateCoins(fuzzed_data_provider, utxos, coin_params, next_locktime)};
305 if (new_total_balance > 0) {
306 std::set<std::shared_ptr<COutput>> new_utxo_pool;
307 for (
const auto& utxo : utxos) {
308 new_utxo_pool.insert(std::make_shared<COutput>(utxo));
310 for (
auto& result : results) {
311 if (!result)
continue;
312 const auto weight{result->GetWeight()};
313 result->AddInputs(new_utxo_pool, subtract_fee_outputs);
314 assert(result->GetWeight() > weight);
318 std::vector<COutput> manual_inputs;
319 CAmount manual_balance{
CreateCoins(fuzzed_data_provider, manual_inputs, coin_params, next_locktime)};
320 if (manual_balance == 0)
return;
321 auto manual_selection{
ManualSelection(manual_inputs, manual_balance, coin_params.m_subtract_fee_outputs)};
322 for (
auto& result : results) {
323 if (!result)
continue;
325 const std::set<std::shared_ptr<COutput>> input_set{result->GetInputSet()};
326 const int old_weight{result->GetWeight()};
327 result->Merge(manual_selection);
328 assert(result->GetInputSet().size() == input_set.size() + manual_inputs.size());
329 assert(result->GetTarget() == old_target + manual_selection.GetTarget());
330 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 kilovirtualbyte: CAmount / kvB.
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)
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...
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)
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)
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.
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.
CAmount GetTarget() const
void AddInputs(const std::set< std::shared_ptr< COutput > > &inputs, bool subtract_fee_outputs)
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.
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.