Bitcoin ABC  0.29.2
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 <wallet/spend.h>
6 
7 #include <consensus/validation.h>
8 #include <interfaces/chain.h>
9 #include <policy/policy.h>
10 #include <util/check.h>
11 #include <util/moneystr.h>
12 #include <util/translation.h>
13 #include <wallet/coincontrol.h>
14 #include <wallet/fees.h>
15 #include <wallet/receive.h>
16 #include <wallet/transaction.h>
17 #include <wallet/wallet.h>
18 
20 
21 static const size_t OUTPUT_GROUP_MAX_ENTRIES = 10;
22 
23 int GetTxSpendSize(const CWallet &wallet, const CWalletTx &wtx,
24  unsigned int out, bool use_max_sig) {
25  return CalculateMaximumSignedInputSize(wtx.tx->vout[out], &wallet,
26  use_max_sig);
27 }
28 std::string COutput::ToString() const {
29  return strprintf("COutput(%s, %d, %d) [%s]", tx->GetId().ToString(), i,
30  nDepth, FormatMoney(tx->tx->vout[i].nValue));
31 }
32 
34  bool use_max_sig) {
36  txn.vin.push_back(CTxIn(COutPoint()));
37  if (!wallet->DummySignInput(txn.vin[0], txout, use_max_sig)) {
38  return -1;
39  }
40  return GetSerializeSize(txn.vin[0], PROTOCOL_VERSION);
41 }
42 
43 // txouts needs to be in the order of tx.vin
45  const CWallet *wallet,
46  const std::vector<CTxOut> &txouts,
47  bool use_max_sig) {
48  CMutableTransaction txNew(tx);
49  if (!wallet->DummySignTx(txNew, txouts, use_max_sig)) {
50  return -1;
51  }
52  return GetSerializeSize(txNew, PROTOCOL_VERSION);
53 }
54 
56  const CWallet *wallet, bool use_max_sig) {
57  std::vector<CTxOut> txouts;
58  for (auto &input : tx.vin) {
59  const auto mi = wallet->mapWallet.find(input.prevout.GetTxId());
60  // Can not estimate size without knowing the input details
61  if (mi == wallet->mapWallet.end()) {
62  return -1;
63  }
64  assert(input.prevout.GetN() < mi->second.tx->vout.size());
65  txouts.emplace_back(mi->second.tx->vout[input.prevout.GetN()]);
66  }
67  return CalculateMaximumSignedTxSize(tx, wallet, txouts, use_max_sig);
68 }
69 
70 void AvailableCoins(const CWallet &wallet, std::vector<COutput> &vCoins,
71  const CCoinControl *coinControl,
72  const Amount nMinimumAmount, const Amount nMaximumAmount,
73  const Amount nMinimumSumAmount,
74  const uint64_t nMaximumCount) {
75  AssertLockHeld(wallet.cs_wallet);
76 
77  vCoins.clear();
78  Amount nTotal = Amount::zero();
79  // Either the WALLET_FLAG_AVOID_REUSE flag is not set (in which case we
80  // always allow), or we default to avoiding, and only in the case where a
81  // coin control object is provided, and has the avoid address reuse flag set
82  // to false, do we allow already used addresses
83  bool allow_used_addresses =
84  !wallet.IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE) ||
85  (coinControl && !coinControl->m_avoid_address_reuse);
86  const int min_depth = {coinControl ? coinControl->m_min_depth
88  const int max_depth = {coinControl ? coinControl->m_max_depth
90  const bool only_safe = {coinControl ? !coinControl->m_include_unsafe_inputs
91  : true};
92 
93  std::set<TxId> trusted_parents;
94  for (const auto &entry : wallet.mapWallet) {
95  const TxId &wtxid = entry.first;
96  const CWalletTx &wtx = entry.second;
97 
98  if (wallet.IsTxImmatureCoinBase(wtx)) {
99  continue;
100  }
101 
102  int nDepth = wallet.GetTxDepthInMainChain(wtx);
103  if (nDepth < 0) {
104  continue;
105  }
106 
107  // We should not consider coins which aren't at least in our mempool.
108  // It's possible for these to be conflicted via ancestors which we may
109  // never be able to detect.
110  if (nDepth == 0 && !wtx.InMempool()) {
111  continue;
112  }
113 
114  bool safeTx = CachedTxIsTrusted(wallet, wtx, trusted_parents);
115 
116  // Bitcoin-ABC: Removed check that prevents consideration of coins from
117  // transactions that are replacing other transactions. This check based
118  // on wtx.mapValue.count("replaces_txid") which was not being set
119  // anywhere.
120 
121  // Similarly, we should not consider coins from transactions that have
122  // been replaced. In the example above, we would want to prevent
123  // creation of a transaction A' spending an output of A, because if
124  // transaction B were initially confirmed, conflicting with A and A', we
125  // wouldn't want to the user to create a transaction D intending to
126  // replace A', but potentially resulting in a scenario where A, A', and
127  // D could all be accepted (instead of just B and D, or just A and A'
128  // like the user would want).
129 
130  // Bitcoin-ABC: retained this check as 'replaced_by_txid' is still set
131  // in the wallet code.
132  if (nDepth == 0 && wtx.mapValue.count("replaced_by_txid")) {
133  safeTx = false;
134  }
135 
136  if (only_safe && !safeTx) {
137  continue;
138  }
139 
140  if (nDepth < min_depth || nDepth > max_depth) {
141  continue;
142  }
143 
144  for (uint32_t i = 0; i < wtx.tx->vout.size(); i++) {
145  // Only consider selected coins if add_inputs is false
146  if (coinControl && !coinControl->m_add_inputs &&
147  !coinControl->IsSelected(COutPoint(entry.first, i))) {
148  continue;
149  }
150 
151  if (wtx.tx->vout[i].nValue < nMinimumAmount ||
152  wtx.tx->vout[i].nValue > nMaximumAmount) {
153  continue;
154  }
155 
156  const COutPoint outpoint(wtxid, i);
157 
158  if (coinControl && coinControl->HasSelected() &&
159  !coinControl->fAllowOtherInputs &&
160  !coinControl->IsSelected(outpoint)) {
161  continue;
162  }
163 
164  if (wallet.IsLockedCoin(outpoint)) {
165  continue;
166  }
167 
168  if (wallet.IsSpent(outpoint)) {
169  continue;
170  }
171 
172  isminetype mine = wallet.IsMine(wtx.tx->vout[i]);
173 
174  if (mine == ISMINE_NO) {
175  continue;
176  }
177 
178  if (!allow_used_addresses && wallet.IsSpentKey(wtxid, i)) {
179  continue;
180  }
181 
182  std::unique_ptr<SigningProvider> provider =
183  wallet.GetSolvingProvider(wtx.tx->vout[i].scriptPubKey);
184 
185  bool solvable =
186  provider ? IsSolvable(*provider, wtx.tx->vout[i].scriptPubKey)
187  : false;
188  bool spendable =
189  ((mine & ISMINE_SPENDABLE) != ISMINE_NO) ||
190  (((mine & ISMINE_WATCH_ONLY) != ISMINE_NO) &&
191  (coinControl && coinControl->fAllowWatchOnly && solvable));
192 
193  vCoins.push_back(
194  COutput(wallet, wtx, i, nDepth, spendable, solvable, safeTx,
195  (coinControl && coinControl->fAllowWatchOnly)));
196 
197  // Checks the sum amount of all UTXO's.
198  if (nMinimumSumAmount != MAX_MONEY) {
199  nTotal += wtx.tx->vout[i].nValue;
200 
201  if (nTotal >= nMinimumSumAmount) {
202  return;
203  }
204  }
205 
206  // Checks the maximum number of UTXO's.
207  if (nMaximumCount > 0 && vCoins.size() >= nMaximumCount) {
208  return;
209  }
210  }
211  }
212 }
213 
215  const CCoinControl *coinControl) {
216  LOCK(wallet.cs_wallet);
217 
219  std::vector<COutput> vCoins;
220  AvailableCoins(wallet, vCoins, coinControl);
221  for (const COutput &out : vCoins) {
222  if (out.fSpendable) {
223  balance += out.tx->tx->vout[out.i].nValue;
224  }
225  }
226  return balance;
227 }
228 
230  const CTransaction &tx, int output) {
231  AssertLockHeld(wallet.cs_wallet);
232  const CTransaction *ptx = &tx;
233  int n = output;
234  while (OutputIsChange(wallet, ptx->vout[n]) && ptx->vin.size() > 0) {
235  const COutPoint &prevout = ptx->vin[0].prevout;
236  auto it = wallet.mapWallet.find(prevout.GetTxId());
237  if (it == wallet.mapWallet.end() ||
238  it->second.tx->vout.size() <= prevout.GetN() ||
239  !wallet.IsMine(it->second.tx->vout[prevout.GetN()])) {
240  break;
241  }
242  ptx = it->second.tx.get();
243  n = prevout.GetN();
244  }
245  return ptx->vout[n];
246 }
247 
248 std::map<CTxDestination, std::vector<COutput>>
250  AssertLockHeld(wallet.cs_wallet);
251 
252  std::map<CTxDestination, std::vector<COutput>> result;
253  std::vector<COutput> availableCoins;
254 
255  AvailableCoins(wallet, availableCoins);
256 
257  for (const auto &coin : availableCoins) {
258  CTxDestination address;
259  if ((coin.fSpendable ||
260  (wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) &&
261  coin.fSolvable)) &&
263  FindNonChangeParentOutput(wallet, *coin.tx->tx, coin.i)
264  .scriptPubKey,
265  address)) {
266  result[address].emplace_back(std::move(coin));
267  }
268  }
269 
270  std::vector<COutPoint> lockedCoins;
271  wallet.ListLockedCoins(lockedCoins);
272  // Include watch-only for LegacyScriptPubKeyMan wallets without private keys
273  const bool include_watch_only =
274  wallet.GetLegacyScriptPubKeyMan() &&
275  wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS);
276  const isminetype is_mine_filter =
277  include_watch_only ? ISMINE_WATCH_ONLY : ISMINE_SPENDABLE;
278  for (const auto &output : lockedCoins) {
279  auto it = wallet.mapWallet.find(output.GetTxId());
280  if (it != wallet.mapWallet.end()) {
281  int depth = wallet.GetTxDepthInMainChain(it->second);
282  if (depth >= 0 && output.GetN() < it->second.tx->vout.size() &&
283  wallet.IsMine(it->second.tx->vout[output.GetN()]) ==
284  is_mine_filter) {
285  CTxDestination address;
287  *it->second.tx,
288  output.GetN())
289  .scriptPubKey,
290  address)) {
291  result[address].emplace_back(
292  wallet, it->second, output.GetN(), depth,
293  true /* spendable */, true /* solvable */,
294  false /* safe */);
295  }
296  }
297  }
298  }
299 
300  return result;
301 }
302 
303 std::vector<OutputGroup>
304 GroupOutputs(const CWallet &wallet, const std::vector<COutput> &outputs,
305  bool separate_coins, const CFeeRate &effective_feerate,
306  const CFeeRate &long_term_feerate,
307  const CoinEligibilityFilter &filter, bool positive_only) {
308  std::vector<OutputGroup> groups_out;
309 
310  if (separate_coins) {
311  // Single coin means no grouping. Each COutput gets its own OutputGroup.
312  for (const COutput &output : outputs) {
313  // Skip outputs we cannot spend
314  if (!output.fSpendable) {
315  continue;
316  }
317 
318  CInputCoin input_coin = output.GetInputCoin();
319 
320  // Make an OutputGroup containing just this output
321  OutputGroup group{effective_feerate, long_term_feerate};
322  group.Insert(input_coin, output.nDepth,
323  CachedTxIsFromMe(wallet, *output.tx, ISMINE_ALL),
324  positive_only);
325 
326  // Check the OutputGroup's eligibility. Only add the eligible ones.
327  if (positive_only && group.effective_value <= Amount::zero()) {
328  continue;
329  }
330  if (group.m_outputs.size() > 0 &&
331  group.EligibleForSpending(filter)) {
332  groups_out.push_back(group);
333  }
334  }
335  return groups_out;
336  }
337 
338  // We want to combine COutputs that have the same scriptPubKey into single
339  // OutputGroups except when there are more than OUTPUT_GROUP_MAX_ENTRIES
340  // COutputs grouped in an OutputGroup.
341  // To do this, we maintain a map where the key is the scriptPubKey and the
342  // value is a vector of OutputGroups.
343  // For each COutput, we check if the scriptPubKey is in the map, and if it
344  // is, the COutput's CInputCoin is added to the last OutputGroup in the
345  // vector for the scriptPubKey. When the last OutputGroup has
346  // OUTPUT_GROUP_MAX_ENTRIES CInputCoins, a new OutputGroup is added to the
347  // end of the vector.
348  std::map<CScript, std::vector<OutputGroup>> spk_to_groups_map;
349  for (const auto &output : outputs) {
350  // Skip outputs we cannot spend
351  if (!output.fSpendable) {
352  continue;
353  }
354 
355  CInputCoin input_coin = output.GetInputCoin();
356  CScript spk = input_coin.txout.scriptPubKey;
357 
358  std::vector<OutputGroup> &groups = spk_to_groups_map[spk];
359 
360  if (groups.size() == 0) {
361  // No OutputGroups for this scriptPubKey yet, add one
362  groups.emplace_back(effective_feerate, long_term_feerate);
363  }
364 
365  // Get the last OutputGroup in the vector so that we can add the
366  // CInputCoin to it.
367  // A pointer is used here so that group can be reassigned later if it
368  // is full.
369  OutputGroup *group = &groups.back();
370 
371  // Check if this OutputGroup is full. We limit to
372  // OUTPUT_GROUP_MAX_ENTRIES when using -avoidpartialspends to avoid
373  // surprising users with very high fees.
374  if (group->m_outputs.size() >= OUTPUT_GROUP_MAX_ENTRIES) {
375  // The last output group is full, add a new group to the vector and
376  // use that group for the insertion
377  groups.emplace_back(effective_feerate, long_term_feerate);
378  group = &groups.back();
379  }
380 
381  // Add the input_coin to group
382  group->Insert(input_coin, output.nDepth,
383  CachedTxIsFromMe(wallet, *output.tx, ISMINE_ALL),
384  positive_only);
385  }
386 
387  // Now we go through the entire map and pull out the OutputGroups
388  for (const auto &spk_and_groups_pair : spk_to_groups_map) {
389  const std::vector<OutputGroup> &groups_per_spk =
390  spk_and_groups_pair.second;
391 
392  // Go through the vector backwards. This allows for the first item we
393  // deal with being the partial group.
394  for (auto group_it = groups_per_spk.rbegin();
395  group_it != groups_per_spk.rend(); group_it++) {
396  const OutputGroup &group = *group_it;
397 
398  // Don't include partial groups if there are full groups too and we
399  // don't want partial groups
400  if (group_it == groups_per_spk.rbegin() &&
401  groups_per_spk.size() > 1 && !filter.m_include_partial_groups) {
402  continue;
403  }
404 
405  // Check the OutputGroup's eligibility. Only add the eligible ones.
406  if (positive_only && group.effective_value <= Amount::zero()) {
407  continue;
408  }
409  if (group.m_outputs.size() > 0 &&
410  group.EligibleForSpending(filter)) {
411  groups_out.push_back(group);
412  }
413  }
414  }
415 
416  return groups_out;
417 }
418 
419 bool SelectCoinsMinConf(const CWallet &wallet, const Amount nTargetValue,
420  const CoinEligibilityFilter &eligibility_filter,
421  std::vector<COutput> coins,
422  std::set<CInputCoin> &setCoinsRet, Amount &nValueRet,
424  bool &bnb_used) {
425  setCoinsRet.clear();
426  nValueRet = Amount::zero();
427 
429  // Get long term estimate
430  CCoinControl temp;
431  temp.m_confirm_target = 1008;
432  CFeeRate long_term_feerate = GetMinimumFeeRate(wallet, temp);
433 
434  // Get the feerate for effective value.
435  // When subtracting the fee from the outputs, we want the effective
436  // feerate to be 0
437  CFeeRate effective_feerate{Amount::zero()};
439  effective_feerate = coin_selection_params.effective_fee;
440  }
441 
442  std::vector<OutputGroup> groups = GroupOutputs(
444  effective_feerate, long_term_feerate, eligibility_filter,
445  /*positive_only=*/true);
446 
447  // Calculate cost of change
448  Amount cost_of_change = wallet.chain().relayDustFee().GetFee(
452 
453  // Calculate the fees for things that aren't inputs
456  bnb_used = true;
457  return SelectCoinsBnB(groups, nTargetValue, cost_of_change, setCoinsRet,
458  nValueRet, not_input_fees);
459  } else {
460  std::vector<OutputGroup> groups = GroupOutputs(
463  eligibility_filter,
464  /*positive_only=*/false);
465 
466  bnb_used = false;
467  return KnapsackSolver(nTargetValue, groups, setCoinsRet, nValueRet);
468  }
469 }
470 
472  const std::vector<COutput> &vAvailableCoins,
473  const Amount nTargetValue, std::set<CInputCoin> &setCoinsRet,
474  Amount &nValueRet, const CCoinControl &coin_control,
475  CoinSelectionParams &coin_selection_params, bool &bnb_used) {
476  std::vector<COutput> vCoins(vAvailableCoins);
477  Amount value_to_select = nTargetValue;
478 
479  // Default to bnb was not used. If we use it, we set it later
480  bnb_used = false;
481 
482  // coin control -> return all selected outputs (we want all selected to go
483  // into the transaction for sure)
484  if (coin_control.HasSelected() && !coin_control.fAllowOtherInputs) {
485  for (const COutput &out : vCoins) {
486  if (!out.fSpendable) {
487  continue;
488  }
489 
490  nValueRet += out.tx->tx->vout[out.i].nValue;
491  setCoinsRet.insert(out.GetInputCoin());
492  }
493 
494  return (nValueRet >= nTargetValue);
495  }
496 
497  // Calculate value from preset inputs and store them.
498  std::set<CInputCoin> setPresetCoins;
499  Amount nValueFromPresetInputs = Amount::zero();
500 
501  std::vector<COutPoint> vPresetInputs;
502  coin_control.ListSelected(vPresetInputs);
503 
504  for (const COutPoint &outpoint : vPresetInputs) {
505  std::map<TxId, CWalletTx>::const_iterator it =
506  wallet.mapWallet.find(outpoint.GetTxId());
507  if (it != wallet.mapWallet.end()) {
508  const CWalletTx &wtx = it->second;
509  // Clearly invalid input, fail
510  if (wtx.tx->vout.size() <= outpoint.GetN()) {
511  return false;
512  }
513  // Just to calculate the marginal byte size
514  CInputCoin coin(
515  wtx.tx, outpoint.GetN(),
516  GetTxSpendSize(wallet, wtx, outpoint.GetN(), false));
517  nValueFromPresetInputs += coin.txout.nValue;
518  if (coin.m_input_bytes <= 0) {
519  // Not solvable, can't estimate size for fee
520  return false;
521  }
522  coin.effective_value =
523  coin.txout.nValue -
526  value_to_select -= coin.effective_value;
527  } else {
528  value_to_select -= coin.txout.nValue;
529  }
530  setPresetCoins.insert(coin);
531  } else {
532  return false; // TODO: Allow non-wallet inputs
533  }
534  }
535 
536  // Remove preset inputs from vCoins
537  for (std::vector<COutput>::iterator it = vCoins.begin();
538  it != vCoins.end() && coin_control.HasSelected();) {
539  if (setPresetCoins.count(it->GetInputCoin())) {
540  it = vCoins.erase(it);
541  } else {
542  ++it;
543  }
544  }
545 
546  // form groups from remaining coins; note that preset coins will not
547  // automatically have their associated (same address) coins included
548  if (coin_control.m_avoid_partial_spends &&
549  vCoins.size() > OUTPUT_GROUP_MAX_ENTRIES) {
550  // Cases where we have 11+ outputs all pointing to the same destination
551  // may result in privacy leaks as they will potentially be
552  // deterministically sorted. We solve that by explicitly shuffling the
553  // outputs before processing
554  Shuffle(vCoins.begin(), vCoins.end(), FastRandomContext());
555  }
556 
557  bool res =
558  value_to_select <= Amount::zero() ||
559  SelectCoinsMinConf(wallet, value_to_select, CoinEligibilityFilter(1, 6),
560  vCoins, setCoinsRet, nValueRet,
561  coin_selection_params, bnb_used) ||
562  SelectCoinsMinConf(wallet, value_to_select, CoinEligibilityFilter(1, 1),
563  vCoins, setCoinsRet, nValueRet,
564  coin_selection_params, bnb_used) ||
565  (wallet.m_spend_zero_conf_change &&
566  SelectCoinsMinConf(wallet, value_to_select,
567  CoinEligibilityFilter(0, 1), vCoins, setCoinsRet,
568  nValueRet, coin_selection_params, bnb_used)) ||
569  (wallet.m_spend_zero_conf_change &&
570  SelectCoinsMinConf(wallet, value_to_select,
571  CoinEligibilityFilter(0, 1), vCoins, setCoinsRet,
572  nValueRet, coin_selection_params, bnb_used)) ||
573  (wallet.m_spend_zero_conf_change &&
574  SelectCoinsMinConf(wallet, value_to_select,
575  CoinEligibilityFilter(0, 1), vCoins, setCoinsRet,
576  nValueRet, coin_selection_params, bnb_used)) ||
577  (wallet.m_spend_zero_conf_change &&
579  wallet, value_to_select,
580  CoinEligibilityFilter(0, 1, /*include_partial_groups=*/true),
581  vCoins, setCoinsRet, nValueRet, coin_selection_params,
582  bnb_used)) ||
583  (wallet.m_spend_zero_conf_change &&
585  wallet, value_to_select,
586  CoinEligibilityFilter(0, 1, /*include_partial_groups=*/true),
587  vCoins, setCoinsRet, nValueRet, coin_selection_params,
588  bnb_used)) ||
589  // Try with unsafe inputs if they are allowed. This may spend
590  // unconfirmed outputs received from other wallets.
591  (coin_control.m_include_unsafe_inputs &&
593  wallet, value_to_select,
594  CoinEligibilityFilter(/*conf_mine=*/0, /*conf_theirs=*/0,
595  /*include_partial_groups=*/true),
596  vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
597 
598  // Because SelectCoinsMinConf clears the setCoinsRet, we now add the
599  // possible inputs to the coinset.
600  util::insert(setCoinsRet, setPresetCoins);
601 
602  // Add preset inputs to the total value selected.
603  nValueRet += nValueFromPresetInputs;
604 
605  return res;
606 }
607 
609  CWallet &wallet, const std::vector<CRecipient> &vecSend,
610  CTransactionRef &tx, Amount &nFeeRet, int &nChangePosInOut,
611  bilingual_str &error, const CCoinControl &coin_control, bool sign) {
612  // TODO: remember to add the lock annotation when adding AssertLockHeld.
613  // The lock annotation was added by core in PR22100, but due to
614  // other missing backports it was not possible to add it during that
615  // backport.
616  Amount nValue = Amount::zero();
617  const OutputType change_type = wallet.TransactionChangeType(
618  coin_control.m_change_type ? *coin_control.m_change_type
619  : wallet.m_default_change_type,
620  vecSend);
621  ReserveDestination reservedest(&wallet, change_type);
622  int nChangePosRequest = nChangePosInOut;
623  unsigned int nSubtractFeeFromAmount = 0;
624  for (const auto &recipient : vecSend) {
625  if (nValue < Amount::zero() || recipient.nAmount < Amount::zero()) {
626  error = _("Transaction amounts must not be negative");
627  return false;
628  }
629 
630  nValue += recipient.nAmount;
631 
632  if (recipient.fSubtractFeeFromAmount) {
633  nSubtractFeeFromAmount++;
634  }
635  }
636 
637  if (vecSend.empty()) {
638  error = _("Transaction must have at least one recipient");
639  return false;
640  }
641 
642  CMutableTransaction txNew;
643 
644  {
645  std::set<CInputCoin> setCoins;
646  LOCK(wallet.cs_wallet);
647  // Previously the locktime was set to the current block height, to
648  // prevent fee-sniping. This is now disabled as fee-sniping is mitigated
649  // by avalanche post-consensus. Consistently Using a locktime of 0 for
650  // most wallets in the ecosystem improves privacy, as this is the
651  // easiest solution to implement for light wallets which are not aware
652  // of the current block height.
653  txNew.nLockTime = 0;
654  std::vector<COutput> vAvailableCoins;
655  AvailableCoins(wallet, vAvailableCoins, &coin_control);
656  // Parameters for coin selection, init with dummy
659  coin_control.m_avoid_partial_spends;
660 
661  // Create change script that will be used if we need change
662  // TODO: pass in scriptChange instead of reservedest so
663  // change transaction isn't always pay-to-bitcoin-address
664  CScript scriptChange;
665 
666  // coin control: send change to custom address
667  if (!std::get_if<CNoDestination>(&coin_control.destChange)) {
668  scriptChange = GetScriptForDestination(coin_control.destChange);
669 
670  // no coin control: send change to newly generated address
671  } else {
672  // Note: We use a new key here to keep it from being obvious
673  // which side is the change.
674  // The drawback is that by not reusing a previous key, the
675  // change may be lost if a backup is restored, if the backup
676  // doesn't have the new private key for the change. If we
677  // reused the old key, it would be possible to add code to look
678  // for and rediscover unknown transactions that were written
679  // with keys of ours to recover post-backup change.
680 
681  // Reserve a new key pair from key pool. If it fails, provide a
682  // dummy destination in case we don't need change.
683  CTxDestination dest;
684  if (!reservedest.GetReservedDestination(dest, true)) {
685  error = _("Transaction needs a change address, but we can't "
686  "generate it. Please call keypoolrefill first.");
687  }
688 
689  scriptChange = GetScriptForDestination(dest);
690  // A valid destination implies a change script (and
691  // vice-versa). An empty change script will abort later, if the
692  // change keypool ran out, but change is required.
693  CHECK_NONFATAL(IsValidDestination(dest) != scriptChange.empty());
694  }
695  CTxOut change_prototype_txout(Amount::zero(), scriptChange);
697  GetSerializeSize(change_prototype_txout);
698 
699  // Get the fee rate to use effective values in coin selection
700  CFeeRate nFeeRateNeeded = GetMinimumFeeRate(wallet, coin_control);
701  // Do not, ever, assume that it's fine to change the fee rate if the
702  // user has explicitly provided one
703  if (coin_control.m_feerate &&
704  nFeeRateNeeded > *coin_control.m_feerate) {
705  error = strprintf(_("Fee rate (%s) is lower than the minimum fee "
706  "rate setting (%s)"),
707  coin_control.m_feerate->ToString(),
708  nFeeRateNeeded.ToString());
709  return false;
710  }
711 
712  nFeeRet = Amount::zero();
713  bool pick_new_inputs = true;
714  Amount nValueIn = Amount::zero();
715 
716  // BnB selector is the only selector used when this is true.
717  // That should only happen on the first pass through the loop.
719  // If we are doing subtract fee from recipient, don't use effective
720  // values
722  nSubtractFeeFromAmount != 0;
723  // Start with no fee and loop until there is enough fee
724  while (true) {
725  nChangePosInOut = nChangePosRequest;
726  txNew.vin.clear();
727  txNew.vout.clear();
728  bool fFirst = true;
729 
730  Amount nValueToSelect = nValue;
731  if (nSubtractFeeFromAmount == 0) {
732  nValueToSelect += nFeeRet;
733  }
734 
735  // vouts to the payees
737  // Static size overhead + outputs vsize. 4 nVersion, 4
738  // nLocktime, 1 input count, 1 output count
740  }
741  // vouts to the payees
742  for (const auto &recipient : vecSend) {
743  CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
744 
745  if (recipient.fSubtractFeeFromAmount) {
746  assert(nSubtractFeeFromAmount != 0);
747  // Subtract fee equally from each selected recipient.
748  txout.nValue -= nFeeRet / int(nSubtractFeeFromAmount);
749 
750  // First receiver pays the remainder not divisible by output
751  // count.
752  if (fFirst) {
753  fFirst = false;
754  txout.nValue -= nFeeRet % int(nSubtractFeeFromAmount);
755  }
756  }
757 
758  // Include the fee cost for outputs. Note this is only used for
759  // BnB right now
763  }
764 
765  if (IsDust(txout, wallet.chain().relayDustFee())) {
766  if (recipient.fSubtractFeeFromAmount &&
767  nFeeRet > Amount::zero()) {
768  if (txout.nValue < Amount::zero()) {
769  error = _("The transaction amount is too small to "
770  "pay the fee");
771  } else {
772  error = _("The transaction amount is too small to "
773  "send after the fee has been deducted");
774  }
775  } else {
776  error = _("Transaction amount too small");
777  }
778 
779  return false;
780  }
781 
782  txNew.vout.push_back(txout);
783  }
784 
785  // Choose coins to use
786  bool bnb_used = false;
787  if (pick_new_inputs) {
788  nValueIn = Amount::zero();
789  setCoins.clear();
790  int change_spend_size = CalculateMaximumSignedInputSize(
791  change_prototype_txout, &wallet);
792  // If the wallet doesn't know how to sign change output, assume
793  // p2pkh as lower-bound to allow BnB to do it's thing
794  if (change_spend_size == -1) {
797  } else {
799  size_t(change_spend_size);
800  }
801  coin_selection_params.effective_fee = nFeeRateNeeded;
802  if (!SelectCoins(wallet, vAvailableCoins, nValueToSelect,
803  setCoins, nValueIn, coin_control,
804  coin_selection_params, bnb_used)) {
805  // If BnB was used, it was the first pass. No longer the
806  // first pass and continue loop with knapsack.
807  if (bnb_used) {
809  continue;
810  } else {
811  error = _("Insufficient funds");
812  return false;
813  }
814  }
815  } else {
816  bnb_used = false;
817  }
818 
819  const Amount nChange = nValueIn - nValueToSelect;
820  if (nChange > Amount::zero()) {
821  // Fill a vout to ourself.
822  CTxOut newTxOut(nChange, scriptChange);
823 
824  // Never create dust outputs; if we would, just add the dust to
825  // the fee.
826  // The nChange when BnB is used is always going to go to fees.
827  if (IsDust(newTxOut, wallet.chain().relayDustFee()) ||
828  bnb_used) {
829  nChangePosInOut = -1;
830  nFeeRet += nChange;
831  } else {
832  if (nChangePosInOut == -1) {
833  // Insert change txn at random position:
834  nChangePosInOut = GetRand<int>(txNew.vout.size() + 1);
835  } else if ((unsigned int)nChangePosInOut >
836  txNew.vout.size()) {
837  error = _("Change index out of range");
838  return false;
839  }
840 
841  std::vector<CTxOut>::iterator position =
842  txNew.vout.begin() + nChangePosInOut;
843  txNew.vout.insert(position, newTxOut);
844  }
845  } else {
846  nChangePosInOut = -1;
847  }
848 
849  // Dummy fill vin for maximum size estimation
850  //
851  for (const auto &coin : setCoins) {
852  txNew.vin.push_back(CTxIn(coin.outpoint, CScript()));
853  }
854 
855  CTransaction txNewConst(txNew);
856  int nBytes = CalculateMaximumSignedTxSize(
857  txNewConst, &wallet, coin_control.fAllowWatchOnly);
858  if (nBytes < 0) {
859  error = _("Signing transaction failed");
860  return false;
861  }
862 
863  Amount nFeeNeeded = GetMinimumFee(wallet, nBytes, coin_control);
864 
865  if (nFeeRet >= nFeeNeeded) {
866  // Reduce fee to only the needed amount if possible. This
867  // prevents potential overpayment in fees if the coins selected
868  // to meet nFeeNeeded result in a transaction that requires less
869  // fee than the prior iteration.
870 
871  // If we have no change and a big enough excess fee, then try to
872  // construct transaction again only without picking new inputs.
873  // We now know we only need the smaller fee (because of reduced
874  // tx size) and so we should add a change output. Only try this
875  // once.
876  if (nChangePosInOut == -1 && nSubtractFeeFromAmount == 0 &&
877  pick_new_inputs) {
878  // Add 2 as a buffer in case increasing # of outputs changes
879  // compact size
880  unsigned int tx_size_with_change =
882  Amount fee_needed_with_change = GetMinimumFee(
883  wallet, tx_size_with_change, coin_control);
884  Amount minimum_value_for_change = GetDustThreshold(
885  change_prototype_txout, wallet.chain().relayDustFee());
886  if (nFeeRet >=
887  fee_needed_with_change + minimum_value_for_change) {
888  pick_new_inputs = false;
889  nFeeRet = fee_needed_with_change;
890  continue;
891  }
892  }
893 
894  // If we have change output already, just increase it
895  if (nFeeRet > nFeeNeeded && nChangePosInOut != -1 &&
896  nSubtractFeeFromAmount == 0) {
897  Amount extraFeePaid = nFeeRet - nFeeNeeded;
898  std::vector<CTxOut>::iterator change_position =
899  txNew.vout.begin() + nChangePosInOut;
900  change_position->nValue += extraFeePaid;
901  nFeeRet -= extraFeePaid;
902  }
903 
904  // Done, enough fee included.
905  break;
906  } else if (!pick_new_inputs) {
907  // This shouldn't happen, we should have had enough excess fee
908  // to pay for the new output and still meet nFeeNeeded.
909  // Or we should have just subtracted fee from recipients and
910  // nFeeNeeded should not have changed.
911  error = _("Transaction fee and change calculation failed");
912  return false;
913  }
914 
915  // Try to reduce change to include necessary fee.
916  if (nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
917  Amount additionalFeeNeeded = nFeeNeeded - nFeeRet;
918  std::vector<CTxOut>::iterator change_position =
919  txNew.vout.begin() + nChangePosInOut;
920  // Only reduce change if remaining amount is still a large
921  // enough output.
922  if (change_position->nValue >=
923  MIN_FINAL_CHANGE + additionalFeeNeeded) {
924  change_position->nValue -= additionalFeeNeeded;
925  nFeeRet += additionalFeeNeeded;
926  // Done, able to increase fee from change.
927  break;
928  }
929  }
930 
931  // If subtracting fee from recipients, we now know what fee we
932  // need to subtract, we have no reason to reselect inputs.
933  if (nSubtractFeeFromAmount > 0) {
934  pick_new_inputs = false;
935  }
936 
937  // Include more fee and try again.
938  nFeeRet = nFeeNeeded;
940  continue;
941  }
942 
943  // Give up if change keypool ran out and change is required
944  if (scriptChange.empty() && nChangePosInOut != -1) {
945  return false;
946  }
947 
948  // Shuffle selected coins and fill in final vin
949  txNew.vin.clear();
950  std::vector<CInputCoin> selected_coins(setCoins.begin(),
951  setCoins.end());
952  Shuffle(selected_coins.begin(), selected_coins.end(),
954 
955  // Note how the sequence number is set to non-maxint so that
956  // the nLockTime set above actually works.
957  for (const auto &coin : selected_coins) {
958  txNew.vin.push_back(
959  CTxIn(coin.outpoint, CScript(),
960  std::numeric_limits<uint32_t>::max() - 1));
961  }
962 
963  if (sign && !wallet.SignTransaction(txNew)) {
964  error = _("Signing transaction failed");
965  return false;
966  }
967 
968  // Return the constructed transaction data.
969  tx = MakeTransactionRef(std::move(txNew));
970 
971  // Limit size.
972  if (tx->GetTotalSize() > MAX_STANDARD_TX_SIZE) {
973  error = _("Transaction too large");
974  return false;
975  }
976  }
977 
978  if (nFeeRet > wallet.m_default_max_tx_fee) {
980  return false;
981  }
982 
983  // Before we return success, we assume any change key will be used to
984  // prevent accidental re-use.
985  reservedest.KeepDestination();
986 
987  return true;
988 }
989 
990 bool CreateTransaction(CWallet &wallet, const std::vector<CRecipient> &vecSend,
991  CTransactionRef &tx, Amount &nFeeRet,
992  int &nChangePosInOut, bilingual_str &error,
993  const CCoinControl &coin_control, bool sign) {
994  int nChangePosIn = nChangePosInOut;
995  CTransactionRef tx2 = tx;
996  bool res =
997  CreateTransactionInternal(wallet, vecSend, tx, nFeeRet, nChangePosInOut,
998  error, coin_control, sign);
999  // try with avoidpartialspends unless it's enabled already
1000  if (res &&
1001  nFeeRet >
1002  Amount::zero() /* 0 means non-functional fee rate estimation */
1003  && wallet.m_max_aps_fee > (-1 * SATOSHI) &&
1004  !coin_control.m_avoid_partial_spends) {
1005  CCoinControl tmp_cc = coin_control;
1006  tmp_cc.m_avoid_partial_spends = true;
1007  Amount nFeeRet2;
1008  int nChangePosInOut2 = nChangePosIn;
1009  // fired and forgotten; if an error occurs, we discard the results
1010  bilingual_str error2;
1011  if (CreateTransactionInternal(wallet, vecSend, tx2, nFeeRet2,
1012  nChangePosInOut2, error2, tmp_cc, sign)) {
1013  // if fee of this alternative one is within the range of the max
1014  // fee, we use this one
1015  const bool use_aps = nFeeRet2 <= nFeeRet + wallet.m_max_aps_fee;
1016  wallet.WalletLogPrintf(
1017  "Fee non-grouped = %lld, grouped = %lld, using %s\n", nFeeRet,
1018  nFeeRet2, use_aps ? "grouped" : "non-grouped");
1019  if (use_aps) {
1020  tx = tx2;
1021  nFeeRet = nFeeRet2;
1022  nChangePosInOut = nChangePosInOut2;
1023  }
1024  }
1025  }
1026  return res;
1027 }
1028 
1030  int &nChangePosInOut, bilingual_str &error,
1031  bool lockUnspents,
1032  const std::set<int> &setSubtractFeeFromOutputs,
1033  CCoinControl coinControl) {
1034  std::vector<CRecipient> vecSend;
1035 
1036  // Turn the txout set into a CRecipient vector.
1037  for (size_t idx = 0; idx < tx.vout.size(); idx++) {
1038  const CTxOut &txOut = tx.vout[idx];
1039  CRecipient recipient = {txOut.scriptPubKey, txOut.nValue,
1040  setSubtractFeeFromOutputs.count(idx) == 1};
1041  vecSend.push_back(recipient);
1042  }
1043 
1044  coinControl.fAllowOtherInputs = true;
1045 
1046  for (const CTxIn &txin : tx.vin) {
1047  coinControl.Select(txin.prevout);
1048  }
1049 
1050  // Acquire the locks to prevent races to the new locked unspents between the
1051  // CreateTransaction call and LockCoin calls (when lockUnspents is true).
1052  LOCK(wallet.cs_wallet);
1053 
1054  CTransactionRef tx_new;
1055  if (!CreateTransaction(wallet, vecSend, tx_new, nFeeRet, nChangePosInOut,
1056  error, coinControl, false)) {
1057  return false;
1058  }
1059 
1060  if (nChangePosInOut != -1) {
1061  tx.vout.insert(tx.vout.begin() + nChangePosInOut,
1062  tx_new->vout[nChangePosInOut]);
1063  }
1064 
1065  // Copy output sizes from new transaction; they may have had the fee
1066  // subtracted from them.
1067  for (size_t idx = 0; idx < tx.vout.size(); idx++) {
1068  tx.vout[idx].nValue = tx_new->vout[idx].nValue;
1069  }
1070 
1071  // Add new txins (keeping original txin scriptSig/order)
1072  for (const CTxIn &txin : tx_new->vin) {
1073  if (!coinControl.IsSelected(txin.prevout)) {
1074  tx.vin.push_back(txin);
1075  }
1076  if (lockUnspents) {
1077  wallet.LockCoin(txin.prevout);
1078  }
1079  }
1080 
1081  return true;
1082 }
static constexpr Amount SATOSHI
Definition: amount.h:143
static constexpr Amount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition: amount.h:165
#define CHECK_NONFATAL(condition)
Identity function.
Definition: check.h:53
Coin Control Features.
Definition: coincontrol.h:21
std::optional< OutputType > m_change_type
Override the default change type if set, ignored if destChange is set.
Definition: coincontrol.h:25
bool HasSelected() const
Definition: coincontrol.h:54
std::optional< unsigned int > m_confirm_target
Override the default confirmation target if set.
Definition: coincontrol.h:40
bool IsSelected(const COutPoint &output) const
Definition: coincontrol.h:56
int m_max_depth
Maximum chain depth value for coin availability.
Definition: coincontrol.h:48
void Select(const COutPoint &output)
Definition: coincontrol.h:60
bool fAllowWatchOnly
Includes watch only addresses which are solvable.
Definition: coincontrol.h:34
int m_min_depth
Minimum chain depth value for coin availability.
Definition: coincontrol.h:46
std::optional< CFeeRate > m_feerate
Override the wallet's m_pay_tx_fee if set.
Definition: coincontrol.h:38
bool m_add_inputs
If false, only selected inputs are used.
Definition: coincontrol.h:27
CTxDestination destChange
Definition: coincontrol.h:23
bool m_avoid_address_reuse
Forbids inclusion of dirty (previously used) addresses.
Definition: coincontrol.h:44
bool m_include_unsafe_inputs
If false, only safe inputs will be used (confirmed or self transfers)
Definition: coincontrol.h:29
bool m_avoid_partial_spends
Avoid partial use of funds sent to a given address.
Definition: coincontrol.h:42
bool fAllowOtherInputs
If false, allows unselected inputs, but requires all selected inputs be used.
Definition: coincontrol.h:32
void ListSelected(std::vector< COutPoint > &vOutpoints) const
Definition: coincontrol.h:66
Fee rate in satoshis per kilobyte: Amount / kB.
Definition: feerate.h:21
std::string ToString() const
Definition: feerate.cpp:57
Amount GetFee(size_t nBytes) const
Return the fee in satoshis for the given size in bytes.
Definition: feerate.cpp:49
int m_input_bytes
Pre-computed estimated size of this output as a fully-signed input in a transaction.
Definition: coinselection.h:47
CTxOut txout
Definition: coinselection.h:38
Amount effective_value
Definition: coinselection.h:39
A mutable version of CTransaction.
Definition: transaction.h:274
std::vector< CTxOut > vout
Definition: transaction.h:277
std::vector< CTxIn > vin
Definition: transaction.h:276
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:20
uint32_t GetN() const
Definition: transaction.h:36
const TxId & GetTxId() const
Definition: transaction.h:35
Definition: spend.h:19
int nDepth
Definition: spend.h:23
const CWalletTx * tx
Definition: spend.h:21
std::string ToString() const
Definition: spend.cpp:28
int i
Definition: spend.h:22
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:431
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:192
const std::vector< CTxOut > vout
Definition: transaction.h:207
const std::vector< CTxIn > vin
Definition: transaction.h:206
An input of a transaction.
Definition: transaction.h:59
COutPoint prevout
Definition: transaction.h:61
An output of a transaction.
Definition: transaction.h:128
CScript scriptPubKey
Definition: transaction.h:131
Amount nValue
Definition: transaction.h:130
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:253
A transaction with a bunch of additional info that only the owner cares about.
Definition: transaction.h:65
mapValue_t mapValue
Key/value map with information about the transaction.
Definition: transaction.h:99
CTransactionRef tx
Definition: transaction.h:160
TxId GetId() const
Definition: transaction.h:300
bool InMempool() const
Definition: transaction.cpp:21
Fast randomness source.
Definition: random.h:156
A wrapper to reserve an address from a wallet.
Definition: wallet.h:160
std::string ToString() const
Definition: uint256.h:80
Helper for findBlock to selectively return pieces of block data.
Definition: chain.h:48
bool empty() const
Definition: prevector.h:388
void emplace_back(Args &&...args)
Definition: prevector.h:522
const int DEFAULT_MAX_DEPTH
Definition: coincontrol.h:15
const int DEFAULT_MIN_DEPTH
Definition: coincontrol.h:14
bool KnapsackSolver(const Amount nTargetValue, std::vector< OutputGroup > &groups, std::set< CInputCoin > &setCoinsRet, Amount &nValueRet)
bool SelectCoinsBnB(std::vector< OutputGroup > &utxo_pool, const Amount &target_value, const Amount &cost_of_change, std::set< CInputCoin > &out_set, Amount &value_ret, const Amount not_input_fees)
This is the Branch and Bound Coin Selection algorithm designed by Murch.
static const Amount MIN_FINAL_CHANGE
final minimum change amount after paying for fees
Definition: coinselection.h:15
static std::vector< COutput > vCoins
CoinSelectionParams coin_selection_params(false, 0, 0, CFeeRate(Amount::zero()), 0, false)
static Amount balance
bilingual_str TransactionErrorString(const TransactionError error)
Definition: error.cpp:11
void KeepDestination()
Keep the address.
Definition: wallet.cpp:2436
bool GetReservedDestination(CTxDestination &pubkey, bool internal)
Reserve an address.
Definition: wallet.cpp:2415
isminetype
IsMine() return codes.
Definition: ismine.h:18
@ ISMINE_ALL
Definition: ismine.h:23
@ ISMINE_SPENDABLE
Definition: ismine.h:21
@ ISMINE_NO
Definition: ismine.h:19
@ ISMINE_WATCH_ONLY
Definition: ismine.h:20
std::string FormatMoney(const Amount amt)
Do not use these functions to represent or parse monetary amounts to or from JSON but use AmountFromV...
Definition: moneystr.cpp:13
void insert(Tdst &dst, const Tsrc &src)
Simplification of std insertion.
Definition: system.h:526
OutputType
Definition: outputtype.h:16
Amount GetDustThreshold(const CTxOut &txout, const CFeeRate &dustRelayFeeIn)
Definition: policy.cpp:14
bool IsDust(const CTxOut &txout, const CFeeRate &dustRelayFeeIn)
Definition: policy.cpp:34
static constexpr unsigned int MAX_STANDARD_TX_SIZE
The maximum size for transactions we're willing to relay/mine.
Definition: policy.h:34
static CTransactionRef MakeTransactionRef()
Definition: transaction.h:316
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:315
void Shuffle(I first, I last, R &&rng)
More efficient than using std::shuffle on a FastRandomContext.
Definition: random.h:291
bool CachedTxIsFromMe(const CWallet &wallet, const CWalletTx &wtx, const isminefilter &filter)
Definition: receive.cpp:321
bool OutputIsChange(const CWallet &wallet, const CTxOut &txout)
Definition: receive.cpp:98
bool CachedTxIsTrusted(const CWallet &wallet, const CWalletTx &wtx, std::set< TxId > &trusted_parents)
Definition: receive.cpp:326
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1258
bool IsSolvable(const SigningProvider &provider, const CScript &script)
Check whether we know how to sign for an output like this, assuming we have all private keys.
Definition: sign.cpp:424
int CalculateMaximumSignedInputSize(const CTxOut &txout, const CWallet *wallet, bool use_max_sig)
Get the marginal bytes of spending the specified output.
Definition: spend.cpp:33
bool SelectCoinsMinConf(const CWallet &wallet, const Amount nTargetValue, const CoinEligibilityFilter &eligibility_filter, std::vector< COutput > coins, std::set< CInputCoin > &setCoinsRet, Amount &nValueRet, const CoinSelectionParams &coin_selection_params, bool &bnb_used)
Shuffle and select coins until nTargetValue is reached while avoiding small change; This method is st...
Definition: spend.cpp:419
bool FundTransaction(CWallet &wallet, CMutableTransaction &tx, Amount &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:1029
int64_t 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:44
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:249
std::vector< OutputGroup > GroupOutputs(const CWallet &wallet, const std::vector< COutput > &outputs, bool separate_coins, const CFeeRate &effective_feerate, const CFeeRate &long_term_feerate, const CoinEligibilityFilter &filter, bool positive_only)
Definition: spend.cpp:304
bool CreateTransaction(CWallet &wallet, const std::vector< CRecipient > &vecSend, CTransactionRef &tx, Amount &nFeeRet, int &nChangePosInOut, bilingual_str &error, const CCoinControl &coin_control, bool sign)
Create a new transaction paying the recipients with a set of coins selected by SelectCoins(); Also cr...
Definition: spend.cpp:990
static bool CreateTransactionInternal(CWallet &wallet, const std::vector< CRecipient > &vecSend, CTransactionRef &tx, Amount &nFeeRet, int &nChangePosInOut, bilingual_str &error, const CCoinControl &coin_control, bool sign)
Definition: spend.cpp:608
static const size_t OUTPUT_GROUP_MAX_ENTRIES
Definition: spend.cpp:21
void AvailableCoins(const CWallet &wallet, std::vector< COutput > &vCoins, const CCoinControl *coinControl, const Amount nMinimumAmount, const Amount nMaximumAmount, const Amount nMinimumSumAmount, const uint64_t nMaximumCount)
populate vCoins with vector of available COutputs.
Definition: spend.cpp:70
const CTxOut & FindNonChangeParentOutput(const CWallet &wallet, const CTransaction &tx, int output)
Find non-change parent output.
Definition: spend.cpp:229
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:23
Amount GetAvailableBalance(const CWallet &wallet, const CCoinControl *coinControl)
Definition: spend.cpp:214
bool SelectCoins(const CWallet &wallet, const std::vector< COutput > &vAvailableCoins, const Amount nTargetValue, std::set< CInputCoin > &setCoinsRet, Amount &nValueRet, const CCoinControl &coin_control, CoinSelectionParams &coin_selection_params, bool &bnb_used)
Select a set of coins such that nValueRet >= nTargetValue and at least all coins from coin_control ar...
Definition: spend.cpp:471
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
Definition: standard.cpp:158
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition: standard.cpp:260
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:240
std::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:85
Definition: amount.h:19
static constexpr Amount zero() noexcept
Definition: amount.h:32
const bool m_include_partial_groups
Include partial destination groups when avoid_reuse and there are full groups.
Definition: coinselection.h:71
bool m_subtract_fee_outputs
Indicate that we are subtracting the fee from outputs.
Definition: wallet.h:232
size_t change_spend_size
Definition: wallet.h:228
size_t tx_noinputs_size
Definition: wallet.h:230
bool m_avoid_partial_spends
Definition: wallet.h:233
CFeeRate effective_fee
Definition: wallet.h:229
size_t change_output_size
Definition: wallet.h:227
std::vector< CInputCoin > m_outputs
Definition: coinselection.h:82
void Insert(const CInputCoin &output, int depth, bool from_me, bool positive_only)
Amount effective_value
Definition: coinselection.h:86
bool EligibleForSpending(const CoinEligibilityFilter &eligibility_filter) const
A TxId is the identifier of a transaction.
Definition: txid.h:14
Bilingual messages:
Definition: translation.h:17
#define LOCK(cs)
Definition: sync.h:306
bool error(const char *fmt, const Args &...args)
Definition: system.h:45
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1202
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:68
AssertLockHeld(pool.cs)
assert(!tx.IsCoinBase())
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:11
Amount GetMinimumFee(const CWallet &wallet, unsigned int nTxBytes, const CCoinControl &coin_control)
Estimate the minimum fee considering user set parameters and the required fee.
Definition: fees.cpp:17
CFeeRate GetMinimumFeeRate(const CWallet &wallet, const CCoinControl &coin_control)
Estimate the minimum fee rate considering user set parameters and the required fee.
Definition: fees.cpp:26
static constexpr size_t DUMMY_P2PKH_INPUT_SIZE
Pre-calculated constants for input size estimation.
Definition: wallet.h:114
@ WALLET_FLAG_DISABLE_PRIVATE_KEYS
Definition: walletutil.h:55
@ WALLET_FLAG_AVOID_REUSE
Definition: walletutil.h:47