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