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