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