Bitcoin Core  24.99.0
P2P Digital Currency
spend.cpp
Go to the documentation of this file.
1 // Copyright (c) 2021-2022 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 <algorithm>
6 #include <consensus/amount.h>
7 #include <consensus/validation.h>
8 #include <interfaces/chain.h>
9 #include <numeric>
10 #include <policy/policy.h>
11 #include <primitives/transaction.h>
12 #include <script/signingprovider.h>
13 #include <util/check.h>
14 #include <util/fees.h>
15 #include <util/moneystr.h>
16 #include <util/rbf.h>
17 #include <util/trace.h>
18 #include <util/translation.h>
19 #include <wallet/coincontrol.h>
20 #include <wallet/fees.h>
21 #include <wallet/receive.h>
22 #include <wallet/spend.h>
23 #include <wallet/transaction.h>
24 #include <wallet/wallet.h>
25 
26 #include <cmath>
27 
29 
30 namespace wallet {
31 static constexpr size_t OUTPUT_GROUP_MAX_ENTRIES{100};
32 
33 int CalculateMaximumSignedInputSize(const CTxOut& txout, const COutPoint outpoint, const SigningProvider* provider, const CCoinControl* coin_control)
34 {
36  txn.vin.push_back(CTxIn(outpoint));
37  if (!provider || !DummySignInput(*provider, txn.vin[0], txout, coin_control)) {
38  return -1;
39  }
40  return GetVirtualTransactionInputSize(txn.vin[0]);
41 }
42 
43 int CalculateMaximumSignedInputSize(const CTxOut& txout, const CWallet* wallet, const CCoinControl* coin_control)
44 {
45  const std::unique_ptr<SigningProvider> provider = wallet->GetSolvingProvider(txout.scriptPubKey);
46  return CalculateMaximumSignedInputSize(txout, COutPoint(), provider.get(), coin_control);
47 }
48 
49 // txouts needs to be in the order of tx.vin
50 TxSize CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, const std::vector<CTxOut>& txouts, const CCoinControl* coin_control)
51 {
52  CMutableTransaction txNew(tx);
53  if (!wallet->DummySignTx(txNew, txouts, coin_control)) {
54  return TxSize{-1, -1};
55  }
56  CTransaction ctx(txNew);
57  int64_t vsize = GetVirtualTransactionSize(ctx);
58  int64_t weight = GetTransactionWeight(ctx);
59  return TxSize{vsize, weight};
60 }
61 
63 {
64  std::vector<CTxOut> txouts;
65  // Look up the inputs. The inputs are either in the wallet, or in coin_control.
66  for (const CTxIn& input : tx.vin) {
67  const auto mi = wallet->mapWallet.find(input.prevout.hash);
68  // Can not estimate size without knowing the input details
69  if (mi != wallet->mapWallet.end()) {
70  assert(input.prevout.n < mi->second.tx->vout.size());
71  txouts.emplace_back(mi->second.tx->vout.at(input.prevout.n));
72  } else if (coin_control) {
73  CTxOut txout;
74  if (!coin_control->GetExternalOutput(input.prevout, txout)) {
75  return TxSize{-1, -1};
76  }
77  txouts.emplace_back(txout);
78  } else {
79  return TxSize{-1, -1};
80  }
81  }
82  return CalculateMaximumSignedTxSize(tx, wallet, txouts, coin_control);
83 }
84 
85 size_t CoinsResult::Size() const
86 {
87  size_t size{0};
88  for (const auto& it : coins) {
89  size += it.second.size();
90  }
91  return size;
92 }
93 
94 std::vector<COutput> CoinsResult::All() const
95 {
96  std::vector<COutput> all;
97  all.reserve(coins.size());
98  for (const auto& it : coins) {
99  all.insert(all.end(), it.second.begin(), it.second.end());
100  }
101  return all;
102 }
103 
105  coins.clear();
106 }
107 
108 void CoinsResult::Erase(const std::unordered_set<COutPoint, SaltedOutpointHasher>& coins_to_remove)
109 {
110  for (auto& [type, vec] : coins) {
111  auto remove_it = std::remove_if(vec.begin(), vec.end(), [&](const COutput& coin) {
112  // remove it if it's on the set
113  if (coins_to_remove.count(coin.outpoint) == 0) return false;
114 
115  // update cached amounts
116  total_amount -= coin.txout.nValue;
117  if (coin.HasEffectiveValue()) total_effective_amount = *total_effective_amount - coin.GetEffectiveValue();
118  return true;
119  });
120  vec.erase(remove_it, vec.end());
121  }
122 }
123 
125 {
126  for (auto& it : coins) {
127  ::Shuffle(it.second.begin(), it.second.end(), rng_fast);
128  }
129 }
130 
131 void CoinsResult::Add(OutputType type, const COutput& out)
132 {
133  coins[type].emplace_back(out);
134  total_amount += out.txout.nValue;
135  if (out.HasEffectiveValue()) {
138  }
139 }
140 
141 static OutputType GetOutputType(TxoutType type, bool is_from_p2sh)
142 {
143  switch (type) {
145  return OutputType::BECH32M;
148  if (is_from_p2sh) return OutputType::P2SH_SEGWIT;
149  else return OutputType::BECH32;
152  return OutputType::LEGACY;
153  default:
154  return OutputType::UNKNOWN;
155  }
156 }
157 
158 // Fetch and validate the coin control selected inputs.
159 // Coins could be internal (from the wallet) or external.
161  const CoinSelectionParams& coin_selection_params) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
162 {
163  PreSelectedInputs result;
164  std::vector<COutPoint> vPresetInputs;
165  coin_control.ListSelected(vPresetInputs);
166  for (const COutPoint& outpoint : vPresetInputs) {
167  int input_bytes = -1;
168  CTxOut txout;
169  if (auto ptr_wtx = wallet.GetWalletTx(outpoint.hash)) {
170  // Clearly invalid input, fail
171  if (ptr_wtx->tx->vout.size() <= outpoint.n) {
172  return util::Error{strprintf(_("Invalid pre-selected input %s"), outpoint.ToString())};
173  }
174  txout = ptr_wtx->tx->vout.at(outpoint.n);
175  input_bytes = CalculateMaximumSignedInputSize(txout, &wallet, &coin_control);
176  } else {
177  // The input is external. We did not find the tx in mapWallet.
178  if (!coin_control.GetExternalOutput(outpoint, txout)) {
179  return util::Error{strprintf(_("Not found pre-selected input %s"), outpoint.ToString())};
180  }
181  }
182 
183  if (input_bytes == -1) {
184  input_bytes = CalculateMaximumSignedInputSize(txout, outpoint, &coin_control.m_external_provider, &coin_control);
185  }
186 
187  // If available, override calculated size with coin control specified size
188  if (coin_control.HasInputWeight(outpoint)) {
189  input_bytes = GetVirtualTransactionSize(coin_control.GetInputWeight(outpoint), 0, 0);
190  }
191 
192  if (input_bytes == -1) {
193  return util::Error{strprintf(_("Not solvable pre-selected input %s"), outpoint.ToString())}; // Not solvable, can't estimate size for fee
194  }
195 
196  /* Set some defaults for depth, spendable, solvable, safe, time, and from_me as these don't matter for preset inputs since no selection is being done. */
197  COutput output(outpoint, txout, /*depth=*/ 0, input_bytes, /*spendable=*/ true, /*solvable=*/ true, /*safe=*/ true, /*time=*/ 0, /*from_me=*/ false, coin_selection_params.m_effective_feerate);
198  result.Insert(output, coin_selection_params.m_subtract_fee_outputs);
199  }
200  return result;
201 }
202 
204  const CCoinControl* coinControl,
205  std::optional<CFeeRate> feerate,
206  const CoinFilterParams& params)
207 {
208  AssertLockHeld(wallet.cs_wallet);
209 
210  CoinsResult result;
211  // Either the WALLET_FLAG_AVOID_REUSE flag is not set (in which case we always allow), or we default to avoiding, and only in the case where
212  // a coin control object is provided, and has the avoid address reuse flag set to false, do we allow already used addresses
213  bool allow_used_addresses = !wallet.IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE) || (coinControl && !coinControl->m_avoid_address_reuse);
214  const int min_depth = {coinControl ? coinControl->m_min_depth : DEFAULT_MIN_DEPTH};
215  const int max_depth = {coinControl ? coinControl->m_max_depth : DEFAULT_MAX_DEPTH};
216  const bool only_safe = {coinControl ? !coinControl->m_include_unsafe_inputs : true};
217 
218  std::set<uint256> trusted_parents;
219  for (const auto& entry : wallet.mapWallet)
220  {
221  const uint256& wtxid = entry.first;
222  const CWalletTx& wtx = entry.second;
223 
224  if (wallet.IsTxImmatureCoinBase(wtx) && !params.include_immature_coinbase)
225  continue;
226 
227  int nDepth = wallet.GetTxDepthInMainChain(wtx);
228  if (nDepth < 0)
229  continue;
230 
231  // We should not consider coins which aren't at least in our mempool
232  // It's possible for these to be conflicted via ancestors which we may never be able to detect
233  if (nDepth == 0 && !wtx.InMempool())
234  continue;
235 
236  bool safeTx = CachedTxIsTrusted(wallet, wtx, trusted_parents);
237 
238  // We should not consider coins from transactions that are replacing
239  // other transactions.
240  //
241  // Example: There is a transaction A which is replaced by bumpfee
242  // transaction B. In this case, we want to prevent creation of
243  // a transaction B' which spends an output of B.
244  //
245  // Reason: If transaction A were initially confirmed, transactions B
246  // and B' would no longer be valid, so the user would have to create
247  // a new transaction C to replace B'. However, in the case of a
248  // one-block reorg, transactions B' and C might BOTH be accepted,
249  // when the user only wanted one of them. Specifically, there could
250  // be a 1-block reorg away from the chain where transactions A and C
251  // were accepted to another chain where B, B', and C were all
252  // accepted.
253  if (nDepth == 0 && wtx.mapValue.count("replaces_txid")) {
254  safeTx = false;
255  }
256 
257  // Similarly, we should not consider coins from transactions that
258  // have been replaced. In the example above, we would want to prevent
259  // creation of a transaction A' spending an output of A, because if
260  // transaction B were initially confirmed, conflicting with A and
261  // A', we wouldn't want to the user to create a transaction D
262  // intending to replace A', but potentially resulting in a scenario
263  // where A, A', and D could all be accepted (instead of just B and
264  // D, or just A and A' like the user would want).
265  if (nDepth == 0 && wtx.mapValue.count("replaced_by_txid")) {
266  safeTx = false;
267  }
268 
269  if (only_safe && !safeTx) {
270  continue;
271  }
272 
273  if (nDepth < min_depth || nDepth > max_depth) {
274  continue;
275  }
276 
277  bool tx_from_me = CachedTxIsFromMe(wallet, wtx, ISMINE_ALL);
278 
279  for (unsigned int i = 0; i < wtx.tx->vout.size(); i++) {
280  const CTxOut& output = wtx.tx->vout[i];
281  const COutPoint outpoint(wtxid, i);
282 
283  if (output.nValue < params.min_amount || output.nValue > params.max_amount)
284  continue;
285 
286  // Skip manually selected coins (the caller can fetch them directly)
287  if (coinControl && coinControl->HasSelected() && coinControl->IsSelected(outpoint))
288  continue;
289 
290  if (wallet.IsLockedCoin(outpoint) && params.skip_locked)
291  continue;
292 
293  if (wallet.IsSpent(outpoint))
294  continue;
295 
296  isminetype mine = wallet.IsMine(output);
297 
298  if (mine == ISMINE_NO) {
299  continue;
300  }
301 
302  if (!allow_used_addresses && wallet.IsSpentKey(output.scriptPubKey)) {
303  continue;
304  }
305 
306  std::unique_ptr<SigningProvider> provider = wallet.GetSolvingProvider(output.scriptPubKey);
307 
308  int input_bytes = CalculateMaximumSignedInputSize(output, COutPoint(), provider.get(), coinControl);
309  // Because CalculateMaximumSignedInputSize just uses ProduceSignature and makes a dummy signature,
310  // it is safe to assume that this input is solvable if input_bytes is greater -1.
311  bool solvable = input_bytes > -1;
312  bool spendable = ((mine & ISMINE_SPENDABLE) != ISMINE_NO) || (((mine & ISMINE_WATCH_ONLY) != ISMINE_NO) && (coinControl && coinControl->fAllowWatchOnly && solvable));
313 
314  // Filter by spendable outputs only
315  if (!spendable && params.only_spendable) continue;
316 
317  // Obtain script type
318  std::vector<std::vector<uint8_t>> script_solutions;
319  TxoutType type = Solver(output.scriptPubKey, script_solutions);
320 
321  // If the output is P2SH and solvable, we want to know if it is
322  // a P2SH (legacy) or one of P2SH-P2WPKH, P2SH-P2WSH (P2SH-Segwit). We can determine
323  // this from the redeemScript. If the output is not solvable, it will be classified
324  // as a P2SH (legacy), since we have no way of knowing otherwise without the redeemScript
325  bool is_from_p2sh{false};
326  if (type == TxoutType::SCRIPTHASH && solvable) {
327  CScript script;
328  if (!provider->GetCScript(CScriptID(uint160(script_solutions[0])), script)) continue;
329  type = Solver(script, script_solutions);
330  is_from_p2sh = true;
331  }
332 
333  result.Add(GetOutputType(type, is_from_p2sh),
334  COutput(outpoint, output, nDepth, input_bytes, spendable, solvable, safeTx, wtx.GetTxTime(), tx_from_me, feerate));
335 
336  // Checks the sum amount of all UTXO's.
337  if (params.min_sum_amount != MAX_MONEY) {
338  if (result.GetTotalAmount() >= params.min_sum_amount) {
339  return result;
340  }
341  }
342 
343  // Checks the maximum number of UTXO's.
344  if (params.max_count > 0 && result.Size() >= params.max_count) {
345  return result;
346  }
347  }
348  }
349 
350  return result;
351 }
352 
354 {
355  params.only_spendable = false;
356  return AvailableCoins(wallet, coinControl, /*feerate=*/ std::nullopt, params);
357 }
358 
360 {
361  LOCK(wallet.cs_wallet);
362  return AvailableCoins(wallet, coinControl).GetTotalAmount();
363 }
364 
365 const CTxOut& FindNonChangeParentOutput(const CWallet& wallet, const COutPoint& outpoint)
366 {
367  AssertLockHeld(wallet.cs_wallet);
368  const CWalletTx* wtx{Assert(wallet.GetWalletTx(outpoint.hash))};
369 
370  const CTransaction* ptx = wtx->tx.get();
371  int n = outpoint.n;
372  while (OutputIsChange(wallet, ptx->vout[n]) && ptx->vin.size() > 0) {
373  const COutPoint& prevout = ptx->vin[0].prevout;
374  const CWalletTx* it = wallet.GetWalletTx(prevout.hash);
375  if (!it || it->tx->vout.size() <= prevout.n ||
376  !wallet.IsMine(it->tx->vout[prevout.n])) {
377  break;
378  }
379  ptx = it->tx.get();
380  n = prevout.n;
381  }
382  return ptx->vout[n];
383 }
384 
385 std::map<CTxDestination, std::vector<COutput>> ListCoins(const CWallet& wallet)
386 {
387  AssertLockHeld(wallet.cs_wallet);
388 
389  std::map<CTxDestination, std::vector<COutput>> result;
390 
391  CCoinControl coin_control;
392  // Include watch-only for LegacyScriptPubKeyMan wallets without private keys
393  coin_control.fAllowWatchOnly = wallet.GetLegacyScriptPubKeyMan() && wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS);
394  CoinFilterParams coins_params;
395  coins_params.only_spendable = false;
396  coins_params.skip_locked = false;
397  for (const COutput& coin : AvailableCoins(wallet, &coin_control, /*feerate=*/std::nullopt, coins_params).All()) {
398  CTxDestination address;
399  if ((coin.spendable || (wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) && coin.solvable)) &&
401  result[address].emplace_back(coin);
402  }
403  }
404  return result;
405 }
406 
407 std::vector<OutputGroup> GroupOutputs(const CWallet& wallet, const std::vector<COutput>& outputs, const CoinSelectionParams& coin_sel_params, const CoinEligibilityFilter& filter, bool positive_only)
408 {
409  std::vector<OutputGroup> groups_out;
410 
411  if (!coin_sel_params.m_avoid_partial_spends) {
412  // Allowing partial spends means no grouping. Each COutput gets its own OutputGroup.
413  for (const COutput& output : outputs) {
414  // Skip outputs we cannot spend
415  if (!output.spendable) continue;
416 
417  size_t ancestors, descendants;
418  wallet.chain().getTransactionAncestry(output.outpoint.hash, ancestors, descendants);
419 
420  // Make an OutputGroup containing just this output
421  OutputGroup group{coin_sel_params};
422  group.Insert(output, ancestors, descendants, positive_only);
423 
424  // Check the OutputGroup's eligibility. Only add the eligible ones.
425  if (positive_only && group.GetSelectionAmount() <= 0) continue;
426  if (group.m_outputs.size() > 0 && group.EligibleForSpending(filter)) groups_out.push_back(group);
427  }
428  return groups_out;
429  }
430 
431  // We want to combine COutputs that have the same scriptPubKey into single OutputGroups
432  // except when there are more than OUTPUT_GROUP_MAX_ENTRIES COutputs grouped in an OutputGroup.
433  // To do this, we maintain a map where the key is the scriptPubKey and the value is a vector of OutputGroups.
434  // For each COutput, we check if the scriptPubKey is in the map, and if it is, the COutput is added
435  // to the last OutputGroup in the vector for the scriptPubKey. When the last OutputGroup has
436  // OUTPUT_GROUP_MAX_ENTRIES COutputs, a new OutputGroup is added to the end of the vector.
437  std::map<CScript, std::vector<OutputGroup>> spk_to_groups_map;
438  for (const auto& output : outputs) {
439  // Skip outputs we cannot spend
440  if (!output.spendable) continue;
441 
442  size_t ancestors, descendants;
443  wallet.chain().getTransactionAncestry(output.outpoint.hash, ancestors, descendants);
444  CScript spk = output.txout.scriptPubKey;
445 
446  std::vector<OutputGroup>& groups = spk_to_groups_map[spk];
447 
448  if (groups.size() == 0) {
449  // No OutputGroups for this scriptPubKey yet, add one
450  groups.emplace_back(coin_sel_params);
451  }
452 
453  // Get the last OutputGroup in the vector so that we can add the COutput to it
454  // A pointer is used here so that group can be reassigned later if it is full.
455  OutputGroup* group = &groups.back();
456 
457  // Check if this OutputGroup is full. We limit to OUTPUT_GROUP_MAX_ENTRIES when using -avoidpartialspends
458  // to avoid surprising users with very high fees.
459  if (group->m_outputs.size() >= OUTPUT_GROUP_MAX_ENTRIES) {
460  // The last output group is full, add a new group to the vector and use that group for the insertion
461  groups.emplace_back(coin_sel_params);
462  group = &groups.back();
463  }
464 
465  // Add the output to group
466  group->Insert(output, ancestors, descendants, positive_only);
467  }
468 
469  // Now we go through the entire map and pull out the OutputGroups
470  for (const auto& spk_and_groups_pair: spk_to_groups_map) {
471  const std::vector<OutputGroup>& groups_per_spk= spk_and_groups_pair.second;
472 
473  // Go through the vector backwards. This allows for the first item we deal with being the partial group.
474  for (auto group_it = groups_per_spk.rbegin(); group_it != groups_per_spk.rend(); group_it++) {
475  const OutputGroup& group = *group_it;
476 
477  // Don't include partial groups if there are full groups too and we don't want partial groups
478  if (group_it == groups_per_spk.rbegin() && groups_per_spk.size() > 1 && !filter.m_include_partial_groups) {
479  continue;
480  }
481 
482  // Check the OutputGroup's eligibility. Only add the eligible ones.
483  if (positive_only && group.GetSelectionAmount() <= 0) continue;
484  if (group.m_outputs.size() > 0 && group.EligibleForSpending(filter)) groups_out.push_back(group);
485  }
486  }
487 
488  return groups_out;
489 }
490 
491 // Returns true if the result contains an error and the message is not empty
492 static bool HasErrorMsg(const util::Result<SelectionResult>& res) { return !util::ErrorString(res).empty(); }
493 
494 util::Result<SelectionResult> AttemptSelection(const CWallet& wallet, const CAmount& nTargetValue, const CoinEligibilityFilter& eligibility_filter, const CoinsResult& available_coins,
495  const CoinSelectionParams& coin_selection_params, bool allow_mixed_output_types)
496 {
497  // Run coin selection on each OutputType and compute the Waste Metric
498  std::vector<SelectionResult> results;
499  for (const auto& it : available_coins.coins) {
500  auto result{ChooseSelectionResult(wallet, nTargetValue, eligibility_filter, it.second, coin_selection_params)};
501  // If any specific error message appears here, then something particularly wrong happened.
502  if (HasErrorMsg(result)) return result; // So let's return the specific error.
503  // Append the favorable result.
504  if (result) results.push_back(*result);
505  }
506  // If we have at least one solution for funding the transaction without mixing, choose the minimum one according to waste metric
507  // and return the result
508  if (results.size() > 0) return *std::min_element(results.begin(), results.end());
509 
510  // If we can't fund the transaction from any individual OutputType, run coin selection one last time
511  // over all available coins, which would allow mixing.
512  // If TypesCount() <= 1, there is nothing to mix.
513  if (allow_mixed_output_types && available_coins.TypesCount() > 1) {
514  return ChooseSelectionResult(wallet, nTargetValue, eligibility_filter, available_coins.All(), coin_selection_params);
515  }
516  // Either mixing is not allowed and we couldn't find a solution from any single OutputType, or mixing was allowed and we still couldn't
517  // find a solution using all available coins
518  return util::Error();
519 };
520 
521 util::Result<SelectionResult> ChooseSelectionResult(const CWallet& wallet, const CAmount& nTargetValue, const CoinEligibilityFilter& eligibility_filter, const std::vector<COutput>& available_coins, const CoinSelectionParams& coin_selection_params)
522 {
523  // Vector of results. We will choose the best one based on waste.
524  std::vector<SelectionResult> results;
525 
526  std::vector<OutputGroup> positive_groups = GroupOutputs(wallet, available_coins, coin_selection_params, eligibility_filter, /*positive_only=*/true);
527  if (auto bnb_result{SelectCoinsBnB(positive_groups, nTargetValue, coin_selection_params.m_cost_of_change)}) {
528  results.push_back(*bnb_result);
529  }
530 
531  // The knapsack solver has some legacy behavior where it will spend dust outputs. We retain this behavior, so don't filter for positive only here.
532  std::vector<OutputGroup> all_groups = GroupOutputs(wallet, available_coins, coin_selection_params, eligibility_filter, /*positive_only=*/false);
533  if (auto knapsack_result{KnapsackSolver(all_groups, nTargetValue, coin_selection_params.m_min_change_target, coin_selection_params.rng_fast)}) {
534  knapsack_result->ComputeAndSetWaste(coin_selection_params.min_viable_change, coin_selection_params.m_cost_of_change, coin_selection_params.m_change_fee);
535  results.push_back(*knapsack_result);
536  }
537 
538  if (auto srd_result{SelectCoinsSRD(positive_groups, nTargetValue, coin_selection_params.rng_fast)}) {
539  srd_result->ComputeAndSetWaste(coin_selection_params.min_viable_change, coin_selection_params.m_cost_of_change, coin_selection_params.m_change_fee);
540  results.push_back(*srd_result);
541  }
542 
543  if (results.empty()) {
544  // No solution found
545  return util::Error();
546  }
547 
548  std::vector<SelectionResult> eligible_results;
549  std::copy_if(results.begin(), results.end(), std::back_inserter(eligible_results), [coin_selection_params](const SelectionResult& result) {
550  const auto initWeight{coin_selection_params.tx_noinputs_size * WITNESS_SCALE_FACTOR};
551  return initWeight + result.GetWeight() <= static_cast<int>(MAX_STANDARD_TX_WEIGHT);
552  });
553 
554  if (eligible_results.empty()) {
555  return util::Error{_("The inputs size exceeds the maximum weight. "
556  "Please try sending a smaller amount or manually consolidating your wallet's UTXOs")};
557  }
558 
559  // Choose the result with the least waste
560  // If the waste is the same, choose the one which spends more inputs.
561  auto& best_result = *std::min_element(eligible_results.begin(), eligible_results.end());
562  return best_result;
563 }
564 
566  const CAmount& nTargetValue, const CCoinControl& coin_control,
567  const CoinSelectionParams& coin_selection_params)
568 {
569  // Deduct preset inputs amount from the search target
570  CAmount selection_target = nTargetValue - pre_set_inputs.total_amount;
571 
572  // Return if automatic coin selection is disabled, and we don't cover the selection target
573  if (!coin_control.m_allow_other_inputs && selection_target > 0) {
574  return util::Error{_("The preselected coins total amount does not cover the transaction target. "
575  "Please allow other inputs to be automatically selected or include more coins manually")};
576  }
577 
578  // Return if we can cover the target only with the preset inputs
579  if (selection_target <= 0) {
580  SelectionResult result(nTargetValue, SelectionAlgorithm::MANUAL);
581  result.AddInputs(pre_set_inputs.coins, coin_selection_params.m_subtract_fee_outputs);
582  result.ComputeAndSetWaste(coin_selection_params.min_viable_change, coin_selection_params.m_cost_of_change, coin_selection_params.m_change_fee);
583  return result;
584  }
585 
586  // Return early if we cannot cover the target with the wallet's UTXO.
587  // We use the total effective value if we are not subtracting fee from outputs and 'available_coins' contains the data.
588  CAmount available_coins_total_amount = coin_selection_params.m_subtract_fee_outputs ? available_coins.GetTotalAmount() :
589  (available_coins.GetEffectiveTotalAmount().has_value() ? *available_coins.GetEffectiveTotalAmount() : 0);
590  if (selection_target > available_coins_total_amount) {
591  return util::Error(); // Insufficient funds
592  }
593 
594  // Start wallet Coin Selection procedure
595  auto op_selection_result = AutomaticCoinSelection(wallet, available_coins, selection_target, coin_control, coin_selection_params);
596  if (!op_selection_result) return op_selection_result;
597 
598  // If needed, add preset inputs to the automatic coin selection result
599  if (!pre_set_inputs.coins.empty()) {
600  SelectionResult preselected(pre_set_inputs.total_amount, SelectionAlgorithm::MANUAL);
601  preselected.AddInputs(pre_set_inputs.coins, coin_selection_params.m_subtract_fee_outputs);
602  op_selection_result->Merge(preselected);
603  op_selection_result->ComputeAndSetWaste(coin_selection_params.min_viable_change,
604  coin_selection_params.m_cost_of_change,
605  coin_selection_params.m_change_fee);
606  }
607  return op_selection_result;
608 }
609 
612  bool allow_mixed_output_types{true};
613 };
614 
615 util::Result<SelectionResult> AutomaticCoinSelection(const CWallet& wallet, CoinsResult& available_coins, const CAmount& value_to_select, const CCoinControl& coin_control, const CoinSelectionParams& coin_selection_params)
616 {
617  unsigned int limit_ancestor_count = 0;
618  unsigned int limit_descendant_count = 0;
619  wallet.chain().getPackageLimits(limit_ancestor_count, limit_descendant_count);
620  const size_t max_ancestors = (size_t)std::max<int64_t>(1, limit_ancestor_count);
621  const size_t max_descendants = (size_t)std::max<int64_t>(1, limit_descendant_count);
622  const bool fRejectLongChains = gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
623 
624  // form groups from remaining coins; note that preset coins will not
625  // automatically have their associated (same address) coins included
626  if (coin_control.m_avoid_partial_spends && available_coins.Size() > OUTPUT_GROUP_MAX_ENTRIES) {
627  // Cases where we have 101+ outputs all pointing to the same destination may result in
628  // privacy leaks as they will potentially be deterministically sorted. We solve that by
629  // explicitly shuffling the outputs before processing
630  available_coins.Shuffle(coin_selection_params.rng_fast);
631  }
632 
633  // Coin Selection attempts to select inputs from a pool of eligible UTXOs to fund the
634  // transaction at a target feerate. If an attempt fails, more attempts may be made using a more
635  // permissive CoinEligibilityFilter.
637  // Place coins eligibility filters on a scope increasing order.
638  std::vector<SelectionFilter> ordered_filters{
639  // If possible, fund the transaction with confirmed UTXOs only. Prefer at least six
640  // confirmations on outputs received from other wallets and only spend confirmed change.
641  {CoinEligibilityFilter(1, 6, 0), /*allow_mixed_output_types=*/false},
642  {CoinEligibilityFilter(1, 1, 0)},
643  };
644  // Fall back to using zero confirmation change (but with as few ancestors in the mempool as
645  // possible) if we cannot fund the transaction otherwise.
646  if (wallet.m_spend_zero_conf_change) {
647  ordered_filters.push_back({CoinEligibilityFilter(0, 1, 2)});
648  ordered_filters.push_back({CoinEligibilityFilter(0, 1, std::min(size_t{4}, max_ancestors/3), std::min(size_t{4}, max_descendants/3))});
649  ordered_filters.push_back({CoinEligibilityFilter(0, 1, max_ancestors/2, max_descendants/2)});
650  // If partial groups are allowed, relax the requirement of spending OutputGroups (groups
651  // of UTXOs sent to the same address, which are obviously controlled by a single wallet)
652  // in their entirety.
653  ordered_filters.push_back({CoinEligibilityFilter(0, 1, max_ancestors-1, max_descendants-1, /*include_partial=*/true)});
654  // Try with unsafe inputs if they are allowed. This may spend unconfirmed outputs
655  // received from other wallets.
656  if (coin_control.m_include_unsafe_inputs) {
657  ordered_filters.push_back({CoinEligibilityFilter(/*conf_mine=*/0, /*conf_theirs*/0, max_ancestors-1, max_descendants-1, /*include_partial=*/true)});
658  }
659  // Try with unlimited ancestors/descendants. The transaction will still need to meet
660  // mempool ancestor/descendant policy to be accepted to mempool and broadcasted, but
661  // OutputGroups use heuristics that may overestimate ancestor/descendant counts.
662  if (!fRejectLongChains) {
663  ordered_filters.push_back({CoinEligibilityFilter(0, 1, std::numeric_limits<uint64_t>::max(),
664  std::numeric_limits<uint64_t>::max(),
665  /*include_partial=*/true)});
666  }
667  }
668 
669  // Walk-through the filters until the solution gets found.
670  // If no solution is found, return the first detailed error (if any).
671  // future: add "error level" so the worst one can be picked instead.
672  std::vector<util::Result<SelectionResult>> res_detailed_errors;
673  for (const auto& select_filter : ordered_filters) {
674  if (auto res{AttemptSelection(wallet, value_to_select, select_filter.filter, available_coins,
675  coin_selection_params, select_filter.allow_mixed_output_types)}) {
676  return res; // result found
677  } else {
678  // If any specific error message appears here, then something particularly wrong might have happened.
679  // Save the error and continue the selection process. So if no solutions gets found, we can return
680  // the detailed error to the upper layers.
681  if (HasErrorMsg(res)) res_detailed_errors.emplace_back(res);
682  }
683  }
684  // Coin Selection failed.
685  return res_detailed_errors.empty() ? util::Result<SelectionResult>(util::Error()) : res_detailed_errors.front();
686  }();
687 
688  return res;
689 }
690 
691 static bool IsCurrentForAntiFeeSniping(interfaces::Chain& chain, const uint256& block_hash)
692 {
693  if (chain.isInitialBlockDownload()) {
694  return false;
695  }
696  constexpr int64_t MAX_ANTI_FEE_SNIPING_TIP_AGE = 8 * 60 * 60; // in seconds
697  int64_t block_time;
698  CHECK_NONFATAL(chain.findBlock(block_hash, FoundBlock().time(block_time)));
699  if (block_time < (GetTime() - MAX_ANTI_FEE_SNIPING_TIP_AGE)) {
700  return false;
701  }
702  return true;
703 }
704 
710  interfaces::Chain& chain, const uint256& block_hash, int block_height)
711 {
712  // All inputs must be added by now
713  assert(!tx.vin.empty());
714  // Discourage fee sniping.
715  //
716  // For a large miner the value of the transactions in the best block and
717  // the mempool can exceed the cost of deliberately attempting to mine two
718  // blocks to orphan the current best block. By setting nLockTime such that
719  // only the next block can include the transaction, we discourage this
720  // practice as the height restricted and limited blocksize gives miners
721  // considering fee sniping fewer options for pulling off this attack.
722  //
723  // A simple way to think about this is from the wallet's point of view we
724  // always want the blockchain to move forward. By setting nLockTime this
725  // way we're basically making the statement that we only want this
726  // transaction to appear in the next block; we don't want to potentially
727  // encourage reorgs by allowing transactions to appear at lower heights
728  // than the next block in forks of the best chain.
729  //
730  // Of course, the subsidy is high enough, and transaction volume low
731  // enough, that fee sniping isn't a problem yet, but by implementing a fix
732  // now we ensure code won't be written that makes assumptions about
733  // nLockTime that preclude a fix later.
734  if (IsCurrentForAntiFeeSniping(chain, block_hash)) {
735  tx.nLockTime = block_height;
736 
737  // Secondly occasionally randomly pick a nLockTime even further back, so
738  // that transactions that are delayed after signing for whatever reason,
739  // e.g. high-latency mix networks and some CoinJoin implementations, have
740  // better privacy.
741  if (rng_fast.randrange(10) == 0) {
742  tx.nLockTime = std::max(0, int(tx.nLockTime) - int(rng_fast.randrange(100)));
743  }
744  } else {
745  // If our chain is lagging behind, we can't discourage fee sniping nor help
746  // the privacy of high-latency transactions. To avoid leaking a potentially
747  // unique "nLockTime fingerprint", set nLockTime to a constant.
748  tx.nLockTime = 0;
749  }
750  // Sanity check all values
751  assert(tx.nLockTime < LOCKTIME_THRESHOLD); // Type must be block height
752  assert(tx.nLockTime <= uint64_t(block_height));
753  for (const auto& in : tx.vin) {
754  // Can not be FINAL for locktime to work
755  assert(in.nSequence != CTxIn::SEQUENCE_FINAL);
756  // May be MAX NONFINAL to disable both BIP68 and BIP125
757  if (in.nSequence == CTxIn::MAX_SEQUENCE_NONFINAL) continue;
758  // May be MAX BIP125 to disable BIP68 and enable BIP125
759  if (in.nSequence == MAX_BIP125_RBF_SEQUENCE) continue;
760  // The wallet does not support any other sequence-use right now.
761  assert(false);
762  }
763 }
764 
766  CWallet& wallet,
767  const std::vector<CRecipient>& vecSend,
768  int change_pos,
769  const CCoinControl& coin_control,
770  bool sign) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
771 {
772  AssertLockHeld(wallet.cs_wallet);
773 
774  // out variables, to be packed into returned result structure
775  int nChangePosInOut = change_pos;
776 
777  FastRandomContext rng_fast;
778  CMutableTransaction txNew; // The resulting transaction that we make
779 
780  CoinSelectionParams coin_selection_params{rng_fast}; // Parameters for coin selection, init with dummy
781  coin_selection_params.m_avoid_partial_spends = coin_control.m_avoid_partial_spends;
782 
783  // Set the long term feerate estimate to the wallet's consolidate feerate
784  coin_selection_params.m_long_term_feerate = wallet.m_consolidate_feerate;
785 
786  CAmount recipients_sum = 0;
787  const OutputType change_type = wallet.TransactionChangeType(coin_control.m_change_type ? *coin_control.m_change_type : wallet.m_default_change_type, vecSend);
788  ReserveDestination reservedest(&wallet, change_type);
789  unsigned int outputs_to_subtract_fee_from = 0; // The number of outputs which we are subtracting the fee from
790  for (const auto& recipient : vecSend) {
791  recipients_sum += recipient.nAmount;
792 
793  if (recipient.fSubtractFeeFromAmount) {
794  outputs_to_subtract_fee_from++;
795  coin_selection_params.m_subtract_fee_outputs = true;
796  }
797  }
798 
799  // Create change script that will be used if we need change
800  CScript scriptChange;
801  bilingual_str error; // possible error str
802 
803  // coin control: send change to custom address
804  if (!std::get_if<CNoDestination>(&coin_control.destChange)) {
805  scriptChange = GetScriptForDestination(coin_control.destChange);
806  } else { // no coin control: send change to newly generated address
807  // Note: We use a new key here to keep it from being obvious which side is the change.
808  // The drawback is that by not reusing a previous key, the change may be lost if a
809  // backup is restored, if the backup doesn't have the new private key for the change.
810  // If we reused the old key, it would be possible to add code to look for and
811  // rediscover unknown transactions that were written with keys of ours to recover
812  // post-backup change.
813 
814  // Reserve a new key pair from key pool. If it fails, provide a dummy
815  // destination in case we don't need change.
816  CTxDestination dest;
817  auto op_dest = reservedest.GetReservedDestination(true);
818  if (!op_dest) {
819  error = _("Transaction needs a change address, but we can't generate it.") + Untranslated(" ") + util::ErrorString(op_dest);
820  } else {
821  dest = *op_dest;
822  scriptChange = GetScriptForDestination(dest);
823  }
824  // A valid destination implies a change script (and
825  // vice-versa). An empty change script will abort later, if the
826  // change keypool ran out, but change is required.
827  CHECK_NONFATAL(IsValidDestination(dest) != scriptChange.empty());
828  }
829  CTxOut change_prototype_txout(0, scriptChange);
830  coin_selection_params.change_output_size = GetSerializeSize(change_prototype_txout);
831 
832  // Get size of spending the change output
833  int change_spend_size = CalculateMaximumSignedInputSize(change_prototype_txout, &wallet);
834  // If the wallet doesn't know how to sign change output, assume p2sh-p2wpkh
835  // as lower-bound to allow BnB to do it's thing
836  if (change_spend_size == -1) {
837  coin_selection_params.change_spend_size = DUMMY_NESTED_P2WPKH_INPUT_SIZE;
838  } else {
839  coin_selection_params.change_spend_size = (size_t)change_spend_size;
840  }
841 
842  // Set discard feerate
843  coin_selection_params.m_discard_feerate = GetDiscardRate(wallet);
844 
845  // Get the fee rate to use effective values in coin selection
846  FeeCalculation feeCalc;
847  coin_selection_params.m_effective_feerate = GetMinimumFeeRate(wallet, coin_control, &feeCalc);
848  // Do not, ever, assume that it's fine to change the fee rate if the user has explicitly
849  // provided one
850  if (coin_control.m_feerate && coin_selection_params.m_effective_feerate > *coin_control.m_feerate) {
851  return util::Error{strprintf(_("Fee rate (%s) is lower than the minimum fee rate setting (%s)"), coin_control.m_feerate->ToString(FeeEstimateMode::SAT_VB), coin_selection_params.m_effective_feerate.ToString(FeeEstimateMode::SAT_VB))};
852  }
853  if (feeCalc.reason == FeeReason::FALLBACK && !wallet.m_allow_fallback_fee) {
854  // eventually allow a fallback fee
855  return util::Error{_("Fee estimation failed. Fallbackfee is disabled. Wait a few blocks or enable -fallbackfee.")};
856  }
857 
858  // Calculate the cost of change
859  // Cost of change is the cost of creating the change output + cost of spending the change output in the future.
860  // For creating the change output now, we use the effective feerate.
861  // For spending the change output in the future, we use the discard feerate for now.
862  // So cost of change = (change output size * effective feerate) + (size of spending change output * discard feerate)
863  coin_selection_params.m_change_fee = coin_selection_params.m_effective_feerate.GetFee(coin_selection_params.change_output_size);
864  coin_selection_params.m_cost_of_change = coin_selection_params.m_discard_feerate.GetFee(coin_selection_params.change_spend_size) + coin_selection_params.m_change_fee;
865 
866  coin_selection_params.m_min_change_target = GenerateChangeTarget(std::floor(recipients_sum / vecSend.size()), coin_selection_params.m_change_fee, rng_fast);
867 
868  // The smallest change amount should be:
869  // 1. at least equal to dust threshold
870  // 2. at least 1 sat greater than fees to spend it at m_discard_feerate
871  const auto dust = GetDustThreshold(change_prototype_txout, coin_selection_params.m_discard_feerate);
872  const auto change_spend_fee = coin_selection_params.m_discard_feerate.GetFee(coin_selection_params.change_spend_size);
873  coin_selection_params.min_viable_change = std::max(change_spend_fee + 1, dust);
874 
875  // Static vsize overhead + outputs vsize. 4 nVersion, 4 nLocktime, 1 input count, 1 witness overhead (dummy, flag, stack size)
876  coin_selection_params.tx_noinputs_size = 10 + GetSizeOfCompactSize(vecSend.size()); // bytes for output count
877 
878  // vouts to the payees
879  for (const auto& recipient : vecSend)
880  {
881  CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
882 
883  // Include the fee cost for outputs.
884  coin_selection_params.tx_noinputs_size += ::GetSerializeSize(txout, PROTOCOL_VERSION);
885 
886  if (IsDust(txout, wallet.chain().relayDustFee())) {
887  return util::Error{_("Transaction amount too small")};
888  }
889  txNew.vout.push_back(txout);
890  }
891 
892  // Include the fees for things that aren't inputs, excluding the change output
893  const CAmount not_input_fees = coin_selection_params.m_effective_feerate.GetFee(coin_selection_params.m_subtract_fee_outputs ? 0 : coin_selection_params.tx_noinputs_size);
894  CAmount selection_target = recipients_sum + not_input_fees;
895 
896  // Fetch manually selected coins
897  PreSelectedInputs preset_inputs;
898  if (coin_control.HasSelected()) {
899  auto res_fetch_inputs = FetchSelectedInputs(wallet, coin_control, coin_selection_params);
900  if (!res_fetch_inputs) return util::Error{util::ErrorString(res_fetch_inputs)};
901  preset_inputs = *res_fetch_inputs;
902  }
903 
904  // Fetch wallet available coins if "other inputs" are
905  // allowed (coins automatically selected by the wallet)
906  CoinsResult available_coins;
907  if (coin_control.m_allow_other_inputs) {
908  available_coins = AvailableCoins(wallet, &coin_control, coin_selection_params.m_effective_feerate);
909  }
910 
911  // Choose coins to use
912  auto select_coins_res = SelectCoins(wallet, available_coins, preset_inputs, /*nTargetValue=*/selection_target, coin_control, coin_selection_params);
913  if (!select_coins_res) {
914  // 'SelectCoins' either returns a specific error message or, if empty, means a general "Insufficient funds".
915  const bilingual_str& err = util::ErrorString(select_coins_res);
916  return util::Error{err.empty() ?_("Insufficient funds") : err};
917  }
918  const SelectionResult& result = *select_coins_res;
919  TRACE5(coin_selection, selected_coins, wallet.GetName().c_str(), GetAlgorithmName(result.GetAlgo()).c_str(), result.GetTarget(), result.GetWaste(), result.GetSelectedValue());
920 
921  const CAmount change_amount = result.GetChange(coin_selection_params.min_viable_change, coin_selection_params.m_change_fee);
922  if (change_amount > 0) {
923  CTxOut newTxOut(change_amount, scriptChange);
924  if (nChangePosInOut == -1) {
925  // Insert change txn at random position:
926  nChangePosInOut = rng_fast.randrange(txNew.vout.size() + 1);
927  } else if ((unsigned int)nChangePosInOut > txNew.vout.size()) {
928  return util::Error{_("Transaction change output index out of range")};
929  }
930  txNew.vout.insert(txNew.vout.begin() + nChangePosInOut, newTxOut);
931  } else {
932  nChangePosInOut = -1;
933  }
934 
935  // Shuffle selected coins and fill in final vin
936  std::vector<COutput> selected_coins = result.GetShuffledInputVector();
937 
938  // The sequence number is set to non-maxint so that DiscourageFeeSniping
939  // works.
940  //
941  // BIP125 defines opt-in RBF as any nSequence < maxint-1, so
942  // we use the highest possible value in that range (maxint-2)
943  // to avoid conflicting with other possible uses of nSequence,
944  // and in the spirit of "smallest possible change from prior
945  // behavior."
946  const uint32_t nSequence{coin_control.m_signal_bip125_rbf.value_or(wallet.m_signal_rbf) ? MAX_BIP125_RBF_SEQUENCE : CTxIn::MAX_SEQUENCE_NONFINAL};
947  for (const auto& coin : selected_coins) {
948  txNew.vin.push_back(CTxIn(coin.outpoint, CScript(), nSequence));
949  }
950  DiscourageFeeSniping(txNew, rng_fast, wallet.chain(), wallet.GetLastBlockHash(), wallet.GetLastBlockHeight());
951 
952  // Calculate the transaction fee
953  TxSize tx_sizes = CalculateMaximumSignedTxSize(CTransaction(txNew), &wallet, &coin_control);
954  int nBytes = tx_sizes.vsize;
955  if (nBytes == -1) {
956  return util::Error{_("Missing solving data for estimating transaction size")};
957  }
958  CAmount fee_needed = coin_selection_params.m_effective_feerate.GetFee(nBytes);
959  const CAmount output_value = CalculateOutputValue(txNew);
960  Assume(recipients_sum + change_amount == output_value);
961  CAmount current_fee = result.GetSelectedValue() - output_value;
962 
963  // Sanity check that the fee cannot be negative as that means we have more output value than input value
964  if (current_fee < 0) {
965  return util::Error{Untranslated(STR_INTERNAL_BUG("Fee paid < 0"))};
966  }
967 
968  // If there is a change output and we overpay the fees then increase the change to match the fee needed
969  if (nChangePosInOut != -1 && fee_needed < current_fee) {
970  auto& change = txNew.vout.at(nChangePosInOut);
971  change.nValue += current_fee - fee_needed;
972  current_fee = result.GetSelectedValue() - CalculateOutputValue(txNew);
973  if (fee_needed != current_fee) {
974  return util::Error{Untranslated(STR_INTERNAL_BUG("Change adjustment: Fee needed != fee paid"))};
975  }
976  }
977 
978  // Reduce output values for subtractFeeFromAmount
979  if (coin_selection_params.m_subtract_fee_outputs) {
980  CAmount to_reduce = fee_needed - current_fee;
981  int i = 0;
982  bool fFirst = true;
983  for (const auto& recipient : vecSend)
984  {
985  if (i == nChangePosInOut) {
986  ++i;
987  }
988  CTxOut& txout = txNew.vout[i];
989 
990  if (recipient.fSubtractFeeFromAmount)
991  {
992  txout.nValue -= to_reduce / outputs_to_subtract_fee_from; // Subtract fee equally from each selected recipient
993 
994  if (fFirst) // first receiver pays the remainder not divisible by output count
995  {
996  fFirst = false;
997  txout.nValue -= to_reduce % outputs_to_subtract_fee_from;
998  }
999 
1000  // Error if this output is reduced to be below dust
1001  if (IsDust(txout, wallet.chain().relayDustFee())) {
1002  if (txout.nValue < 0) {
1003  return util::Error{_("The transaction amount is too small to pay the fee")};
1004  } else {
1005  return util::Error{_("The transaction amount is too small to send after the fee has been deducted")};
1006  }
1007  }
1008  }
1009  ++i;
1010  }
1011  current_fee = result.GetSelectedValue() - CalculateOutputValue(txNew);
1012  if (fee_needed != current_fee) {
1013  return util::Error{Untranslated(STR_INTERNAL_BUG("SFFO: Fee needed != fee paid"))};
1014  }
1015  }
1016 
1017  // fee_needed should now always be less than or equal to the current fees that we pay.
1018  // If it is not, it is a bug.
1019  if (fee_needed > current_fee) {
1020  return util::Error{Untranslated(STR_INTERNAL_BUG("Fee needed > fee paid"))};
1021  }
1022 
1023  // Give up if change keypool ran out and change is required
1024  if (scriptChange.empty() && nChangePosInOut != -1) {
1025  return util::Error{error};
1026  }
1027 
1028  if (sign && !wallet.SignTransaction(txNew)) {
1029  return util::Error{_("Signing transaction failed")};
1030  }
1031 
1032  // Return the constructed transaction data.
1033  CTransactionRef tx = MakeTransactionRef(std::move(txNew));
1034 
1035  // Limit size
1036  if ((sign && GetTransactionWeight(*tx) > MAX_STANDARD_TX_WEIGHT) ||
1037  (!sign && tx_sizes.weight > MAX_STANDARD_TX_WEIGHT))
1038  {
1039  return util::Error{_("Transaction too large")};
1040  }
1041 
1042  if (current_fee > wallet.m_default_max_tx_fee) {
1044  }
1045 
1046  if (gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
1047  // Lastly, ensure this tx will pass the mempool's chain limits
1048  if (!wallet.chain().checkChainLimits(tx)) {
1049  return util::Error{_("Transaction has too long of a mempool chain")};
1050  }
1051  }
1052 
1053  // Before we return success, we assume any change key will be used to prevent
1054  // accidental re-use.
1055  reservedest.KeepDestination();
1056 
1057  wallet.WalletLogPrintf("Fee Calculation: Fee:%d Bytes:%u Tgt:%d (requested %d) Reason:\"%s\" Decay %.5f: Estimation: (%g - %g) %.2f%% %.1f/(%.1f %d mem %.1f out) Fail: (%g - %g) %.2f%% %.1f/(%.1f %d mem %.1f out)\n",
1058  current_fee, nBytes, feeCalc.returnedTarget, feeCalc.desiredTarget, StringForFeeReason(feeCalc.reason), feeCalc.est.decay,
1059  feeCalc.est.pass.start, feeCalc.est.pass.end,
1060  (feeCalc.est.pass.totalConfirmed + feeCalc.est.pass.inMempool + feeCalc.est.pass.leftMempool) > 0.0 ? 100 * feeCalc.est.pass.withinTarget / (feeCalc.est.pass.totalConfirmed + feeCalc.est.pass.inMempool + feeCalc.est.pass.leftMempool) : 0.0,
1061  feeCalc.est.pass.withinTarget, feeCalc.est.pass.totalConfirmed, feeCalc.est.pass.inMempool, feeCalc.est.pass.leftMempool,
1062  feeCalc.est.fail.start, feeCalc.est.fail.end,
1063  (feeCalc.est.fail.totalConfirmed + feeCalc.est.fail.inMempool + feeCalc.est.fail.leftMempool) > 0.0 ? 100 * feeCalc.est.fail.withinTarget / (feeCalc.est.fail.totalConfirmed + feeCalc.est.fail.inMempool + feeCalc.est.fail.leftMempool) : 0.0,
1064  feeCalc.est.fail.withinTarget, feeCalc.est.fail.totalConfirmed, feeCalc.est.fail.inMempool, feeCalc.est.fail.leftMempool);
1065  return CreatedTransactionResult(tx, current_fee, nChangePosInOut, feeCalc);
1066 }
1067 
1069  CWallet& wallet,
1070  const std::vector<CRecipient>& vecSend,
1071  int change_pos,
1072  const CCoinControl& coin_control,
1073  bool sign)
1074 {
1075  if (vecSend.empty()) {
1076  return util::Error{_("Transaction must have at least one recipient")};
1077  }
1078 
1079  if (std::any_of(vecSend.cbegin(), vecSend.cend(), [](const auto& recipient){ return recipient.nAmount < 0; })) {
1080  return util::Error{_("Transaction amounts must not be negative")};
1081  }
1082 
1083  LOCK(wallet.cs_wallet);
1084 
1085  auto res = CreateTransactionInternal(wallet, vecSend, change_pos, coin_control, sign);
1086  TRACE4(coin_selection, normal_create_tx_internal, wallet.GetName().c_str(), bool(res),
1087  res ? res->fee : 0, res ? res->change_pos : 0);
1088  if (!res) return res;
1089  const auto& txr_ungrouped = *res;
1090  // try with avoidpartialspends unless it's enabled already
1091  if (txr_ungrouped.fee > 0 /* 0 means non-functional fee rate estimation */ && wallet.m_max_aps_fee > -1 && !coin_control.m_avoid_partial_spends) {
1092  TRACE1(coin_selection, attempting_aps_create_tx, wallet.GetName().c_str());
1093  CCoinControl tmp_cc = coin_control;
1094  tmp_cc.m_avoid_partial_spends = true;
1095  auto txr_grouped = CreateTransactionInternal(wallet, vecSend, change_pos, tmp_cc, sign);
1096  // if fee of this alternative one is within the range of the max fee, we use this one
1097  const bool use_aps{txr_grouped.has_value() ? (txr_grouped->fee <= txr_ungrouped.fee + wallet.m_max_aps_fee) : false};
1098  TRACE5(coin_selection, aps_create_tx_internal, wallet.GetName().c_str(), use_aps, txr_grouped.has_value(),
1099  txr_grouped.has_value() ? txr_grouped->fee : 0, txr_grouped.has_value() ? txr_grouped->change_pos : 0);
1100  if (txr_grouped) {
1101  wallet.WalletLogPrintf("Fee non-grouped = %lld, grouped = %lld, using %s\n",
1102  txr_ungrouped.fee, txr_grouped->fee, use_aps ? "grouped" : "non-grouped");
1103  if (use_aps) return txr_grouped;
1104  }
1105  }
1106  return res;
1107 }
1108 
1109 bool FundTransaction(CWallet& wallet, CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, bilingual_str& error, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl coinControl)
1110 {
1111  std::vector<CRecipient> vecSend;
1112 
1113  // Turn the txout set into a CRecipient vector.
1114  for (size_t idx = 0; idx < tx.vout.size(); idx++) {
1115  const CTxOut& txOut = tx.vout[idx];
1116  CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, setSubtractFeeFromOutputs.count(idx) == 1};
1117  vecSend.push_back(recipient);
1118  }
1119 
1120  // Acquire the locks to prevent races to the new locked unspents between the
1121  // CreateTransaction call and LockCoin calls (when lockUnspents is true).
1122  LOCK(wallet.cs_wallet);
1123 
1124  // Fetch specified UTXOs from the UTXO set to get the scriptPubKeys and values of the outputs being selected
1125  // and to match with the given solving_data. Only used for non-wallet outputs.
1126  std::map<COutPoint, Coin> coins;
1127  for (const CTxIn& txin : tx.vin) {
1128  coins[txin.prevout]; // Create empty map entry keyed by prevout.
1129  }
1130  wallet.chain().findCoins(coins);
1131 
1132  for (const CTxIn& txin : tx.vin) {
1133  const auto& outPoint = txin.prevout;
1134  if (wallet.IsMine(outPoint)) {
1135  // The input was found in the wallet, so select as internal
1136  coinControl.Select(outPoint);
1137  } else if (coins[outPoint].out.IsNull()) {
1138  error = _("Unable to find UTXO for external input");
1139  return false;
1140  } else {
1141  // The input was not in the wallet, but is in the UTXO set, so select as external
1142  coinControl.SelectExternal(outPoint, coins[outPoint].out);
1143  }
1144  }
1145 
1146  auto res = CreateTransaction(wallet, vecSend, nChangePosInOut, coinControl, false);
1147  if (!res) {
1148  error = util::ErrorString(res);
1149  return false;
1150  }
1151  const auto& txr = *res;
1152  CTransactionRef tx_new = txr.tx;
1153  nFeeRet = txr.fee;
1154  nChangePosInOut = txr.change_pos;
1155 
1156  if (nChangePosInOut != -1) {
1157  tx.vout.insert(tx.vout.begin() + nChangePosInOut, tx_new->vout[nChangePosInOut]);
1158  }
1159 
1160  // Copy output sizes from new transaction; they may have had the fee
1161  // subtracted from them.
1162  for (unsigned int idx = 0; idx < tx.vout.size(); idx++) {
1163  tx.vout[idx].nValue = tx_new->vout[idx].nValue;
1164  }
1165 
1166  // Add new txins while keeping original txin scriptSig/order.
1167  for (const CTxIn& txin : tx_new->vin) {
1168  if (!coinControl.IsSelected(txin.prevout)) {
1169  tx.vin.push_back(txin);
1170 
1171  }
1172  if (lockUnspents) {
1173  wallet.LockCoin(txin.prevout);
1174  }
1175 
1176  }
1177 
1178  return true;
1179 }
1180 } // namespace wallet
static constexpr CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition: amount.h:26
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
#define CHECK_NONFATAL(condition)
Identity function.
Definition: check.h:46
#define Assert(val)
Identity function.
Definition: check.h:73
#define STR_INTERNAL_BUG(msg)
Definition: check.h:23
#define Assume(val)
Assume is the identity function.
Definition: check.h:85
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:641
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:36
uint32_t n
Definition: transaction.h:39
uint256 hash
Definition: transaction.h:38
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:411
A reference to a CScript: the Hash160 of its serialization (see script.h)
Definition: standard.h:27
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:295
const std::vector< CTxOut > vout
Definition: transaction.h:306
const std::vector< CTxIn > vin
Definition: transaction.h:305
An input of a transaction.
Definition: transaction.h:75
static const uint32_t MAX_SEQUENCE_NONFINAL
This is the maximum sequence number that enables both nLockTime and OP_CHECKLOCKTIMEVERIFY (BIP 65).
Definition: transaction.h:95
static const uint32_t SEQUENCE_FINAL
Setting nSequence to this value for every input in a transaction disables nLockTime/IsFinalTx().
Definition: transaction.h:89
COutPoint prevout
Definition: transaction.h:77
An output of a transaction.
Definition: transaction.h:158
CScript scriptPubKey
Definition: transaction.h:161
CAmount nValue
Definition: transaction.h:160
Fast randomness source.
Definition: random.h:143
uint64_t randrange(uint64_t range) noexcept
Generate a random integer in the range [0..range).
Definition: random.h:213
An interface to be implemented by keystores that support signing.
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:119
virtual bool isInitialBlockDownload()=0
Check if in IBD.
virtual bool findBlock(const uint256 &hash, const FoundBlock &block={})=0
Return whether node has the block and optionally return block metadata or contents.
Helper for findBlock to selectively return pieces of block data.
Definition: chain.h:52
bool empty() const
Definition: prevector.h:288
void emplace_back(Args &&... args)
Definition: prevector.h:422
160-bit opaque blob.
Definition: uint256.h:108
256-bit opaque blob.
Definition: uint256.h:119
Coin Control Features.
Definition: coincontrol.h:30
void Select(const COutPoint &output)
Definition: coincontrol.h:91
void SelectExternal(const COutPoint &outpoint, const CTxOut &txout)
Definition: coincontrol.h:96
bool m_avoid_address_reuse
Forbids inclusion of dirty (previously used) addresses.
Definition: coincontrol.h:54
bool IsSelected(const COutPoint &output) const
Definition: coincontrol.h:71
bool HasSelected() const
Definition: coincontrol.h:66
int m_min_depth
Minimum chain depth value for coin availability.
Definition: coincontrol.h:58
bool m_allow_other_inputs
If true, the selection process can add extra unselected inputs from the wallet while requires all sel...
Definition: coincontrol.h:40
int m_max_depth
Maximum chain depth value for coin availability.
Definition: coincontrol.h:60
bool m_include_unsafe_inputs
If false, only safe inputs will be used.
Definition: coincontrol.h:37
bool m_avoid_partial_spends
Avoid partial use of funds sent to a given address.
Definition: coincontrol.h:52
bool fAllowWatchOnly
Includes watch only addresses which are solvable.
Definition: coincontrol.h:42
bool GetExternalOutput(const COutPoint &outpoint, CTxOut &txout) const
Definition: coincontrol.h:81
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:237
A transaction with a bunch of additional info that only the owner cares about.
Definition: transaction.h:138
mapValue_t mapValue
Key/value map with information about the transaction.
Definition: transaction.h:165
CTransactionRef tx
Definition: transaction.h:219
bool InMempool() const
Definition: transaction.cpp:17
int64_t GetTxTime() const
Definition: transaction.cpp:22
A wrapper to reserve an address from a wallet.
Definition: wallet.h:166
static int64_t GetTransactionWeight(const CTransaction &tx)
Definition: validation.h:148
bilingual_str TransactionErrorString(const TransactionError err)
Definition: error.cpp:13
@ SAT_VB
Use sat/vB fee rate unit.
void KeepDestination()
Keep the address. Do not return its key to the keypool when this object goes out of scope.
Definition: wallet.cpp:2572
util::Result< CTxDestination > GetReservedDestination(bool internal)
Reserve an address.
Definition: wallet.cpp:2555
bool DummySignInput(const SigningProvider &provider, CTxIn &tx_in, const CTxOut &txout, const CCoinControl *coin_control)
Definition: wallet.cpp:1612
bilingual_str ErrorString(const Result< T > &result)
Definition: result.h:78
Definition: node.h:39
static constexpr size_t DUMMY_NESTED_P2WPKH_INPUT_SIZE
Pre-calculated constants for input size estimation in virtual size
Definition: wallet.h:117
const CTxOut & FindNonChangeParentOutput(const CWallet &wallet, const COutPoint &outpoint)
Find non-change parent output.
Definition: spend.cpp:365
static util::Result< CreatedTransactionResult > CreateTransactionInternal(CWallet &wallet, const std::vector< CRecipient > &vecSend, int change_pos, const CCoinControl &coin_control, bool sign) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
Definition: spend.cpp:765
bool OutputIsChange(const CWallet &wallet, const CTxOut &txout)
Definition: receive.cpp:73
bool FundTransaction(CWallet &wallet, CMutableTransaction &tx, CAmount &nFeeRet, int &nChangePosInOut, bilingual_str &error, bool lockUnspents, const std::set< int > &setSubtractFeeFromOutputs, CCoinControl coinControl)
Insert additional inputs into the transaction by calling CreateTransaction();.
Definition: spend.cpp:1109
CAmount GetAvailableBalance(const CWallet &wallet, const CCoinControl *coinControl)
Definition: spend.cpp:359
const int DEFAULT_MIN_DEPTH
Definition: coincontrol.h:22
CAmount GenerateChangeTarget(const CAmount payment_value, const CAmount change_fee, FastRandomContext &rng)
Choose a random change target for each transaction to make it harder to fingerprint the Core wallet b...
bool CachedTxIsFromMe(const CWallet &wallet, const CWalletTx &wtx, const isminefilter &filter)
Definition: receive.cpp:251
util::Result< PreSelectedInputs > FetchSelectedInputs(const CWallet &wallet, const CCoinControl &coin_control, const CoinSelectionParams &coin_selection_params) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
Fetch and validate coin control selected inputs.
Definition: spend.cpp:160
static OutputType GetOutputType(TxoutType type, bool is_from_p2sh)
Definition: spend.cpp:141
bool CachedTxIsTrusted(const CWallet &wallet, const CWalletTx &wtx, std::set< uint256 > &trusted_parents)
Definition: receive.cpp:256
const int DEFAULT_MAX_DEPTH
Definition: coincontrol.h:23
util::Result< CreatedTransactionResult > CreateTransaction(CWallet &wallet, const std::vector< CRecipient > &vecSend, int change_pos, const CCoinControl &coin_control, bool sign)
Create a new transaction paying the recipients with a set of coins selected by SelectCoins(); Also cr...
Definition: spend.cpp:1068
util::Result< SelectionResult > SelectCoins(const CWallet &wallet, CoinsResult &available_coins, const PreSelectedInputs &pre_set_inputs, const CAmount &nTargetValue, const CCoinControl &coin_control, const CoinSelectionParams &coin_selection_params)
Select all coins from coin_control, and if coin_control 'm_allow_other_inputs=true',...
Definition: spend.cpp:565
CFeeRate GetMinimumFeeRate(const CWallet &wallet, const CCoinControl &coin_control, FeeCalculation *feeCalc)
Estimate the minimum fee rate considering user set parameters and the required fee.
Definition: fees.cpp:29
std::optional< SelectionResult > SelectCoinsSRD(const std::vector< OutputGroup > &utxo_pool, CAmount target_value, FastRandomContext &rng)
Select coins by Single Random Draw.
std::optional< SelectionResult > KnapsackSolver(std::vector< OutputGroup > &groups, const CAmount &nTargetValue, CAmount change_target, FastRandomContext &rng)
std::map< CTxDestination, std::vector< COutput > > ListCoins(const CWallet &wallet)
Return list of available coins and locked coins grouped by non-change output address.
Definition: spend.cpp:385
isminetype
IsMine() return codes, which depend on ScriptPubKeyMan implementation.
Definition: ismine.h:41
@ ISMINE_NO
Definition: ismine.h:42
@ ISMINE_SPENDABLE
Definition: ismine.h:44
@ ISMINE_WATCH_ONLY
Definition: ismine.h:43
@ ISMINE_ALL
Definition: ismine.h:46
CoinsResult AvailableCoinsListUnspent(const CWallet &wallet, const CCoinControl *coinControl, CoinFilterParams params)
Wrapper function for AvailableCoins which skips the feerate and CoinFilterParams::only_spendable para...
Definition: spend.cpp:353
util::Result< SelectionResult > ChooseSelectionResult(const CWallet &wallet, const CAmount &nTargetValue, const CoinEligibilityFilter &eligibility_filter, const std::vector< COutput > &available_coins, const CoinSelectionParams &coin_selection_params)
Attempt to find a valid input set that meets the provided eligibility filter and target.
Definition: spend.cpp:521
std::string GetAlgorithmName(const SelectionAlgorithm algo)
TxSize CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, const CCoinControl *coin_control)
Definition: spend.cpp:62
static bool HasErrorMsg(const util::Result< SelectionResult > &res)
Definition: spend.cpp:492
int CalculateMaximumSignedInputSize(const CTxOut &txout, const COutPoint outpoint, const SigningProvider *provider, const CCoinControl *coin_control)
Definition: spend.cpp:33
std::vector< OutputGroup > GroupOutputs(const CWallet &wallet, const std::vector< COutput > &outputs, const CoinSelectionParams &coin_sel_params, const CoinEligibilityFilter &filter, bool positive_only)
Definition: spend.cpp:407
std::optional< SelectionResult > SelectCoinsBnB(std::vector< OutputGroup > &utxo_pool, const CAmount &selection_target, const CAmount &cost_of_change)
CFeeRate GetDiscardRate(const CWallet &wallet)
Return the maximum feerate for discarding change.
Definition: fees.cpp:84
TxSize CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, const std::vector< CTxOut > &txouts, const CCoinControl *coin_control)
Calculate the size of the transaction using CoinControl to determine whether to expect signature grin...
Definition: spend.cpp:50
@ WALLET_FLAG_AVOID_REUSE
Definition: walletutil.h:42
@ WALLET_FLAG_DISABLE_PRIVATE_KEYS
Definition: walletutil.h:51
static bool IsCurrentForAntiFeeSniping(interfaces::Chain &chain, const uint256 &block_hash)
Definition: spend.cpp:691
int CalculateMaximumSignedInputSize(const CTxOut &txout, const CWallet *wallet, const CCoinControl *coin_control)
Get the marginal bytes if spending the specified output from this transaction.
Definition: spend.cpp:43
util::Result< SelectionResult > AutomaticCoinSelection(const CWallet &wallet, CoinsResult &available_coins, const CAmount &value_to_select, const CCoinControl &coin_control, const CoinSelectionParams &coin_selection_params)
Select a set of coins such that nTargetValue is met; never select unconfirmed coins if they are not o...
Definition: spend.cpp:615
static void DiscourageFeeSniping(CMutableTransaction &tx, FastRandomContext &rng_fast, interfaces::Chain &chain, const uint256 &block_hash, int block_height)
Set a height-based locktime for new transactions (uses the height of the current chain tip unless we ...
Definition: spend.cpp:709
static constexpr size_t OUTPUT_GROUP_MAX_ENTRIES
Definition: spend.cpp:31
util::Result< SelectionResult > AttemptSelection(const CWallet &wallet, const CAmount &nTargetValue, const CoinEligibilityFilter &eligibility_filter, const CoinsResult &available_coins, const CoinSelectionParams &coin_selection_params, bool allow_mixed_output_types)
Attempt to find a valid input set that preserves privacy by not mixing OutputTypes.
Definition: spend.cpp:494
static const bool DEFAULT_WALLET_REJECT_LONG_CHAINS
Default for -walletrejectlongchains.
Definition: wallet.h:102
CoinsResult AvailableCoins(const CWallet &wallet, const CCoinControl *coinControl, std::optional< CFeeRate > feerate, const CoinFilterParams &params)
Populate the CoinsResult struct with vectors of available COutputs, organized by OutputType.
Definition: spend.cpp:203
OutputType
Definition: outputtype.h:17
CAmount GetDustThreshold(const CTxOut &txout, const CFeeRate &dustRelayFeeIn)
Definition: policy.cpp:26
int64_t GetVirtualTransactionSize(int64_t nWeight, int64_t nSigOpCost, unsigned int bytes_per_sigop)
Compute the virtual transaction size (weight reinterpreted as bytes).
Definition: policy.cpp:295
int64_t GetVirtualTransactionInputSize(const CTxIn &txin, int64_t nSigOpCost, unsigned int bytes_per_sigop)
Definition: policy.cpp:305
bool IsDust(const CTxOut &txout, const CFeeRate &dustRelayFeeIn)
Definition: policy.cpp:65
static constexpr unsigned int MAX_STANDARD_TX_WEIGHT
The maximum weight for transactions we're willing to relay/mine.
Definition: policy.h:27
CAmount CalculateOutputValue(const TxType &tx)
Definition: transaction.h:285
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:422
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:421
static const unsigned int LOCKTIME_THRESHOLD
Definition: script.h:43
unsigned int GetSizeOfCompactSize(uint64_t nSize)
Compact Size size < 253 – 1 byte size <= USHRT_MAX – 3 bytes (253 + 2 bytes) size <= UINT_MAX – 5 byt...
Definition: serialize.h:233
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1109
TxoutType Solver(const CScript &scriptPubKey, std::vector< std::vector< unsigned char >> &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
Definition: standard.cpp:168
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
Definition: standard.cpp:237
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition: standard.cpp:356
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:334
TxoutType
Definition: standard.h:51
@ WITNESS_V1_TAPROOT
@ WITNESS_V0_SCRIPTHASH
@ WITNESS_V0_KEYHASH
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:149
A mutable version of CTransaction.
Definition: transaction.h:380
std::vector< CTxOut > vout
Definition: transaction.h:382
std::vector< CTxIn > vin
Definition: transaction.h:381
EstimatorBucket fail
Definition: fees.h:71
EstimatorBucket pass
Definition: fees.h:70
double decay
Definition: fees.h:72
double totalConfirmed
Definition: fees.h:62
double end
Definition: fees.h:60
double leftMempool
Definition: fees.h:64
double start
Definition: fees.h:59
double withinTarget
Definition: fees.h:61
double inMempool
Definition: fees.h:63
int returnedTarget
Definition: fees.h:81
int desiredTarget
Definition: fees.h:80
FeeReason reason
Definition: fees.h:79
EstimationResult est
Definition: fees.h:78
Bilingual messages:
Definition: translation.h:18
bool empty() const
Definition: translation.h:29
A UTXO under consideration for use in funding a new transaction.
Definition: coinselection.h:25
CTxOut txout
The output itself.
Definition: coinselection.h:38
CAmount GetEffectiveValue() const
bool HasEffectiveValue() const
Parameters for filtering which OutputGroups we may use in coin selection.
const bool m_include_partial_groups
When avoid_reuse=true and there are full groups (OUTPUT_GROUP_MAX_ENTRIES), whether or not to use any...
uint64_t max_count
Definition: spend.h:74
bool include_immature_coinbase
Definition: spend.h:78
CAmount min_sum_amount
Definition: spend.h:72
Parameters for one iteration of Coin Selection.
FastRandomContext & rng_fast
Randomness to use in the context of coin selection.
CAmount m_min_change_target
Mininmum change to target in Knapsack solver: select coins to cover the payment and at least this val...
bool m_subtract_fee_outputs
Indicate that we are subtracting the fee from outputs.
CAmount min_viable_change
Minimum amount for creating a change output.
CAmount m_cost_of_change
Cost of creating the change output + cost of spending the change output in the future.
CAmount m_change_fee
Cost of creating the change output.
bool m_avoid_partial_spends
When true, always spend all (up to OUTPUT_GROUP_MAX_ENTRIES) or none of the outputs associated with t...
COutputs available for spending, stored by OutputType.
Definition: spend.h:40
std::optional< CAmount > GetEffectiveTotalAmount()
Definition: spend.h:57
size_t TypesCount() const
Return how many different output types this struct stores.
Definition: spend.h:50
CAmount total_amount
Sum of all available coins raw value.
Definition: spend.h:61
void Add(OutputType type, const COutput &out)
Definition: spend.cpp:131
std::vector< COutput > All() const
Concatenate and return all COutputs as one vector.
Definition: spend.cpp:94
size_t Size() const
The following methods are provided so that CoinsResult can mimic a vector, i.e., methods can work wit...
Definition: spend.cpp:85
std::map< OutputType, std::vector< COutput > > coins
Definition: spend.h:41
void Shuffle(FastRandomContext &rng_fast)
Definition: spend.cpp:124
std::optional< CAmount > total_effective_amount
Sum of all available coins effective value (each output value minus fees required to spend it)
Definition: spend.h:63
CAmount GetTotalAmount()
Definition: spend.h:56
void Erase(const std::unordered_set< COutPoint, SaltedOutpointHasher > &coins_to_remove)
Definition: spend.cpp:108
A group of UTXOs paid to the same output script.
void Insert(const COutput &output, size_t ancestors, size_t descendants, bool positive_only)
CAmount GetSelectionAmount() const
std::vector< COutput > m_outputs
The list of UTXOs contained in this output group.
bool EligibleForSpending(const CoinEligibilityFilter &eligibility_filter) const
void Insert(const COutput &output, bool subtract_fee_outputs)
Definition: spend.h:157
std::set< COutput > coins
Definition: spend.h:151
CoinEligibilityFilter filter
Definition: spend.cpp:611
void ComputeAndSetWaste(const CAmount min_viable_change, const CAmount change_cost, const CAmount change_fee)
Calculates and stores the waste for this selection via GetSelectionWaste.
void AddInputs(const std::set< COutput > &inputs, bool subtract_fee_outputs)
std::vector< COutput > GetShuffledInputVector() const
Get the vector of COutputs that will be used to fill in a CTransaction's vin.
CAmount GetChange(const CAmount min_viable_change, const CAmount change_fee) const
Get the amount for the change output after paying needed fees.
CAmount GetSelectedValue() const
Get the sum of the input values.
CAmount GetTarget() const
SelectionAlgorithm GetAlgo() const
CAmount GetWaste() const
int64_t vsize
Definition: spend.h:23
int64_t weight
Definition: spend.h:24
#define LOCK(cs)
Definition: sync.h:258
bool error(const char *fmt, const Args &... args)
Definition: system.h:48
static secp256k1_context * ctx
Definition: tests.c:35
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
int64_t GetTime()
Definition: time.cpp:115
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1165
#define TRACE5(context, event, a, b, c, d, e)
Definition: trace.h:33
#define TRACE4(context, event, a, b, c, d)
Definition: trace.h:32
#define TRACE1(context, event, a)
Definition: trace.h:29
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:65
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:48
std::string StringForFeeReason(FeeReason reason)
Definition: fees.cpp:17
static constexpr uint32_t MAX_BIP125_RBF_SEQUENCE
Definition: rbf.h:12
ArgsManager gArgs
Definition: system.cpp:73
AssertLockHeld(pool.cs)
assert(!tx.IsCoinBase())
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:12
static void AvailableCoins(benchmark::Bench &bench, const std::vector< OutputType > &output_type)