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