Ensure `Event::BumpTransaction` is forwards-compatible
[rust-lightning] / lightning / src / util / events.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 //! Events are returned from various bits in the library which indicate some action must be taken
11 //! by the client.
12 //!
13 //! Because we don't have a built-in runtime, it's up to the client to call events at a time in the
14 //! future, as well as generate and broadcast funding transactions handle payment preimages and a
15 //! few other things.
16
17 use crate::chain::keysinterface::SpendableOutputDescriptor;
18 #[cfg(anchors)]
19 use crate::ln::chan_utils::{self, ChannelTransactionParameters, HTLCOutputInCommitment};
20 use crate::ln::channelmanager::{InterceptId, PaymentId};
21 use crate::ln::channel::FUNDING_CONF_DEADLINE_BLOCKS;
22 use crate::ln::features::ChannelTypeFeatures;
23 use crate::ln::msgs;
24 use crate::ln::msgs::DecodeError;
25 use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
26 use crate::routing::gossip::NetworkUpdate;
27 use crate::util::ser::{BigSize, FixedLengthReader, Writeable, Writer, MaybeReadable, Readable, WithoutLength, OptionDeserWrapper};
28 use crate::routing::router::{RouteHop, RouteParameters};
29
30 use bitcoin::{PackedLockTime, Transaction};
31 #[cfg(anchors)]
32 use bitcoin::{OutPoint, Txid, TxIn, TxOut, Witness};
33 use bitcoin::blockdata::script::Script;
34 use bitcoin::hashes::Hash;
35 use bitcoin::hashes::sha256::Hash as Sha256;
36 use bitcoin::secp256k1::PublicKey;
37 #[cfg(anchors)]
38 use bitcoin::secp256k1::{self, Secp256k1};
39 #[cfg(anchors)]
40 use bitcoin::secp256k1::ecdsa::Signature;
41 use crate::io;
42 use crate::prelude::*;
43 use core::time::Duration;
44 use core::ops::Deref;
45 use crate::sync::Arc;
46
47 /// Some information provided on receipt of payment depends on whether the payment received is a
48 /// spontaneous payment or a "conventional" lightning payment that's paying an invoice.
49 #[derive(Clone, Debug)]
50 pub enum PaymentPurpose {
51         /// Information for receiving a payment that we generated an invoice for.
52         InvoicePayment {
53                 /// The preimage to the payment_hash, if the payment hash (and secret) were fetched via
54                 /// [`ChannelManager::create_inbound_payment`]. If provided, this can be handed directly to
55                 /// [`ChannelManager::claim_funds`].
56                 ///
57                 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
58                 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
59                 payment_preimage: Option<PaymentPreimage>,
60                 /// The "payment secret". This authenticates the sender to the recipient, preventing a
61                 /// number of deanonymization attacks during the routing process.
62                 /// It is provided here for your reference, however its accuracy is enforced directly by
63                 /// [`ChannelManager`] using the values you previously provided to
64                 /// [`ChannelManager::create_inbound_payment`] or
65                 /// [`ChannelManager::create_inbound_payment_for_hash`].
66                 ///
67                 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
68                 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
69                 /// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
70                 payment_secret: PaymentSecret,
71         },
72         /// Because this is a spontaneous payment, the payer generated their own preimage rather than us
73         /// (the payee) providing a preimage.
74         SpontaneousPayment(PaymentPreimage),
75 }
76
77 impl_writeable_tlv_based_enum!(PaymentPurpose,
78         (0, InvoicePayment) => {
79                 (0, payment_preimage, option),
80                 (2, payment_secret, required),
81         };
82         (2, SpontaneousPayment)
83 );
84
85 #[derive(Clone, Debug, PartialEq, Eq)]
86 /// The reason the channel was closed. See individual variants more details.
87 pub enum ClosureReason {
88         /// Closure generated from receiving a peer error message.
89         ///
90         /// Our counterparty may have broadcasted their latest commitment state, and we have
91         /// as well.
92         CounterpartyForceClosed {
93                 /// The error which the peer sent us.
94                 ///
95                 /// The string should be sanitized before it is used (e.g emitted to logs
96                 /// or printed to stdout). Otherwise, a well crafted error message may exploit
97                 /// a security vulnerability in the terminal emulator or the logging subsystem.
98                 peer_msg: String,
99         },
100         /// Closure generated from [`ChannelManager::force_close_channel`], called by the user.
101         ///
102         /// [`ChannelManager::force_close_channel`]: crate::ln::channelmanager::ChannelManager::force_close_channel.
103         HolderForceClosed,
104         /// The channel was closed after negotiating a cooperative close and we've now broadcasted
105         /// the cooperative close transaction. Note the shutdown may have been initiated by us.
106         //TODO: split between CounterpartyInitiated/LocallyInitiated
107         CooperativeClosure,
108         /// A commitment transaction was confirmed on chain, closing the channel. Most likely this
109         /// commitment transaction came from our counterparty, but it may also have come from
110         /// a copy of our own `ChannelMonitor`.
111         CommitmentTxConfirmed,
112         /// The funding transaction failed to confirm in a timely manner on an inbound channel.
113         FundingTimedOut,
114         /// Closure generated from processing an event, likely a HTLC forward/relay/reception.
115         ProcessingError {
116                 /// A developer-readable error message which we generated.
117                 err: String,
118         },
119         /// The peer disconnected prior to funding completing. In this case the spec mandates that we
120         /// forget the channel entirely - we can attempt again if the peer reconnects.
121         ///
122         /// This includes cases where we restarted prior to funding completion, including prior to the
123         /// initial [`ChannelMonitor`] persistence completing.
124         ///
125         /// In LDK versions prior to 0.0.107 this could also occur if we were unable to connect to the
126         /// peer because of mutual incompatibility between us and our channel counterparty.
127         ///
128         /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
129         DisconnectedPeer,
130         /// Closure generated from `ChannelManager::read` if the [`ChannelMonitor`] is newer than
131         /// the [`ChannelManager`] deserialized.
132         ///
133         /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
134         /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
135         OutdatedChannelManager
136 }
137
138 impl core::fmt::Display for ClosureReason {
139         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
140                 f.write_str("Channel closed because ")?;
141                 match self {
142                         ClosureReason::CounterpartyForceClosed { peer_msg } => {
143                                 f.write_str("counterparty force-closed with message ")?;
144                                 f.write_str(&peer_msg)
145                         },
146                         ClosureReason::HolderForceClosed => f.write_str("user manually force-closed the channel"),
147                         ClosureReason::CooperativeClosure => f.write_str("the channel was cooperatively closed"),
148                         ClosureReason::CommitmentTxConfirmed => f.write_str("commitment or closing transaction was confirmed on chain."),
149                         ClosureReason::FundingTimedOut => write!(f, "funding transaction failed to confirm within {} blocks", FUNDING_CONF_DEADLINE_BLOCKS),
150                         ClosureReason::ProcessingError { err } => {
151                                 f.write_str("of an exception: ")?;
152                                 f.write_str(&err)
153                         },
154                         ClosureReason::DisconnectedPeer => f.write_str("the peer disconnected prior to the channel being funded"),
155                         ClosureReason::OutdatedChannelManager => f.write_str("the ChannelManager read from disk was stale compared to ChannelMonitor(s)"),
156                 }
157         }
158 }
159
160 impl_writeable_tlv_based_enum_upgradable!(ClosureReason,
161         (0, CounterpartyForceClosed) => { (1, peer_msg, required) },
162         (1, FundingTimedOut) => {},
163         (2, HolderForceClosed) => {},
164         (6, CommitmentTxConfirmed) => {},
165         (4, CooperativeClosure) => {},
166         (8, ProcessingError) => { (1, err, required) },
167         (10, DisconnectedPeer) => {},
168         (12, OutdatedChannelManager) => {},
169 );
170
171 /// Intended destination of a failed HTLC as indicated in [`Event::HTLCHandlingFailed`].
172 #[derive(Clone, Debug, PartialEq, Eq)]
173 pub enum HTLCDestination {
174         /// We tried forwarding to a channel but failed to do so. An example of such an instance is when
175         /// there is insufficient capacity in our outbound channel.
176         NextHopChannel {
177                 /// The `node_id` of the next node. For backwards compatibility, this field is
178                 /// marked as optional, versions prior to 0.0.110 may not always be able to provide
179                 /// counterparty node information.
180                 node_id: Option<PublicKey>,
181                 /// The outgoing `channel_id` between us and the next node.
182                 channel_id: [u8; 32],
183         },
184         /// Scenario where we are unsure of the next node to forward the HTLC to.
185         UnknownNextHop {
186                 /// Short channel id we are requesting to forward an HTLC to.
187                 requested_forward_scid: u64,
188         },
189         /// We couldn't forward to the outgoing scid. An example would be attempting to send a duplicate
190         /// intercept HTLC.
191         InvalidForward {
192                 /// Short channel id we are requesting to forward an HTLC to.
193                 requested_forward_scid: u64
194         },
195         /// Failure scenario where an HTLC may have been forwarded to be intended for us,
196         /// but is invalid for some reason, so we reject it.
197         ///
198         /// Some of the reasons may include:
199         /// * HTLC Timeouts
200         /// * Expected MPP amount to claim does not equal HTLC total
201         /// * Claimable amount does not match expected amount
202         FailedPayment {
203                 /// The payment hash of the payment we attempted to process.
204                 payment_hash: PaymentHash
205         },
206 }
207
208 impl_writeable_tlv_based_enum_upgradable!(HTLCDestination,
209         (0, NextHopChannel) => {
210                 (0, node_id, required),
211                 (2, channel_id, required),
212         },
213         (1, InvalidForward) => {
214                 (0, requested_forward_scid, required),
215         },
216         (2, UnknownNextHop) => {
217                 (0, requested_forward_scid, required),
218         },
219         (4, FailedPayment) => {
220                 (0, payment_hash, required),
221         },
222 );
223
224 #[cfg(anchors)]
225 /// A descriptor used to sign for a commitment transaction's anchor output.
226 #[derive(Clone, Debug)]
227 pub struct AnchorDescriptor {
228         /// A unique identifier used along with `channel_value_satoshis` to re-derive the
229         /// [`InMemorySigner`] required to sign `input`.
230         ///
231         /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
232         pub channel_keys_id: [u8; 32],
233         /// The value in satoshis of the channel we're attempting to spend the anchor output of. This is
234         /// used along with `channel_keys_id` to re-derive the [`InMemorySigner`] required to sign
235         /// `input`.
236         ///
237         /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
238         pub channel_value_satoshis: u64,
239         /// The transaction input's outpoint corresponding to the commitment transaction's anchor
240         /// output.
241         pub outpoint: OutPoint,
242 }
243
244 #[cfg(anchors)]
245 /// A descriptor used to sign for a commitment transaction's HTLC output.
246 #[derive(Clone, Debug)]
247 pub struct HTLCDescriptor {
248         /// A unique identifier used along with `channel_value_satoshis` to re-derive the
249         /// [`InMemorySigner`] required to sign `input`.
250         ///
251         /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
252         pub channel_keys_id: [u8; 32],
253         /// The value in satoshis of the channel we're attempting to spend the anchor output of. This is
254         /// used along with `channel_keys_id` to re-derive the [`InMemorySigner`] required to sign
255         /// `input`.
256         ///
257         /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
258         pub channel_value_satoshis: u64,
259         /// The necessary channel parameters that need to be provided to the re-derived
260         /// [`InMemorySigner`] through [`BaseSign::ready_channel`].
261         ///
262         /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
263         /// [`BaseSign::ready_channel`]: crate::chain::keysinterface::BaseSign::ready_channel
264         pub channel_parameters: ChannelTransactionParameters,
265         /// The txid of the commitment transaction in which the HTLC output lives.
266         pub commitment_txid: Txid,
267         /// The number of the commitment transaction in which the HTLC output lives.
268         pub per_commitment_number: u64,
269         /// The details of the HTLC as it appears in the commitment transaction.
270         pub htlc: HTLCOutputInCommitment,
271         /// The preimage, if `Some`, to claim the HTLC output with. If `None`, the timeout path must be
272         /// taken.
273         pub preimage: Option<PaymentPreimage>,
274         /// The counterparty's signature required to spend the HTLC output.
275         pub counterparty_sig: Signature
276 }
277
278 #[cfg(anchors)]
279 impl HTLCDescriptor {
280         /// Returns the unsigned transaction input spending the HTLC output in the commitment
281         /// transaction.
282         pub fn unsigned_tx_input(&self) -> TxIn {
283                 chan_utils::build_htlc_input(&self.commitment_txid, &self.htlc, true /* opt_anchors */)
284         }
285
286         /// Returns the delayed output created as a result of spending the HTLC output in the commitment
287         /// transaction.
288         pub fn tx_output<C: secp256k1::Signing + secp256k1::Verification>(
289                 &self, per_commitment_point: &PublicKey, secp: &Secp256k1<C>
290         ) -> TxOut {
291                 let channel_params = self.channel_parameters.as_holder_broadcastable();
292                 let broadcaster_keys = channel_params.broadcaster_pubkeys();
293                 let counterparty_keys = channel_params.countersignatory_pubkeys();
294                 let broadcaster_delayed_key = chan_utils::derive_public_key(
295                         secp, per_commitment_point, &broadcaster_keys.delayed_payment_basepoint
296                 );
297                 let counterparty_revocation_key = chan_utils::derive_public_revocation_key(
298                         secp, per_commitment_point, &counterparty_keys.revocation_basepoint
299                 );
300                 chan_utils::build_htlc_output(
301                         0 /* feerate_per_kw */, channel_params.contest_delay(), &self.htlc, true /* opt_anchors */,
302                         false /* use_non_zero_fee_anchors */, &broadcaster_delayed_key, &counterparty_revocation_key
303                 )
304         }
305
306         /// Returns the witness script of the HTLC output in the commitment transaction.
307         pub fn witness_script<C: secp256k1::Signing + secp256k1::Verification>(
308                 &self, per_commitment_point: &PublicKey, secp: &Secp256k1<C>
309         ) -> Script {
310                 let channel_params = self.channel_parameters.as_holder_broadcastable();
311                 let broadcaster_keys = channel_params.broadcaster_pubkeys();
312                 let counterparty_keys = channel_params.countersignatory_pubkeys();
313                 let broadcaster_htlc_key = chan_utils::derive_public_key(
314                         secp, per_commitment_point, &broadcaster_keys.htlc_basepoint
315                 );
316                 let counterparty_htlc_key = chan_utils::derive_public_key(
317                         secp, per_commitment_point, &counterparty_keys.htlc_basepoint
318                 );
319                 let counterparty_revocation_key = chan_utils::derive_public_revocation_key(
320                         secp, per_commitment_point, &counterparty_keys.revocation_basepoint
321                 );
322                 chan_utils::get_htlc_redeemscript_with_explicit_keys(
323                         &self.htlc, true /* opt_anchors */, &broadcaster_htlc_key, &counterparty_htlc_key,
324                         &counterparty_revocation_key,
325                 )
326         }
327
328         /// Returns the fully signed witness required to spend the HTLC output in the commitment
329         /// transaction.
330         pub fn tx_input_witness(&self, signature: &Signature, witness_script: &Script) -> Witness {
331                 chan_utils::build_htlc_input_witness(
332                         signature, &self.counterparty_sig, &self.preimage, witness_script, true /* opt_anchors */
333                 )
334         }
335 }
336
337 #[cfg(anchors)]
338 /// Represents the different types of transactions, originating from LDK, to be bumped.
339 #[derive(Clone, Debug)]
340 pub enum BumpTransactionEvent {
341         /// Indicates that a channel featuring anchor outputs is to be closed by broadcasting the local
342         /// commitment transaction. Since commitment transactions have a static feerate pre-agreed upon,
343         /// they may need additional fees to be attached through a child transaction using the popular
344         /// [Child-Pays-For-Parent](https://bitcoinops.org/en/topics/cpfp) fee bumping technique. This
345         /// child transaction must include the anchor input described within `anchor_descriptor` along
346         /// with additional inputs to meet the target feerate. Failure to meet the target feerate
347         /// decreases the confirmation odds of the transaction package (which includes the commitment
348         /// and child anchor transactions), possibly resulting in a loss of funds. Once the transaction
349         /// is constructed, it must be fully signed for and broadcast by the consumer of the event
350         /// along with the `commitment_tx` enclosed. Note that the `commitment_tx` must always be
351         /// broadcast first, as the child anchor transaction depends on it.
352         ///
353         /// The consumer should be able to sign for any of the additional inputs included within the
354         /// child anchor transaction. To sign its anchor input, an [`InMemorySigner`] should be
355         /// re-derived through [`KeysManager::derive_channel_keys`] with the help of
356         /// [`AnchorDescriptor::channel_keys_id`] and [`AnchorDescriptor::channel_value_satoshis`]. The
357         /// anchor input signature can be computed with [`BaseSign::sign_holder_anchor_input`],
358         /// which can then be provided to [`build_anchor_input_witness`] along with the `funding_pubkey`
359         /// to obtain the full witness required to spend.
360         ///
361         /// It is possible to receive more than one instance of this event if a valid child anchor
362         /// transaction is never broadcast or is but not with a sufficient fee to be mined. Care should
363         /// be taken by the consumer of the event to ensure any future iterations of the child anchor
364         /// transaction adhere to the [Replace-By-Fee
365         /// rules](https://github.com/bitcoin/bitcoin/blob/master/doc/policy/mempool-replacements.md)
366         /// for fee bumps to be accepted into the mempool, and eventually the chain. As the frequency of
367         /// these events is not user-controlled, users may ignore/drop the event if they are no longer
368         /// able to commit external confirmed funds to the child anchor transaction.
369         ///
370         /// The set of `pending_htlcs` on the commitment transaction to be broadcast can be inspected to
371         /// determine whether a significant portion of the channel's funds are allocated to HTLCs,
372         /// enabling users to make their own decisions regarding the importance of the commitment
373         /// transaction's confirmation. Note that this is not required, but simply exists as an option
374         /// for users to override LDK's behavior. On commitments with no HTLCs (indicated by those with
375         /// an empty `pending_htlcs`), confirmation of the commitment transaction can be considered to
376         /// be not urgent.
377         ///
378         /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
379         /// [`KeysManager::derive_channel_keys`]: crate::chain::keysinterface::KeysManager::derive_channel_keys
380         /// [`BaseSign::sign_holder_anchor_input`]: crate::chain::keysinterface::BaseSign::sign_holder_anchor_input
381         /// [`build_anchor_input_witness`]: crate::ln::chan_utils::build_anchor_input_witness
382         ChannelClose {
383                 /// The target feerate that the transaction package, which consists of the commitment
384                 /// transaction and the to-be-crafted child anchor transaction, must meet.
385                 package_target_feerate_sat_per_1000_weight: u32,
386                 /// The channel's commitment transaction to bump the fee of. This transaction should be
387                 /// broadcast along with the anchor transaction constructed as a result of consuming this
388                 /// event.
389                 commitment_tx: Transaction,
390                 /// The absolute fee in satoshis of the commitment transaction. This can be used along the
391                 /// with weight of the commitment transaction to determine its feerate.
392                 commitment_tx_fee_satoshis: u64,
393                 /// The descriptor to sign the anchor input of the anchor transaction constructed as a
394                 /// result of consuming this event.
395                 anchor_descriptor: AnchorDescriptor,
396                 /// The set of pending HTLCs on the commitment transaction that need to be resolved once the
397                 /// commitment transaction confirms.
398                 pending_htlcs: Vec<HTLCOutputInCommitment>,
399         },
400         /// Indicates that a channel featuring anchor outputs has unilaterally closed on-chain by a
401         /// holder commitment transaction and its HTLC(s) need to be resolved on-chain. With the
402         /// zero-HTLC-transaction-fee variant of anchor outputs, the pre-signed HTLC
403         /// transactions have a zero fee, thus requiring additional inputs and/or outputs to be attached
404         /// for a timely confirmation within the chain. These additional inputs and/or outputs must be
405         /// appended to the resulting HTLC transaction to meet the target feerate. Failure to meet the
406         /// target feerate decreases the confirmation odds of the transaction, possibly resulting in a
407         /// loss of funds. Once the transaction meets the target feerate, it must be signed for and
408         /// broadcast by the consumer of the event.
409         ///
410         /// The consumer should be able to sign for any of the non-HTLC inputs added to the resulting
411         /// HTLC transaction. To sign HTLC inputs, an [`InMemorySigner`] should be re-derived through
412         /// [`KeysManager::derive_channel_keys`] with the help of `channel_keys_id` and
413         /// `channel_value_satoshis`. Each HTLC input's signature can be computed with
414         /// [`BaseSign::sign_holder_htlc_transaction`], which can then be provided to
415         /// [`HTLCDescriptor::tx_input_witness`] to obtain the fully signed witness required to spend.
416         ///
417         /// It is possible to receive more than one instance of this event if a valid HTLC transaction
418         /// is never broadcast or is but not with a sufficient fee to be mined. Care should be taken by
419         /// the consumer of the event to ensure any future iterations of the HTLC transaction adhere to
420         /// the [Replace-By-Fee
421         /// rules](https://github.com/bitcoin/bitcoin/blob/master/doc/policy/mempool-replacements.md)
422         /// for fee bumps to be accepted into the mempool, and eventually the chain. As the frequency of
423         /// these events is not user-controlled, users may ignore/drop the event if either they are no
424         /// longer able to commit external confirmed funds to the HTLC transaction or the fee committed
425         /// to the HTLC transaction is greater in value than the HTLCs being claimed.
426         ///
427         /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
428         /// [`KeysManager::derive_channel_keys`]: crate::chain::keysinterface::KeysManager::derive_channel_keys
429         /// [`BaseSign::sign_holder_htlc_transaction`]: crate::chain::keysinterface::BaseSign::sign_holder_htlc_transaction
430         /// [`HTLCDescriptor::tx_input_witness`]: HTLCDescriptor::tx_input_witness
431         HTLCResolution {
432                 target_feerate_sat_per_1000_weight: u32,
433                 htlc_descriptors: Vec<HTLCDescriptor>,
434         },
435 }
436
437 /// Will be used in [`Event::HTLCIntercepted`] to identify the next hop in the HTLC's path.
438 /// Currently only used in serialization for the sake of maintaining compatibility. More variants
439 /// will be added for general-purpose HTLC forward intercepts as well as trampoline forward
440 /// intercepts in upcoming work.
441 enum InterceptNextHop {
442         FakeScid {
443                 requested_next_hop_scid: u64,
444         },
445 }
446
447 impl_writeable_tlv_based_enum!(InterceptNextHop,
448         (0, FakeScid) => {
449                 (0, requested_next_hop_scid, required),
450         };
451 );
452
453 /// An Event which you should probably take some action in response to.
454 ///
455 /// Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
456 /// them directly as they don't round-trip exactly (for example FundingGenerationReady is never
457 /// written as it makes no sense to respond to it after reconnecting to peers).
458 #[derive(Clone, Debug)]
459 pub enum Event {
460         /// Used to indicate that the client should generate a funding transaction with the given
461         /// parameters and then call [`ChannelManager::funding_transaction_generated`].
462         /// Generated in [`ChannelManager`] message handling.
463         /// Note that *all inputs* in the funding transaction must spend SegWit outputs or your
464         /// counterparty can steal your funds!
465         ///
466         /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
467         /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
468         FundingGenerationReady {
469                 /// The random channel_id we picked which you'll need to pass into
470                 /// [`ChannelManager::funding_transaction_generated`].
471                 ///
472                 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
473                 temporary_channel_id: [u8; 32],
474                 /// The counterparty's node_id, which you'll need to pass back into
475                 /// [`ChannelManager::funding_transaction_generated`].
476                 ///
477                 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
478                 counterparty_node_id: PublicKey,
479                 /// The value, in satoshis, that the output should have.
480                 channel_value_satoshis: u64,
481                 /// The script which should be used in the transaction output.
482                 output_script: Script,
483                 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`], or a
484                 /// random value for an inbound channel. This may be zero for objects serialized with LDK
485                 /// versions prior to 0.0.113.
486                 ///
487                 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
488                 user_channel_id: u128,
489         },
490         /// Indicates that we've been offered a payment and it needs to be claimed via calling
491         /// [`ChannelManager::claim_funds`] with the preimage given in [`PaymentPurpose`].
492         ///
493         /// Note that if the preimage is not known, you should call
494         /// [`ChannelManager::fail_htlc_backwards`] to free up resources for this HTLC and avoid
495         /// network congestion.
496         /// If you fail to call either [`ChannelManager::claim_funds`] or
497         /// [`ChannelManager::fail_htlc_backwards`] within the HTLC's timeout, the HTLC will be
498         /// automatically failed.
499         ///
500         /// # Note
501         /// LDK will not stop an inbound payment from being paid multiple times, so multiple
502         /// `PaymentClaimable` events may be generated for the same payment.
503         ///
504         /// # Note
505         /// This event used to be called `PaymentReceived` in LDK versions 0.0.112 and earlier.
506         ///
507         /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
508         /// [`ChannelManager::fail_htlc_backwards`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards
509         PaymentClaimable {
510                 /// The node that will receive the payment after it has been claimed.
511                 /// This is useful to identify payments received via [phantom nodes].
512                 /// This field will always be filled in when the event was generated by LDK versions
513                 /// 0.0.113 and above.
514                 ///
515                 /// [phantom nodes]: crate::chain::keysinterface::PhantomKeysManager
516                 receiver_node_id: Option<PublicKey>,
517                 /// The hash for which the preimage should be handed to the ChannelManager. Note that LDK will
518                 /// not stop you from registering duplicate payment hashes for inbound payments.
519                 payment_hash: PaymentHash,
520                 /// The value, in thousandths of a satoshi, that this payment is for.
521                 amount_msat: u64,
522                 /// Information for claiming this received payment, based on whether the purpose of the
523                 /// payment is to pay an invoice or to send a spontaneous payment.
524                 purpose: PaymentPurpose,
525                 /// The `channel_id` indicating over which channel we received the payment.
526                 via_channel_id: Option<[u8; 32]>,
527                 /// The `user_channel_id` indicating over which channel we received the payment.
528                 via_user_channel_id: Option<u128>,
529         },
530         /// Indicates a payment has been claimed and we've received money!
531         ///
532         /// This most likely occurs when [`ChannelManager::claim_funds`] has been called in response
533         /// to an [`Event::PaymentClaimable`]. However, if we previously crashed during a
534         /// [`ChannelManager::claim_funds`] call you may see this event without a corresponding
535         /// [`Event::PaymentClaimable`] event.
536         ///
537         /// # Note
538         /// LDK will not stop an inbound payment from being paid multiple times, so multiple
539         /// `PaymentClaimable` events may be generated for the same payment. If you then call
540         /// [`ChannelManager::claim_funds`] twice for the same [`Event::PaymentClaimable`] you may get
541         /// multiple `PaymentClaimed` events.
542         ///
543         /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
544         PaymentClaimed {
545                 /// The node that received the payment.
546                 /// This is useful to identify payments which were received via [phantom nodes].
547                 /// This field will always be filled in when the event was generated by LDK versions
548                 /// 0.0.113 and above.
549                 ///
550                 /// [phantom nodes]: crate::chain::keysinterface::PhantomKeysManager
551                 receiver_node_id: Option<PublicKey>,
552                 /// The payment hash of the claimed payment. Note that LDK will not stop you from
553                 /// registering duplicate payment hashes for inbound payments.
554                 payment_hash: PaymentHash,
555                 /// The value, in thousandths of a satoshi, that this payment is for.
556                 amount_msat: u64,
557                 /// The purpose of the claimed payment, i.e. whether the payment was for an invoice or a
558                 /// spontaneous payment.
559                 purpose: PaymentPurpose,
560         },
561         /// Indicates an outbound payment we made succeeded (i.e. it made it all the way to its target
562         /// and we got back the payment preimage for it).
563         ///
564         /// Note for MPP payments: in rare cases, this event may be preceded by a `PaymentPathFailed`
565         /// event. In this situation, you SHOULD treat this payment as having succeeded.
566         PaymentSent {
567                 /// The id returned by [`ChannelManager::send_payment`] and used with
568                 /// [`ChannelManager::retry_payment`].
569                 ///
570                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
571                 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
572                 payment_id: Option<PaymentId>,
573                 /// The preimage to the hash given to ChannelManager::send_payment.
574                 /// Note that this serves as a payment receipt, if you wish to have such a thing, you must
575                 /// store it somehow!
576                 payment_preimage: PaymentPreimage,
577                 /// The hash that was given to [`ChannelManager::send_payment`].
578                 ///
579                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
580                 payment_hash: PaymentHash,
581                 /// The total fee which was spent at intermediate hops in this payment, across all paths.
582                 ///
583                 /// Note that, like [`Route::get_total_fees`] this does *not* include any potential
584                 /// overpayment to the recipient node.
585                 ///
586                 /// If the recipient or an intermediate node misbehaves and gives us free money, this may
587                 /// overstate the amount paid, though this is unlikely.
588                 ///
589                 /// [`Route::get_total_fees`]: crate::routing::router::Route::get_total_fees
590                 fee_paid_msat: Option<u64>,
591         },
592         /// Indicates an outbound payment failed. Individual [`Event::PaymentPathFailed`] events
593         /// provide failure information for each MPP part in the payment.
594         ///
595         /// This event is provided once there are no further pending HTLCs for the payment and the
596         /// payment is no longer retryable due to [`ChannelManager::abandon_payment`] having been
597         /// called for the corresponding payment.
598         ///
599         /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
600         PaymentFailed {
601                 /// The id returned by [`ChannelManager::send_payment`] and used with
602                 /// [`ChannelManager::retry_payment`] and [`ChannelManager::abandon_payment`].
603                 ///
604                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
605                 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
606                 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
607                 payment_id: PaymentId,
608                 /// The hash that was given to [`ChannelManager::send_payment`].
609                 ///
610                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
611                 payment_hash: PaymentHash,
612         },
613         /// Indicates that a path for an outbound payment was successful.
614         ///
615         /// Always generated after [`Event::PaymentSent`] and thus useful for scoring channels. See
616         /// [`Event::PaymentSent`] for obtaining the payment preimage.
617         PaymentPathSuccessful {
618                 /// The id returned by [`ChannelManager::send_payment`] and used with
619                 /// [`ChannelManager::retry_payment`].
620                 ///
621                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
622                 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
623                 payment_id: PaymentId,
624                 /// The hash that was given to [`ChannelManager::send_payment`].
625                 ///
626                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
627                 payment_hash: Option<PaymentHash>,
628                 /// The payment path that was successful.
629                 ///
630                 /// May contain a closed channel if the HTLC sent along the path was fulfilled on chain.
631                 path: Vec<RouteHop>,
632         },
633         /// Indicates an outbound HTLC we sent failed. Probably some intermediary node dropped
634         /// something. You may wish to retry with a different route.
635         ///
636         /// If you have given up retrying this payment and wish to fail it, you MUST call
637         /// [`ChannelManager::abandon_payment`] at least once for a given [`PaymentId`] or memory
638         /// related to payment tracking will leak.
639         ///
640         /// Note that this does *not* indicate that all paths for an MPP payment have failed, see
641         /// [`Event::PaymentFailed`] and [`all_paths_failed`].
642         ///
643         /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
644         /// [`all_paths_failed`]: Self::PaymentPathFailed::all_paths_failed
645         PaymentPathFailed {
646                 /// The id returned by [`ChannelManager::send_payment`] and used with
647                 /// [`ChannelManager::retry_payment`] and [`ChannelManager::abandon_payment`].
648                 ///
649                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
650                 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
651                 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
652                 payment_id: Option<PaymentId>,
653                 /// The hash that was given to [`ChannelManager::send_payment`].
654                 ///
655                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
656                 payment_hash: PaymentHash,
657                 /// Indicates the payment was rejected for some reason by the recipient. This implies that
658                 /// the payment has failed, not just the route in question. If this is not set, you may
659                 /// retry the payment via a different route.
660                 payment_failed_permanently: bool,
661                 /// Any failure information conveyed via the Onion return packet by a node along the failed
662                 /// payment route.
663                 ///
664                 /// Should be applied to the [`NetworkGraph`] so that routing decisions can take into
665                 /// account the update.
666                 ///
667                 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
668                 network_update: Option<NetworkUpdate>,
669                 /// For both single-path and multi-path payments, this is set if all paths of the payment have
670                 /// failed. This will be set to false if (1) this is an MPP payment and (2) other parts of the
671                 /// larger MPP payment were still in flight when this event was generated.
672                 ///
673                 /// Note that if you are retrying individual MPP parts, using this value to determine if a
674                 /// payment has fully failed is race-y. Because multiple failures can happen prior to events
675                 /// being processed, you may retry in response to a first failure, with a second failure
676                 /// (with `all_paths_failed` set) still pending. Then, when the second failure is processed
677                 /// you will see `all_paths_failed` set even though the retry of the first failure still
678                 /// has an associated in-flight HTLC. See (1) for an example of such a failure.
679                 ///
680                 /// If you wish to retry individual MPP parts and learn when a payment has failed, you must
681                 /// call [`ChannelManager::abandon_payment`] and wait for a [`Event::PaymentFailed`] event.
682                 ///
683                 /// (1) <https://github.com/lightningdevkit/rust-lightning/issues/1164>
684                 ///
685                 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
686                 all_paths_failed: bool,
687                 /// The payment path that failed.
688                 path: Vec<RouteHop>,
689                 /// The channel responsible for the failed payment path.
690                 ///
691                 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
692                 /// may not refer to a channel in the public network graph. These aliases may also collide
693                 /// with channels in the public network graph.
694                 ///
695                 /// If this is `Some`, then the corresponding channel should be avoided when the payment is
696                 /// retried. May be `None` for older [`Event`] serializations.
697                 short_channel_id: Option<u64>,
698                 /// Parameters needed to compute a new [`Route`] when retrying the failed payment path.
699                 ///
700                 /// See [`find_route`] for details.
701                 ///
702                 /// [`Route`]: crate::routing::router::Route
703                 /// [`find_route`]: crate::routing::router::find_route
704                 retry: Option<RouteParameters>,
705 #[cfg(test)]
706                 error_code: Option<u16>,
707 #[cfg(test)]
708                 error_data: Option<Vec<u8>>,
709         },
710         /// Indicates that a probe payment we sent returned successful, i.e., only failed at the destination.
711         ProbeSuccessful {
712                 /// The id returned by [`ChannelManager::send_probe`].
713                 ///
714                 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
715                 payment_id: PaymentId,
716                 /// The hash generated by [`ChannelManager::send_probe`].
717                 ///
718                 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
719                 payment_hash: PaymentHash,
720                 /// The payment path that was successful.
721                 path: Vec<RouteHop>,
722         },
723         /// Indicates that a probe payment we sent failed at an intermediary node on the path.
724         ProbeFailed {
725                 /// The id returned by [`ChannelManager::send_probe`].
726                 ///
727                 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
728                 payment_id: PaymentId,
729                 /// The hash generated by [`ChannelManager::send_probe`].
730                 ///
731                 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
732                 payment_hash: PaymentHash,
733                 /// The payment path that failed.
734                 path: Vec<RouteHop>,
735                 /// The channel responsible for the failed probe.
736                 ///
737                 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
738                 /// may not refer to a channel in the public network graph. These aliases may also collide
739                 /// with channels in the public network graph.
740                 short_channel_id: Option<u64>,
741         },
742         /// Used to indicate that [`ChannelManager::process_pending_htlc_forwards`] should be called at
743         /// a time in the future.
744         ///
745         /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
746         PendingHTLCsForwardable {
747                 /// The minimum amount of time that should be waited prior to calling
748                 /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
749                 /// you should wait a random amount of time in roughly the range (now + time_forwardable,
750                 /// now + 5*time_forwardable).
751                 time_forwardable: Duration,
752         },
753         /// Used to indicate that we've intercepted an HTLC forward. This event will only be generated if
754         /// you've encoded an intercept scid in the receiver's invoice route hints using
755         /// [`ChannelManager::get_intercept_scid`] and have set [`UserConfig::accept_intercept_htlcs`].
756         ///
757         /// [`ChannelManager::forward_intercepted_htlc`] or
758         /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to this event. See
759         /// their docs for more information.
760         ///
761         /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
762         /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
763         /// [`ChannelManager::forward_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::forward_intercepted_htlc
764         /// [`ChannelManager::fail_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::fail_intercepted_htlc
765         HTLCIntercepted {
766                 /// An id to help LDK identify which HTLC is being forwarded or failed.
767                 intercept_id: InterceptId,
768                 /// The fake scid that was programmed as the next hop's scid, generated using
769                 /// [`ChannelManager::get_intercept_scid`].
770                 ///
771                 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
772                 requested_next_hop_scid: u64,
773                 /// The payment hash used for this HTLC.
774                 payment_hash: PaymentHash,
775                 /// How many msats were received on the inbound edge of this HTLC.
776                 inbound_amount_msat: u64,
777                 /// How many msats the payer intended to route to the next node. Depending on the reason you are
778                 /// intercepting this payment, you might take a fee by forwarding less than this amount.
779                 ///
780                 /// Note that LDK will NOT check that expected fees were factored into this value. You MUST
781                 /// check that whatever fee you want has been included here or subtract it as required. Further,
782                 /// LDK will not stop you from forwarding more than you received.
783                 expected_outbound_amount_msat: u64,
784         },
785         /// Used to indicate that an output which you should know how to spend was confirmed on chain
786         /// and is now spendable.
787         /// Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
788         /// counterparty spending them due to some kind of timeout. Thus, you need to store them
789         /// somewhere and spend them when you create on-chain transactions.
790         SpendableOutputs {
791                 /// The outputs which you should store as spendable by you.
792                 outputs: Vec<SpendableOutputDescriptor>,
793         },
794         /// This event is generated when a payment has been successfully forwarded through us and a
795         /// forwarding fee earned.
796         PaymentForwarded {
797                 /// The incoming channel between the previous node and us. This is only `None` for events
798                 /// generated or serialized by versions prior to 0.0.107.
799                 prev_channel_id: Option<[u8; 32]>,
800                 /// The outgoing channel between the next node and us. This is only `None` for events
801                 /// generated or serialized by versions prior to 0.0.107.
802                 next_channel_id: Option<[u8; 32]>,
803                 /// The fee, in milli-satoshis, which was earned as a result of the payment.
804                 ///
805                 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
806                 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
807                 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
808                 /// claimed the full value in millisatoshis from the source. In this case,
809                 /// `claim_from_onchain_tx` will be set.
810                 ///
811                 /// If the channel which sent us the payment has been force-closed, we will claim the funds
812                 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
813                 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
814                 /// `PaymentForwarded` events are generated for the same payment iff `fee_earned_msat` is
815                 /// `None`.
816                 fee_earned_msat: Option<u64>,
817                 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
818                 /// transaction.
819                 claim_from_onchain_tx: bool,
820         },
821         /// Used to indicate that a channel with the given `channel_id` is ready to
822         /// be used. This event is emitted either when the funding transaction has been confirmed
823         /// on-chain, or, in case of a 0conf channel, when both parties have confirmed the channel
824         /// establishment.
825         ChannelReady {
826                 /// The channel_id of the channel that is ready.
827                 channel_id: [u8; 32],
828                 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
829                 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
830                 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
831                 /// `user_channel_id` will be randomized for an inbound channel.
832                 ///
833                 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
834                 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
835                 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
836                 user_channel_id: u128,
837                 /// The node_id of the channel counterparty.
838                 counterparty_node_id: PublicKey,
839                 /// The features that this channel will operate with.
840                 channel_type: ChannelTypeFeatures,
841         },
842         /// Used to indicate that a previously opened channel with the given `channel_id` is in the
843         /// process of closure.
844         ChannelClosed  {
845                 /// The channel_id of the channel which has been closed. Note that on-chain transactions
846                 /// resolving the channel are likely still awaiting confirmation.
847                 channel_id: [u8; 32],
848                 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
849                 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
850                 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
851                 /// `user_channel_id` will be randomized for inbound channels.
852                 /// This may be zero for inbound channels serialized prior to 0.0.113 and will always be
853                 /// zero for objects serialized with LDK versions prior to 0.0.102.
854                 ///
855                 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
856                 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
857                 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
858                 user_channel_id: u128,
859                 /// The reason the channel was closed.
860                 reason: ClosureReason
861         },
862         /// Used to indicate to the user that they can abandon the funding transaction and recycle the
863         /// inputs for another purpose.
864         DiscardFunding {
865                 /// The channel_id of the channel which has been closed.
866                 channel_id: [u8; 32],
867                 /// The full transaction received from the user
868                 transaction: Transaction
869         },
870         /// Indicates a request to open a new channel by a peer.
871         ///
872         /// To accept the request, call [`ChannelManager::accept_inbound_channel`]. To reject the
873         /// request, call [`ChannelManager::force_close_without_broadcasting_txn`].
874         ///
875         /// The event is only triggered when a new open channel request is received and the
876         /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true.
877         ///
878         /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
879         /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
880         /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
881         OpenChannelRequest {
882                 /// The temporary channel ID of the channel requested to be opened.
883                 ///
884                 /// When responding to the request, the `temporary_channel_id` should be passed
885                 /// back to the ChannelManager through [`ChannelManager::accept_inbound_channel`] to accept,
886                 /// or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject.
887                 ///
888                 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
889                 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
890                 temporary_channel_id: [u8; 32],
891                 /// The node_id of the counterparty requesting to open the channel.
892                 ///
893                 /// When responding to the request, the `counterparty_node_id` should be passed
894                 /// back to the `ChannelManager` through [`ChannelManager::accept_inbound_channel`] to
895                 /// accept the request, or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject the
896                 /// request.
897                 ///
898                 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
899                 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
900                 counterparty_node_id: PublicKey,
901                 /// The channel value of the requested channel.
902                 funding_satoshis: u64,
903                 /// Our starting balance in the channel if the request is accepted, in milli-satoshi.
904                 push_msat: u64,
905                 /// The features that this channel will operate with. If you reject the channel, a
906                 /// well-behaved counterparty may automatically re-attempt the channel with a new set of
907                 /// feature flags.
908                 ///
909                 /// Note that if [`ChannelTypeFeatures::supports_scid_privacy`] returns true on this type,
910                 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
911                 /// 0.0.106.
912                 ///
913                 /// Furthermore, note that if [`ChannelTypeFeatures::supports_zero_conf`] returns true on this type,
914                 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
915                 /// 0.0.107. Channels setting this type also need to get manually accepted via
916                 /// [`crate::ln::channelmanager::ChannelManager::accept_inbound_channel_from_trusted_peer_0conf`],
917                 /// or will be rejected otherwise.
918                 ///
919                 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
920                 channel_type: ChannelTypeFeatures,
921         },
922         /// Indicates that the HTLC was accepted, but could not be processed when or after attempting to
923         /// forward it.
924         ///
925         /// Some scenarios where this event may be sent include:
926         /// * Insufficient capacity in the outbound channel
927         /// * While waiting to forward the HTLC, the channel it is meant to be forwarded through closes
928         /// * When an unknown SCID is requested for forwarding a payment.
929         /// * Claiming an amount for an MPP payment that exceeds the HTLC total
930         /// * The HTLC has timed out
931         ///
932         /// This event, however, does not get generated if an HTLC fails to meet the forwarding
933         /// requirements (i.e. insufficient fees paid, or a CLTV that is too soon).
934         HTLCHandlingFailed {
935                 /// The channel over which the HTLC was received.
936                 prev_channel_id: [u8; 32],
937                 /// Destination of the HTLC that failed to be processed.
938                 failed_next_destination: HTLCDestination,
939         },
940         #[cfg(anchors)]
941         /// Indicates that a transaction originating from LDK needs to have its fee bumped. This event
942         /// requires confirmed external funds to be readily available to spend.
943         ///
944         /// LDK does not currently generate this event. It is limited to the scope of channels with
945         /// anchor outputs, which will be introduced in a future release.
946         BumpTransaction(BumpTransactionEvent),
947 }
948
949 impl Writeable for Event {
950         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
951                 match self {
952                         &Event::FundingGenerationReady { .. } => {
953                                 0u8.write(writer)?;
954                                 // We never write out FundingGenerationReady events as, upon disconnection, peers
955                                 // drop any channels which have not yet exchanged funding_signed.
956                         },
957                         &Event::PaymentClaimable { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id, ref via_channel_id, ref via_user_channel_id } => {
958                                 1u8.write(writer)?;
959                                 let mut payment_secret = None;
960                                 let payment_preimage;
961                                 match &purpose {
962                                         PaymentPurpose::InvoicePayment { payment_preimage: preimage, payment_secret: secret } => {
963                                                 payment_secret = Some(secret);
964                                                 payment_preimage = *preimage;
965                                         },
966                                         PaymentPurpose::SpontaneousPayment(preimage) => {
967                                                 payment_preimage = Some(*preimage);
968                                         }
969                                 }
970                                 write_tlv_fields!(writer, {
971                                         (0, payment_hash, required),
972                                         (1, receiver_node_id, option),
973                                         (2, payment_secret, option),
974                                         (3, via_channel_id, option),
975                                         (4, amount_msat, required),
976                                         (5, via_user_channel_id, option),
977                                         (6, 0u64, required), // user_payment_id required for compatibility with 0.0.103 and earlier
978                                         (8, payment_preimage, option),
979                                 });
980                         },
981                         &Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
982                                 2u8.write(writer)?;
983                                 write_tlv_fields!(writer, {
984                                         (0, payment_preimage, required),
985                                         (1, payment_hash, required),
986                                         (3, payment_id, option),
987                                         (5, fee_paid_msat, option),
988                                 });
989                         },
990                         &Event::PaymentPathFailed {
991                                 ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update,
992                                 ref all_paths_failed, ref path, ref short_channel_id, ref retry,
993                                 #[cfg(test)]
994                                 ref error_code,
995                                 #[cfg(test)]
996                                 ref error_data,
997                         } => {
998                                 3u8.write(writer)?;
999                                 #[cfg(test)]
1000                                 error_code.write(writer)?;
1001                                 #[cfg(test)]
1002                                 error_data.write(writer)?;
1003                                 write_tlv_fields!(writer, {
1004                                         (0, payment_hash, required),
1005                                         (1, network_update, option),
1006                                         (2, payment_failed_permanently, required),
1007                                         (3, all_paths_failed, required),
1008                                         (5, *path, vec_type),
1009                                         (7, short_channel_id, option),
1010                                         (9, retry, option),
1011                                         (11, payment_id, option),
1012                                 });
1013                         },
1014                         &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
1015                                 4u8.write(writer)?;
1016                                 // Note that we now ignore these on the read end as we'll re-generate them in
1017                                 // ChannelManager, we write them here only for backwards compatibility.
1018                         },
1019                         &Event::SpendableOutputs { ref outputs } => {
1020                                 5u8.write(writer)?;
1021                                 write_tlv_fields!(writer, {
1022                                         (0, WithoutLength(outputs), required),
1023                                 });
1024                         },
1025                         &Event::HTLCIntercepted { requested_next_hop_scid, payment_hash, inbound_amount_msat, expected_outbound_amount_msat, intercept_id } => {
1026                                 6u8.write(writer)?;
1027                                 let intercept_scid = InterceptNextHop::FakeScid { requested_next_hop_scid };
1028                                 write_tlv_fields!(writer, {
1029                                         (0, intercept_id, required),
1030                                         (2, intercept_scid, required),
1031                                         (4, payment_hash, required),
1032                                         (6, inbound_amount_msat, required),
1033                                         (8, expected_outbound_amount_msat, required),
1034                                 });
1035                         }
1036                         &Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
1037                                 7u8.write(writer)?;
1038                                 write_tlv_fields!(writer, {
1039                                         (0, fee_earned_msat, option),
1040                                         (1, prev_channel_id, option),
1041                                         (2, claim_from_onchain_tx, required),
1042                                         (3, next_channel_id, option),
1043                                 });
1044                         },
1045                         &Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason } => {
1046                                 9u8.write(writer)?;
1047                                 // `user_channel_id` used to be a single u64 value. In order to remain backwards
1048                                 // compatible with versions prior to 0.0.113, the u128 is serialized as two
1049                                 // separate u64 values.
1050                                 let user_channel_id_low = *user_channel_id as u64;
1051                                 let user_channel_id_high = (*user_channel_id >> 64) as u64;
1052                                 write_tlv_fields!(writer, {
1053                                         (0, channel_id, required),
1054                                         (1, user_channel_id_low, required),
1055                                         (2, reason, required),
1056                                         (3, user_channel_id_high, required),
1057                                 });
1058                         },
1059                         &Event::DiscardFunding { ref channel_id, ref transaction } => {
1060                                 11u8.write(writer)?;
1061                                 write_tlv_fields!(writer, {
1062                                         (0, channel_id, required),
1063                                         (2, transaction, required)
1064                                 })
1065                         },
1066                         &Event::PaymentPathSuccessful { ref payment_id, ref payment_hash, ref path } => {
1067                                 13u8.write(writer)?;
1068                                 write_tlv_fields!(writer, {
1069                                         (0, payment_id, required),
1070                                         (2, payment_hash, option),
1071                                         (4, *path, vec_type)
1072                                 })
1073                         },
1074                         &Event::PaymentFailed { ref payment_id, ref payment_hash } => {
1075                                 15u8.write(writer)?;
1076                                 write_tlv_fields!(writer, {
1077                                         (0, payment_id, required),
1078                                         (2, payment_hash, required),
1079                                 })
1080                         },
1081                         &Event::OpenChannelRequest { .. } => {
1082                                 17u8.write(writer)?;
1083                                 // We never write the OpenChannelRequest events as, upon disconnection, peers
1084                                 // drop any channels which have not yet exchanged funding_signed.
1085                         },
1086                         &Event::PaymentClaimed { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id } => {
1087                                 19u8.write(writer)?;
1088                                 write_tlv_fields!(writer, {
1089                                         (0, payment_hash, required),
1090                                         (1, receiver_node_id, option),
1091                                         (2, purpose, required),
1092                                         (4, amount_msat, required),
1093                                 });
1094                         },
1095                         &Event::ProbeSuccessful { ref payment_id, ref payment_hash, ref path } => {
1096                                 21u8.write(writer)?;
1097                                 write_tlv_fields!(writer, {
1098                                         (0, payment_id, required),
1099                                         (2, payment_hash, required),
1100                                         (4, *path, vec_type)
1101                                 })
1102                         },
1103                         &Event::ProbeFailed { ref payment_id, ref payment_hash, ref path, ref short_channel_id } => {
1104                                 23u8.write(writer)?;
1105                                 write_tlv_fields!(writer, {
1106                                         (0, payment_id, required),
1107                                         (2, payment_hash, required),
1108                                         (4, *path, vec_type),
1109                                         (6, short_channel_id, option),
1110                                 })
1111                         },
1112                         &Event::HTLCHandlingFailed { ref prev_channel_id, ref failed_next_destination } => {
1113                                 25u8.write(writer)?;
1114                                 write_tlv_fields!(writer, {
1115                                         (0, prev_channel_id, required),
1116                                         (2, failed_next_destination, required),
1117                                 })
1118                         },
1119                         #[cfg(anchors)]
1120                         &Event::BumpTransaction(ref event)=> {
1121                                 27u8.write(writer)?;
1122                                 match event {
1123                                         // We never write the ChannelClose|HTLCResolution events as they'll be replayed
1124                                         // upon restarting anyway if they remain unresolved.
1125                                         BumpTransactionEvent::ChannelClose { .. } => {}
1126                                         BumpTransactionEvent::HTLCResolution { .. } => {}
1127                                 }
1128                                 write_tlv_fields!(writer, {}); // Write a length field for forwards compat
1129                         }
1130                         &Event::ChannelReady { ref channel_id, ref user_channel_id, ref counterparty_node_id, ref channel_type } => {
1131                                 29u8.write(writer)?;
1132                                 write_tlv_fields!(writer, {
1133                                         (0, channel_id, required),
1134                                         (2, user_channel_id, required),
1135                                         (4, counterparty_node_id, required),
1136                                         (6, channel_type, required),
1137                                 });
1138                         },
1139                         // Note that, going forward, all new events must only write data inside of
1140                         // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
1141                         // data via `write_tlv_fields`.
1142                 }
1143                 Ok(())
1144         }
1145 }
1146 impl MaybeReadable for Event {
1147         fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
1148                 match Readable::read(reader)? {
1149                         // Note that we do not write a length-prefixed TLV for FundingGenerationReady events,
1150                         // unlike all other events, thus we return immediately here.
1151                         0u8 => Ok(None),
1152                         1u8 => {
1153                                 let f = || {
1154                                         let mut payment_hash = PaymentHash([0; 32]);
1155                                         let mut payment_preimage = None;
1156                                         let mut payment_secret = None;
1157                                         let mut amount_msat = 0;
1158                                         let mut receiver_node_id = None;
1159                                         let mut _user_payment_id = None::<u64>; // For compatibility with 0.0.103 and earlier
1160                                         let mut via_channel_id = None;
1161                                         let mut via_user_channel_id = None;
1162                                         read_tlv_fields!(reader, {
1163                                                 (0, payment_hash, required),
1164                                                 (1, receiver_node_id, option),
1165                                                 (2, payment_secret, option),
1166                                                 (3, via_channel_id, option),
1167                                                 (4, amount_msat, required),
1168                                                 (5, via_user_channel_id, option),
1169                                                 (6, _user_payment_id, option),
1170                                                 (8, payment_preimage, option),
1171                                         });
1172                                         let purpose = match payment_secret {
1173                                                 Some(secret) => PaymentPurpose::InvoicePayment {
1174                                                         payment_preimage,
1175                                                         payment_secret: secret
1176                                                 },
1177                                                 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
1178                                                 None => return Err(msgs::DecodeError::InvalidValue),
1179                                         };
1180                                         Ok(Some(Event::PaymentClaimable {
1181                                                 receiver_node_id,
1182                                                 payment_hash,
1183                                                 amount_msat,
1184                                                 purpose,
1185                                                 via_channel_id,
1186                                                 via_user_channel_id,
1187                                         }))
1188                                 };
1189                                 f()
1190                         },
1191                         2u8 => {
1192                                 let f = || {
1193                                         let mut payment_preimage = PaymentPreimage([0; 32]);
1194                                         let mut payment_hash = None;
1195                                         let mut payment_id = None;
1196                                         let mut fee_paid_msat = None;
1197                                         read_tlv_fields!(reader, {
1198                                                 (0, payment_preimage, required),
1199                                                 (1, payment_hash, option),
1200                                                 (3, payment_id, option),
1201                                                 (5, fee_paid_msat, option),
1202                                         });
1203                                         if payment_hash.is_none() {
1204                                                 payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()));
1205                                         }
1206                                         Ok(Some(Event::PaymentSent {
1207                                                 payment_id,
1208                                                 payment_preimage,
1209                                                 payment_hash: payment_hash.unwrap(),
1210                                                 fee_paid_msat,
1211                                         }))
1212                                 };
1213                                 f()
1214                         },
1215                         3u8 => {
1216                                 let f = || {
1217                                         #[cfg(test)]
1218                                         let error_code = Readable::read(reader)?;
1219                                         #[cfg(test)]
1220                                         let error_data = Readable::read(reader)?;
1221                                         let mut payment_hash = PaymentHash([0; 32]);
1222                                         let mut payment_failed_permanently = false;
1223                                         let mut network_update = None;
1224                                         let mut all_paths_failed = Some(true);
1225                                         let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1226                                         let mut short_channel_id = None;
1227                                         let mut retry = None;
1228                                         let mut payment_id = None;
1229                                         read_tlv_fields!(reader, {
1230                                                 (0, payment_hash, required),
1231                                                 (1, network_update, ignorable),
1232                                                 (2, payment_failed_permanently, required),
1233                                                 (3, all_paths_failed, option),
1234                                                 (5, path, vec_type),
1235                                                 (7, short_channel_id, option),
1236                                                 (9, retry, option),
1237                                                 (11, payment_id, option),
1238                                         });
1239                                         Ok(Some(Event::PaymentPathFailed {
1240                                                 payment_id,
1241                                                 payment_hash,
1242                                                 payment_failed_permanently,
1243                                                 network_update,
1244                                                 all_paths_failed: all_paths_failed.unwrap(),
1245                                                 path: path.unwrap(),
1246                                                 short_channel_id,
1247                                                 retry,
1248                                                 #[cfg(test)]
1249                                                 error_code,
1250                                                 #[cfg(test)]
1251                                                 error_data,
1252                                         }))
1253                                 };
1254                                 f()
1255                         },
1256                         4u8 => Ok(None),
1257                         5u8 => {
1258                                 let f = || {
1259                                         let mut outputs = WithoutLength(Vec::new());
1260                                         read_tlv_fields!(reader, {
1261                                                 (0, outputs, required),
1262                                         });
1263                                         Ok(Some(Event::SpendableOutputs { outputs: outputs.0 }))
1264                                 };
1265                                 f()
1266                         },
1267                         6u8 => {
1268                                 let mut payment_hash = PaymentHash([0; 32]);
1269                                 let mut intercept_id = InterceptId([0; 32]);
1270                                 let mut requested_next_hop_scid = InterceptNextHop::FakeScid { requested_next_hop_scid: 0 };
1271                                 let mut inbound_amount_msat = 0;
1272                                 let mut expected_outbound_amount_msat = 0;
1273                                 read_tlv_fields!(reader, {
1274                                         (0, intercept_id, required),
1275                                         (2, requested_next_hop_scid, required),
1276                                         (4, payment_hash, required),
1277                                         (6, inbound_amount_msat, required),
1278                                         (8, expected_outbound_amount_msat, required),
1279                                 });
1280                                 let next_scid = match requested_next_hop_scid {
1281                                         InterceptNextHop::FakeScid { requested_next_hop_scid: scid } => scid
1282                                 };
1283                                 Ok(Some(Event::HTLCIntercepted {
1284                                         payment_hash,
1285                                         requested_next_hop_scid: next_scid,
1286                                         inbound_amount_msat,
1287                                         expected_outbound_amount_msat,
1288                                         intercept_id,
1289                                 }))
1290                         },
1291                         7u8 => {
1292                                 let f = || {
1293                                         let mut fee_earned_msat = None;
1294                                         let mut prev_channel_id = None;
1295                                         let mut claim_from_onchain_tx = false;
1296                                         let mut next_channel_id = None;
1297                                         read_tlv_fields!(reader, {
1298                                                 (0, fee_earned_msat, option),
1299                                                 (1, prev_channel_id, option),
1300                                                 (2, claim_from_onchain_tx, required),
1301                                                 (3, next_channel_id, option),
1302                                         });
1303                                         Ok(Some(Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id }))
1304                                 };
1305                                 f()
1306                         },
1307                         9u8 => {
1308                                 let f = || {
1309                                         let mut channel_id = [0; 32];
1310                                         let mut reason = None;
1311                                         let mut user_channel_id_low_opt: Option<u64> = None;
1312                                         let mut user_channel_id_high_opt: Option<u64> = None;
1313                                         read_tlv_fields!(reader, {
1314                                                 (0, channel_id, required),
1315                                                 (1, user_channel_id_low_opt, option),
1316                                                 (2, reason, ignorable),
1317                                                 (3, user_channel_id_high_opt, option),
1318                                         });
1319                                         if reason.is_none() { return Ok(None); }
1320
1321                                         // `user_channel_id` used to be a single u64 value. In order to remain
1322                                         // backwards compatible with versions prior to 0.0.113, the u128 is serialized
1323                                         // as two separate u64 values.
1324                                         let user_channel_id = (user_channel_id_low_opt.unwrap_or(0) as u128) +
1325                                                 ((user_channel_id_high_opt.unwrap_or(0) as u128) << 64);
1326
1327                                         Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: reason.unwrap() }))
1328                                 };
1329                                 f()
1330                         },
1331                         11u8 => {
1332                                 let f = || {
1333                                         let mut channel_id = [0; 32];
1334                                         let mut transaction = Transaction{ version: 2, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
1335                                         read_tlv_fields!(reader, {
1336                                                 (0, channel_id, required),
1337                                                 (2, transaction, required),
1338                                         });
1339                                         Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
1340                                 };
1341                                 f()
1342                         },
1343                         13u8 => {
1344                                 let f = || {
1345                                         let mut payment_id = PaymentId([0; 32]);
1346                                         let mut payment_hash = None;
1347                                         let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1348                                         read_tlv_fields!(reader, {
1349                                                 (0, payment_id, required),
1350                                                 (2, payment_hash, option),
1351                                                 (4, path, vec_type),
1352                                         });
1353                                         Ok(Some(Event::PaymentPathSuccessful {
1354                                                 payment_id,
1355                                                 payment_hash,
1356                                                 path: path.unwrap(),
1357                                         }))
1358                                 };
1359                                 f()
1360                         },
1361                         15u8 => {
1362                                 let f = || {
1363                                         let mut payment_hash = PaymentHash([0; 32]);
1364                                         let mut payment_id = PaymentId([0; 32]);
1365                                         read_tlv_fields!(reader, {
1366                                                 (0, payment_id, required),
1367                                                 (2, payment_hash, required),
1368                                         });
1369                                         Ok(Some(Event::PaymentFailed {
1370                                                 payment_id,
1371                                                 payment_hash,
1372                                         }))
1373                                 };
1374                                 f()
1375                         },
1376                         17u8 => {
1377                                 // Value 17 is used for `Event::OpenChannelRequest`.
1378                                 Ok(None)
1379                         },
1380                         19u8 => {
1381                                 let f = || {
1382                                         let mut payment_hash = PaymentHash([0; 32]);
1383                                         let mut purpose = None;
1384                                         let mut amount_msat = 0;
1385                                         let mut receiver_node_id = None;
1386                                         read_tlv_fields!(reader, {
1387                                                 (0, payment_hash, required),
1388                                                 (1, receiver_node_id, option),
1389                                                 (2, purpose, ignorable),
1390                                                 (4, amount_msat, required),
1391                                         });
1392                                         if purpose.is_none() { return Ok(None); }
1393                                         Ok(Some(Event::PaymentClaimed {
1394                                                 receiver_node_id,
1395                                                 payment_hash,
1396                                                 purpose: purpose.unwrap(),
1397                                                 amount_msat,
1398                                         }))
1399                                 };
1400                                 f()
1401                         },
1402                         21u8 => {
1403                                 let f = || {
1404                                         let mut payment_id = PaymentId([0; 32]);
1405                                         let mut payment_hash = PaymentHash([0; 32]);
1406                                         let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1407                                         read_tlv_fields!(reader, {
1408                                                 (0, payment_id, required),
1409                                                 (2, payment_hash, required),
1410                                                 (4, path, vec_type),
1411                                         });
1412                                         Ok(Some(Event::ProbeSuccessful {
1413                                                 payment_id,
1414                                                 payment_hash,
1415                                                 path: path.unwrap(),
1416                                         }))
1417                                 };
1418                                 f()
1419                         },
1420                         23u8 => {
1421                                 let f = || {
1422                                         let mut payment_id = PaymentId([0; 32]);
1423                                         let mut payment_hash = PaymentHash([0; 32]);
1424                                         let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1425                                         let mut short_channel_id = None;
1426                                         read_tlv_fields!(reader, {
1427                                                 (0, payment_id, required),
1428                                                 (2, payment_hash, required),
1429                                                 (4, path, vec_type),
1430                                                 (6, short_channel_id, option),
1431                                         });
1432                                         Ok(Some(Event::ProbeFailed {
1433                                                 payment_id,
1434                                                 payment_hash,
1435                                                 path: path.unwrap(),
1436                                                 short_channel_id,
1437                                         }))
1438                                 };
1439                                 f()
1440                         },
1441                         25u8 => {
1442                                 let f = || {
1443                                         let mut prev_channel_id = [0; 32];
1444                                         let mut failed_next_destination_opt = None;
1445                                         read_tlv_fields!(reader, {
1446                                                 (0, prev_channel_id, required),
1447                                                 (2, failed_next_destination_opt, ignorable),
1448                                         });
1449                                         if let Some(failed_next_destination) = failed_next_destination_opt {
1450                                                 Ok(Some(Event::HTLCHandlingFailed {
1451                                                         prev_channel_id,
1452                                                         failed_next_destination,
1453                                                 }))
1454                                         } else {
1455                                                 // If we fail to read a `failed_next_destination` assume it's because
1456                                                 // `MaybeReadable::read` returned `Ok(None)`, though it's also possible we
1457                                                 // were simply missing the field.
1458                                                 Ok(None)
1459                                         }
1460                                 };
1461                                 f()
1462                         },
1463                         27u8 => Ok(None),
1464                         29u8 => {
1465                                 let f = || {
1466                                         let mut channel_id = [0; 32];
1467                                         let mut user_channel_id: u128 = 0;
1468                                         let mut counterparty_node_id = OptionDeserWrapper(None);
1469                                         let mut channel_type = OptionDeserWrapper(None);
1470                                         read_tlv_fields!(reader, {
1471                                                 (0, channel_id, required),
1472                                                 (2, user_channel_id, required),
1473                                                 (4, counterparty_node_id, required),
1474                                                 (6, channel_type, required),
1475                                         });
1476
1477                                         Ok(Some(Event::ChannelReady {
1478                                                 channel_id,
1479                                                 user_channel_id,
1480                                                 counterparty_node_id: counterparty_node_id.0.unwrap(),
1481                                                 channel_type: channel_type.0.unwrap()
1482                                         }))
1483                                 };
1484                                 f()
1485                         },
1486                         // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
1487                         // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
1488                         // reads.
1489                         x if x % 2 == 1 => {
1490                                 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
1491                                 // which prefixes the whole thing with a length BigSize. Because the event is
1492                                 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
1493                                 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
1494                                 // exactly the number of bytes specified, ignoring them entirely.
1495                                 let tlv_len: BigSize = Readable::read(reader)?;
1496                                 FixedLengthReader::new(reader, tlv_len.0)
1497                                         .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
1498                                 Ok(None)
1499                         },
1500                         _ => Err(msgs::DecodeError::InvalidValue)
1501                 }
1502         }
1503 }
1504
1505 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
1506 /// broadcast to most peers).
1507 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
1508 #[derive(Clone, Debug)]
1509 pub enum MessageSendEvent {
1510         /// Used to indicate that we've accepted a channel open and should send the accept_channel
1511         /// message provided to the given peer.
1512         SendAcceptChannel {
1513                 /// The node_id of the node which should receive this message
1514                 node_id: PublicKey,
1515                 /// The message which should be sent.
1516                 msg: msgs::AcceptChannel,
1517         },
1518         /// Used to indicate that we've initiated a channel open and should send the open_channel
1519         /// message provided to the given peer.
1520         SendOpenChannel {
1521                 /// The node_id of the node which should receive this message
1522                 node_id: PublicKey,
1523                 /// The message which should be sent.
1524                 msg: msgs::OpenChannel,
1525         },
1526         /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
1527         SendFundingCreated {
1528                 /// The node_id of the node which should receive this message
1529                 node_id: PublicKey,
1530                 /// The message which should be sent.
1531                 msg: msgs::FundingCreated,
1532         },
1533         /// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
1534         SendFundingSigned {
1535                 /// The node_id of the node which should receive this message
1536                 node_id: PublicKey,
1537                 /// The message which should be sent.
1538                 msg: msgs::FundingSigned,
1539         },
1540         /// Used to indicate that a channel_ready message should be sent to the peer with the given node_id.
1541         SendChannelReady {
1542                 /// The node_id of the node which should receive these message(s)
1543                 node_id: PublicKey,
1544                 /// The channel_ready message which should be sent.
1545                 msg: msgs::ChannelReady,
1546         },
1547         /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
1548         SendAnnouncementSignatures {
1549                 /// The node_id of the node which should receive these message(s)
1550                 node_id: PublicKey,
1551                 /// The announcement_signatures message which should be sent.
1552                 msg: msgs::AnnouncementSignatures,
1553         },
1554         /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
1555         /// message should be sent to the peer with the given node_id.
1556         UpdateHTLCs {
1557                 /// The node_id of the node which should receive these message(s)
1558                 node_id: PublicKey,
1559                 /// The update messages which should be sent. ALL messages in the struct should be sent!
1560                 updates: msgs::CommitmentUpdate,
1561         },
1562         /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
1563         SendRevokeAndACK {
1564                 /// The node_id of the node which should receive this message
1565                 node_id: PublicKey,
1566                 /// The message which should be sent.
1567                 msg: msgs::RevokeAndACK,
1568         },
1569         /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
1570         SendClosingSigned {
1571                 /// The node_id of the node which should receive this message
1572                 node_id: PublicKey,
1573                 /// The message which should be sent.
1574                 msg: msgs::ClosingSigned,
1575         },
1576         /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
1577         SendShutdown {
1578                 /// The node_id of the node which should receive this message
1579                 node_id: PublicKey,
1580                 /// The message which should be sent.
1581                 msg: msgs::Shutdown,
1582         },
1583         /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
1584         SendChannelReestablish {
1585                 /// The node_id of the node which should receive this message
1586                 node_id: PublicKey,
1587                 /// The message which should be sent.
1588                 msg: msgs::ChannelReestablish,
1589         },
1590         /// Used to send a channel_announcement and channel_update to a specific peer, likely on
1591         /// initial connection to ensure our peers know about our channels.
1592         SendChannelAnnouncement {
1593                 /// The node_id of the node which should receive this message
1594                 node_id: PublicKey,
1595                 /// The channel_announcement which should be sent.
1596                 msg: msgs::ChannelAnnouncement,
1597                 /// The followup channel_update which should be sent.
1598                 update_msg: msgs::ChannelUpdate,
1599         },
1600         /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
1601         /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
1602         ///
1603         /// Note that after doing so, you very likely (unless you did so very recently) want to
1604         /// broadcast a node_announcement (e.g. via [`PeerManager::broadcast_node_announcement`]). This
1605         /// ensures that any nodes which see our channel_announcement also have a relevant
1606         /// node_announcement, including relevant feature flags which may be important for routing
1607         /// through or to us.
1608         ///
1609         /// [`PeerManager::broadcast_node_announcement`]: crate::ln::peer_handler::PeerManager::broadcast_node_announcement
1610         BroadcastChannelAnnouncement {
1611                 /// The channel_announcement which should be sent.
1612                 msg: msgs::ChannelAnnouncement,
1613                 /// The followup channel_update which should be sent.
1614                 update_msg: msgs::ChannelUpdate,
1615         },
1616         /// Used to indicate that a channel_update should be broadcast to all peers.
1617         BroadcastChannelUpdate {
1618                 /// The channel_update which should be sent.
1619                 msg: msgs::ChannelUpdate,
1620         },
1621         /// Used to indicate that a channel_update should be sent to a single peer.
1622         /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
1623         /// private channel and we shouldn't be informing all of our peers of channel parameters.
1624         SendChannelUpdate {
1625                 /// The node_id of the node which should receive this message
1626                 node_id: PublicKey,
1627                 /// The channel_update which should be sent.
1628                 msg: msgs::ChannelUpdate,
1629         },
1630         /// Broadcast an error downstream to be handled
1631         HandleError {
1632                 /// The node_id of the node which should receive this message
1633                 node_id: PublicKey,
1634                 /// The action which should be taken.
1635                 action: msgs::ErrorAction
1636         },
1637         /// Query a peer for channels with funding transaction UTXOs in a block range.
1638         SendChannelRangeQuery {
1639                 /// The node_id of this message recipient
1640                 node_id: PublicKey,
1641                 /// The query_channel_range which should be sent.
1642                 msg: msgs::QueryChannelRange,
1643         },
1644         /// Request routing gossip messages from a peer for a list of channels identified by
1645         /// their short_channel_ids.
1646         SendShortIdsQuery {
1647                 /// The node_id of this message recipient
1648                 node_id: PublicKey,
1649                 /// The query_short_channel_ids which should be sent.
1650                 msg: msgs::QueryShortChannelIds,
1651         },
1652         /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
1653         /// emitted during processing of the query.
1654         SendReplyChannelRange {
1655                 /// The node_id of this message recipient
1656                 node_id: PublicKey,
1657                 /// The reply_channel_range which should be sent.
1658                 msg: msgs::ReplyChannelRange,
1659         },
1660         /// Sends a timestamp filter for inbound gossip. This should be sent on each new connection to
1661         /// enable receiving gossip messages from the peer.
1662         SendGossipTimestampFilter {
1663                 /// The node_id of this message recipient
1664                 node_id: PublicKey,
1665                 /// The gossip_timestamp_filter which should be sent.
1666                 msg: msgs::GossipTimestampFilter,
1667         },
1668 }
1669
1670 /// A trait indicating an object may generate message send events
1671 pub trait MessageSendEventsProvider {
1672         /// Gets the list of pending events which were generated by previous actions, clearing the list
1673         /// in the process.
1674         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
1675 }
1676
1677 /// A trait indicating an object may generate onion messages to send
1678 pub trait OnionMessageProvider {
1679         /// Gets the next pending onion message for the peer with the given node id.
1680         fn next_onion_message_for_peer(&self, peer_node_id: PublicKey) -> Option<msgs::OnionMessage>;
1681 }
1682
1683 /// A trait indicating an object may generate events.
1684 ///
1685 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
1686 ///
1687 /// Implementations of this trait may also feature an async version of event handling, as shown with
1688 /// [`ChannelManager::process_pending_events_async`] and
1689 /// [`ChainMonitor::process_pending_events_async`].
1690 ///
1691 /// # Requirements
1692 ///
1693 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
1694 /// event since the last invocation.
1695 ///
1696 /// In order to ensure no [`Event`]s are lost, implementors of this trait will persist [`Event`]s
1697 /// and replay any unhandled events on startup. An [`Event`] is considered handled when
1698 /// [`process_pending_events`] returns, thus handlers MUST fully handle [`Event`]s and persist any
1699 /// relevant changes to disk *before* returning.
1700 ///
1701 /// Further, because an application may crash between an [`Event`] being handled and the
1702 /// implementor of this trait being re-serialized, [`Event`] handling must be idempotent - in
1703 /// effect, [`Event`]s may be replayed.
1704 ///
1705 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
1706 /// consult the provider's documentation on the implication of processing events and how a handler
1707 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
1708 /// [`ChainMonitor::process_pending_events`]).
1709 ///
1710 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
1711 /// own type(s).
1712 ///
1713 /// [`process_pending_events`]: Self::process_pending_events
1714 /// [`handle_event`]: EventHandler::handle_event
1715 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
1716 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
1717 /// [`ChannelManager::process_pending_events_async`]: crate::ln::channelmanager::ChannelManager::process_pending_events_async
1718 /// [`ChainMonitor::process_pending_events_async`]: crate::chain::chainmonitor::ChainMonitor::process_pending_events_async
1719 pub trait EventsProvider {
1720         /// Processes any events generated since the last call using the given event handler.
1721         ///
1722         /// See the trait-level documentation for requirements.
1723         fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
1724 }
1725
1726 /// A trait implemented for objects handling events from [`EventsProvider`].
1727 ///
1728 /// An async variation also exists for implementations of [`EventsProvider`] that support async
1729 /// event handling. The async event handler should satisfy the generic bounds: `F:
1730 /// core::future::Future, H: Fn(Event) -> F`.
1731 pub trait EventHandler {
1732         /// Handles the given [`Event`].
1733         ///
1734         /// See [`EventsProvider`] for details that must be considered when implementing this method.
1735         fn handle_event(&self, event: Event);
1736 }
1737
1738 impl<F> EventHandler for F where F: Fn(Event) {
1739         fn handle_event(&self, event: Event) {
1740                 self(event)
1741         }
1742 }
1743
1744 impl<T: EventHandler> EventHandler for Arc<T> {
1745         fn handle_event(&self, event: Event) {
1746                 self.deref().handle_event(event)
1747         }
1748 }