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