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