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