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