Branch data Line data Source code
1 : : // Copyright (c) 2017-present The Bitcoin Core developers
2 : : // Distributed under the MIT software license, see the accompanying
3 : : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 : :
5 : : #include <wallet/feebumper.h>
6 : :
7 : : #include <coins.h>
8 : : #include <common/system.h>
9 : : #include <consensus/validation.h>
10 : : #include <interfaces/chain.h>
11 : : #include <policy/fees/block_policy_estimator.h>
12 : : #include <policy/policy.h>
13 : : #include <util/moneystr.h>
14 : : #include <util/rbf.h>
15 : : #include <util/translation.h>
16 : : #include <wallet/coincontrol.h>
17 : : #include <wallet/fees.h>
18 : : #include <wallet/receive.h>
19 : : #include <wallet/spend.h>
20 : : #include <wallet/wallet.h>
21 : :
22 : : namespace wallet {
23 : : //! Check whether transaction has descendant in wallet or mempool, or has been
24 : : //! mined, or conflicts with a mined transaction. Return a feebumper::Result.
25 : 0 : static feebumper::Result PreconditionChecks(const CWallet& wallet, const CWalletTx& wtx, bool require_mine, std::vector<bilingual_str>& errors) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
26 : : {
27 [ # # # # : 0 : if (wallet.HasWalletSpend(wtx.GetTx())) {
# # ]
28 [ # # # # ]: 0 : errors.emplace_back(Untranslated("Transaction has descendants in the wallet"));
29 : 0 : return feebumper::Result::INVALID_PARAMETER;
30 : : }
31 : :
32 : 0 : {
33 [ # # ]: 0 : if (wallet.chain().hasDescendantsInMempool(wtx.GetHash())) {
34 [ # # # # ]: 0 : errors.emplace_back(Untranslated("Transaction has descendants in the mempool"));
35 : 0 : return feebumper::Result::INVALID_PARAMETER;
36 : : }
37 : : }
38 : :
39 [ # # ]: 0 : if (wallet.GetTxDepthInMainChain(wtx) != 0) {
40 [ # # # # ]: 0 : errors.emplace_back(Untranslated("Transaction has been mined, or is conflicted with a mined transaction"));
41 : 0 : return feebumper::Result::WALLET_ERROR;
42 : : }
43 : :
44 [ # # ]: 0 : if (wtx.m_replaced_by_txid) {
45 [ # # # # : 0 : errors.push_back(Untranslated(strprintf("Cannot bump transaction %s which was already bumped by transaction %s", wtx.GetHash().ToString(), wtx.m_replaced_by_txid->ToString())));
# # # # ]
46 : 0 : return feebumper::Result::WALLET_ERROR;
47 : : }
48 : :
49 [ # # ]: 0 : if (require_mine) {
50 : : // check that original tx consists entirely of our inputs
51 : : // if not, we can't bump the fee, because the wallet has no way of knowing the value of the other inputs (thus the fee)
52 [ # # # # : 0 : if (!AllInputsMine(wallet, *wtx.GetTx())) {
# # ]
53 [ # # # # ]: 0 : errors.emplace_back(Untranslated("Transaction contains inputs that don't belong to this wallet"));
54 : 0 : return feebumper::Result::WALLET_ERROR;
55 : : }
56 : : }
57 : :
58 : : return feebumper::Result::OK;
59 : : }
60 : :
61 : : //! Check if the user provided a valid feeRate
62 : 0 : static feebumper::Result CheckFeeRate(const CWallet& wallet, const CMutableTransaction& mtx, const CFeeRate& newFeerate, const int64_t maxTxSize, CAmount old_fee, std::vector<bilingual_str>& errors)
63 : : {
64 : : // check that fee rate is higher than mempool's minimum fee
65 : : // (no point in bumping fee if we know that the new tx won't be accepted to the mempool)
66 : : // This may occur if fallbackfee is too low, or, perhaps,
67 : : // in a rare situation where the mempool minimum fee increased significantly since the fee estimation just a
68 : : // moment earlier. In this case, we report an error to the user, who may adjust the fee.
69 : 0 : CFeeRate minMempoolFeeRate = wallet.chain().mempoolMinFee();
70 : :
71 [ # # ]: 0 : if (newFeerate.GetFeePerK() < minMempoolFeeRate.GetFeePerK()) {
72 [ # # ]: 0 : errors.push_back(Untranslated(
73 [ # # ]: 0 : strprintf("New fee rate (%s) is lower than the minimum fee rate (%s) to get into the mempool -- ",
74 [ # # ]: 0 : FormatMoney(newFeerate.GetFeePerK()),
75 : 0 : FormatMoney(minMempoolFeeRate.GetFeePerK()))));
76 : 0 : return feebumper::Result::WALLET_ERROR;
77 : : }
78 : :
79 : 0 : std::vector<COutPoint> reused_inputs;
80 [ # # # # ]: 0 : reused_inputs.reserve(mtx.vin.size());
81 [ # # ]: 0 : for (const CTxIn& txin : mtx.vin) {
82 [ # # ]: 0 : reused_inputs.push_back(txin.prevout);
83 : : }
84 : :
85 [ # # ]: 0 : const std::optional<CAmount> combined_bump_fee = wallet.chain().calculateCombinedBumpFee(reused_inputs, newFeerate);
86 [ # # ]: 0 : if (!combined_bump_fee.has_value()) {
87 [ # # # # ]: 0 : errors.push_back(Untranslated(strprintf("Failed to calculate bump fees, because unconfirmed UTXOs depend on an enormous cluster of unconfirmed transactions.")));
88 : 0 : return feebumper::Result::WALLET_ERROR;
89 : : }
90 [ # # ]: 0 : CAmount new_total_fee = newFeerate.GetFee(maxTxSize) + combined_bump_fee.value();
91 : :
92 [ # # ]: 0 : CFeeRate incrementalRelayFee = wallet.chain().relayIncrementalFee();
93 : :
94 : : // Min total fee is old fee + relay fee
95 [ # # ]: 0 : CAmount minTotalFee = old_fee + incrementalRelayFee.GetFee(maxTxSize);
96 : :
97 [ # # ]: 0 : if (new_total_fee < minTotalFee) {
98 [ # # # # ]: 0 : errors.push_back(Untranslated(strprintf("Insufficient total fee %s, must be at least %s (oldFee %s + incrementalFee %s)",
99 [ # # # # : 0 : FormatMoney(new_total_fee), FormatMoney(minTotalFee), FormatMoney(old_fee), FormatMoney(incrementalRelayFee.GetFee(maxTxSize)))));
# # # # #
# ]
100 : 0 : return feebumper::Result::INVALID_PARAMETER;
101 : : }
102 : :
103 [ # # ]: 0 : CAmount requiredFee = GetRequiredFee(wallet, maxTxSize);
104 [ # # ]: 0 : if (new_total_fee < requiredFee) {
105 [ # # # # ]: 0 : errors.push_back(Untranslated(strprintf("Insufficient total fee (cannot be less than required fee %s)",
106 [ # # ]: 0 : FormatMoney(requiredFee))));
107 : 0 : return feebumper::Result::INVALID_PARAMETER;
108 : : }
109 : :
110 : : // Check that in all cases the new fee doesn't violate maxTxFee
111 : 0 : const CAmount max_tx_fee = wallet.m_default_max_tx_fee;
112 [ # # ]: 0 : if (new_total_fee > max_tx_fee) {
113 [ # # # # ]: 0 : errors.push_back(Untranslated(strprintf("Specified or calculated fee %s is too high (cannot be higher than -maxtxfee %s)",
114 [ # # # # ]: 0 : FormatMoney(new_total_fee), FormatMoney(max_tx_fee))));
115 : 0 : return feebumper::Result::WALLET_ERROR;
116 : : }
117 : :
118 : : return feebumper::Result::OK;
119 : 0 : }
120 : :
121 : 0 : static CFeeRate EstimateFeeRate(const CWallet& wallet, const CWalletTx& wtx, const CAmount old_fee, const CCoinControl& coin_control)
122 : : {
123 : : // Get the fee rate of the original transaction. This is calculated from
124 : : // the tx fee/vsize, so it may have been rounded down. Add 1 satoshi to the
125 : : // result.
126 [ # # # # ]: 0 : int64_t txSize = GetVirtualTransactionSize(*(wtx.GetTx()));
127 : 0 : CFeeRate feerate(old_fee, txSize);
128 : 0 : feerate += CFeeRate(1);
129 : :
130 : : // The node has a configurable incremental relay fee. Increment the fee by
131 : : // the minimum of that and the wallet's conservative
132 : : // WALLET_INCREMENTAL_RELAY_FEE value to future proof against changes to
133 : : // network wide policy for incremental relay fee that our node may not be
134 : : // aware of. This ensures we're over the required relay fee rate
135 : : // (Rule 4). The replacement tx will be at least as large as the
136 : : // original tx, so the total fee will be greater (Rule 3)
137 : 0 : CFeeRate node_incremental_relay_fee = wallet.chain().relayIncrementalFee();
138 : 0 : CFeeRate wallet_incremental_relay_fee = CFeeRate(WALLET_INCREMENTAL_RELAY_FEE);
139 : 0 : feerate += std::max(node_incremental_relay_fee, wallet_incremental_relay_fee);
140 : :
141 : : // Fee rate must also be at least the wallet's GetMinimumFeeRate
142 : 0 : CFeeRate min_feerate(GetMinimumFeeRate(wallet, coin_control, /*feeCalc=*/nullptr));
143 : :
144 : : // Set the required fee rate for the replacement transaction in coin control.
145 : 0 : return std::max(feerate, min_feerate);
146 : : }
147 : :
148 : : namespace feebumper {
149 : :
150 : 0 : bool TransactionCanBeBumped(const CWallet& wallet, const Txid& txid)
151 : : {
152 : 0 : LOCK(wallet.cs_wallet);
153 [ # # ]: 0 : const CWalletTx* wtx = wallet.GetWalletTx(txid);
154 [ # # ]: 0 : if (wtx == nullptr) return false;
155 : :
156 : 0 : std::vector<bilingual_str> errors_dummy;
157 [ # # ]: 0 : feebumper::Result res = PreconditionChecks(wallet, *wtx, /* require_mine=*/ true, errors_dummy);
158 : 0 : return res == feebumper::Result::OK;
159 : 0 : }
160 : :
161 : 0 : Result CreateRateBumpTransaction(CWallet& wallet, const Txid& txid, const CCoinControl& coin_control, std::vector<bilingual_str>& errors,
162 : : CAmount& old_fee, CAmount& new_fee, CMutableTransaction& mtx, bool require_mine, const std::vector<CTxOut>& outputs, std::optional<uint32_t> original_change_index)
163 : : {
164 : : // For now, cannot specify both new outputs to use and an output index to send change
165 [ # # # # ]: 0 : if (!outputs.empty() && original_change_index.has_value()) {
166 [ # # # # ]: 0 : errors.emplace_back(Untranslated("The options 'outputs' and 'original_change_index' are incompatible. You can only either specify a new set of outputs, or designate a change output to be recycled."));
167 : 0 : return Result::INVALID_PARAMETER;
168 : : }
169 : :
170 : : // We are going to modify coin control later, copy to reuse
171 : 0 : CCoinControl new_coin_control(coin_control);
172 : :
173 [ # # ]: 0 : LOCK(wallet.cs_wallet);
174 : 0 : errors.clear();
175 : 0 : auto it = wallet.mapWallet.find(txid);
176 [ # # ]: 0 : if (it == wallet.mapWallet.end()) {
177 [ # # # # : 0 : errors.emplace_back(Untranslated("Invalid or non-wallet transaction id"));
# # ]
178 : 0 : return Result::INVALID_ADDRESS_OR_KEY;
179 : : }
180 [ # # ]: 0 : const CWalletTx& wtx = it->second;
181 [ # # ]: 0 : const CTransactionRef& tx = wtx.GetTx();
182 : :
183 : : // Make sure that original_change_index is valid
184 [ # # # # : 0 : if (original_change_index.has_value() && original_change_index.value() >= tx->vout.size()) {
# # ]
185 [ # # # # : 0 : errors.emplace_back(Untranslated("Change position is out of range"));
# # ]
186 : 0 : return Result::INVALID_PARAMETER;
187 : : }
188 : :
189 : : // Retrieve all of the UTXOs and add them to coin control
190 : : // While we're here, calculate the input amount
191 : 0 : std::map<COutPoint, Coin> coins;
192 : 0 : CAmount input_value = 0;
193 : 0 : std::vector<CTxOut> spent_outputs;
194 [ # # ]: 0 : for (const CTxIn& txin : tx->vin) {
195 [ # # ]: 0 : coins[txin.prevout]; // Create empty map entry keyed by prevout.
196 : : }
197 [ # # ]: 0 : wallet.chain().findCoins(coins);
198 [ # # ]: 0 : for (const CTxIn& txin : tx->vin) {
199 [ # # ]: 0 : const Coin& coin = coins.at(txin.prevout);
200 [ # # ]: 0 : if (coin.out.IsNull()) {
201 [ # # # # : 0 : errors.emplace_back(Untranslated(strprintf("%s:%u is already spent", txin.prevout.hash.GetHex(), txin.prevout.n)));
# # # # ]
202 : 0 : return Result::MISC_ERROR;
203 : : }
204 [ # # ]: 0 : PreselectedInput& preset_txin = new_coin_control.Select(txin.prevout);
205 [ # # # # ]: 0 : if (!wallet.IsMine(txin.prevout)) {
206 [ # # ]: 0 : preset_txin.SetTxOut(coin.out);
207 : : }
208 : 0 : input_value += coin.out.nValue;
209 [ # # ]: 0 : spent_outputs.push_back(coin.out);
210 : : }
211 : :
212 : : // Figure out if we need to compute the input weight, and do so if necessary
213 : 0 : PrecomputedTransactionData txdata;
214 [ # # ]: 0 : txdata.Init(*tx, std::move(spent_outputs), /* force=*/ true);
215 [ # # # # ]: 0 : for (unsigned int i = 0; i < tx->vin.size(); ++i) {
216 [ # # ]: 0 : const CTxIn& txin = tx->vin.at(i);
217 [ # # ]: 0 : const Coin& coin = coins.at(txin.prevout);
218 : :
219 [ # # # # ]: 0 : if (new_coin_control.IsExternalSelected(txin.prevout)) {
220 : : // For external inputs, we estimate the size using the size of this input
221 : 0 : int64_t input_weight = GetTransactionInputWeight(txin);
222 : : // Because signatures can have different sizes, we need to figure out all of the
223 : : // signature sizes and replace them with the max sized signature.
224 : : // In order to do this, we verify the script with a special SignatureChecker which
225 : : // will observe the signatures verified and record their sizes.
226 : 0 : SignatureWeights weights;
227 [ # # ]: 0 : TransactionSignatureChecker tx_checker(tx.get(), i, coin.out.nValue, txdata, MissingDataBehavior::FAIL);
228 [ # # ]: 0 : SignatureWeightChecker size_checker(weights, tx_checker);
229 [ # # ]: 0 : VerifyScript(txin.scriptSig, coin.out.scriptPubKey, &txin.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, size_checker);
230 : : // Add the difference between max and current to input_weight so that it represents the largest the input could be
231 [ # # ]: 0 : input_weight += weights.GetWeightDiffToMax();
232 [ # # ]: 0 : new_coin_control.SetInputWeight(txin.prevout, input_weight);
233 : 0 : }
234 : : }
235 : :
236 [ # # ]: 0 : Result result = PreconditionChecks(wallet, wtx, require_mine, errors);
237 [ # # ]: 0 : if (result != Result::OK) {
238 : : return result;
239 : : }
240 : :
241 : : // Calculate the old output amount.
242 : 0 : CAmount output_value = 0;
243 [ # # ]: 0 : for (const auto& old_output : tx->vout) {
244 : 0 : output_value += old_output.nValue;
245 : : }
246 : :
247 : 0 : old_fee = input_value - output_value;
248 : :
249 : : // Fill in recipients (and preserve a single change key if there
250 : : // is one). If outputs vector is non-empty, replace original
251 : : // outputs with its contents, otherwise use original outputs.
252 : 0 : std::vector<CRecipient> recipients;
253 : 0 : CAmount new_outputs_value = 0;
254 [ # # ]: 0 : const auto& txouts = outputs.empty() ? tx->vout : outputs;
255 [ # # # # ]: 0 : for (size_t i = 0; i < txouts.size(); ++i) {
256 [ # # ]: 0 : const CTxOut& output = txouts.at(i);
257 : 0 : CTxDestination dest;
258 [ # # ]: 0 : ExtractDestination(output.scriptPubKey, dest);
259 [ # # # # : 0 : if (original_change_index.has_value() ? original_change_index.value() == i : OutputIsChange(wallet, output)) {
# # ]
260 [ # # ]: 0 : new_coin_control.destChange = dest;
261 : : } else {
262 [ # # ]: 0 : CRecipient recipient = {dest, output.nValue, false};
263 [ # # ]: 0 : recipients.push_back(recipient);
264 : 0 : }
265 : 0 : new_outputs_value += output.nValue;
266 : 0 : }
267 : :
268 : : // If no recipients, means that we are sending coins to a change address
269 [ # # ]: 0 : if (recipients.empty()) {
270 : : // Just as a sanity check, ensure that the change address exist
271 [ # # ]: 0 : if (std::get_if<CNoDestination>(&new_coin_control.destChange)) {
272 [ # # # # : 0 : errors.emplace_back(Untranslated("Unable to create transaction. Transaction must have at least one recipient"));
# # ]
273 : 0 : return Result::INVALID_PARAMETER;
274 : : }
275 : :
276 : : // Add change as recipient with SFFO flag enabled, so fees are deduced from it.
277 : : // If the output differs from the original tx output (because the user customized it) a new change output will be created.
278 [ # # # # ]: 0 : recipients.emplace_back(CRecipient{new_coin_control.destChange, new_outputs_value, /*fSubtractFeeFromAmount=*/true});
279 : 0 : new_coin_control.destChange = CNoDestination();
280 : : }
281 : :
282 [ # # ]: 0 : if (coin_control.m_feerate) {
283 : : // The user provided a feeRate argument.
284 : : // We calculate this here to avoid compiler warning on the cs_wallet lock
285 : : // We need to make a temporary transaction with no input witnesses as the dummy signer expects them to be empty for external inputs
286 [ # # ]: 0 : CMutableTransaction temp_mtx{*tx};
287 [ # # ]: 0 : for (auto& txin : temp_mtx.vin) {
288 : 0 : txin.scriptSig.clear();
289 : 0 : txin.scriptWitness.SetNull();
290 : : }
291 [ # # ]: 0 : temp_mtx.vout = txouts;
292 [ # # # # ]: 0 : const int64_t maxTxSize{CalculateMaximumSignedTxSize(CTransaction(temp_mtx), &wallet, &new_coin_control).vsize};
293 [ # # ]: 0 : Result res = CheckFeeRate(wallet, temp_mtx, *new_coin_control.m_feerate, maxTxSize, old_fee, errors);
294 [ # # ]: 0 : if (res != Result::OK) {
295 : 0 : return res;
296 : : }
297 : 0 : } else {
298 : : // The user did not provide a feeRate argument
299 [ # # ]: 0 : new_coin_control.m_feerate = EstimateFeeRate(wallet, wtx, old_fee, new_coin_control);
300 : : }
301 : :
302 : : // Fill in required inputs we are double-spending(all of them)
303 : : // N.B.: bip125 doesn't require all the inputs in the replaced transaction to be
304 : : // used in the replacement transaction, but it's very important for wallets to make
305 : : // sure that happens. If not, it would be possible to bump a transaction A twice to
306 : : // A2 and A3 where A2 and A3 don't conflict (or alternatively bump A to A2 and A2
307 : : // to A3 where A and A3 don't conflict). If both later get confirmed then the sender
308 : : // has accidentally double paid.
309 [ # # ]: 0 : for (const auto& inputs : tx->vin) {
310 [ # # ]: 0 : new_coin_control.Select(COutPoint(inputs.prevout));
311 : : }
312 : 0 : new_coin_control.m_allow_other_inputs = true;
313 : :
314 : : // We cannot source new unconfirmed inputs(bip125 rule 2)
315 : 0 : new_coin_control.m_min_depth = 1;
316 : :
317 [ # # ]: 0 : auto res = CreateTransaction(wallet, recipients, /*change_pos=*/std::nullopt, new_coin_control, false);
318 [ # # ]: 0 : if (!res) {
319 : 0 : errors.emplace_back(Untranslated("Unable to create transaction.") + Untranslated(" ") + util::ErrorString(res));
[ # # # #
# # # # #
# # # #
# ]
320 : 0 : return Result::WALLET_ERROR;
321 : : }
322 : :
323 : 0 : const auto& txr = *res;
324 : : // Write back new fee if successful
325 : 0 : new_fee = txr.fee;
326 : :
327 : : // Write back transaction
328 [ # # ]: 0 : mtx = CMutableTransaction(*txr.tx);
329 : :
330 : 0 : return Result::OK;
331 : 0 : }
332 : :
333 : 0 : bool SignTransaction(CWallet& wallet, CMutableTransaction& mtx) {
334 : 0 : LOCK(wallet.cs_wallet);
335 : :
336 [ # # # # ]: 0 : if (wallet.IsWalletFlagSet(WALLET_FLAG_EXTERNAL_SIGNER)) {
337 : : // Make a blank psbt
338 [ # # ]: 0 : PartiallySignedTransaction psbtx(mtx);
339 : :
340 : : // First fill transaction with our data without signing,
341 : : // so external signers are not asked to sign more than once.
342 : 0 : bool complete;
343 [ # # ]: 0 : wallet.FillPSBT(psbtx, {.sign = false, .bip32_derivs = true}, complete);
344 [ # # ]: 0 : auto err{wallet.FillPSBT(psbtx, {.sign = true, .bip32_derivs = false}, complete)};
345 [ # # ]: 0 : if (err) return false;
346 [ # # ]: 0 : complete = FinalizeAndExtractPSBT(psbtx, mtx);
347 : 0 : return complete;
348 : 0 : } else {
349 [ # # ]: 0 : return wallet.SignTransaction(mtx);
350 : : }
351 : 0 : }
352 : :
353 : 0 : Result CommitTransaction(CWallet& wallet, const Txid& txid, CMutableTransaction&& mtx, std::vector<bilingual_str>& errors, Txid& bumped_txid)
354 : : {
355 : 0 : LOCK(wallet.cs_wallet);
356 [ # # ]: 0 : if (!errors.empty()) {
357 : : return Result::MISC_ERROR;
358 : : }
359 [ # # ]: 0 : auto it = txid.IsNull() ? wallet.mapWallet.end() : wallet.mapWallet.find(txid);
360 [ # # ]: 0 : if (it == wallet.mapWallet.end()) {
361 [ # # # # : 0 : errors.emplace_back(Untranslated("Invalid or non-wallet transaction id"));
# # ]
362 : 0 : return Result::MISC_ERROR;
363 : : }
364 [ # # ]: 0 : const CWalletTx& oldWtx = it->second;
365 : :
366 : : // make sure the transaction still has no descendants and hasn't been mined in the meantime
367 [ # # ]: 0 : Result result = PreconditionChecks(wallet, oldWtx, /* require_mine=*/ false, errors);
368 [ # # ]: 0 : if (result != Result::OK) {
369 : : return result;
370 : : }
371 : :
372 : : // commit/broadcast the tx
373 [ # # ]: 0 : CTransactionRef tx = MakeTransactionRef(std::move(mtx));
374 [ # # # # : 0 : wallet.CommitTransaction(tx, oldWtx.GetHash(), oldWtx.m_comment, oldWtx.m_comment_to, oldWtx.m_messages, oldWtx.m_payment_requests);
# # # # #
# ]
375 : :
376 : : // mark the original tx as bumped
377 [ # # ]: 0 : bumped_txid = tx->GetHash();
378 [ # # # # : 0 : if (!wallet.MarkReplaced(oldWtx.GetHash(), bumped_txid)) {
# # ]
379 [ # # # # : 0 : errors.emplace_back(Untranslated("Created new bumpfee transaction but could not mark the original transaction as replaced"));
# # ]
380 : : }
381 [ # # ]: 0 : return Result::OK;
382 : 0 : }
383 : :
384 : : } // namespace feebumper
385 : : } // namespace wallet
|