Add the ability to broadcast gossip msgs via the event pipeline
[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, PartialEq, Eq)]
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::provide_channel_parameters`].
261         ///
262         /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
263         /// [`BaseSign::provide_channel_parameters`]: crate::chain::keysinterface::BaseSign::provide_channel_parameters
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, PartialEq, Eq)]
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`] or [`ChannelManager::fail_htlc_backwards_with_reason`]
495         /// to free up resources for this HTLC and avoid network congestion.
496         /// If you fail to call either [`ChannelManager::claim_funds`], [`ChannelManager::fail_htlc_backwards`],
497         /// or [`ChannelManager::fail_htlc_backwards_with_reason`] 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         /// [`ChannelManager::fail_htlc_backwards_with_reason`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards_with_reason
510         PaymentClaimable {
511                 /// The node that will receive the payment after it has been claimed.
512                 /// This is useful to identify payments received via [phantom nodes].
513                 /// This field will always be filled in when the event was generated by LDK versions
514                 /// 0.0.113 and above.
515                 ///
516                 /// [phantom nodes]: crate::chain::keysinterface::PhantomKeysManager
517                 receiver_node_id: Option<PublicKey>,
518                 /// The hash for which the preimage should be handed to the ChannelManager. Note that LDK will
519                 /// not stop you from registering duplicate payment hashes for inbound payments.
520                 payment_hash: PaymentHash,
521                 /// The value, in thousandths of a satoshi, that this payment is for.
522                 amount_msat: u64,
523                 /// Information for claiming this received payment, based on whether the purpose of the
524                 /// payment is to pay an invoice or to send a spontaneous payment.
525                 purpose: PaymentPurpose,
526                 /// The `channel_id` indicating over which channel we received the payment.
527                 via_channel_id: Option<[u8; 32]>,
528                 /// The `user_channel_id` indicating over which channel we received the payment.
529                 via_user_channel_id: Option<u128>,
530         },
531         /// Indicates a payment has been claimed and we've received money!
532         ///
533         /// This most likely occurs when [`ChannelManager::claim_funds`] has been called in response
534         /// to an [`Event::PaymentClaimable`]. However, if we previously crashed during a
535         /// [`ChannelManager::claim_funds`] call you may see this event without a corresponding
536         /// [`Event::PaymentClaimable`] event.
537         ///
538         /// # Note
539         /// LDK will not stop an inbound payment from being paid multiple times, so multiple
540         /// `PaymentClaimable` events may be generated for the same payment. If you then call
541         /// [`ChannelManager::claim_funds`] twice for the same [`Event::PaymentClaimable`] you may get
542         /// multiple `PaymentClaimed` events.
543         ///
544         /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
545         PaymentClaimed {
546                 /// The node that received the payment.
547                 /// This is useful to identify payments which were received via [phantom nodes].
548                 /// This field will always be filled in when the event was generated by LDK versions
549                 /// 0.0.113 and above.
550                 ///
551                 /// [phantom nodes]: crate::chain::keysinterface::PhantomKeysManager
552                 receiver_node_id: Option<PublicKey>,
553                 /// The payment hash of the claimed payment. Note that LDK will not stop you from
554                 /// registering duplicate payment hashes for inbound payments.
555                 payment_hash: PaymentHash,
556                 /// The value, in thousandths of a satoshi, that this payment is for.
557                 amount_msat: u64,
558                 /// The purpose of the claimed payment, i.e. whether the payment was for an invoice or a
559                 /// spontaneous payment.
560                 purpose: PaymentPurpose,
561         },
562         /// Indicates an outbound payment we made succeeded (i.e. it made it all the way to its target
563         /// and we got back the payment preimage for it).
564         ///
565         /// Note for MPP payments: in rare cases, this event may be preceded by a `PaymentPathFailed`
566         /// event. In this situation, you SHOULD treat this payment as having succeeded.
567         PaymentSent {
568                 /// The id returned by [`ChannelManager::send_payment`] and used with
569                 /// [`ChannelManager::retry_payment`].
570                 ///
571                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
572                 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
573                 payment_id: Option<PaymentId>,
574                 /// The preimage to the hash given to ChannelManager::send_payment.
575                 /// Note that this serves as a payment receipt, if you wish to have such a thing, you must
576                 /// store it somehow!
577                 payment_preimage: PaymentPreimage,
578                 /// The hash that was given to [`ChannelManager::send_payment`].
579                 ///
580                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
581                 payment_hash: PaymentHash,
582                 /// The total fee which was spent at intermediate hops in this payment, across all paths.
583                 ///
584                 /// Note that, like [`Route::get_total_fees`] this does *not* include any potential
585                 /// overpayment to the recipient node.
586                 ///
587                 /// If the recipient or an intermediate node misbehaves and gives us free money, this may
588                 /// overstate the amount paid, though this is unlikely.
589                 ///
590                 /// [`Route::get_total_fees`]: crate::routing::router::Route::get_total_fees
591                 fee_paid_msat: Option<u64>,
592         },
593         /// Indicates an outbound payment failed. Individual [`Event::PaymentPathFailed`] events
594         /// provide failure information for each MPP part in the payment.
595         ///
596         /// This event is provided once there are no further pending HTLCs for the payment and the
597         /// payment is no longer retryable due to [`ChannelManager::abandon_payment`] having been
598         /// called for the corresponding payment.
599         ///
600         /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
601         PaymentFailed {
602                 /// The id returned by [`ChannelManager::send_payment`] and used with
603                 /// [`ChannelManager::retry_payment`] and [`ChannelManager::abandon_payment`].
604                 ///
605                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
606                 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
607                 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
608                 payment_id: PaymentId,
609                 /// The hash that was given to [`ChannelManager::send_payment`].
610                 ///
611                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
612                 payment_hash: PaymentHash,
613         },
614         /// Indicates that a path for an outbound payment was successful.
615         ///
616         /// Always generated after [`Event::PaymentSent`] and thus useful for scoring channels. See
617         /// [`Event::PaymentSent`] for obtaining the payment preimage.
618         PaymentPathSuccessful {
619                 /// The id returned by [`ChannelManager::send_payment`] and used with
620                 /// [`ChannelManager::retry_payment`].
621                 ///
622                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
623                 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
624                 payment_id: PaymentId,
625                 /// The hash that was given to [`ChannelManager::send_payment`].
626                 ///
627                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
628                 payment_hash: Option<PaymentHash>,
629                 /// The payment path that was successful.
630                 ///
631                 /// May contain a closed channel if the HTLC sent along the path was fulfilled on chain.
632                 path: Vec<RouteHop>,
633         },
634         /// Indicates an outbound HTLC we sent failed. Probably some intermediary node dropped
635         /// something. You may wish to retry with a different route.
636         ///
637         /// If you have given up retrying this payment and wish to fail it, you MUST call
638         /// [`ChannelManager::abandon_payment`] at least once for a given [`PaymentId`] or memory
639         /// related to payment tracking will leak.
640         ///
641         /// Note that this does *not* indicate that all paths for an MPP payment have failed, see
642         /// [`Event::PaymentFailed`] and [`all_paths_failed`].
643         ///
644         /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
645         /// [`all_paths_failed`]: Self::PaymentPathFailed::all_paths_failed
646         PaymentPathFailed {
647                 /// The id returned by [`ChannelManager::send_payment`] and used with
648                 /// [`ChannelManager::retry_payment`] and [`ChannelManager::abandon_payment`].
649                 ///
650                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
651                 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
652                 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
653                 payment_id: Option<PaymentId>,
654                 /// The hash that was given to [`ChannelManager::send_payment`].
655                 ///
656                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
657                 payment_hash: PaymentHash,
658                 /// Indicates the payment was rejected for some reason by the recipient. This implies that
659                 /// the payment has failed, not just the route in question. If this is not set, you may
660                 /// retry the payment via a different route.
661                 payment_failed_permanently: bool,
662                 /// Any failure information conveyed via the Onion return packet by a node along the failed
663                 /// payment route.
664                 ///
665                 /// Should be applied to the [`NetworkGraph`] so that routing decisions can take into
666                 /// account the update.
667                 ///
668                 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
669                 network_update: Option<NetworkUpdate>,
670                 /// For both single-path and multi-path payments, this is set if all paths of the payment have
671                 /// failed. This will be set to false if (1) this is an MPP payment and (2) other parts of the
672                 /// larger MPP payment were still in flight when this event was generated.
673                 ///
674                 /// Note that if you are retrying individual MPP parts, using this value to determine if a
675                 /// payment has fully failed is race-y. Because multiple failures can happen prior to events
676                 /// being processed, you may retry in response to a first failure, with a second failure
677                 /// (with `all_paths_failed` set) still pending. Then, when the second failure is processed
678                 /// you will see `all_paths_failed` set even though the retry of the first failure still
679                 /// has an associated in-flight HTLC. See (1) for an example of such a failure.
680                 ///
681                 /// If you wish to retry individual MPP parts and learn when a payment has failed, you must
682                 /// call [`ChannelManager::abandon_payment`] and wait for a [`Event::PaymentFailed`] event.
683                 ///
684                 /// (1) <https://github.com/lightningdevkit/rust-lightning/issues/1164>
685                 ///
686                 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
687                 all_paths_failed: bool,
688                 /// The payment path that failed.
689                 path: Vec<RouteHop>,
690                 /// The channel responsible for the failed payment path.
691                 ///
692                 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
693                 /// may not refer to a channel in the public network graph. These aliases may also collide
694                 /// with channels in the public network graph.
695                 ///
696                 /// If this is `Some`, then the corresponding channel should be avoided when the payment is
697                 /// retried. May be `None` for older [`Event`] serializations.
698                 short_channel_id: Option<u64>,
699                 /// Parameters needed to compute a new [`Route`] when retrying the failed payment path.
700                 ///
701                 /// See [`find_route`] for details.
702                 ///
703                 /// [`Route`]: crate::routing::router::Route
704                 /// [`find_route`]: crate::routing::router::find_route
705                 retry: Option<RouteParameters>,
706 #[cfg(test)]
707                 error_code: Option<u16>,
708 #[cfg(test)]
709                 error_data: Option<Vec<u8>>,
710         },
711         /// Indicates that a probe payment we sent returned successful, i.e., only failed at the destination.
712         ProbeSuccessful {
713                 /// The id returned by [`ChannelManager::send_probe`].
714                 ///
715                 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
716                 payment_id: PaymentId,
717                 /// The hash generated by [`ChannelManager::send_probe`].
718                 ///
719                 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
720                 payment_hash: PaymentHash,
721                 /// The payment path that was successful.
722                 path: Vec<RouteHop>,
723         },
724         /// Indicates that a probe payment we sent failed at an intermediary node on the path.
725         ProbeFailed {
726                 /// The id returned by [`ChannelManager::send_probe`].
727                 ///
728                 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
729                 payment_id: PaymentId,
730                 /// The hash generated by [`ChannelManager::send_probe`].
731                 ///
732                 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
733                 payment_hash: PaymentHash,
734                 /// The payment path that failed.
735                 path: Vec<RouteHop>,
736                 /// The channel responsible for the failed probe.
737                 ///
738                 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
739                 /// may not refer to a channel in the public network graph. These aliases may also collide
740                 /// with channels in the public network graph.
741                 short_channel_id: Option<u64>,
742         },
743         /// Used to indicate that [`ChannelManager::process_pending_htlc_forwards`] should be called at
744         /// a time in the future.
745         ///
746         /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
747         PendingHTLCsForwardable {
748                 /// The minimum amount of time that should be waited prior to calling
749                 /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
750                 /// you should wait a random amount of time in roughly the range (now + time_forwardable,
751                 /// now + 5*time_forwardable).
752                 time_forwardable: Duration,
753         },
754         /// Used to indicate that we've intercepted an HTLC forward. This event will only be generated if
755         /// you've encoded an intercept scid in the receiver's invoice route hints using
756         /// [`ChannelManager::get_intercept_scid`] and have set [`UserConfig::accept_intercept_htlcs`].
757         ///
758         /// [`ChannelManager::forward_intercepted_htlc`] or
759         /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to this event. See
760         /// their docs for more information.
761         ///
762         /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
763         /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
764         /// [`ChannelManager::forward_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::forward_intercepted_htlc
765         /// [`ChannelManager::fail_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::fail_intercepted_htlc
766         HTLCIntercepted {
767                 /// An id to help LDK identify which HTLC is being forwarded or failed.
768                 intercept_id: InterceptId,
769                 /// The fake scid that was programmed as the next hop's scid, generated using
770                 /// [`ChannelManager::get_intercept_scid`].
771                 ///
772                 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
773                 requested_next_hop_scid: u64,
774                 /// The payment hash used for this HTLC.
775                 payment_hash: PaymentHash,
776                 /// How many msats were received on the inbound edge of this HTLC.
777                 inbound_amount_msat: u64,
778                 /// How many msats the payer intended to route to the next node. Depending on the reason you are
779                 /// intercepting this payment, you might take a fee by forwarding less than this amount.
780                 ///
781                 /// Note that LDK will NOT check that expected fees were factored into this value. You MUST
782                 /// check that whatever fee you want has been included here or subtract it as required. Further,
783                 /// LDK will not stop you from forwarding more than you received.
784                 expected_outbound_amount_msat: u64,
785         },
786         /// Used to indicate that an output which you should know how to spend was confirmed on chain
787         /// and is now spendable.
788         /// Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
789         /// counterparty spending them due to some kind of timeout. Thus, you need to store them
790         /// somewhere and spend them when you create on-chain transactions.
791         SpendableOutputs {
792                 /// The outputs which you should store as spendable by you.
793                 outputs: Vec<SpendableOutputDescriptor>,
794         },
795         /// This event is generated when a payment has been successfully forwarded through us and a
796         /// forwarding fee earned.
797         PaymentForwarded {
798                 /// The incoming channel between the previous node and us. This is only `None` for events
799                 /// generated or serialized by versions prior to 0.0.107.
800                 prev_channel_id: Option<[u8; 32]>,
801                 /// The outgoing channel between the next node and us. This is only `None` for events
802                 /// generated or serialized by versions prior to 0.0.107.
803                 next_channel_id: Option<[u8; 32]>,
804                 /// The fee, in milli-satoshis, which was earned as a result of the payment.
805                 ///
806                 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
807                 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
808                 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
809                 /// claimed the full value in millisatoshis from the source. In this case,
810                 /// `claim_from_onchain_tx` will be set.
811                 ///
812                 /// If the channel which sent us the payment has been force-closed, we will claim the funds
813                 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
814                 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
815                 /// `PaymentForwarded` events are generated for the same payment iff `fee_earned_msat` is
816                 /// `None`.
817                 fee_earned_msat: Option<u64>,
818                 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
819                 /// transaction.
820                 claim_from_onchain_tx: bool,
821         },
822         /// Used to indicate that a channel with the given `channel_id` is ready to
823         /// be used. This event is emitted either when the funding transaction has been confirmed
824         /// on-chain, or, in case of a 0conf channel, when both parties have confirmed the channel
825         /// establishment.
826         ChannelReady {
827                 /// The channel_id of the channel that is ready.
828                 channel_id: [u8; 32],
829                 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
830                 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
831                 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
832                 /// `user_channel_id` will be randomized for an inbound channel.
833                 ///
834                 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
835                 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
836                 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
837                 user_channel_id: u128,
838                 /// The node_id of the channel counterparty.
839                 counterparty_node_id: PublicKey,
840                 /// The features that this channel will operate with.
841                 channel_type: ChannelTypeFeatures,
842         },
843         /// Used to indicate that a previously opened channel with the given `channel_id` is in the
844         /// process of closure.
845         ChannelClosed  {
846                 /// The channel_id of the channel which has been closed. Note that on-chain transactions
847                 /// resolving the channel are likely still awaiting confirmation.
848                 channel_id: [u8; 32],
849                 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
850                 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
851                 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
852                 /// `user_channel_id` will be randomized for inbound channels.
853                 /// This may be zero for inbound channels serialized prior to 0.0.113 and will always be
854                 /// zero for objects serialized with LDK versions prior to 0.0.102.
855                 ///
856                 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
857                 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
858                 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
859                 user_channel_id: u128,
860                 /// The reason the channel was closed.
861                 reason: ClosureReason
862         },
863         /// Used to indicate to the user that they can abandon the funding transaction and recycle the
864         /// inputs for another purpose.
865         DiscardFunding {
866                 /// The channel_id of the channel which has been closed.
867                 channel_id: [u8; 32],
868                 /// The full transaction received from the user
869                 transaction: Transaction
870         },
871         /// Indicates a request to open a new channel by a peer.
872         ///
873         /// To accept the request, call [`ChannelManager::accept_inbound_channel`]. To reject the
874         /// request, call [`ChannelManager::force_close_without_broadcasting_txn`].
875         ///
876         /// The event is only triggered when a new open channel request is received and the
877         /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true.
878         ///
879         /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
880         /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
881         /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
882         OpenChannelRequest {
883                 /// The temporary channel ID of the channel requested to be opened.
884                 ///
885                 /// When responding to the request, the `temporary_channel_id` should be passed
886                 /// back to the ChannelManager through [`ChannelManager::accept_inbound_channel`] to accept,
887                 /// or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject.
888                 ///
889                 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
890                 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
891                 temporary_channel_id: [u8; 32],
892                 /// The node_id of the counterparty requesting to open the channel.
893                 ///
894                 /// When responding to the request, the `counterparty_node_id` should be passed
895                 /// back to the `ChannelManager` through [`ChannelManager::accept_inbound_channel`] to
896                 /// accept the request, or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject the
897                 /// request.
898                 ///
899                 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
900                 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
901                 counterparty_node_id: PublicKey,
902                 /// The channel value of the requested channel.
903                 funding_satoshis: u64,
904                 /// Our starting balance in the channel if the request is accepted, in milli-satoshi.
905                 push_msat: u64,
906                 /// The features that this channel will operate with. If you reject the channel, a
907                 /// well-behaved counterparty may automatically re-attempt the channel with a new set of
908                 /// feature flags.
909                 ///
910                 /// Note that if [`ChannelTypeFeatures::supports_scid_privacy`] returns true on this type,
911                 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
912                 /// 0.0.106.
913                 ///
914                 /// Furthermore, note that if [`ChannelTypeFeatures::supports_zero_conf`] returns true on this type,
915                 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
916                 /// 0.0.107. Channels setting this type also need to get manually accepted via
917                 /// [`crate::ln::channelmanager::ChannelManager::accept_inbound_channel_from_trusted_peer_0conf`],
918                 /// or will be rejected otherwise.
919                 ///
920                 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
921                 channel_type: ChannelTypeFeatures,
922         },
923         /// Indicates that the HTLC was accepted, but could not be processed when or after attempting to
924         /// forward it.
925         ///
926         /// Some scenarios where this event may be sent include:
927         /// * Insufficient capacity in the outbound channel
928         /// * While waiting to forward the HTLC, the channel it is meant to be forwarded through closes
929         /// * When an unknown SCID is requested for forwarding a payment.
930         /// * Claiming an amount for an MPP payment that exceeds the HTLC total
931         /// * The HTLC has timed out
932         ///
933         /// This event, however, does not get generated if an HTLC fails to meet the forwarding
934         /// requirements (i.e. insufficient fees paid, or a CLTV that is too soon).
935         HTLCHandlingFailed {
936                 /// The channel over which the HTLC was received.
937                 prev_channel_id: [u8; 32],
938                 /// Destination of the HTLC that failed to be processed.
939                 failed_next_destination: HTLCDestination,
940         },
941         #[cfg(anchors)]
942         /// Indicates that a transaction originating from LDK needs to have its fee bumped. This event
943         /// requires confirmed external funds to be readily available to spend.
944         ///
945         /// LDK does not currently generate this event. It is limited to the scope of channels with
946         /// anchor outputs, which will be introduced in a future release.
947         BumpTransaction(BumpTransactionEvent),
948 }
949
950 impl Writeable for Event {
951         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
952                 match self {
953                         &Event::FundingGenerationReady { .. } => {
954                                 0u8.write(writer)?;
955                                 // We never write out FundingGenerationReady events as, upon disconnection, peers
956                                 // drop any channels which have not yet exchanged funding_signed.
957                         },
958                         &Event::PaymentClaimable { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id, ref via_channel_id, ref via_user_channel_id } => {
959                                 1u8.write(writer)?;
960                                 let mut payment_secret = None;
961                                 let payment_preimage;
962                                 match &purpose {
963                                         PaymentPurpose::InvoicePayment { payment_preimage: preimage, payment_secret: secret } => {
964                                                 payment_secret = Some(secret);
965                                                 payment_preimage = *preimage;
966                                         },
967                                         PaymentPurpose::SpontaneousPayment(preimage) => {
968                                                 payment_preimage = Some(*preimage);
969                                         }
970                                 }
971                                 write_tlv_fields!(writer, {
972                                         (0, payment_hash, required),
973                                         (1, receiver_node_id, option),
974                                         (2, payment_secret, option),
975                                         (3, via_channel_id, option),
976                                         (4, amount_msat, required),
977                                         (5, via_user_channel_id, option),
978                                         (6, 0u64, required), // user_payment_id required for compatibility with 0.0.103 and earlier
979                                         (8, payment_preimage, option),
980                                 });
981                         },
982                         &Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
983                                 2u8.write(writer)?;
984                                 write_tlv_fields!(writer, {
985                                         (0, payment_preimage, required),
986                                         (1, payment_hash, required),
987                                         (3, payment_id, option),
988                                         (5, fee_paid_msat, option),
989                                 });
990                         },
991                         &Event::PaymentPathFailed {
992                                 ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update,
993                                 ref all_paths_failed, ref path, ref short_channel_id, ref retry,
994                                 #[cfg(test)]
995                                 ref error_code,
996                                 #[cfg(test)]
997                                 ref error_data,
998                         } => {
999                                 3u8.write(writer)?;
1000                                 #[cfg(test)]
1001                                 error_code.write(writer)?;
1002                                 #[cfg(test)]
1003                                 error_data.write(writer)?;
1004                                 write_tlv_fields!(writer, {
1005                                         (0, payment_hash, required),
1006                                         (1, network_update, option),
1007                                         (2, payment_failed_permanently, required),
1008                                         (3, all_paths_failed, required),
1009                                         (5, *path, vec_type),
1010                                         (7, short_channel_id, option),
1011                                         (9, retry, option),
1012                                         (11, payment_id, option),
1013                                 });
1014                         },
1015                         &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
1016                                 4u8.write(writer)?;
1017                                 // Note that we now ignore these on the read end as we'll re-generate them in
1018                                 // ChannelManager, we write them here only for backwards compatibility.
1019                         },
1020                         &Event::SpendableOutputs { ref outputs } => {
1021                                 5u8.write(writer)?;
1022                                 write_tlv_fields!(writer, {
1023                                         (0, WithoutLength(outputs), required),
1024                                 });
1025                         },
1026                         &Event::HTLCIntercepted { requested_next_hop_scid, payment_hash, inbound_amount_msat, expected_outbound_amount_msat, intercept_id } => {
1027                                 6u8.write(writer)?;
1028                                 let intercept_scid = InterceptNextHop::FakeScid { requested_next_hop_scid };
1029                                 write_tlv_fields!(writer, {
1030                                         (0, intercept_id, required),
1031                                         (2, intercept_scid, required),
1032                                         (4, payment_hash, required),
1033                                         (6, inbound_amount_msat, required),
1034                                         (8, expected_outbound_amount_msat, required),
1035                                 });
1036                         }
1037                         &Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
1038                                 7u8.write(writer)?;
1039                                 write_tlv_fields!(writer, {
1040                                         (0, fee_earned_msat, option),
1041                                         (1, prev_channel_id, option),
1042                                         (2, claim_from_onchain_tx, required),
1043                                         (3, next_channel_id, option),
1044                                 });
1045                         },
1046                         &Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason } => {
1047                                 9u8.write(writer)?;
1048                                 // `user_channel_id` used to be a single u64 value. In order to remain backwards
1049                                 // compatible with versions prior to 0.0.113, the u128 is serialized as two
1050                                 // separate u64 values.
1051                                 let user_channel_id_low = *user_channel_id as u64;
1052                                 let user_channel_id_high = (*user_channel_id >> 64) as u64;
1053                                 write_tlv_fields!(writer, {
1054                                         (0, channel_id, required),
1055                                         (1, user_channel_id_low, required),
1056                                         (2, reason, required),
1057                                         (3, user_channel_id_high, required),
1058                                 });
1059                         },
1060                         &Event::DiscardFunding { ref channel_id, ref transaction } => {
1061                                 11u8.write(writer)?;
1062                                 write_tlv_fields!(writer, {
1063                                         (0, channel_id, required),
1064                                         (2, transaction, required)
1065                                 })
1066                         },
1067                         &Event::PaymentPathSuccessful { ref payment_id, ref payment_hash, ref path } => {
1068                                 13u8.write(writer)?;
1069                                 write_tlv_fields!(writer, {
1070                                         (0, payment_id, required),
1071                                         (2, payment_hash, option),
1072                                         (4, *path, vec_type)
1073                                 })
1074                         },
1075                         &Event::PaymentFailed { ref payment_id, ref payment_hash } => {
1076                                 15u8.write(writer)?;
1077                                 write_tlv_fields!(writer, {
1078                                         (0, payment_id, required),
1079                                         (2, payment_hash, required),
1080                                 })
1081                         },
1082                         &Event::OpenChannelRequest { .. } => {
1083                                 17u8.write(writer)?;
1084                                 // We never write the OpenChannelRequest events as, upon disconnection, peers
1085                                 // drop any channels which have not yet exchanged funding_signed.
1086                         },
1087                         &Event::PaymentClaimed { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id } => {
1088                                 19u8.write(writer)?;
1089                                 write_tlv_fields!(writer, {
1090                                         (0, payment_hash, required),
1091                                         (1, receiver_node_id, option),
1092                                         (2, purpose, required),
1093                                         (4, amount_msat, required),
1094                                 });
1095                         },
1096                         &Event::ProbeSuccessful { ref payment_id, ref payment_hash, ref path } => {
1097                                 21u8.write(writer)?;
1098                                 write_tlv_fields!(writer, {
1099                                         (0, payment_id, required),
1100                                         (2, payment_hash, required),
1101                                         (4, *path, vec_type)
1102                                 })
1103                         },
1104                         &Event::ProbeFailed { ref payment_id, ref payment_hash, ref path, ref short_channel_id } => {
1105                                 23u8.write(writer)?;
1106                                 write_tlv_fields!(writer, {
1107                                         (0, payment_id, required),
1108                                         (2, payment_hash, required),
1109                                         (4, *path, vec_type),
1110                                         (6, short_channel_id, option),
1111                                 })
1112                         },
1113                         &Event::HTLCHandlingFailed { ref prev_channel_id, ref failed_next_destination } => {
1114                                 25u8.write(writer)?;
1115                                 write_tlv_fields!(writer, {
1116                                         (0, prev_channel_id, required),
1117                                         (2, failed_next_destination, required),
1118                                 })
1119                         },
1120                         #[cfg(anchors)]
1121                         &Event::BumpTransaction(ref event)=> {
1122                                 27u8.write(writer)?;
1123                                 match event {
1124                                         // We never write the ChannelClose|HTLCResolution events as they'll be replayed
1125                                         // upon restarting anyway if they remain unresolved.
1126                                         BumpTransactionEvent::ChannelClose { .. } => {}
1127                                         BumpTransactionEvent::HTLCResolution { .. } => {}
1128                                 }
1129                                 write_tlv_fields!(writer, {}); // Write a length field for forwards compat
1130                         }
1131                         &Event::ChannelReady { ref channel_id, ref user_channel_id, ref counterparty_node_id, ref channel_type } => {
1132                                 29u8.write(writer)?;
1133                                 write_tlv_fields!(writer, {
1134                                         (0, channel_id, required),
1135                                         (2, user_channel_id, required),
1136                                         (4, counterparty_node_id, required),
1137                                         (6, channel_type, required),
1138                                 });
1139                         },
1140                         // Note that, going forward, all new events must only write data inside of
1141                         // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
1142                         // data via `write_tlv_fields`.
1143                 }
1144                 Ok(())
1145         }
1146 }
1147 impl MaybeReadable for Event {
1148         fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
1149                 match Readable::read(reader)? {
1150                         // Note that we do not write a length-prefixed TLV for FundingGenerationReady events,
1151                         // unlike all other events, thus we return immediately here.
1152                         0u8 => Ok(None),
1153                         1u8 => {
1154                                 let f = || {
1155                                         let mut payment_hash = PaymentHash([0; 32]);
1156                                         let mut payment_preimage = None;
1157                                         let mut payment_secret = None;
1158                                         let mut amount_msat = 0;
1159                                         let mut receiver_node_id = None;
1160                                         let mut _user_payment_id = None::<u64>; // For compatibility with 0.0.103 and earlier
1161                                         let mut via_channel_id = None;
1162                                         let mut via_user_channel_id = None;
1163                                         read_tlv_fields!(reader, {
1164                                                 (0, payment_hash, required),
1165                                                 (1, receiver_node_id, option),
1166                                                 (2, payment_secret, option),
1167                                                 (3, via_channel_id, option),
1168                                                 (4, amount_msat, required),
1169                                                 (5, via_user_channel_id, option),
1170                                                 (6, _user_payment_id, option),
1171                                                 (8, payment_preimage, option),
1172                                         });
1173                                         let purpose = match payment_secret {
1174                                                 Some(secret) => PaymentPurpose::InvoicePayment {
1175                                                         payment_preimage,
1176                                                         payment_secret: secret
1177                                                 },
1178                                                 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
1179                                                 None => return Err(msgs::DecodeError::InvalidValue),
1180                                         };
1181                                         Ok(Some(Event::PaymentClaimable {
1182                                                 receiver_node_id,
1183                                                 payment_hash,
1184                                                 amount_msat,
1185                                                 purpose,
1186                                                 via_channel_id,
1187                                                 via_user_channel_id,
1188                                         }))
1189                                 };
1190                                 f()
1191                         },
1192                         2u8 => {
1193                                 let f = || {
1194                                         let mut payment_preimage = PaymentPreimage([0; 32]);
1195                                         let mut payment_hash = None;
1196                                         let mut payment_id = None;
1197                                         let mut fee_paid_msat = None;
1198                                         read_tlv_fields!(reader, {
1199                                                 (0, payment_preimage, required),
1200                                                 (1, payment_hash, option),
1201                                                 (3, payment_id, option),
1202                                                 (5, fee_paid_msat, option),
1203                                         });
1204                                         if payment_hash.is_none() {
1205                                                 payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()));
1206                                         }
1207                                         Ok(Some(Event::PaymentSent {
1208                                                 payment_id,
1209                                                 payment_preimage,
1210                                                 payment_hash: payment_hash.unwrap(),
1211                                                 fee_paid_msat,
1212                                         }))
1213                                 };
1214                                 f()
1215                         },
1216                         3u8 => {
1217                                 let f = || {
1218                                         #[cfg(test)]
1219                                         let error_code = Readable::read(reader)?;
1220                                         #[cfg(test)]
1221                                         let error_data = Readable::read(reader)?;
1222                                         let mut payment_hash = PaymentHash([0; 32]);
1223                                         let mut payment_failed_permanently = false;
1224                                         let mut network_update = None;
1225                                         let mut all_paths_failed = Some(true);
1226                                         let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1227                                         let mut short_channel_id = None;
1228                                         let mut retry = None;
1229                                         let mut payment_id = None;
1230                                         read_tlv_fields!(reader, {
1231                                                 (0, payment_hash, required),
1232                                                 (1, network_update, ignorable),
1233                                                 (2, payment_failed_permanently, required),
1234                                                 (3, all_paths_failed, option),
1235                                                 (5, path, vec_type),
1236                                                 (7, short_channel_id, option),
1237                                                 (9, retry, option),
1238                                                 (11, payment_id, option),
1239                                         });
1240                                         Ok(Some(Event::PaymentPathFailed {
1241                                                 payment_id,
1242                                                 payment_hash,
1243                                                 payment_failed_permanently,
1244                                                 network_update,
1245                                                 all_paths_failed: all_paths_failed.unwrap(),
1246                                                 path: path.unwrap(),
1247                                                 short_channel_id,
1248                                                 retry,
1249                                                 #[cfg(test)]
1250                                                 error_code,
1251                                                 #[cfg(test)]
1252                                                 error_data,
1253                                         }))
1254                                 };
1255                                 f()
1256                         },
1257                         4u8 => Ok(None),
1258                         5u8 => {
1259                                 let f = || {
1260                                         let mut outputs = WithoutLength(Vec::new());
1261                                         read_tlv_fields!(reader, {
1262                                                 (0, outputs, required),
1263                                         });
1264                                         Ok(Some(Event::SpendableOutputs { outputs: outputs.0 }))
1265                                 };
1266                                 f()
1267                         },
1268                         6u8 => {
1269                                 let mut payment_hash = PaymentHash([0; 32]);
1270                                 let mut intercept_id = InterceptId([0; 32]);
1271                                 let mut requested_next_hop_scid = InterceptNextHop::FakeScid { requested_next_hop_scid: 0 };
1272                                 let mut inbound_amount_msat = 0;
1273                                 let mut expected_outbound_amount_msat = 0;
1274                                 read_tlv_fields!(reader, {
1275                                         (0, intercept_id, required),
1276                                         (2, requested_next_hop_scid, required),
1277                                         (4, payment_hash, required),
1278                                         (6, inbound_amount_msat, required),
1279                                         (8, expected_outbound_amount_msat, required),
1280                                 });
1281                                 let next_scid = match requested_next_hop_scid {
1282                                         InterceptNextHop::FakeScid { requested_next_hop_scid: scid } => scid
1283                                 };
1284                                 Ok(Some(Event::HTLCIntercepted {
1285                                         payment_hash,
1286                                         requested_next_hop_scid: next_scid,
1287                                         inbound_amount_msat,
1288                                         expected_outbound_amount_msat,
1289                                         intercept_id,
1290                                 }))
1291                         },
1292                         7u8 => {
1293                                 let f = || {
1294                                         let mut fee_earned_msat = None;
1295                                         let mut prev_channel_id = None;
1296                                         let mut claim_from_onchain_tx = false;
1297                                         let mut next_channel_id = None;
1298                                         read_tlv_fields!(reader, {
1299                                                 (0, fee_earned_msat, option),
1300                                                 (1, prev_channel_id, option),
1301                                                 (2, claim_from_onchain_tx, required),
1302                                                 (3, next_channel_id, option),
1303                                         });
1304                                         Ok(Some(Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id }))
1305                                 };
1306                                 f()
1307                         },
1308                         9u8 => {
1309                                 let f = || {
1310                                         let mut channel_id = [0; 32];
1311                                         let mut reason = None;
1312                                         let mut user_channel_id_low_opt: Option<u64> = None;
1313                                         let mut user_channel_id_high_opt: Option<u64> = None;
1314                                         read_tlv_fields!(reader, {
1315                                                 (0, channel_id, required),
1316                                                 (1, user_channel_id_low_opt, option),
1317                                                 (2, reason, ignorable),
1318                                                 (3, user_channel_id_high_opt, option),
1319                                         });
1320                                         if reason.is_none() { return Ok(None); }
1321
1322                                         // `user_channel_id` used to be a single u64 value. In order to remain
1323                                         // backwards compatible with versions prior to 0.0.113, the u128 is serialized
1324                                         // as two separate u64 values.
1325                                         let user_channel_id = (user_channel_id_low_opt.unwrap_or(0) as u128) +
1326                                                 ((user_channel_id_high_opt.unwrap_or(0) as u128) << 64);
1327
1328                                         Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: reason.unwrap() }))
1329                                 };
1330                                 f()
1331                         },
1332                         11u8 => {
1333                                 let f = || {
1334                                         let mut channel_id = [0; 32];
1335                                         let mut transaction = Transaction{ version: 2, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
1336                                         read_tlv_fields!(reader, {
1337                                                 (0, channel_id, required),
1338                                                 (2, transaction, required),
1339                                         });
1340                                         Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
1341                                 };
1342                                 f()
1343                         },
1344                         13u8 => {
1345                                 let f = || {
1346                                         let mut payment_id = PaymentId([0; 32]);
1347                                         let mut payment_hash = None;
1348                                         let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1349                                         read_tlv_fields!(reader, {
1350                                                 (0, payment_id, required),
1351                                                 (2, payment_hash, option),
1352                                                 (4, path, vec_type),
1353                                         });
1354                                         Ok(Some(Event::PaymentPathSuccessful {
1355                                                 payment_id,
1356                                                 payment_hash,
1357                                                 path: path.unwrap(),
1358                                         }))
1359                                 };
1360                                 f()
1361                         },
1362                         15u8 => {
1363                                 let f = || {
1364                                         let mut payment_hash = PaymentHash([0; 32]);
1365                                         let mut payment_id = PaymentId([0; 32]);
1366                                         read_tlv_fields!(reader, {
1367                                                 (0, payment_id, required),
1368                                                 (2, payment_hash, required),
1369                                         });
1370                                         Ok(Some(Event::PaymentFailed {
1371                                                 payment_id,
1372                                                 payment_hash,
1373                                         }))
1374                                 };
1375                                 f()
1376                         },
1377                         17u8 => {
1378                                 // Value 17 is used for `Event::OpenChannelRequest`.
1379                                 Ok(None)
1380                         },
1381                         19u8 => {
1382                                 let f = || {
1383                                         let mut payment_hash = PaymentHash([0; 32]);
1384                                         let mut purpose = None;
1385                                         let mut amount_msat = 0;
1386                                         let mut receiver_node_id = None;
1387                                         read_tlv_fields!(reader, {
1388                                                 (0, payment_hash, required),
1389                                                 (1, receiver_node_id, option),
1390                                                 (2, purpose, ignorable),
1391                                                 (4, amount_msat, required),
1392                                         });
1393                                         if purpose.is_none() { return Ok(None); }
1394                                         Ok(Some(Event::PaymentClaimed {
1395                                                 receiver_node_id,
1396                                                 payment_hash,
1397                                                 purpose: purpose.unwrap(),
1398                                                 amount_msat,
1399                                         }))
1400                                 };
1401                                 f()
1402                         },
1403                         21u8 => {
1404                                 let f = || {
1405                                         let mut payment_id = PaymentId([0; 32]);
1406                                         let mut payment_hash = PaymentHash([0; 32]);
1407                                         let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1408                                         read_tlv_fields!(reader, {
1409                                                 (0, payment_id, required),
1410                                                 (2, payment_hash, required),
1411                                                 (4, path, vec_type),
1412                                         });
1413                                         Ok(Some(Event::ProbeSuccessful {
1414                                                 payment_id,
1415                                                 payment_hash,
1416                                                 path: path.unwrap(),
1417                                         }))
1418                                 };
1419                                 f()
1420                         },
1421                         23u8 => {
1422                                 let f = || {
1423                                         let mut payment_id = PaymentId([0; 32]);
1424                                         let mut payment_hash = PaymentHash([0; 32]);
1425                                         let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1426                                         let mut short_channel_id = None;
1427                                         read_tlv_fields!(reader, {
1428                                                 (0, payment_id, required),
1429                                                 (2, payment_hash, required),
1430                                                 (4, path, vec_type),
1431                                                 (6, short_channel_id, option),
1432                                         });
1433                                         Ok(Some(Event::ProbeFailed {
1434                                                 payment_id,
1435                                                 payment_hash,
1436                                                 path: path.unwrap(),
1437                                                 short_channel_id,
1438                                         }))
1439                                 };
1440                                 f()
1441                         },
1442                         25u8 => {
1443                                 let f = || {
1444                                         let mut prev_channel_id = [0; 32];
1445                                         let mut failed_next_destination_opt = None;
1446                                         read_tlv_fields!(reader, {
1447                                                 (0, prev_channel_id, required),
1448                                                 (2, failed_next_destination_opt, ignorable),
1449                                         });
1450                                         if let Some(failed_next_destination) = failed_next_destination_opt {
1451                                                 Ok(Some(Event::HTLCHandlingFailed {
1452                                                         prev_channel_id,
1453                                                         failed_next_destination,
1454                                                 }))
1455                                         } else {
1456                                                 // If we fail to read a `failed_next_destination` assume it's because
1457                                                 // `MaybeReadable::read` returned `Ok(None)`, though it's also possible we
1458                                                 // were simply missing the field.
1459                                                 Ok(None)
1460                                         }
1461                                 };
1462                                 f()
1463                         },
1464                         27u8 => Ok(None),
1465                         29u8 => {
1466                                 let f = || {
1467                                         let mut channel_id = [0; 32];
1468                                         let mut user_channel_id: u128 = 0;
1469                                         let mut counterparty_node_id = OptionDeserWrapper(None);
1470                                         let mut channel_type = OptionDeserWrapper(None);
1471                                         read_tlv_fields!(reader, {
1472                                                 (0, channel_id, required),
1473                                                 (2, user_channel_id, required),
1474                                                 (4, counterparty_node_id, required),
1475                                                 (6, channel_type, required),
1476                                         });
1477
1478                                         Ok(Some(Event::ChannelReady {
1479                                                 channel_id,
1480                                                 user_channel_id,
1481                                                 counterparty_node_id: counterparty_node_id.0.unwrap(),
1482                                                 channel_type: channel_type.0.unwrap()
1483                                         }))
1484                                 };
1485                                 f()
1486                         },
1487                         // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
1488                         // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
1489                         // reads.
1490                         x if x % 2 == 1 => {
1491                                 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
1492                                 // which prefixes the whole thing with a length BigSize. Because the event is
1493                                 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
1494                                 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
1495                                 // exactly the number of bytes specified, ignoring them entirely.
1496                                 let tlv_len: BigSize = Readable::read(reader)?;
1497                                 FixedLengthReader::new(reader, tlv_len.0)
1498                                         .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
1499                                 Ok(None)
1500                         },
1501                         _ => Err(msgs::DecodeError::InvalidValue)
1502                 }
1503         }
1504 }
1505
1506 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
1507 /// broadcast to most peers).
1508 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
1509 #[derive(Clone, Debug)]
1510 pub enum MessageSendEvent {
1511         /// Used to indicate that we've accepted a channel open and should send the accept_channel
1512         /// message provided to the given peer.
1513         SendAcceptChannel {
1514                 /// The node_id of the node which should receive this message
1515                 node_id: PublicKey,
1516                 /// The message which should be sent.
1517                 msg: msgs::AcceptChannel,
1518         },
1519         /// Used to indicate that we've initiated a channel open and should send the open_channel
1520         /// message provided to the given peer.
1521         SendOpenChannel {
1522                 /// The node_id of the node which should receive this message
1523                 node_id: PublicKey,
1524                 /// The message which should be sent.
1525                 msg: msgs::OpenChannel,
1526         },
1527         /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
1528         SendFundingCreated {
1529                 /// The node_id of the node which should receive this message
1530                 node_id: PublicKey,
1531                 /// The message which should be sent.
1532                 msg: msgs::FundingCreated,
1533         },
1534         /// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
1535         SendFundingSigned {
1536                 /// The node_id of the node which should receive this message
1537                 node_id: PublicKey,
1538                 /// The message which should be sent.
1539                 msg: msgs::FundingSigned,
1540         },
1541         /// Used to indicate that a channel_ready message should be sent to the peer with the given node_id.
1542         SendChannelReady {
1543                 /// The node_id of the node which should receive these message(s)
1544                 node_id: PublicKey,
1545                 /// The channel_ready message which should be sent.
1546                 msg: msgs::ChannelReady,
1547         },
1548         /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
1549         SendAnnouncementSignatures {
1550                 /// The node_id of the node which should receive these message(s)
1551                 node_id: PublicKey,
1552                 /// The announcement_signatures message which should be sent.
1553                 msg: msgs::AnnouncementSignatures,
1554         },
1555         /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
1556         /// message should be sent to the peer with the given node_id.
1557         UpdateHTLCs {
1558                 /// The node_id of the node which should receive these message(s)
1559                 node_id: PublicKey,
1560                 /// The update messages which should be sent. ALL messages in the struct should be sent!
1561                 updates: msgs::CommitmentUpdate,
1562         },
1563         /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
1564         SendRevokeAndACK {
1565                 /// The node_id of the node which should receive this message
1566                 node_id: PublicKey,
1567                 /// The message which should be sent.
1568                 msg: msgs::RevokeAndACK,
1569         },
1570         /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
1571         SendClosingSigned {
1572                 /// The node_id of the node which should receive this message
1573                 node_id: PublicKey,
1574                 /// The message which should be sent.
1575                 msg: msgs::ClosingSigned,
1576         },
1577         /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
1578         SendShutdown {
1579                 /// The node_id of the node which should receive this message
1580                 node_id: PublicKey,
1581                 /// The message which should be sent.
1582                 msg: msgs::Shutdown,
1583         },
1584         /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
1585         SendChannelReestablish {
1586                 /// The node_id of the node which should receive this message
1587                 node_id: PublicKey,
1588                 /// The message which should be sent.
1589                 msg: msgs::ChannelReestablish,
1590         },
1591         /// Used to send a channel_announcement and channel_update to a specific peer, likely on
1592         /// initial connection to ensure our peers know about our channels.
1593         SendChannelAnnouncement {
1594                 /// The node_id of the node which should receive this message
1595                 node_id: PublicKey,
1596                 /// The channel_announcement which should be sent.
1597                 msg: msgs::ChannelAnnouncement,
1598                 /// The followup channel_update which should be sent.
1599                 update_msg: msgs::ChannelUpdate,
1600         },
1601         /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
1602         /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
1603         ///
1604         /// Note that after doing so, you very likely (unless you did so very recently) want to
1605         /// broadcast a node_announcement (e.g. via [`PeerManager::broadcast_node_announcement`]). This
1606         /// ensures that any nodes which see our channel_announcement also have a relevant
1607         /// node_announcement, including relevant feature flags which may be important for routing
1608         /// through or to us.
1609         ///
1610         /// [`PeerManager::broadcast_node_announcement`]: crate::ln::peer_handler::PeerManager::broadcast_node_announcement
1611         BroadcastChannelAnnouncement {
1612                 /// The channel_announcement which should be sent.
1613                 msg: msgs::ChannelAnnouncement,
1614                 /// The followup channel_update which should be sent.
1615                 update_msg: Option<msgs::ChannelUpdate>,
1616         },
1617         /// Used to indicate that a channel_update should be broadcast to all peers.
1618         BroadcastChannelUpdate {
1619                 /// The channel_update which should be sent.
1620                 msg: msgs::ChannelUpdate,
1621         },
1622         /// Used to indicate that a node_announcement should be broadcast to all peers.
1623         BroadcastNodeAnnouncement {
1624                 /// The node_announcement which should be sent.
1625                 msg: msgs::NodeAnnouncement,
1626         },
1627         /// Used to indicate that a channel_update should be sent to a single peer.
1628         /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
1629         /// private channel and we shouldn't be informing all of our peers of channel parameters.
1630         SendChannelUpdate {
1631                 /// The node_id of the node which should receive this message
1632                 node_id: PublicKey,
1633                 /// The channel_update which should be sent.
1634                 msg: msgs::ChannelUpdate,
1635         },
1636         /// Broadcast an error downstream to be handled
1637         HandleError {
1638                 /// The node_id of the node which should receive this message
1639                 node_id: PublicKey,
1640                 /// The action which should be taken.
1641                 action: msgs::ErrorAction
1642         },
1643         /// Query a peer for channels with funding transaction UTXOs in a block range.
1644         SendChannelRangeQuery {
1645                 /// The node_id of this message recipient
1646                 node_id: PublicKey,
1647                 /// The query_channel_range which should be sent.
1648                 msg: msgs::QueryChannelRange,
1649         },
1650         /// Request routing gossip messages from a peer for a list of channels identified by
1651         /// their short_channel_ids.
1652         SendShortIdsQuery {
1653                 /// The node_id of this message recipient
1654                 node_id: PublicKey,
1655                 /// The query_short_channel_ids which should be sent.
1656                 msg: msgs::QueryShortChannelIds,
1657         },
1658         /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
1659         /// emitted during processing of the query.
1660         SendReplyChannelRange {
1661                 /// The node_id of this message recipient
1662                 node_id: PublicKey,
1663                 /// The reply_channel_range which should be sent.
1664                 msg: msgs::ReplyChannelRange,
1665         },
1666         /// Sends a timestamp filter for inbound gossip. This should be sent on each new connection to
1667         /// enable receiving gossip messages from the peer.
1668         SendGossipTimestampFilter {
1669                 /// The node_id of this message recipient
1670                 node_id: PublicKey,
1671                 /// The gossip_timestamp_filter which should be sent.
1672                 msg: msgs::GossipTimestampFilter,
1673         },
1674 }
1675
1676 /// A trait indicating an object may generate message send events
1677 pub trait MessageSendEventsProvider {
1678         /// Gets the list of pending events which were generated by previous actions, clearing the list
1679         /// in the process.
1680         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
1681 }
1682
1683 /// A trait indicating an object may generate onion messages to send
1684 pub trait OnionMessageProvider {
1685         /// Gets the next pending onion message for the peer with the given node id.
1686         fn next_onion_message_for_peer(&self, peer_node_id: PublicKey) -> Option<msgs::OnionMessage>;
1687 }
1688
1689 /// A trait indicating an object may generate events.
1690 ///
1691 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
1692 ///
1693 /// Implementations of this trait may also feature an async version of event handling, as shown with
1694 /// [`ChannelManager::process_pending_events_async`] and
1695 /// [`ChainMonitor::process_pending_events_async`].
1696 ///
1697 /// # Requirements
1698 ///
1699 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
1700 /// event since the last invocation.
1701 ///
1702 /// In order to ensure no [`Event`]s are lost, implementors of this trait will persist [`Event`]s
1703 /// and replay any unhandled events on startup. An [`Event`] is considered handled when
1704 /// [`process_pending_events`] returns, thus handlers MUST fully handle [`Event`]s and persist any
1705 /// relevant changes to disk *before* returning.
1706 ///
1707 /// Further, because an application may crash between an [`Event`] being handled and the
1708 /// implementor of this trait being re-serialized, [`Event`] handling must be idempotent - in
1709 /// effect, [`Event`]s may be replayed.
1710 ///
1711 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
1712 /// consult the provider's documentation on the implication of processing events and how a handler
1713 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
1714 /// [`ChainMonitor::process_pending_events`]).
1715 ///
1716 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
1717 /// own type(s).
1718 ///
1719 /// [`process_pending_events`]: Self::process_pending_events
1720 /// [`handle_event`]: EventHandler::handle_event
1721 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
1722 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
1723 /// [`ChannelManager::process_pending_events_async`]: crate::ln::channelmanager::ChannelManager::process_pending_events_async
1724 /// [`ChainMonitor::process_pending_events_async`]: crate::chain::chainmonitor::ChainMonitor::process_pending_events_async
1725 pub trait EventsProvider {
1726         /// Processes any events generated since the last call using the given event handler.
1727         ///
1728         /// See the trait-level documentation for requirements.
1729         fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
1730 }
1731
1732 /// A trait implemented for objects handling events from [`EventsProvider`].
1733 ///
1734 /// An async variation also exists for implementations of [`EventsProvider`] that support async
1735 /// event handling. The async event handler should satisfy the generic bounds: `F:
1736 /// core::future::Future, H: Fn(Event) -> F`.
1737 pub trait EventHandler {
1738         /// Handles the given [`Event`].
1739         ///
1740         /// See [`EventsProvider`] for details that must be considered when implementing this method.
1741         fn handle_event(&self, event: Event);
1742 }
1743
1744 impl<F> EventHandler for F where F: Fn(Event) {
1745         fn handle_event(&self, event: Event) {
1746                 self(event)
1747         }
1748 }
1749
1750 impl<T: EventHandler> EventHandler for Arc<T> {
1751         fn handle_event(&self, event: Event) {
1752                 self.deref().handle_event(event)
1753         }
1754 }