Branch data Line data Source code
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>
10 : : #include <consensus/validation.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>
16 : : #include <primitives/transaction.h>
17 : : #include <primitives/transaction_identifier.h>
18 : : #include <script/script.h>
19 : : #include <script/signingprovider.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 : : #include <vector>
35 : :
36 : : using common::StringForFeeReason;
37 : : using common::TransactionErrorString;
38 : : using interfaces::FoundBlock;
39 : : using node::TransactionError;
40 : :
41 : : TRACEPOINT_SEMAPHORE(coin_selection, selected_coins);
42 : : TRACEPOINT_SEMAPHORE(coin_selection, normal_create_tx_internal);
43 : : TRACEPOINT_SEMAPHORE(coin_selection, attempting_aps_create_tx);
44 : : TRACEPOINT_SEMAPHORE(coin_selection, aps_create_tx_internal);
45 : :
46 : : namespace wallet {
47 : : static constexpr size_t OUTPUT_GROUP_MAX_ENTRIES{100};
48 : :
49 : : /** Whether the descriptor represents, directly or not, a witness program. */
50 : 197191 : static bool IsSegwit(const Descriptor& desc) {
51 [ + + ]: 197191 : if (const auto typ = desc.GetOutputType()) return *typ != OutputType::LEGACY;
52 : : return false;
53 : : }
54 : :
55 : : /** Whether to assume ECDSA signatures' will be high-r. */
56 : 181820 : static bool UseMaxSig(const std::optional<CTxIn>& txin, const CCoinControl* coin_control) {
57 : : // Use max sig if watch only inputs were used or if this particular input is an external input
58 : : // to ensure a sufficient fee is attained for the requested feerate.
59 [ + + + - : 181820 : return coin_control && txin && coin_control->IsExternalSelected(txin->prevout);
+ + ]
60 : : }
61 : :
62 : : /** Get the size of an input (in witness units) once it's signed.
63 : : *
64 : : * @param desc The output script descriptor of the coin spent by this input.
65 : : * @param txin Optionally the txin to estimate the size of. Used to determine the size of ECDSA signatures.
66 : : * @param coin_control Information about the context to determine the size of ECDSA signatures.
67 : : * @param tx_is_segwit Whether the transaction has at least a single input spending a segwit coin.
68 : : * @param can_grind_r Whether the signer will be able to grind the R of the signature.
69 : : */
70 : 182828 : static std::optional<int64_t> MaxInputWeight(const Descriptor& desc, const std::optional<CTxIn>& txin,
71 : : const CCoinControl* coin_control, const bool tx_is_segwit,
72 : : const bool can_grind_r) {
73 [ + + + + : 182864 : if (const auto sat_weight = desc.MaxSatisfactionWeight(!can_grind_r || UseMaxSig(txin, coin_control))) {
+ + ]
74 [ + - ]: 182818 : if (const auto elems_count = desc.MaxSatisfactionElems()) {
75 : 182818 : const bool is_segwit = IsSegwit(desc);
76 : : // Account for the size of the scriptsig and the number of elements on the witness stack. Note
77 : : // that if any input in the transaction is spending a witness program, we need to specify the
78 : : // witness stack size for every input regardless of whether it is segwit itself.
79 : : // NOTE: this also works in case of mixed scriptsig-and-witness such as in p2sh-wrapped segwit v0
80 : : // outputs. In this case the size of the scriptsig length will always be one (since the redeemScript
81 : : // is always a push of the witness program in this case, which is smaller than 253 bytes).
82 [ + + + + ]: 182818 : const int64_t scriptsig_len = is_segwit ? 1 : GetSizeOfCompactSize(*sat_weight / WITNESS_SCALE_FACTOR);
83 [ - + + + ]: 182818 : const int64_t witstack_len = is_segwit ? GetSizeOfCompactSize(*elems_count) : (tx_is_segwit ? 1 : 0);
84 : : // previous txid + previous vout + sequence + scriptsig len + witstack size + scriptsig or witness
85 : : // NOTE: sat_weight already accounts for the witness discount accordingly.
86 : 182818 : return (32 + 4 + 4 + scriptsig_len) * WITNESS_SCALE_FACTOR + witstack_len + *sat_weight;
87 : : }
88 : : }
89 : :
90 : 10 : return {};
91 : : }
92 : :
93 : 274591 : int CalculateMaximumSignedInputSize(const CTxOut& txout, const COutPoint outpoint, const SigningProvider* provider, bool can_grind_r, const CCoinControl* coin_control)
94 : : {
95 [ + + ]: 274591 : if (!provider) return -1;
96 : :
97 [ + - ]: 164547 : if (const auto desc = InferDescriptor(txout.scriptPubKey, *provider)) {
98 [ + - + - : 658188 : if (const auto weight = MaxInputWeight(*desc, CTxIn{outpoint}, coin_control, true, can_grind_r)) {
+ + ]
99 [ + - ]: 164540 : return static_cast<int>(GetVirtualTransactionSize(*weight, 0, 0));
100 : : }
101 : 164540 : }
102 : :
103 : 7 : return -1;
104 : : }
105 : :
106 : 122783 : int CalculateMaximumSignedInputSize(const CTxOut& txout, const CWallet* wallet, const CCoinControl* coin_control)
107 : : {
108 : 122783 : const std::unique_ptr<SigningProvider> provider = wallet->GetSolvingProvider(txout.scriptPubKey);
109 [ + - + - ]: 245566 : return CalculateMaximumSignedInputSize(txout, COutPoint(), provider.get(), wallet->CanGrindR(), coin_control);
110 : 122783 : }
111 : :
112 : : /** Infer a descriptor for the given output script. */
113 : 32654 : static std::unique_ptr<Descriptor> GetDescriptor(const CWallet* wallet, const CCoinControl* coin_control,
114 : : const CScript script_pubkey)
115 : : {
116 : 32654 : MultiSigningProvider providers;
117 [ + - + + ]: 65258 : for (const auto spkman: wallet->GetScriptPubKeyMans(script_pubkey)) {
118 [ + - + - ]: 32604 : providers.AddProvider(spkman->GetSolvingProvider(script_pubkey));
119 : 0 : }
120 [ + + ]: 32654 : if (coin_control) {
121 [ + - + - : 29559 : providers.AddProvider(std::make_unique<FlatSigningProvider>(coin_control->m_external_provider));
- + ]
122 : : }
123 [ + - ]: 32654 : return InferDescriptor(script_pubkey, providers);
124 : 32654 : }
125 : :
126 : : /** Infer the maximum size of this input after it will be signed. */
127 : 19784 : static std::optional<int64_t> GetSignedTxinWeight(const CWallet* wallet, const CCoinControl* coin_control,
128 : : const CTxIn& txin, const CTxOut& txo, const bool tx_is_segwit,
129 : : const bool can_grind_r)
130 : : {
131 : : // If weight was provided, use that.
132 : 19784 : std::optional<int64_t> weight;
133 [ + + + + ]: 19784 : if (coin_control && (weight = coin_control->GetInputWeight(txin.prevout))) {
134 : 1503 : return weight.value();
135 : : }
136 : :
137 : : // Otherwise, use the maximum satisfaction size provided by the descriptor.
138 [ + - ]: 18281 : std::unique_ptr<Descriptor> desc{GetDescriptor(wallet, coin_control, txo.scriptPubKey)};
139 [ + - + - : 36562 : if (desc) return MaxInputWeight(*desc, {txin}, coin_control, tx_is_segwit, can_grind_r);
+ - ]
140 : :
141 : 0 : return {};
142 : 18281 : }
143 : :
144 : : // txouts needs to be in the order of tx.vin
145 : 4004 : TxSize CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, const std::vector<CTxOut>& txouts, const CCoinControl* coin_control)
146 : : {
147 : : // version + nLockTime + input count + output count
148 [ - + + + : 4008 : int64_t weight = (4 + 4 + GetSizeOfCompactSize(tx.vin.size()) + GetSizeOfCompactSize(tx.vout.size())) * WITNESS_SCALE_FACTOR;
- + + + ]
149 : : // Whether any input spends a witness program. Necessary to run before the next loop over the
150 : : // inputs in order to accurately compute the compactSize length for the witness data per input.
151 : 4004 : bool is_segwit = std::any_of(txouts.begin(), txouts.end(), [&](const CTxOut& txo) {
152 [ + - ]: 14373 : std::unique_ptr<Descriptor> desc{GetDescriptor(wallet, coin_control, txo.scriptPubKey)};
153 [ + - + - ]: 14373 : if (desc) return IsSegwit(*desc);
154 : : return false;
155 : 14373 : });
156 : : // Segwit marker and flag
157 [ + + ]: 4004 : if (is_segwit) weight += 2;
158 : :
159 : : // Add the size of the transaction outputs.
160 [ + + ]: 48181 : for (const auto& txo : tx.vout) weight += GetSerializeSize(txo) * WITNESS_SCALE_FACTOR;
161 : :
162 : : // Add the size of the transaction inputs as if they were signed.
163 [ - + + + ]: 23785 : for (uint32_t i = 0; i < txouts.size(); i++) {
164 : 19784 : const auto txin_weight = GetSignedTxinWeight(wallet, coin_control, tx.vin[i], txouts[i], is_segwit, wallet->CanGrindR());
165 [ + + ]: 19784 : if (!txin_weight) return TxSize{-1, -1};
166 [ - + ]: 19781 : assert(*txin_weight > -1);
167 : 19781 : weight += *txin_weight;
168 : : }
169 : :
170 : : // It's ok to use 0 as the number of sigops since we never create any pathological transaction.
171 : 4001 : return TxSize{GetVirtualTransactionSize(weight, 0, 0), weight};
172 : : }
173 : :
174 : 4004 : TxSize CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, const CCoinControl* coin_control)
175 : : {
176 : 4004 : std::vector<CTxOut> txouts;
177 : : // Look up the inputs. The inputs are either in the wallet, or in coin_control.
178 [ + + ]: 23788 : for (const CTxIn& input : tx.vin) {
179 : 19784 : const auto mi = wallet->mapWallet.find(input.prevout.hash);
180 : : // Can not estimate size without knowing the input details
181 [ + + ]: 19784 : if (mi != wallet->mapWallet.end()) {
182 [ + - - + : 19748 : assert(input.prevout.n < mi->second.GetTx()->vout.size());
- + ]
183 [ + - + - : 39496 : txouts.emplace_back(mi->second.GetTx()->vout.at(input.prevout.n));
+ - ]
184 [ + - ]: 36 : } else if (coin_control) {
185 [ + - ]: 72 : const auto& txout{coin_control->GetExternalOutput(input.prevout)};
186 [ - + ]: 36 : if (!txout) return TxSize{-1, -1};
187 [ + - ]: 36 : txouts.emplace_back(*txout);
188 : : } else {
189 : 0 : return TxSize{-1, -1};
190 : : }
191 : : }
192 [ + - ]: 4004 : return CalculateMaximumSignedTxSize(tx, wallet, txouts, coin_control);
193 : 4004 : }
194 : :
195 : 8418 : size_t CoinsResult::Size() const
196 : : {
197 : 8418 : size_t size{0};
198 [ + + ]: 14405 : for (const auto& it : coins) {
199 [ - + ]: 5987 : size += it.second.size();
200 : : }
201 : 8418 : return size;
202 : : }
203 : :
204 : 6765 : std::vector<COutput> CoinsResult::All() const
205 : : {
206 : 6765 : std::vector<COutput> all;
207 [ + - + - ]: 6765 : all.reserve(Size());
208 [ + + ]: 10266 : for (const auto& it : coins) {
209 [ + - ]: 3501 : all.insert(all.end(), it.second.begin(), it.second.end());
210 : : }
211 : 6765 : return all;
212 : 0 : }
213 : :
214 : 4 : void CoinsResult::Erase(const std::unordered_set<COutPoint, SaltedOutpointHasher>& coins_to_remove)
215 : : {
216 [ + + ]: 8 : for (auto& [type, vec] : coins) {
217 : 4 : std::erase_if(vec, [&](const COutput& coin) {
218 : : // remove it if it's on the set
219 [ + + ]: 17 : if (!coins_to_remove.contains(coin.outpoint)) return false;
220 : :
221 : : // update cached amounts
222 : 5 : total_amount -= coin.txout.nValue;
223 [ + - + - ]: 5 : if (coin.HasEffectiveValue() && total_effective_amount.has_value()) total_effective_amount = *total_effective_amount - coin.GetEffectiveValue();
224 : : return true;
225 : : });
226 : : }
227 : 4 : }
228 : :
229 : 25 : void CoinsResult::Shuffle(FastRandomContext& rng_fast)
230 : : {
231 [ + + ]: 70 : for (auto& it : coins) {
232 : 45 : std::shuffle(it.second.begin(), it.second.end(), rng_fast);
233 : : }
234 : 25 : }
235 : :
236 : 273803 : void CoinsResult::Add(OutputType type, const COutput& out)
237 : : {
238 : 273803 : coins[type].emplace_back(out);
239 : 273803 : total_amount += out.txout.nValue;
240 [ + + ]: 273803 : if (out.HasEffectiveValue()) {
241 [ + + ]: 531498 : total_effective_amount = total_effective_amount.has_value() ?
242 : 265749 : *total_effective_amount + out.GetEffectiveValue() : out.GetEffectiveValue();
243 : : }
244 : 273803 : }
245 : :
246 : 151787 : static OutputType GetOutputType(TxoutType type, bool is_from_p2sh)
247 : : {
248 [ + + + + ]: 151787 : switch (type) {
249 : : case TxoutType::WITNESS_V1_TAPROOT:
250 : : return OutputType::BECH32M;
251 : 108645 : case TxoutType::WITNESS_V0_KEYHASH:
252 : 108645 : case TxoutType::WITNESS_V0_SCRIPTHASH:
253 [ + + ]: 108645 : if (is_from_p2sh) return OutputType::P2SH_SEGWIT;
254 : 107604 : else return OutputType::BECH32;
255 : 40523 : case TxoutType::SCRIPTHASH:
256 : 40523 : case TxoutType::PUBKEYHASH:
257 : 40523 : return OutputType::LEGACY;
258 : 37 : default:
259 : 37 : 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.
265 : 583 : util::Result<CoinsResult> FetchSelectedInputs(const CWallet& wallet, const CCoinControl& coin_control,
266 : : const CoinSelectionParams& coin_selection_params)
267 : : {
268 [ + - ]: 583 : CoinsResult result;
269 [ + - ]: 583 : const bool can_grind_r = wallet.CanGrindR();
270 [ + - + - ]: 583 : std::map<COutPoint, CAmount> map_of_bump_fees = wallet.chain().calculateIndividualBumpFees(coin_control.ListSelected(), coin_selection_params.m_effective_feerate);
271 [ + - + + ]: 6356 : for (const COutPoint& outpoint : coin_control.ListSelected()) {
272 [ + - + + ]: 5779 : int64_t input_bytes = coin_control.GetInputWeight(outpoint).value_or(-1);
273 [ + - ]: 2503 : if (input_bytes != -1) {
274 [ + - ]: 2503 : input_bytes = GetVirtualTransactionSize(input_bytes, 0, 0);
275 : : }
276 : 5779 : CTxOut txout;
277 [ + - + + ]: 5779 : if (auto txo = wallet.GetTXO(outpoint)) {
278 : 5731 : txout = txo->GetTxOut();
279 [ + + ]: 5731 : if (input_bytes == -1) {
280 [ + - ]: 3257 : input_bytes = CalculateMaximumSignedInputSize(txout, &wallet, &coin_control);
281 : : }
282 [ + - ]: 5731 : const CWalletTx& parent_tx = txo->GetWalletTx();
283 [ + - + + ]: 5731 : if (wallet.GetTxDepthInMainChain(parent_tx) == 0) {
284 [ + - + + : 184 : if (parent_tx.GetTx()->version == TRUC_VERSION && coin_control.m_version != TRUC_VERSION) {
- + + + ]
285 [ + - ]: 6 : return util::Error{strprintf(_("Can't spend unconfirmed version 3 pre-selected input with a version %d tx"), coin_control.m_version)};
286 [ + + + - : 91 : } else if (coin_control.m_version == TRUC_VERSION && parent_tx.GetTx()->version != TRUC_VERSION) {
+ - + + ]
287 [ + - + - : 4 : 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 [ + - ]: 48 : const auto out{coin_control.GetExternalOutput(outpoint)};
293 [ - + ]: 48 : if (!out) {
294 [ # # # # ]: 0 : return util::Error{strprintf(_("Not found pre-selected input %s"), outpoint.ToString())};
295 : : }
296 : :
297 : 48 : txout = *out;
298 : 48 : }
299 : :
300 [ + + ]: 5776 : if (input_bytes == -1) {
301 [ + - ]: 19 : input_bytes = CalculateMaximumSignedInputSize(txout, outpoint, &coin_control.m_external_provider, can_grind_r, &coin_control);
302 : : }
303 : :
304 [ + + ]: 19 : if (input_bytes == -1) {
305 [ + - + - ]: 9 : 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 [ + - ]: 5773 : COutput output(outpoint, txout, /*depth=*/0, input_bytes, /*solvable=*/true, /*safe=*/true, /*time=*/0, /*from_me=*/false, coin_selection_params.m_effective_feerate);
310 [ + - ]: 5773 : output.ApplyBumpFee(map_of_bump_fees.at(output.outpoint));
311 [ + - ]: 5773 : result.Add(OutputType::UNKNOWN, output);
312 : 5779 : }
313 : 577 : return result;
314 : 583 : }
315 : :
316 : 4277 : CoinsResult AvailableCoins(const CWallet& wallet,
317 : : const CCoinControl* coinControl,
318 : : std::optional<CFeeRate> feerate,
319 : : const CoinFilterParams& params)
320 : : {
321 : 4277 : AssertLockHeld(wallet.cs_wallet);
322 : :
323 [ + - ]: 4277 : CoinsResult result;
324 : : // track unconfirmed truc outputs separately if we are tracking trucness
325 : 4277 : std::vector<std::pair<OutputType, COutput>> unconfirmed_truc_coins;
326 [ + - ]: 4277 : 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 [ + - + + : 4277 : bool allow_used_addresses = !wallet.IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE) || (coinControl && !coinControl->m_avoid_address_reuse);
+ - + + ]
330 [ + + ]: 4215 : const int min_depth = {coinControl ? coinControl->m_min_depth : DEFAULT_MIN_DEPTH};
331 : 4268 : const int max_depth = {coinControl ? coinControl->m_max_depth : DEFAULT_MAX_DEPTH};
332 [ + + ]: 4268 : const bool only_safe = {coinControl ? !coinControl->m_include_unsafe_inputs : true};
333 [ + - ]: 4277 : const bool can_grind_r = wallet.CanGrindR();
334 : 4277 : std::vector<COutPoint> outpoints;
335 : :
336 [ + - ]: 4277 : 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 [ + - ]: 4277 : std::unordered_map<Txid, std::pair<bool, bool>, SaltedTxidHasher> tx_safe_cache;
339 [ + + ]: 710130 : for (const auto& [outpoint, txo] : wallet.GetTXOs()) {
340 : 705853 : const CWalletTx& wtx = txo.GetWalletTx();
341 : 705853 : const CTxOut& output = txo.GetTxOut();
342 : :
343 [ + - + + : 705853 : if (tx_safe_cache.contains(outpoint.hash) && !tx_safe_cache.at(outpoint.hash).first) {
+ + ]
344 : 1086 : continue;
345 : : }
346 : :
347 [ + - ]: 704767 : int nDepth = wallet.GetTxDepthInMainChain(wtx);
348 : :
349 : : // Perform tx level checks if we haven't already come across outputs from this tx before.
350 [ + + ]: 704767 : if (!tx_safe_cache.contains(outpoint.hash)) {
351 [ + - + - ]: 679222 : tx_safe_cache[outpoint.hash] = {false, false};
352 : :
353 [ + - + + : 679222 : if (wallet.IsTxImmatureCoinBase(wtx) && !params.include_immature_coinbase)
+ + ]
354 : 237553 : continue;
355 : :
356 [ + + ]: 441669 : if (nDepth < 0)
357 : 4884 : 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 [ + + + - : 436785 : if (nDepth == 0 && !wtx.InMempool())
+ + ]
362 : 4652 : continue;
363 : :
364 [ + - ]: 432133 : 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 [ + + + + ]: 432133 : 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 [ + + + + ]: 432133 : if (nDepth == 0 && wtx.m_replaced_by_txid) {
394 : : safeTx = false;
395 : : }
396 : :
397 [ + + + + ]: 432133 : if (nDepth == 0 && params.check_version_trucness) {
398 [ + + ]: 67263 : if (coinControl->m_version == TRUC_VERSION) {
399 [ + - + - : 54 : if (wtx.GetTx()->version != TRUC_VERSION) continue;
+ + ]
400 : : // this unconfirmed v3 transaction already has a child
401 [ + + ]: 23 : 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 : 17 : size_t ancestors, unused_cluster_count;
405 [ + - + - ]: 17 : wallet.chain().getTransactionAncestry(wtx.GetTx()->GetHash(), ancestors, unused_cluster_count);
406 [ + + ]: 17 : if (ancestors > 1) continue;
407 : : } else {
408 [ + - + - : 134472 : if (wtx.GetTx()->version == TRUC_VERSION) continue;
+ + ]
409 : : }
410 : : }
411 : :
412 [ + + + + ]: 432113 : if (only_safe && !safeTx) {
413 : 2364 : continue;
414 : : }
415 : :
416 [ + + ]: 429749 : if (nDepth < min_depth || nDepth > max_depth) {
417 : 1650 : continue;
418 : : }
419 : :
420 [ + - ]: 428099 : tx_safe_cache[outpoint.hash] = {true, safeTx};
421 : : }
422 [ + - - + ]: 453644 : const auto& [tx_ok, tx_safe] = tx_safe_cache.at(outpoint.hash);
423 [ - + ]: 453644 : if (!Assume(tx_ok)) {
424 : 0 : continue;
425 : : }
426 : :
427 [ + + - + ]: 453644 : if (output.nValue < params.min_amount || output.nValue > params.max_amount)
428 : 372 : continue;
429 : :
430 : : // Skip manually selected coins (the caller can fetch them directly)
431 [ + + + - : 453272 : if (coinControl && coinControl->HasSelected() && coinControl->IsSelected(outpoint))
+ + + - +
+ ]
432 : 4036 : continue;
433 : :
434 [ + - + + : 449236 : if (wallet.IsLockedCoin(outpoint) && params.skip_locked)
+ + ]
435 : 413 : continue;
436 : :
437 [ + - + + ]: 448823 : if (wallet.IsSpent(outpoint))
438 : 297036 : continue;
439 : :
440 [ + + + - : 151787 : if (!allow_used_addresses && wallet.IsSpentKey(output.scriptPubKey)) {
+ - ]
441 : 0 : continue;
442 : : }
443 : :
444 [ + - ]: 151787 : bool tx_from_me = CachedTxIsFromMe(wallet, wtx);
445 : :
446 [ + - ]: 151787 : std::unique_ptr<SigningProvider> provider = wallet.GetSolvingProvider(output.scriptPubKey);
447 : :
448 [ + - ]: 151787 : 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 : 151787 : bool solvable = input_bytes > -1;
452 : :
453 : : // Obtain script type
454 : 151787 : std::vector<std::vector<uint8_t>> script_solutions;
455 [ + - ]: 151787 : 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 : 151787 : bool is_from_p2sh{false};
462 [ + + ]: 151787 : if (type == TxoutType::SCRIPTHASH && solvable) {
463 : 1062 : CScript script;
464 [ - + + - : 1062 : if (!provider->GetCScript(CScriptID(uint160(script_solutions[0])), script)) continue;
- + ]
465 [ + - ]: 1062 : type = Solver(script, script_solutions);
466 : 1062 : is_from_p2sh = true;
467 : 1062 : }
468 : :
469 : 151787 : auto available_output_type = GetOutputType(type, is_from_p2sh);
470 [ + - + - ]: 151787 : auto available_output = COutput(outpoint, output, nDepth, input_bytes, solvable, tx_safe, wtx.GetTxTime(), tx_from_me, feerate);
471 [ + - + + : 303574 : if (wtx.GetTx()->version == TRUC_VERSION && nDepth == 0 && params.check_version_trucness) {
+ + + + +
+ ]
472 [ + - ]: 14 : unconfirmed_truc_coins.emplace_back(available_output_type, available_output);
473 [ + - + - : 14 : auto [it, _] = truc_txid_by_value.try_emplace(wtx.GetTx()->GetHash(), 0);
+ - ]
474 : 14 : it->second += output.nValue;
475 : : } else {
476 [ + - ]: 151773 : result.Add(available_output_type, available_output);
477 : : }
478 : :
479 [ + - ]: 151787 : outpoints.push_back(outpoint);
480 : :
481 : : // Checks the sum amount of all UTXO's.
482 [ - + ]: 151787 : if (params.min_sum_amount != MAX_MONEY) {
483 [ # # ]: 0 : if (result.GetTotalAmount() >= params.min_sum_amount) {
484 : : return result;
485 : : }
486 : : }
487 : :
488 : : // Checks the maximum number of UTXO's.
489 [ - + - - : 151787 : if (params.max_count > 0 && result.Size() >= params.max_count) {
- - ]
490 : : return result;
491 : : }
492 : 151787 : }
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 [ + + + + ]: 8094 : if (params.check_version_trucness && unconfirmed_truc_coins.size() > 0) {
499 : 12 : 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 [ - + ]: 1 : return tx1.second < tx2.second;
501 : : });
502 : :
503 : 12 : const Txid& truc_txid = highest_value_truc_tx->first;
504 [ + + + + ]: 26 : for (const auto& [type, output] : unconfirmed_truc_coins) {
505 [ + + ]: 27 : if (output.outpoint.hash == truc_txid) {
506 [ + - ]: 13 : result.Add(type, output);
507 : : }
508 : : }
509 : : }
510 : :
511 [ + + ]: 4277 : if (feerate.has_value()) {
512 [ + - ]: 3805 : std::map<COutPoint, CAmount> map_of_bump_fees = wallet.chain().calculateIndividualBumpFees(outpoints, feerate.value());
513 : :
514 [ + + ]: 9427 : for (auto& [_, outputs] : result.coins) {
515 [ + + ]: 149354 : for (auto& output : outputs) {
516 [ + - ]: 143732 : output.ApplyBumpFee(map_of_bump_fees.at(output.outpoint));
517 : : }
518 : : }
519 : 3805 : }
520 : :
521 : : return result;
522 : 4277 : }
523 : :
524 : 5 : const CTxOut& FindNonChangeParentOutput(const CWallet& wallet, const COutPoint& outpoint)
525 : : {
526 : 5 : AssertLockHeld(wallet.cs_wallet);
527 : 5 : const CWalletTx* wtx{Assert(wallet.GetWalletTx(outpoint.hash))};
528 : :
529 [ + - ]: 5 : const CTransaction* ptx = wtx->GetTx().get();
530 : 5 : int n = outpoint.n;
531 [ + - - + : 7 : while (OutputIsChange(wallet, ptx->vout[n]) && ptx->vin.size() > 0) {
+ - ]
532 : 7 : const COutPoint& prevout = ptx->vin[0].prevout;
533 : 7 : const CWalletTx* it = wallet.GetWalletTx(prevout.hash);
534 [ + - - + : 13 : if (!it || it->GetTx()->vout.size() <= prevout.n ||
+ - + - +
- + + + +
+ + - - ]
535 [ + - + - : 4 : !wallet.IsMine(it->GetTx()->vout[prevout.n])) {
- - ]
536 : : break;
537 : : }
538 [ + - ]: 2 : ptx = it->GetTx().get();
539 : 2 : n = prevout.n;
540 : : }
541 : 5 : return ptx->vout[n];
542 : : }
543 : :
544 : 3 : std::map<CTxDestination, std::vector<COutput>> ListCoins(const CWallet& wallet)
545 : : {
546 : 3 : AssertLockHeld(wallet.cs_wallet);
547 : :
548 [ + - ]: 3 : std::map<CTxDestination, std::vector<COutput>> result;
549 : :
550 [ + - ]: 3 : CCoinControl coin_control;
551 : 3 : CoinFilterParams coins_params;
552 : 3 : coins_params.skip_locked = false;
553 [ + - + - : 8 : for (const COutput& coin : AvailableCoins(wallet, &coin_control, /*feerate=*/std::nullopt, coins_params).All()) {
+ + ]
554 : 5 : CTxDestination address;
555 [ + - + - : 5 : if (!ExtractDestination(FindNonChangeParentOutput(wallet, coin.outpoint).scriptPubKey, address)) {
+ - ]
556 : : // For backwards compatibility, we convert P2PK output scripts into PKHash destinations
557 [ + - ]: 5 : if (auto pk_dest = std::get_if<PubKeyDestination>(&address)) {
558 [ + - ]: 5 : address = PKHash(pk_dest->GetPubKey());
559 : : } else {
560 : 0 : continue;
561 : : }
562 : : }
563 [ + - + - ]: 5 : result[address].emplace_back(coin);
564 : 8 : }
565 : 3 : return result;
566 : 3 : }
567 : :
568 : 6831 : FilteredOutputGroups GroupOutputs(const CWallet& wallet,
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 [ + + ]: 6831 : FilteredOutputGroups filtered_groups;
575 : :
576 [ + + ]: 6831 : if (!coin_sel_params.m_avoid_partial_spends) {
577 : : // Allowing partial spends means no grouping. Each COutput gets its own OutputGroup
578 [ + + ]: 11112 : for (const auto& [type, outputs] : coins.coins) {
579 [ + + ]: 524656 : for (const COutput& output : outputs) {
580 : : // Get mempool info
581 : 518725 : size_t ancestors, cluster_count;
582 [ + - ]: 518725 : 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 [ + - ]: 518725 : OutputGroup group(coin_sel_params);
586 [ + - + - ]: 518725 : group.Insert(std::make_shared<COutput>(output), ancestors, cluster_count);
587 : :
588 : : // Each filter maps to a different set of groups
589 : 518725 : bool accepted = false;
590 [ + + ]: 1853536 : for (const auto& sel_filter : filters) {
591 : 1334811 : const auto& filter = sel_filter.filter;
592 [ + - + + ]: 1334811 : if (!group.EligibleForSpending(filter)) continue;
593 [ + - + - ]: 1276811 : filtered_groups[filter].Push(group, type, /*insert_positive=*/true, /*insert_mixed=*/true);
594 : : accepted = true;
595 : : }
596 [ + + + - ]: 518725 : if (!accepted) ret_discarded_groups.emplace_back(group);
597 : 518725 : }
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 : 1650 : typedef std::map<std::pair<CScript, OutputType>, std::vector<OutputGroup>> ScriptPubKeyToOutgroup;
609 : 125966 : 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 [ + - ]: 124316 : std::vector<OutputGroup>& groups = groups_map[std::make_pair(output->txout.scriptPubKey,type)];
613 : :
614 [ - + + + ]: 124316 : if (groups.size() == 0) {
615 : : // No OutputGroups for this scriptPubKey yet, add one
616 : 74710 : 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 : 124316 : 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 [ - + + + ]: 124316 : 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 : 236 : groups.emplace_back(coin_sel_params);
628 : 236 : group = &groups.back();
629 : : }
630 : :
631 : 124316 : group->Insert(output, ancestors, cluster_count);
632 : 124316 : };
633 : :
634 : 1650 : ScriptPubKeyToOutgroup spk_to_groups_map;
635 : 1650 : ScriptPubKeyToOutgroup spk_to_positive_groups_map;
636 [ + + ]: 4136 : for (const auto& [type, outs] : coins.coins) {
637 [ + + ]: 64653 : for (const COutput& output : outs) {
638 : 62167 : size_t ancestors, cluster_count;
639 [ + - ]: 62167 : wallet.chain().getTransactionAncestry(output.outpoint.hash, ancestors, cluster_count);
640 : :
641 [ + - ]: 62167 : const auto& shared_output = std::make_shared<COutput>(output);
642 : : // Filter for positive only before adding the output
643 [ + + ]: 62167 : if (output.GetEffectiveValue() > 0) {
644 [ + - ]: 62149 : insert_output(shared_output, type, ancestors, cluster_count, spk_to_positive_groups_map);
645 : : }
646 : :
647 : : // 'All' groups
648 [ + - ]: 62167 : insert_output(shared_output, type, ancestors, cluster_count, spk_to_groups_map);
649 : 62167 : }
650 : : }
651 : :
652 : : // Now we go through the entire maps and pull out the OutputGroups
653 : 4950 : const auto& push_output_groups = [&](const ScriptPubKeyToOutgroup& groups_map, bool positive_only) {
654 [ + + ]: 78010 : 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 [ + + ]: 149656 : for (auto group_it = groups.rbegin(); group_it != groups.rend(); group_it++) {
657 : 74946 : const OutputGroup& group = *group_it;
658 : :
659 : : // Each filter maps to a different set of groups
660 : 74946 : bool accepted = false;
661 [ + + ]: 524743 : for (const auto& sel_filter : filters) {
662 : 449797 : const auto& filter = sel_filter.filter;
663 [ + + ]: 449797 : 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 [ + + + + : 685032 : if (group_it == groups.rbegin() && groups.size() > 1 && !filter.m_include_partial_groups) {
+ + ]
667 : 164 : continue;
668 : : }
669 : :
670 : 342947 : OutputType type = script.second;
671 : : // Either insert the group into the positive-only groups or the mixed ones.
672 : 342947 : filtered_groups[filter].Push(group, type, positive_only, /*insert_mixed=*/!positive_only);
673 : 342947 : accepted = true;
674 : : }
675 : : // The positive-only groups are a subset of the mixed ones, don't record them twice
676 [ + + ]: 74946 : if (!accepted && !positive_only) ret_discarded_groups.emplace_back(group);
677 : : }
678 : : }
679 : 4950 : };
680 : :
681 [ + - ]: 1650 : push_output_groups(spk_to_groups_map, /*positive_only=*/ false);
682 [ + - ]: 1650 : push_output_groups(spk_to_positive_groups_map, /*positive_only=*/ true);
683 : :
684 : 1650 : return filtered_groups;
685 : 1650 : }
686 : :
687 : 3426 : FilteredOutputGroups GroupOutputs(const CWallet& wallet,
688 : : const CoinsResult& coins,
689 : : const CoinSelectionParams& params,
690 : : const std::vector<SelectionFilter>& filters)
691 : : {
692 : 3426 : std::vector<OutputGroup> unused;
693 [ + - ]: 6852 : return GroupOutputs(wallet, coins, params, filters, unused);
694 : 3426 : }
695 : :
696 : : // Returns true if the result contains an error and the message is not empty
697 : 12215 : static bool HasErrorMsg(const util::Result<SelectionResult>& res) { return !util::ErrorString(res).empty(); }
698 : :
699 : 3876 : util::Result<SelectionResult> AttemptSelection(interfaces::Chain& chain, const CAmount& nTargetValue, OutputGroupTypeMap& groups,
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 : 3876 : std::vector<SelectionResult> results;
704 [ + - + + ]: 9190 : for (auto& [type, group] : groups.groups_by_type) {
705 [ + - ]: 5382 : auto result{ChooseSelectionResult(chain, nTargetValue, group, coin_selection_params)};
706 : : // If any specific error message appears here, then something particularly wrong happened.
707 [ + - + + ]: 5382 : if (HasErrorMsg(result)) return result; // So let's return the specific error.
708 : : // Append the favorable result.
709 [ + + + - ]: 5314 : if (result) results.push_back(*result);
710 : 5314 : }
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 [ - + + + : 7118 : 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 [ + + + + ]: 498 : if (allow_mixed_output_types && groups.TypesCount() > 1) {
719 [ + - ]: 82 : 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 : 832 : return util::Error();
724 : 3876 : };
725 : :
726 : 5464 : util::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 : 5464 : std::vector<SelectionResult> results;
730 : 5464 : std::vector<util::Result<SelectionResult>> errors;
731 : 11811 : 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 [ + + ]: 6347 : if (HasErrorMsg(result)) {
735 : 115 : errors.emplace_back(std::move(result));
736 : : }
737 : 11811 : };
738 : :
739 : : // Maximum allowed weight for selected coins.
740 [ + + ]: 5464 : int max_transaction_weight = coin_selection_params.m_max_tx_weight.value_or(MAX_STANDARD_TX_WEIGHT);
741 : 5464 : int tx_weight_no_input = coin_selection_params.tx_noinputs_size * WITNESS_SCALE_FACTOR;
742 : 5464 : int max_selection_weight = max_transaction_weight - tx_weight_no_input;
743 [ + + ]: 5464 : if (max_selection_weight <= 0) {
744 [ + - ]: 75 : 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 [ + + ]: 5439 : if (!coin_selection_params.m_subtract_fee_outputs) {
749 [ + - + + ]: 3941 : if (auto bnb_result{SelectCoinsBnB(groups.positive_group, nTargetValue, coin_selection_params.m_cost_of_change, max_selection_weight)}) {
750 [ + - ]: 116 : results.push_back(*bnb_result);
751 [ + - ]: 7766 : } else append_error(std::move(bnb_result));
752 : : }
753 : :
754 : : // Deduct change weight because remaining Coin Selection algorithms can create change output
755 : 5439 : int change_outputs_weight = coin_selection_params.change_output_size * WITNESS_SCALE_FACTOR;
756 : 5439 : max_selection_weight -= change_outputs_weight;
757 [ + + + - ]: 5439 : if (max_selection_weight < 0 && results.empty()) {
758 [ + - ]: 18 : 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 [ + - + + ]: 5433 : 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 [ + - ]: 4271 : results.push_back(*knapsack_result);
764 [ + - ]: 1162 : } else append_error(std::move(knapsack_result));
765 : :
766 [ + - + + ]: 5433 : 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 [ + - + + ]: 520 : if (auto cg_result{CoinGrinder(groups.positive_group, nTargetValue, coin_selection_params.m_min_change_target, max_selection_weight)}) {
768 [ + - ]: 382 : cg_result->RecalculateWaste(coin_selection_params.min_viable_change, coin_selection_params.m_cost_of_change, coin_selection_params.m_change_fee);
769 [ + - ]: 382 : results.push_back(*cg_result);
770 : : } else {
771 [ + - ]: 138 : append_error(std::move(cg_result));
772 : 520 : }
773 : : }
774 : :
775 [ + - + + ]: 5433 : if (auto srd_result{SelectCoinsSRD(groups.positive_group, nTargetValue, coin_selection_params.m_change_fee, coin_selection_params.rng_fast, max_selection_weight)}) {
776 [ + - ]: 4211 : results.push_back(*srd_result);
777 [ + - ]: 1222 : } else append_error(std::move(srd_result));
778 : :
779 [ + + ]: 5433 : 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 [ + + ]: 2287 : 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 [ + + ]: 13251 : for (auto& result : results) {
787 : 8980 : std::vector<COutPoint> outpoints;
788 [ + - + - ]: 8980 : OutputSet coins = result.GetInputSet();
789 : 8980 : CAmount summed_bump_fees = 0;
790 [ + + ]: 161216 : for (auto& coin : coins) {
791 [ + + ]: 152236 : if (coin->depth > 0) continue; // Bump fees only exist for unconfirmed inputs
792 [ + - ]: 1548 : outpoints.push_back(coin->outpoint);
793 : 1548 : summed_bump_fees += coin->ancestor_bump_fees;
794 : : }
795 [ + - ]: 8980 : std::optional<CAmount> combined_bump_fee = chain.calculateCombinedBumpFee(outpoints, coin_selection_params.m_effective_feerate);
796 [ - + ]: 8980 : if (!combined_bump_fee.has_value()) {
797 [ # # ]: 0 : return util::Error{_("Failed to calculate bump fees, because unconfirmed UTXOs depend on an enormous cluster of unconfirmed transactions.")};
798 : : }
799 [ + + ]: 8980 : 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 [ + + ]: 8980 : if (bump_fee_overestimate > 0) {
802 [ + - ]: 24 : result.SetBumpFeeDiscount(bump_fee_overestimate);
803 : : }
804 [ + - ]: 8980 : result.RecalculateWaste(coin_selection_params.min_viable_change, coin_selection_params.m_cost_of_change, coin_selection_params.m_change_fee);
805 : 8980 : }
806 : :
807 : : // Choose the result with the least waste
808 : : // If the waste is the same, choose the one which spends more inputs.
809 [ + - + - ]: 8542 : return *std::min_element(results.begin(), results.end());
810 : 5464 : }
811 : :
812 : 3920 : util::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 [ + + + + ]: 7840 : 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 [ + + + + ]: 3920 : if (!coin_control.m_allow_other_inputs && selection_target > 0) {
821 : 26 : return util::Error{_("The preselected coins total amount does not cover the transaction target. "
822 : 13 : "Please allow other inputs to be automatically selected or include more coins manually")};
823 : : }
824 : :
825 [ + - ]: 3907 : OutputSet preset_coin_set;
826 [ + - + + ]: 9669 : for (const auto& output: pre_set_inputs.All()) {
827 [ + - + - ]: 11524 : preset_coin_set.insert(std::make_shared<COutput>(output));
828 : 3907 : }
829 : :
830 : : // Return if we can cover the target only with the preset inputs
831 [ + + ]: 3907 : if (selection_target <= 0) {
832 [ + - ]: 476 : SelectionResult result(nTargetValue, SelectionAlgorithm::MANUAL);
833 [ + - ]: 476 : result.AddInputs(preset_coin_set, coin_selection_params.m_subtract_fee_outputs);
834 [ + - ]: 476 : result.RecalculateWaste(coin_selection_params.min_viable_change, coin_selection_params.m_cost_of_change, coin_selection_params.m_change_fee);
835 : 476 : return result;
836 : 476 : }
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 [ + + + + ]: 6862 : CAmount available_coins_total_amount = available_coins.GetAppropriateTotal(coin_selection_params.m_subtract_fee_outputs).value_or(0);
841 [ + + ]: 3431 : if (selection_target > available_coins_total_amount) {
842 : 54 : return util::Error(); // Insufficient funds
843 : : }
844 : :
845 : : // Start wallet Coin Selection procedure
846 [ + - ]: 3404 : auto op_selection_result = AutomaticCoinSelection(wallet, available_coins, selection_target, coin_selection_params);
847 [ + + ]: 3404 : if (!op_selection_result) return op_selection_result;
848 : :
849 : : // If needed, add preset inputs to the automatic coin selection result
850 [ + + ]: 3390 : if (!pre_set_inputs.coins.empty()) {
851 [ + + ]: 84 : auto preset_total = pre_set_inputs.GetAppropriateTotal(coin_selection_params.m_subtract_fee_outputs);
852 [ - + ]: 84 : assert(preset_total.has_value());
853 [ + - ]: 84 : SelectionResult preselected(preset_total.value(), SelectionAlgorithm::MANUAL);
854 [ + - ]: 84 : preselected.AddInputs(preset_coin_set, coin_selection_params.m_subtract_fee_outputs);
855 [ + - ]: 84 : op_selection_result->Merge(preselected);
856 : 84 : op_selection_result->RecalculateWaste(coin_selection_params.min_viable_change,
857 : 84 : coin_selection_params.m_cost_of_change,
858 [ + - ]: 84 : coin_selection_params.m_change_fee);
859 : :
860 : : // Verify we haven't exceeded the maximum allowed weight
861 [ + + ]: 84 : 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 [ + + ]: 84 : if (op_selection_result->GetWeight() > max_inputs_weight) {
863 [ + - ]: 4 : return util::Error{_("The combination of the pre-selected inputs and the wallet automatic inputs selection exceeds the transaction maximum weight. "
864 : 2 : "Please try sending a smaller amount or manually consolidating your wallet's UTXOs")};
865 : : }
866 : 84 : }
867 : 3388 : return op_selection_result;
868 : 7311 : }
869 : :
870 : 3404 : util::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 : 3404 : unsigned int limit_ancestor_count = 0;
878 : 3404 : unsigned int limit_descendant_count = 0;
879 : 3404 : wallet.chain().getPackageLimits(limit_ancestor_count, limit_descendant_count);
880 [ - + ]: 3404 : const size_t max_ancestors = (size_t)std::max<int64_t>(1, limit_ancestor_count);
881 [ - + ]: 3404 : const size_t max_cluster_count = (size_t)std::max<int64_t>(1, limit_descendant_count);
882 [ + - ]: 3404 : 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 [ + + + + ]: 3404 : if (coin_selection_params.m_avoid_partial_spends && available_coins.Size() > OUTPUT_GROUP_MAX_ENTRIES) {
888 : 25 : 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 : 3404 : {
895 : : // Place coins eligibility filters on a scope increasing order.
896 : 3404 : 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 : 3404 : };
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 [ + + ]: 3404 : if (wallet.m_spend_zero_conf_change) {
905 [ + - ]: 3402 : ordered_filters.push_back({CoinEligibilityFilter(0, 1, 2)});
906 [ + - + + : 10180 : 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 [ + - ]: 3402 : 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 [ + - ]: 3402 : 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 [ + + ]: 3402 : if (coin_selection_params.m_include_unsafe_inputs) {
915 [ + - ]: 67 : 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 [ + + ]: 3402 : if (!fRejectLongChains) {
922 [ + - ]: 60 : 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 : 3404 : std::vector<OutputGroup> discarded_groups;
930 [ + - ]: 3404 : 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 : 3404 : CAmount total_discarded = 0;
934 : 3404 : CAmount total_unconf_long_chain = 0;
935 [ + + ]: 3432 : for (const auto& group : discarded_groups) {
936 [ + - ]: 28 : total_discarded += group.GetSelectionAmount();
937 [ + + + - : 28 : if (group.m_ancestors >= max_ancestors || group.m_max_cluster_count >= max_cluster_count) total_unconf_long_chain += group.GetSelectionAmount();
+ - ]
938 : : }
939 : :
940 [ + + ]: 3404 : if (CAmount total_amount = available_coins.GetTotalAmount() - total_discarded; total_amount < value_to_select) {
941 : : // Special case, too-long-mempool cluster.
942 [ + - ]: 1 : if (total_amount + total_unconf_long_chain > value_to_select) {
943 [ + - ]: 3 : return util::Error{_("Unconfirmed UTXOs are available, but spending them creates a chain of transactions that will be rejected by the mempool")};
944 : : }
945 : 0 : 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 : 3403 : std::vector<util::Result<SelectionResult>> res_detailed_errors;
952 : 3403 : CoinSelectionParams updated_selection_params = coin_selection_params;
953 [ + + ]: 5721 : for (const auto& select_filter : ordered_filters) {
954 : 5708 : auto it = filtered_groups.find(select_filter.filter);
955 [ + + ]: 5708 : if (it == filtered_groups.end()) continue;
956 [ + + + + : 3876 : if (updated_selection_params.m_version == TRUC_VERSION && (select_filter.filter.conf_mine == 0 || select_filter.filter.conf_theirs == 0)) {
- + ]
957 [ + - ]: 16 : if (updated_selection_params.m_max_tx_weight > (TRUC_CHILD_MAX_WEIGHT)) {
958 : 7 : updated_selection_params.m_max_tx_weight = TRUC_CHILD_MAX_WEIGHT;
959 : : }
960 : : }
961 : 7752 : if (auto res{AttemptSelection(wallet.chain(), value_to_select, it->second,
962 [ + - + + ]: 3876 : updated_selection_params, select_filter.allow_mixed_output_types)}) {
963 : 3390 : 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 [ + - + + : 486 : if (HasErrorMsg(res)) res_detailed_errors.emplace_back(std::move(res));
+ - ]
969 : 3876 : }
970 : : }
971 : :
972 : : // Return right away if we have a detailed error
973 [ + - ]: 13 : if (!res_detailed_errors.empty()) return std::move(res_detailed_errors.front());
974 : :
975 : :
976 : : // General "Insufficient Funds"
977 : 0 : return util::Error{};
978 : 6807 : }
979 : : }
980 : :
981 : 3552 : static bool IsCurrentForAntiFeeSniping(interfaces::Chain& chain, const uint256& block_hash)
982 : : {
983 [ + - ]: 3552 : if (chain.isInitialBlockDownload()) {
984 : : return false;
985 : : }
986 : 3552 : constexpr int64_t MAX_ANTI_FEE_SNIPING_TIP_AGE = 8 * 60 * 60; // in seconds
987 : 3552 : int64_t block_time;
988 : 3552 : CHECK_NONFATAL(chain.findBlock(block_hash, FoundBlock().time(block_time)));
989 [ + + ]: 3552 : if (block_time < (GetTime() - MAX_ANTI_FEE_SNIPING_TIP_AGE)) {
990 : 23 : return false;
991 : : }
992 : : return true;
993 : : }
994 : :
995 : 3552 : void DiscourageFeeSniping(CMutableTransaction& tx, FastRandomContext& rng_fast,
996 : : interfaces::Chain& chain, const uint256& block_hash, int block_height, uint32_t minimum_height)
997 : : {
998 : : // All inputs must be added by now
999 [ - + ]: 3552 : 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 [ + + ]: 3552 : if (IsCurrentForAntiFeeSniping(chain, block_hash)) {
1021 : 3529 : 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 [ + + + + ]: 3529 : if (rng_fast.randrange(10) == 0 && tx.nLockTime > minimum_height) {
1028 : : // If a minimum_height is passed, the backdating is limited between
1029 : : // the current height and the minimum_height.
1030 [ + + ]: 313 : int range = std::min(100, int(block_height - static_cast<int>(minimum_height) + 1));
1031 : 313 : tx.nLockTime = int(tx.nLockTime) - int(rng_fast.randrange(range));
1032 : : }
1033 : : } else {
1034 : : // If our chain is lagging behind, we can't discourage fee sniping nor help
1035 : : // the privacy of high-latency transactions. Use minimum_height so new
1036 : : // sends still get a constant 0 fingerprint.
1037 : 23 : tx.nLockTime = minimum_height;
1038 : : }
1039 : : // If minimum_height is ahead of the local tip, use 0 so the tx stays final
1040 : : // and we do not fingerprint the lagging tip.
1041 [ + + ]: 3552 : if (minimum_height > static_cast<uint32_t>(block_height)) {
1042 : 2 : tx.nLockTime = 0;
1043 : : }
1044 : : // Sanity check all values
1045 [ - + ]: 3552 : assert(tx.nLockTime < LOCKTIME_THRESHOLD); // Type must be block height
1046 [ - + ]: 3552 : assert(tx.nLockTime <= uint64_t(block_height));
1047 [ + + ]: 16517 : for (const auto& in : tx.vin) {
1048 : : // Can not be FINAL for locktime to work
1049 [ - + ]: 12965 : assert(in.nSequence != CTxIn::SEQUENCE_FINAL);
1050 : : // May be MAX NONFINAL to disable both BIP68 and BIP125
1051 [ + + ]: 12965 : if (in.nSequence == CTxIn::MAX_SEQUENCE_NONFINAL) continue;
1052 : : // May be MAX BIP125 to disable BIP68 and enable BIP125
1053 [ + - ]: 12556 : if (in.nSequence == MAX_BIP125_RBF_SEQUENCE) continue;
1054 : : // The wallet does not support any other sequence-use right now.
1055 : 0 : AssertUnreachable();
1056 : : }
1057 : 3552 : }
1058 : :
1059 : 39607 : uint64_t GetSerializeSizeForRecipient(const CRecipient& recipient)
1060 : : {
1061 [ + - ]: 39607 : return ::GetSerializeSize(CTxOut(recipient.nAmount, GetScriptForDestination(recipient.dest)));
1062 : : }
1063 : :
1064 : 39607 : bool IsDust(const CRecipient& recipient, const CFeeRate& dustRelayFee)
1065 : : {
1066 [ + - + - ]: 39607 : return ::IsDust(CTxOut(recipient.nAmount, GetScriptForDestination(recipient.dest)), dustRelayFee);
1067 : : }
1068 : :
1069 : 3854 : static util::Result<CreatedTransactionResult> CreateTransactionInternal(
1070 : : CWallet& wallet,
1071 : : const std::vector<CRecipient>& vecSend,
1072 : : std::optional<unsigned int> change_pos,
1073 : : const CCoinControl& coin_control,
1074 : : bool sign) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
1075 : : {
1076 : 3854 : AssertLockHeld(wallet.cs_wallet);
1077 : :
1078 : 3854 : FastRandomContext rng_fast;
1079 [ + - ]: 3854 : CMutableTransaction txNew; // The resulting transaction that we make
1080 : :
1081 : 3854 : txNew.version = coin_control.m_version;
1082 : :
1083 : 3854 : CoinSelectionParams coin_selection_params{rng_fast}; // Parameters for coin selection, init with dummy
1084 : 3854 : coin_selection_params.m_avoid_partial_spends = coin_control.m_avoid_partial_spends;
1085 : 3854 : coin_selection_params.m_include_unsafe_inputs = coin_control.m_include_unsafe_inputs;
1086 [ + + + - ]: 3922 : coin_selection_params.m_max_tx_weight = coin_control.m_max_tx_weight.value_or(MAX_STANDARD_TX_WEIGHT);
1087 : 3854 : coin_selection_params.m_version = coin_control.m_version;
1088 : 3854 : int minimum_tx_weight = MIN_STANDARD_TX_NONWITNESS_SIZE * WITNESS_SCALE_FACTOR;
1089 [ + - + + : 3854 : if (coin_selection_params.m_max_tx_weight.value() < minimum_tx_weight || coin_selection_params.m_max_tx_weight.value() > MAX_STANDARD_TX_WEIGHT) {
+ + ]
1090 [ + - ]: 9 : return util::Error{strprintf(_("Maximum transaction weight must be between %d and %d"), minimum_tx_weight, MAX_STANDARD_TX_WEIGHT)};
1091 : : }
1092 : : // Set the long term feerate estimate to the wallet's consolidate feerate
1093 : 3851 : coin_selection_params.m_long_term_feerate = wallet.m_consolidate_feerate;
1094 : : // Static vsize overhead + outputs vsize. 4 nVersion, 4 nLocktime, 1 input count, 1 witness overhead (dummy, flag, stack size)
1095 [ - + + + ]: 3851 : coin_selection_params.tx_noinputs_size = 10 + GetSizeOfCompactSize(vecSend.size()); // bytes for output count
1096 : :
1097 : 3851 : CAmount recipients_sum = 0;
1098 [ + + + - ]: 3851 : const OutputType change_type = wallet.TransactionChangeType(coin_control.m_change_type ? *coin_control.m_change_type : wallet.m_default_change_type, vecSend);
1099 : 3851 : ReserveDestination reservedest(&wallet, change_type);
1100 : 3851 : unsigned int outputs_to_subtract_fee_from = 0; // The number of outputs which we are subtracting the fee from
1101 [ + + ]: 43458 : for (const auto& recipient : vecSend) {
1102 [ + + + + ]: 39611 : if (!MoneyRange(recipient.nAmount) || !MoneyRange(recipients_sum + recipient.nAmount)) {
1103 [ + - ]: 12 : return util::Error{_("Transaction output amount must be valid")};
1104 : : }
1105 [ + - + - : 39607 : if (IsDust(recipient, wallet.chain().relayDustFee())) {
- + ]
1106 [ # # ]: 0 : return util::Error{_("Transaction amount too small")};
1107 : : }
1108 : :
1109 : : // Include the fee cost for outputs.
1110 [ + - ]: 39607 : coin_selection_params.tx_noinputs_size += GetSerializeSizeForRecipient(recipient);
1111 : 39607 : recipients_sum += recipient.nAmount;
1112 : :
1113 [ + + ]: 39607 : if (recipient.fSubtractFeeFromAmount) {
1114 : 648 : outputs_to_subtract_fee_from++;
1115 : 648 : coin_selection_params.m_subtract_fee_outputs = true;
1116 : : }
1117 : : }
1118 : :
1119 : : // Create change script that will be used if we need change
1120 : 3847 : CScript scriptChange;
1121 [ + - ]: 3847 : bilingual_str error; // possible error str
1122 : :
1123 : : // coin control: send change to custom address
1124 [ + - ]: 3847 : if (!std::get_if<CNoDestination>(&coin_control.destChange)) {
1125 [ + - ]: 3836 : scriptChange = GetScriptForDestination(coin_control.destChange);
1126 : : } else { // no coin control: send change to newly generated address
1127 : : // Note: We use a new key here to keep it from being obvious which side is the change.
1128 : : // The drawback is that by not reusing a previous key, the change may be lost if a
1129 : : // backup is restored, if the backup doesn't have the new private key for the change.
1130 : : // If we reused the old key, it would be possible to add code to look for and
1131 : : // rediscover unknown transactions that were written with keys of ours to recover
1132 : : // post-backup change.
1133 : :
1134 : : // Reserve a new key pair from key pool. If it fails, provide a dummy
1135 : : // destination in case we don't need change.
1136 : 1929 : CTxDestination dest;
1137 [ + - ]: 1929 : auto op_dest = reservedest.GetReservedDestination(true);
1138 [ + + ]: 1929 : if (!op_dest) {
1139 [ + - + - : 90 : error = _("Transaction needs a change address, but we can't generate it.") + Untranslated(" ") + util::ErrorString(op_dest);
+ - + - ]
1140 : : } else {
1141 [ + - ]: 1914 : dest = *op_dest;
1142 [ + - ]: 3828 : scriptChange = GetScriptForDestination(dest);
1143 : : }
1144 : : // A valid destination implies a change script (and
1145 : : // vice-versa). An empty change script will abort later, if the
1146 : : // change keypool ran out, but change is required.
1147 [ + - - + : 1929 : CHECK_NONFATAL(IsValidDestination(dest) != scriptChange.empty());
+ - ]
1148 : 1929 : }
1149 [ + - ]: 3847 : CTxOut change_prototype_txout(0, scriptChange);
1150 : 3847 : coin_selection_params.change_output_size = GetSerializeSize(change_prototype_txout);
1151 : :
1152 : : // Get size of spending the change output
1153 [ + - ]: 3847 : int change_spend_size = CalculateMaximumSignedInputSize(change_prototype_txout, &wallet, /*coin_control=*/nullptr);
1154 : : // If the wallet doesn't know how to sign change output, assume p2sh-p2wpkh
1155 : : // as lower-bound to allow BnB to do its thing
1156 [ + + ]: 3847 : if (change_spend_size == -1) {
1157 : 25 : coin_selection_params.change_spend_size = DUMMY_NESTED_P2WPKH_INPUT_SIZE;
1158 : : } else {
1159 : 3822 : coin_selection_params.change_spend_size = change_spend_size;
1160 : : }
1161 : :
1162 : : // Set discard feerate
1163 [ + - ]: 3847 : coin_selection_params.m_discard_feerate = GetDiscardRate(wallet);
1164 : :
1165 : : // Get the fee rate to use effective values in coin selection
1166 [ + - ]: 3847 : auto min_fee_rate{GetMinimumFeeRate(wallet, coin_control)};
1167 : 3847 : coin_selection_params.m_effective_feerate = min_fee_rate.fee_rate;
1168 : : // Do not, ever, assume that it's fine to change the fee rate if the user has explicitly
1169 : : // provided one
1170 [ + + + + ]: 3847 : if (coin_control.m_feerate && coin_selection_params.m_effective_feerate > *coin_control.m_feerate) {
1171 : 21 : const auto feerate_format = FeeRateFormat::SAT_VB;
1172 : 21 : auto msg{strprintf(_("Fee rate (%s) is lower than the minimum fee rate setting (%s)."),
1173 [ + - ]: 42 : coin_control.m_feerate->ToString(feerate_format),
1174 [ + - + - ]: 42 : coin_selection_params.m_effective_feerate.ToString(feerate_format))};
1175 [ + - ]: 21 : if (min_fee_rate.fee_reason == FeeReason::REQUIRED) {
1176 [ + - ]: 42 : msg += strprintf(_("\nConsider modifying %s (%s) or %s (%s)."),
1177 : : "-mintxfee",
1178 [ + - ]: 42 : wallet.m_min_fee.ToString(feerate_format),
1179 : : "-minrelaytxfee",
1180 [ + - + - : 63 : wallet.chain().relayMinFee().ToString(feerate_format));
+ - ]
1181 : : }
1182 [ + - ]: 63 : return util::Error{msg};
1183 : 21 : }
1184 [ + + + + ]: 3826 : if (min_fee_rate.fee_reason == FeeReason::FALLBACK && !wallet.m_allow_fallback_fee) {
1185 : : // eventually allow a fallback fee
1186 [ + - ]: 18 : return util::Error{strprintf(_("Fee estimation failed. Fallbackfee is disabled. Wait a few blocks or enable %s."), "-fallbackfee")};
1187 : : }
1188 : :
1189 : : // Calculate the cost of change
1190 : : // Cost of change is the cost of creating the change output + cost of spending the change output in the future.
1191 : : // For creating the change output now, we use the effective feerate.
1192 : : // For spending the change output in the future, we use the discard feerate for now.
1193 : : // So cost of change = (change output size * effective feerate) + (size of spending change output * discard feerate)
1194 [ + - ]: 3820 : coin_selection_params.m_change_fee = coin_selection_params.m_effective_feerate.GetFee(coin_selection_params.change_output_size);
1195 [ + - ]: 3820 : 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;
1196 : :
1197 [ - + + - ]: 3820 : coin_selection_params.m_min_change_target = GenerateChangeTarget(std::floor(recipients_sum / vecSend.size()), coin_selection_params.m_change_fee, rng_fast);
1198 : :
1199 : : // The smallest change amount should be:
1200 : : // 1. at least equal to dust threshold
1201 : : // 2. at least 1 sat greater than fees to spend it at m_discard_feerate
1202 [ + - ]: 3820 : const auto dust = GetDustThreshold(change_prototype_txout, coin_selection_params.m_discard_feerate);
1203 [ + - ]: 3820 : const auto change_spend_fee = coin_selection_params.m_discard_feerate.GetFee(coin_selection_params.change_spend_size);
1204 [ + + ]: 3820 : coin_selection_params.min_viable_change = std::max(change_spend_fee + 1, dust);
1205 : :
1206 : : // Include the fees for things that aren't inputs, excluding the change output
1207 [ + + + - ]: 3820 : 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);
1208 : 3820 : CAmount selection_target = recipients_sum + not_input_fees;
1209 : :
1210 : : // This can only happen if feerate is 0, and requested destinations are value of 0 (e.g. OP_RETURN)
1211 : : // and no pre-selected inputs. This will result in 0-input transaction, which is consensus-invalid anyways
1212 [ + + + - : 3820 : if (selection_target == 0 && !coin_control.HasSelected()) {
- + ]
1213 [ + - ]: 3 : return util::Error{_("Transaction requires one destination of non-zero value, a non-zero feerate, or a pre-selected input")};
1214 : : }
1215 : :
1216 : : // Fetch manually selected coins
1217 [ + - ]: 3819 : CoinsResult preset_inputs;
1218 [ + - + + ]: 3819 : if (coin_control.HasSelected()) {
1219 [ + - ]: 582 : auto res_fetch_inputs = FetchSelectedInputs(wallet, coin_control, coin_selection_params);
1220 [ + + + - ]: 594 : if (!res_fetch_inputs) return util::Error{util::ErrorString(res_fetch_inputs)};
1221 [ + - ]: 576 : preset_inputs = *res_fetch_inputs;
1222 : 582 : }
1223 : :
1224 : : // Fetch wallet available coins if "other inputs" are
1225 : : // allowed (coins automatically selected by the wallet)
1226 [ + + ]: 3813 : CoinsResult available_coins;
1227 [ + + ]: 3813 : if (coin_control.m_allow_other_inputs) {
1228 [ + - ]: 7244 : available_coins = AvailableCoins(wallet, &coin_control, coin_selection_params.m_effective_feerate);
1229 : : }
1230 : :
1231 : : // Choose coins to use
1232 [ + - ]: 3813 : auto select_coins_res = SelectCoins(wallet, available_coins, preset_inputs, /*nTargetValue=*/selection_target, coin_control, coin_selection_params);
1233 [ + + ]: 3813 : if (!select_coins_res) {
1234 : : // 'SelectCoins' either returns a specific error message or, if empty, means a general "Insufficient funds".
1235 [ + - ]: 54 : const bilingual_str& err = util::ErrorString(select_coins_res);
1236 [ + + + - ]: 108 : if (!err.empty()) return util::Error{err};
1237 : :
1238 : : // Check if we have enough balance but cannot cover the fees
1239 [ + + ]: 27 : CAmount available_balance = preset_inputs.GetTotalAmount() + available_coins.GetTotalAmount();
1240 : : // Note: if SelectCoins() fails when SFFO is enabled (recipients_sum = selection_target with SFFO),
1241 : : // then recipients_sum > available_balance and we wouldn't enter into the if condition below.
1242 [ + + ]: 27 : if (available_balance >= recipients_sum) {
1243 : : // If we have coins with balance, they should have effective values since we constructed them with valid feerate.
1244 [ + - + + : 4 : assert(!preset_inputs.Size() || preset_inputs.GetEffectiveTotalAmount().has_value());
- + ]
1245 [ + - + + : 4 : assert(!available_coins.Size() || available_coins.GetEffectiveTotalAmount().has_value());
- + ]
1246 [ + + + + ]: 6 : CAmount available_effective_balance = preset_inputs.GetEffectiveTotalAmount().value_or(0) + available_coins.GetEffectiveTotalAmount().value_or(0);
1247 [ + - ]: 4 : if (available_effective_balance < selection_target) {
1248 [ + - ]: 4 : Assume(!coin_selection_params.m_subtract_fee_outputs);
1249 [ + - + - ]: 12 : return util::Error{strprintf(_("The total exceeds your balance when the %s transaction fee is included."), FormatMoney(selection_target - recipients_sum))};
1250 : : }
1251 : : }
1252 : :
1253 : : // General failure description
1254 [ + - ]: 69 : return util::Error{_("Insufficient funds")};
1255 : 54 : }
1256 : 3759 : const SelectionResult& result = *select_coins_res;
1257 : : TRACEPOINT(coin_selection, selected_coins,
1258 : : wallet.GetName().c_str(),
1259 : : GetAlgorithmName(result.GetAlgo()).c_str(),
1260 : : result.GetTarget(),
1261 : : result.GetWaste(),
1262 : 3759 : result.GetSelectedValue());
1263 : :
1264 : : // vouts to the payees
1265 [ - + + - ]: 3759 : txNew.vout.reserve(vecSend.size() + 1); // + 1 because of possible later insert
1266 [ + + ]: 43272 : for (const auto& recipient : vecSend)
1267 : : {
1268 [ + - + - ]: 79026 : txNew.vout.emplace_back(recipient.nAmount, GetScriptForDestination(recipient.dest));
1269 : : }
1270 [ + - ]: 3759 : const CAmount change_amount = result.GetChange(coin_selection_params.min_viable_change, coin_selection_params.m_change_fee);
1271 [ + + ]: 3759 : if (change_amount > 0) {
1272 [ + - ]: 3681 : CTxOut newTxOut(change_amount, scriptChange);
1273 [ + + ]: 3681 : if (!change_pos) {
1274 : : // Insert change txn at random position:
1275 [ - + ]: 3565 : change_pos = rng_fast.randrange(txNew.vout.size() + 1);
1276 [ - + - + ]: 116 : } else if ((unsigned int)*change_pos > txNew.vout.size()) {
1277 [ # # ]: 0 : return util::Error{_("Transaction change output index out of range")};
1278 : : }
1279 [ + - ]: 3681 : txNew.vout.insert(txNew.vout.begin() + *change_pos, newTxOut);
1280 : 3681 : } else {
1281 [ + + ]: 78 : change_pos = std::nullopt;
1282 : : }
1283 : :
1284 : : // Shuffle selected coins and fill in final vin
1285 [ + - ]: 3759 : std::vector<std::shared_ptr<COutput>> selected_coins = result.GetShuffledInputVector();
1286 : :
1287 [ + - + + : 3759 : if (coin_control.HasSelected() && coin_control.HasSelectedOrder()) {
+ + ]
1288 : : // When there are preselected inputs, we need to move them to be the first UTXOs
1289 : : // and have them be in the order selected. We can use stable_sort for this, where we
1290 : : // compare with the positions stored in coin_control. The COutputs that have positions
1291 : : // will be placed before those that don't, and those positions will be in order.
1292 [ + - ]: 555 : std::stable_sort(selected_coins.begin(), selected_coins.end(),
1293 : 15456 : [&coin_control](const std::shared_ptr<COutput>& a, const std::shared_ptr<COutput>& b) {
1294 : 15456 : auto a_pos = coin_control.GetSelectionPos(a->outpoint);
1295 : 15456 : auto b_pos = coin_control.GetSelectionPos(b->outpoint);
1296 [ + + + + ]: 15456 : if (a_pos.has_value() && b_pos.has_value()) {
1297 : 14923 : return a_pos.value() < b_pos.value();
1298 [ + + + - ]: 533 : } else if (a_pos.has_value() && !b_pos.has_value()) {
1299 : 99 : return true;
1300 : : } else {
1301 : : return false;
1302 : : }
1303 : : });
1304 : : }
1305 : :
1306 : : // The sequence number is set to non-maxint so that DiscourageFeeSniping
1307 : : // works.
1308 : : //
1309 : : // BIP125 defines opt-in RBF as any nSequence < maxint-1, so
1310 : : // we use the highest possible value in that range (maxint-2)
1311 : : // to avoid conflicting with other possible uses of nSequence,
1312 : : // and in the spirit of "smallest possible change from prior
1313 : : // behavior."
1314 : 3759 : bool use_anti_fee_sniping = true;
1315 [ + + + + ]: 7518 : 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};
1316 [ - + + - ]: 3759 : txNew.vin.reserve(selected_coins.size());
1317 [ + + ]: 20610 : for (const auto& coin : selected_coins) {
1318 [ + - ]: 16851 : std::optional<uint32_t> sequence = coin_control.GetSequence(coin->outpoint);
1319 [ + + ]: 16851 : if (sequence) {
1320 : : // If an input has a preset sequence, we can't do anti-fee-sniping
1321 : 1871 : use_anti_fee_sniping = false;
1322 : : }
1323 [ + + + - ]: 18722 : txNew.vin.emplace_back(coin->outpoint, CScript{}, sequence.value_or(default_sequence));
1324 : :
1325 [ + - ]: 16851 : auto scripts = coin_control.GetScripts(coin->outpoint);
1326 [ + + ]: 16851 : if (scripts.first) {
1327 : 1871 : txNew.vin.back().scriptSig = *scripts.first;
1328 : : }
1329 [ + + ]: 16851 : if (scripts.second) {
1330 [ + - ]: 16851 : txNew.vin.back().scriptWitness = *scripts.second;
1331 : : }
1332 : 16851 : }
1333 [ + + ]: 3759 : if (coin_control.m_locktime) {
1334 : 912 : txNew.nLockTime = coin_control.m_locktime.value();
1335 : : // If we have a locktime set, we can't use anti-fee-sniping
1336 : 912 : use_anti_fee_sniping = false;
1337 : : }
1338 [ + - ]: 3759 : if (use_anti_fee_sniping) {
1339 : 2847 : uint32_t minimum_height = 0;
1340 [ + + + - ]: 2847 : if (coin_control.m_minimum_locktime.has_value() && coin_control.m_minimum_locktime < LOCKTIME_THRESHOLD) {
1341 : 233 : minimum_height = coin_control.m_minimum_locktime.value();
1342 : : }
1343 [ + - ]: 2847 : DiscourageFeeSniping(txNew, rng_fast, wallet.chain(), wallet.GetLastBlockHash(), wallet.GetLastBlockHeight(), minimum_height);
1344 : : }
1345 : :
1346 : : // Calculate the transaction fee
1347 [ + - + - ]: 3759 : TxSize tx_sizes = CalculateMaximumSignedTxSize(CTransaction(txNew), &wallet, &coin_control);
1348 : 3759 : int nBytes = tx_sizes.vsize;
1349 [ + + ]: 3759 : if (nBytes == -1) {
1350 [ + - ]: 3 : return util::Error{_("Missing solving data for estimating transaction size")};
1351 : : }
1352 [ + - + - ]: 3758 : CAmount fee_needed = coin_selection_params.m_effective_feerate.GetFee(nBytes) + result.GetTotalBumpFees();
1353 : 3758 : const CAmount output_value = CalculateOutputValue(txNew);
1354 [ + - ]: 3758 : Assume(recipients_sum + change_amount == output_value);
1355 [ + - ]: 3758 : CAmount current_fee = result.GetSelectedValue() - output_value;
1356 : :
1357 : : // Sanity check that the fee cannot be negative as that means we have more output value than input value
1358 [ - + ]: 3758 : if (current_fee < 0) {
1359 [ # # # # ]: 0 : return util::Error{Untranslated(STR_INTERNAL_BUG("Fee paid < 0"))};
1360 : : }
1361 : :
1362 : : // If there is a change output and we overpay the fees then increase the change to match the fee needed
1363 [ + + + + ]: 3758 : if (change_pos && fee_needed < current_fee) {
1364 [ + - ]: 1285 : auto& change = txNew.vout.at(*change_pos);
1365 : 1285 : change.nValue += current_fee - fee_needed;
1366 [ + - ]: 1285 : current_fee = result.GetSelectedValue() - CalculateOutputValue(txNew);
1367 [ - + ]: 1285 : if (fee_needed != current_fee) {
1368 [ # # # # ]: 0 : return util::Error{Untranslated(STR_INTERNAL_BUG("Change adjustment: Fee needed != fee paid"))};
1369 : : }
1370 : : }
1371 : :
1372 : : // Reduce output values for subtractFeeFromAmount
1373 [ + + ]: 3758 : if (coin_selection_params.m_subtract_fee_outputs) {
1374 : 636 : CAmount to_reduce = fee_needed - current_fee;
1375 : 636 : unsigned int i = 0;
1376 : 636 : bool fFirst = true;
1377 [ + + ]: 1283 : for (const auto& recipient : vecSend)
1378 : : {
1379 [ + + + + ]: 648 : if (change_pos && i == *change_pos) {
1380 : 296 : ++i;
1381 : : }
1382 [ + + ]: 648 : CTxOut& txout = txNew.vout[i];
1383 : :
1384 [ + + ]: 648 : if (recipient.fSubtractFeeFromAmount)
1385 : : {
1386 : 646 : txout.nValue -= to_reduce / outputs_to_subtract_fee_from; // Subtract fee equally from each selected recipient
1387 : :
1388 [ + + ]: 646 : if (fFirst) // first receiver pays the remainder not divisible by output count
1389 : : {
1390 : 636 : fFirst = false;
1391 : 636 : txout.nValue -= to_reduce % outputs_to_subtract_fee_from;
1392 : : }
1393 : :
1394 : : // Error if this output is reduced to be below dust
1395 [ + - + - : 646 : if (IsDust(txout, wallet.chain().relayDustFee())) {
+ + ]
1396 [ + - ]: 1 : if (txout.nValue < 0) {
1397 [ + - ]: 3 : return util::Error{_("The transaction amount is too small to pay the fee")};
1398 : : } else {
1399 [ # # ]: 0 : return util::Error{_("The transaction amount is too small to send after the fee has been deducted")};
1400 : : }
1401 : : }
1402 : : }
1403 : 647 : ++i;
1404 : : }
1405 [ + - ]: 635 : current_fee = result.GetSelectedValue() - CalculateOutputValue(txNew);
1406 [ - + ]: 635 : if (fee_needed != current_fee) {
1407 [ # # # # ]: 0 : return util::Error{Untranslated(STR_INTERNAL_BUG("SFFO: Fee needed != fee paid"))};
1408 : : }
1409 : : }
1410 : :
1411 : : // fee_needed should now always be less than or equal to the current fees that we pay.
1412 : : // If it is not, it is a bug.
1413 [ - + ]: 3757 : if (fee_needed > current_fee) {
1414 [ # # # # ]: 0 : return util::Error{Untranslated(STR_INTERNAL_BUG("Fee needed > fee paid"))};
1415 : : }
1416 : :
1417 : : // Give up if change keypool ran out and change is required
1418 [ - + + + : 3757 : if (scriptChange.empty() && change_pos) {
+ + ]
1419 [ + - ]: 6 : return util::Error{error};
1420 : : }
1421 : :
1422 [ + + + - : 3755 : if (sign && !wallet.SignTransaction(txNew)) {
+ - ]
1423 [ # # ]: 0 : return util::Error{_("Signing transaction failed")};
1424 : : }
1425 : :
1426 : : // Return the constructed transaction data.
1427 [ + - ]: 3755 : CTransactionRef tx = MakeTransactionRef(std::move(txNew));
1428 : :
1429 : : // Limit size
1430 [ + + - + ]: 3755 : if ((sign && GetTransactionWeight(*tx) > MAX_STANDARD_TX_WEIGHT) ||
1431 [ + + ]: 1141 : (!sign && tx_sizes.weight > MAX_STANDARD_TX_WEIGHT))
1432 : : {
1433 [ + - ]: 6 : return util::Error{_("Transaction too large")};
1434 : : }
1435 : :
1436 [ + + ]: 3753 : if (current_fee > wallet.m_max_tx_fee) {
1437 [ + - ]: 51 : return util::Error{TransactionErrorString(TransactionError::MAX_FEE_EXCEEDED)};
1438 : : }
1439 : :
1440 [ + - ]: 3736 : const int64_t tx_vsize{GetVirtualTransactionSize(*tx)};
1441 [ + - + + ]: 3736 : if (current_fee > wallet.m_max_tx_fee_rate.GetFee(tx_vsize)) {
1442 [ + - ]: 6 : return util::Error{TransactionErrorString(TransactionError::MAX_FEE_RATE_EXCEEDED)};
1443 : : }
1444 : :
1445 [ + - + - : 3734 : if (gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
+ + ]
1446 : : // Lastly, ensure this tx will pass the mempool's chain limits
1447 [ + - ]: 3670 : auto result = wallet.chain().checkChainLimits(tx);
1448 [ + + ]: 3670 : if (!result) {
1449 [ + - ]: 3 : return util::Error{util::ErrorString(result)};
1450 : : }
1451 : 3670 : }
1452 : :
1453 : : // Before we return success, we assume any change key will be used to prevent
1454 : : // accidental reuse.
1455 [ + - ]: 3733 : reservedest.KeepDestination();
1456 : :
1457 [ + - + - : 3733 : wallet.WalletLogPrintf("Coin Selection: Algorithm:%s, Waste Metric Score:%d", GetAlgorithmName(result.GetAlgo()), result.GetWaste());
+ - ]
1458 [ + - ]: 3733 : wallet.WalletLogPrintf("Fee Calculation: Fee:%d Bytes:%u, Source: %s",
1459 [ + - ]: 3733 : current_fee, nBytes, StringForFeeReason(min_fee_rate.fee_reason));
1460 [ + - + - : 14932 : return CreatedTransactionResult(tx, current_fee, change_pos, min_fee_rate.fee_reason);
+ - ]
1461 : 26790 : }
1462 : :
1463 : 2016 : util::Result<CreatedTransactionResult> CreateTransaction(
1464 : : CWallet& wallet,
1465 : : const std::vector<CRecipient>& vecSend,
1466 : : std::optional<unsigned int> change_pos,
1467 : : const CCoinControl& coin_control,
1468 : : bool sign)
1469 : : {
1470 [ - + ]: 2016 : if (vecSend.empty()) {
1471 : 0 : return util::Error{_("Transaction must have at least one recipient")};
1472 : : }
1473 : :
1474 : 2016 : LOCK(wallet.cs_wallet);
1475 : :
1476 [ + - ]: 2016 : auto res = CreateTransactionInternal(wallet, vecSend, change_pos, coin_control, sign);
1477 : : TRACEPOINT(coin_selection, normal_create_tx_internal,
1478 : : wallet.GetName().c_str(),
1479 : : bool(res),
1480 : : res ? res->fee : 0,
1481 : 2016 : res && res->change_pos.has_value() ? int32_t(*res->change_pos) : -1);
1482 [ + + ]: 2016 : if (!res) return res;
1483 : 1899 : const auto& txr_ungrouped = *res;
1484 : : // try with avoidpartialspends unless it's enabled already
1485 [ + + + - : 1899 : if (txr_ungrouped.fee > 0 /* 0 means non-functional fee rate estimation */ && wallet.m_max_aps_fee > -1 && !coin_control.m_avoid_partial_spends) {
+ + ]
1486 : 1838 : TRACEPOINT(coin_selection, attempting_aps_create_tx, wallet.GetName().c_str());
1487 [ + - ]: 1838 : CCoinControl tmp_cc = coin_control;
1488 : 1838 : tmp_cc.m_avoid_partial_spends = true;
1489 : :
1490 : : // Reuse the change destination from the first creation attempt to avoid skipping BIP44 indexes
1491 [ + + ]: 1838 : if (txr_ungrouped.change_pos) {
1492 [ + - ]: 1799 : ExtractDestination(txr_ungrouped.tx->vout[*txr_ungrouped.change_pos].scriptPubKey, tmp_cc.destChange);
1493 : : }
1494 : :
1495 [ + - ]: 1838 : auto txr_grouped = CreateTransactionInternal(wallet, vecSend, change_pos, tmp_cc, sign);
1496 : : // if fee of this alternative one is within the range of the max fee, we use this one
1497 [ + + ]: 3672 : const bool use_aps{txr_grouped.has_value() ? (txr_grouped->fee <= txr_ungrouped.fee + wallet.m_max_aps_fee) : false};
1498 : : TRACEPOINT(coin_selection, aps_create_tx_internal,
1499 : : wallet.GetName().c_str(),
1500 : : use_aps,
1501 : : txr_grouped.has_value(),
1502 : : txr_grouped.has_value() ? txr_grouped->fee : 0,
1503 : 1838 : txr_grouped.has_value() && txr_grouped->change_pos.has_value() ? int32_t(*txr_grouped->change_pos) : -1);
1504 [ + + ]: 1838 : if (txr_grouped) {
1505 : 3668 : wallet.WalletLogPrintf("Fee non-grouped = %lld, grouped = %lld, using %s",
1506 [ + + + - ]: 2216 : txr_ungrouped.fee, txr_grouped->fee, use_aps ? "grouped" : "non-grouped");
1507 [ + + ]: 1834 : if (use_aps) return txr_grouped;
1508 : : }
1509 : 1838 : }
1510 : 447 : return res;
1511 [ + - ]: 4032 : }
1512 : :
1513 : 556 : util::Result<CreatedTransactionResult> FundTransaction(CWallet& wallet, const CMutableTransaction& tx, const std::vector<CRecipient>& vecSend, std::optional<unsigned int> change_pos, bool lockUnspents, CCoinControl coinControl)
1514 : : {
1515 : : // We want to make sure tx.vout is not used now that we are passing outputs as a vector of recipients.
1516 : : // This sets us up to remove tx completely in a future PR in favor of passing the inputs directly.
1517 [ - + ]: 556 : assert(tx.vout.empty());
1518 : :
1519 : : // Set the user desired locktime
1520 : 556 : coinControl.m_locktime = tx.nLockTime;
1521 : :
1522 : : // Set the user desired version
1523 : 556 : coinControl.m_version = tx.version;
1524 : :
1525 : : // Acquire the locks to prevent races to the new locked unspents between the
1526 : : // CreateTransaction call and LockCoin calls (when lockUnspents is true).
1527 : 556 : LOCK(wallet.cs_wallet);
1528 : :
1529 : : // Fetch specified UTXOs from the UTXO set to get the scriptPubKeys and values of the outputs being selected
1530 : : // and to match with the given solving_data. Only used for non-wallet outputs.
1531 : 556 : std::map<COutPoint, Coin> coins;
1532 [ + + ]: 3283 : for (const CTxIn& txin : tx.vin) {
1533 [ + - ]: 2727 : coins[txin.prevout]; // Create empty map entry keyed by prevout.
1534 : : }
1535 [ + - ]: 556 : wallet.chain().findCoins(coins);
1536 : :
1537 [ + + ]: 3282 : for (const CTxIn& txin : tx.vin) {
1538 : 2727 : const auto& outPoint = txin.prevout;
1539 [ + - ]: 2727 : PreselectedInput& preset_txin = coinControl.Select(outPoint);
1540 [ + - + + ]: 2727 : if (!wallet.IsMine(outPoint)) {
1541 [ + - + + ]: 24 : if (coins[outPoint].out.IsNull()) {
1542 [ + - ]: 3 : return util::Error{_("Unable to find UTXO for external input")};
1543 : : }
1544 : :
1545 : : // The input was not in the wallet, but is in the UTXO set, so select as external
1546 [ + - + - ]: 23 : preset_txin.SetTxOut(coins[outPoint].out);
1547 : : }
1548 [ + - ]: 2726 : preset_txin.SetSequence(txin.nSequence);
1549 [ + - ]: 2726 : preset_txin.SetScriptSig(txin.scriptSig);
1550 [ + - ]: 2726 : preset_txin.SetScriptWitness(txin.scriptWitness);
1551 : : }
1552 : :
1553 [ + - ]: 555 : auto res = CreateTransaction(wallet, vecSend, change_pos, coinControl, false);
1554 [ + + ]: 555 : if (!res) {
1555 : 94 : return res;
1556 : : }
1557 : :
1558 [ + + ]: 461 : if (lockUnspents) {
1559 [ + + ]: 8 : for (const CTxIn& txin : res->tx->vin) {
1560 [ + - ]: 4 : wallet.LockCoin(txin.prevout, /*persist=*/false);
1561 : : }
1562 : : }
1563 : :
1564 : 461 : return res;
1565 [ + - ]: 1667 : }
1566 : : } // namespace wallet
|