Branch data Line data Source code
1 : : // Copyright (c) 2017-present 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>
7 : : #include <policy/policy.h>
8 : : #include <primitives/transaction.h>
9 : : #include <random.h>
10 : : #include <test/util/setup_common.h>
11 : : #include <util/translation.h>
12 : : #include <wallet/coincontrol.h>
13 : : #include <wallet/coinselection.h>
14 : : #include <wallet/spend.h>
15 : : #include <wallet/test/util.h>
16 : : #include <wallet/test/wallet_test_fixture.h>
17 : : #include <wallet/wallet.h>
18 : :
19 : : #include <algorithm>
20 : : #include <boost/test/unit_test.hpp>
21 : : #include <random>
22 : :
23 : : namespace wallet {
24 : : BOOST_FIXTURE_TEST_SUITE(coinselector_tests, WalletTestingSetup)
25 : :
26 : : // how many times to run all the tests to have a chance to catch errors that only show up with particular random shuffles
27 : : #define RUN_TESTS 100
28 : :
29 : : // some tests fail 1% of the time due to bad luck.
30 : : // we repeat those tests this many times and only complain if all iterations of the test fail
31 : : #define RANDOM_REPEATS 5
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 : 51 : static void add_coin(const CAmount& nValue, int nInput, SelectionResult& result)
39 : : {
40 : 51 : CMutableTransaction tx;
41 [ + - ]: 51 : tx.vout.resize(nInput + 1);
42 [ + - ]: 51 : tx.vout[nInput].nValue = nValue;
43 : 51 : tx.nLockTime = nextLockTime++; // so all transactions get different hashes
44 [ + - + - : 51 : COutput output(COutPoint(tx.GetHash(), nInput), tx.vout.at(nInput), /*depth=*/1, /*input_bytes=*/-1, /*solvable=*/true, /*safe=*/true, /*time=*/0, /*from_me=*/false, /*fees=*/ 0);
+ - ]
45 [ + - ]: 51 : OutputGroup group;
46 [ + - + - ]: 51 : group.Insert(std::make_shared<COutput>(output), /*ancestors=*/ 0, /*descendants=*/ 0);
47 [ + - ]: 51 : result.AddInput(group);
48 : 102 : }
49 : :
50 : 28 : static void add_coin(const CAmount& nValue, int nInput, SelectionResult& result, CAmount fee, CAmount long_term_fee)
51 : : {
52 : 28 : CMutableTransaction tx;
53 [ + - ]: 28 : tx.vout.resize(nInput + 1);
54 [ + - ]: 28 : tx.vout[nInput].nValue = nValue;
55 : 28 : tx.nLockTime = nextLockTime++; // so all transactions get different hashes
56 [ + - + - : 28 : std::shared_ptr<COutput> coin = std::make_shared<COutput>(COutPoint(tx.GetHash(), nInput), tx.vout.at(nInput), /*depth=*/1, /*input_bytes=*/148, /*solvable=*/true, /*safe=*/true, /*time=*/0, /*from_me=*/false, fee);
+ - ]
57 [ + - ]: 28 : OutputGroup group;
58 [ + - ]: 28 : group.Insert(coin, /*ancestors=*/ 0, /*descendants=*/ 0);
59 [ + - ]: 28 : coin->long_term_fee = long_term_fee; // group.Insert() will modify long_term_fee, so we need to set it afterwards
60 [ + - ]: 28 : result.AddInput(group);
61 [ + - ]: 84 : }
62 : :
63 : 116228 : 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, int custom_size = 0)
64 : : {
65 : 116228 : CMutableTransaction tx;
66 : 116228 : tx.nLockTime = nextLockTime++; // so all transactions get different hashes
67 [ + - ]: 116228 : tx.vout.resize(nInput + 1);
68 [ + + ]: 116228 : tx.vout[nInput].nValue = nValue;
69 [ + + ]: 116228 : if (spendable) {
70 [ + - + - : 12378 : tx.vout[nInput].scriptPubKey = GetScriptForDestination(*Assert(wallet.GetNewDestination(OutputType::BECH32, "")));
+ - ]
71 : : }
72 [ + - ]: 116228 : Txid txid = tx.GetHash();
73 : :
74 [ + - ]: 116228 : LOCK(wallet.cs_wallet);
75 [ + - + - : 232456 : auto ret = wallet.mapWallet.emplace(std::piecewise_construct, std::forward_as_tuple(txid), std::forward_as_tuple(MakeTransactionRef(std::move(tx)), TxStateInactive{}));
- + ]
76 [ - + ]: 116228 : assert(ret.second);
77 [ + - ]: 116228 : CWalletTx& wtx = (*ret.first).second;
78 [ + - ]: 116228 : const auto& txout = wtx.tx->vout.at(nInput);
79 [ + + + - : 232456 : available_coins.Add(OutputType::BECH32, {COutPoint(wtx.GetHash(), nInput), txout, nAge, custom_size == 0 ? CalculateMaximumSignedInputSize(txout, &wallet, /*coin_control=*/nullptr) : custom_size, /*solvable=*/true, /*safe=*/true, wtx.GetTxTime(), fIsFromMe, feerate});
+ - + - +
- + - ]
80 : 232456 : }
81 : :
82 : : // Helpers
83 : 5601 : std::optional<SelectionResult> KnapsackSolver(std::vector<OutputGroup>& groups, const CAmount& nTargetValue,
84 : : CAmount change_target, FastRandomContext& rng)
85 : : {
86 : 5601 : auto res{KnapsackSolver(groups, nTargetValue, change_target, rng, MAX_STANDARD_TX_WEIGHT)};
87 [ + + + - ]: 10602 : return res ? std::optional<SelectionResult>(*res) : std::nullopt;
88 : 5601 : }
89 : :
90 : 3 : std::optional<SelectionResult> SelectCoinsBnB(std::vector<OutputGroup>& utxo_pool, const CAmount& selection_target, const CAmount& cost_of_change)
91 : : {
92 : 3 : auto res{SelectCoinsBnB(utxo_pool, selection_target, cost_of_change, MAX_STANDARD_TX_WEIGHT)};
93 [ + + + - ]: 5 : return res ? std::optional<SelectionResult>(*res) : std::nullopt;
94 : 3 : }
95 : :
96 : : /** Check if SelectionResult a is equivalent to SelectionResult b.
97 : : * Equivalent means same input values, but maybe different inputs (i.e. same value, different prevout) */
98 : 8 : static bool EquivalentResult(const SelectionResult& a, const SelectionResult& b)
99 : : {
100 : 8 : std::vector<CAmount> a_amts;
101 : 8 : std::vector<CAmount> b_amts;
102 [ + - + + ]: 59 : for (const auto& coin : a.GetInputSet()) {
103 [ + - ]: 51 : a_amts.push_back(coin->txout.nValue);
104 : : }
105 [ + - + + ]: 59 : for (const auto& coin : b.GetInputSet()) {
106 [ + - ]: 51 : b_amts.push_back(coin->txout.nValue);
107 : : }
108 : 8 : std::sort(a_amts.begin(), a_amts.end());
109 : 8 : std::sort(b_amts.begin(), b_amts.end());
110 : :
111 : 8 : std::pair<std::vector<CAmount>::iterator, std::vector<CAmount>::iterator> ret = std::mismatch(a_amts.begin(), a_amts.end(), b_amts.begin());
112 [ + - - + ]: 8 : return ret.first == a_amts.end() && ret.second == b_amts.end();
113 : 8 : }
114 : :
115 : : /** Check if this selection is equal to another one. Equal means same inputs (i.e same value and prevout) */
116 : 1100 : static bool EqualResult(const SelectionResult& a, const SelectionResult& b)
117 : : {
118 : 1100 : std::pair<OutputSet::iterator, OutputSet::iterator> ret = std::mismatch(a.GetInputSet().begin(), a.GetInputSet().end(), b.GetInputSet().begin(),
119 : 1126 : [](const std::shared_ptr<COutput>& a, const std::shared_ptr<COutput>& b) {
120 [ + + ]: 1126 : return a->outpoint == b->outpoint;
121 : : });
122 [ + + - + ]: 1100 : return ret.first == a.GetInputSet().end() && ret.second == b.GetInputSet().end();
123 : : }
124 : :
125 : 2204 : inline std::vector<OutputGroup>& GroupCoins(const std::vector<COutput>& available_coins, bool subtract_fee_outputs = false)
126 : : {
127 [ + + + - ]: 2205 : static std::vector<OutputGroup> static_groups;
128 : 2204 : static_groups.clear();
129 [ + + ]: 227219 : for (auto& coin : available_coins) {
130 : 225015 : static_groups.emplace_back();
131 : 225015 : OutputGroup& group = static_groups.back();
132 [ + - ]: 225015 : group.Insert(std::make_shared<COutput>(coin), /*ancestors=*/ 0, /*descendants=*/ 0);
133 : 225015 : group.m_subtract_fee_outputs = subtract_fee_outputs;
134 : : }
135 : 2204 : return static_groups;
136 : : }
137 : :
138 : 3401 : inline std::vector<OutputGroup>& KnapsackGroupOutputs(const CoinsResult& available_coins, CWallet& wallet, const CoinEligibilityFilter& filter)
139 : : {
140 : 3401 : FastRandomContext rand{};
141 [ + + ]: 3401 : CoinSelectionParams coin_selection_params{
142 : : rand,
143 : : /*change_output_size=*/ 0,
144 : : /*change_spend_size=*/ 0,
145 : : /*min_change_target=*/ CENT,
146 : 3401 : /*effective_feerate=*/ CFeeRate(0),
147 : 3401 : /*long_term_feerate=*/ CFeeRate(0),
148 : 3401 : /*discard_feerate=*/ CFeeRate(0),
149 : : /*tx_noinputs_size=*/ 0,
150 : : /*avoid_partial=*/ false,
151 [ + + ]: 3401 : };
152 [ + + + - ]: 3401 : static OutputGroupTypeMap static_groups;
153 [ + - + - : 6802 : static_groups = GroupOutputs(wallet, available_coins, coin_selection_params, {{filter}})[filter];
+ - + - ]
154 : 3401 : return static_groups.all_groups.mixed_group;
155 : 3401 : }
156 : :
157 : 26 : static std::unique_ptr<CWallet> NewWallet(const node::NodeContext& m_node, const std::string& wallet_name = "")
158 : : {
159 [ + - + - ]: 26 : std::unique_ptr<CWallet> wallet = std::make_unique<CWallet>(m_node.chain.get(), wallet_name, CreateMockableWalletDatabase());
160 [ + - ]: 26 : LOCK(wallet->cs_wallet);
161 [ + - ]: 26 : wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
162 [ + - ]: 26 : wallet->SetupDescriptorScriptPubKeyMans();
163 [ + - ]: 26 : return wallet;
164 : 26 : }
165 : :
166 : : // Branch and bound coin selection tests
167 [ + - + - : 7 : BOOST_AUTO_TEST_CASE(bnb_search_test)
+ - + - -
+ + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- ]
168 : : {
169 : 1 : FastRandomContext rand{};
170 : : // Setup
171 : 1 : std::vector<COutput> utxo_pool;
172 [ + - ]: 1 : SelectionResult expected_result(CAmount(0), SelectionAlgorithm::BNB);
173 : :
174 : : ////////////////////
175 : : // Behavior tests //
176 : : ////////////////////
177 : :
178 : : // Make sure that effective value is working in AttemptSelection when BnB is used
179 [ + - ]: 1 : CoinSelectionParams coin_selection_params_bnb{
180 : : rand,
181 : : /*change_output_size=*/ 31,
182 : : /*change_spend_size=*/ 68,
183 : : /*min_change_target=*/ 0,
184 : 1 : /*effective_feerate=*/ CFeeRate(3000),
185 : 1 : /*long_term_feerate=*/ CFeeRate(1000),
186 : 1 : /*discard_feerate=*/ CFeeRate(1000),
187 : : /*tx_noinputs_size=*/ 0,
188 : : /*avoid_partial=*/ false,
189 [ + - ]: 1 : };
190 : 1 : coin_selection_params_bnb.m_change_fee = coin_selection_params_bnb.m_effective_feerate.GetFee(coin_selection_params_bnb.change_output_size);
191 [ + - ]: 1 : 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;
192 [ + - ]: 1 : coin_selection_params_bnb.min_viable_change = coin_selection_params_bnb.m_effective_feerate.GetFee(coin_selection_params_bnb.change_spend_size);
193 : :
194 : 1 : {
195 [ + - + - ]: 1 : std::unique_ptr<CWallet> wallet = NewWallet(m_node);
196 : :
197 [ + - ]: 1 : CoinsResult available_coins;
198 : :
199 [ + - ]: 1 : add_coin(available_coins, *wallet, 1, coin_selection_params_bnb.m_effective_feerate);
200 [ + - ]: 2 : 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
201 [ + - + - : 2 : BOOST_CHECK(!SelectCoinsBnB(GroupCoins(available_coins.All()), 1 * CENT, coin_selection_params_bnb.m_cost_of_change));
+ - + - +
- + - ]
202 : :
203 : : // Test fees subtracted from output:
204 [ + - ]: 1 : available_coins.Clear();
205 [ + - ]: 1 : add_coin(available_coins, *wallet, 1 * CENT, coin_selection_params_bnb.m_effective_feerate);
206 [ + - ]: 2 : available_coins.All().at(0).input_bytes = 40;
207 [ + - + - : 1 : const auto result9 = SelectCoinsBnB(GroupCoins(available_coins.All()), 1 * CENT, coin_selection_params_bnb.m_cost_of_change);
+ - ]
208 [ + - + - : 2 : BOOST_CHECK(result9);
+ - ]
209 [ + - + - : 1 : BOOST_CHECK_EQUAL(result9->GetSelectedValue(), 1 * CENT);
+ - ]
210 [ + - ]: 1 : }
211 : :
212 : 1 : {
213 [ + - + - ]: 1 : std::unique_ptr<CWallet> wallet = NewWallet(m_node);
214 : :
215 [ + - ]: 1 : CoinsResult available_coins;
216 : :
217 [ + - ]: 1 : coin_selection_params_bnb.m_effective_feerate = CFeeRate(0);
218 [ + - ]: 1 : add_coin(available_coins, *wallet, 5 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true);
219 [ + - ]: 1 : add_coin(available_coins, *wallet, 3 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true);
220 [ + - ]: 1 : add_coin(available_coins, *wallet, 2 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true);
221 [ + - ]: 1 : CCoinControl coin_control;
222 : 1 : coin_control.m_allow_other_inputs = true;
223 [ + - ]: 2 : COutput select_coin = available_coins.All().at(0);
224 [ + - ]: 1 : coin_control.Select(select_coin.outpoint);
225 [ + - ]: 1 : CoinsResult selected_input;
226 [ + - ]: 1 : selected_input.Add(OutputType::BECH32, select_coin);
227 [ + - + - : 3 : available_coins.Erase({available_coins.coins[OutputType::BECH32].begin()->outpoint});
+ - + - ]
228 : :
229 [ + - ]: 1 : LOCK(wallet->cs_wallet);
230 [ + - ]: 1 : const auto result10 = SelectCoins(*wallet, available_coins, selected_input, 10 * CENT, coin_control, coin_selection_params_bnb);
231 [ + - + - ]: 2 : BOOST_CHECK(result10);
232 [ + - + - ]: 2 : }
233 : 1 : {
234 [ + - + - ]: 1 : std::unique_ptr<CWallet> wallet = NewWallet(m_node);
235 [ + - ]: 1 : LOCK(wallet->cs_wallet); // Every 'SelectCoins' call requires it
236 : :
237 [ + - ]: 1 : CoinsResult available_coins;
238 : :
239 : : // pre selected coin should be selected even if disadvantageous
240 [ + - ]: 1 : coin_selection_params_bnb.m_effective_feerate = CFeeRate(5000);
241 : 1 : coin_selection_params_bnb.m_long_term_feerate = CFeeRate(3000);
242 : :
243 : : // Add selectable outputs, increasing their raw amounts by their input fee to make the effective value equal to the raw amount
244 [ + - ]: 1 : CAmount input_fee = coin_selection_params_bnb.m_effective_feerate.GetFee(/*virtual_bytes=*/68); // bech32 input size (default test output type)
245 [ + - ]: 1 : add_coin(available_coins, *wallet, 10 * CENT + input_fee, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true);
246 [ + - ]: 1 : add_coin(available_coins, *wallet, 9 * CENT + input_fee, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true);
247 [ + - ]: 1 : add_coin(available_coins, *wallet, 1 * CENT + input_fee, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true);
248 : :
249 [ + - ]: 1 : expected_result.Clear();
250 [ + - ]: 1 : add_coin(9 * CENT + input_fee, 2, expected_result);
251 [ + - ]: 1 : add_coin(1 * CENT + input_fee, 2, expected_result);
252 [ + - ]: 1 : CCoinControl coin_control;
253 : 1 : coin_control.m_allow_other_inputs = true;
254 [ + - ]: 2 : COutput select_coin = available_coins.All().at(1); // pre select 9 coin
255 [ + - ]: 1 : coin_control.Select(select_coin.outpoint);
256 [ + - ]: 1 : CoinsResult selected_input;
257 [ + - ]: 1 : selected_input.Add(OutputType::BECH32, select_coin);
258 [ + - + - : 3 : available_coins.Erase({(++available_coins.coins[OutputType::BECH32].begin())->outpoint});
+ - + - ]
259 [ + - ]: 1 : const auto result13 = SelectCoins(*wallet, available_coins, selected_input, 10 * CENT, coin_control, coin_selection_params_bnb);
260 [ + - + - : 2 : BOOST_CHECK(EquivalentResult(expected_result, *result13));
+ - ]
261 [ + - + - ]: 2 : }
262 : :
263 : 1 : {
264 : : // Test bnb max weight exceeded
265 : : // Inputs set [10, 9, 8, 5, 3, 1], Selection Target = 16 and coin 5 exceeding the max weight.
266 : :
267 [ + - + - ]: 1 : std::unique_ptr<CWallet> wallet = NewWallet(m_node);
268 : :
269 [ + - ]: 1 : CoinsResult available_coins;
270 [ + - ]: 1 : add_coin(available_coins, *wallet, 10 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true);
271 [ + - ]: 1 : add_coin(available_coins, *wallet, 9 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true);
272 [ + - ]: 1 : add_coin(available_coins, *wallet, 8 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true);
273 [ + - ]: 1 : add_coin(available_coins, *wallet, 5 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true, /*custom_size=*/MAX_STANDARD_TX_WEIGHT);
274 [ + - ]: 1 : add_coin(available_coins, *wallet, 3 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true);
275 [ + - ]: 1 : add_coin(available_coins, *wallet, 1 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true);
276 : :
277 : 1 : CAmount selection_target = 16 * CENT;
278 : 0 : const auto& no_res = SelectCoinsBnB(GroupCoins(available_coins.All(), /*subtract_fee_outputs=*/true),
279 [ + - + - : 2 : selection_target, /*cost_of_change=*/0, MAX_STANDARD_TX_WEIGHT);
+ - ]
280 [ + - + - : 2 : BOOST_REQUIRE(!no_res);
+ - ]
281 [ + - + - : 3 : BOOST_CHECK(util::ErrorString(no_res).original.find("The inputs size exceeds the maximum weight") != std::string::npos);
+ - + - ]
282 : :
283 : : // Now add same coin value with a good size and check that it gets selected
284 [ + - ]: 1 : add_coin(available_coins, *wallet, 5 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true);
285 [ + - + - : 2 : const auto& res = SelectCoinsBnB(GroupCoins(available_coins.All(), /*subtract_fee_outputs=*/true), selection_target, /*cost_of_change=*/0);
+ - ]
286 : :
287 [ + - ]: 1 : expected_result.Clear();
288 [ + - ]: 1 : add_coin(8 * CENT, 2, expected_result);
289 [ + - ]: 1 : add_coin(5 * CENT, 2, expected_result);
290 [ + - ]: 1 : add_coin(3 * CENT, 2, expected_result);
291 [ + - + - : 2 : BOOST_CHECK(EquivalentResult(expected_result, *res));
+ - ]
292 [ + - ]: 2 : }
293 : 1 : }
294 : :
295 [ + - + - : 7 : BOOST_AUTO_TEST_CASE(bnb_sffo_restriction)
+ - + - -
+ + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- ]
296 : : {
297 : : // Verify the coin selection process does not produce a BnB solution when SFFO is enabled.
298 : : // This is currently problematic because it could require a change output. And BnB is specialized on changeless solutions.
299 [ + - ]: 1 : std::unique_ptr<CWallet> wallet = NewWallet(m_node);
300 [ + - ]: 3 : WITH_LOCK(wallet->cs_wallet, wallet->SetLastBlockProcessed(300, uint256{})); // set a high block so internal UTXOs are selectable
301 : :
302 : 1 : FastRandomContext rand{};
303 [ + - ]: 1 : CoinSelectionParams params{
304 : : rand,
305 : : /*change_output_size=*/ 31, // unused value, p2wpkh output size (wallet default change type)
306 : : /*change_spend_size=*/ 68, // unused value, p2wpkh input size (high-r signature)
307 : : /*min_change_target=*/ 0, // dummy, set later
308 : 1 : /*effective_feerate=*/ CFeeRate(3000),
309 : 1 : /*long_term_feerate=*/ CFeeRate(1000),
310 : 1 : /*discard_feerate=*/ CFeeRate(1000),
311 : : /*tx_noinputs_size=*/ 0,
312 : : /*avoid_partial=*/ false,
313 [ + - ]: 1 : };
314 : 1 : params.m_subtract_fee_outputs = true;
315 [ + - ]: 1 : params.m_change_fee = params.m_effective_feerate.GetFee(params.change_output_size);
316 [ + - ]: 1 : params.m_cost_of_change = params.m_discard_feerate.GetFee(params.change_spend_size) + params.m_change_fee;
317 : 1 : params.m_min_change_target = params.m_cost_of_change + 1;
318 : : // Add spendable coin at the BnB selection upper bound
319 [ + - ]: 1 : CoinsResult available_coins;
320 [ + - ]: 1 : add_coin(available_coins, *wallet, COIN + params.m_cost_of_change, /*feerate=*/params.m_effective_feerate, /*nAge=*/6, /*fIsFromMe=*/true, /*nInput=*/0, /*spendable=*/true);
321 [ + - ]: 1 : add_coin(available_coins, *wallet, 0.5 * COIN + params.m_cost_of_change, /*feerate=*/params.m_effective_feerate, /*nAge=*/6, /*fIsFromMe=*/true, /*nInput=*/0, /*spendable=*/true);
322 [ + - ]: 1 : add_coin(available_coins, *wallet, 0.5 * COIN, /*feerate=*/params.m_effective_feerate, /*nAge=*/6, /*fIsFromMe=*/true, /*nInput=*/0, /*spendable=*/true);
323 : : // Knapsack will only find a changeless solution on an exact match to the satoshi, SRD doesn’t look for changeless
324 : : // If BnB were run, it would produce a single input solution with the best waste score
325 [ + - + - : 4 : auto result = WITH_LOCK(wallet->cs_wallet, return SelectCoins(*wallet, available_coins, /*pre_set_inputs=*/{}, COIN, /*coin_control=*/{}, params));
+ - ]
326 [ + - + - : 2 : BOOST_CHECK(result.has_value());
+ - ]
327 [ + - + - ]: 1 : BOOST_CHECK_NE(result->GetAlgo(), SelectionAlgorithm::BNB);
328 [ + - + - : 2 : BOOST_CHECK(result->GetInputSet().size() == 2);
+ - + - ]
329 : : // We have only considered BnB, SRD, and Knapsack. Test needs to be reevaluated if new algo is added
330 [ + - + - : 3 : BOOST_CHECK(result->GetAlgo() == SelectionAlgorithm::SRD || result->GetAlgo() == SelectionAlgorithm::KNAPSACK);
+ - + - ]
331 [ + - ]: 2 : }
332 : :
333 [ + - + - : 7 : BOOST_AUTO_TEST_CASE(knapsack_solver_test)
+ - + - -
+ + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- ]
334 : : {
335 : 1 : FastRandomContext rand{};
336 : 5601 : const auto temp1{[&rand](std::vector<OutputGroup>& g, const CAmount& v, CAmount c) { return KnapsackSolver(g, v, c, rand); }};
337 : 1 : const auto KnapsackSolver{temp1};
338 [ + - + - ]: 1 : std::unique_ptr<CWallet> wallet = NewWallet(m_node);
339 : :
340 : 1 : CoinsResult available_coins;
341 : :
342 : : // test multiple times to allow for differences in the shuffle order
343 [ + + ]: 101 : for (int i = 0; i < RUN_TESTS; i++)
344 : : {
345 [ + - ]: 100 : available_coins.Clear();
346 : :
347 : : // with an empty wallet we can't even pay one cent
348 [ + - + - : 200 : BOOST_CHECK(!KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_standard), 1 * CENT, CENT));
+ - + - +
- ]
349 : :
350 [ + - ]: 100 : add_coin(available_coins, *wallet, 1*CENT, CFeeRate(0), 4); // add a new 1 cent coin
351 : :
352 : : // with a new 1 cent coin, we still can't find a mature 1 cent
353 [ + - + - : 200 : BOOST_CHECK(!KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_standard), 1 * CENT, CENT));
+ - + - +
- ]
354 : :
355 : : // but we can find a new 1 cent
356 [ + - + - ]: 100 : const auto result1 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 1 * CENT, CENT);
357 [ + - + - : 200 : BOOST_CHECK(result1);
+ - ]
358 [ + - + - : 100 : BOOST_CHECK_EQUAL(result1->GetSelectedValue(), 1 * CENT);
+ - ]
359 : :
360 [ + - ]: 100 : add_coin(available_coins, *wallet, 2*CENT); // add a mature 2 cent coin
361 : :
362 : : // we can't make 3 cents of mature coins
363 [ + - + - : 200 : BOOST_CHECK(!KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_standard), 3 * CENT, CENT));
+ - + - +
- ]
364 : :
365 : : // we can make 3 cents of new coins
366 [ + - + - ]: 100 : const auto result2 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 3 * CENT, CENT);
367 [ + - + - : 200 : BOOST_CHECK(result2);
+ - ]
368 [ + - + - : 100 : BOOST_CHECK_EQUAL(result2->GetSelectedValue(), 3 * CENT);
+ - ]
369 : :
370 [ + - ]: 100 : add_coin(available_coins, *wallet, 5*CENT); // add a mature 5 cent coin,
371 [ + - ]: 100 : add_coin(available_coins, *wallet, 10*CENT, CFeeRate(0), 3, true); // a new 10 cent coin sent from one of our own addresses
372 [ + - ]: 100 : add_coin(available_coins, *wallet, 20*CENT); // and a mature 20 cent coin
373 : :
374 : : // now we have new: 1+10=11 (of which 10 was self-sent), and mature: 2+5+20=27. total = 38
375 : :
376 : : // we can't make 38 cents only if we disallow new coins:
377 [ + - + - : 200 : BOOST_CHECK(!KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_standard), 38 * CENT, CENT));
+ - + - +
- ]
378 : : // we can't even make 37 cents if we don't allow new coins even if they're from us
379 [ + - + - : 200 : BOOST_CHECK(!KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_standard_extra), 38 * CENT, CENT));
+ - + - +
- ]
380 : : // but we can make 37 cents if we accept new coins from ourself
381 [ + - + - ]: 100 : const auto result3 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_standard), 37 * CENT, CENT);
382 [ + - + - : 200 : BOOST_CHECK(result3);
+ - ]
383 [ + - + - : 100 : BOOST_CHECK_EQUAL(result3->GetSelectedValue(), 37 * CENT);
+ - ]
384 : : // and we can make 38 cents if we accept all new coins
385 [ + - + - ]: 100 : const auto result4 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 38 * CENT, CENT);
386 [ + - + - : 200 : BOOST_CHECK(result4);
+ - ]
387 [ + - + - : 100 : BOOST_CHECK_EQUAL(result4->GetSelectedValue(), 38 * CENT);
+ - ]
388 : :
389 : : // try making 34 cents from 1,2,5,10,20 - we can't do it exactly
390 [ + - + - ]: 100 : const auto result5 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 34 * CENT, CENT);
391 [ + - + - : 200 : BOOST_CHECK(result5);
+ - ]
392 [ + - + - : 100 : BOOST_CHECK_EQUAL(result5->GetSelectedValue(), 35 * CENT); // but 35 cents is closest
+ - ]
393 [ + - + - : 100 : 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)
+ - ]
394 : :
395 : : // when we try making 7 cents, the smaller coins (1,2,5) are enough. We should see just 2+5
396 [ + - + - ]: 100 : const auto result6 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 7 * CENT, CENT);
397 [ + - + - : 200 : BOOST_CHECK(result6);
+ - ]
398 [ + - + - : 100 : BOOST_CHECK_EQUAL(result6->GetSelectedValue(), 7 * CENT);
+ - ]
399 [ + - + - : 100 : BOOST_CHECK_EQUAL(result6->GetInputSet().size(), 2U);
+ - ]
400 : :
401 : : // when we try making 8 cents, the smaller coins (1,2,5) are exactly enough.
402 [ + - + - ]: 100 : const auto result7 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 8 * CENT, CENT);
403 [ + - + - : 200 : BOOST_CHECK(result7);
+ - ]
404 [ + - + - : 200 : BOOST_CHECK(result7->GetSelectedValue() == 8 * CENT);
+ - + - ]
405 [ + - + - : 100 : BOOST_CHECK_EQUAL(result7->GetInputSet().size(), 3U);
+ - ]
406 : :
407 : : // when we try making 9 cents, no subset of smaller coins is enough, and we get the next bigger coin (10)
408 [ + - + - ]: 100 : const auto result8 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 9 * CENT, CENT);
409 [ + - + - : 200 : BOOST_CHECK(result8);
+ - ]
410 [ + - + - : 100 : BOOST_CHECK_EQUAL(result8->GetSelectedValue(), 10 * CENT);
+ - ]
411 [ + - + - : 100 : BOOST_CHECK_EQUAL(result8->GetInputSet().size(), 1U);
+ - ]
412 : :
413 : : // now clear out the wallet and start again to test choosing between subsets of smaller coins and the next biggest coin
414 [ + - ]: 100 : available_coins.Clear();
415 : :
416 [ + - ]: 100 : add_coin(available_coins, *wallet, 6*CENT);
417 [ + - ]: 100 : add_coin(available_coins, *wallet, 7*CENT);
418 [ + - ]: 100 : add_coin(available_coins, *wallet, 8*CENT);
419 [ + - ]: 100 : add_coin(available_coins, *wallet, 20*CENT);
420 [ + - ]: 100 : add_coin(available_coins, *wallet, 30*CENT); // now we have 6+7+8+20+30 = 71 cents total
421 : :
422 : : // check that we have 71 and not 72
423 [ + - + - ]: 100 : const auto result9 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 71 * CENT, CENT);
424 [ + - + - : 200 : BOOST_CHECK(result9);
+ - ]
425 [ + - + - : 200 : BOOST_CHECK(!KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 72 * CENT, CENT));
+ - + - +
- ]
426 : :
427 : : // 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
428 [ + - + - ]: 100 : const auto result10 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 16 * CENT, CENT);
429 [ + - + - : 200 : BOOST_CHECK(result10);
+ - ]
430 [ + - + - : 100 : BOOST_CHECK_EQUAL(result10->GetSelectedValue(), 20 * CENT); // we should get 20 in one coin
+ - ]
431 [ + - + - : 100 : BOOST_CHECK_EQUAL(result10->GetInputSet().size(), 1U);
+ - ]
432 : :
433 [ + - ]: 100 : add_coin(available_coins, *wallet, 5*CENT); // now we have 5+6+7+8+20+30 = 75 cents total
434 : :
435 : : // 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
436 [ + - + - ]: 100 : const auto result11 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 16 * CENT, CENT);
437 [ + - + - : 200 : BOOST_CHECK(result11);
+ - ]
438 [ + - + - : 100 : BOOST_CHECK_EQUAL(result11->GetSelectedValue(), 18 * CENT); // we should get 18 in 3 coins
+ - ]
439 [ + - + - : 100 : BOOST_CHECK_EQUAL(result11->GetInputSet().size(), 3U);
+ - ]
440 : :
441 [ + - ]: 100 : add_coin(available_coins, *wallet, 18*CENT); // now we have 5+6+7+8+18+20+30
442 : :
443 : : // 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
444 [ + - + - ]: 100 : const auto result12 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 16 * CENT, CENT);
445 [ + - + - : 200 : BOOST_CHECK(result12);
+ - ]
446 [ + - + - : 100 : BOOST_CHECK_EQUAL(result12->GetSelectedValue(), 18 * CENT); // we should get 18 in 1 coin
+ - ]
447 [ + - + - : 100 : BOOST_CHECK_EQUAL(result12->GetInputSet().size(), 1U); // because in the event of a tie, the biggest coin wins
+ - ]
448 : :
449 : : // now try making 11 cents. we should get 5+6
450 [ + - + - ]: 100 : const auto result13 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 11 * CENT, CENT);
451 [ + - + - : 200 : BOOST_CHECK(result13);
+ - ]
452 [ + - + - : 100 : BOOST_CHECK_EQUAL(result13->GetSelectedValue(), 11 * CENT);
+ - ]
453 [ + - + - : 100 : BOOST_CHECK_EQUAL(result13->GetInputSet().size(), 2U);
+ - ]
454 : :
455 : : // check that the smallest bigger coin is used
456 [ + - ]: 100 : add_coin(available_coins, *wallet, 1*COIN);
457 [ + - ]: 100 : add_coin(available_coins, *wallet, 2*COIN);
458 [ + - ]: 100 : add_coin(available_coins, *wallet, 3*COIN);
459 [ + - ]: 100 : add_coin(available_coins, *wallet, 4*COIN); // now we have 5+6+7+8+18+20+30+100+200+300+400 = 1094 cents
460 [ + - + - ]: 100 : const auto result14 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 95 * CENT, CENT);
461 [ + - + - : 200 : BOOST_CHECK(result14);
+ - ]
462 [ + - + - : 100 : BOOST_CHECK_EQUAL(result14->GetSelectedValue(), 1 * COIN); // we should get 1 BTC in 1 coin
+ - ]
463 [ + - + - : 100 : BOOST_CHECK_EQUAL(result14->GetInputSet().size(), 1U);
+ - ]
464 : :
465 [ + - + - ]: 100 : const auto result15 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 195 * CENT, CENT);
466 [ + - + - : 200 : BOOST_CHECK(result15);
+ - ]
467 [ + - + - : 100 : BOOST_CHECK_EQUAL(result15->GetSelectedValue(), 2 * COIN); // we should get 2 BTC in 1 coin
+ - ]
468 [ + - + - : 100 : BOOST_CHECK_EQUAL(result15->GetInputSet().size(), 1U);
+ - ]
469 : :
470 : : // empty the wallet and start again, now with fractions of a cent, to test small change avoidance
471 : :
472 [ + - ]: 100 : available_coins.Clear();
473 [ + - ]: 100 : add_coin(available_coins, *wallet, CENT * 1 / 10);
474 [ + - ]: 100 : add_coin(available_coins, *wallet, CENT * 2 / 10);
475 [ + - ]: 100 : add_coin(available_coins, *wallet, CENT * 3 / 10);
476 [ + - ]: 100 : add_coin(available_coins, *wallet, CENT * 4 / 10);
477 [ + - ]: 100 : add_coin(available_coins, *wallet, CENT * 5 / 10);
478 : :
479 : : // try making 1 * CENT from the 1.5 * CENT
480 : : // we'll get change smaller than CENT whatever happens, so can expect CENT exactly
481 [ + - + - ]: 100 : const auto result16 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), CENT, CENT);
482 [ + - + - : 200 : BOOST_CHECK(result16);
+ - ]
483 [ + - + - : 100 : BOOST_CHECK_EQUAL(result16->GetSelectedValue(), CENT);
+ - ]
484 : :
485 : : // but if we add a bigger coin, small change is avoided
486 [ + - ]: 100 : add_coin(available_coins, *wallet, 1111*CENT);
487 : :
488 : : // try making 1 from 0.1 + 0.2 + 0.3 + 0.4 + 0.5 + 1111 = 1112.5
489 [ + - + - ]: 100 : const auto result17 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 1 * CENT, CENT);
490 [ + - + - : 200 : BOOST_CHECK(result17);
+ - ]
491 [ + - + - : 100 : BOOST_CHECK_EQUAL(result17->GetSelectedValue(), 1 * CENT); // we should get the exact amount
+ - ]
492 : :
493 : : // if we add more small coins:
494 [ + - ]: 100 : add_coin(available_coins, *wallet, CENT * 6 / 10);
495 [ + - ]: 100 : add_coin(available_coins, *wallet, CENT * 7 / 10);
496 : :
497 : : // and try again to make 1.0 * CENT
498 [ + - + - ]: 100 : const auto result18 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 1 * CENT, CENT);
499 [ + - + - : 200 : BOOST_CHECK(result18);
+ - ]
500 [ + - + - : 100 : BOOST_CHECK_EQUAL(result18->GetSelectedValue(), 1 * CENT); // we should get the exact amount
+ - ]
501 : :
502 : : // run the 'mtgox' test (see https://blockexplorer.com/tx/29a3efd3ef04f9153d47a990bd7b048a4b2d213daaa5fb8ed670fb85f13bdbcf)
503 : : // they tried to consolidate 10 50k coins into one 500k coin, and ended up with 50k in change
504 [ + - ]: 100 : available_coins.Clear();
505 [ + + ]: 2100 : for (int j = 0; j < 20; j++)
506 [ + - ]: 2000 : add_coin(available_coins, *wallet, 50000 * COIN);
507 : :
508 [ + - + - ]: 100 : const auto result19 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 500000 * COIN, CENT);
509 [ + - + - : 200 : BOOST_CHECK(result19);
+ - ]
510 [ + - + - : 100 : BOOST_CHECK_EQUAL(result19->GetSelectedValue(), 500000 * COIN); // we should get the exact amount
+ - ]
511 [ + - + - : 100 : BOOST_CHECK_EQUAL(result19->GetInputSet().size(), 10U); // in ten coins
+ - ]
512 : :
513 : : // 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),
514 : : // we need to try finding an exact subset anyway
515 : :
516 : : // sometimes it will fail, and so we use the next biggest coin:
517 [ + - ]: 100 : available_coins.Clear();
518 [ + - ]: 100 : add_coin(available_coins, *wallet, CENT * 5 / 10);
519 [ + - ]: 100 : add_coin(available_coins, *wallet, CENT * 6 / 10);
520 [ + - ]: 100 : add_coin(available_coins, *wallet, CENT * 7 / 10);
521 [ + - ]: 100 : add_coin(available_coins, *wallet, 1111 * CENT);
522 [ + - + - ]: 100 : const auto result20 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 1 * CENT, CENT);
523 [ + - + - : 200 : BOOST_CHECK(result20);
+ - ]
524 [ + - + - : 100 : BOOST_CHECK_EQUAL(result20->GetSelectedValue(), 1111 * CENT); // we get the bigger coin
+ - ]
525 [ + - + - : 100 : BOOST_CHECK_EQUAL(result20->GetInputSet().size(), 1U);
+ - ]
526 : :
527 : : // but sometimes it's possible, and we use an exact subset (0.4 + 0.6 = 1.0)
528 [ + - ]: 100 : available_coins.Clear();
529 [ + - ]: 100 : add_coin(available_coins, *wallet, CENT * 4 / 10);
530 [ + - ]: 100 : add_coin(available_coins, *wallet, CENT * 6 / 10);
531 [ + - ]: 100 : add_coin(available_coins, *wallet, CENT * 8 / 10);
532 [ + - ]: 100 : add_coin(available_coins, *wallet, 1111 * CENT);
533 [ + - + - ]: 100 : const auto result21 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), CENT, CENT);
534 [ + - + - : 200 : BOOST_CHECK(result21);
+ - ]
535 [ + - + - : 100 : BOOST_CHECK_EQUAL(result21->GetSelectedValue(), CENT); // we should get the exact amount
+ - ]
536 [ + - + - : 100 : BOOST_CHECK_EQUAL(result21->GetInputSet().size(), 2U); // in two coins 0.4+0.6
+ - ]
537 : :
538 : : // test avoiding small change
539 [ + - ]: 100 : available_coins.Clear();
540 [ + - ]: 100 : add_coin(available_coins, *wallet, CENT * 5 / 100);
541 [ + - ]: 100 : add_coin(available_coins, *wallet, CENT * 1);
542 [ + - ]: 100 : add_coin(available_coins, *wallet, CENT * 100);
543 : :
544 : : // trying to make 100.01 from these three coins
545 [ + - + - ]: 100 : const auto result22 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), CENT * 10001 / 100, CENT);
546 [ + - + - : 200 : BOOST_CHECK(result22);
+ - ]
547 [ + - + - : 100 : BOOST_CHECK_EQUAL(result22->GetSelectedValue(), CENT * 10105 / 100); // we should get all coins
+ - ]
548 [ + - + - : 100 : BOOST_CHECK_EQUAL(result22->GetInputSet().size(), 3U);
+ - ]
549 : :
550 : : // but if we try to make 99.9, we should take the bigger of the two small coins to avoid small change
551 [ + - + - ]: 100 : const auto result23 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), CENT * 9990 / 100, CENT);
552 [ + - + - : 200 : BOOST_CHECK(result23);
+ - ]
553 [ + - + - : 100 : BOOST_CHECK_EQUAL(result23->GetSelectedValue(), 101 * CENT);
+ - ]
554 [ + - + - : 100 : BOOST_CHECK_EQUAL(result23->GetInputSet().size(), 2U);
+ - ]
555 : 100 : }
556 : :
557 : : // test with many inputs
558 [ + + ]: 6 : for (CAmount amt=1500; amt < COIN; amt*=10) {
559 [ + - ]: 5 : available_coins.Clear();
560 : : // Create 676 inputs (= (old MAX_STANDARD_TX_SIZE == 100000) / 148 bytes per input)
561 [ + + ]: 3385 : for (uint16_t j = 0; j < 676; j++)
562 [ + - ]: 3380 : add_coin(available_coins, *wallet, amt);
563 : :
564 : : // We only create the wallet once to save time, but we still run the coin selection RUN_TESTS times.
565 [ + + ]: 505 : for (int i = 0; i < RUN_TESTS; i++) {
566 [ + - + - ]: 500 : const auto result24 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 2000, CENT);
567 [ + - + - : 1000 : BOOST_CHECK(result24);
+ + ]
568 : :
569 [ + + ]: 500 : if (amt - 2000 < CENT) {
570 : : // needs more than one input:
571 : 300 : uint16_t returnSize = std::ceil((2000.0 + CENT)/amt);
572 : 300 : CAmount returnValue = amt * returnSize;
573 [ + - + - : 300 : BOOST_CHECK_EQUAL(result24->GetSelectedValue(), returnValue);
+ - ]
574 [ + - + - : 300 : BOOST_CHECK_EQUAL(result24->GetInputSet().size(), returnSize);
+ - ]
575 : : } else {
576 : : // one input is sufficient:
577 [ + - + - : 200 : BOOST_CHECK_EQUAL(result24->GetSelectedValue(), amt);
+ - ]
578 [ + - + - : 500 : BOOST_CHECK_EQUAL(result24->GetInputSet().size(), 1U);
+ - ]
579 : : }
580 : 500 : }
581 : : }
582 : :
583 : : // test randomness
584 : 1 : {
585 [ + - ]: 1 : available_coins.Clear();
586 [ + + ]: 101 : for (int i2 = 0; i2 < 100; i2++)
587 [ + - ]: 100 : add_coin(available_coins, *wallet, COIN);
588 : :
589 : : // Again, we only create the wallet once to save time, but we still run the coin selection RUN_TESTS times.
590 [ + + ]: 101 : for (int i = 0; i < RUN_TESTS; i++) {
591 : : // picking 50 from 100 coins doesn't depend on the shuffle,
592 : : // but does depend on randomness in the stochastic approximation code
593 [ + - + - : 100 : const auto result25 = KnapsackSolver(GroupCoins(available_coins.All()), 50 * COIN, CENT);
+ - ]
594 [ + - + - : 200 : BOOST_CHECK(result25);
+ - ]
595 [ + - + - : 100 : const auto result26 = KnapsackSolver(GroupCoins(available_coins.All()), 50 * COIN, CENT);
+ - ]
596 [ + - + - : 200 : BOOST_CHECK(result26);
+ - ]
597 [ + - + - : 200 : BOOST_CHECK(!EqualResult(*result25, *result26));
+ - ]
598 : :
599 : 100 : int fails = 0;
600 [ + + ]: 600 : for (int j = 0; j < RANDOM_REPEATS; j++)
601 : : {
602 : : // Test that the KnapsackSolver selects randomly from equivalent coins (same value and same input size).
603 : : // When choosing 1 from 100 identical coins, 1% of the time, this test will choose the same coin twice
604 : : // which will cause it to fail.
605 : : // To avoid that issue, run the test RANDOM_REPEATS times and only complain if all of them fail
606 [ + - + - : 500 : const auto result27 = KnapsackSolver(GroupCoins(available_coins.All()), COIN, CENT);
+ - ]
607 [ + - + - : 1000 : BOOST_CHECK(result27);
+ - ]
608 [ + - + - : 500 : const auto result28 = KnapsackSolver(GroupCoins(available_coins.All()), COIN, CENT);
+ - ]
609 [ + - + - : 1000 : BOOST_CHECK(result28);
+ - ]
610 [ + - + + ]: 500 : if (EqualResult(*result27, *result28))
611 : 4 : fails++;
612 : 500 : }
613 [ + - + - ]: 100 : BOOST_CHECK_NE(fails, RANDOM_REPEATS);
614 : 100 : }
615 : :
616 : : // add 75 cents in small change. not enough to make 90 cents,
617 : : // then try making 90 cents. there are multiple competing "smallest bigger" coins,
618 : : // one of which should be picked at random
619 [ + - ]: 1 : add_coin(available_coins, *wallet, 5 * CENT);
620 [ + - ]: 1 : add_coin(available_coins, *wallet, 10 * CENT);
621 [ + - ]: 1 : add_coin(available_coins, *wallet, 15 * CENT);
622 [ + - ]: 1 : add_coin(available_coins, *wallet, 20 * CENT);
623 [ + - ]: 1 : add_coin(available_coins, *wallet, 25 * CENT);
624 : :
625 [ + + ]: 101 : for (int i = 0; i < RUN_TESTS; i++) {
626 : 100 : int fails = 0;
627 [ + + ]: 600 : for (int j = 0; j < RANDOM_REPEATS; j++)
628 : : {
629 [ + - + - : 500 : const auto result29 = KnapsackSolver(GroupCoins(available_coins.All()), 90 * CENT, CENT);
+ - ]
630 [ + - + - : 1000 : BOOST_CHECK(result29);
+ - ]
631 [ + - + - : 500 : const auto result30 = KnapsackSolver(GroupCoins(available_coins.All()), 90 * CENT, CENT);
+ - ]
632 [ + - + - : 1000 : BOOST_CHECK(result30);
+ - ]
633 [ + - + + ]: 500 : if (EqualResult(*result29, *result30))
634 : 6 : fails++;
635 : 500 : }
636 [ + - + - ]: 100 : BOOST_CHECK_NE(fails, RANDOM_REPEATS);
637 : : }
638 : : }
639 [ + - ]: 2 : }
640 : :
641 [ + - + - : 7 : BOOST_AUTO_TEST_CASE(ApproximateBestSubset)
+ - + - -
+ + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- ]
642 : : {
643 : 1 : FastRandomContext rand{};
644 [ + - + - ]: 1 : std::unique_ptr<CWallet> wallet = NewWallet(m_node);
645 : :
646 : 1 : CoinsResult available_coins;
647 : :
648 : : // Test vValue sort order
649 [ + + ]: 1001 : for (int i = 0; i < 1000; i++)
650 [ + - ]: 1000 : add_coin(available_coins, *wallet, 1000 * COIN);
651 [ + - ]: 1 : add_coin(available_coins, *wallet, 3 * COIN);
652 : :
653 [ + - + - ]: 1 : const auto result = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_standard), 1003 * COIN, CENT, rand);
654 [ + - + - : 2 : BOOST_CHECK(result);
+ - ]
655 [ + - + - : 1 : BOOST_CHECK_EQUAL(result->GetSelectedValue(), 1003 * COIN);
+ - ]
656 [ + - + - : 1 : BOOST_CHECK_EQUAL(result->GetInputSet().size(), 2U);
+ - ]
657 [ + - ]: 2 : }
658 : :
659 : : // Tests that with the ideal conditions, the coin selector will always be able to find a solution that can pay the target value
660 [ + - + - : 7 : BOOST_AUTO_TEST_CASE(SelectCoins_test)
+ - + - -
+ + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- ]
661 : : {
662 [ + - ]: 1 : std::unique_ptr<CWallet> wallet = NewWallet(m_node);
663 [ + - ]: 1 : LOCK(wallet->cs_wallet); // Every 'SelectCoins' call requires it
664 : :
665 : : // Random generator stuff
666 : 1 : std::default_random_engine generator;
667 : 1 : std::exponential_distribution<double> distribution (100);
668 : 1 : FastRandomContext rand;
669 : :
670 : : // Run this test 100 times
671 [ + + ]: 101 : for (int i = 0; i < 100; ++i)
672 : : {
673 : 100 : CoinsResult available_coins;
674 : 100 : CAmount balance{0};
675 : :
676 : : // Make a wallet with 1000 exponentially distributed random inputs
677 [ + + ]: 100100 : for (int j = 0; j < 1000; ++j)
678 : : {
679 : 100000 : CAmount val = distribution(generator)*10000000;
680 [ + - ]: 100000 : add_coin(available_coins, *wallet, val);
681 : 100000 : balance += val;
682 : : }
683 : :
684 : : // Generate a random fee rate in the range of 100 - 400
685 : 100 : CFeeRate rate(rand.randrange(300) + 100);
686 : :
687 : : // Generate a random target value between 1000 and wallet balance
688 : 100 : CAmount target = rand.randrange(balance - 1000) + 1000;
689 : :
690 : : // Perform selection
691 [ + - ]: 100 : CoinSelectionParams cs_params{
692 : : rand,
693 : : /*change_output_size=*/ 34,
694 : : /*change_spend_size=*/ 148,
695 : : /*min_change_target=*/ CENT,
696 : 100 : /*effective_feerate=*/ CFeeRate(0),
697 : 100 : /*long_term_feerate=*/ CFeeRate(0),
698 : 100 : /*discard_feerate=*/ CFeeRate(0),
699 : : /*tx_noinputs_size=*/ 0,
700 : : /*avoid_partial=*/ false,
701 [ + - ]: 100 : };
702 : 100 : cs_params.m_cost_of_change = 1;
703 : 100 : cs_params.min_viable_change = 1;
704 [ + - ]: 100 : CCoinControl cc;
705 [ + - ]: 100 : const auto result = SelectCoins(*wallet, available_coins, /*pre_set_inputs=*/{}, target, cc, cs_params);
706 [ + - + - : 200 : BOOST_CHECK(result);
+ - ]
707 [ + - + - : 100 : BOOST_CHECK_GE(result->GetSelectedValue(), target);
+ - ]
708 : 100 : }
709 [ + - + - ]: 3 : }
710 : :
711 [ + - + - : 7 : BOOST_AUTO_TEST_CASE(waste_test)
+ - + - -
+ + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- ]
712 : : {
713 : 1 : const CAmount fee{100};
714 : 1 : const CAmount min_viable_change{300};
715 : 1 : const CAmount change_cost{125};
716 : 1 : const CAmount change_fee{30};
717 : 1 : const CAmount fee_diff{40};
718 : 1 : const CAmount in_amt{3 * COIN};
719 : 1 : const CAmount target{2 * COIN};
720 : 1 : const CAmount excess{80};
721 : 1 : const CAmount exact_target{in_amt - fee * 2}; // Maximum spendable amount after fees: no change, no excess
722 : :
723 : : // In the following, we test that the waste is calculated correctly in various scenarios.
724 : : // Usually, RecalculateWaste would compute change_fee and change_cost on basis of the
725 : : // change output type, current feerate, and discard_feerate, but we use fixed values
726 : : // across this test to make the test easier to understand.
727 : 1 : {
728 : : // Waste with change is the change cost and difference between fee and long term fee
729 [ + - ]: 1 : SelectionResult selection1{target, SelectionAlgorithm::MANUAL};
730 [ + - ]: 1 : add_coin(1 * COIN, 1, selection1, /*fee=*/fee, /*long_term_fee=*/fee - fee_diff);
731 [ + - ]: 1 : add_coin(2 * COIN, 2, selection1, fee, fee - fee_diff);
732 [ + - ]: 1 : selection1.RecalculateWaste(min_viable_change, change_cost, change_fee);
733 [ + - + - : 1 : BOOST_CHECK_EQUAL(fee_diff * 2 + change_cost, selection1.GetWaste());
+ - ]
734 : :
735 : : // Waste will be greater when fee is greater, but long term fee is the same
736 [ + - ]: 1 : SelectionResult selection2{target, SelectionAlgorithm::MANUAL};
737 [ + - ]: 1 : add_coin(1 * COIN, 1, selection2, fee * 2, fee - fee_diff);
738 [ + - ]: 1 : add_coin(2 * COIN, 2, selection2, fee * 2, fee - fee_diff);
739 [ + - ]: 1 : selection2.RecalculateWaste(min_viable_change, change_cost, change_fee);
740 [ + - + - : 1 : BOOST_CHECK_GT(selection2.GetWaste(), selection1.GetWaste());
+ - + - ]
741 : :
742 : : // Waste with change is the change cost and difference between fee and long term fee
743 : : // With long term fee greater than fee, waste should be less than when long term fee is less than fee
744 [ + - ]: 1 : SelectionResult selection3{target, SelectionAlgorithm::MANUAL};
745 [ + - ]: 1 : add_coin(1 * COIN, 1, selection3, fee, fee + fee_diff);
746 [ + - ]: 1 : add_coin(2 * COIN, 2, selection3, fee, fee + fee_diff);
747 [ + - ]: 1 : selection3.RecalculateWaste(min_viable_change, change_cost, change_fee);
748 [ + - + - : 1 : BOOST_CHECK_EQUAL(fee_diff * -2 + change_cost, selection3.GetWaste());
+ - ]
749 [ + - + - : 1 : BOOST_CHECK_LT(selection3.GetWaste(), selection1.GetWaste());
+ - + - ]
750 : 1 : }
751 : :
752 : 1 : {
753 : : // Waste without change is the excess and difference between fee and long term fee
754 [ + - ]: 1 : SelectionResult selection_nochange1{exact_target - excess, SelectionAlgorithm::MANUAL};
755 [ + - ]: 1 : add_coin(1 * COIN, 1, selection_nochange1, fee, fee - fee_diff);
756 [ + - ]: 1 : add_coin(2 * COIN, 2, selection_nochange1, fee, fee - fee_diff);
757 [ + - ]: 1 : selection_nochange1.RecalculateWaste(min_viable_change, change_cost, change_fee);
758 [ + - + - : 1 : BOOST_CHECK_EQUAL(fee_diff * 2 + excess, selection_nochange1.GetWaste());
+ - ]
759 : :
760 : : // Waste without change is the excess and difference between fee and long term fee
761 : : // With long term fee greater than fee, waste should be less than when long term fee is less than fee
762 [ + - ]: 1 : SelectionResult selection_nochange2{exact_target - excess, SelectionAlgorithm::MANUAL};
763 [ + - ]: 1 : add_coin(1 * COIN, 1, selection_nochange2, fee, fee + fee_diff);
764 [ + - ]: 1 : add_coin(2 * COIN, 2, selection_nochange2, fee, fee + fee_diff);
765 [ + - ]: 1 : selection_nochange2.RecalculateWaste(min_viable_change, change_cost, change_fee);
766 [ + - + - : 1 : BOOST_CHECK_EQUAL(fee_diff * -2 + excess, selection_nochange2.GetWaste());
+ - ]
767 [ + - + - : 1 : BOOST_CHECK_LT(selection_nochange2.GetWaste(), selection_nochange1.GetWaste());
+ - + - ]
768 : 1 : }
769 : :
770 : 1 : {
771 : : // Waste with change and fee == long term fee is just cost of change
772 [ + - ]: 1 : SelectionResult selection{target, SelectionAlgorithm::MANUAL};
773 [ + - ]: 1 : add_coin(1 * COIN, 1, selection, fee, fee);
774 [ + - ]: 1 : add_coin(2 * COIN, 2, selection, fee, fee);
775 [ + - ]: 1 : selection.RecalculateWaste(min_viable_change, change_cost, change_fee);
776 [ + - + - : 1 : BOOST_CHECK_EQUAL(change_cost, selection.GetWaste());
+ - ]
777 : 0 : }
778 : :
779 : 1 : {
780 : : // Waste without change and fee == long term fee is just the excess
781 [ + - ]: 1 : SelectionResult selection{exact_target - excess, SelectionAlgorithm::MANUAL};
782 [ + - ]: 1 : add_coin(1 * COIN, 1, selection, fee, fee);
783 [ + - ]: 1 : add_coin(2 * COIN, 2, selection, fee, fee);
784 [ + - ]: 1 : selection.RecalculateWaste(min_viable_change, change_cost, change_fee);
785 [ + - + - : 1 : BOOST_CHECK_EQUAL(excess, selection.GetWaste());
+ - ]
786 : 0 : }
787 : :
788 : 1 : {
789 : : // Waste is 0 when fee == long_term_fee, no change, and no excess
790 [ + - ]: 1 : SelectionResult selection{exact_target, SelectionAlgorithm::MANUAL};
791 [ + - ]: 1 : add_coin(1 * COIN, 1, selection, fee, fee);
792 [ + - ]: 1 : add_coin(2 * COIN, 2, selection, fee, fee);
793 [ + - ]: 1 : selection.RecalculateWaste(min_viable_change, change_cost , change_fee);
794 [ + - + - : 1 : BOOST_CHECK_EQUAL(0, selection.GetWaste());
+ - ]
795 : 0 : }
796 : :
797 : 1 : {
798 : : // Waste is 0 when (fee - long_term_fee) == (-cost_of_change), and no excess
799 [ + - ]: 1 : SelectionResult selection{target, SelectionAlgorithm::MANUAL};
800 [ + - ]: 1 : add_coin(1 * COIN, 1, selection, fee, fee + fee_diff);
801 [ + - ]: 1 : add_coin(2 * COIN, 2, selection, fee, fee + fee_diff);
802 [ + - ]: 1 : selection.RecalculateWaste(min_viable_change, /*change_cost=*/fee_diff * 2, change_fee);
803 [ + - + - : 1 : BOOST_CHECK_EQUAL(0, selection.GetWaste());
+ - ]
804 : 0 : }
805 : :
806 : 1 : {
807 : : // Waste is 0 when (fee - long_term_fee) == (-excess), no change cost
808 : 1 : const CAmount new_target{exact_target - /*excess=*/fee_diff * 2};
809 [ + - ]: 1 : SelectionResult selection{new_target, SelectionAlgorithm::MANUAL};
810 [ + - ]: 1 : add_coin(1 * COIN, 1, selection, fee, fee + fee_diff);
811 [ + - ]: 1 : add_coin(2 * COIN, 2, selection, fee, fee + fee_diff);
812 [ + - ]: 1 : selection.RecalculateWaste(min_viable_change, change_cost, change_fee);
813 [ + - + - : 1 : BOOST_CHECK_EQUAL(0, selection.GetWaste());
+ - ]
814 : 0 : }
815 : :
816 : 1 : {
817 : : // Negative waste when the long term fee is greater than the current fee and the selected value == target
818 [ + - ]: 1 : SelectionResult selection{exact_target, SelectionAlgorithm::MANUAL};
819 : 1 : const CAmount target_waste1{-2 * fee_diff}; // = (2 * fee) - (2 * (fee + fee_diff))
820 [ + - ]: 1 : add_coin(1 * COIN, 1, selection, fee, fee + fee_diff);
821 [ + - ]: 1 : add_coin(2 * COIN, 2, selection, fee, fee + fee_diff);
822 [ + - ]: 1 : selection.RecalculateWaste(min_viable_change, change_cost, change_fee);
823 [ + - + - : 1 : BOOST_CHECK_EQUAL(target_waste1, selection.GetWaste());
+ - ]
824 : 0 : }
825 : :
826 : 1 : {
827 : : // Negative waste when the long term fee is greater than the current fee and change_cost < - (inputs * (fee - long_term_fee))
828 [ + - ]: 1 : SelectionResult selection{target, SelectionAlgorithm::MANUAL};
829 : 1 : const CAmount large_fee_diff{90};
830 : 1 : const CAmount target_waste2{-2 * large_fee_diff + change_cost};
831 : : // = (2 * fee) - (2 * (fee + large_fee_diff)) + change_cost
832 : : // = (2 * 100) - (2 * (100 + 90)) + 125
833 : : // = 200 - 380 + 125 = -55
834 : 1 : assert(target_waste2 == -55);
835 [ + - ]: 1 : add_coin(1 * COIN, 1, selection, fee, fee + large_fee_diff);
836 [ + - ]: 1 : add_coin(2 * COIN, 2, selection, fee, fee + large_fee_diff);
837 [ + - ]: 1 : selection.RecalculateWaste(min_viable_change, change_cost, change_fee);
838 [ + - + - : 1 : BOOST_CHECK_EQUAL(target_waste2, selection.GetWaste());
+ - ]
839 : 1 : }
840 : 1 : }
841 : :
842 : :
843 [ + - + - : 7 : BOOST_AUTO_TEST_CASE(bump_fee_test)
+ - + - -
+ + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- ]
844 : : {
845 : 1 : const CAmount fee{100};
846 : 1 : const CAmount min_viable_change{200};
847 : 1 : const CAmount change_cost{125};
848 : 1 : const CAmount change_fee{35};
849 : 1 : const CAmount fee_diff{40};
850 : 1 : const CAmount target{2 * COIN};
851 : :
852 : 1 : {
853 [ + - ]: 1 : SelectionResult selection{target, SelectionAlgorithm::MANUAL};
854 [ + - ]: 1 : add_coin(1 * COIN, 1, selection, /*fee=*/fee, /*long_term_fee=*/fee + fee_diff);
855 [ + - ]: 1 : add_coin(2 * COIN, 2, selection, fee, fee + fee_diff);
856 [ + - ]: 1 : const std::vector<std::shared_ptr<COutput>> inputs = selection.GetShuffledInputVector();
857 : :
858 [ - + + + ]: 3 : for (size_t i = 0; i < inputs.size(); ++i) {
859 : 2 : inputs[i]->ApplyBumpFee(20*(i+1));
860 : : }
861 : :
862 [ + - ]: 1 : selection.RecalculateWaste(min_viable_change, change_cost, change_fee);
863 : 1 : CAmount expected_waste = fee_diff * -2 + change_cost + /*bump_fees=*/60;
864 [ + - + - : 1 : BOOST_CHECK_EQUAL(expected_waste, selection.GetWaste());
+ - ]
865 : :
866 [ + - ]: 1 : selection.SetBumpFeeDiscount(30);
867 [ + - ]: 1 : selection.RecalculateWaste(min_viable_change, change_cost, change_fee);
868 : 1 : expected_waste = fee_diff * -2 + change_cost + /*bump_fees=*/60 - /*group_discount=*/30;
869 [ + - + - : 1 : BOOST_CHECK_EQUAL(expected_waste, selection.GetWaste());
+ - ]
870 : 1 : }
871 : :
872 : 1 : {
873 : : // Test with changeless transaction
874 : : //
875 : : // Bump fees and excess both contribute fully to the waste score,
876 : : // therefore, a bump fee group discount will not change the waste
877 : : // score as long as we do not create change in both instances.
878 : 1 : CAmount changeless_target = 3 * COIN - 2 * fee - 100;
879 [ + - ]: 1 : SelectionResult selection{changeless_target, SelectionAlgorithm::MANUAL};
880 [ + - ]: 1 : add_coin(1 * COIN, 1, selection, /*fee=*/fee, /*long_term_fee=*/fee + fee_diff);
881 [ + - ]: 1 : add_coin(2 * COIN, 2, selection, fee, fee + fee_diff);
882 [ + - ]: 1 : const std::vector<std::shared_ptr<COutput>> inputs = selection.GetShuffledInputVector();
883 : :
884 [ - + + + ]: 3 : for (size_t i = 0; i < inputs.size(); ++i) {
885 : 2 : inputs[i]->ApplyBumpFee(20*(i+1));
886 : : }
887 : :
888 [ + - ]: 1 : selection.RecalculateWaste(min_viable_change, change_cost, change_fee);
889 : 1 : CAmount expected_waste = fee_diff * -2 + /*bump_fees=*/60 + /*excess = 100 - bump_fees*/40;
890 [ + - + - : 1 : BOOST_CHECK_EQUAL(expected_waste, selection.GetWaste());
+ - ]
891 : :
892 [ + - ]: 1 : selection.SetBumpFeeDiscount(30);
893 [ + - ]: 1 : selection.RecalculateWaste(min_viable_change, change_cost, change_fee);
894 : 1 : expected_waste = fee_diff * -2 + /*bump_fees=*/60 - /*group_discount=*/30 + /*excess = 100 - bump_fees + group_discount*/70;
895 [ + - + - : 1 : BOOST_CHECK_EQUAL(expected_waste, selection.GetWaste());
+ - ]
896 : 1 : }
897 : 1 : }
898 : :
899 [ + - + - : 7 : BOOST_AUTO_TEST_CASE(effective_value_test)
+ - + - -
+ + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- ]
900 : : {
901 : 1 : const int input_bytes = 148;
902 : 1 : const CFeeRate feerate(1000);
903 : 1 : const CAmount nValue = 10000;
904 : 1 : const int nInput = 0;
905 : :
906 : 1 : CMutableTransaction tx;
907 [ + - ]: 1 : tx.vout.resize(1);
908 [ + - ]: 1 : tx.vout[nInput].nValue = nValue;
909 : :
910 : : // standard case, pass feerate in constructor
911 [ + - + - : 1 : COutput output1(COutPoint(tx.GetHash(), nInput), tx.vout.at(nInput), /*depth=*/1, input_bytes, /*solvable=*/true, /*safe=*/true, /*time=*/0, /*from_me=*/false, feerate);
+ - ]
912 : 1 : const CAmount expected_ev1 = 9852; // 10000 - 148
913 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(output1.GetEffectiveValue(), expected_ev1);
914 : :
915 : : // input bytes unknown (input_bytes = -1), pass feerate in constructor
916 [ + - + - : 1 : COutput output2(COutPoint(tx.GetHash(), nInput), tx.vout.at(nInput), /*depth=*/1, /*input_bytes=*/-1, /*solvable=*/true, /*safe=*/true, /*time=*/0, /*from_me=*/ false, feerate);
+ - ]
917 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(output2.GetEffectiveValue(), nValue); // The effective value should be equal to the absolute value if input_bytes is -1
918 : :
919 : : // negative effective value, pass feerate in constructor
920 [ + - + - : 1 : COutput output3(COutPoint(tx.GetHash(), nInput), tx.vout.at(nInput), /*depth=*/1, input_bytes, /*solvable=*/true, /*safe=*/true, /*time=*/0, /*from_me=*/false, CFeeRate(100000));
+ - ]
921 : 1 : const CAmount expected_ev3 = -4800; // 10000 - 14800
922 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(output3.GetEffectiveValue(), expected_ev3);
923 : :
924 : : // standard case, pass fees in constructor
925 : 1 : const CAmount fees = 148;
926 [ + - + - : 1 : COutput output4(COutPoint(tx.GetHash(), nInput), tx.vout.at(nInput), /*depth=*/1, input_bytes, /*solvable=*/true, /*safe=*/true, /*time=*/0, /*from_me=*/false, fees);
+ - ]
927 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(output4.GetEffectiveValue(), expected_ev1);
928 : :
929 : : // input bytes unknown (input_bytes = -1), pass fees in constructor
930 [ + - + - : 1 : COutput output5(COutPoint(tx.GetHash(), nInput), tx.vout.at(nInput), /*depth=*/1, /*input_bytes=*/-1, /*solvable=*/true, /*safe=*/true, /*time=*/0, /*from_me=*/false, /*fees=*/0);
+ - ]
931 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(output5.GetEffectiveValue(), nValue); // The effective value should be equal to the absolute value if input_bytes is -1
932 : 2 : }
933 : :
934 : 9 : static util::Result<SelectionResult> CoinGrinder(const CAmount& target,
935 : : const CoinSelectionParams& cs_params,
936 : : const node::NodeContext& m_node,
937 : : int max_selection_weight,
938 : : std::function<CoinsResult(CWallet&)> coin_setup)
939 : : {
940 [ + - ]: 9 : std::unique_ptr<CWallet> wallet = NewWallet(m_node);
941 [ + - ]: 9 : CoinEligibilityFilter filter(0, 0, 0); // accept all coins without ancestors
942 [ + - + - : 18 : Groups group = GroupOutputs(*wallet, coin_setup(*wallet), cs_params, {{filter}})[filter].all_groups;
+ - + - +
- + - ]
943 [ + - ]: 9 : return CoinGrinder(group.positive_group, target, cs_params.m_min_change_target, max_selection_weight);
944 [ + - ]: 18 : }
945 : :
946 [ + - + - : 7 : BOOST_AUTO_TEST_CASE(coin_grinder_tests)
+ - + - -
+ + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- ]
947 : : {
948 : : // Test Coin Grinder:
949 : : // 1) Insufficient funds, select all provided coins and fail.
950 : : // 2) Exceeded max weight, coin selection always surpasses the max allowed weight.
951 : : // 3) Select coins without surpassing the max weight (some coins surpasses the max allowed weight, some others not)
952 : : // 4) Test that two less valuable UTXOs with a combined lower weight are preferred over a more valuable heavier UTXO
953 : : // 5) Test finding a solution in a UTXO pool with mixed weights
954 : : // 6) Test that the lightest solution among many clones is found
955 : : // 7) Test that lots of tiny UTXOs can be skipped if they are too heavy while there are enough funds in lookahead
956 : :
957 : 1 : FastRandomContext rand;
958 [ + - ]: 1 : CoinSelectionParams dummy_params{ // Only used to provide the 'avoid_partial' flag.
959 : : rand,
960 : : /*change_output_size=*/34,
961 : : /*change_spend_size=*/68,
962 : : /*min_change_target=*/CENT,
963 : 1 : /*effective_feerate=*/CFeeRate(5000),
964 : 1 : /*long_term_feerate=*/CFeeRate(2000),
965 : 1 : /*discard_feerate=*/CFeeRate(1000),
966 : : /*tx_noinputs_size=*/10 + 34, // static header size + output size
967 : : /*avoid_partial=*/false,
968 [ + - ]: 1 : };
969 : :
970 : 1 : {
971 : : // #########################################################
972 : : // 1) Insufficient funds, select all provided coins and fail
973 : : // #########################################################
974 : 1 : CAmount target = 49.5L * COIN;
975 : 1 : int max_selection_weight = 10'000; // high enough to not fail for this reason.
976 [ + - ]: 2 : const auto& res = CoinGrinder(target, dummy_params, m_node, max_selection_weight, [&](CWallet& wallet) {
977 : 1 : CoinsResult available_coins;
978 [ + + ]: 11 : for (int j = 0; j < 10; ++j) {
979 [ + - ]: 10 : add_coin(available_coins, wallet, CAmount(1 * COIN));
980 [ + - ]: 10 : add_coin(available_coins, wallet, CAmount(2 * COIN));
981 : : }
982 : 1 : return available_coins;
983 [ + - ]: 1 : });
984 [ + - + - : 2 : BOOST_CHECK(!res);
+ - ]
985 [ + - + - : 3 : BOOST_CHECK(util::ErrorString(res).empty()); // empty means "insufficient funds"
+ - ]
986 : 0 : }
987 : :
988 : 1 : {
989 : : // ###########################
990 : : // 2) Test max weight exceeded
991 : : // ###########################
992 : 1 : CAmount target = 29.5L * COIN;
993 : 1 : int max_selection_weight = 3000;
994 [ + - ]: 2 : const auto& res = CoinGrinder(target, dummy_params, m_node, max_selection_weight, [&](CWallet& wallet) {
995 : 1 : CoinsResult available_coins;
996 [ + + ]: 11 : for (int j = 0; j < 10; ++j) {
997 [ + - ]: 10 : add_coin(available_coins, wallet, CAmount(1 * COIN), CFeeRate(5000), 144, false, 0, true);
998 [ + - ]: 10 : add_coin(available_coins, wallet, CAmount(2 * COIN), CFeeRate(5000), 144, false, 0, true);
999 : : }
1000 : 1 : return available_coins;
1001 [ + - ]: 1 : });
1002 [ + - + - : 2 : BOOST_CHECK(!res);
+ - ]
1003 [ + - + - : 3 : BOOST_CHECK(util::ErrorString(res).original.find("The inputs size exceeds the maximum weight") != std::string::npos);
+ - ]
1004 : 0 : }
1005 : :
1006 : 1 : {
1007 : : // ###############################################################################################################
1008 : : // 3) Test that the lowest-weight solution is found when some combinations would exceed the allowed weight
1009 : : // ################################################################################################################
1010 : 1 : CAmount target = 25.33L * COIN;
1011 : 1 : int max_selection_weight = 10'000; // WU
1012 [ + - ]: 2 : const auto& res = CoinGrinder(target, dummy_params, m_node, max_selection_weight, [&](CWallet& wallet) {
1013 : 1 : CoinsResult available_coins;
1014 [ + + ]: 61 : for (int j = 0; j < 60; ++j) { // 60 UTXO --> 19,8 BTC total --> 60 × 272 WU = 16320 WU
1015 [ + - ]: 60 : add_coin(available_coins, wallet, CAmount(0.33 * COIN), CFeeRate(5000), 144, false, 0, true);
1016 : : }
1017 [ + + ]: 11 : for (int i = 0; i < 10; i++) { // 10 UTXO --> 20 BTC total --> 10 × 272 WU = 2720 WU
1018 [ + - ]: 10 : add_coin(available_coins, wallet, CAmount(2 * COIN), CFeeRate(5000), 144, false, 0, true);
1019 : : }
1020 : 1 : return available_coins;
1021 [ + - ]: 1 : });
1022 : 1 : SelectionResult expected_result(CAmount(0), SelectionAlgorithm::CG);
1023 [ + + ]: 11 : for (int i = 0; i < 10; ++i) {
1024 [ + - ]: 10 : add_coin(2 * COIN, i, expected_result);
1025 : : }
1026 [ + + ]: 18 : for (int j = 0; j < 17; ++j) {
1027 [ + - ]: 17 : add_coin(0.33 * COIN, j + 10, expected_result);
1028 : : }
1029 [ + - + - : 2 : BOOST_CHECK(EquivalentResult(expected_result, *res));
+ - + - ]
1030 : : // Demonstrate how following improvements reduce iteration count and catch any regressions in the future.
1031 : 1 : size_t expected_attempts = 37;
1032 [ + - + - : 2 : BOOST_CHECK_MESSAGE(res->GetSelectionsEvaluated() == expected_attempts, strprintf("Expected %i attempts, but got %i", expected_attempts, res->GetSelectionsEvaluated()));
+ - + - +
- ]
1033 : 1 : }
1034 : :
1035 : 1 : {
1036 : : // #################################################################################################################
1037 : : // 4) Test that two less valuable UTXOs with a combined lower weight are preferred over a more valuable heavier UTXO
1038 : : // #################################################################################################################
1039 : 1 : CAmount target = 1.9L * COIN;
1040 : 1 : int max_selection_weight = 400'000; // WU
1041 [ + - ]: 2 : const auto& res = CoinGrinder(target, dummy_params, m_node, max_selection_weight, [&](CWallet& wallet) {
1042 [ + - ]: 1 : CoinsResult available_coins;
1043 [ + - ]: 1 : add_coin(available_coins, wallet, CAmount(2 * COIN), CFeeRate(5000), 144, false, 0, true, 148);
1044 [ + - ]: 1 : add_coin(available_coins, wallet, CAmount(1 * COIN), CFeeRate(5000), 144, false, 0, true, 68);
1045 [ + - ]: 1 : add_coin(available_coins, wallet, CAmount(1 * COIN), CFeeRate(5000), 144, false, 0, true, 68);
1046 : 1 : return available_coins;
1047 [ + - ]: 1 : });
1048 [ + - ]: 1 : SelectionResult expected_result(CAmount(0), SelectionAlgorithm::CG);
1049 [ + - ]: 1 : add_coin(1 * COIN, 1, expected_result);
1050 [ + - ]: 1 : add_coin(1 * COIN, 2, expected_result);
1051 [ + - + - : 2 : BOOST_CHECK(EquivalentResult(expected_result, *res));
+ - + - ]
1052 : : // Demonstrate how following improvements reduce iteration count and catch any regressions in the future.
1053 : 1 : size_t expected_attempts = 3;
1054 [ + - + - : 2 : BOOST_CHECK_MESSAGE(res->GetSelectionsEvaluated() == expected_attempts, strprintf("Expected %i attempts, but got %i", expected_attempts, res->GetSelectionsEvaluated()));
+ - + - +
- ]
1055 : 1 : }
1056 : :
1057 : 1 : {
1058 : : // ###############################################################################################################
1059 : : // 5) Test finding a solution in a UTXO pool with mixed weights
1060 : : // ################################################################################################################
1061 : 1 : CAmount target = 30L * COIN;
1062 : 1 : int max_selection_weight = 400'000; // WU
1063 [ + - ]: 2 : const auto& res = CoinGrinder(target, dummy_params, m_node, max_selection_weight, [&](CWallet& wallet) {
1064 : 1 : CoinsResult available_coins;
1065 [ + + ]: 6 : for (int j = 0; j < 5; ++j) {
1066 : : // Add heavy coins {3, 6, 9, 12, 15}
1067 [ + - ]: 5 : add_coin(available_coins, wallet, CAmount((3 + 3 * j) * COIN), CFeeRate(5000), 144, false, 0, true, 350);
1068 : : // Add medium coins {2, 5, 8, 11, 14}
1069 [ + - ]: 5 : add_coin(available_coins, wallet, CAmount((2 + 3 * j) * COIN), CFeeRate(5000), 144, false, 0, true, 250);
1070 : : // Add light coins {1, 4, 7, 10, 13}
1071 [ + - ]: 5 : add_coin(available_coins, wallet, CAmount((1 + 3 * j) * COIN), CFeeRate(5000), 144, false, 0, true, 150);
1072 : : }
1073 : 1 : return available_coins;
1074 [ + - ]: 1 : });
1075 [ + - + - : 2 : BOOST_CHECK(res);
+ - ]
1076 [ + - ]: 1 : SelectionResult expected_result(CAmount(0), SelectionAlgorithm::CG);
1077 [ + - ]: 1 : add_coin(14 * COIN, 1, expected_result);
1078 [ + - ]: 1 : add_coin(13 * COIN, 2, expected_result);
1079 [ + - ]: 1 : add_coin(4 * COIN, 3, expected_result);
1080 [ + - + - : 2 : BOOST_CHECK(EquivalentResult(expected_result, *res));
+ - + - ]
1081 : : // Demonstrate how following improvements reduce iteration count and catch any regressions in the future.
1082 : 1 : size_t expected_attempts = 92;
1083 [ + - + - : 2 : BOOST_CHECK_MESSAGE(res->GetSelectionsEvaluated() == expected_attempts, strprintf("Expected %i attempts, but got %i", expected_attempts, res->GetSelectionsEvaluated()));
+ - + - +
- ]
1084 : 1 : }
1085 : :
1086 : 1 : {
1087 : : // #################################################################################################################
1088 : : // 6) Test that the lightest solution among many clones is found
1089 : : // #################################################################################################################
1090 : 1 : CAmount target = 9.9L * COIN;
1091 : 1 : int max_selection_weight = 400'000; // WU
1092 [ + - ]: 2 : const auto& res = CoinGrinder(target, dummy_params, m_node, max_selection_weight, [&](CWallet& wallet) {
1093 [ + - ]: 1 : CoinsResult available_coins;
1094 : : // Expected Result: 4 + 3 + 2 + 1 = 10 BTC at 400 vB
1095 [ + - ]: 1 : add_coin(available_coins, wallet, CAmount(4 * COIN), CFeeRate(5000), 144, false, 0, true, 100);
1096 [ + - ]: 1 : add_coin(available_coins, wallet, CAmount(3 * COIN), CFeeRate(5000), 144, false, 0, true, 100);
1097 [ + - ]: 1 : add_coin(available_coins, wallet, CAmount(2 * COIN), CFeeRate(5000), 144, false, 0, true, 100);
1098 [ + - ]: 1 : add_coin(available_coins, wallet, CAmount(1 * COIN), CFeeRate(5000), 144, false, 0, true, 100);
1099 : : // Distracting clones:
1100 [ + + ]: 101 : for (int j = 0; j < 100; ++j) {
1101 [ + - ]: 100 : add_coin(available_coins, wallet, CAmount(8 * COIN), CFeeRate(5000), 144, false, 0, true, 1000);
1102 : : }
1103 [ + + ]: 101 : for (int j = 0; j < 100; ++j) {
1104 [ + - ]: 100 : add_coin(available_coins, wallet, CAmount(7 * COIN), CFeeRate(5000), 144, false, 0, true, 800);
1105 : : }
1106 [ + + ]: 101 : for (int j = 0; j < 100; ++j) {
1107 [ + - ]: 100 : add_coin(available_coins, wallet, CAmount(6 * COIN), CFeeRate(5000), 144, false, 0, true, 600);
1108 : : }
1109 [ + + ]: 101 : for (int j = 0; j < 100; ++j) {
1110 [ + - ]: 100 : add_coin(available_coins, wallet, CAmount(5 * COIN), CFeeRate(5000), 144, false, 0, true, 400);
1111 : : }
1112 : 1 : return available_coins;
1113 [ + - ]: 1 : });
1114 [ + - ]: 1 : SelectionResult expected_result(CAmount(0), SelectionAlgorithm::CG);
1115 [ + - ]: 1 : add_coin(4 * COIN, 0, expected_result);
1116 [ + - ]: 1 : add_coin(3 * COIN, 0, expected_result);
1117 [ + - ]: 1 : add_coin(2 * COIN, 0, expected_result);
1118 [ + - ]: 1 : add_coin(1 * COIN, 0, expected_result);
1119 [ + - + - : 2 : BOOST_CHECK(EquivalentResult(expected_result, *res));
+ - + - ]
1120 : : // Demonstrate how following improvements reduce iteration count and catch any regressions in the future.
1121 : 1 : size_t expected_attempts = 38;
1122 [ + - + - : 2 : BOOST_CHECK_MESSAGE(res->GetSelectionsEvaluated() == expected_attempts, strprintf("Expected %i attempts, but got %i", expected_attempts, res->GetSelectionsEvaluated()));
+ - + - +
- ]
1123 : 1 : }
1124 : :
1125 : 1 : {
1126 : : // #################################################################################################################
1127 : : // 7) Test that lots of tiny UTXOs can be skipped if they are too heavy while there are enough funds in lookahead
1128 : : // #################################################################################################################
1129 : 1 : CAmount target = 1.9L * COIN;
1130 : 1 : int max_selection_weight = 40000; // WU
1131 [ + - ]: 2 : const auto& res = CoinGrinder(target, dummy_params, m_node, max_selection_weight, [&](CWallet& wallet) {
1132 [ + - ]: 1 : CoinsResult available_coins;
1133 [ + - ]: 1 : add_coin(available_coins, wallet, CAmount(1.8 * COIN), CFeeRate(5000), 144, false, 0, true, 2500);
1134 [ + - ]: 1 : add_coin(available_coins, wallet, CAmount(1 * COIN), CFeeRate(5000), 144, false, 0, true, 1000);
1135 [ + - ]: 1 : add_coin(available_coins, wallet, CAmount(1 * COIN), CFeeRate(5000), 144, false, 0, true, 1000);
1136 [ + + ]: 101 : for (int j = 0; j < 100; ++j) {
1137 : : // make a 100 unique coins only differing by one sat
1138 [ + - ]: 100 : add_coin(available_coins, wallet, CAmount(0.01 * COIN + j), CFeeRate(5000), 144, false, 0, true, 110);
1139 : : }
1140 : 1 : return available_coins;
1141 [ + - ]: 1 : });
1142 [ + - ]: 1 : SelectionResult expected_result(CAmount(0), SelectionAlgorithm::CG);
1143 [ + - ]: 1 : add_coin(1 * COIN, 1, expected_result);
1144 [ + - ]: 1 : add_coin(1 * COIN, 2, expected_result);
1145 [ + - + - : 2 : BOOST_CHECK(EquivalentResult(expected_result, *res));
+ - + - ]
1146 : : // Demonstrate how following improvements reduce iteration count and catch any regressions in the future.
1147 : 1 : size_t expected_attempts = 7;
1148 [ + - + - : 2 : BOOST_CHECK_MESSAGE(res->GetSelectionsEvaluated() == expected_attempts, strprintf("Expected %i attempts, but got %i", expected_attempts, res->GetSelectionsEvaluated()));
+ - + - +
- ]
1149 : 1 : }
1150 : :
1151 : 1 : {
1152 : : // #################################################################################################################
1153 : : // 8) Test input set that has a solution will not find a solution before reaching the attempt limit
1154 : : // #################################################################################################################
1155 : 1 : CAmount target = 8 * COIN;
1156 : 1 : int max_selection_weight = 3200; // WU
1157 : 1 : dummy_params.m_min_change_target = 0;
1158 [ + - ]: 2 : const auto& result_a = CoinGrinder(target, dummy_params, m_node, max_selection_weight, [&](CWallet& wallet) {
1159 : 1 : CoinsResult doppelgangers;
1160 [ + + ]: 19 : for (int i = 0; i < 18; ++i) {
1161 [ + - ]: 18 : add_coin(doppelgangers, wallet, CAmount(1 * COIN + i), CFeeRate(0), 144, false, 0, true, 96 + i);
1162 : : }
1163 : 1 : return doppelgangers;
1164 [ + - ]: 1 : });
1165 [ + - + - ]: 2 : BOOST_CHECK(result_a);
1166 : 1 : SelectionResult expected_result(CAmount(0), SelectionAlgorithm::CG);
1167 [ + + ]: 9 : for (int i = 0; i < 8; ++i) {
1168 [ + - ]: 8 : add_coin(1 * COIN + i, 0, expected_result);
1169 : : }
1170 [ + - + - : 2 : BOOST_CHECK(EquivalentResult(expected_result, *result_a));
+ - + - ]
1171 : : // Demonstrate a solution is found before the attempts limit is reached.
1172 : 1 : size_t expected_attempts = 87'525;
1173 [ + - + - : 2 : BOOST_CHECK_MESSAGE(result_a->GetSelectionsEvaluated() == expected_attempts, strprintf("Expected %i attempts, but got %i", expected_attempts, result_a->GetSelectionsEvaluated()));
+ - + - +
- ]
1174 : :
1175 : : // Adding one more doppelganger causes the attempt limit to be reached before finding a solution.
1176 [ + - ]: 2 : const auto& result_b = CoinGrinder(target, dummy_params, m_node, max_selection_weight, [&](CWallet& wallet) {
1177 : 1 : CoinsResult doppelgangers;
1178 [ + + ]: 20 : for (int i = 0; i < 19; ++i) {
1179 [ + - ]: 19 : add_coin(doppelgangers, wallet, CAmount(1 * COIN + i), CFeeRate(0), 144, false, 0, true, 96 + i);
1180 : : }
1181 : 1 : return doppelgangers;
1182 [ + - ]: 2 : });
1183 [ + - + - ]: 2 : BOOST_CHECK(!result_b);
1184 : 1 : }
1185 : 1 : }
1186 : :
1187 : 3 : static util::Result<SelectionResult> SelectCoinsSRD(const CAmount& target,
1188 : : const CoinSelectionParams& cs_params,
1189 : : const node::NodeContext& m_node,
1190 : : int max_selection_weight,
1191 : : std::function<CoinsResult(CWallet&)> coin_setup)
1192 : : {
1193 [ + - ]: 3 : std::unique_ptr<CWallet> wallet = NewWallet(m_node);
1194 [ + - ]: 3 : CoinEligibilityFilter filter(0, 0, 0); // accept all coins without ancestors
1195 [ + - + - : 6 : Groups group = GroupOutputs(*wallet, coin_setup(*wallet), cs_params, {{filter}})[filter].all_groups;
+ - + - +
- + - ]
1196 [ + - ]: 3 : return SelectCoinsSRD(group.positive_group, target, cs_params.m_change_fee, cs_params.rng_fast, max_selection_weight);
1197 [ + - ]: 6 : }
1198 : :
1199 [ + - + - : 7 : BOOST_AUTO_TEST_CASE(srd_tests)
+ - + - -
+ + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- ]
1200 : : {
1201 : : // Test SRD:
1202 : : // 1) Insufficient funds, select all provided coins and fail.
1203 : : // 2) Exceeded max weight, coin selection always surpasses the max allowed weight.
1204 : : // 3) Select coins without surpassing the max weight (some coins surpasses the max allowed weight, some others not)
1205 : :
1206 : 1 : FastRandomContext rand;
1207 [ + - ]: 1 : CoinSelectionParams dummy_params{ // Only used to provide the 'avoid_partial' flag.
1208 : : rand,
1209 : : /*change_output_size=*/34,
1210 : : /*change_spend_size=*/68,
1211 : : /*min_change_target=*/CENT,
1212 : 1 : /*effective_feerate=*/CFeeRate(0),
1213 : 1 : /*long_term_feerate=*/CFeeRate(0),
1214 : 1 : /*discard_feerate=*/CFeeRate(0),
1215 : : /*tx_noinputs_size=*/10 + 34, // static header size + output size
1216 : : /*avoid_partial=*/false,
1217 [ + - ]: 1 : };
1218 : :
1219 : 1 : {
1220 : : // #########################################################
1221 : : // 1) Insufficient funds, select all provided coins and fail
1222 : : // #########################################################
1223 : 1 : CAmount target = 49.5L * COIN;
1224 : 1 : int max_selection_weight = 10000; // high enough to not fail for this reason.
1225 [ + - ]: 2 : const auto& res = SelectCoinsSRD(target, dummy_params, m_node, max_selection_weight, [&](CWallet& wallet) {
1226 : 1 : CoinsResult available_coins;
1227 [ + + ]: 11 : for (int j = 0; j < 10; ++j) {
1228 [ + - ]: 10 : add_coin(available_coins, wallet, CAmount(1 * COIN));
1229 [ + - ]: 10 : add_coin(available_coins, wallet, CAmount(2 * COIN));
1230 : : }
1231 : 1 : return available_coins;
1232 [ + - ]: 1 : });
1233 [ + - + - : 2 : BOOST_CHECK(!res);
+ - ]
1234 [ + - + - : 3 : BOOST_CHECK(util::ErrorString(res).empty()); // empty means "insufficient funds"
+ - ]
1235 : 0 : }
1236 : :
1237 : 1 : {
1238 : : // ###########################
1239 : : // 2) Test max weight exceeded
1240 : : // ###########################
1241 : 1 : CAmount target = 49.5L * COIN;
1242 : 1 : int max_selection_weight = 3000;
1243 [ + - ]: 2 : const auto& res = SelectCoinsSRD(target, dummy_params, m_node, max_selection_weight, [&](CWallet& wallet) {
1244 : 1 : CoinsResult available_coins;
1245 [ + + ]: 11 : for (int j = 0; j < 10; ++j) {
1246 : : /* 10 × 1 BTC + 10 × 2 BTC = 30 BTC. 20 × 272 WU = 5440 WU */
1247 [ + - ]: 10 : add_coin(available_coins, wallet, CAmount(1 * COIN), CFeeRate(0), 144, false, 0, true);
1248 [ + - ]: 10 : add_coin(available_coins, wallet, CAmount(2 * COIN), CFeeRate(0), 144, false, 0, true);
1249 : : }
1250 : 1 : return available_coins;
1251 [ + - ]: 1 : });
1252 [ + - + - : 2 : BOOST_CHECK(!res);
+ - ]
1253 [ + - + - : 3 : BOOST_CHECK(util::ErrorString(res).original.find("The inputs size exceeds the maximum weight") != std::string::npos);
+ - ]
1254 : 0 : }
1255 : :
1256 : 1 : {
1257 : : // ################################################################################################################
1258 : : // 3) Test that SRD result does not exceed the max weight
1259 : : // ################################################################################################################
1260 : 1 : CAmount target = 25.33L * COIN;
1261 : 1 : int max_selection_weight = 10000; // WU
1262 [ + - ]: 2 : const auto& res = SelectCoinsSRD(target, dummy_params, m_node, max_selection_weight, [&](CWallet& wallet) {
1263 : 1 : CoinsResult available_coins;
1264 [ + + ]: 61 : for (int j = 0; j < 60; ++j) { // 60 UTXO --> 19,8 BTC total --> 60 × 272 WU = 16320 WU
1265 [ + - ]: 60 : add_coin(available_coins, wallet, CAmount(0.33 * COIN), CFeeRate(0), 144, false, 0, true);
1266 : : }
1267 [ + + ]: 11 : for (int i = 0; i < 10; i++) { // 10 UTXO --> 20 BTC total --> 10 × 272 WU = 2720 WU
1268 [ + - ]: 10 : add_coin(available_coins, wallet, CAmount(2 * COIN), CFeeRate(0), 144, false, 0, true);
1269 : : }
1270 : 1 : return available_coins;
1271 [ + - ]: 2 : });
1272 [ + - + - : 2 : BOOST_CHECK(res);
+ - ]
1273 [ + - + - ]: 2 : BOOST_CHECK(res->GetWeight() <= max_selection_weight);
1274 : : }
1275 : 1 : }
1276 : :
1277 : 3 : static util::Result<SelectionResult> select_coins(const CAmount& target, const CoinSelectionParams& cs_params, const CCoinControl& cc, std::function<CoinsResult(CWallet&)> coin_setup, const node::NodeContext& m_node)
1278 : : {
1279 [ + - ]: 3 : std::unique_ptr<CWallet> wallet = NewWallet(m_node);
1280 [ + - ]: 3 : auto available_coins = coin_setup(*wallet);
1281 : :
1282 [ + - ]: 3 : LOCK(wallet->cs_wallet);
1283 [ + - ]: 3 : auto result = SelectCoins(*wallet, available_coins, /*pre_set_inputs=*/ {}, target, cc, cs_params);
1284 [ + + ]: 3 : if (result) {
1285 [ + - + - ]: 2 : const auto signedTxSize = 10 + 34 + 68 * result->GetInputSet().size(); // static header size + output size + inputs size (P2WPKH)
1286 [ + - + - ]: 2 : BOOST_CHECK_LE(signedTxSize * WITNESS_SCALE_FACTOR, MAX_STANDARD_TX_WEIGHT);
1287 : :
1288 [ + - + - : 2 : BOOST_CHECK_GE(result->GetSelectedValue(), target);
+ - ]
1289 : : }
1290 [ + - ]: 3 : return result;
1291 [ + - ]: 6 : }
1292 : :
1293 : 3 : static bool has_coin(const OutputSet& set, CAmount amount)
1294 : : {
1295 [ + + ]: 143 : return std::any_of(set.begin(), set.end(), [&](const auto& coin) { return coin->GetEffectiveValue() == amount; });
1296 : : }
1297 : :
1298 [ + - + - : 7 : BOOST_AUTO_TEST_CASE(check_max_selection_weight)
+ - + - -
+ + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- ]
1299 : : {
1300 : 1 : const CAmount target = 49.5L * COIN;
1301 : 1 : CCoinControl cc;
1302 : :
1303 : 1 : FastRandomContext rand;
1304 [ + - ]: 1 : CoinSelectionParams cs_params{
1305 : : rand,
1306 : : /*change_output_size=*/34,
1307 : : /*change_spend_size=*/68,
1308 : : /*min_change_target=*/CENT,
1309 : 1 : /*effective_feerate=*/CFeeRate(0),
1310 : 1 : /*long_term_feerate=*/CFeeRate(0),
1311 : 1 : /*discard_feerate=*/CFeeRate(0),
1312 : : /*tx_noinputs_size=*/10 + 34, // static header size + output size
1313 : : /*avoid_partial=*/false,
1314 [ + - ]: 1 : };
1315 : :
1316 : 1 : int max_weight = MAX_STANDARD_TX_WEIGHT - WITNESS_SCALE_FACTOR * (cs_params.tx_noinputs_size + cs_params.change_output_size);
1317 : 1 : {
1318 : : // Scenario 1:
1319 : : // The actor starts with 1x 50.0 BTC and 1515x 0.033 BTC (~100.0 BTC total) unspent outputs
1320 : : // Then tries to spend 49.5 BTC
1321 : : // The 50.0 BTC output should be selected, because the transaction would otherwise be too large
1322 : :
1323 : : // Perform selection
1324 : :
1325 : 1 : const auto result = select_coins(
1326 [ + - ]: 2 : target, cs_params, cc, [&](CWallet& wallet) {
1327 : 1 : CoinsResult available_coins;
1328 [ + + ]: 1516 : for (int j = 0; j < 1515; ++j) {
1329 [ + - ]: 1515 : add_coin(available_coins, wallet, CAmount(0.033 * COIN), CFeeRate(0), 144, false, 0, true);
1330 : : }
1331 : :
1332 [ + - ]: 1 : add_coin(available_coins, wallet, CAmount(50 * COIN), CFeeRate(0), 144, false, 0, true);
1333 : 1 : return available_coins;
1334 : 0 : },
1335 [ + - ]: 1 : m_node);
1336 : :
1337 [ + - + - : 2 : BOOST_CHECK(result);
+ - ]
1338 : : // Verify that the 50 BTC UTXO was selected, and result is below max_weight
1339 [ + - + - : 2 : BOOST_CHECK(has_coin(result->GetInputSet(), CAmount(50 * COIN)));
+ - + - ]
1340 [ + - + - ]: 1 : BOOST_CHECK_LE(result->GetWeight(), max_weight);
1341 : 0 : }
1342 : :
1343 : 1 : {
1344 : : // Scenario 2:
1345 : :
1346 : : // The actor starts with 400x 0.0625 BTC and 2000x 0.025 BTC (75.0 BTC total) unspent outputs
1347 : : // Then tries to spend 49.5 BTC
1348 : : // A combination of coins should be selected, such that the created transaction is not too large
1349 : :
1350 : : // Perform selection
1351 : 1 : const auto result = select_coins(
1352 [ + - ]: 2 : target, cs_params, cc, [&](CWallet& wallet) {
1353 : 1 : CoinsResult available_coins;
1354 [ + + ]: 401 : for (int j = 0; j < 400; ++j) {
1355 [ + - ]: 400 : add_coin(available_coins, wallet, CAmount(0.0625 * COIN), CFeeRate(0), 144, false, 0, true);
1356 : : }
1357 [ + + ]: 2001 : for (int j = 0; j < 2000; ++j) {
1358 [ + - ]: 2000 : add_coin(available_coins, wallet, CAmount(0.025 * COIN), CFeeRate(0), 144, false, 0, true);
1359 : : }
1360 : 1 : return available_coins;
1361 : 0 : },
1362 [ + - ]: 1 : m_node);
1363 : :
1364 [ + - + - : 2 : BOOST_CHECK(has_coin(result->GetInputSet(), CAmount(0.0625 * COIN)));
+ - + - ]
1365 [ + - + - : 2 : BOOST_CHECK(has_coin(result->GetInputSet(), CAmount(0.025 * COIN)));
+ - + - ]
1366 [ + - + - ]: 1 : BOOST_CHECK_LE(result->GetWeight(), max_weight);
1367 : 0 : }
1368 : :
1369 : 1 : {
1370 : : // Scenario 3:
1371 : :
1372 : : // The actor starts with 1515x 0.033 BTC (49.995 BTC total) unspent outputs
1373 : : // No results should be returned, because the transaction would be too large
1374 : :
1375 : : // Perform selection
1376 : 1 : const auto result = select_coins(
1377 [ + - ]: 2 : target, cs_params, cc, [&](CWallet& wallet) {
1378 : 1 : CoinsResult available_coins;
1379 [ + + ]: 1516 : for (int j = 0; j < 1515; ++j) {
1380 [ + - ]: 1515 : add_coin(available_coins, wallet, CAmount(0.033 * COIN), CFeeRate(0), 144, false, 0, true);
1381 : : }
1382 : 1 : return available_coins;
1383 : 0 : },
1384 [ + - ]: 1 : m_node);
1385 : :
1386 : : // No results
1387 : : // 1515 inputs * 68 bytes = 103,020 bytes
1388 : : // 103,020 bytes * 4 = 412,080 weight, which is above the MAX_STANDARD_TX_WEIGHT of 400,000
1389 [ + - + - ]: 2 : BOOST_CHECK(!result);
1390 : 1 : }
1391 : 1 : }
1392 : :
1393 [ + - + - : 7 : BOOST_AUTO_TEST_CASE(SelectCoins_effective_value_test)
+ - + - -
+ + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- ]
1394 : : {
1395 : : // Test that the effective value is used to check whether preset inputs provide sufficient funds when subtract_fee_outputs is not used.
1396 : : // This test creates a coin whose value is higher than the target but whose effective value is lower than the target.
1397 : : // The coin is selected using coin control, with m_allow_other_inputs = false. SelectCoins should fail due to insufficient funds.
1398 : :
1399 [ + - ]: 1 : std::unique_ptr<CWallet> wallet = NewWallet(m_node);
1400 : :
1401 [ + - ]: 1 : CoinsResult available_coins;
1402 : 1 : {
1403 [ + - + - ]: 1 : std::unique_ptr<CWallet> dummyWallet = NewWallet(m_node, /*wallet_name=*/"dummy");
1404 [ + - ]: 1 : add_coin(available_coins, *dummyWallet, 100000); // 0.001 BTC
1405 : 0 : }
1406 : :
1407 : 1 : CAmount target{99900}; // 0.000999 BTC
1408 : :
1409 : 1 : FastRandomContext rand;
1410 [ + - ]: 1 : CoinSelectionParams cs_params{
1411 : : rand,
1412 : : /*change_output_size=*/34,
1413 : : /*change_spend_size=*/148,
1414 : : /*min_change_target=*/1000,
1415 : 1 : /*effective_feerate=*/CFeeRate(3000),
1416 : 1 : /*long_term_feerate=*/CFeeRate(1000),
1417 : 1 : /*discard_feerate=*/CFeeRate(1000),
1418 : : /*tx_noinputs_size=*/0,
1419 : : /*avoid_partial=*/false,
1420 [ + - ]: 1 : };
1421 [ + - ]: 1 : CCoinControl cc;
1422 : 1 : cc.m_allow_other_inputs = false;
1423 [ + - ]: 2 : COutput output = available_coins.All().at(0);
1424 [ + - ]: 1 : cc.SetInputWeight(output.outpoint, 148);
1425 [ + - + - ]: 1 : cc.Select(output.outpoint).SetTxOut(output.txout);
1426 : :
1427 [ + - ]: 1 : LOCK(wallet->cs_wallet);
1428 [ + - + - ]: 2 : const auto preset_inputs = *Assert(FetchSelectedInputs(*wallet, cc, cs_params));
1429 [ + - + - : 3 : available_coins.Erase({available_coins.coins[OutputType::BECH32].begin()->outpoint});
+ - + - ]
1430 : :
1431 [ + - ]: 1 : const auto result = SelectCoins(*wallet, available_coins, preset_inputs, target, cc, cs_params);
1432 [ + - + - ]: 2 : BOOST_CHECK(!result);
1433 [ + - + - ]: 3 : }
1434 : :
1435 [ + - + - : 7 : BOOST_FIXTURE_TEST_CASE(wallet_coinsresult_test, BasicTestingSetup)
+ - + - -
+ + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- ]
1436 : : {
1437 : : // Test case to verify CoinsResult object sanity.
1438 [ + - ]: 1 : CoinsResult available_coins;
1439 : 1 : {
1440 [ + - + - ]: 1 : std::unique_ptr<CWallet> dummyWallet = NewWallet(m_node, /*wallet_name=*/"dummy");
1441 : :
1442 : : // Add some coins to 'available_coins'
1443 [ + + ]: 11 : for (int i=0; i<10; i++) {
1444 [ + - ]: 10 : add_coin(available_coins, *dummyWallet, 1 * COIN);
1445 : : }
1446 : 0 : }
1447 : :
1448 : 1 : {
1449 : : // First test case, check that 'CoinsResult::Erase' function works as expected.
1450 : : // By trying to erase two elements from the 'available_coins' object.
1451 [ + - ]: 1 : std::unordered_set<COutPoint, SaltedOutpointHasher> outs_to_remove;
1452 [ + - ]: 1 : const auto& coins = available_coins.All();
1453 [ + + ]: 3 : for (int i = 0; i < 2; i++) {
1454 [ + - ]: 2 : outs_to_remove.emplace(coins[i].outpoint);
1455 : : }
1456 [ + - ]: 1 : available_coins.Erase(outs_to_remove);
1457 : :
1458 : : // Check that the elements were actually removed.
1459 [ + - ]: 1 : const auto& updated_coins = available_coins.All();
1460 [ + + ]: 3 : for (const auto& out: outs_to_remove) {
1461 : 18 : auto it = std::find_if(updated_coins.begin(), updated_coins.end(), [&out](const COutput &coin) {
1462 [ + - ]: 16 : return coin.outpoint == out;
1463 : : });
1464 [ + - + - ]: 4 : BOOST_CHECK(it == updated_coins.end());
1465 : : }
1466 : : // And verify that no extra element were removed
1467 [ + - + - : 1 : BOOST_CHECK_EQUAL(available_coins.Size(), 8);
+ - ]
1468 : 1 : }
1469 : 1 : }
1470 : :
1471 : : BOOST_AUTO_TEST_SUITE_END()
1472 : : } // namespace wallet
|