Bitcoin Core  24.1.0
P2P Digital Currency
coinselector_tests.cpp
Go to the documentation of this file.
1 // Copyright (c) 2017-2021 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #include <consensus/amount.h>
6 #include <node/context.h>
8 #include <random.h>
10 #include <util/translation.h>
11 #include <wallet/coincontrol.h>
12 #include <wallet/coinselection.h>
13 #include <wallet/spend.h>
15 #include <wallet/wallet.h>
16 
17 #include <algorithm>
18 #include <boost/test/unit_test.hpp>
19 #include <random>
20 
21 namespace wallet {
22 BOOST_FIXTURE_TEST_SUITE(coinselector_tests, WalletTestingSetup)
23 
24 // how many times to run all the tests to have a chance to catch errors that only show up with particular random shuffles
25 #define RUN_TESTS 100
26 
27 // some tests fail 1% of the time due to bad luck.
28 // we repeat those tests this many times and only complain if all iterations of the test fail
29 #define RANDOM_REPEATS 5
30 
31 typedef std::set<COutput> CoinSet;
32 
33 static const CoinEligibilityFilter filter_standard(1, 6, 0);
34 static const CoinEligibilityFilter filter_confirmed(1, 1, 0);
35 static const CoinEligibilityFilter filter_standard_extra(6, 6, 0);
36 static int nextLockTime = 0;
37 
38 static void add_coin(const CAmount& nValue, int nInput, std::vector<COutput>& set)
39 {
41  tx.vout.resize(nInput + 1);
42  tx.vout[nInput].nValue = nValue;
43  tx.nLockTime = nextLockTime++; // so all transactions get different hashes
44  set.emplace_back(COutPoint(tx.GetHash(), nInput), tx.vout.at(nInput), /*depth=*/ 1, /*input_bytes=*/ -1, /*spendable=*/ true, /*solvable=*/ true, /*safe=*/ true, /*time=*/ 0, /*from_me=*/ false, /*fees=*/ 0);
45 }
46 
47 static void add_coin(const CAmount& nValue, int nInput, SelectionResult& result)
48 {
50  tx.vout.resize(nInput + 1);
51  tx.vout[nInput].nValue = nValue;
52  tx.nLockTime = nextLockTime++; // so all transactions get different hashes
53  COutput output(COutPoint(tx.GetHash(), nInput), tx.vout.at(nInput), /*depth=*/ 1, /*input_bytes=*/ -1, /*spendable=*/ true, /*solvable=*/ true, /*safe=*/ true, /*time=*/ 0, /*from_me=*/ false, /*fees=*/ 0);
54  OutputGroup group;
55  group.Insert(output, /*ancestors=*/ 0, /*descendants=*/ 0, /*positive_only=*/ true);
56  result.AddInput(group);
57 }
58 
59 static void add_coin(const CAmount& nValue, int nInput, CoinSet& set, CAmount fee = 0, CAmount long_term_fee = 0)
60 {
62  tx.vout.resize(nInput + 1);
63  tx.vout[nInput].nValue = nValue;
64  tx.nLockTime = nextLockTime++; // so all transactions get different hashes
65  COutput coin(COutPoint(tx.GetHash(), nInput), tx.vout.at(nInput), /*depth=*/ 1, /*input_bytes=*/ 148, /*spendable=*/ true, /*solvable=*/ true, /*safe=*/ true, /*time=*/ 0, /*from_me=*/ false, fee);
66  coin.long_term_fee = long_term_fee;
67  set.insert(coin);
68 }
69 
70 static void add_coin(CoinsResult& available_coins, CWallet& wallet, const CAmount& nValue, CFeeRate feerate = CFeeRate(0), int nAge = 6*24, bool fIsFromMe = false, int nInput =0, bool spendable = false)
71 {
73  tx.nLockTime = nextLockTime++; // so all transactions get different hashes
74  tx.vout.resize(nInput + 1);
75  tx.vout[nInput].nValue = nValue;
76  if (spendable) {
77  tx.vout[nInput].scriptPubKey = GetScriptForDestination(*Assert(wallet.GetNewDestination(OutputType::BECH32, "")));
78  }
79  uint256 txid = tx.GetHash();
80 
81  LOCK(wallet.cs_wallet);
82  auto ret = wallet.mapWallet.emplace(std::piecewise_construct, std::forward_as_tuple(txid), std::forward_as_tuple(MakeTransactionRef(std::move(tx)), TxStateInactive{}));
83  assert(ret.second);
84  CWalletTx& wtx = (*ret.first).second;
85  const auto& txout = wtx.tx->vout.at(nInput);
86  available_coins.coins[OutputType::BECH32].emplace_back(COutPoint(wtx.GetHash(), nInput), txout, nAge, CalculateMaximumSignedInputSize(txout, &wallet, /*coin_control=*/nullptr), /*spendable=*/ true, /*solvable=*/ true, /*safe=*/ true, wtx.GetTxTime(), fIsFromMe, feerate);
87 }
88 
91 static bool EquivalentResult(const SelectionResult& a, const SelectionResult& b)
92 {
93  std::vector<CAmount> a_amts;
94  std::vector<CAmount> b_amts;
95  for (const auto& coin : a.GetInputSet()) {
96  a_amts.push_back(coin.txout.nValue);
97  }
98  for (const auto& coin : b.GetInputSet()) {
99  b_amts.push_back(coin.txout.nValue);
100  }
101  std::sort(a_amts.begin(), a_amts.end());
102  std::sort(b_amts.begin(), b_amts.end());
103 
104  std::pair<std::vector<CAmount>::iterator, std::vector<CAmount>::iterator> ret = std::mismatch(a_amts.begin(), a_amts.end(), b_amts.begin());
105  return ret.first == a_amts.end() && ret.second == b_amts.end();
106 }
107 
109 static bool EqualResult(const SelectionResult& a, const SelectionResult& b)
110 {
111  std::pair<CoinSet::iterator, CoinSet::iterator> ret = std::mismatch(a.GetInputSet().begin(), a.GetInputSet().end(), b.GetInputSet().begin(),
112  [](const COutput& a, const COutput& b) {
113  return a.outpoint == b.outpoint;
114  });
115  return ret.first == a.GetInputSet().end() && ret.second == b.GetInputSet().end();
116 }
117 
118 static CAmount make_hard_case(int utxos, std::vector<COutput>& utxo_pool)
119 {
120  utxo_pool.clear();
121  CAmount target = 0;
122  for (int i = 0; i < utxos; ++i) {
123  target += (CAmount)1 << (utxos+i);
124  add_coin((CAmount)1 << (utxos+i), 2*i, utxo_pool);
125  add_coin(((CAmount)1 << (utxos+i)) + ((CAmount)1 << (utxos-1-i)), 2*i + 1, utxo_pool);
126  }
127  return target;
128 }
129 
130 inline std::vector<OutputGroup>& GroupCoins(const std::vector<COutput>& available_coins)
131 {
132  static std::vector<OutputGroup> static_groups;
133  static_groups.clear();
134  for (auto& coin : available_coins) {
135  static_groups.emplace_back();
136  static_groups.back().Insert(coin, /*ancestors=*/ 0, /*descendants=*/ 0, /*positive_only=*/ false);
137  }
138  return static_groups;
139 }
140 
141 inline std::vector<OutputGroup>& KnapsackGroupOutputs(const std::vector<COutput>& available_coins, CWallet& wallet, const CoinEligibilityFilter& filter)
142 {
143  FastRandomContext rand{};
144  CoinSelectionParams coin_selection_params{
145  rand,
146  /*change_output_size=*/ 0,
147  /*change_spend_size=*/ 0,
148  /*min_change_target=*/ CENT,
149  /*effective_feerate=*/ CFeeRate(0),
150  /*long_term_feerate=*/ CFeeRate(0),
151  /*discard_feerate=*/ CFeeRate(0),
152  /*tx_noinputs_size=*/ 0,
153  /*avoid_partial=*/ false,
154  };
155  static std::vector<OutputGroup> static_groups;
156  static_groups = GroupOutputs(wallet, available_coins, coin_selection_params, filter, /*positive_only=*/false);
157  return static_groups;
158 }
159 
160 // Branch and bound coin selection tests
161 BOOST_AUTO_TEST_CASE(bnb_search_test)
162 {
163  FastRandomContext rand{};
164  // Setup
165  std::vector<COutput> utxo_pool;
166  SelectionResult expected_result(CAmount(0), SelectionAlgorithm::BNB);
167 
169  // Known Outcome tests //
171 
172  // Empty utxo pool
173  BOOST_CHECK(!SelectCoinsBnB(GroupCoins(utxo_pool), 1 * CENT, 0.5 * CENT));
174 
175  // Add utxos
176  add_coin(1 * CENT, 1, utxo_pool);
177  add_coin(2 * CENT, 2, utxo_pool);
178  add_coin(3 * CENT, 3, utxo_pool);
179  add_coin(4 * CENT, 4, utxo_pool);
180 
181  // Select 1 Cent
182  add_coin(1 * CENT, 1, expected_result);
183  const auto result1 = SelectCoinsBnB(GroupCoins(utxo_pool), 1 * CENT, 0.5 * CENT);
184  BOOST_CHECK(result1);
185  BOOST_CHECK(EquivalentResult(expected_result, *result1));
186  BOOST_CHECK_EQUAL(result1->GetSelectedValue(), 1 * CENT);
187  expected_result.Clear();
188 
189  // Select 2 Cent
190  add_coin(2 * CENT, 2, expected_result);
191  const auto result2 = SelectCoinsBnB(GroupCoins(utxo_pool), 2 * CENT, 0.5 * CENT);
192  BOOST_CHECK(result2);
193  BOOST_CHECK(EquivalentResult(expected_result, *result2));
194  BOOST_CHECK_EQUAL(result2->GetSelectedValue(), 2 * CENT);
195  expected_result.Clear();
196 
197  // Select 5 Cent
198  add_coin(3 * CENT, 3, expected_result);
199  add_coin(2 * CENT, 2, expected_result);
200  const auto result3 = SelectCoinsBnB(GroupCoins(utxo_pool), 5 * CENT, 0.5 * CENT);
201  BOOST_CHECK(result3);
202  BOOST_CHECK(EquivalentResult(expected_result, *result3));
203  BOOST_CHECK_EQUAL(result3->GetSelectedValue(), 5 * CENT);
204  expected_result.Clear();
205 
206  // Select 11 Cent, not possible
207  BOOST_CHECK(!SelectCoinsBnB(GroupCoins(utxo_pool), 11 * CENT, 0.5 * CENT));
208  expected_result.Clear();
209 
210  // Cost of change is greater than the difference between target value and utxo sum
211  add_coin(1 * CENT, 1, expected_result);
212  const auto result4 = SelectCoinsBnB(GroupCoins(utxo_pool), 0.9 * CENT, 0.5 * CENT);
213  BOOST_CHECK(result4);
214  BOOST_CHECK_EQUAL(result4->GetSelectedValue(), 1 * CENT);
215  BOOST_CHECK(EquivalentResult(expected_result, *result4));
216  expected_result.Clear();
217 
218  // Cost of change is less than the difference between target value and utxo sum
219  BOOST_CHECK(!SelectCoinsBnB(GroupCoins(utxo_pool), 0.9 * CENT, 0));
220  expected_result.Clear();
221 
222  // Select 10 Cent
223  add_coin(5 * CENT, 5, utxo_pool);
224  add_coin(4 * CENT, 4, expected_result);
225  add_coin(3 * CENT, 3, expected_result);
226  add_coin(2 * CENT, 2, expected_result);
227  add_coin(1 * CENT, 1, expected_result);
228  const auto result5 = SelectCoinsBnB(GroupCoins(utxo_pool), 10 * CENT, 0.5 * CENT);
229  BOOST_CHECK(result5);
230  BOOST_CHECK(EquivalentResult(expected_result, *result5));
231  BOOST_CHECK_EQUAL(result5->GetSelectedValue(), 10 * CENT);
232  expected_result.Clear();
233 
234  // Negative effective value
235  // Select 10 Cent but have 1 Cent not be possible because too small
236  add_coin(5 * CENT, 5, expected_result);
237  add_coin(3 * CENT, 3, expected_result);
238  add_coin(2 * CENT, 2, expected_result);
239  const auto result6 = SelectCoinsBnB(GroupCoins(utxo_pool), 10 * CENT, 5000);
240  BOOST_CHECK(result6);
241  BOOST_CHECK_EQUAL(result6->GetSelectedValue(), 10 * CENT);
242  // FIXME: this test is redundant with the above, because 1 Cent is selected, not "too small"
243  // BOOST_CHECK(EquivalentResult(expected_result, *result));
244 
245  // Select 0.25 Cent, not possible
246  BOOST_CHECK(!SelectCoinsBnB(GroupCoins(utxo_pool), 0.25 * CENT, 0.5 * CENT));
247  expected_result.Clear();
248 
249  // Iteration exhaustion test
250  CAmount target = make_hard_case(17, utxo_pool);
251  BOOST_CHECK(!SelectCoinsBnB(GroupCoins(utxo_pool), target, 1)); // Should exhaust
252  target = make_hard_case(14, utxo_pool);
253  const auto result7 = SelectCoinsBnB(GroupCoins(utxo_pool), target, 1); // Should not exhaust
254  BOOST_CHECK(result7);
255 
256  // Test same value early bailout optimization
257  utxo_pool.clear();
258  add_coin(7 * CENT, 7, expected_result);
259  add_coin(7 * CENT, 7, expected_result);
260  add_coin(7 * CENT, 7, expected_result);
261  add_coin(7 * CENT, 7, expected_result);
262  add_coin(2 * CENT, 7, expected_result);
263  add_coin(7 * CENT, 7, utxo_pool);
264  add_coin(7 * CENT, 7, utxo_pool);
265  add_coin(7 * CENT, 7, utxo_pool);
266  add_coin(7 * CENT, 7, utxo_pool);
267  add_coin(2 * CENT, 7, utxo_pool);
268  for (int i = 0; i < 50000; ++i) {
269  add_coin(5 * CENT, 7, utxo_pool);
270  }
271  const auto result8 = SelectCoinsBnB(GroupCoins(utxo_pool), 30 * CENT, 5000);
272  BOOST_CHECK(result8);
273  BOOST_CHECK_EQUAL(result8->GetSelectedValue(), 30 * CENT);
274  BOOST_CHECK(EquivalentResult(expected_result, *result8));
275 
277  // Behavior tests //
279  // Select 1 Cent with pool of only greater than 5 Cent
280  utxo_pool.clear();
281  for (int i = 5; i <= 20; ++i) {
282  add_coin(i * CENT, i, utxo_pool);
283  }
284  // Run 100 times, to make sure it is never finding a solution
285  for (int i = 0; i < 100; ++i) {
286  BOOST_CHECK(!SelectCoinsBnB(GroupCoins(utxo_pool), 1 * CENT, 2 * CENT));
287  }
288 
289  // Make sure that effective value is working in AttemptSelection when BnB is used
290  CoinSelectionParams coin_selection_params_bnb{
291  rand,
292  /*change_output_size=*/ 31,
293  /*change_spend_size=*/ 68,
294  /*min_change_target=*/ 0,
295  /*effective_feerate=*/ CFeeRate(3000),
296  /*long_term_feerate=*/ CFeeRate(1000),
297  /*discard_feerate=*/ CFeeRate(1000),
298  /*tx_noinputs_size=*/ 0,
299  /*avoid_partial=*/ false,
300  };
301  coin_selection_params_bnb.m_change_fee = coin_selection_params_bnb.m_effective_feerate.GetFee(coin_selection_params_bnb.change_output_size);
302  coin_selection_params_bnb.m_cost_of_change = coin_selection_params_bnb.m_effective_feerate.GetFee(coin_selection_params_bnb.change_spend_size) + coin_selection_params_bnb.m_change_fee;
303  coin_selection_params_bnb.min_viable_change = coin_selection_params_bnb.m_effective_feerate.GetFee(coin_selection_params_bnb.change_spend_size);
304  {
305  std::unique_ptr<CWallet> wallet = std::make_unique<CWallet>(m_node.chain.get(), "", m_args, CreateMockWalletDatabase());
306  wallet->LoadWallet();
307  LOCK(wallet->cs_wallet);
308  wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
309  wallet->SetupDescriptorScriptPubKeyMans();
310 
311  CoinsResult available_coins;
312 
313  add_coin(available_coins, *wallet, 1, coin_selection_params_bnb.m_effective_feerate);
314  available_coins.All().at(0).input_bytes = 40; // Make sure that it has a negative effective value. The next check should assert if this somehow got through. Otherwise it will fail
315  BOOST_CHECK(!SelectCoinsBnB(GroupCoins(available_coins.All()), 1 * CENT, coin_selection_params_bnb.m_cost_of_change));
316 
317  // Test fees subtracted from output:
318  available_coins.Clear();
319  add_coin(available_coins, *wallet, 1 * CENT, coin_selection_params_bnb.m_effective_feerate);
320  available_coins.All().at(0).input_bytes = 40;
321  coin_selection_params_bnb.m_subtract_fee_outputs = true;
322  const auto result9 = SelectCoinsBnB(GroupCoins(available_coins.All()), 1 * CENT, coin_selection_params_bnb.m_cost_of_change);
323  BOOST_CHECK(result9);
324  BOOST_CHECK_EQUAL(result9->GetSelectedValue(), 1 * CENT);
325  }
326 
327  {
328  std::unique_ptr<CWallet> wallet = std::make_unique<CWallet>(m_node.chain.get(), "", m_args, CreateMockWalletDatabase());
329  wallet->LoadWallet();
330  LOCK(wallet->cs_wallet);
331  wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
332  wallet->SetupDescriptorScriptPubKeyMans();
333 
334  CoinsResult available_coins;
335 
336  add_coin(available_coins, *wallet, 5 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true);
337  add_coin(available_coins, *wallet, 3 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true);
338  add_coin(available_coins, *wallet, 2 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true);
339  CCoinControl coin_control;
340  coin_control.m_allow_other_inputs = true;
341  coin_control.Select(available_coins.All().at(0).outpoint);
342  coin_selection_params_bnb.m_effective_feerate = CFeeRate(0);
343  const auto result10 = SelectCoins(*wallet, available_coins, 10 * CENT, coin_control, coin_selection_params_bnb);
344  BOOST_CHECK(result10);
345  }
346  {
347  std::unique_ptr<CWallet> wallet = std::make_unique<CWallet>(m_node.chain.get(), "", m_args, CreateMockWalletDatabase());
348  wallet->LoadWallet();
349  LOCK(wallet->cs_wallet);
350  wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
351  wallet->SetupDescriptorScriptPubKeyMans();
352 
353  CoinsResult available_coins;
354 
355  // single coin should be selected when effective fee > long term fee
356  coin_selection_params_bnb.m_effective_feerate = CFeeRate(5000);
357  coin_selection_params_bnb.m_long_term_feerate = CFeeRate(3000);
358 
359  add_coin(available_coins, *wallet, 10 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true);
360  add_coin(available_coins, *wallet, 9 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true);
361  add_coin(available_coins, *wallet, 1 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true);
362 
363  expected_result.Clear();
364  add_coin(10 * CENT, 2, expected_result);
365  CCoinControl coin_control;
366  const auto result11 = SelectCoins(*wallet, available_coins, 10 * CENT, coin_control, coin_selection_params_bnb);
367  BOOST_CHECK(EquivalentResult(expected_result, *result11));
368  available_coins.Clear();
369 
370  // more coins should be selected when effective fee < long term fee
371  coin_selection_params_bnb.m_effective_feerate = CFeeRate(3000);
372  coin_selection_params_bnb.m_long_term_feerate = CFeeRate(5000);
373 
374  add_coin(available_coins, *wallet, 10 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true);
375  add_coin(available_coins, *wallet, 9 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true);
376  add_coin(available_coins, *wallet, 1 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true);
377 
378  expected_result.Clear();
379  add_coin(9 * CENT, 2, expected_result);
380  add_coin(1 * CENT, 2, expected_result);
381  const auto result12 = SelectCoins(*wallet, available_coins, 10 * CENT, coin_control, coin_selection_params_bnb);
382  BOOST_CHECK(EquivalentResult(expected_result, *result12));
383  available_coins.Clear();
384 
385  // pre selected coin should be selected even if disadvantageous
386  coin_selection_params_bnb.m_effective_feerate = CFeeRate(5000);
387  coin_selection_params_bnb.m_long_term_feerate = CFeeRate(3000);
388 
389  add_coin(available_coins, *wallet, 10 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true);
390  add_coin(available_coins, *wallet, 9 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true);
391  add_coin(available_coins, *wallet, 1 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true);
392 
393  expected_result.Clear();
394  add_coin(9 * CENT, 2, expected_result);
395  add_coin(1 * CENT, 2, expected_result);
396  coin_control.m_allow_other_inputs = true;
397  coin_control.Select(available_coins.All().at(1).outpoint); // pre select 9 coin
398  const auto result13 = SelectCoins(*wallet, available_coins, 10 * CENT, coin_control, coin_selection_params_bnb);
399  BOOST_CHECK(EquivalentResult(expected_result, *result13));
400  }
401 }
402 
403 BOOST_AUTO_TEST_CASE(knapsack_solver_test)
404 {
405  FastRandomContext rand{};
406  const auto temp1{[&rand](std::vector<OutputGroup>& g, const CAmount& v, CAmount c) { return KnapsackSolver(g, v, c, rand); }};
407  const auto KnapsackSolver{temp1};
408  std::unique_ptr<CWallet> wallet = std::make_unique<CWallet>(m_node.chain.get(), "", m_args, CreateMockWalletDatabase());
409  wallet->LoadWallet();
410  LOCK(wallet->cs_wallet);
411  wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
412  wallet->SetupDescriptorScriptPubKeyMans();
413 
414  CoinsResult available_coins;
415 
416  // test multiple times to allow for differences in the shuffle order
417  for (int i = 0; i < RUN_TESTS; i++)
418  {
419  available_coins.Clear();
420 
421  // with an empty wallet we can't even pay one cent
423 
424  add_coin(available_coins, *wallet, 1*CENT, CFeeRate(0), 4); // add a new 1 cent coin
425 
426  // with a new 1 cent coin, we still can't find a mature 1 cent
428 
429  // but we can find a new 1 cent
430  const auto result1 = KnapsackSolver(KnapsackGroupOutputs(available_coins.All(), *wallet, filter_confirmed), 1 * CENT, CENT);
431  BOOST_CHECK(result1);
432  BOOST_CHECK_EQUAL(result1->GetSelectedValue(), 1 * CENT);
433 
434  add_coin(available_coins, *wallet, 2*CENT); // add a mature 2 cent coin
435 
436  // we can't make 3 cents of mature coins
438 
439  // we can make 3 cents of new coins
440  const auto result2 = KnapsackSolver(KnapsackGroupOutputs(available_coins.All(), *wallet, filter_confirmed), 3 * CENT, CENT);
441  BOOST_CHECK(result2);
442  BOOST_CHECK_EQUAL(result2->GetSelectedValue(), 3 * CENT);
443 
444  add_coin(available_coins, *wallet, 5*CENT); // add a mature 5 cent coin,
445  add_coin(available_coins, *wallet, 10*CENT, CFeeRate(0), 3, true); // a new 10 cent coin sent from one of our own addresses
446  add_coin(available_coins, *wallet, 20*CENT); // and a mature 20 cent coin
447 
448  // now we have new: 1+10=11 (of which 10 was self-sent), and mature: 2+5+20=27. total = 38
449 
450  // we can't make 38 cents only if we disallow new coins:
452  // we can't even make 37 cents if we don't allow new coins even if they're from us
454  // but we can make 37 cents if we accept new coins from ourself
455  const auto result3 = KnapsackSolver(KnapsackGroupOutputs(available_coins.All(), *wallet, filter_standard), 37 * CENT, CENT);
456  BOOST_CHECK(result3);
457  BOOST_CHECK_EQUAL(result3->GetSelectedValue(), 37 * CENT);
458  // and we can make 38 cents if we accept all new coins
459  const auto result4 = KnapsackSolver(KnapsackGroupOutputs(available_coins.All(), *wallet, filter_confirmed), 38 * CENT, CENT);
460  BOOST_CHECK(result4);
461  BOOST_CHECK_EQUAL(result4->GetSelectedValue(), 38 * CENT);
462 
463  // try making 34 cents from 1,2,5,10,20 - we can't do it exactly
464  const auto result5 = KnapsackSolver(KnapsackGroupOutputs(available_coins.All(), *wallet, filter_confirmed), 34 * CENT, CENT);
465  BOOST_CHECK(result5);
466  BOOST_CHECK_EQUAL(result5->GetSelectedValue(), 35 * CENT); // but 35 cents is closest
467  BOOST_CHECK_EQUAL(result5->GetInputSet().size(), 3U); // the best should be 20+10+5. it's incredibly unlikely the 1 or 2 got included (but possible)
468 
469  // when we try making 7 cents, the smaller coins (1,2,5) are enough. We should see just 2+5
470  const auto result6 = KnapsackSolver(KnapsackGroupOutputs(available_coins.All(), *wallet, filter_confirmed), 7 * CENT, CENT);
471  BOOST_CHECK(result6);
472  BOOST_CHECK_EQUAL(result6->GetSelectedValue(), 7 * CENT);
473  BOOST_CHECK_EQUAL(result6->GetInputSet().size(), 2U);
474 
475  // when we try making 8 cents, the smaller coins (1,2,5) are exactly enough.
476  const auto result7 = KnapsackSolver(KnapsackGroupOutputs(available_coins.All(), *wallet, filter_confirmed), 8 * CENT, CENT);
477  BOOST_CHECK(result7);
478  BOOST_CHECK(result7->GetSelectedValue() == 8 * CENT);
479  BOOST_CHECK_EQUAL(result7->GetInputSet().size(), 3U);
480 
481  // when we try making 9 cents, no subset of smaller coins is enough, and we get the next bigger coin (10)
482  const auto result8 = KnapsackSolver(KnapsackGroupOutputs(available_coins.All(), *wallet, filter_confirmed), 9 * CENT, CENT);
483  BOOST_CHECK(result8);
484  BOOST_CHECK_EQUAL(result8->GetSelectedValue(), 10 * CENT);
485  BOOST_CHECK_EQUAL(result8->GetInputSet().size(), 1U);
486 
487  // now clear out the wallet and start again to test choosing between subsets of smaller coins and the next biggest coin
488  available_coins.Clear();
489 
490  add_coin(available_coins, *wallet, 6*CENT);
491  add_coin(available_coins, *wallet, 7*CENT);
492  add_coin(available_coins, *wallet, 8*CENT);
493  add_coin(available_coins, *wallet, 20*CENT);
494  add_coin(available_coins, *wallet, 30*CENT); // now we have 6+7+8+20+30 = 71 cents total
495 
496  // check that we have 71 and not 72
497  const auto result9 = KnapsackSolver(KnapsackGroupOutputs(available_coins.All(), *wallet, filter_confirmed), 71 * CENT, CENT);
498  BOOST_CHECK(result9);
500 
501  // now try making 16 cents. the best smaller coins can do is 6+7+8 = 21; not as good at the next biggest coin, 20
502  const auto result10 = KnapsackSolver(KnapsackGroupOutputs(available_coins.All(), *wallet, filter_confirmed), 16 * CENT, CENT);
503  BOOST_CHECK(result10);
504  BOOST_CHECK_EQUAL(result10->GetSelectedValue(), 20 * CENT); // we should get 20 in one coin
505  BOOST_CHECK_EQUAL(result10->GetInputSet().size(), 1U);
506 
507  add_coin(available_coins, *wallet, 5*CENT); // now we have 5+6+7+8+20+30 = 75 cents total
508 
509  // now if we try making 16 cents again, the smaller coins can make 5+6+7 = 18 cents, better than the next biggest coin, 20
510  const auto result11 = KnapsackSolver(KnapsackGroupOutputs(available_coins.All(), *wallet, filter_confirmed), 16 * CENT, CENT);
511  BOOST_CHECK(result11);
512  BOOST_CHECK_EQUAL(result11->GetSelectedValue(), 18 * CENT); // we should get 18 in 3 coins
513  BOOST_CHECK_EQUAL(result11->GetInputSet().size(), 3U);
514 
515  add_coin(available_coins, *wallet, 18*CENT); // now we have 5+6+7+8+18+20+30
516 
517  // and now if we try making 16 cents again, the smaller coins can make 5+6+7 = 18 cents, the same as the next biggest coin, 18
518  const auto result12 = KnapsackSolver(KnapsackGroupOutputs(available_coins.All(), *wallet, filter_confirmed), 16 * CENT, CENT);
519  BOOST_CHECK(result12);
520  BOOST_CHECK_EQUAL(result12->GetSelectedValue(), 18 * CENT); // we should get 18 in 1 coin
521  BOOST_CHECK_EQUAL(result12->GetInputSet().size(), 1U); // because in the event of a tie, the biggest coin wins
522 
523  // now try making 11 cents. we should get 5+6
524  const auto result13 = KnapsackSolver(KnapsackGroupOutputs(available_coins.All(), *wallet, filter_confirmed), 11 * CENT, CENT);
525  BOOST_CHECK(result13);
526  BOOST_CHECK_EQUAL(result13->GetSelectedValue(), 11 * CENT);
527  BOOST_CHECK_EQUAL(result13->GetInputSet().size(), 2U);
528 
529  // check that the smallest bigger coin is used
530  add_coin(available_coins, *wallet, 1*COIN);
531  add_coin(available_coins, *wallet, 2*COIN);
532  add_coin(available_coins, *wallet, 3*COIN);
533  add_coin(available_coins, *wallet, 4*COIN); // now we have 5+6+7+8+18+20+30+100+200+300+400 = 1094 cents
534  const auto result14 = KnapsackSolver(KnapsackGroupOutputs(available_coins.All(), *wallet, filter_confirmed), 95 * CENT, CENT);
535  BOOST_CHECK(result14);
536  BOOST_CHECK_EQUAL(result14->GetSelectedValue(), 1 * COIN); // we should get 1 BTC in 1 coin
537  BOOST_CHECK_EQUAL(result14->GetInputSet().size(), 1U);
538 
539  const auto result15 = KnapsackSolver(KnapsackGroupOutputs(available_coins.All(), *wallet, filter_confirmed), 195 * CENT, CENT);
540  BOOST_CHECK(result15);
541  BOOST_CHECK_EQUAL(result15->GetSelectedValue(), 2 * COIN); // we should get 2 BTC in 1 coin
542  BOOST_CHECK_EQUAL(result15->GetInputSet().size(), 1U);
543 
544  // empty the wallet and start again, now with fractions of a cent, to test small change avoidance
545 
546  available_coins.Clear();
547  add_coin(available_coins, *wallet, CENT * 1 / 10);
548  add_coin(available_coins, *wallet, CENT * 2 / 10);
549  add_coin(available_coins, *wallet, CENT * 3 / 10);
550  add_coin(available_coins, *wallet, CENT * 4 / 10);
551  add_coin(available_coins, *wallet, CENT * 5 / 10);
552 
553  // try making 1 * CENT from the 1.5 * CENT
554  // we'll get change smaller than CENT whatever happens, so can expect CENT exactly
555  const auto result16 = KnapsackSolver(KnapsackGroupOutputs(available_coins.All(), *wallet, filter_confirmed), CENT, CENT);
556  BOOST_CHECK(result16);
557  BOOST_CHECK_EQUAL(result16->GetSelectedValue(), CENT);
558 
559  // but if we add a bigger coin, small change is avoided
560  add_coin(available_coins, *wallet, 1111*CENT);
561 
562  // try making 1 from 0.1 + 0.2 + 0.3 + 0.4 + 0.5 + 1111 = 1112.5
563  const auto result17 = KnapsackSolver(KnapsackGroupOutputs(available_coins.All(), *wallet, filter_confirmed), 1 * CENT, CENT);
564  BOOST_CHECK(result17);
565  BOOST_CHECK_EQUAL(result17->GetSelectedValue(), 1 * CENT); // we should get the exact amount
566 
567  // if we add more small coins:
568  add_coin(available_coins, *wallet, CENT * 6 / 10);
569  add_coin(available_coins, *wallet, CENT * 7 / 10);
570 
571  // and try again to make 1.0 * CENT
572  const auto result18 = KnapsackSolver(KnapsackGroupOutputs(available_coins.All(), *wallet, filter_confirmed), 1 * CENT, CENT);
573  BOOST_CHECK(result18);
574  BOOST_CHECK_EQUAL(result18->GetSelectedValue(), 1 * CENT); // we should get the exact amount
575 
576  // run the 'mtgox' test (see https://blockexplorer.com/tx/29a3efd3ef04f9153d47a990bd7b048a4b2d213daaa5fb8ed670fb85f13bdbcf)
577  // they tried to consolidate 10 50k coins into one 500k coin, and ended up with 50k in change
578  available_coins.Clear();
579  for (int j = 0; j < 20; j++)
580  add_coin(available_coins, *wallet, 50000 * COIN);
581 
582  const auto result19 = KnapsackSolver(KnapsackGroupOutputs(available_coins.All(), *wallet, filter_confirmed), 500000 * COIN, CENT);
583  BOOST_CHECK(result19);
584  BOOST_CHECK_EQUAL(result19->GetSelectedValue(), 500000 * COIN); // we should get the exact amount
585  BOOST_CHECK_EQUAL(result19->GetInputSet().size(), 10U); // in ten coins
586 
587  // if there's not enough in the smaller coins to make at least 1 * CENT change (0.5+0.6+0.7 < 1.0+1.0),
588  // we need to try finding an exact subset anyway
589 
590  // sometimes it will fail, and so we use the next biggest coin:
591  available_coins.Clear();
592  add_coin(available_coins, *wallet, CENT * 5 / 10);
593  add_coin(available_coins, *wallet, CENT * 6 / 10);
594  add_coin(available_coins, *wallet, CENT * 7 / 10);
595  add_coin(available_coins, *wallet, 1111 * CENT);
596  const auto result20 = KnapsackSolver(KnapsackGroupOutputs(available_coins.All(), *wallet, filter_confirmed), 1 * CENT, CENT);
597  BOOST_CHECK(result20);
598  BOOST_CHECK_EQUAL(result20->GetSelectedValue(), 1111 * CENT); // we get the bigger coin
599  BOOST_CHECK_EQUAL(result20->GetInputSet().size(), 1U);
600 
601  // but sometimes it's possible, and we use an exact subset (0.4 + 0.6 = 1.0)
602  available_coins.Clear();
603  add_coin(available_coins, *wallet, CENT * 4 / 10);
604  add_coin(available_coins, *wallet, CENT * 6 / 10);
605  add_coin(available_coins, *wallet, CENT * 8 / 10);
606  add_coin(available_coins, *wallet, 1111 * CENT);
607  const auto result21 = KnapsackSolver(KnapsackGroupOutputs(available_coins.All(), *wallet, filter_confirmed), CENT, CENT);
608  BOOST_CHECK(result21);
609  BOOST_CHECK_EQUAL(result21->GetSelectedValue(), CENT); // we should get the exact amount
610  BOOST_CHECK_EQUAL(result21->GetInputSet().size(), 2U); // in two coins 0.4+0.6
611 
612  // test avoiding small change
613  available_coins.Clear();
614  add_coin(available_coins, *wallet, CENT * 5 / 100);
615  add_coin(available_coins, *wallet, CENT * 1);
616  add_coin(available_coins, *wallet, CENT * 100);
617 
618  // trying to make 100.01 from these three coins
619  const auto result22 = KnapsackSolver(KnapsackGroupOutputs(available_coins.All(), *wallet, filter_confirmed), CENT * 10001 / 100, CENT);
620  BOOST_CHECK(result22);
621  BOOST_CHECK_EQUAL(result22->GetSelectedValue(), CENT * 10105 / 100); // we should get all coins
622  BOOST_CHECK_EQUAL(result22->GetInputSet().size(), 3U);
623 
624  // but if we try to make 99.9, we should take the bigger of the two small coins to avoid small change
625  const auto result23 = KnapsackSolver(KnapsackGroupOutputs(available_coins.All(), *wallet, filter_confirmed), CENT * 9990 / 100, CENT);
626  BOOST_CHECK(result23);
627  BOOST_CHECK_EQUAL(result23->GetSelectedValue(), 101 * CENT);
628  BOOST_CHECK_EQUAL(result23->GetInputSet().size(), 2U);
629  }
630 
631  // test with many inputs
632  for (CAmount amt=1500; amt < COIN; amt*=10) {
633  available_coins.Clear();
634  // Create 676 inputs (= (old MAX_STANDARD_TX_SIZE == 100000) / 148 bytes per input)
635  for (uint16_t j = 0; j < 676; j++)
636  add_coin(available_coins, *wallet, amt);
637 
638  // We only create the wallet once to save time, but we still run the coin selection RUN_TESTS times.
639  for (int i = 0; i < RUN_TESTS; i++) {
640  const auto result24 = KnapsackSolver(KnapsackGroupOutputs(available_coins.All(), *wallet, filter_confirmed), 2000, CENT);
641  BOOST_CHECK(result24);
642 
643  if (amt - 2000 < CENT) {
644  // needs more than one input:
645  uint16_t returnSize = std::ceil((2000.0 + CENT)/amt);
646  CAmount returnValue = amt * returnSize;
647  BOOST_CHECK_EQUAL(result24->GetSelectedValue(), returnValue);
648  BOOST_CHECK_EQUAL(result24->GetInputSet().size(), returnSize);
649  } else {
650  // one input is sufficient:
651  BOOST_CHECK_EQUAL(result24->GetSelectedValue(), amt);
652  BOOST_CHECK_EQUAL(result24->GetInputSet().size(), 1U);
653  }
654  }
655  }
656 
657  // test randomness
658  {
659  available_coins.Clear();
660  for (int i2 = 0; i2 < 100; i2++)
661  add_coin(available_coins, *wallet, COIN);
662 
663  // Again, we only create the wallet once to save time, but we still run the coin selection RUN_TESTS times.
664  for (int i = 0; i < RUN_TESTS; i++) {
665  // picking 50 from 100 coins doesn't depend on the shuffle,
666  // but does depend on randomness in the stochastic approximation code
667  const auto result25 = KnapsackSolver(GroupCoins(available_coins.All()), 50 * COIN, CENT);
668  BOOST_CHECK(result25);
669  const auto result26 = KnapsackSolver(GroupCoins(available_coins.All()), 50 * COIN, CENT);
670  BOOST_CHECK(result26);
671  BOOST_CHECK(!EqualResult(*result25, *result26));
672 
673  int fails = 0;
674  for (int j = 0; j < RANDOM_REPEATS; j++)
675  {
676  // Test that the KnapsackSolver selects randomly from equivalent coins (same value and same input size).
677  // When choosing 1 from 100 identical coins, 1% of the time, this test will choose the same coin twice
678  // which will cause it to fail.
679  // To avoid that issue, run the test RANDOM_REPEATS times and only complain if all of them fail
680  const auto result27 = KnapsackSolver(GroupCoins(available_coins.All()), COIN, CENT);
681  BOOST_CHECK(result27);
682  const auto result28 = KnapsackSolver(GroupCoins(available_coins.All()), COIN, CENT);
683  BOOST_CHECK(result28);
684  if (EqualResult(*result27, *result28))
685  fails++;
686  }
687  BOOST_CHECK_NE(fails, RANDOM_REPEATS);
688  }
689 
690  // add 75 cents in small change. not enough to make 90 cents,
691  // then try making 90 cents. there are multiple competing "smallest bigger" coins,
692  // one of which should be picked at random
693  add_coin(available_coins, *wallet, 5 * CENT);
694  add_coin(available_coins, *wallet, 10 * CENT);
695  add_coin(available_coins, *wallet, 15 * CENT);
696  add_coin(available_coins, *wallet, 20 * CENT);
697  add_coin(available_coins, *wallet, 25 * CENT);
698 
699  for (int i = 0; i < RUN_TESTS; i++) {
700  int fails = 0;
701  for (int j = 0; j < RANDOM_REPEATS; j++)
702  {
703  const auto result29 = KnapsackSolver(GroupCoins(available_coins.All()), 90 * CENT, CENT);
704  BOOST_CHECK(result29);
705  const auto result30 = KnapsackSolver(GroupCoins(available_coins.All()), 90 * CENT, CENT);
706  BOOST_CHECK(result30);
707  if (EqualResult(*result29, *result30))
708  fails++;
709  }
710  BOOST_CHECK_NE(fails, RANDOM_REPEATS);
711  }
712  }
713 }
714 
716 {
717  FastRandomContext rand{};
718  std::unique_ptr<CWallet> wallet = std::make_unique<CWallet>(m_node.chain.get(), "", m_args, CreateMockWalletDatabase());
719  wallet->LoadWallet();
720  LOCK(wallet->cs_wallet);
721  wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
722  wallet->SetupDescriptorScriptPubKeyMans();
723 
724  CoinsResult available_coins;
725 
726  // Test vValue sort order
727  for (int i = 0; i < 1000; i++)
728  add_coin(available_coins, *wallet, 1000 * COIN);
729  add_coin(available_coins, *wallet, 3 * COIN);
730 
731  const auto result = KnapsackSolver(KnapsackGroupOutputs(available_coins.All(), *wallet, filter_standard), 1003 * COIN, CENT, rand);
732  BOOST_CHECK(result);
733  BOOST_CHECK_EQUAL(result->GetSelectedValue(), 1003 * COIN);
734  BOOST_CHECK_EQUAL(result->GetInputSet().size(), 2U);
735 }
736 
737 // Tests that with the ideal conditions, the coin selector will always be able to find a solution that can pay the target value
738 BOOST_AUTO_TEST_CASE(SelectCoins_test)
739 {
740  std::unique_ptr<CWallet> wallet = std::make_unique<CWallet>(m_node.chain.get(), "", m_args, CreateMockWalletDatabase());
741  wallet->LoadWallet();
742  LOCK(wallet->cs_wallet);
743  wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
744  wallet->SetupDescriptorScriptPubKeyMans();
745 
746  // Random generator stuff
747  std::default_random_engine generator;
748  std::exponential_distribution<double> distribution (100);
749  FastRandomContext rand;
750 
751  // Run this test 100 times
752  for (int i = 0; i < 100; ++i)
753  {
754  CoinsResult available_coins;
755  CAmount balance{0};
756 
757  // Make a wallet with 1000 exponentially distributed random inputs
758  for (int j = 0; j < 1000; ++j)
759  {
760  CAmount val = distribution(generator)*10000000;
761  add_coin(available_coins, *wallet, val);
762  balance += val;
763  }
764 
765  // Generate a random fee rate in the range of 100 - 400
766  CFeeRate rate(rand.randrange(300) + 100);
767 
768  // Generate a random target value between 1000 and wallet balance
769  CAmount target = rand.randrange(balance - 1000) + 1000;
770 
771  // Perform selection
772  CoinSelectionParams cs_params{
773  rand,
774  /*change_output_size=*/ 34,
775  /*change_spend_size=*/ 148,
776  /*min_change_target=*/ CENT,
777  /*effective_feerate=*/ CFeeRate(0),
778  /*long_term_feerate=*/ CFeeRate(0),
779  /*discard_feerate=*/ CFeeRate(0),
780  /*tx_noinputs_size=*/ 0,
781  /*avoid_partial=*/ false,
782  };
783  cs_params.m_cost_of_change = 1;
784  cs_params.min_viable_change = 1;
785  CCoinControl cc;
786  const auto result = SelectCoins(*wallet, available_coins, target, cc, cs_params);
787  BOOST_CHECK(result);
788  BOOST_CHECK_GE(result->GetSelectedValue(), target);
789  }
790 }
791 
793 {
794  CoinSet selection;
795  const CAmount fee{100};
796  const CAmount change_cost{125};
797  const CAmount fee_diff{40};
798  const CAmount in_amt{3 * COIN};
799  const CAmount target{2 * COIN};
800  const CAmount excess{in_amt - fee * 2 - target};
801 
802  // Waste with change is the change cost and difference between fee and long term fee
803  add_coin(1 * COIN, 1, selection, fee, fee - fee_diff);
804  add_coin(2 * COIN, 2, selection, fee, fee - fee_diff);
805  const CAmount waste1 = GetSelectionWaste(selection, change_cost, target);
806  BOOST_CHECK_EQUAL(fee_diff * 2 + change_cost, waste1);
807  selection.clear();
808 
809  // Waste without change is the excess and difference between fee and long term fee
810  add_coin(1 * COIN, 1, selection, fee, fee - fee_diff);
811  add_coin(2 * COIN, 2, selection, fee, fee - fee_diff);
812  const CAmount waste_nochange1 = GetSelectionWaste(selection, 0, target);
813  BOOST_CHECK_EQUAL(fee_diff * 2 + excess, waste_nochange1);
814  selection.clear();
815 
816  // Waste with change and fee == long term fee is just cost of change
817  add_coin(1 * COIN, 1, selection, fee, fee);
818  add_coin(2 * COIN, 2, selection, fee, fee);
819  BOOST_CHECK_EQUAL(change_cost, GetSelectionWaste(selection, change_cost, target));
820  selection.clear();
821 
822  // Waste without change and fee == long term fee is just the excess
823  add_coin(1 * COIN, 1, selection, fee, fee);
824  add_coin(2 * COIN, 2, selection, fee, fee);
825  BOOST_CHECK_EQUAL(excess, GetSelectionWaste(selection, 0, target));
826  selection.clear();
827 
828  // Waste will be greater when fee is greater, but long term fee is the same
829  add_coin(1 * COIN, 1, selection, fee * 2, fee - fee_diff);
830  add_coin(2 * COIN, 2, selection, fee * 2, fee - fee_diff);
831  const CAmount waste2 = GetSelectionWaste(selection, change_cost, target);
832  BOOST_CHECK_GT(waste2, waste1);
833  selection.clear();
834 
835  // Waste with change is the change cost and difference between fee and long term fee
836  // With long term fee greater than fee, waste should be less than when long term fee is less than fee
837  add_coin(1 * COIN, 1, selection, fee, fee + fee_diff);
838  add_coin(2 * COIN, 2, selection, fee, fee + fee_diff);
839  const CAmount waste3 = GetSelectionWaste(selection, change_cost, target);
840  BOOST_CHECK_EQUAL(fee_diff * -2 + change_cost, waste3);
841  BOOST_CHECK_LT(waste3, waste1);
842  selection.clear();
843 
844  // Waste without change is the excess and difference between fee and long term fee
845  // With long term fee greater than fee, waste should be less than when long term fee is less than fee
846  add_coin(1 * COIN, 1, selection, fee, fee + fee_diff);
847  add_coin(2 * COIN, 2, selection, fee, fee + fee_diff);
848  const CAmount waste_nochange2 = GetSelectionWaste(selection, 0, target);
849  BOOST_CHECK_EQUAL(fee_diff * -2 + excess, waste_nochange2);
850  BOOST_CHECK_LT(waste_nochange2, waste_nochange1);
851  selection.clear();
852 
853  // No Waste when fee == long_term_fee, no change, and no excess
854  add_coin(1 * COIN, 1, selection, fee, fee);
855  add_coin(2 * COIN, 2, selection, fee, fee);
856  const CAmount exact_target{in_amt - fee * 2};
857  BOOST_CHECK_EQUAL(0, GetSelectionWaste(selection, /*change_cost=*/0, exact_target));
858  selection.clear();
859 
860  // No Waste when (fee - long_term_fee) == (-cost_of_change), and no excess
861  const CAmount new_change_cost{fee_diff * 2};
862  add_coin(1 * COIN, 1, selection, fee, fee + fee_diff);
863  add_coin(2 * COIN, 2, selection, fee, fee + fee_diff);
864  BOOST_CHECK_EQUAL(0, GetSelectionWaste(selection, new_change_cost, target));
865  selection.clear();
866 
867  // No Waste when (fee - long_term_fee) == (-excess), no change cost
868  const CAmount new_target{in_amt - fee * 2 - fee_diff * 2};
869  add_coin(1 * COIN, 1, selection, fee, fee + fee_diff);
870  add_coin(2 * COIN, 2, selection, fee, fee + fee_diff);
871  BOOST_CHECK_EQUAL(0, GetSelectionWaste(selection, /*change_cost=*/ 0, new_target));
872  selection.clear();
873 
874  // Negative waste when the long term fee is greater than the current fee and the selected value == target
875  const CAmount exact_target1{3 * COIN - 2 * fee};
876  const CAmount target_waste1{-2 * fee_diff}; // = (2 * fee) - (2 * (fee + fee_diff))
877  add_coin(1 * COIN, 1, selection, fee, fee + fee_diff);
878  add_coin(2 * COIN, 2, selection, fee, fee + fee_diff);
879  BOOST_CHECK_EQUAL(target_waste1, GetSelectionWaste(selection, /*change_cost=*/ 0, exact_target1));
880  selection.clear();
881 
882  // Negative waste when the long term fee is greater than the current fee and change_cost < - (inputs * (fee - long_term_fee))
883  const CAmount large_fee_diff{90};
884  const CAmount target_waste2{-2 * large_fee_diff + change_cost}; // = (2 * fee) - (2 * (fee + large_fee_diff)) + change_cost
885  add_coin(1 * COIN, 1, selection, fee, fee + large_fee_diff);
886  add_coin(2 * COIN, 2, selection, fee, fee + large_fee_diff);
887  BOOST_CHECK_EQUAL(target_waste2, GetSelectionWaste(selection, change_cost, target));
888 }
889 
890 BOOST_AUTO_TEST_CASE(effective_value_test)
891 {
892  const int input_bytes = 148;
893  const CFeeRate feerate(1000);
894  const CAmount nValue = 10000;
895  const int nInput = 0;
896 
898  tx.vout.resize(1);
899  tx.vout[nInput].nValue = nValue;
900 
901  // standard case, pass feerate in constructor
902  COutput output1(COutPoint(tx.GetHash(), nInput), tx.vout.at(nInput), /*depth=*/ 1, input_bytes, /*spendable=*/ true, /*solvable=*/ true, /*safe=*/ true, /*time=*/ 0, /*from_me=*/ false, feerate);
903  const CAmount expected_ev1 = 9852; // 10000 - 148
904  BOOST_CHECK_EQUAL(output1.GetEffectiveValue(), expected_ev1);
905 
906  // input bytes unknown (input_bytes = -1), pass feerate in constructor
907  COutput output2(COutPoint(tx.GetHash(), nInput), tx.vout.at(nInput), /*depth=*/ 1, /*input_bytes=*/ -1, /*spendable=*/ true, /*solvable=*/ true, /*safe=*/ true, /*time=*/ 0, /*from_me=*/ false, feerate);
908  BOOST_CHECK_EQUAL(output2.GetEffectiveValue(), nValue); // The effective value should be equal to the absolute value if input_bytes is -1
909 
910  // negative effective value, pass feerate in constructor
911  COutput output3(COutPoint(tx.GetHash(), nInput), tx.vout.at(nInput), /*depth=*/ 1, input_bytes, /*spendable=*/ true, /*solvable=*/ true, /*safe=*/ true, /*time=*/ 0, /*from_me=*/ false, CFeeRate(100000));
912  const CAmount expected_ev3 = -4800; // 10000 - 14800
913  BOOST_CHECK_EQUAL(output3.GetEffectiveValue(), expected_ev3);
914 
915  // standard case, pass fees in constructor
916  const CAmount fees = 148;
917  COutput output4(COutPoint(tx.GetHash(), nInput), tx.vout.at(nInput), /*depth=*/ 1, input_bytes, /*spendable=*/ true, /*solvable=*/ true, /*safe=*/ true, /*time=*/ 0, /*from_me=*/ false, fees);
918  BOOST_CHECK_EQUAL(output4.GetEffectiveValue(), expected_ev1);
919 
920  // input bytes unknown (input_bytes = -1), pass fees in constructor
921  COutput output5(COutPoint(tx.GetHash(), nInput), tx.vout.at(nInput), /*depth=*/ 1, /*input_bytes=*/ -1, /*spendable=*/ true, /*solvable=*/ true, /*safe=*/ true, /*time=*/ 0, /*from_me=*/ false, /*fees=*/ 0);
922  BOOST_CHECK_EQUAL(output5.GetEffectiveValue(), nValue); // The effective value should be equal to the absolute value if input_bytes is -1
923 }
924 
925 BOOST_AUTO_TEST_CASE(SelectCoins_effective_value_test)
926 {
927  // Test that the effective value is used to check whether preset inputs provide sufficient funds when subtract_fee_outputs is not used.
928  // This test creates a coin whose value is higher than the target but whose effective value is lower than the target.
929  // The coin is selected using coin control, with m_allow_other_inputs = false. SelectCoins should fail due to insufficient funds.
930 
931  std::unique_ptr<CWallet> wallet = std::make_unique<CWallet>(m_node.chain.get(), "", m_args, CreateMockWalletDatabase());
932  wallet->LoadWallet();
933  LOCK(wallet->cs_wallet);
934  wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
935  wallet->SetupDescriptorScriptPubKeyMans();
936 
937  CoinsResult available_coins;
938  {
939  std::unique_ptr<CWallet> dummyWallet = std::make_unique<CWallet>(m_node.chain.get(), "dummy", m_args, CreateMockWalletDatabase());
940  dummyWallet->LoadWallet();
941  LOCK(dummyWallet->cs_wallet);
942  dummyWallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
943  dummyWallet->SetupDescriptorScriptPubKeyMans();
944 
945  add_coin(available_coins, *dummyWallet, 100000); // 0.001 BTC
946  }
947 
948  CAmount target{99900}; // 0.000999 BTC
949 
950  FastRandomContext rand;
951  CoinSelectionParams cs_params{
952  rand,
953  /*change_output_size=*/34,
954  /*change_spend_size=*/148,
955  /*min_change_target=*/1000,
956  /*effective_feerate=*/CFeeRate(3000),
957  /*long_term_feerate=*/CFeeRate(1000),
958  /*discard_feerate=*/CFeeRate(1000),
959  /*tx_noinputs_size=*/0,
960  /*avoid_partial=*/false,
961  };
962  CCoinControl cc;
963  cc.m_allow_other_inputs = false;
964  COutput output = available_coins.All().at(0);
965  cc.SetInputWeight(output.outpoint, 148);
966  cc.SelectExternal(output.outpoint, output.txout);
967 
968  const auto result = SelectCoins(*wallet, available_coins, target, cc, cs_params);
969  BOOST_CHECK(!result);
970 }
971 
973 {
974  // Test case to verify CoinsResult object sanity.
975  CoinsResult available_coins;
976  {
977  std::unique_ptr<CWallet> dummyWallet = std::make_unique<CWallet>(m_node.chain.get(), "dummy", m_args, CreateMockWalletDatabase());
978  BOOST_CHECK_EQUAL(dummyWallet->LoadWallet(), DBErrors::LOAD_OK);
979  LOCK(dummyWallet->cs_wallet);
980  dummyWallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
981  dummyWallet->SetupDescriptorScriptPubKeyMans();
982 
983  // Add some coins to 'available_coins'
984  for (int i=0; i<10; i++) {
985  add_coin(available_coins, *dummyWallet, 1 * COIN);
986  }
987  }
988 
989  {
990  // First test case, check that 'CoinsResult::Erase' function works as expected.
991  // By trying to erase two elements from the 'available_coins' object.
992  std::set<COutPoint> outs_to_remove;
993  const auto& coins = available_coins.All();
994  for (int i = 0; i < 2; i++) {
995  outs_to_remove.emplace(coins[i].outpoint);
996  }
997  available_coins.Erase(outs_to_remove);
998 
999  // Check that the elements were actually removed.
1000  const auto& updated_coins = available_coins.All();
1001  for (const auto& out: outs_to_remove) {
1002  auto it = std::find_if(updated_coins.begin(), updated_coins.end(), [&out](const COutput &coin) {
1003  return coin.outpoint == out;
1004  });
1005  BOOST_CHECK(it == updated_coins.end());
1006  }
1007  // And verify that no extra element were removed
1008  BOOST_CHECK_EQUAL(available_coins.Size(), 8);
1009  }
1010 }
1011 
1013 } // namespace wallet
COutPoint outpoint
The outpoint identifying this UTXO.
Definition: coinselection.h:32
std::unique_ptr< interfaces::Chain > chain
Definition: context.h:57
int ret
CAmount GetSelectionWaste(const std::set< COutput > &inputs, CAmount change_cost, CAmount target, bool use_effective_value)
Compute the waste for this result given the cost of change and the opportunity cost of spending these...
assert(!tx.IsCoinBase())
static bool EquivalentResult(const SelectionResult &a, const SelectionResult &b)
Check if SelectionResult a is equivalent to SelectionResult b.
size_t Size() const
The following methods are provided so that CoinsResult can mimic a vector, i.e., methods can work wit...
Definition: spend.cpp:82
std::vector< COutput > All() const
Concatenate and return all COutputs as one vector.
Definition: spend.cpp:91
void AddInput(const OutputGroup &group)
node::NodeContext m_node
Definition: bitcoin-gui.cpp:37
void Insert(const COutput &output, size_t ancestors, size_t descendants, bool positive_only)
State of transaction not confirmed or conflicting with a known block and not in the mempool...
Definition: transaction.h:48
std::optional< SelectionResult > SelectCoinsBnB(std::vector< OutputGroup > &utxo_pool, const CAmount &selection_target, const CAmount &cost_of_change)
static int nextLockTime
#define RANDOM_REPEATS
void SelectExternal(const COutPoint &outpoint, const CTxOut &txout)
Definition: coincontrol.h:96
int64_t GetTxTime() const
Definition: transaction.cpp:22
Basic testing setup.
Definition: setup_common.h:83
static bool EqualResult(const SelectionResult &a, const SelectionResult &b)
Check if this selection is equal to another one.
CTxOut txout
The output itself.
Definition: coinselection.h:35
void Select(const COutPoint &output)
Definition: coincontrol.h:91
std::map< OutputType, std::vector< COutput > > coins
Definition: spend.h:41
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
COutputs available for spending, stored by OutputType.
Definition: spend.h:40
A transaction with a bunch of additional info that only the owner cares about.
Definition: transaction.h:137
CAmount long_term_fee
The fee required to spend this output at the consolidation feerate.
Definition: coinselection.h:67
static void add_coin(const CAmount &nValue, int nInput, std::vector< COutput > &set)
std::unique_ptr< WalletDatabase > CreateMockWalletDatabase(DatabaseOptions &options)
Return object for accessing temporary in-memory database.
Definition: walletdb.cpp:1242
#define LOCK(cs)
Definition: sync.h:261
BOOST_FIXTURE_TEST_CASE(BasicOutputTypesTest, AvailableCoinsTestingSetup)
Fast randomness source.
Definition: random.h:142
BOOST_AUTO_TEST_SUITE_END()
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:66
static void ApproximateBestSubset(FastRandomContext &insecure_rand, const std::vector< OutputGroup > &groups, const CAmount &nTotalLower, const CAmount &nTargetValue, std::vector< char > &vfBest, CAmount &nBest, int iterations=1000)
Find a subset of the OutputGroups that is at least as large as, but as close as possible to...
void SetInputWeight(const COutPoint &outpoint, int64_t weight)
Definition: coincontrol.h:117
#define RUN_TESTS
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:235
A group of UTXOs paid to the same output script.
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:334
std::set< COutput > CoinSet
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:34
static const CoinEligibilityFilter filter_standard_extra(6, 6, 0)
std::vector< CTxOut > vout
Definition: transaction.h:375
Definition: node.h:39
std::vector< OutputGroup > & GroupCoins(const std::vector< COutput > &available_coins)
Parameters for one iteration of Coin Selection.
const std::set< COutput > & GetInputSet() const
Get m_selected_inputs.
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:415
Parameters for filtering which OutputGroups we may use in coin selection.
256-bit opaque blob.
Definition: uint256.h:119
static const CoinEligibilityFilter filter_standard(1, 6, 0)
int CalculateMaximumSignedInputSize(const CTxOut &txout, const COutPoint outpoint, const SigningProvider *provider, const CCoinControl *coin_control)
Definition: spend.cpp:30
uint256 GetHash() const
Compute the hash of this CMutableTransaction.
Definition: transaction.cpp:68
#define BOOST_CHECK_EQUAL(v1, v2)
Definition: object.cpp:17
const uint256 & GetHash() const
Definition: transaction.h:298
std::optional< SelectionResult > SelectCoins(const CWallet &wallet, CoinsResult &available_coins, const CAmount &nTargetValue, const CCoinControl &coin_control, const CoinSelectionParams &coin_selection_params)
Select a set of coins such that nTargetValue is met and at least all coins from coin_control are sele...
Definition: spend.cpp:531
bool m_allow_other_inputs
If true, the selection process can add extra unselected inputs from the wallet while requires all sel...
Definition: coincontrol.h:40
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
Definition: feerate.h:32
CAmount GetFee(uint32_t num_bytes) const
Return the fee in satoshis for the given vsize in vbytes.
Definition: feerate.cpp:23
A mutable version of CTransaction.
Definition: transaction.h:372
static constexpr CAmount CENT
Definition: setup_common.h:78
std::vector< OutputGroup > GroupOutputs(const CWallet &wallet, const std::vector< COutput > &outputs, const CoinSelectionParams &coin_sel_params, const CoinEligibilityFilter &filter, bool positive_only)
Definition: spend.cpp:388
std::shared_ptr< CWallet > wallet
BOOST_AUTO_TEST_CASE(bnb_search_test)
std::optional< SelectionResult > KnapsackSolver(std::vector< OutputGroup > &groups, const CAmount &nTargetValue, CAmount change_target, FastRandomContext &rng)
A UTXO under consideration for use in funding a new transaction.
Definition: coinselection.h:22
CTransactionRef tx
Definition: transaction.h:219
uint64_t randrange(uint64_t range) noexcept
Generate a random integer in the range [0..range).
Definition: random.h:213
Coin Control Features.
Definition: coincontrol.h:29
void Erase(const std::set< COutPoint > &coins_to_remove)
Definition: spend.cpp:105
#define Assert(val)
Identity function.
Definition: check.h:74
std::vector< OutputGroup > & KnapsackGroupOutputs(const std::vector< COutput > &available_coins, CWallet &wallet, const CoinEligibilityFilter &filter)
static CAmount make_hard_case(int utxos, std::vector< COutput > &utxo_pool)
#define BOOST_CHECK(expr)
Definition: object.cpp:16
static const CoinEligibilityFilter filter_confirmed(1, 1, 0)
static constexpr CAmount COIN
The amount of satoshis in one BTC.
Definition: amount.h:15