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