Bitcoin Core 32.99.0
P2P Digital Currency
spend.cpp
Go to the documentation of this file.
1// Copyright (c) 2021-present 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 <algorithm>
6#include <common/args.h>
7#include <common/messages.h>
8#include <common/system.h>
9#include <consensus/amount.h>
11#include <interfaces/chain.h>
12#include <node/types.h>
13#include <numeric>
14#include <policy/policy.h>
15#include <policy/truc_policy.h>
18#include <script/script.h>
20#include <script/solver.h>
21#include <util/check.h>
22#include <util/moneystr.h>
23#include <util/rbf.h>
24#include <util/trace.h>
25#include <util/translation.h>
26#include <wallet/coincontrol.h>
27#include <wallet/fees.h>
28#include <wallet/receive.h>
29#include <wallet/spend.h>
30#include <wallet/transaction.h>
31#include <wallet/wallet.h>
32
33#include <cmath>
34
39
40TRACEPOINT_SEMAPHORE(coin_selection, selected_coins);
41TRACEPOINT_SEMAPHORE(coin_selection, normal_create_tx_internal);
42TRACEPOINT_SEMAPHORE(coin_selection, attempting_aps_create_tx);
43TRACEPOINT_SEMAPHORE(coin_selection, aps_create_tx_internal);
44
45namespace wallet {
46static constexpr size_t OUTPUT_GROUP_MAX_ENTRIES{100};
47
49static bool IsSegwit(const Descriptor& desc) {
50 if (const auto typ = desc.GetOutputType()) return *typ != OutputType::LEGACY;
51 return false;
52}
53
55static bool UseMaxSig(const std::optional<CTxIn>& txin, const CCoinControl* coin_control) {
56 // Use max sig if watch only inputs were used or if this particular input is an external input
57 // to ensure a sufficient fee is attained for the requested feerate.
58 return coin_control && txin && coin_control->IsExternalSelected(txin->prevout);
59}
60
69static std::optional<int64_t> MaxInputWeight(const Descriptor& desc, const std::optional<CTxIn>& txin,
70 const CCoinControl* coin_control, const bool tx_is_segwit,
71 const bool can_grind_r) {
72 if (const auto sat_weight = desc.MaxSatisfactionWeight(!can_grind_r || UseMaxSig(txin, coin_control))) {
73 if (const auto elems_count = desc.MaxSatisfactionElems()) {
74 const bool is_segwit = IsSegwit(desc);
75 // Account for the size of the scriptsig and the number of elements on the witness stack. Note
76 // that if any input in the transaction is spending a witness program, we need to specify the
77 // witness stack size for every input regardless of whether it is segwit itself.
78 // NOTE: this also works in case of mixed scriptsig-and-witness such as in p2sh-wrapped segwit v0
79 // outputs. In this case the size of the scriptsig length will always be one (since the redeemScript
80 // is always a push of the witness program in this case, which is smaller than 253 bytes).
81 const int64_t scriptsig_len = is_segwit ? 1 : GetSizeOfCompactSize(*sat_weight / WITNESS_SCALE_FACTOR);
82 const int64_t witstack_len = is_segwit ? GetSizeOfCompactSize(*elems_count) : (tx_is_segwit ? 1 : 0);
83 // previous txid + previous vout + sequence + scriptsig len + witstack size + scriptsig or witness
84 // NOTE: sat_weight already accounts for the witness discount accordingly.
85 return (32 + 4 + 4 + scriptsig_len) * WITNESS_SCALE_FACTOR + witstack_len + *sat_weight;
86 }
87 }
88
89 return {};
90}
91
92int CalculateMaximumSignedInputSize(const CTxOut& txout, const COutPoint outpoint, const SigningProvider* provider, bool can_grind_r, const CCoinControl* coin_control)
93{
94 if (!provider) return -1;
95
96 if (const auto desc = InferDescriptor(txout.scriptPubKey, *provider)) {
97 if (const auto weight = MaxInputWeight(*desc, CTxIn{outpoint}, coin_control, true, can_grind_r)) {
98 return static_cast<int>(GetVirtualTransactionSize(*weight, 0, 0));
99 }
100 }
101
102 return -1;
103}
104
105int CalculateMaximumSignedInputSize(const CTxOut& txout, const CWallet* wallet, const CCoinControl* coin_control)
106{
107 const std::unique_ptr<SigningProvider> provider = wallet->GetSolvingProvider(txout.scriptPubKey);
108 return CalculateMaximumSignedInputSize(txout, COutPoint(), provider.get(), wallet->CanGrindR(), coin_control);
109}
110
112static std::unique_ptr<Descriptor> GetDescriptor(const CWallet* wallet, const CCoinControl* coin_control,
113 const CScript script_pubkey)
114{
115 MultiSigningProvider providers;
116 for (const auto spkman: wallet->GetScriptPubKeyMans(script_pubkey)) {
117 providers.AddProvider(spkman->GetSolvingProvider(script_pubkey));
118 }
119 if (coin_control) {
120 providers.AddProvider(std::make_unique<FlatSigningProvider>(coin_control->m_external_provider));
121 }
122 return InferDescriptor(script_pubkey, providers);
123}
124
126static std::optional<int64_t> GetSignedTxinWeight(const CWallet* wallet, const CCoinControl* coin_control,
127 const CTxIn& txin, const CTxOut& txo, const bool tx_is_segwit,
128 const bool can_grind_r)
129{
130 // If weight was provided, use that.
131 std::optional<int64_t> weight;
132 if (coin_control && (weight = coin_control->GetInputWeight(txin.prevout))) {
133 return weight.value();
134 }
135
136 // Otherwise, use the maximum satisfaction size provided by the descriptor.
137 std::unique_ptr<Descriptor> desc{GetDescriptor(wallet, coin_control, txo.scriptPubKey)};
138 if (desc) return MaxInputWeight(*desc, {txin}, coin_control, tx_is_segwit, can_grind_r);
139
140 return {};
141}
142
143// txouts needs to be in the order of tx.vin
144TxSize CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, const std::vector<CTxOut>& txouts, const CCoinControl* coin_control)
145{
146 // version + nLockTime + input count + output count
147 int64_t weight = (4 + 4 + GetSizeOfCompactSize(tx.vin.size()) + GetSizeOfCompactSize(tx.vout.size())) * WITNESS_SCALE_FACTOR;
148 // Whether any input spends a witness program. Necessary to run before the next loop over the
149 // inputs in order to accurately compute the compactSize length for the witness data per input.
150 bool is_segwit = std::any_of(txouts.begin(), txouts.end(), [&](const CTxOut& txo) {
151 std::unique_ptr<Descriptor> desc{GetDescriptor(wallet, coin_control, txo.scriptPubKey)};
152 if (desc) return IsSegwit(*desc);
153 return false;
154 });
155 // Segwit marker and flag
156 if (is_segwit) weight += 2;
157
158 // Add the size of the transaction outputs.
159 for (const auto& txo : tx.vout) weight += GetSerializeSize(txo) * WITNESS_SCALE_FACTOR;
160
161 // Add the size of the transaction inputs as if they were signed.
162 for (uint32_t i = 0; i < txouts.size(); i++) {
163 const auto txin_weight = GetSignedTxinWeight(wallet, coin_control, tx.vin[i], txouts[i], is_segwit, wallet->CanGrindR());
164 if (!txin_weight) return TxSize{-1, -1};
165 assert(*txin_weight > -1);
166 weight += *txin_weight;
167 }
168
169 // It's ok to use 0 as the number of sigops since we never create any pathological transaction.
170 return TxSize{GetVirtualTransactionSize(weight, 0, 0), weight};
171}
172
174{
175 std::vector<CTxOut> txouts;
176 // Look up the inputs. The inputs are either in the wallet, or in coin_control.
177 for (const CTxIn& input : tx.vin) {
178 const auto mi = wallet->mapWallet.find(input.prevout.hash);
179 // Can not estimate size without knowing the input details
180 if (mi != wallet->mapWallet.end()) {
181 assert(input.prevout.n < mi->second.GetTx()->vout.size());
182 txouts.emplace_back(mi->second.GetTx()->vout.at(input.prevout.n));
183 } else if (coin_control) {
184 const auto& txout{coin_control->GetExternalOutput(input.prevout)};
185 if (!txout) return TxSize{-1, -1};
186 txouts.emplace_back(*txout);
187 } else {
188 return TxSize{-1, -1};
189 }
190 }
191 return CalculateMaximumSignedTxSize(tx, wallet, txouts, coin_control);
192}
193
194size_t CoinsResult::Size() const
195{
196 size_t size{0};
197 for (const auto& it : coins) {
198 size += it.second.size();
199 }
200 return size;
201}
202
203std::vector<COutput> CoinsResult::All() const
204{
205 std::vector<COutput> all;
206 all.reserve(Size());
207 for (const auto& it : coins) {
208 all.insert(all.end(), it.second.begin(), it.second.end());
209 }
210 return all;
211}
212
213void CoinsResult::Erase(const std::unordered_set<COutPoint, SaltedOutpointHasher>& coins_to_remove)
214{
215 for (auto& [type, vec] : coins) {
216 auto remove_it = std::remove_if(vec.begin(), vec.end(), [&](const COutput& coin) {
217 // remove it if it's on the set
218 if (!coins_to_remove.contains(coin.outpoint)) return false;
219
220 // update cached amounts
221 total_amount -= coin.txout.nValue;
222 if (coin.HasEffectiveValue() && total_effective_amount.has_value()) total_effective_amount = *total_effective_amount - coin.GetEffectiveValue();
223 return true;
224 });
225 vec.erase(remove_it, vec.end());
226 }
227}
228
229void CoinsResult::Shuffle(FastRandomContext& rng_fast)
230{
231 for (auto& it : coins) {
232 std::shuffle(it.second.begin(), it.second.end(), rng_fast);
233 }
234}
235
236void CoinsResult::Add(OutputType type, const COutput& out)
237{
238 coins[type].emplace_back(out);
239 total_amount += out.txout.nValue;
240 if (out.HasEffectiveValue()) {
241 total_effective_amount = total_effective_amount.has_value() ?
242 *total_effective_amount + out.GetEffectiveValue() : out.GetEffectiveValue();
243 }
244}
245
246static OutputType GetOutputType(TxoutType type, bool is_from_p2sh)
247{
248 switch (type) {
250 return OutputType::BECH32M;
253 if (is_from_p2sh) return OutputType::P2SH_SEGWIT;
254 else return OutputType::BECH32;
257 return OutputType::LEGACY;
258 default:
259 return OutputType::UNKNOWN;
260 }
261}
262
263// Fetch and validate the coin control selected inputs.
264// Coins could be internal (from the wallet) or external.
266 const CoinSelectionParams& coin_selection_params)
267{
268 CoinsResult result;
269 const bool can_grind_r = wallet.CanGrindR();
270 std::map<COutPoint, CAmount> map_of_bump_fees = wallet.chain().calculateIndividualBumpFees(coin_control.ListSelected(), coin_selection_params.m_effective_feerate);
271 for (const COutPoint& outpoint : coin_control.ListSelected()) {
272 int64_t input_bytes = coin_control.GetInputWeight(outpoint).value_or(-1);
273 if (input_bytes != -1) {
274 input_bytes = GetVirtualTransactionSize(input_bytes, 0, 0);
275 }
276 CTxOut txout;
277 if (auto txo = wallet.GetTXO(outpoint)) {
278 txout = txo->GetTxOut();
279 if (input_bytes == -1) {
280 input_bytes = CalculateMaximumSignedInputSize(txout, &wallet, &coin_control);
281 }
282 const CWalletTx& parent_tx = txo->GetWalletTx();
283 if (wallet.GetTxDepthInMainChain(parent_tx) == 0) {
284 if (parent_tx.GetTx()->version == TRUC_VERSION && coin_control.m_version != TRUC_VERSION) {
285 return util::Error{strprintf(_("Can't spend unconfirmed version 3 pre-selected input with a version %d tx"), coin_control.m_version)};
286 } else if (coin_control.m_version == TRUC_VERSION && parent_tx.GetTx()->version != TRUC_VERSION) {
287 return util::Error{strprintf(_("Can't spend unconfirmed version %d pre-selected input with a version 3 tx"), parent_tx.GetTx()->version)};
288 }
289 }
290 } else {
291 // The input is external. We did not find the tx in mapWallet.
292 const auto out{coin_control.GetExternalOutput(outpoint)};
293 if (!out) {
294 return util::Error{strprintf(_("Not found pre-selected input %s"), outpoint.ToString())};
295 }
296
297 txout = *out;
298 }
299
300 if (input_bytes == -1) {
301 input_bytes = CalculateMaximumSignedInputSize(txout, outpoint, &coin_control.m_external_provider, can_grind_r, &coin_control);
302 }
303
304 if (input_bytes == -1) {
305 return util::Error{strprintf(_("Not solvable pre-selected input %s"), outpoint.ToString())}; // Not solvable, can't estimate size for fee
306 }
307
308 /* Set some defaults for depth, solvable, safe, time, and from_me as these don't matter for preset inputs since no selection is being done. */
309 COutput output(outpoint, txout, /*depth=*/0, input_bytes, /*solvable=*/true, /*safe=*/true, /*time=*/0, /*from_me=*/false, coin_selection_params.m_effective_feerate);
310 output.ApplyBumpFee(map_of_bump_fees.at(output.outpoint));
311 result.Add(OutputType::UNKNOWN, output);
312 }
313 return result;
314}
315
317 const CCoinControl* coinControl,
318 std::optional<CFeeRate> feerate,
319 const CoinFilterParams& params)
320{
321 AssertLockHeld(wallet.cs_wallet);
322
323 CoinsResult result;
324 // track unconfirmed truc outputs separately if we are tracking trucness
325 std::vector<std::pair<OutputType, COutput>> unconfirmed_truc_coins;
326 std::unordered_map<Txid, CAmount, SaltedTxidHasher> truc_txid_by_value;
327 // 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
328 // a coin control object is provided, and has the avoid address reuse flag set to false, do we allow already used addresses
329 bool allow_used_addresses = !wallet.IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE) || (coinControl && !coinControl->m_avoid_address_reuse);
330 const int min_depth = {coinControl ? coinControl->m_min_depth : DEFAULT_MIN_DEPTH};
331 const int max_depth = {coinControl ? coinControl->m_max_depth : DEFAULT_MAX_DEPTH};
332 const bool only_safe = {coinControl ? !coinControl->m_include_unsafe_inputs : true};
333 const bool can_grind_r = wallet.CanGrindR();
334 std::vector<COutPoint> outpoints;
335
336 std::set<Txid> trusted_parents;
337 // Cache for whether each tx passes the tx level checks (first bool), and whether the transaction is "safe" (second bool)
338 std::unordered_map<Txid, std::pair<bool, bool>, SaltedTxidHasher> tx_safe_cache;
339 for (const auto& [outpoint, txo] : wallet.GetTXOs()) {
340 const CWalletTx& wtx = txo.GetWalletTx();
341 const CTxOut& output = txo.GetTxOut();
342
343 if (tx_safe_cache.contains(outpoint.hash) && !tx_safe_cache.at(outpoint.hash).first) {
344 continue;
345 }
346
347 int nDepth = wallet.GetTxDepthInMainChain(wtx);
348
349 // Perform tx level checks if we haven't already come across outputs from this tx before.
350 if (!tx_safe_cache.contains(outpoint.hash)) {
351 tx_safe_cache[outpoint.hash] = {false, false};
352
353 if (wallet.IsTxImmatureCoinBase(wtx) && !params.include_immature_coinbase)
354 continue;
355
356 if (nDepth < 0)
357 continue;
358
359 // We should not consider coins which aren't at least in our mempool
360 // It's possible for these to be conflicted via ancestors which we may never be able to detect
361 if (nDepth == 0 && !wtx.InMempool())
362 continue;
363
364 bool safeTx = CachedTxIsTrusted(wallet, wtx, trusted_parents);
365
366 // We should not consider coins from transactions that are replacing
367 // other transactions.
368 //
369 // Example: There is a transaction A which is replaced by bumpfee
370 // transaction B. In this case, we want to prevent creation of
371 // a transaction B' which spends an output of B.
372 //
373 // Reason: If transaction A were initially confirmed, transactions B
374 // and B' would no longer be valid, so the user would have to create
375 // a new transaction C to replace B'. However, in the case of a
376 // one-block reorg, transactions B' and C might BOTH be accepted,
377 // when the user only wanted one of them. Specifically, there could
378 // be a 1-block reorg away from the chain where transactions A and C
379 // were accepted to another chain where B, B', and C were all
380 // accepted.
381 if (nDepth == 0 && wtx.m_replaces_txid) {
382 safeTx = false;
383 }
384
385 // Similarly, we should not consider coins from transactions that
386 // have been replaced. In the example above, we would want to prevent
387 // creation of a transaction A' spending an output of A, because if
388 // transaction B were initially confirmed, conflicting with A and
389 // A', we wouldn't want to the user to create a transaction D
390 // intending to replace A', but potentially resulting in a scenario
391 // where A, A', and D could all be accepted (instead of just B and
392 // D, or just A and A' like the user would want).
393 if (nDepth == 0 && wtx.m_replaced_by_txid) {
394 safeTx = false;
395 }
396
397 if (nDepth == 0 && params.check_version_trucness) {
398 if (coinControl->m_version == TRUC_VERSION) {
399 if (wtx.GetTx()->version != TRUC_VERSION) continue;
400 // this unconfirmed v3 transaction already has a child
401 if (wtx.truc_child_in_mempool.has_value()) continue;
402
403 // this unconfirmed v3 transaction has a parent: spending would create a third generation
404 size_t ancestors, unused_cluster_count;
405 wallet.chain().getTransactionAncestry(wtx.GetTx()->GetHash(), ancestors, unused_cluster_count);
406 if (ancestors > 1) continue;
407 } else {
408 if (wtx.GetTx()->version == TRUC_VERSION) continue;
409 }
410 }
411
412 if (only_safe && !safeTx) {
413 continue;
414 }
415
416 if (nDepth < min_depth || nDepth > max_depth) {
417 continue;
418 }
419
420 tx_safe_cache[outpoint.hash] = {true, safeTx};
421 }
422 const auto& [tx_ok, tx_safe] = tx_safe_cache.at(outpoint.hash);
423 if (!Assume(tx_ok)) {
424 continue;
425 }
426
427 if (output.nValue < params.min_amount || output.nValue > params.max_amount)
428 continue;
429
430 // Skip manually selected coins (the caller can fetch them directly)
431 if (coinControl && coinControl->HasSelected() && coinControl->IsSelected(outpoint))
432 continue;
433
434 if (wallet.IsLockedCoin(outpoint) && params.skip_locked)
435 continue;
436
437 if (wallet.IsSpent(outpoint))
438 continue;
439
440 if (!allow_used_addresses && wallet.IsSpentKey(output.scriptPubKey)) {
441 continue;
442 }
443
444 bool tx_from_me = CachedTxIsFromMe(wallet, wtx);
445
446 std::unique_ptr<SigningProvider> provider = wallet.GetSolvingProvider(output.scriptPubKey);
447
448 int input_bytes = CalculateMaximumSignedInputSize(output, COutPoint(), provider.get(), can_grind_r, coinControl);
449 // Because CalculateMaximumSignedInputSize infers a solvable descriptor to get the satisfaction size,
450 // it is safe to assume that this input is solvable if input_bytes is greater than -1.
451 bool solvable = input_bytes > -1;
452
453 // Obtain script type
454 std::vector<std::vector<uint8_t>> script_solutions;
455 TxoutType type = Solver(output.scriptPubKey, script_solutions);
456
457 // If the output is P2SH and solvable, we want to know if it is
458 // a P2SH (legacy) or one of P2SH-P2WPKH, P2SH-P2WSH (P2SH-Segwit). We can determine
459 // this from the redeemScript. If the output is not solvable, it will be classified
460 // as a P2SH (legacy), since we have no way of knowing otherwise without the redeemScript
461 bool is_from_p2sh{false};
462 if (type == TxoutType::SCRIPTHASH && solvable) {
464 if (!provider->GetCScript(CScriptID(uint160(script_solutions[0])), script)) continue;
465 type = Solver(script, script_solutions);
466 is_from_p2sh = true;
467 }
468
469 auto available_output_type = GetOutputType(type, is_from_p2sh);
470 auto available_output = COutput(outpoint, output, nDepth, input_bytes, solvable, tx_safe, wtx.GetTxTime(), tx_from_me, feerate);
471 if (wtx.GetTx()->version == TRUC_VERSION && nDepth == 0 && params.check_version_trucness) {
472 unconfirmed_truc_coins.emplace_back(available_output_type, available_output);
473 auto [it, _] = truc_txid_by_value.try_emplace(wtx.GetTx()->GetHash(), 0);
474 it->second += output.nValue;
475 } else {
476 result.Add(available_output_type, available_output);
477 }
478
479 outpoints.push_back(outpoint);
480
481 // Checks the sum amount of all UTXO's.
482 if (params.min_sum_amount != MAX_MONEY) {
483 if (result.GetTotalAmount() >= params.min_sum_amount) {
484 return result;
485 }
486 }
487
488 // Checks the maximum number of UTXO's.
489 if (params.max_count > 0 && result.Size() >= params.max_count) {
490 return result;
491 }
492 }
493
494 // Return all the coins from one TRUC transaction, that have the highest value.
495 // This could be improved in the future by encoding these restrictions in
496 // the coin selection itself so that we don't have to filter out
497 // other unconfirmed TRUC coins beforehand.
498 if (params.check_version_trucness && unconfirmed_truc_coins.size() > 0) {
499 auto highest_value_truc_tx = std::max_element(truc_txid_by_value.begin(), truc_txid_by_value.end(), [](const auto& tx1, const auto& tx2){
500 return tx1.second < tx2.second;
501 });
502
503 const Txid& truc_txid = highest_value_truc_tx->first;
504 for (const auto& [type, output] : unconfirmed_truc_coins) {
505 if (output.outpoint.hash == truc_txid) {
506 result.Add(type, output);
507 }
508 }
509 }
510
511 if (feerate.has_value()) {
512 std::map<COutPoint, CAmount> map_of_bump_fees = wallet.chain().calculateIndividualBumpFees(outpoints, feerate.value());
513
514 for (auto& [_, outputs] : result.coins) {
515 for (auto& output : outputs) {
516 output.ApplyBumpFee(map_of_bump_fees.at(output.outpoint));
517 }
518 }
519 }
520
521 return result;
522}
523
525{
526 AssertLockHeld(wallet.cs_wallet);
527 const CWalletTx* wtx{Assert(wallet.GetWalletTx(outpoint.hash))};
528
529 const CTransaction* ptx = wtx->GetTx().get();
530 int n = outpoint.n;
531 while (OutputIsChange(wallet, ptx->vout[n]) && ptx->vin.size() > 0) {
532 const COutPoint& prevout = ptx->vin[0].prevout;
533 const CWalletTx* it = wallet.GetWalletTx(prevout.hash);
534 if (!it || it->GetTx()->vout.size() <= prevout.n ||
535 !wallet.IsMine(it->GetTx()->vout[prevout.n])) {
536 break;
537 }
538 ptx = it->GetTx().get();
539 n = prevout.n;
540 }
541 return ptx->vout[n];
542}
543
544std::map<CTxDestination, std::vector<COutput>> ListCoins(const CWallet& wallet)
545{
546 AssertLockHeld(wallet.cs_wallet);
547
548 std::map<CTxDestination, std::vector<COutput>> result;
549
550 CCoinControl coin_control;
551 CoinFilterParams coins_params;
552 coins_params.skip_locked = false;
553 for (const COutput& coin : AvailableCoins(wallet, &coin_control, /*feerate=*/std::nullopt, coins_params).All()) {
554 CTxDestination address;
555 if (!ExtractDestination(FindNonChangeParentOutput(wallet, coin.outpoint).scriptPubKey, address)) {
556 // For backwards compatibility, we convert P2PK output scripts into PKHash destinations
557 if (auto pk_dest = std::get_if<PubKeyDestination>(&address)) {
558 address = PKHash(pk_dest->GetPubKey());
559 } else {
560 continue;
561 }
562 }
563 result[address].emplace_back(coin);
564 }
565 return result;
566}
567
569 const CoinsResult& coins,
570 const CoinSelectionParams& coin_sel_params,
571 const std::vector<SelectionFilter>& filters,
572 std::vector<OutputGroup>& ret_discarded_groups)
573{
574 FilteredOutputGroups filtered_groups;
575
576 if (!coin_sel_params.m_avoid_partial_spends) {
577 // Allowing partial spends means no grouping. Each COutput gets its own OutputGroup
578 for (const auto& [type, outputs] : coins.coins) {
579 for (const COutput& output : outputs) {
580 // Get mempool info
581 size_t ancestors, cluster_count;
582 wallet.chain().getTransactionAncestry(output.outpoint.hash, ancestors, cluster_count);
583
584 // Create a new group per output and add it to the all groups vector
585 OutputGroup group(coin_sel_params);
586 group.Insert(std::make_shared<COutput>(output), ancestors, cluster_count);
587
588 // Each filter maps to a different set of groups
589 bool accepted = false;
590 for (const auto& sel_filter : filters) {
591 const auto& filter = sel_filter.filter;
592 if (!group.EligibleForSpending(filter)) continue;
593 filtered_groups[filter].Push(group, type, /*insert_positive=*/true, /*insert_mixed=*/true);
594 accepted = true;
595 }
596 if (!accepted) ret_discarded_groups.emplace_back(group);
597 }
598 }
599 return filtered_groups;
600 }
601
602 // We want to combine COutputs that have the same scriptPubKey into single OutputGroups
603 // except when there are more than OUTPUT_GROUP_MAX_ENTRIES COutputs grouped in an OutputGroup.
604 // To do this, we maintain a map where the key is the scriptPubKey and the value is a vector of OutputGroups.
605 // For each COutput, we check if the scriptPubKey is in the map, and if it is, the COutput is added
606 // to the last OutputGroup in the vector for the scriptPubKey. When the last OutputGroup has
607 // OUTPUT_GROUP_MAX_ENTRIES COutputs, a new OutputGroup is added to the end of the vector.
608 typedef std::map<std::pair<CScript, OutputType>, std::vector<OutputGroup>> ScriptPubKeyToOutgroup;
609 const auto& insert_output = [&](
610 const std::shared_ptr<COutput>& output, OutputType type, size_t ancestors, size_t cluster_count,
611 ScriptPubKeyToOutgroup& groups_map) {
612 std::vector<OutputGroup>& groups = groups_map[std::make_pair(output->txout.scriptPubKey,type)];
613
614 if (groups.size() == 0) {
615 // No OutputGroups for this scriptPubKey yet, add one
616 groups.emplace_back(coin_sel_params);
617 }
618
619 // Get the last OutputGroup in the vector so that we can add the COutput to it
620 // A pointer is used here so that group can be reassigned later if it is full.
621 OutputGroup* group = &groups.back();
622
623 // Check if this OutputGroup is full. We limit to OUTPUT_GROUP_MAX_ENTRIES when using -avoidpartialspends
624 // to avoid surprising users with very high fees.
625 if (group->m_outputs.size() >= OUTPUT_GROUP_MAX_ENTRIES) {
626 // The last output group is full, add a new group to the vector and use that group for the insertion
627 groups.emplace_back(coin_sel_params);
628 group = &groups.back();
629 }
630
631 group->Insert(output, ancestors, cluster_count);
632 };
633
634 ScriptPubKeyToOutgroup spk_to_groups_map;
635 ScriptPubKeyToOutgroup spk_to_positive_groups_map;
636 for (const auto& [type, outs] : coins.coins) {
637 for (const COutput& output : outs) {
638 size_t ancestors, cluster_count;
639 wallet.chain().getTransactionAncestry(output.outpoint.hash, ancestors, cluster_count);
640
641 const auto& shared_output = std::make_shared<COutput>(output);
642 // Filter for positive only before adding the output
643 if (output.GetEffectiveValue() > 0) {
644 insert_output(shared_output, type, ancestors, cluster_count, spk_to_positive_groups_map);
645 }
646
647 // 'All' groups
648 insert_output(shared_output, type, ancestors, cluster_count, spk_to_groups_map);
649 }
650 }
651
652 // Now we go through the entire maps and pull out the OutputGroups
653 const auto& push_output_groups = [&](const ScriptPubKeyToOutgroup& groups_map, bool positive_only) {
654 for (const auto& [script, groups] : groups_map) {
655 // Go through the vector backwards. This allows for the first item we deal with being the partial group.
656 for (auto group_it = groups.rbegin(); group_it != groups.rend(); group_it++) {
657 const OutputGroup& group = *group_it;
658
659 // Each filter maps to a different set of groups
660 bool accepted = false;
661 for (const auto& sel_filter : filters) {
662 const auto& filter = sel_filter.filter;
663 if (!group.EligibleForSpending(filter)) continue;
664
665 // Don't include partial groups if there are full groups too and we don't want partial groups
666 if (group_it == groups.rbegin() && groups.size() > 1 && !filter.m_include_partial_groups) {
667 continue;
668 }
669
670 OutputType type = script.second;
671 // Either insert the group into the positive-only groups or the mixed ones.
672 filtered_groups[filter].Push(group, type, positive_only, /*insert_mixed=*/!positive_only);
673 accepted = true;
674 }
675 // The positive-only groups are a subset of the mixed ones, don't record them twice
676 if (!accepted && !positive_only) ret_discarded_groups.emplace_back(group);
677 }
678 }
679 };
680
681 push_output_groups(spk_to_groups_map, /*positive_only=*/ false);
682 push_output_groups(spk_to_positive_groups_map, /*positive_only=*/ true);
683
684 return filtered_groups;
685}
686
688 const CoinsResult& coins,
689 const CoinSelectionParams& params,
690 const std::vector<SelectionFilter>& filters)
691{
692 std::vector<OutputGroup> unused;
693 return GroupOutputs(wallet, coins, params, filters, unused);
694}
695
696// Returns true if the result contains an error and the message is not empty
697static bool HasErrorMsg(const util::Result<SelectionResult>& res) { return !util::ErrorString(res).empty(); }
698
700 const CoinSelectionParams& coin_selection_params, bool allow_mixed_output_types)
701{
702 // Run coin selection on each OutputType and compute the Waste Metric
703 std::vector<SelectionResult> results;
704 for (auto& [type, group] : groups.groups_by_type) {
705 auto result{ChooseSelectionResult(chain, nTargetValue, group, coin_selection_params)};
706 // If any specific error message appears here, then something particularly wrong happened.
707 if (HasErrorMsg(result)) return result; // So let's return the specific error.
708 // Append the favorable result.
709 if (result) results.push_back(*result);
710 }
711 // If we have at least one solution for funding the transaction without mixing, choose the minimum one according to waste metric
712 // and return the result
713 if (results.size() > 0) return *std::min_element(results.begin(), results.end());
714
715 // If we can't fund the transaction from any individual OutputType, run coin selection one last time
716 // over all available coins, which would allow mixing.
717 // If TypesCount() <= 1, there is nothing to mix.
718 if (allow_mixed_output_types && groups.TypesCount() > 1) {
719 return ChooseSelectionResult(chain, nTargetValue, groups.all_groups, coin_selection_params);
720 }
721 // Either mixing is not allowed and we couldn't find a solution from any single OutputType, or mixing was allowed and we still couldn't
722 // find a solution using all available coins
723 return util::Error();
724};
725
726util::Result<SelectionResult> ChooseSelectionResult(interfaces::Chain& chain, const CAmount& nTargetValue, Groups& groups, const CoinSelectionParams& coin_selection_params)
727{
728 // Vector of results. We will choose the best one based on waste.
729 std::vector<SelectionResult> results;
730 std::vector<util::Result<SelectionResult>> errors;
731 auto append_error = [&] (util::Result<SelectionResult>&& result) {
732 // If any specific error message appears here, then something different from a simple "no selection found" happened.
733 // Let's save it, so it can be retrieved to the user if no other selection algorithm succeeded.
734 if (HasErrorMsg(result)) {
735 errors.emplace_back(std::move(result));
736 }
737 };
738
739 // Maximum allowed weight for selected coins.
740 int max_transaction_weight = coin_selection_params.m_max_tx_weight.value_or(MAX_STANDARD_TX_WEIGHT);
741 int tx_weight_no_input = coin_selection_params.tx_noinputs_size * WITNESS_SCALE_FACTOR;
742 int max_selection_weight = max_transaction_weight - tx_weight_no_input;
743 if (max_selection_weight <= 0) {
744 return util::Error{_("Maximum transaction weight is less than transaction weight without inputs")};
745 }
746
747 // SFFO frequently causes issues in the context of changeless input sets: skip BnB when SFFO is active
748 if (!coin_selection_params.m_subtract_fee_outputs) {
749 if (auto bnb_result{SelectCoinsBnB(groups.positive_group, nTargetValue, coin_selection_params.m_cost_of_change, max_selection_weight)}) {
750 results.push_back(*bnb_result);
751 } else append_error(std::move(bnb_result));
752 }
753
754 // Deduct change weight because remaining Coin Selection algorithms can create change output
755 int change_outputs_weight = coin_selection_params.change_output_size * WITNESS_SCALE_FACTOR;
756 max_selection_weight -= change_outputs_weight;
757 if (max_selection_weight < 0 && results.empty()) {
758 return util::Error{_("Maximum transaction weight is too low, can not accommodate change output")};
759 }
760
761 // 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.
762 if (auto knapsack_result{KnapsackSolver(groups.mixed_group, nTargetValue, coin_selection_params.m_min_change_target, coin_selection_params.rng_fast, max_selection_weight)}) {
763 results.push_back(*knapsack_result);
764 } else append_error(std::move(knapsack_result));
765
766 if (coin_selection_params.m_effective_feerate > CFeeRate{3 * coin_selection_params.m_long_term_feerate}) { // Minimize input set for feerates of at least 3×LTFRE (default: 30 ṩ/vB+)
767 if (auto cg_result{CoinGrinder(groups.positive_group, nTargetValue, coin_selection_params.m_min_change_target, max_selection_weight)}) {
768 cg_result->RecalculateWaste(coin_selection_params.min_viable_change, coin_selection_params.m_cost_of_change, coin_selection_params.m_change_fee);
769 results.push_back(*cg_result);
770 } else {
771 append_error(std::move(cg_result));
772 }
773 }
774
775 if (auto srd_result{SelectCoinsSRD(groups.positive_group, nTargetValue, coin_selection_params.m_change_fee, coin_selection_params.rng_fast, max_selection_weight)}) {
776 results.push_back(*srd_result);
777 } else append_error(std::move(srd_result));
778
779 if (results.empty()) {
780 // No solution found, retrieve the first explicit error (if any).
781 // future: add 'severity level' to errors so the worst one can be retrieved instead of the first one.
782 return errors.empty() ? util::Error() : std::move(errors.front());
783 }
784
785 // If the chosen input set has unconfirmed inputs, check for synergies from overlapping ancestry
786 for (auto& result : results) {
787 std::vector<COutPoint> outpoints;
788 OutputSet coins = result.GetInputSet();
789 CAmount summed_bump_fees = 0;
790 for (auto& coin : coins) {
791 if (coin->depth > 0) continue; // Bump fees only exist for unconfirmed inputs
792 outpoints.push_back(coin->outpoint);
793 summed_bump_fees += coin->ancestor_bump_fees;
794 }
795 std::optional<CAmount> combined_bump_fee = chain.calculateCombinedBumpFee(outpoints, coin_selection_params.m_effective_feerate);
796 if (!combined_bump_fee.has_value()) {
797 return util::Error{_("Failed to calculate bump fees, because unconfirmed UTXOs depend on an enormous cluster of unconfirmed transactions.")};
798 }
799 CAmount bump_fee_overestimate = summed_bump_fees - combined_bump_fee.value();
800 // Avoid negative discount if mempool changed between the two bump fee snapshots.
801 if (bump_fee_overestimate > 0) {
802 result.SetBumpFeeDiscount(bump_fee_overestimate);
803 }
804 result.RecalculateWaste(coin_selection_params.min_viable_change, coin_selection_params.m_cost_of_change, coin_selection_params.m_change_fee);
805 }
806
807 // Choose the result with the least waste
808 // If the waste is the same, choose the one which spends more inputs.
809 return *std::min_element(results.begin(), results.end());
810}
811
812util::Result<SelectionResult> SelectCoins(const CWallet& wallet, CoinsResult& available_coins, const CoinsResult& pre_set_inputs,
813 const CAmount& nTargetValue, const CCoinControl& coin_control,
814 const CoinSelectionParams& coin_selection_params)
815{
816 // Deduct preset inputs amount from the search target
817 CAmount selection_target = nTargetValue - pre_set_inputs.GetAppropriateTotal(coin_selection_params.m_subtract_fee_outputs).value_or(0);
818
819 // Return if automatic coin selection is disabled, and we don't cover the selection target
820 if (!coin_control.m_allow_other_inputs && selection_target > 0) {
821 return util::Error{_("The preselected coins total amount does not cover the transaction target. "
822 "Please allow other inputs to be automatically selected or include more coins manually")};
823 }
824
825 OutputSet preset_coin_set;
826 for (const auto& output: pre_set_inputs.All()) {
827 preset_coin_set.insert(std::make_shared<COutput>(output));
828 }
829
830 // Return if we can cover the target only with the preset inputs
831 if (selection_target <= 0) {
832 SelectionResult result(nTargetValue, SelectionAlgorithm::MANUAL);
833 result.AddInputs(preset_coin_set, coin_selection_params.m_subtract_fee_outputs);
834 result.RecalculateWaste(coin_selection_params.min_viable_change, coin_selection_params.m_cost_of_change, coin_selection_params.m_change_fee);
835 return result;
836 }
837
838 // Return early if we cannot cover the target with the wallet's UTXO.
839 // We use the total effective value if we are not subtracting fee from outputs and 'available_coins' contains the data.
840 CAmount available_coins_total_amount = available_coins.GetAppropriateTotal(coin_selection_params.m_subtract_fee_outputs).value_or(0);
841 if (selection_target > available_coins_total_amount) {
842 return util::Error(); // Insufficient funds
843 }
844
845 // Start wallet Coin Selection procedure
846 auto op_selection_result = AutomaticCoinSelection(wallet, available_coins, selection_target, coin_selection_params);
847 if (!op_selection_result) return op_selection_result;
848
849 // If needed, add preset inputs to the automatic coin selection result
850 if (!pre_set_inputs.coins.empty()) {
851 auto preset_total = pre_set_inputs.GetAppropriateTotal(coin_selection_params.m_subtract_fee_outputs);
852 assert(preset_total.has_value());
853 SelectionResult preselected(preset_total.value(), SelectionAlgorithm::MANUAL);
854 preselected.AddInputs(preset_coin_set, coin_selection_params.m_subtract_fee_outputs);
855 op_selection_result->Merge(preselected);
856 op_selection_result->RecalculateWaste(coin_selection_params.min_viable_change,
857 coin_selection_params.m_cost_of_change,
858 coin_selection_params.m_change_fee);
859
860 // Verify we haven't exceeded the maximum allowed weight
861 int max_inputs_weight = coin_selection_params.m_max_tx_weight.value_or(MAX_STANDARD_TX_WEIGHT) - (coin_selection_params.tx_noinputs_size * WITNESS_SCALE_FACTOR);
862 if (op_selection_result->GetWeight() > max_inputs_weight) {
863 return util::Error{_("The combination of the pre-selected inputs and the wallet automatic inputs selection exceeds the transaction maximum weight. "
864 "Please try sending a smaller amount or manually consolidating your wallet's UTXOs")};
865 }
866 }
867 return op_selection_result;
868}
869
870util::Result<SelectionResult> AutomaticCoinSelection(const CWallet& wallet, CoinsResult& available_coins, const CAmount& value_to_select, const CoinSelectionParams& coin_selection_params)
871{
872 // Try to enforce a mixture of cluster limits and ancestor/descendant limits on transactions we create by limiting
873 // the ancestors and the maximum cluster count of any UTXO we use. We use the ancestor/descendant limits, which are
874 // lower than the cluster limits, to avoid exceeding any ancestor/descendant limits of legacy nodes. This filter is safe
875 // because a transaction's ancestor or descendant count cannot be larger than its cluster count.
876 // TODO: these limits can be relaxed in the future, and we can replace the ancestor filter with a cluster equivalent.
877 unsigned int limit_ancestor_count = 0;
878 unsigned int limit_descendant_count = 0;
879 wallet.chain().getPackageLimits(limit_ancestor_count, limit_descendant_count);
880 const size_t max_ancestors = (size_t)std::max<int64_t>(1, limit_ancestor_count);
881 const size_t max_cluster_count = (size_t)std::max<int64_t>(1, limit_descendant_count);
882 const bool fRejectLongChains = gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
883
884 // Cases where we have 101+ outputs all pointing to the same destination may result in
885 // privacy leaks as they will potentially be deterministically sorted. We solve that by
886 // explicitly shuffling the outputs before processing
887 if (coin_selection_params.m_avoid_partial_spends && available_coins.Size() > OUTPUT_GROUP_MAX_ENTRIES) {
888 available_coins.Shuffle(coin_selection_params.rng_fast);
889 }
890
891 // Coin Selection attempts to select inputs from a pool of eligible UTXOs to fund the
892 // transaction at a target feerate. If an attempt fails, more attempts may be made using a more
893 // permissive CoinEligibilityFilter.
894 {
895 // Place coins eligibility filters on a scope increasing order.
896 std::vector<SelectionFilter> ordered_filters{
897 // If possible, fund the transaction with confirmed UTXOs only. Prefer at least six
898 // confirmations on outputs received from other wallets and only spend confirmed change.
899 {CoinEligibilityFilter(1, 6, 0), /*allow_mixed_output_types=*/false},
900 {CoinEligibilityFilter(1, 1, 0)},
901 };
902 // Fall back to using zero confirmation change (but with as few ancestors in the mempool as
903 // possible) if we cannot fund the transaction otherwise.
904 if (wallet.m_spend_zero_conf_change) {
905 ordered_filters.push_back({CoinEligibilityFilter(0, 1, 2)});
906 ordered_filters.push_back({CoinEligibilityFilter(0, 1, std::min(size_t{4}, max_ancestors/3), std::min(size_t{4}, max_cluster_count/3))});
907 ordered_filters.push_back({CoinEligibilityFilter(0, 1, max_ancestors/2, max_cluster_count/2)});
908 // If partial groups are allowed, relax the requirement of spending OutputGroups (groups
909 // of UTXOs sent to the same address, which are obviously controlled by a single wallet)
910 // in their entirety.
911 ordered_filters.push_back({CoinEligibilityFilter(0, 1, max_ancestors-1, max_cluster_count-1, /*include_partial=*/true)});
912 // Try with unsafe inputs if they are allowed. This may spend unconfirmed outputs
913 // received from other wallets.
914 if (coin_selection_params.m_include_unsafe_inputs) {
915 ordered_filters.push_back({CoinEligibilityFilter(/*conf_mine=*/0, /*conf_theirs=*/0, max_ancestors-1, max_cluster_count-1, /*include_partial=*/true)});
916 }
917 // Try with unlimited ancestors/clusters. The transaction will still need to meet
918 // local mempool policy (i.e. cluster limits) to be accepted to mempool and broadcasted, and
919 // limits of other nodes (e.g. ancestor/descendant limits) to propagate, but OutputGroups
920 // use heuristics that may overestimate.
921 if (!fRejectLongChains) {
922 ordered_filters.push_back({CoinEligibilityFilter(0, 1, std::numeric_limits<uint64_t>::max(),
923 std::numeric_limits<uint64_t>::max(),
924 /*include_partial=*/true)});
925 }
926 }
927
928 // Group outputs and map them by coin eligibility filter
929 std::vector<OutputGroup> discarded_groups;
930 FilteredOutputGroups filtered_groups = GroupOutputs(wallet, available_coins, coin_selection_params, ordered_filters, discarded_groups);
931
932 // Check if we still have enough balance after applying filters (some coins might be discarded)
933 CAmount total_discarded = 0;
934 CAmount total_unconf_long_chain = 0;
935 for (const auto& group : discarded_groups) {
936 total_discarded += group.GetSelectionAmount();
937 if (group.m_ancestors >= max_ancestors || group.m_max_cluster_count >= max_cluster_count) total_unconf_long_chain += group.GetSelectionAmount();
938 }
939
940 if (CAmount total_amount = available_coins.GetTotalAmount() - total_discarded; total_amount < value_to_select) {
941 // Special case, too-long-mempool cluster.
942 if (total_amount + total_unconf_long_chain > value_to_select) {
943 return util::Error{_("Unconfirmed UTXOs are available, but spending them creates a chain of transactions that will be rejected by the mempool")};
944 }
945 return util::Error{}; // General "Insufficient Funds"
946 }
947
948 // Walk-through the filters until the solution gets found.
949 // If no solution is found, return the first detailed error (if any).
950 // future: add "error level" so the worst one can be picked instead.
951 std::vector<util::Result<SelectionResult>> res_detailed_errors;
952 CoinSelectionParams updated_selection_params = coin_selection_params;
953 for (const auto& select_filter : ordered_filters) {
954 auto it = filtered_groups.find(select_filter.filter);
955 if (it == filtered_groups.end()) continue;
956 if (updated_selection_params.m_version == TRUC_VERSION && (select_filter.filter.conf_mine == 0 || select_filter.filter.conf_theirs == 0)) {
957 if (updated_selection_params.m_max_tx_weight > (TRUC_CHILD_MAX_WEIGHT)) {
958 updated_selection_params.m_max_tx_weight = TRUC_CHILD_MAX_WEIGHT;
959 }
960 }
961 if (auto res{AttemptSelection(wallet.chain(), value_to_select, it->second,
962 updated_selection_params, select_filter.allow_mixed_output_types)}) {
963 return res; // result found
964 } else {
965 // If any specific error message appears here, then something particularly wrong might have happened.
966 // Save the error and continue the selection process. So if no solutions gets found, we can return
967 // the detailed error to the upper layers.
968 if (HasErrorMsg(res)) res_detailed_errors.emplace_back(std::move(res));
969 }
970 }
971
972 // Return right away if we have a detailed error
973 if (!res_detailed_errors.empty()) return std::move(res_detailed_errors.front());
974
975
976 // General "Insufficient Funds"
977 return util::Error{};
978 }
979}
980
981static bool IsCurrentForAntiFeeSniping(interfaces::Chain& chain, const uint256& block_hash)
982{
983 if (chain.isInitialBlockDownload()) {
984 return false;
985 }
986 constexpr int64_t MAX_ANTI_FEE_SNIPING_TIP_AGE = 8 * 60 * 60; // in seconds
987 int64_t block_time;
988 CHECK_NONFATAL(chain.findBlock(block_hash, FoundBlock().time(block_time)));
989 if (block_time < (GetTime() - MAX_ANTI_FEE_SNIPING_TIP_AGE)) {
990 return false;
991 }
992 return true;
993}
994
996 interfaces::Chain& chain, const uint256& block_hash, int block_height)
997{
998 // All inputs must be added by now
999 assert(!tx.vin.empty());
1000 // Discourage fee sniping.
1001 //
1002 // For a large miner the value of the transactions in the best block and
1003 // the mempool can exceed the cost of deliberately attempting to mine two
1004 // blocks to orphan the current best block. By setting nLockTime such that
1005 // only the next block can include the transaction, we discourage this
1006 // practice as the height restricted and limited blocksize gives miners
1007 // considering fee sniping fewer options for pulling off this attack.
1008 //
1009 // A simple way to think about this is from the wallet's point of view we
1010 // always want the blockchain to move forward. By setting nLockTime this
1011 // way we're basically making the statement that we only want this
1012 // transaction to appear in the next block; we don't want to potentially
1013 // encourage reorgs by allowing transactions to appear at lower heights
1014 // than the next block in forks of the best chain.
1015 //
1016 // Of course, the subsidy is high enough, and transaction volume low
1017 // enough, that fee sniping isn't a problem yet, but by implementing a fix
1018 // now we ensure code won't be written that makes assumptions about
1019 // nLockTime that preclude a fix later.
1020 if (IsCurrentForAntiFeeSniping(chain, block_hash)) {
1021 tx.nLockTime = block_height;
1022
1023 // Secondly occasionally randomly pick a nLockTime even further back, so
1024 // that transactions that are delayed after signing for whatever reason,
1025 // e.g. high-latency mix networks and some CoinJoin implementations, have
1026 // better privacy.
1027 if (rng_fast.randrange(10) == 0) {
1028 tx.nLockTime = std::max(0, int(tx.nLockTime) - int(rng_fast.randrange(100)));
1029 }
1030 } else {
1031 // If our chain is lagging behind, we can't discourage fee sniping nor help
1032 // the privacy of high-latency transactions. To avoid leaking a potentially
1033 // unique "nLockTime fingerprint", set nLockTime to a constant.
1034 tx.nLockTime = 0;
1035 }
1036 // Sanity check all values
1037 assert(tx.nLockTime < LOCKTIME_THRESHOLD); // Type must be block height
1038 assert(tx.nLockTime <= uint64_t(block_height));
1039 for (const auto& in : tx.vin) {
1040 // Can not be FINAL for locktime to work
1041 assert(in.nSequence != CTxIn::SEQUENCE_FINAL);
1042 // May be MAX NONFINAL to disable both BIP68 and BIP125
1043 if (in.nSequence == CTxIn::MAX_SEQUENCE_NONFINAL) continue;
1044 // May be MAX BIP125 to disable BIP68 and enable BIP125
1045 if (in.nSequence == MAX_BIP125_RBF_SEQUENCE) continue;
1046 // The wallet does not support any other sequence-use right now.
1047 assert(false);
1048 }
1049}
1050
1052{
1054}
1055
1056bool IsDust(const CRecipient& recipient, const CFeeRate& dustRelayFee)
1057{
1058 return ::IsDust(CTxOut(recipient.nAmount, GetScriptForDestination(recipient.dest)), dustRelayFee);
1059}
1060
1062 CWallet& wallet,
1063 const std::vector<CRecipient>& vecSend,
1064 std::optional<unsigned int> change_pos,
1065 const CCoinControl& coin_control,
1066 bool sign) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
1067{
1068 AssertLockHeld(wallet.cs_wallet);
1069
1070 FastRandomContext rng_fast;
1071 CMutableTransaction txNew; // The resulting transaction that we make
1072
1073 txNew.version = coin_control.m_version;
1074
1075 CoinSelectionParams coin_selection_params{rng_fast}; // Parameters for coin selection, init with dummy
1076 coin_selection_params.m_avoid_partial_spends = coin_control.m_avoid_partial_spends;
1077 coin_selection_params.m_include_unsafe_inputs = coin_control.m_include_unsafe_inputs;
1078 coin_selection_params.m_max_tx_weight = coin_control.m_max_tx_weight.value_or(MAX_STANDARD_TX_WEIGHT);
1079 coin_selection_params.m_version = coin_control.m_version;
1080 int minimum_tx_weight = MIN_STANDARD_TX_NONWITNESS_SIZE * WITNESS_SCALE_FACTOR;
1081 if (coin_selection_params.m_max_tx_weight.value() < minimum_tx_weight || coin_selection_params.m_max_tx_weight.value() > MAX_STANDARD_TX_WEIGHT) {
1082 return util::Error{strprintf(_("Maximum transaction weight must be between %d and %d"), minimum_tx_weight, MAX_STANDARD_TX_WEIGHT)};
1083 }
1084 // Set the long term feerate estimate to the wallet's consolidate feerate
1085 coin_selection_params.m_long_term_feerate = wallet.m_consolidate_feerate;
1086 // Static vsize overhead + outputs vsize. 4 nVersion, 4 nLocktime, 1 input count, 1 witness overhead (dummy, flag, stack size)
1087 coin_selection_params.tx_noinputs_size = 10 + GetSizeOfCompactSize(vecSend.size()); // bytes for output count
1088
1089 CAmount recipients_sum = 0;
1090 const OutputType change_type = wallet.TransactionChangeType(coin_control.m_change_type ? *coin_control.m_change_type : wallet.m_default_change_type, vecSend);
1091 ReserveDestination reservedest(&wallet, change_type);
1092 unsigned int outputs_to_subtract_fee_from = 0; // The number of outputs which we are subtracting the fee from
1093 for (const auto& recipient : vecSend) {
1094 if (IsDust(recipient, wallet.chain().relayDustFee())) {
1095 return util::Error{_("Transaction amount too small")};
1096 }
1097
1098 // Include the fee cost for outputs.
1099 coin_selection_params.tx_noinputs_size += GetSerializeSizeForRecipient(recipient);
1100 recipients_sum += recipient.nAmount;
1101
1102 if (recipient.fSubtractFeeFromAmount) {
1103 outputs_to_subtract_fee_from++;
1104 coin_selection_params.m_subtract_fee_outputs = true;
1105 }
1106 }
1107
1108 // Create change script that will be used if we need change
1109 CScript scriptChange;
1110 bilingual_str error; // possible error str
1111
1112 // coin control: send change to custom address
1113 if (!std::get_if<CNoDestination>(&coin_control.destChange)) {
1114 scriptChange = GetScriptForDestination(coin_control.destChange);
1115 } else { // no coin control: send change to newly generated address
1116 // Note: We use a new key here to keep it from being obvious which side is the change.
1117 // The drawback is that by not reusing a previous key, the change may be lost if a
1118 // backup is restored, if the backup doesn't have the new private key for the change.
1119 // If we reused the old key, it would be possible to add code to look for and
1120 // rediscover unknown transactions that were written with keys of ours to recover
1121 // post-backup change.
1122
1123 // Reserve a new key pair from key pool. If it fails, provide a dummy
1124 // destination in case we don't need change.
1125 CTxDestination dest;
1126 auto op_dest = reservedest.GetReservedDestination(true);
1127 if (!op_dest) {
1128 error = _("Transaction needs a change address, but we can't generate it.") + Untranslated(" ") + util::ErrorString(op_dest);
1129 } else {
1130 dest = *op_dest;
1131 scriptChange = GetScriptForDestination(dest);
1132 }
1133 // A valid destination implies a change script (and
1134 // vice-versa). An empty change script will abort later, if the
1135 // change keypool ran out, but change is required.
1136 CHECK_NONFATAL(IsValidDestination(dest) != scriptChange.empty());
1137 }
1138 CTxOut change_prototype_txout(0, scriptChange);
1139 coin_selection_params.change_output_size = GetSerializeSize(change_prototype_txout);
1140
1141 // Get size of spending the change output
1142 int change_spend_size = CalculateMaximumSignedInputSize(change_prototype_txout, &wallet, /*coin_control=*/nullptr);
1143 // If the wallet doesn't know how to sign change output, assume p2sh-p2wpkh
1144 // as lower-bound to allow BnB to do its thing
1145 if (change_spend_size == -1) {
1146 coin_selection_params.change_spend_size = DUMMY_NESTED_P2WPKH_INPUT_SIZE;
1147 } else {
1148 coin_selection_params.change_spend_size = change_spend_size;
1149 }
1150
1151 // Set discard feerate
1152 coin_selection_params.m_discard_feerate = GetDiscardRate(wallet);
1153
1154 // Get the fee rate to use effective values in coin selection
1155 auto min_fee_rate{GetMinimumFeeRate(wallet, coin_control)};
1156 coin_selection_params.m_effective_feerate = min_fee_rate.fee_rate;
1157 // Do not, ever, assume that it's fine to change the fee rate if the user has explicitly
1158 // provided one
1159 if (coin_control.m_feerate && coin_selection_params.m_effective_feerate > *coin_control.m_feerate) {
1160 const auto feerate_format = FeeRateFormat::SAT_VB;
1161 auto msg{strprintf(_("Fee rate (%s) is lower than the minimum fee rate setting (%s)."),
1162 coin_control.m_feerate->ToString(feerate_format),
1163 coin_selection_params.m_effective_feerate.ToString(feerate_format))};
1164 if (min_fee_rate.fee_reason == FeeReason::REQUIRED) {
1165 msg += strprintf(_("\nConsider modifying %s (%s) or %s (%s)."),
1166 "-mintxfee",
1167 wallet.m_min_fee.ToString(feerate_format),
1168 "-minrelaytxfee",
1169 wallet.chain().relayMinFee().ToString(feerate_format));
1170 }
1171 return util::Error{msg};
1172 }
1173 if (min_fee_rate.fee_reason == FeeReason::FALLBACK && !wallet.m_allow_fallback_fee) {
1174 // eventually allow a fallback fee
1175 return util::Error{strprintf(_("Fee estimation failed. Fallbackfee is disabled. Wait a few blocks or enable %s."), "-fallbackfee")};
1176 }
1177
1178 // Calculate the cost of change
1179 // Cost of change is the cost of creating the change output + cost of spending the change output in the future.
1180 // For creating the change output now, we use the effective feerate.
1181 // For spending the change output in the future, we use the discard feerate for now.
1182 // So cost of change = (change output size * effective feerate) + (size of spending change output * discard feerate)
1183 coin_selection_params.m_change_fee = coin_selection_params.m_effective_feerate.GetFee(coin_selection_params.change_output_size);
1184 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;
1185
1186 coin_selection_params.m_min_change_target = GenerateChangeTarget(std::floor(recipients_sum / vecSend.size()), coin_selection_params.m_change_fee, rng_fast);
1187
1188 // The smallest change amount should be:
1189 // 1. at least equal to dust threshold
1190 // 2. at least 1 sat greater than fees to spend it at m_discard_feerate
1191 const auto dust = GetDustThreshold(change_prototype_txout, coin_selection_params.m_discard_feerate);
1192 const auto change_spend_fee = coin_selection_params.m_discard_feerate.GetFee(coin_selection_params.change_spend_size);
1193 coin_selection_params.min_viable_change = std::max(change_spend_fee + 1, dust);
1194
1195 // Include the fees for things that aren't inputs, excluding the change output
1196 const CAmount not_input_fees = coin_selection_params.m_effective_feerate.GetFee(coin_selection_params.m_subtract_fee_outputs ? 0 : coin_selection_params.tx_noinputs_size);
1197 CAmount selection_target = recipients_sum + not_input_fees;
1198
1199 // This can only happen if feerate is 0, and requested destinations are value of 0 (e.g. OP_RETURN)
1200 // and no pre-selected inputs. This will result in 0-input transaction, which is consensus-invalid anyways
1201 if (selection_target == 0 && !coin_control.HasSelected()) {
1202 return util::Error{_("Transaction requires one destination of non-zero value, a non-zero feerate, or a pre-selected input")};
1203 }
1204
1205 // Fetch manually selected coins
1206 CoinsResult preset_inputs;
1207 if (coin_control.HasSelected()) {
1208 auto res_fetch_inputs = FetchSelectedInputs(wallet, coin_control, coin_selection_params);
1209 if (!res_fetch_inputs) return util::Error{util::ErrorString(res_fetch_inputs)};
1210 preset_inputs = *res_fetch_inputs;
1211 }
1212
1213 // Fetch wallet available coins if "other inputs" are
1214 // allowed (coins automatically selected by the wallet)
1215 CoinsResult available_coins;
1216 if (coin_control.m_allow_other_inputs) {
1217 available_coins = AvailableCoins(wallet, &coin_control, coin_selection_params.m_effective_feerate);
1218 }
1219
1220 // Choose coins to use
1221 auto select_coins_res = SelectCoins(wallet, available_coins, preset_inputs, /*nTargetValue=*/selection_target, coin_control, coin_selection_params);
1222 if (!select_coins_res) {
1223 // 'SelectCoins' either returns a specific error message or, if empty, means a general "Insufficient funds".
1224 const bilingual_str& err = util::ErrorString(select_coins_res);
1225 if (!err.empty()) return util::Error{err};
1226
1227 // Check if we have enough balance but cannot cover the fees
1228 CAmount available_balance = preset_inputs.GetTotalAmount() + available_coins.GetTotalAmount();
1229 // Note: if SelectCoins() fails when SFFO is enabled (recipients_sum = selection_target with SFFO),
1230 // then recipients_sum > available_balance and we wouldn't enter into the if condition below.
1231 if (available_balance >= recipients_sum) {
1232 // If we have coins with balance, they should have effective values since we constructed them with valid feerate.
1233 assert(!preset_inputs.Size() || preset_inputs.GetEffectiveTotalAmount().has_value());
1234 assert(!available_coins.Size() || available_coins.GetEffectiveTotalAmount().has_value());
1235 CAmount available_effective_balance = preset_inputs.GetEffectiveTotalAmount().value_or(0) + available_coins.GetEffectiveTotalAmount().value_or(0);
1236 if (available_effective_balance < selection_target) {
1237 Assume(!coin_selection_params.m_subtract_fee_outputs);
1238 return util::Error{strprintf(_("The total exceeds your balance when the %s transaction fee is included."), FormatMoney(selection_target - recipients_sum))};
1239 }
1240 }
1241
1242 // General failure description
1243 return util::Error{_("Insufficient funds")};
1244 }
1245 const SelectionResult& result = *select_coins_res;
1246 TRACEPOINT(coin_selection, selected_coins,
1247 wallet.GetName().c_str(),
1248 GetAlgorithmName(result.GetAlgo()).c_str(),
1249 result.GetTarget(),
1250 result.GetWaste(),
1251 result.GetSelectedValue());
1252
1253 // vouts to the payees
1254 txNew.vout.reserve(vecSend.size() + 1); // + 1 because of possible later insert
1255 for (const auto& recipient : vecSend)
1256 {
1257 txNew.vout.emplace_back(recipient.nAmount, GetScriptForDestination(recipient.dest));
1258 }
1259 const CAmount change_amount = result.GetChange(coin_selection_params.min_viable_change, coin_selection_params.m_change_fee);
1260 if (change_amount > 0) {
1261 CTxOut newTxOut(change_amount, scriptChange);
1262 if (!change_pos) {
1263 // Insert change txn at random position:
1264 change_pos = rng_fast.randrange(txNew.vout.size() + 1);
1265 } else if ((unsigned int)*change_pos > txNew.vout.size()) {
1266 return util::Error{_("Transaction change output index out of range")};
1267 }
1268 txNew.vout.insert(txNew.vout.begin() + *change_pos, newTxOut);
1269 } else {
1270 change_pos = std::nullopt;
1271 }
1272
1273 // Shuffle selected coins and fill in final vin
1274 std::vector<std::shared_ptr<COutput>> selected_coins = result.GetShuffledInputVector();
1275
1276 if (coin_control.HasSelected() && coin_control.HasSelectedOrder()) {
1277 // When there are preselected inputs, we need to move them to be the first UTXOs
1278 // and have them be in the order selected. We can use stable_sort for this, where we
1279 // compare with the positions stored in coin_control. The COutputs that have positions
1280 // will be placed before those that don't, and those positions will be in order.
1281 std::stable_sort(selected_coins.begin(), selected_coins.end(),
1282 [&coin_control](const std::shared_ptr<COutput>& a, const std::shared_ptr<COutput>& b) {
1283 auto a_pos = coin_control.GetSelectionPos(a->outpoint);
1284 auto b_pos = coin_control.GetSelectionPos(b->outpoint);
1285 if (a_pos.has_value() && b_pos.has_value()) {
1286 return a_pos.value() < b_pos.value();
1287 } else if (a_pos.has_value() && !b_pos.has_value()) {
1288 return true;
1289 } else {
1290 return false;
1291 }
1292 });
1293 }
1294
1295 // The sequence number is set to non-maxint so that DiscourageFeeSniping
1296 // works.
1297 //
1298 // BIP125 defines opt-in RBF as any nSequence < maxint-1, so
1299 // we use the highest possible value in that range (maxint-2)
1300 // to avoid conflicting with other possible uses of nSequence,
1301 // and in the spirit of "smallest possible change from prior
1302 // behavior."
1303 bool use_anti_fee_sniping = true;
1304 const uint32_t default_sequence{coin_control.m_signal_bip125_rbf.value_or(wallet.m_signal_rbf) ? MAX_BIP125_RBF_SEQUENCE : CTxIn::MAX_SEQUENCE_NONFINAL};
1305 txNew.vin.reserve(selected_coins.size());
1306 for (const auto& coin : selected_coins) {
1307 std::optional<uint32_t> sequence = coin_control.GetSequence(coin->outpoint);
1308 if (sequence) {
1309 // If an input has a preset sequence, we can't do anti-fee-sniping
1310 use_anti_fee_sniping = false;
1311 }
1312 txNew.vin.emplace_back(coin->outpoint, CScript{}, sequence.value_or(default_sequence));
1313
1314 auto scripts = coin_control.GetScripts(coin->outpoint);
1315 if (scripts.first) {
1316 txNew.vin.back().scriptSig = *scripts.first;
1317 }
1318 if (scripts.second) {
1319 txNew.vin.back().scriptWitness = *scripts.second;
1320 }
1321 }
1322 if (coin_control.m_locktime) {
1323 txNew.nLockTime = coin_control.m_locktime.value();
1324 // If we have a locktime set, we can't use anti-fee-sniping
1325 use_anti_fee_sniping = false;
1326 }
1327 if (use_anti_fee_sniping) {
1328 DiscourageFeeSniping(txNew, rng_fast, wallet.chain(), wallet.GetLastBlockHash(), wallet.GetLastBlockHeight());
1329 }
1330
1331 // Calculate the transaction fee
1332 TxSize tx_sizes = CalculateMaximumSignedTxSize(CTransaction(txNew), &wallet, &coin_control);
1333 int nBytes = tx_sizes.vsize;
1334 if (nBytes == -1) {
1335 return util::Error{_("Missing solving data for estimating transaction size")};
1336 }
1337 CAmount fee_needed = coin_selection_params.m_effective_feerate.GetFee(nBytes) + result.GetTotalBumpFees();
1338 const CAmount output_value = CalculateOutputValue(txNew);
1339 Assume(recipients_sum + change_amount == output_value);
1340 CAmount current_fee = result.GetSelectedValue() - output_value;
1341
1342 // Sanity check that the fee cannot be negative as that means we have more output value than input value
1343 if (current_fee < 0) {
1344 return util::Error{Untranslated(STR_INTERNAL_BUG("Fee paid < 0"))};
1345 }
1346
1347 // If there is a change output and we overpay the fees then increase the change to match the fee needed
1348 if (change_pos && fee_needed < current_fee) {
1349 auto& change = txNew.vout.at(*change_pos);
1350 change.nValue += current_fee - fee_needed;
1351 current_fee = result.GetSelectedValue() - CalculateOutputValue(txNew);
1352 if (fee_needed != current_fee) {
1353 return util::Error{Untranslated(STR_INTERNAL_BUG("Change adjustment: Fee needed != fee paid"))};
1354 }
1355 }
1356
1357 // Reduce output values for subtractFeeFromAmount
1358 if (coin_selection_params.m_subtract_fee_outputs) {
1359 CAmount to_reduce = fee_needed - current_fee;
1360 unsigned int i = 0;
1361 bool fFirst = true;
1362 for (const auto& recipient : vecSend)
1363 {
1364 if (change_pos && i == *change_pos) {
1365 ++i;
1366 }
1367 CTxOut& txout = txNew.vout[i];
1368
1369 if (recipient.fSubtractFeeFromAmount)
1370 {
1371 txout.nValue -= to_reduce / outputs_to_subtract_fee_from; // Subtract fee equally from each selected recipient
1372
1373 if (fFirst) // first receiver pays the remainder not divisible by output count
1374 {
1375 fFirst = false;
1376 txout.nValue -= to_reduce % outputs_to_subtract_fee_from;
1377 }
1378
1379 // Error if this output is reduced to be below dust
1380 if (IsDust(txout, wallet.chain().relayDustFee())) {
1381 if (txout.nValue < 0) {
1382 return util::Error{_("The transaction amount is too small to pay the fee")};
1383 } else {
1384 return util::Error{_("The transaction amount is too small to send after the fee has been deducted")};
1385 }
1386 }
1387 }
1388 ++i;
1389 }
1390 current_fee = result.GetSelectedValue() - CalculateOutputValue(txNew);
1391 if (fee_needed != current_fee) {
1392 return util::Error{Untranslated(STR_INTERNAL_BUG("SFFO: Fee needed != fee paid"))};
1393 }
1394 }
1395
1396 // fee_needed should now always be less than or equal to the current fees that we pay.
1397 // If it is not, it is a bug.
1398 if (fee_needed > current_fee) {
1399 return util::Error{Untranslated(STR_INTERNAL_BUG("Fee needed > fee paid"))};
1400 }
1401
1402 // Give up if change keypool ran out and change is required
1403 if (scriptChange.empty() && change_pos) {
1404 return util::Error{error};
1405 }
1406
1407 if (sign && !wallet.SignTransaction(txNew)) {
1408 return util::Error{_("Signing transaction failed")};
1409 }
1410
1411 // Return the constructed transaction data.
1412 CTransactionRef tx = MakeTransactionRef(std::move(txNew));
1413
1414 // Limit size
1416 (!sign && tx_sizes.weight > MAX_STANDARD_TX_WEIGHT))
1417 {
1418 return util::Error{_("Transaction too large")};
1419 }
1420
1421 if (current_fee > wallet.m_max_tx_fee) {
1422 return util::Error{TransactionErrorString(TransactionError::MAX_FEE_EXCEEDED)};
1423 }
1424
1425 const int64_t tx_vsize{GetVirtualTransactionSize(*tx)};
1426 if (current_fee > wallet.m_max_tx_fee_rate.GetFee(tx_vsize)) {
1427 return util::Error{TransactionErrorString(TransactionError::MAX_FEE_RATE_EXCEEDED)};
1428 }
1429
1430 if (gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
1431 // Lastly, ensure this tx will pass the mempool's chain limits
1432 auto result = wallet.chain().checkChainLimits(tx);
1433 if (!result) {
1434 return util::Error{util::ErrorString(result)};
1435 }
1436 }
1437
1438 // Before we return success, we assume any change key will be used to prevent
1439 // accidental reuse.
1440 reservedest.KeepDestination();
1441
1442 wallet.WalletLogPrintf("Coin Selection: Algorithm:%s, Waste Metric Score:%d\n", GetAlgorithmName(result.GetAlgo()), result.GetWaste());
1443 wallet.WalletLogPrintf("Fee Calculation: Fee:%d Bytes:%u, Source: %s\n",
1444 current_fee, nBytes, StringForFeeReason(min_fee_rate.fee_reason));
1445 return CreatedTransactionResult(tx, current_fee, change_pos, min_fee_rate.fee_reason);
1446}
1447
1449 CWallet& wallet,
1450 const std::vector<CRecipient>& vecSend,
1451 std::optional<unsigned int> change_pos,
1452 const CCoinControl& coin_control,
1453 bool sign)
1454{
1455 if (vecSend.empty()) {
1456 return util::Error{_("Transaction must have at least one recipient")};
1457 }
1458
1459 if (std::any_of(vecSend.cbegin(), vecSend.cend(), [](const auto& recipient){ return recipient.nAmount < 0; })) {
1460 return util::Error{_("Transaction amounts must not be negative")};
1461 }
1462
1463 LOCK(wallet.cs_wallet);
1464
1465 auto res = CreateTransactionInternal(wallet, vecSend, change_pos, coin_control, sign);
1466 TRACEPOINT(coin_selection, normal_create_tx_internal,
1467 wallet.GetName().c_str(),
1468 bool(res),
1469 res ? res->fee : 0,
1470 res && res->change_pos.has_value() ? int32_t(*res->change_pos) : -1);
1471 if (!res) return res;
1472 const auto& txr_ungrouped = *res;
1473 // try with avoidpartialspends unless it's enabled already
1474 if (txr_ungrouped.fee > 0 /* 0 means non-functional fee rate estimation */ && wallet.m_max_aps_fee > -1 && !coin_control.m_avoid_partial_spends) {
1475 TRACEPOINT(coin_selection, attempting_aps_create_tx, wallet.GetName().c_str());
1476 CCoinControl tmp_cc = coin_control;
1477 tmp_cc.m_avoid_partial_spends = true;
1478
1479 // Reuse the change destination from the first creation attempt to avoid skipping BIP44 indexes
1480 if (txr_ungrouped.change_pos) {
1481 ExtractDestination(txr_ungrouped.tx->vout[*txr_ungrouped.change_pos].scriptPubKey, tmp_cc.destChange);
1482 }
1483
1484 auto txr_grouped = CreateTransactionInternal(wallet, vecSend, change_pos, tmp_cc, sign);
1485 // if fee of this alternative one is within the range of the max fee, we use this one
1486 const bool use_aps{txr_grouped.has_value() ? (txr_grouped->fee <= txr_ungrouped.fee + wallet.m_max_aps_fee) : false};
1487 TRACEPOINT(coin_selection, aps_create_tx_internal,
1488 wallet.GetName().c_str(),
1489 use_aps,
1490 txr_grouped.has_value(),
1491 txr_grouped.has_value() ? txr_grouped->fee : 0,
1492 txr_grouped.has_value() && txr_grouped->change_pos.has_value() ? int32_t(*txr_grouped->change_pos) : -1);
1493 if (txr_grouped) {
1494 wallet.WalletLogPrintf("Fee non-grouped = %lld, grouped = %lld, using %s\n",
1495 txr_ungrouped.fee, txr_grouped->fee, use_aps ? "grouped" : "non-grouped");
1496 if (use_aps) return txr_grouped;
1497 }
1498 }
1499 return res;
1500}
1501
1502util::Result<CreatedTransactionResult> FundTransaction(CWallet& wallet, const CMutableTransaction& tx, const std::vector<CRecipient>& vecSend, std::optional<unsigned int> change_pos, bool lockUnspents, CCoinControl coinControl)
1503{
1504 // We want to make sure tx.vout is not used now that we are passing outputs as a vector of recipients.
1505 // This sets us up to remove tx completely in a future PR in favor of passing the inputs directly.
1506 assert(tx.vout.empty());
1507
1508 // Set the user desired locktime
1509 coinControl.m_locktime = tx.nLockTime;
1510
1511 // Set the user desired version
1512 coinControl.m_version = tx.version;
1513
1514 // Acquire the locks to prevent races to the new locked unspents between the
1515 // CreateTransaction call and LockCoin calls (when lockUnspents is true).
1516 LOCK(wallet.cs_wallet);
1517
1518 // Fetch specified UTXOs from the UTXO set to get the scriptPubKeys and values of the outputs being selected
1519 // and to match with the given solving_data. Only used for non-wallet outputs.
1520 std::map<COutPoint, Coin> coins;
1521 for (const CTxIn& txin : tx.vin) {
1522 coins[txin.prevout]; // Create empty map entry keyed by prevout.
1523 }
1524 wallet.chain().findCoins(coins);
1525
1526 for (const CTxIn& txin : tx.vin) {
1527 const auto& outPoint = txin.prevout;
1528 PreselectedInput& preset_txin = coinControl.Select(outPoint);
1529 if (!wallet.IsMine(outPoint)) {
1530 if (coins[outPoint].out.IsNull()) {
1531 return util::Error{_("Unable to find UTXO for external input")};
1532 }
1533
1534 // The input was not in the wallet, but is in the UTXO set, so select as external
1535 preset_txin.SetTxOut(coins[outPoint].out);
1536 }
1537 preset_txin.SetSequence(txin.nSequence);
1538 preset_txin.SetScriptSig(txin.scriptSig);
1539 preset_txin.SetScriptWitness(txin.scriptWitness);
1540 }
1541
1542 auto res = CreateTransaction(wallet, vecSend, change_pos, coinControl, false);
1543 if (!res) {
1544 return res;
1545 }
1546
1547 if (lockUnspents) {
1548 for (const CTxIn& txin : res->tx->vin) {
1549 wallet.LockCoin(txin.prevout, /*persist=*/false);
1550 }
1551 }
1552
1553 return res;
1554}
1555} // namespace wallet
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a scriptPubKey for the destination.
Definition: addresstype.cpp:49
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination corresponds to one with an address.
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
std::variant< CNoDestination, PubKeyDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, PayToAnchor, WitnessUnknown > CTxDestination
A txout script categorized into standard templates.
Definition: addresstype.h:143
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
ArgsManager gArgs
Definition: args.cpp:38
if(!SetupNetworking())
#define CHECK_NONFATAL(condition)
Identity function.
Definition: check.h:112
#define Assert(val)
Identity function.
Definition: check.h:116
#define STR_INTERNAL_BUG(msg)
Definition: check.h:99
#define Assume(val)
Assume is the identity function.
Definition: check.h:128
bool GetBoolArg(const std::string &strArg, bool fDefault) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Return boolean argument or default value.
Definition: args.cpp:571
Fee rate in satoshis per virtualbyte: CAmount / vB the feerate is represented internally as FeeFrac.
Definition: feerate.h:32
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:30
uint32_t n
Definition: transaction.h:33
Txid hash
Definition: transaction.h:32
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:406
A reference to a CScript: the Hash160 of its serialization.
Definition: script.h:597
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:287
const std::vector< CTxOut > vout
Definition: transaction.h:298
const std::vector< CTxIn > vin
Definition: transaction.h:297
An input of a transaction.
Definition: transaction.h:63
static constexpr uint32_t SEQUENCE_FINAL
Setting nSequence to this value for every input in a transaction disables nLockTime/IsFinalTx().
Definition: transaction.h:77
uint32_t nSequence
Definition: transaction.h:67
CScript scriptSig
Definition: transaction.h:66
CScriptWitness scriptWitness
Only serialized through CTransaction.
Definition: transaction.h:68
static constexpr uint32_t MAX_SEQUENCE_NONFINAL
This is the maximum sequence number that enables both nLockTime and OP_CHECKLOCKTIMEVERIFY (BIP 65).
Definition: transaction.h:83
COutPoint prevout
Definition: transaction.h:65
An output of a transaction.
Definition: transaction.h:141
CScript scriptPubKey
Definition: transaction.h:144
CAmount nValue
Definition: transaction.h:143
Fast randomness source.
Definition: random.h:386
A signing provider to be used to interface with multiple signing providers at once.
void AddProvider(std::unique_ptr< SigningProvider > provider)
I randrange(I range) noexcept
Generate a random integer in the range [0..range), with range > 0.
Definition: random.h:254
An interface to be implemented by keystores that support signing.
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:117
virtual bool isInitialBlockDownload()=0
Check if in IBD.
virtual std::optional< CAmount > calculateCombinedBumpFee(const std::vector< COutPoint > &outpoints, const CFeeRate &target_feerate)=0
Calculate the combined bump fee for an input set per the same strategy.
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:52
bool empty() const
Definition: prevector.h:251
160-bit opaque blob.
Definition: uint256.h:184
256-bit opaque blob.
Definition: uint256.h:196
Coin Control Features.
Definition: coincontrol.h:83
bool IsSelected(const COutPoint &outpoint) const
Returns true if the given output is pre-selected.
Definition: coincontrol.cpp:20
std::optional< CTxOut > GetExternalOutput(const COutPoint &outpoint) const
Returns the external output for the given outpoint if it exists.
Definition: coincontrol.cpp:31
bool m_avoid_address_reuse
Forbids inclusion of dirty (previously used) addresses.
Definition: coincontrol.h:105
std::optional< int64_t > GetInputWeight(const COutPoint &outpoint) const
Returns the input weight.
Definition: coincontrol.cpp:72
PreselectedInput & Select(const COutPoint &outpoint)
Lock-in the given output for spending.
Definition: coincontrol.cpp:40
bool HasSelected() const
Returns true if there are pre-selected inputs.
Definition: coincontrol.cpp:15
bool IsExternalSelected(const COutPoint &outpoint) const
Returns true if the given output is selected as an external input.
Definition: coincontrol.cpp:25
int m_min_depth
Minimum chain depth value for coin availability.
Definition: coincontrol.h:109
bool m_allow_other_inputs
If true, the selection process can add extra unselected inputs from the wallet while requires all sel...
Definition: coincontrol.h:93
int m_max_depth
Maximum chain depth value for coin availability.
Definition: coincontrol.h:111
bool m_include_unsafe_inputs
If false, only safe inputs will be used.
Definition: coincontrol.h:90
bool m_avoid_partial_spends
Avoid partial use of funds sent to a given address.
Definition: coincontrol.h:103
uint32_t m_version
Version.
Definition: coincontrol.h:115
FlatSigningProvider m_external_provider
SigningProvider that has pubkeys and scripts to do spend size estimation for external inputs.
Definition: coincontrol.h:113
CTxDestination destChange
Custom change destination, if not set an address is generated.
Definition: coincontrol.h:86
std::vector< COutPoint > ListSelected() const
List the selected inputs.
Definition: coincontrol.cpp:57
std::optional< uint32_t > m_locktime
Locktime.
Definition: coincontrol.h:117
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:318
A transaction with a bunch of additional info that only the owner cares about.
Definition: transaction.h:194
std::optional< Txid > m_replaces_txid
Definition: transaction.h:204
std::optional< Txid > m_replaced_by_txid
Definition: transaction.h:205
bool InMempool() const
Definition: transaction.cpp:19
std::optional< Txid > truc_child_in_mempool
Definition: transaction.h:272
int64_t GetTxTime() const
Definition: transaction.cpp:24
CTransactionRef GetTx() const
Definition: transaction.h:351
void SetScriptSig(const CScript &script)
Set the scriptSig for this input.
void SetSequence(uint32_t sequence)
Set the sequence for this input.
void SetScriptWitness(const CScriptWitness &script_wit)
Set the scriptWitness for this input.
void SetTxOut(const CTxOut &txout)
Set the previous output for this input.
Definition: coincontrol.cpp:90
A wrapper to reserve an address from a wallet.
Definition: wallet.h:206
util::Result< CTxDestination > GetReservedDestination(bool internal)
Reserve an address.
Definition: wallet.cpp:2490
static int32_t GetTransactionWeight(const CTransaction &tx)
Definition: validation.h:139
constexpr int WITNESS_SCALE_FACTOR
Definition: consensus.h:21
@ SAT_VB
Use sat/vB fee rate unit.
uint64_t sequence
is a home for simple string functions returning descriptive messages that are used in RPC and GUI int...
std::string FormatMoney(const CAmount n)
Money parsing/formatting utilities.
Definition: moneystr.cpp:19
static int sign(const secp256k1_context *ctx, struct signer_secrets *signer_secrets, struct signer *signer, const secp256k1_musig_keyagg_cache *cache, const unsigned char *msg32, unsigned char *sig64)
Definition: musig.c:106
bilingual_str TransactionErrorString(const TransactionError err)
Definition: messages.cpp:118
std::string StringForFeeReason(FeeReason reason)
Definition: messages.cpp:27
TransactionError
Definition: types.h:19
bilingual_str ErrorString(const Result< T > &result)
Definition: result.h:93
constexpr size_t DUMMY_NESTED_P2WPKH_INPUT_SIZE
Pre-calculated constants for input size estimation in virtual size
Definition: wallet.h:151
const CTxOut & FindNonChangeParentOutput(const CWallet &wallet, const COutPoint &outpoint)
Find non-change parent output.
Definition: spend.cpp:524
bool OutputIsChange(const CWallet &wallet, const CTxOut &txout)
Definition: receive.cpp:74
constexpr bool DEFAULT_WALLET_REJECT_LONG_CHAINS
Default for -walletrejectlongchains.
Definition: wallet.h:131
util::Result< SelectionResult > AutomaticCoinSelection(const CWallet &wallet, CoinsResult &available_coins, const CAmount &value_to_select, const CoinSelectionParams &coin_selection_params)
Select a set of coins such that nTargetValue is met; never select unconfirmed coins if they are not o...
Definition: spend.cpp:870
util::Result< CreatedTransactionResult > FundTransaction(CWallet &wallet, const CMutableTransaction &tx, const std::vector< CRecipient > &vecSend, std::optional< unsigned int > change_pos, bool lockUnspents, CCoinControl coinControl)
Insert additional inputs into the transaction by calling CreateTransaction();.
Definition: spend.cpp:1502
util::Result< CreatedTransactionResult > CreateTransaction(CWallet &wallet, const std::vector< CRecipient > &vecSend, std::optional< unsigned 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:1448
bool CachedTxIsFromMe(const CWallet &wallet, const CWalletTx &wtx)
Definition: receive.cpp:196
util::Result< CoinsResult > FetchSelectedInputs(const CWallet &wallet, const CCoinControl &coin_control, const CoinSelectionParams &coin_selection_params)
Fetch and validate coin control selected inputs.
Definition: spend.cpp:265
bool CachedTxIsTrusted(const CWallet &wallet, const CWalletTx &wtx, std::set< Txid > &trusted_parents)
Definition: receive.cpp:205
MinimumFeeRateResult GetMinimumFeeRate(const CWallet &wallet, const CCoinControl &coin_control)
Estimate the minimum fee rate considering user set parameters and the required fee.
Definition: fees.cpp:32
util::Result< SelectionResult > SelectCoinsBnB(std::vector< OutputGroup > &utxo_pool, const CAmount &selection_target, const CAmount &cost_of_change, int max_selection_weight)
static std::unique_ptr< Descriptor > GetDescriptor(const CWallet *wallet, const CCoinControl *coin_control, const CScript script_pubkey)
Infer a descriptor for the given output script.
Definition: spend.cpp:112
static bool UseMaxSig(const std::optional< CTxIn > &txin, const CCoinControl *coin_control)
Whether to assume ECDSA signatures' will be high-r.
Definition: spend.cpp:55
static std::optional< int64_t > GetSignedTxinWeight(const CWallet *wallet, const CCoinControl *coin_control, const CTxIn &txin, const CTxOut &txo, const bool tx_is_segwit, const bool can_grind_r)
Infer the maximum size of this input after it will be signed.
Definition: spend.cpp:126
util::Result< SelectionResult > CoinGrinder(std::vector< OutputGroup > &utxo_pool, const CAmount &selection_target, CAmount change_target, int max_selection_weight)
bool IsDust(const CRecipient &recipient, const CFeeRate &dustRelayFee)
Definition: spend.cpp:1056
static OutputType GetOutputType(TxoutType type, bool is_from_p2sh)
Definition: spend.cpp:246
static bool IsSegwit(const Descriptor &desc)
Whether the descriptor represents, directly or not, a witness program.
Definition: spend.cpp:49
std::set< std::shared_ptr< COutput >, OutputPtrComparator > OutputSet
util::Result< SelectionResult > AttemptSelection(interfaces::Chain &chain, const CAmount &nTargetValue, OutputGroupTypeMap &groups, const CoinSelectionParams &coin_selection_params, bool allow_mixed_output_types)
Attempt to find a valid input set that preserves privacy by not mixing OutputTypes.
Definition: spend.cpp:699
util::Result< SelectionResult > ChooseSelectionResult(interfaces::Chain &chain, const CAmount &nTargetValue, Groups &groups, const CoinSelectionParams &coin_selection_params)
Attempt to find a valid input set that meets the provided eligibility filter and target.
Definition: spend.cpp:726
util::Result< SelectionResult > KnapsackSolver(std::vector< OutputGroup > &groups, const CAmount &nTargetValue, CAmount change_target, FastRandomContext &rng, int max_selection_weight)
util::Result< SelectionResult > SelectCoins(const CWallet &wallet, CoinsResult &available_coins, const CoinsResult &pre_set_inputs, const CAmount &nTargetValue, const CCoinControl &coin_control, const CoinSelectionParams &coin_selection_params)
Select all coins from coin_control, and if coin_control 'm_allow_other_inputs=true',...
Definition: spend.cpp:812
constexpr int DEFAULT_MAX_DEPTH
Definition: coincontrol.h:22
CAmount GenerateChangeTarget(const CAmount payment_value, const CAmount change_fee, FastRandomContext &rng)
Choose a random change target for each transaction to make it harder to fingerprint the Core wallet b...
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:544
int CalculateMaximumSignedInputSize(const CTxOut &txout, const CWallet *wallet, const CCoinControl *coin_control)
Get the marginal bytes if spending the specified output from this transaction.
Definition: spend.cpp:105
std::string GetAlgorithmName(const SelectionAlgorithm algo)
void DiscourageFeeSniping(CMutableTransaction &tx, FastRandomContext &rng_fast, interfaces::Chain &chain, const uint256 &block_hash, int block_height)
Set a height-based locktime for new transactions (uses the height of the current chain tip unless we ...
Definition: spend.cpp:995
TxSize CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, const CCoinControl *coin_control)
Definition: spend.cpp:173
static bool HasErrorMsg(const util::Result< SelectionResult > &res)
Definition: spend.cpp:697
CFeeRate GetDiscardRate(const CWallet &wallet)
Return the maximum feerate for discarding change.
Definition: fees.cpp:90
std::map< CoinEligibilityFilter, OutputGroupTypeMap > FilteredOutputGroups
TxSize CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, const std::vector< CTxOut > &txouts, const CCoinControl *coin_control)
Calculate the size of the transaction using CoinControl to determine whether to expect signature grin...
Definition: spend.cpp:144
static util::Result< CreatedTransactionResult > CreateTransactionInternal(CWallet &wallet, const std::vector< CRecipient > &vecSend, std::optional< unsigned int > change_pos, const CCoinControl &coin_control, bool sign) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
Definition: spend.cpp:1061
@ WALLET_FLAG_AVOID_REUSE
Definition: walletutil.h:21
static bool IsCurrentForAntiFeeSniping(interfaces::Chain &chain, const uint256 &block_hash)
Definition: spend.cpp:981
constexpr int DEFAULT_MIN_DEPTH
Definition: coincontrol.h:21
FilteredOutputGroups GroupOutputs(const CWallet &wallet, const CoinsResult &coins, const CoinSelectionParams &params, const std::vector< SelectionFilter > &filters)
Group coins by the provided filters.
Definition: spend.cpp:687
static constexpr size_t OUTPUT_GROUP_MAX_ENTRIES
Definition: spend.cpp:46
int CalculateMaximumSignedInputSize(const CTxOut &txout, const COutPoint outpoint, const SigningProvider *provider, bool can_grind_r, const CCoinControl *coin_control)
Definition: spend.cpp:92
static std::optional< int64_t > MaxInputWeight(const Descriptor &desc, const std::optional< CTxIn > &txin, const CCoinControl *coin_control, const bool tx_is_segwit, const bool can_grind_r)
Get the size of an input (in witness units) once it's signed.
Definition: spend.cpp:69
util::Result< SelectionResult > SelectCoinsSRD(const std::vector< OutputGroup > &utxo_pool, CAmount target_value, CAmount change_fee, FastRandomContext &rng, int max_selection_weight)
Select coins by Single Random Draw (SRD).
uint64_t GetSerializeSizeForRecipient(const CRecipient &recipient)
Definition: spend.cpp:1051
is a home for public enum and struct type definitions that are used internally by node code,...
OutputType
Definition: outputtype.h:18
CAmount GetDustThreshold(const CTxOut &txout, const CFeeRate &dustRelayFeeIn)
Definition: policy.cpp:27
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:395
constexpr unsigned int MIN_STANDARD_TX_NONWITNESS_SIZE
The minimum non-witness size for transactions we're willing to relay/mine: one larger than 64
Definition: policy.h:40
constexpr int32_t MAX_STANDARD_TX_WEIGHT
The maximum weight for transactions we're willing to relay/mine.
Definition: policy.h:38
CAmount CalculateOutputValue(const TxType &tx)
Definition: transaction.h:272
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:418
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:417
std::unique_ptr< Descriptor > InferDescriptor(const CScript &script, const SigningProvider &provider)
Find a descriptor for the specified script, using information from provider where possible.
constexpr unsigned int LOCKTIME_THRESHOLD
Definition: script.h:48
constexpr unsigned int GetSizeOfCompactSize(uint64_t nSize)
Compact Size size < 253 – 1 byte size <= USHRT_MAX – 3 bytes (253 + 2 bytes) size <= UINT_MAX – 5 byt...
Definition: serialize.h:291
uint64_t GetSerializeSize(const T &t)
Definition: serialize.h:1157
TxoutType Solver(const CScript &scriptPubKey, std::vector< std::vector< unsigned char > > &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
Definition: solver.cpp:141
TxoutType
Definition: solver.h:22
@ WITNESS_V1_TAPROOT
@ WITNESS_V0_SCRIPTHASH
@ WITNESS_V0_KEYHASH
TRACEPOINT_SEMAPHORE(coin_selection, selected_coins)
A mutable version of CTransaction.
Definition: transaction.h:372
std::vector< CTxOut > vout
Definition: transaction.h:374
std::vector< CTxIn > vin
Definition: transaction.h:373
Interface for parsed descriptor objects.
Definition: descriptor.h:109
virtual std::optional< int64_t > MaxSatisfactionElems() const =0
Get the maximum size number of stack elements for satisfying this descriptor.
virtual std::optional< int64_t > MaxSatisfactionWeight(bool use_max_sig) const =0
Get the maximum size of a satisfaction for this descriptor, in weight units.
virtual std::optional< OutputType > GetOutputType() const =0
Bilingual messages:
Definition: translation.h:24
bool empty() const
Definition: translation.h:35
A UTXO under consideration for use in funding a new transaction.
Definition: coinselection.h:28
COutPoint outpoint
The outpoint identifying this UTXO.
Definition: coinselection.h:38
void ApplyBumpFee(CAmount bump_fee)
CAmount nAmount
Definition: wallet.h:309
CTxDestination dest
Definition: wallet.h:308
Parameters for filtering which OutputGroups we may use in coin selection.
uint64_t max_count
Definition: spend.h:82
bool check_version_trucness
Definition: spend.h:89
bool include_immature_coinbase
Definition: spend.h:84
CAmount min_sum_amount
Definition: spend.h:80
Parameters for one iteration of Coin Selection.
uint32_t m_version
The version of the transaction we are trying to create.
FastRandomContext & rng_fast
Randomness to use in the context of coin selection.
CAmount m_min_change_target
Mininmum change to target in Knapsack solver and CoinGrinder: select coins to cover the payment and a...
bool m_subtract_fee_outputs
Indicate that we are subtracting the fee from outputs.
bool m_include_unsafe_inputs
When true, allow unsafe coins to be selected during Coin Selection.
CFeeRate m_effective_feerate
The targeted feerate of the transaction being built.
CAmount min_viable_change
Minimum amount for creating a change output.
CAmount m_cost_of_change
Cost of creating the change output + cost of spending the change output in the future.
CAmount m_change_fee
Cost of creating the change output.
int change_output_size
Size of a change output in bytes, determined by the output type.
int tx_noinputs_size
Size of the transaction before coin selection, consisting of the header and recipient output(s),...
std::optional< int > m_max_tx_weight
The maximum weight for this transaction.
bool m_avoid_partial_spends
When true, always spend all (up to OUTPUT_GROUP_MAX_ENTRIES) or none of the outputs associated with t...
COutputs available for spending, stored by OutputType.
Definition: spend.h:45
std::optional< CAmount > GetAppropriateTotal(bool subtract_fee_outputs) const
Definition: spend.h:63
void Add(OutputType type, const COutput &out)
Definition: spend.cpp:236
std::vector< COutput > All() const
Concatenate and return all COutputs as one vector.
Definition: spend.cpp:203
std::optional< CAmount > GetEffectiveTotalAmount() const
Definition: spend.h:61
CAmount GetTotalAmount() const
Definition: spend.h:60
size_t Size() const
The following methods are provided so that CoinsResult can mimic a vector, i.e., methods can work wit...
Definition: spend.cpp:194
std::map< OutputType, std::vector< COutput > > coins
Definition: spend.h:46
void Shuffle(FastRandomContext &rng_fast)
Definition: spend.cpp:229
std::vector< OutputGroup > positive_group
std::vector< OutputGroup > mixed_group
A group of UTXOs paid to the same output script.
Stores several 'Groups' whose were mapped by output type.
std::map< OutputType, Groups > groups_by_type
void AddInputs(const OutputSet &inputs, bool subtract_fee_outputs)
CAmount GetChange(CAmount min_viable_change, CAmount change_fee) const
Get the amount for the change output after paying needed fees.
void RecalculateWaste(CAmount min_viable_change, CAmount change_cost, CAmount change_fee)
Calculates and stores the waste for this result given the cost of change and the opportunity cost of ...
CAmount GetSelectedValue() const
Get the sum of the input values.
CAmount GetTarget() const
SelectionAlgorithm GetAlgo() const
std::vector< std::shared_ptr< COutput > > GetShuffledInputVector() const
Get the vector of COutputs that will be used to fill in a CTransaction's vin.
CAmount GetWaste() const
#define LOCK(cs)
Definition: sync.h:268
FuzzedDataProvider provider
Definition: dbwrapper.cpp:366
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172
#define TRACEPOINT(context,...)
Definition: trace.h:56
consteval auto _(util::TranslatedLiteral str)
Definition: translation.h:79
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:82
constexpr decltype(CTransaction::version) TRUC_VERSION
Definition: truc_policy.h:20
constexpr int64_t TRUC_CHILD_MAX_WEIGHT
Definition: truc_policy.h:34
constexpr uint32_t MAX_BIP125_RBF_SEQUENCE
Definition: rbf.h:12
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
Definition: time.cpp:88
AssertLockHeld(pool.cs)
assert(!tx.IsCoinBase())
static void AvailableCoins(benchmark::Bench &bench, const std::vector< OutputType > &output_type)