Expose ClaimId for each claim bump in BumpTransactionEvent
[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 crate::chain::ClaimId;
13 use crate::ln::PaymentPreimage;
14 use crate::ln::chan_utils;
15 use crate::ln::chan_utils::{ChannelTransactionParameters, HTLCOutputInCommitment};
16
17 use bitcoin::{OutPoint, PackedLockTime, Script, Transaction, Txid, TxIn, TxOut, Witness};
18 use bitcoin::secp256k1;
19 use bitcoin::secp256k1::{PublicKey, Secp256k1};
20 use bitcoin::secp256k1::ecdsa::Signature;
21
22 /// A descriptor used to sign for a commitment transaction's anchor output.
23 #[derive(Clone, Debug, PartialEq, Eq)]
24 pub struct AnchorDescriptor {
25         /// A unique identifier used along with `channel_value_satoshis` to re-derive the
26         /// [`InMemorySigner`] required to sign `input`.
27         ///
28         /// [`InMemorySigner`]: crate::sign::InMemorySigner
29         pub channel_keys_id: [u8; 32],
30         /// The value in satoshis of the channel we're attempting to spend the anchor output of. This is
31         /// used along with `channel_keys_id` to re-derive the [`InMemorySigner`] required to sign
32         /// `input`.
33         ///
34         /// [`InMemorySigner`]: crate::sign::InMemorySigner
35         pub channel_value_satoshis: u64,
36         /// The transaction input's outpoint corresponding to the commitment transaction's anchor
37         /// output.
38         pub outpoint: OutPoint,
39 }
40
41 /// A descriptor used to sign for a commitment transaction's HTLC output.
42 #[derive(Clone, Debug, PartialEq, Eq)]
43 pub struct HTLCDescriptor {
44         /// A unique identifier used along with `channel_value_satoshis` to re-derive the
45         /// [`InMemorySigner`] required to sign `input`.
46         ///
47         /// [`InMemorySigner`]: crate::sign::InMemorySigner
48         pub channel_keys_id: [u8; 32],
49         /// The value in satoshis of the channel we're attempting to spend the anchor output of. This is
50         /// used along with `channel_keys_id` to re-derive the [`InMemorySigner`] required to sign
51         /// `input`.
52         ///
53         /// [`InMemorySigner`]: crate::sign::InMemorySigner
54         pub channel_value_satoshis: u64,
55         /// The necessary channel parameters that need to be provided to the re-derived
56         /// [`InMemorySigner`] through [`ChannelSigner::provide_channel_parameters`].
57         ///
58         /// [`InMemorySigner`]: crate::sign::InMemorySigner
59         /// [`ChannelSigner::provide_channel_parameters`]: crate::sign::ChannelSigner::provide_channel_parameters
60         pub channel_parameters: ChannelTransactionParameters,
61         /// The txid of the commitment transaction in which the HTLC output lives.
62         pub commitment_txid: Txid,
63         /// The number of the commitment transaction in which the HTLC output lives.
64         pub per_commitment_number: u64,
65         /// The details of the HTLC as it appears in the commitment transaction.
66         pub htlc: HTLCOutputInCommitment,
67         /// The preimage, if `Some`, to claim the HTLC output with. If `None`, the timeout path must be
68         /// taken.
69         pub preimage: Option<PaymentPreimage>,
70         /// The counterparty's signature required to spend the HTLC output.
71         pub counterparty_sig: Signature
72 }
73
74 impl HTLCDescriptor {
75         /// Returns the unsigned transaction input spending the HTLC output in the commitment
76         /// transaction.
77         pub fn unsigned_tx_input(&self) -> TxIn {
78                 chan_utils::build_htlc_input(&self.commitment_txid, &self.htlc, true /* opt_anchors */)
79         }
80
81         /// Returns the delayed output created as a result of spending the HTLC output in the commitment
82         /// transaction.
83         pub fn tx_output<C: secp256k1::Signing + secp256k1::Verification>(
84                 &self, per_commitment_point: &PublicKey, secp: &Secp256k1<C>
85         ) -> TxOut {
86                 let channel_params = self.channel_parameters.as_holder_broadcastable();
87                 let broadcaster_keys = channel_params.broadcaster_pubkeys();
88                 let counterparty_keys = channel_params.countersignatory_pubkeys();
89                 let broadcaster_delayed_key = chan_utils::derive_public_key(
90                         secp, per_commitment_point, &broadcaster_keys.delayed_payment_basepoint
91                 );
92                 let counterparty_revocation_key = chan_utils::derive_public_revocation_key(
93                         secp, per_commitment_point, &counterparty_keys.revocation_basepoint
94                 );
95                 chan_utils::build_htlc_output(
96                         0 /* feerate_per_kw */, channel_params.contest_delay(), &self.htlc, true /* opt_anchors */,
97                         false /* use_non_zero_fee_anchors */, &broadcaster_delayed_key, &counterparty_revocation_key
98                 )
99         }
100
101         /// Returns the witness script of the HTLC output in the commitment transaction.
102         pub fn witness_script<C: secp256k1::Signing + secp256k1::Verification>(
103                 &self, per_commitment_point: &PublicKey, secp: &Secp256k1<C>
104         ) -> Script {
105                 let channel_params = self.channel_parameters.as_holder_broadcastable();
106                 let broadcaster_keys = channel_params.broadcaster_pubkeys();
107                 let counterparty_keys = channel_params.countersignatory_pubkeys();
108                 let broadcaster_htlc_key = chan_utils::derive_public_key(
109                         secp, per_commitment_point, &broadcaster_keys.htlc_basepoint
110                 );
111                 let counterparty_htlc_key = chan_utils::derive_public_key(
112                         secp, per_commitment_point, &counterparty_keys.htlc_basepoint
113                 );
114                 let counterparty_revocation_key = chan_utils::derive_public_revocation_key(
115                         secp, per_commitment_point, &counterparty_keys.revocation_basepoint
116                 );
117                 chan_utils::get_htlc_redeemscript_with_explicit_keys(
118                         &self.htlc, true /* opt_anchors */, &broadcaster_htlc_key, &counterparty_htlc_key,
119                         &counterparty_revocation_key,
120                 )
121         }
122
123         /// Returns the fully signed witness required to spend the HTLC output in the commitment
124         /// transaction.
125         pub fn tx_input_witness(&self, signature: &Signature, witness_script: &Script) -> Witness {
126                 chan_utils::build_htlc_input_witness(
127                         signature, &self.counterparty_sig, &self.preimage, witness_script, true /* opt_anchors */
128                 )
129         }
130 }
131
132 /// Represents the different types of transactions, originating from LDK, to be bumped.
133 #[derive(Clone, Debug, PartialEq, Eq)]
134 pub enum BumpTransactionEvent {
135         /// Indicates that a channel featuring anchor outputs is to be closed by broadcasting the local
136         /// commitment transaction. Since commitment transactions have a static feerate pre-agreed upon,
137         /// they may need additional fees to be attached through a child transaction using the popular
138         /// [Child-Pays-For-Parent](https://bitcoinops.org/en/topics/cpfp) fee bumping technique. This
139         /// child transaction must include the anchor input described within `anchor_descriptor` along
140         /// with additional inputs to meet the target feerate. Failure to meet the target feerate
141         /// decreases the confirmation odds of the transaction package (which includes the commitment
142         /// and child anchor transactions), possibly resulting in a loss of funds. Once the transaction
143         /// is constructed, it must be fully signed for and broadcast by the consumer of the event
144         /// along with the `commitment_tx` enclosed. Note that the `commitment_tx` must always be
145         /// broadcast first, as the child anchor transaction depends on it.
146         ///
147         /// The consumer should be able to sign for any of the additional inputs included within the
148         /// child anchor transaction. To sign its anchor input, an [`InMemorySigner`] should be
149         /// re-derived through [`KeysManager::derive_channel_keys`] with the help of
150         /// [`AnchorDescriptor::channel_keys_id`] and [`AnchorDescriptor::channel_value_satoshis`]. The
151         /// anchor input signature can be computed with [`EcdsaChannelSigner::sign_holder_anchor_input`],
152         /// which can then be provided to [`build_anchor_input_witness`] along with the `funding_pubkey`
153         /// to obtain the full witness required to spend.
154         ///
155         /// It is possible to receive more than one instance of this event if a valid child anchor
156         /// transaction is never broadcast or is but not with a sufficient fee to be mined. Care should
157         /// be taken by the consumer of the event to ensure any future iterations of the child anchor
158         /// transaction adhere to the [Replace-By-Fee
159         /// rules](https://github.com/bitcoin/bitcoin/blob/master/doc/policy/mempool-replacements.md)
160         /// for fee bumps to be accepted into the mempool, and eventually the chain. As the frequency of
161         /// these events is not user-controlled, users may ignore/drop the event if they are no longer
162         /// able to commit external confirmed funds to the child anchor transaction.
163         ///
164         /// The set of `pending_htlcs` on the commitment transaction to be broadcast can be inspected to
165         /// determine whether a significant portion of the channel's funds are allocated to HTLCs,
166         /// enabling users to make their own decisions regarding the importance of the commitment
167         /// transaction's confirmation. Note that this is not required, but simply exists as an option
168         /// for users to override LDK's behavior. On commitments with no HTLCs (indicated by those with
169         /// an empty `pending_htlcs`), confirmation of the commitment transaction can be considered to
170         /// be not urgent.
171         ///
172         /// [`InMemorySigner`]: crate::sign::InMemorySigner
173         /// [`KeysManager::derive_channel_keys`]: crate::sign::KeysManager::derive_channel_keys
174         /// [`EcdsaChannelSigner::sign_holder_anchor_input`]: crate::sign::EcdsaChannelSigner::sign_holder_anchor_input
175         /// [`build_anchor_input_witness`]: crate::ln::chan_utils::build_anchor_input_witness
176         ChannelClose {
177                 /// The unique identifier for the claim of the anchor output in the commitment transaction.
178                 ///
179                 /// The identifier must map to the set of external UTXOs assigned to the claim, such that
180                 /// they can be reused when a new claim with the same identifier needs to be made, resulting
181                 /// in a fee-bumping attempt.
182                 claim_id: ClaimId,
183                 /// The target feerate that the transaction package, which consists of the commitment
184                 /// transaction and the to-be-crafted child anchor transaction, must meet.
185                 package_target_feerate_sat_per_1000_weight: u32,
186                 /// The channel's commitment transaction to bump the fee of. This transaction should be
187                 /// broadcast along with the anchor transaction constructed as a result of consuming this
188                 /// event.
189                 commitment_tx: Transaction,
190                 /// The absolute fee in satoshis of the commitment transaction. This can be used along the
191                 /// with weight of the commitment transaction to determine its feerate.
192                 commitment_tx_fee_satoshis: u64,
193                 /// The descriptor to sign the anchor input of the anchor transaction constructed as a
194                 /// result of consuming this event.
195                 anchor_descriptor: AnchorDescriptor,
196                 /// The set of pending HTLCs on the commitment transaction that need to be resolved once the
197                 /// commitment transaction confirms.
198                 pending_htlcs: Vec<HTLCOutputInCommitment>,
199         },
200         /// Indicates that a channel featuring anchor outputs has unilaterally closed on-chain by a
201         /// holder commitment transaction and its HTLC(s) need to be resolved on-chain. With the
202         /// zero-HTLC-transaction-fee variant of anchor outputs, the pre-signed HTLC
203         /// transactions have a zero fee, thus requiring additional inputs and/or outputs to be attached
204         /// for a timely confirmation within the chain. These additional inputs and/or outputs must be
205         /// appended to the resulting HTLC transaction to meet the target feerate. Failure to meet the
206         /// target feerate decreases the confirmation odds of the transaction, possibly resulting in a
207         /// loss of funds. Once the transaction meets the target feerate, it must be signed for and
208         /// broadcast by the consumer of the event.
209         ///
210         /// The consumer should be able to sign for any of the non-HTLC inputs added to the resulting
211         /// HTLC transaction. To sign HTLC inputs, an [`InMemorySigner`] should be re-derived through
212         /// [`KeysManager::derive_channel_keys`] with the help of `channel_keys_id` and
213         /// `channel_value_satoshis`. Each HTLC input's signature can be computed with
214         /// [`EcdsaChannelSigner::sign_holder_htlc_transaction`], which can then be provided to
215         /// [`HTLCDescriptor::tx_input_witness`] to obtain the fully signed witness required to spend.
216         ///
217         /// It is possible to receive more than one instance of this event if a valid HTLC transaction
218         /// is never broadcast or is but not with a sufficient fee to be mined. Care should be taken by
219         /// the consumer of the event to ensure any future iterations of the HTLC transaction adhere to
220         /// the [Replace-By-Fee
221         /// rules](https://github.com/bitcoin/bitcoin/blob/master/doc/policy/mempool-replacements.md)
222         /// for fee bumps to be accepted into the mempool, and eventually the chain. As the frequency of
223         /// these events is not user-controlled, users may ignore/drop the event if either they are no
224         /// longer able to commit external confirmed funds to the HTLC transaction or the fee committed
225         /// to the HTLC transaction is greater in value than the HTLCs being claimed.
226         ///
227         /// [`InMemorySigner`]: crate::sign::InMemorySigner
228         /// [`KeysManager::derive_channel_keys`]: crate::sign::KeysManager::derive_channel_keys
229         /// [`EcdsaChannelSigner::sign_holder_htlc_transaction`]: crate::sign::EcdsaChannelSigner::sign_holder_htlc_transaction
230         /// [`HTLCDescriptor::tx_input_witness`]: HTLCDescriptor::tx_input_witness
231         HTLCResolution {
232                 /// The unique identifier for the claim of the HTLCs in the confirmed commitment
233                 /// transaction.
234                 ///
235                 /// The identifier must map to the set of external UTXOs assigned to the claim, such that
236                 /// they can be reused when a new claim with the same identifier needs to be made, resulting
237                 /// in a fee-bumping attempt.
238                 claim_id: ClaimId,
239                 /// The target feerate that the resulting HTLC transaction must meet.
240                 target_feerate_sat_per_1000_weight: u32,
241                 /// The set of pending HTLCs on the confirmed commitment that need to be claimed, preferably
242                 /// by the same transaction.
243                 htlc_descriptors: Vec<HTLCDescriptor>,
244                 /// The locktime required for the resulting HTLC transaction.
245                 tx_lock_time: PackedLockTime,
246         },
247 }