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