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