55e0171aa19b3aa493cf7b9ad1117d0840988ce4
[rust-lightning] / lightning / src / events / bump_transaction.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Utitilies for bumping transactions originating from [`super::Event`]s.
11
12 use core::convert::TryInto;
13 use core::ops::Deref;
14
15 use crate::chain::chaininterface::BroadcasterInterface;
16 use crate::chain::ClaimId;
17 use crate::sign::{ChannelSigner, EcdsaChannelSigner, SignerProvider};
18 use crate::io_extras::sink;
19 use crate::ln::PaymentPreimage;
20 use crate::ln::chan_utils;
21 use crate::ln::chan_utils::{
22         ANCHOR_INPUT_WITNESS_WEIGHT, HTLC_SUCCESS_INPUT_ANCHOR_WITNESS_WEIGHT,
23         HTLC_TIMEOUT_INPUT_ANCHOR_WITNESS_WEIGHT, ChannelTransactionParameters, HTLCOutputInCommitment
24 };
25 use crate::events::Event;
26 use crate::prelude::HashMap;
27 use crate::util::logger::Logger;
28
29 use bitcoin::{OutPoint, PackedLockTime, PubkeyHash, Sequence, Script, Transaction, Txid, TxIn, TxOut, Witness, WPubkeyHash};
30 use bitcoin::blockdata::constants::WITNESS_SCALE_FACTOR;
31 use bitcoin::consensus::Encodable;
32 use bitcoin::secp256k1;
33 use bitcoin::secp256k1::{PublicKey, Secp256k1};
34 use bitcoin::secp256k1::ecdsa::Signature;
35
36 const EMPTY_SCRIPT_SIG_WEIGHT: u64 = 1 /* empty script_sig */ * WITNESS_SCALE_FACTOR as u64;
37
38 const BASE_INPUT_SIZE: u64 = 32 /* txid */ + 4 /* vout */ + 4 /* sequence */;
39
40 const BASE_INPUT_WEIGHT: u64 = BASE_INPUT_SIZE * WITNESS_SCALE_FACTOR as u64;
41
42 // TODO: Define typed abstraction over feerates to handle their conversions.
43 fn compute_feerate_sat_per_1000_weight(fee_sat: u64, weight: u64) -> u32 {
44         (fee_sat * 1000 / weight).try_into().unwrap_or(u32::max_value())
45 }
46 const fn fee_for_weight(feerate_sat_per_1000_weight: u32, weight: u64) -> u64 {
47         ((feerate_sat_per_1000_weight as u64 * weight) + 1000 - 1) / 1000
48 }
49
50 /// A descriptor used to sign for a commitment transaction's anchor output.
51 #[derive(Clone, Debug, PartialEq, Eq)]
52 pub struct AnchorDescriptor {
53         /// A unique identifier used along with `channel_value_satoshis` to re-derive the
54         /// [`InMemorySigner`] required to sign `input`.
55         ///
56         /// [`InMemorySigner`]: crate::sign::InMemorySigner
57         pub channel_keys_id: [u8; 32],
58         /// The value in satoshis of the channel we're attempting to spend the anchor output of. This is
59         /// used along with `channel_keys_id` to re-derive the [`InMemorySigner`] required to sign
60         /// `input`.
61         ///
62         /// [`InMemorySigner`]: crate::sign::InMemorySigner
63         pub channel_value_satoshis: u64,
64         /// The transaction input's outpoint corresponding to the commitment transaction's anchor
65         /// output.
66         pub outpoint: OutPoint,
67 }
68
69 /// A descriptor used to sign for a commitment transaction's HTLC output.
70 #[derive(Clone, Debug, PartialEq, Eq)]
71 pub struct HTLCDescriptor {
72         /// A unique identifier used along with `channel_value_satoshis` to re-derive the
73         /// [`InMemorySigner`] required to sign `input`.
74         ///
75         /// [`InMemorySigner`]: crate::sign::InMemorySigner
76         pub channel_keys_id: [u8; 32],
77         /// The value in satoshis of the channel we're attempting to spend the anchor output of. This is
78         /// used along with `channel_keys_id` to re-derive the [`InMemorySigner`] required to sign
79         /// `input`.
80         ///
81         /// [`InMemorySigner`]: crate::sign::InMemorySigner
82         pub channel_value_satoshis: u64,
83         /// The necessary channel parameters that need to be provided to the re-derived
84         /// [`InMemorySigner`] through [`ChannelSigner::provide_channel_parameters`].
85         ///
86         /// [`InMemorySigner`]: crate::sign::InMemorySigner
87         /// [`ChannelSigner::provide_channel_parameters`]: crate::sign::ChannelSigner::provide_channel_parameters
88         pub channel_parameters: ChannelTransactionParameters,
89         /// The txid of the commitment transaction in which the HTLC output lives.
90         pub commitment_txid: Txid,
91         /// The number of the commitment transaction in which the HTLC output lives.
92         pub per_commitment_number: u64,
93         /// The details of the HTLC as it appears in the commitment transaction.
94         pub htlc: HTLCOutputInCommitment,
95         /// The preimage, if `Some`, to claim the HTLC output with. If `None`, the timeout path must be
96         /// taken.
97         pub preimage: Option<PaymentPreimage>,
98         /// The counterparty's signature required to spend the HTLC output.
99         pub counterparty_sig: Signature
100 }
101
102 impl HTLCDescriptor {
103         /// Returns the unsigned transaction input spending the HTLC output in the commitment
104         /// transaction.
105         pub fn unsigned_tx_input(&self) -> TxIn {
106                 chan_utils::build_htlc_input(&self.commitment_txid, &self.htlc, true /* opt_anchors */)
107         }
108
109         /// Returns the delayed output created as a result of spending the HTLC output in the commitment
110         /// transaction.
111         pub fn tx_output<C: secp256k1::Signing + secp256k1::Verification>(
112                 &self, per_commitment_point: &PublicKey, secp: &Secp256k1<C>
113         ) -> TxOut {
114                 let channel_params = self.channel_parameters.as_holder_broadcastable();
115                 let broadcaster_keys = channel_params.broadcaster_pubkeys();
116                 let counterparty_keys = channel_params.countersignatory_pubkeys();
117                 let broadcaster_delayed_key = chan_utils::derive_public_key(
118                         secp, per_commitment_point, &broadcaster_keys.delayed_payment_basepoint
119                 );
120                 let counterparty_revocation_key = chan_utils::derive_public_revocation_key(
121                         secp, per_commitment_point, &counterparty_keys.revocation_basepoint
122                 );
123                 chan_utils::build_htlc_output(
124                         0 /* feerate_per_kw */, channel_params.contest_delay(), &self.htlc, true /* opt_anchors */,
125                         false /* use_non_zero_fee_anchors */, &broadcaster_delayed_key, &counterparty_revocation_key
126                 )
127         }
128
129         /// Returns the witness script of the HTLC output in the commitment transaction.
130         pub fn witness_script<C: secp256k1::Signing + secp256k1::Verification>(
131                 &self, per_commitment_point: &PublicKey, secp: &Secp256k1<C>
132         ) -> Script {
133                 let channel_params = self.channel_parameters.as_holder_broadcastable();
134                 let broadcaster_keys = channel_params.broadcaster_pubkeys();
135                 let counterparty_keys = channel_params.countersignatory_pubkeys();
136                 let broadcaster_htlc_key = chan_utils::derive_public_key(
137                         secp, per_commitment_point, &broadcaster_keys.htlc_basepoint
138                 );
139                 let counterparty_htlc_key = chan_utils::derive_public_key(
140                         secp, per_commitment_point, &counterparty_keys.htlc_basepoint
141                 );
142                 let counterparty_revocation_key = chan_utils::derive_public_revocation_key(
143                         secp, per_commitment_point, &counterparty_keys.revocation_basepoint
144                 );
145                 chan_utils::get_htlc_redeemscript_with_explicit_keys(
146                         &self.htlc, true /* opt_anchors */, &broadcaster_htlc_key, &counterparty_htlc_key,
147                         &counterparty_revocation_key,
148                 )
149         }
150
151         /// Returns the fully signed witness required to spend the HTLC output in the commitment
152         /// transaction.
153         pub fn tx_input_witness(&self, signature: &Signature, witness_script: &Script) -> Witness {
154                 chan_utils::build_htlc_input_witness(
155                         signature, &self.counterparty_sig, &self.preimage, witness_script, true /* opt_anchors */
156                 )
157         }
158 }
159
160 /// Represents the different types of transactions, originating from LDK, to be bumped.
161 #[derive(Clone, Debug, PartialEq, Eq)]
162 pub enum BumpTransactionEvent {
163         /// Indicates that a channel featuring anchor outputs is to be closed by broadcasting the local
164         /// commitment transaction. Since commitment transactions have a static feerate pre-agreed upon,
165         /// they may need additional fees to be attached through a child transaction using the popular
166         /// [Child-Pays-For-Parent](https://bitcoinops.org/en/topics/cpfp) fee bumping technique. This
167         /// child transaction must include the anchor input described within `anchor_descriptor` along
168         /// with additional inputs to meet the target feerate. Failure to meet the target feerate
169         /// decreases the confirmation odds of the transaction package (which includes the commitment
170         /// and child anchor transactions), possibly resulting in a loss of funds. Once the transaction
171         /// is constructed, it must be fully signed for and broadcast by the consumer of the event
172         /// along with the `commitment_tx` enclosed. Note that the `commitment_tx` must always be
173         /// broadcast first, as the child anchor transaction depends on it.
174         ///
175         /// The consumer should be able to sign for any of the additional inputs included within the
176         /// child anchor transaction. To sign its anchor input, an [`InMemorySigner`] should be
177         /// re-derived through [`KeysManager::derive_channel_keys`] with the help of
178         /// [`AnchorDescriptor::channel_keys_id`] and [`AnchorDescriptor::channel_value_satoshis`]. The
179         /// anchor input signature can be computed with [`EcdsaChannelSigner::sign_holder_anchor_input`],
180         /// which can then be provided to [`build_anchor_input_witness`] along with the `funding_pubkey`
181         /// to obtain the full witness required to spend.
182         ///
183         /// It is possible to receive more than one instance of this event if a valid child anchor
184         /// transaction is never broadcast or is but not with a sufficient fee to be mined. Care should
185         /// be taken by the consumer of the event to ensure any future iterations of the child anchor
186         /// transaction adhere to the [Replace-By-Fee
187         /// rules](https://github.com/bitcoin/bitcoin/blob/master/doc/policy/mempool-replacements.md)
188         /// for fee bumps to be accepted into the mempool, and eventually the chain. As the frequency of
189         /// these events is not user-controlled, users may ignore/drop the event if they are no longer
190         /// able to commit external confirmed funds to the child anchor transaction.
191         ///
192         /// The set of `pending_htlcs` on the commitment transaction to be broadcast can be inspected to
193         /// determine whether a significant portion of the channel's funds are allocated to HTLCs,
194         /// enabling users to make their own decisions regarding the importance of the commitment
195         /// transaction's confirmation. Note that this is not required, but simply exists as an option
196         /// for users to override LDK's behavior. On commitments with no HTLCs (indicated by those with
197         /// an empty `pending_htlcs`), confirmation of the commitment transaction can be considered to
198         /// be not urgent.
199         ///
200         /// [`InMemorySigner`]: crate::sign::InMemorySigner
201         /// [`KeysManager::derive_channel_keys`]: crate::sign::KeysManager::derive_channel_keys
202         /// [`EcdsaChannelSigner::sign_holder_anchor_input`]: crate::sign::EcdsaChannelSigner::sign_holder_anchor_input
203         /// [`build_anchor_input_witness`]: crate::ln::chan_utils::build_anchor_input_witness
204         ChannelClose {
205                 /// The unique identifier for the claim of the anchor output in the commitment transaction.
206                 ///
207                 /// The identifier must map to the set of external UTXOs assigned to the claim, such that
208                 /// they can be reused when a new claim with the same identifier needs to be made, resulting
209                 /// in a fee-bumping attempt.
210                 claim_id: ClaimId,
211                 /// The target feerate that the transaction package, which consists of the commitment
212                 /// transaction and the to-be-crafted child anchor transaction, must meet.
213                 package_target_feerate_sat_per_1000_weight: u32,
214                 /// The channel's commitment transaction to bump the fee of. This transaction should be
215                 /// broadcast along with the anchor transaction constructed as a result of consuming this
216                 /// event.
217                 commitment_tx: Transaction,
218                 /// The absolute fee in satoshis of the commitment transaction. This can be used along the
219                 /// with weight of the commitment transaction to determine its feerate.
220                 commitment_tx_fee_satoshis: u64,
221                 /// The descriptor to sign the anchor input of the anchor transaction constructed as a
222                 /// result of consuming this event.
223                 anchor_descriptor: AnchorDescriptor,
224                 /// The set of pending HTLCs on the commitment transaction that need to be resolved once the
225                 /// commitment transaction confirms.
226                 pending_htlcs: Vec<HTLCOutputInCommitment>,
227         },
228         /// Indicates that a channel featuring anchor outputs has unilaterally closed on-chain by a
229         /// holder commitment transaction and its HTLC(s) need to be resolved on-chain. With the
230         /// zero-HTLC-transaction-fee variant of anchor outputs, the pre-signed HTLC
231         /// transactions have a zero fee, thus requiring additional inputs and/or outputs to be attached
232         /// for a timely confirmation within the chain. These additional inputs and/or outputs must be
233         /// appended to the resulting HTLC transaction to meet the target feerate. Failure to meet the
234         /// target feerate decreases the confirmation odds of the transaction, possibly resulting in a
235         /// loss of funds. Once the transaction meets the target feerate, it must be signed for and
236         /// broadcast by the consumer of the event.
237         ///
238         /// The consumer should be able to sign for any of the non-HTLC inputs added to the resulting
239         /// HTLC transaction. To sign HTLC inputs, an [`InMemorySigner`] should be re-derived through
240         /// [`KeysManager::derive_channel_keys`] with the help of `channel_keys_id` and
241         /// `channel_value_satoshis`. Each HTLC input's signature can be computed with
242         /// [`EcdsaChannelSigner::sign_holder_htlc_transaction`], which can then be provided to
243         /// [`HTLCDescriptor::tx_input_witness`] to obtain the fully signed witness required to spend.
244         ///
245         /// It is possible to receive more than one instance of this event if a valid HTLC transaction
246         /// is never broadcast or is but not with a sufficient fee to be mined. Care should be taken by
247         /// the consumer of the event to ensure any future iterations of the HTLC transaction adhere to
248         /// the [Replace-By-Fee
249         /// rules](https://github.com/bitcoin/bitcoin/blob/master/doc/policy/mempool-replacements.md)
250         /// for fee bumps to be accepted into the mempool, and eventually the chain. As the frequency of
251         /// these events is not user-controlled, users may ignore/drop the event if either they are no
252         /// longer able to commit external confirmed funds to the HTLC transaction or the fee committed
253         /// to the HTLC transaction is greater in value than the HTLCs being claimed.
254         ///
255         /// [`InMemorySigner`]: crate::sign::InMemorySigner
256         /// [`KeysManager::derive_channel_keys`]: crate::sign::KeysManager::derive_channel_keys
257         /// [`EcdsaChannelSigner::sign_holder_htlc_transaction`]: crate::sign::EcdsaChannelSigner::sign_holder_htlc_transaction
258         /// [`HTLCDescriptor::tx_input_witness`]: HTLCDescriptor::tx_input_witness
259         HTLCResolution {
260                 /// The unique identifier for the claim of the HTLCs in the confirmed commitment
261                 /// transaction.
262                 ///
263                 /// The identifier must map to the set of external UTXOs assigned to the claim, such that
264                 /// they can be reused when a new claim with the same identifier needs to be made, resulting
265                 /// in a fee-bumping attempt.
266                 claim_id: ClaimId,
267                 /// The target feerate that the resulting HTLC transaction must meet.
268                 target_feerate_sat_per_1000_weight: u32,
269                 /// The set of pending HTLCs on the confirmed commitment that need to be claimed, preferably
270                 /// by the same transaction.
271                 htlc_descriptors: Vec<HTLCDescriptor>,
272                 /// The locktime required for the resulting HTLC transaction.
273                 tx_lock_time: PackedLockTime,
274         },
275 }
276
277 /// An input that must be included in a transaction when performing coin selection through
278 /// [`CoinSelectionSource::select_confirmed_utxos`]. It is guaranteed to be a SegWit input, so it
279 /// must have an empty [`TxIn::script_sig`] when spent.
280 pub struct Input {
281         /// The unique identifier of the input.
282         pub outpoint: OutPoint,
283         /// The upper-bound weight consumed by the input's full [`TxIn::script_sig`] and
284         /// [`TxIn::witness`], each with their lengths included, required to satisfy the output's
285         /// script.
286         pub satisfaction_weight: u64,
287 }
288
289 /// An unspent transaction output that is available to spend resulting from a successful
290 /// [`CoinSelection`] attempt.
291 #[derive(Clone, Debug)]
292 pub struct Utxo {
293         /// The unique identifier of the output.
294         pub outpoint: OutPoint,
295         /// The output to spend.
296         pub output: TxOut,
297         /// The upper-bound weight consumed by the input's full [`TxIn::script_sig`] and [`TxIn::witness`], each
298         /// with their lengths included, required to satisfy the output's script. The weight consumed by
299         /// the input's `script_sig` must account for [`WITNESS_SCALE_FACTOR`].
300         pub satisfaction_weight: u64,
301 }
302
303 impl Utxo {
304         const P2WPKH_WITNESS_WEIGHT: u64 = 1 /* num stack items */ +
305                 1 /* sig length */ +
306                 73 /* sig including sighash flag */ +
307                 1 /* pubkey length */ +
308                 33 /* pubkey */;
309
310         /// Returns a `Utxo` with the `satisfaction_weight` estimate for a legacy P2PKH output.
311         pub fn new_p2pkh(outpoint: OutPoint, value: u64, pubkey_hash: &PubkeyHash) -> Self {
312                 let script_sig_size = 1 /* script_sig length */ +
313                         1 /* OP_PUSH73 */ +
314                         73 /* sig including sighash flag */ +
315                         1 /* OP_PUSH33 */ +
316                         33 /* pubkey */;
317                 Self {
318                         outpoint,
319                         output: TxOut {
320                                 value,
321                                 script_pubkey: Script::new_p2pkh(pubkey_hash),
322                         },
323                         satisfaction_weight: script_sig_size * WITNESS_SCALE_FACTOR as u64 + 1 /* empty witness */,
324                 }
325         }
326
327         /// Returns a `Utxo` with the `satisfaction_weight` estimate for a P2WPKH nested in P2SH output.
328         pub fn new_nested_p2wpkh(outpoint: OutPoint, value: u64, pubkey_hash: &WPubkeyHash) -> Self {
329                 let script_sig_size = 1 /* script_sig length */ +
330                         1 /* OP_0 */ +
331                         1 /* OP_PUSH20 */ +
332                         20 /* pubkey_hash */;
333                 Self {
334                         outpoint,
335                         output: TxOut {
336                                 value,
337                                 script_pubkey: Script::new_p2sh(&Script::new_v0_p2wpkh(pubkey_hash).script_hash()),
338                         },
339                         satisfaction_weight: script_sig_size * WITNESS_SCALE_FACTOR as u64 + Self::P2WPKH_WITNESS_WEIGHT,
340                 }
341         }
342
343         /// Returns a `Utxo` with the `satisfaction_weight` estimate for a SegWit v0 P2WPKH output.
344         pub fn new_v0_p2wpkh(outpoint: OutPoint, value: u64, pubkey_hash: &WPubkeyHash) -> Self {
345                 Self {
346                         outpoint,
347                         output: TxOut {
348                                 value,
349                                 script_pubkey: Script::new_v0_p2wpkh(pubkey_hash),
350                         },
351                         satisfaction_weight: EMPTY_SCRIPT_SIG_WEIGHT + Self::P2WPKH_WITNESS_WEIGHT,
352                 }
353         }
354 }
355
356 /// The result of a successful coin selection attempt for a transaction requiring additional UTXOs
357 /// to cover its fees.
358 pub struct CoinSelection {
359         /// The set of UTXOs (with at least 1 confirmation) to spend and use within a transaction
360         /// requiring additional fees.
361         confirmed_utxos: Vec<Utxo>,
362         /// An additional output tracking whether any change remained after coin selection. This output
363         /// should always have a value above dust for its given `script_pubkey`. It should not be
364         /// spent until the transaction it belongs to confirms to ensure mempool descendant limits are
365         /// not met. This implies no other party should be able to spend it except us.
366         change_output: Option<TxOut>,
367 }
368
369 /// An abstraction over a bitcoin wallet that can perform coin selection over a set of UTXOs and can
370 /// sign for them. The coin selection method aims to mimic Bitcoin Core's `fundrawtransaction` RPC,
371 /// which most wallets should be able to satisfy.
372 pub trait CoinSelectionSource {
373         /// Performs coin selection of a set of UTXOs, with at least 1 confirmation each, that are
374         /// available to spend. Implementations are free to pick their coin selection algorithm of
375         /// choice, as long as the following requirements are met:
376         ///
377         /// 1. `must_spend` contains a set of [`Input`]s that must be included in the transaction
378         ///    throughout coin selection, but must not be returned as part of the result.
379         /// 2. `must_pay_to` contains a set of [`TxOut`]s that must be included in the transaction
380         ///    throughout coin selection. In some cases, like when funding an anchor transaction, this
381         ///    set is empty. Implementations should ensure they handle this correctly on their end,
382         ///    e.g., Bitcoin Core's `fundrawtransaction` RPC requires at least one output to be
383         ///    provided, in which case a zero-value empty OP_RETURN output can be used instead.
384         /// 3. Enough inputs must be selected/contributed for the resulting transaction (including the
385         ///    inputs and outputs noted above) to meet `target_feerate_sat_per_1000_weight`.
386         ///
387         /// Implementations must take note that [`Input::satisfaction_weight`] only tracks the weight of
388         /// the input's `script_sig` and `witness`. Some wallets, like Bitcoin Core's, may require
389         /// providing the full input weight. Failing to do so may lead to underestimating fee bumps and
390         /// delaying block inclusion.
391         ///
392         /// The `claim_id` must map to the set of external UTXOs assigned to the claim, such that they
393         /// can be re-used within new fee-bumped iterations of the original claiming transaction,
394         /// ensuring that claims don't double spend each other. If a specific `claim_id` has never had a
395         /// transaction associated with it, and all of the available UTXOs have already been assigned to
396         /// other claims, implementations must be willing to double spend their UTXOs. The choice of
397         /// which UTXOs to double spend is left to the implementation, but it must strive to keep the
398         /// set of other claims being double spent to a minimum.
399         fn select_confirmed_utxos(
400                 &self, claim_id: ClaimId, must_spend: &[Input], must_pay_to: &[TxOut],
401                 target_feerate_sat_per_1000_weight: u32,
402         ) -> Result<CoinSelection, ()>;
403         /// Signs and provides the full witness for all inputs within the transaction known to the
404         /// trait (i.e., any provided via [`CoinSelectionSource::select_confirmed_utxos`]).
405         fn sign_tx(&self, tx: &mut Transaction) -> Result<(), ()>;
406 }
407
408 /// A handler for [`Event::BumpTransaction`] events that sources confirmed UTXOs from a
409 /// [`CoinSelectionSource`] to fee bump transactions via Child-Pays-For-Parent (CPFP) or
410 /// Replace-By-Fee (RBF).
411 pub struct BumpTransactionEventHandler<B: Deref, C: Deref, SP: Deref, L: Deref>
412 where
413         B::Target: BroadcasterInterface,
414         C::Target: CoinSelectionSource,
415         SP::Target: SignerProvider,
416         L::Target: Logger,
417 {
418         broadcaster: B,
419         utxo_source: C,
420         signer_provider: SP,
421         logger: L,
422         secp: Secp256k1<secp256k1::All>,
423 }
424
425 impl<B: Deref, C: Deref, SP: Deref, L: Deref> BumpTransactionEventHandler<B, C, SP, L>
426 where
427         B::Target: BroadcasterInterface,
428         C::Target: CoinSelectionSource,
429         SP::Target: SignerProvider,
430         L::Target: Logger,
431 {
432         /// Returns a new instance capable of handling [`Event::BumpTransaction`] events.
433         pub fn new(broadcaster: B, utxo_source: C, signer_provider: SP, logger: L) -> Self {
434                 Self {
435                         broadcaster,
436                         utxo_source,
437                         signer_provider,
438                         logger,
439                         secp: Secp256k1::new(),
440                 }
441         }
442
443         /// Updates a transaction with the result of a successful coin selection attempt.
444         fn process_coin_selection(&self, tx: &mut Transaction, mut coin_selection: CoinSelection) {
445                 for utxo in coin_selection.confirmed_utxos.drain(..) {
446                         tx.input.push(TxIn {
447                                 previous_output: utxo.outpoint,
448                                 script_sig: Script::new(),
449                                 sequence: Sequence::ZERO,
450                                 witness: Witness::new(),
451                         });
452                 }
453                 if let Some(change_output) = coin_selection.change_output.take() {
454                         tx.output.push(change_output);
455                 } else if tx.output.is_empty() {
456                         // We weren't provided a change output, likely because the input set was a perfect
457                         // match, but we still need to have at least one output in the transaction for it to be
458                         // considered standard. We choose to go with an empty OP_RETURN as it is the cheapest
459                         // way to include a dummy output.
460                         tx.output.push(TxOut {
461                                 value: 0,
462                                 script_pubkey: Script::new_op_return(&[]),
463                         });
464                 }
465         }
466
467         /// Returns an unsigned transaction spending an anchor output of the commitment transaction, and
468         /// any additional UTXOs sourced, to bump the commitment transaction's fee.
469         fn build_anchor_tx(
470                 &self, claim_id: ClaimId, target_feerate_sat_per_1000_weight: u32,
471                 commitment_tx: &Transaction, anchor_descriptor: &AnchorDescriptor,
472         ) -> Result<Transaction, ()> {
473                 let must_spend = vec![Input {
474                         outpoint: anchor_descriptor.outpoint,
475                         satisfaction_weight: commitment_tx.weight() as u64 + ANCHOR_INPUT_WITNESS_WEIGHT + EMPTY_SCRIPT_SIG_WEIGHT,
476                 }];
477                 let coin_selection = self.utxo_source.select_confirmed_utxos(
478                         claim_id, &must_spend, &[], target_feerate_sat_per_1000_weight,
479                 )?;
480
481                 let mut tx = Transaction {
482                         version: 2,
483                         lock_time: PackedLockTime::ZERO, // TODO: Use next best height.
484                         input: vec![TxIn {
485                                 previous_output: anchor_descriptor.outpoint,
486                                 script_sig: Script::new(),
487                                 sequence: Sequence::ZERO,
488                                 witness: Witness::new(),
489                         }],
490                         output: vec![],
491                 };
492                 self.process_coin_selection(&mut tx, coin_selection);
493                 Ok(tx)
494         }
495
496         /// Handles a [`BumpTransactionEvent::ChannelClose`] event variant by producing a fully-signed
497         /// transaction spending an anchor output of the commitment transaction to bump its fee and
498         /// broadcasts them to the network as a package.
499         fn handle_channel_close(
500                 &self, claim_id: ClaimId, package_target_feerate_sat_per_1000_weight: u32,
501                 commitment_tx: &Transaction, commitment_tx_fee_sat: u64, anchor_descriptor: &AnchorDescriptor,
502         ) -> Result<(), ()> {
503                 // Compute the feerate the anchor transaction must meet to meet the overall feerate for the
504                 // package (commitment + anchor transactions).
505                 let commitment_tx_sat_per_1000_weight: u32 = compute_feerate_sat_per_1000_weight(
506                         commitment_tx_fee_sat, commitment_tx.weight() as u64,
507                 );
508                 if commitment_tx_sat_per_1000_weight >= package_target_feerate_sat_per_1000_weight {
509                         // If the commitment transaction already has a feerate high enough on its own, broadcast
510                         // it as is without a child.
511                         self.broadcaster.broadcast_transactions(&[&commitment_tx]);
512                         return Ok(());
513                 }
514
515                 let mut anchor_tx = self.build_anchor_tx(
516                         claim_id, package_target_feerate_sat_per_1000_weight, commitment_tx, anchor_descriptor,
517                 )?;
518                 debug_assert_eq!(anchor_tx.output.len(), 1);
519
520                 self.utxo_source.sign_tx(&mut anchor_tx)?;
521                 let signer = self.signer_provider.derive_channel_signer(
522                         anchor_descriptor.channel_value_satoshis, anchor_descriptor.channel_keys_id,
523                 );
524                 let anchor_sig = signer.sign_holder_anchor_input(&anchor_tx, 0, &self.secp)?;
525                 anchor_tx.input[0].witness =
526                         chan_utils::build_anchor_input_witness(&signer.pubkeys().funding_pubkey, &anchor_sig);
527
528                 self.broadcaster.broadcast_transactions(&[&commitment_tx, &anchor_tx]);
529                 Ok(())
530         }
531
532         /// Returns an unsigned, fee-bumped HTLC transaction, along with the set of signers required to
533         /// fulfill the witness for each HTLC input within it.
534         fn build_htlc_tx(
535                 &self, claim_id: ClaimId, target_feerate_sat_per_1000_weight: u32,
536                 htlc_descriptors: &[HTLCDescriptor], tx_lock_time: PackedLockTime,
537         ) -> Result<(Transaction, HashMap<[u8; 32], <SP::Target as SignerProvider>::Signer>), ()> {
538                 let mut tx = Transaction {
539                         version: 2,
540                         lock_time: tx_lock_time,
541                         input: vec![],
542                         output: vec![],
543                 };
544                 // Unfortunately, we need to derive the signer for each HTLC ahead of time to obtain its
545                 // input.
546                 let mut signers = HashMap::new();
547                 let mut must_spend = Vec::with_capacity(htlc_descriptors.len());
548                 for htlc_descriptor in htlc_descriptors {
549                         let signer = signers.entry(htlc_descriptor.channel_keys_id)
550                                 .or_insert_with(||
551                                         self.signer_provider.derive_channel_signer(
552                                                 htlc_descriptor.channel_value_satoshis, htlc_descriptor.channel_keys_id,
553                                         )
554                                 );
555                         let per_commitment_point = signer.get_per_commitment_point(
556                                 htlc_descriptor.per_commitment_number, &self.secp
557                         );
558
559                         let htlc_input = htlc_descriptor.unsigned_tx_input();
560                         must_spend.push(Input {
561                                 outpoint: htlc_input.previous_output.clone(),
562                                 satisfaction_weight: EMPTY_SCRIPT_SIG_WEIGHT + if htlc_descriptor.preimage.is_some() {
563                                         HTLC_SUCCESS_INPUT_ANCHOR_WITNESS_WEIGHT
564                                 } else {
565                                         HTLC_TIMEOUT_INPUT_ANCHOR_WITNESS_WEIGHT
566                                 },
567                         });
568                         tx.input.push(htlc_input);
569                         let htlc_output = htlc_descriptor.tx_output(&per_commitment_point, &self.secp);
570                         tx.output.push(htlc_output);
571                 }
572
573                 let coin_selection = self.utxo_source.select_confirmed_utxos(
574                         claim_id, &must_spend, &tx.output, target_feerate_sat_per_1000_weight,
575                 )?;
576                 self.process_coin_selection(&mut tx, coin_selection);
577                 Ok((tx, signers))
578         }
579
580         /// Handles a [`BumpTransactionEvent::HTLCResolution`] event variant by producing a
581         /// fully-signed, fee-bumped HTLC transaction that is broadcast to the network.
582         fn handle_htlc_resolution(
583                 &self, claim_id: ClaimId, target_feerate_sat_per_1000_weight: u32,
584                 htlc_descriptors: &[HTLCDescriptor], tx_lock_time: PackedLockTime,
585         ) -> Result<(), ()> {
586                 let (mut htlc_tx, signers) = self.build_htlc_tx(
587                         claim_id, target_feerate_sat_per_1000_weight, htlc_descriptors, tx_lock_time,
588                 )?;
589
590                 self.utxo_source.sign_tx(&mut htlc_tx)?;
591                 for (idx, htlc_descriptor) in htlc_descriptors.iter().enumerate() {
592                         let signer = signers.get(&htlc_descriptor.channel_keys_id).unwrap();
593                         let htlc_sig = signer.sign_holder_htlc_transaction(
594                                 &htlc_tx, idx, htlc_descriptor, &self.secp
595                         )?;
596                         let per_commitment_point = signer.get_per_commitment_point(
597                                 htlc_descriptor.per_commitment_number, &self.secp
598                         );
599                         let witness_script = htlc_descriptor.witness_script(&per_commitment_point, &self.secp);
600                         htlc_tx.input[idx].witness = htlc_descriptor.tx_input_witness(&htlc_sig, &witness_script);
601                 }
602
603                 self.broadcaster.broadcast_transactions(&[&htlc_tx]);
604                 Ok(())
605         }
606
607         /// Handles all variants of [`BumpTransactionEvent`], immediately returning otherwise.
608         pub fn handle_event(&self, event: &Event) {
609                 let event = if let Event::BumpTransaction(event) = event {
610                         event
611                 } else {
612                         return;
613                 };
614                 match event {
615                         BumpTransactionEvent::ChannelClose {
616                                 claim_id, package_target_feerate_sat_per_1000_weight, commitment_tx,
617                                 anchor_descriptor, commitment_tx_fee_satoshis,  ..
618                         } => {
619                                 if let Err(_) = self.handle_channel_close(
620                                         *claim_id, *package_target_feerate_sat_per_1000_weight, commitment_tx,
621                                         *commitment_tx_fee_satoshis, anchor_descriptor,
622                                 ) {
623                                         log_error!(self.logger, "Failed bumping commitment transaction fee for {}",
624                                                 commitment_tx.txid());
625                                 }
626                         }
627                         BumpTransactionEvent::HTLCResolution {
628                                 claim_id, target_feerate_sat_per_1000_weight, htlc_descriptors, tx_lock_time,
629                         } => {
630                                 if let Err(_) = self.handle_htlc_resolution(
631                                         *claim_id, *target_feerate_sat_per_1000_weight, htlc_descriptors, *tx_lock_time,
632                                 ) {
633                                         log_error!(self.logger, "Failed bumping HTLC transaction fee for commitment {}",
634                                                 htlc_descriptors[0].commitment_txid);
635                                 }
636                         }
637                 }
638         }
639 }