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