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