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