coinselector_tests.cpp raw

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