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