Merge pull request #2934 from TheBlueMatt/2023-03-no-num-traits
[rust-lightning] / lightning / src / events / mod.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Events are returned from various bits in the library which indicate some action must be taken
11 //! by the client.
12 //!
13 //! Because we don't have a built-in runtime, it's up to the client to call events at a time in the
14 //! future, as well as generate and broadcast funding transactions handle payment preimages and a
15 //! few other things.
16
17 pub mod bump_transaction;
18
19 pub use bump_transaction::BumpTransactionEvent;
20
21 use crate::sign::SpendableOutputDescriptor;
22 use crate::ln::channelmanager::{InterceptId, PaymentId, RecipientOnionFields};
23 use crate::ln::channel::FUNDING_CONF_DEADLINE_BLOCKS;
24 use crate::ln::features::ChannelTypeFeatures;
25 use crate::ln::msgs;
26 use crate::ln::{ChannelId, PaymentPreimage, PaymentHash, PaymentSecret};
27 use crate::chain::transaction;
28 use crate::routing::gossip::NetworkUpdate;
29 use crate::util::errors::APIError;
30 use crate::util::ser::{BigSize, FixedLengthReader, Writeable, Writer, MaybeReadable, Readable, RequiredWrapper, UpgradableRequired, WithoutLength};
31 use crate::util::string::UntrustedString;
32 use crate::routing::router::{BlindedTail, Path, RouteHop, RouteParameters};
33
34 use bitcoin::{Transaction, OutPoint};
35 use bitcoin::blockdata::locktime::absolute::LockTime;
36 use bitcoin::blockdata::script::ScriptBuf;
37 use bitcoin::hashes::Hash;
38 use bitcoin::hashes::sha256::Hash as Sha256;
39 use bitcoin::secp256k1::PublicKey;
40 use crate::io;
41 use crate::prelude::*;
42 use core::time::Duration;
43 use core::ops::Deref;
44 use crate::sync::Arc;
45
46 /// Some information provided on receipt of payment depends on whether the payment received is a
47 /// spontaneous payment or a "conventional" lightning payment that's paying an invoice.
48 #[derive(Clone, Debug, PartialEq, Eq)]
49 pub enum PaymentPurpose {
50         /// Information for receiving a payment that we generated an invoice for.
51         InvoicePayment {
52                 /// The preimage to the payment_hash, if the payment hash (and secret) were fetched via
53                 /// [`ChannelManager::create_inbound_payment`]. If provided, this can be handed directly to
54                 /// [`ChannelManager::claim_funds`].
55                 ///
56                 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
57                 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
58                 payment_preimage: Option<PaymentPreimage>,
59                 /// The "payment secret". This authenticates the sender to the recipient, preventing a
60                 /// number of deanonymization attacks during the routing process.
61                 /// It is provided here for your reference, however its accuracy is enforced directly by
62                 /// [`ChannelManager`] using the values you previously provided to
63                 /// [`ChannelManager::create_inbound_payment`] or
64                 /// [`ChannelManager::create_inbound_payment_for_hash`].
65                 ///
66                 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
67                 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
68                 /// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
69                 payment_secret: PaymentSecret,
70         },
71         /// Because this is a spontaneous payment, the payer generated their own preimage rather than us
72         /// (the payee) providing a preimage.
73         SpontaneousPayment(PaymentPreimage),
74 }
75
76 impl PaymentPurpose {
77         /// Returns the preimage for this payment, if it is known.
78         pub fn preimage(&self) -> Option<PaymentPreimage> {
79                 match self {
80                         PaymentPurpose::InvoicePayment { payment_preimage, .. } => *payment_preimage,
81                         PaymentPurpose::SpontaneousPayment(preimage) => Some(*preimage),
82                 }
83         }
84 }
85
86 impl_writeable_tlv_based_enum!(PaymentPurpose,
87         (0, InvoicePayment) => {
88                 (0, payment_preimage, option),
89                 (2, payment_secret, required),
90         };
91         (2, SpontaneousPayment)
92 );
93
94 /// Information about an HTLC that is part of a payment that can be claimed.
95 #[derive(Clone, Debug, PartialEq, Eq)]
96 pub struct ClaimedHTLC {
97         /// The `channel_id` of the channel over which the HTLC was received.
98         pub channel_id: ChannelId,
99         /// The `user_channel_id` of the channel over which the HTLC was received. This is the value
100         /// passed in to [`ChannelManager::create_channel`] for outbound channels, or to
101         /// [`ChannelManager::accept_inbound_channel`] for inbound channels if
102         /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
103         /// `user_channel_id` will be randomized for an inbound channel.
104         ///
105         /// This field will be zero for a payment that was serialized prior to LDK version 0.0.117. (This
106         /// should only happen in the case that a payment was claimable prior to LDK version 0.0.117, but
107         /// was not actually claimed until after upgrading.)
108         ///
109         /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
110         /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
111         /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
112         pub user_channel_id: u128,
113         /// The block height at which this HTLC expires.
114         pub cltv_expiry: u32,
115         /// The amount (in msats) of this part of an MPP.
116         pub value_msat: u64,
117         /// The extra fee our counterparty skimmed off the top of this HTLC, if any.
118         ///
119         /// This value will always be 0 for [`ClaimedHTLC`]s serialized with LDK versions prior to
120         /// 0.0.119.
121         pub counterparty_skimmed_fee_msat: u64,
122 }
123 impl_writeable_tlv_based!(ClaimedHTLC, {
124         (0, channel_id, required),
125         (1, counterparty_skimmed_fee_msat, (default_value, 0u64)),
126         (2, user_channel_id, required),
127         (4, cltv_expiry, required),
128         (6, value_msat, required),
129 });
130
131 /// When the payment path failure took place and extra details about it. [`PathFailure::OnPath`] may
132 /// contain a [`NetworkUpdate`] that needs to be applied to the [`NetworkGraph`].
133 ///
134 /// [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate
135 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
136 #[derive(Clone, Debug, Eq, PartialEq)]
137 pub enum PathFailure {
138         /// We failed to initially send the payment and no HTLC was committed to. Contains the relevant
139         /// error.
140         InitialSend {
141                 /// The error surfaced from initial send.
142                 err: APIError,
143         },
144         /// A hop on the path failed to forward our payment.
145         OnPath {
146                 /// If present, this [`NetworkUpdate`] should be applied to the [`NetworkGraph`] so that routing
147                 /// decisions can take into account the update.
148                 ///
149                 /// [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate
150                 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
151                 network_update: Option<NetworkUpdate>,
152         },
153 }
154
155 impl_writeable_tlv_based_enum_upgradable!(PathFailure,
156         (0, OnPath) => {
157                 (0, network_update, upgradable_option),
158         },
159         (2, InitialSend) => {
160                 (0, err, upgradable_required),
161         },
162 );
163
164 #[derive(Clone, Debug, PartialEq, Eq)]
165 /// The reason the channel was closed. See individual variants for more details.
166 pub enum ClosureReason {
167         /// Closure generated from receiving a peer error message.
168         ///
169         /// Our counterparty may have broadcasted their latest commitment state, and we have
170         /// as well.
171         CounterpartyForceClosed {
172                 /// The error which the peer sent us.
173                 ///
174                 /// Be careful about printing the peer_msg, a well-crafted message could exploit
175                 /// a security vulnerability in the terminal emulator or the logging subsystem.
176                 /// To be safe, use `Display` on `UntrustedString`
177                 ///
178                 /// [`UntrustedString`]: crate::util::string::UntrustedString
179                 peer_msg: UntrustedString,
180         },
181         /// Closure generated from [`ChannelManager::force_close_channel`], called by the user.
182         ///
183         /// [`ChannelManager::force_close_channel`]: crate::ln::channelmanager::ChannelManager::force_close_channel.
184         HolderForceClosed,
185         /// The channel was closed after negotiating a cooperative close and we've now broadcasted
186         /// the cooperative close transaction. Note the shutdown may have been initiated by us.
187         ///
188         /// This was only set in versions of LDK prior to 0.0.122.
189         // Can be removed once we disallow downgrading to 0.0.121
190         LegacyCooperativeClosure,
191         /// The channel was closed after negotiating a cooperative close and we've now broadcasted
192         /// the cooperative close transaction. This indicates that the shutdown was initiated by our
193         /// counterparty.
194         ///
195         /// In rare cases where we initiated closure immediately prior to shutting down without
196         /// persisting, this value may be provided for channels we initiated closure for.
197         CounterpartyInitiatedCooperativeClosure,
198         /// The channel was closed after negotiating a cooperative close and we've now broadcasted
199         /// the cooperative close transaction. This indicates that the shutdown was initiated by us.
200         LocallyInitiatedCooperativeClosure,
201         /// A commitment transaction was confirmed on chain, closing the channel. Most likely this
202         /// commitment transaction came from our counterparty, but it may also have come from
203         /// a copy of our own `ChannelMonitor`.
204         CommitmentTxConfirmed,
205         /// The funding transaction failed to confirm in a timely manner on an inbound channel.
206         FundingTimedOut,
207         /// Closure generated from processing an event, likely a HTLC forward/relay/reception.
208         ProcessingError {
209                 /// A developer-readable error message which we generated.
210                 err: String,
211         },
212         /// The peer disconnected prior to funding completing. In this case the spec mandates that we
213         /// forget the channel entirely - we can attempt again if the peer reconnects.
214         ///
215         /// This includes cases where we restarted prior to funding completion, including prior to the
216         /// initial [`ChannelMonitor`] persistence completing.
217         ///
218         /// In LDK versions prior to 0.0.107 this could also occur if we were unable to connect to the
219         /// peer because of mutual incompatibility between us and our channel counterparty.
220         ///
221         /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
222         DisconnectedPeer,
223         /// Closure generated from `ChannelManager::read` if the [`ChannelMonitor`] is newer than
224         /// the [`ChannelManager`] deserialized.
225         ///
226         /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
227         /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
228         OutdatedChannelManager,
229         /// The counterparty requested a cooperative close of a channel that had not been funded yet.
230         /// The channel has been immediately closed.
231         CounterpartyCoopClosedUnfundedChannel,
232         /// Another channel in the same funding batch closed before the funding transaction
233         /// was ready to be broadcast.
234         FundingBatchClosure,
235         /// One of our HTLCs timed out in a channel, causing us to force close the channel.
236         HTLCsTimedOut,
237 }
238
239 impl core::fmt::Display for ClosureReason {
240         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
241                 f.write_str("Channel closed because ")?;
242                 match self {
243                         ClosureReason::CounterpartyForceClosed { peer_msg } => {
244                                 f.write_fmt(format_args!("counterparty force-closed with message: {}", peer_msg))
245                         },
246                         ClosureReason::HolderForceClosed => f.write_str("user force-closed the channel"),
247                         ClosureReason::LegacyCooperativeClosure => f.write_str("the channel was cooperatively closed"),
248                         ClosureReason::CounterpartyInitiatedCooperativeClosure => f.write_str("the channel was cooperatively closed by our peer"),
249                         ClosureReason::LocallyInitiatedCooperativeClosure => f.write_str("the channel was cooperatively closed by us"),
250                         ClosureReason::CommitmentTxConfirmed => f.write_str("commitment or closing transaction was confirmed on chain."),
251                         ClosureReason::FundingTimedOut => write!(f, "funding transaction failed to confirm within {} blocks", FUNDING_CONF_DEADLINE_BLOCKS),
252                         ClosureReason::ProcessingError { err } => {
253                                 f.write_str("of an exception: ")?;
254                                 f.write_str(&err)
255                         },
256                         ClosureReason::DisconnectedPeer => f.write_str("the peer disconnected prior to the channel being funded"),
257                         ClosureReason::OutdatedChannelManager => f.write_str("the ChannelManager read from disk was stale compared to ChannelMonitor(s)"),
258                         ClosureReason::CounterpartyCoopClosedUnfundedChannel => f.write_str("the peer requested the unfunded channel be closed"),
259                         ClosureReason::FundingBatchClosure => f.write_str("another channel in the same funding batch closed"),
260                         ClosureReason::HTLCsTimedOut => f.write_str("htlcs on the channel timed out"),
261                 }
262         }
263 }
264
265 impl_writeable_tlv_based_enum_upgradable!(ClosureReason,
266         (0, CounterpartyForceClosed) => { (1, peer_msg, required) },
267         (1, FundingTimedOut) => {},
268         (2, HolderForceClosed) => {},
269         (6, CommitmentTxConfirmed) => {},
270         (4, LegacyCooperativeClosure) => {},
271         (8, ProcessingError) => { (1, err, required) },
272         (10, DisconnectedPeer) => {},
273         (12, OutdatedChannelManager) => {},
274         (13, CounterpartyCoopClosedUnfundedChannel) => {},
275         (15, FundingBatchClosure) => {},
276         (17, CounterpartyInitiatedCooperativeClosure) => {},
277         (19, LocallyInitiatedCooperativeClosure) => {},
278         (21, HTLCsTimedOut) => {},
279 );
280
281 /// Intended destination of a failed HTLC as indicated in [`Event::HTLCHandlingFailed`].
282 #[derive(Clone, Debug, PartialEq, Eq)]
283 pub enum HTLCDestination {
284         /// We tried forwarding to a channel but failed to do so. An example of such an instance is when
285         /// there is insufficient capacity in our outbound channel.
286         NextHopChannel {
287                 /// The `node_id` of the next node. For backwards compatibility, this field is
288                 /// marked as optional, versions prior to 0.0.110 may not always be able to provide
289                 /// counterparty node information.
290                 node_id: Option<PublicKey>,
291                 /// The outgoing `channel_id` between us and the next node.
292                 channel_id: ChannelId,
293         },
294         /// Scenario where we are unsure of the next node to forward the HTLC to.
295         UnknownNextHop {
296                 /// Short channel id we are requesting to forward an HTLC to.
297                 requested_forward_scid: u64,
298         },
299         /// We couldn't forward to the outgoing scid. An example would be attempting to send a duplicate
300         /// intercept HTLC.
301         InvalidForward {
302                 /// Short channel id we are requesting to forward an HTLC to.
303                 requested_forward_scid: u64
304         },
305         /// Failure scenario where an HTLC may have been forwarded to be intended for us,
306         /// but is invalid for some reason, so we reject it.
307         ///
308         /// Some of the reasons may include:
309         /// * HTLC Timeouts
310         /// * Excess HTLCs for a payment that we have already fully received, over-paying for the
311         ///   payment,
312         /// * The counterparty node modified the HTLC in transit,
313         /// * A probing attack where an intermediary node is trying to detect if we are the ultimate
314         ///   recipient for a payment.
315         FailedPayment {
316                 /// The payment hash of the payment we attempted to process.
317                 payment_hash: PaymentHash
318         },
319 }
320
321 impl_writeable_tlv_based_enum_upgradable!(HTLCDestination,
322         (0, NextHopChannel) => {
323                 (0, node_id, required),
324                 (2, channel_id, required),
325         },
326         (1, InvalidForward) => {
327                 (0, requested_forward_scid, required),
328         },
329         (2, UnknownNextHop) => {
330                 (0, requested_forward_scid, required),
331         },
332         (4, FailedPayment) => {
333                 (0, payment_hash, required),
334         },
335 );
336
337 /// Will be used in [`Event::HTLCIntercepted`] to identify the next hop in the HTLC's path.
338 /// Currently only used in serialization for the sake of maintaining compatibility. More variants
339 /// will be added for general-purpose HTLC forward intercepts as well as trampoline forward
340 /// intercepts in upcoming work.
341 enum InterceptNextHop {
342         FakeScid {
343                 requested_next_hop_scid: u64,
344         },
345 }
346
347 impl_writeable_tlv_based_enum!(InterceptNextHop,
348         (0, FakeScid) => {
349                 (0, requested_next_hop_scid, required),
350         };
351 );
352
353 /// The reason the payment failed. Used in [`Event::PaymentFailed`].
354 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
355 pub enum PaymentFailureReason {
356         /// The intended recipient rejected our payment.
357         RecipientRejected,
358         /// The user chose to abandon this payment by calling [`ChannelManager::abandon_payment`].
359         ///
360         /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
361         UserAbandoned,
362         /// We exhausted all of our retry attempts while trying to send the payment, or we
363         /// exhausted the [`Retry::Timeout`] if the user set one. If at any point a retry
364         /// attempt failed while being forwarded along the path, an [`Event::PaymentPathFailed`] will
365         /// have come before this.
366         ///
367         /// [`Retry::Timeout`]: crate::ln::channelmanager::Retry::Timeout
368         RetriesExhausted,
369         /// The payment expired while retrying, based on the provided
370         /// [`PaymentParameters::expiry_time`].
371         ///
372         /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
373         PaymentExpired,
374         /// We failed to find a route while retrying the payment.
375         ///
376         /// Note that this generally indicates that we've exhausted the available set of possible
377         /// routes - we tried the payment over a few routes but were not able to find any further
378         /// candidate routes beyond those.
379         RouteNotFound,
380         /// This error should generally never happen. This likely means that there is a problem with
381         /// your router.
382         UnexpectedError,
383 }
384
385 impl_writeable_tlv_based_enum!(PaymentFailureReason,
386         (0, RecipientRejected) => {},
387         (2, UserAbandoned) => {},
388         (4, RetriesExhausted) => {},
389         (6, PaymentExpired) => {},
390         (8, RouteNotFound) => {},
391         (10, UnexpectedError) => {}, ;
392 );
393
394 /// An Event which you should probably take some action in response to.
395 ///
396 /// Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
397 /// them directly as they don't round-trip exactly (for example FundingGenerationReady is never
398 /// written as it makes no sense to respond to it after reconnecting to peers).
399 #[derive(Clone, Debug, PartialEq, Eq)]
400 pub enum Event {
401         /// Used to indicate that the client should generate a funding transaction with the given
402         /// parameters and then call [`ChannelManager::funding_transaction_generated`].
403         /// Generated in [`ChannelManager`] message handling.
404         /// Note that *all inputs* in the funding transaction must spend SegWit outputs or your
405         /// counterparty can steal your funds!
406         ///
407         /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
408         /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
409         FundingGenerationReady {
410                 /// The random channel_id we picked which you'll need to pass into
411                 /// [`ChannelManager::funding_transaction_generated`].
412                 ///
413                 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
414                 temporary_channel_id: ChannelId,
415                 /// The counterparty's node_id, which you'll need to pass back into
416                 /// [`ChannelManager::funding_transaction_generated`].
417                 ///
418                 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
419                 counterparty_node_id: PublicKey,
420                 /// The value, in satoshis, that the output should have.
421                 channel_value_satoshis: u64,
422                 /// The script which should be used in the transaction output.
423                 output_script: ScriptBuf,
424                 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
425                 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
426                 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
427                 /// `user_channel_id` will be randomized for an inbound channel.  This may be zero for objects
428                 /// serialized with LDK versions prior to 0.0.113.
429                 ///
430                 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
431                 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
432                 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
433                 user_channel_id: u128,
434         },
435         /// Indicates that we've been offered a payment and it needs to be claimed via calling
436         /// [`ChannelManager::claim_funds`] with the preimage given in [`PaymentPurpose`].
437         ///
438         /// Note that if the preimage is not known, you should call
439         /// [`ChannelManager::fail_htlc_backwards`] or [`ChannelManager::fail_htlc_backwards_with_reason`]
440         /// to free up resources for this HTLC and avoid network congestion.
441         ///
442         /// If [`Event::PaymentClaimable::onion_fields`] is `Some`, and includes custom TLVs with even type
443         /// numbers, you should use [`ChannelManager::fail_htlc_backwards_with_reason`] with
444         /// [`FailureCode::InvalidOnionPayload`] if you fail to understand and handle the contents, or
445         /// [`ChannelManager::claim_funds_with_known_custom_tlvs`] upon successful handling.
446         /// If you don't intend to check for custom TLVs, you can simply use
447         /// [`ChannelManager::claim_funds`], which will automatically fail back even custom TLVs.
448         ///
449         /// If you fail to call [`ChannelManager::claim_funds`],
450         /// [`ChannelManager::claim_funds_with_known_custom_tlvs`],
451         /// [`ChannelManager::fail_htlc_backwards`], or
452         /// [`ChannelManager::fail_htlc_backwards_with_reason`] within the HTLC's timeout, the HTLC will
453         /// be automatically failed.
454         ///
455         /// # Note
456         /// LDK will not stop an inbound payment from being paid multiple times, so multiple
457         /// `PaymentClaimable` events may be generated for the same payment. In such a case it is
458         /// polite (and required in the lightning specification) to fail the payment the second time
459         /// and give the sender their money back rather than accepting double payment.
460         ///
461         /// # Note
462         /// This event used to be called `PaymentReceived` in LDK versions 0.0.112 and earlier.
463         ///
464         /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
465         /// [`ChannelManager::claim_funds_with_known_custom_tlvs`]: crate::ln::channelmanager::ChannelManager::claim_funds_with_known_custom_tlvs
466         /// [`FailureCode::InvalidOnionPayload`]: crate::ln::channelmanager::FailureCode::InvalidOnionPayload
467         /// [`ChannelManager::fail_htlc_backwards`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards
468         /// [`ChannelManager::fail_htlc_backwards_with_reason`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards_with_reason
469         PaymentClaimable {
470                 /// The node that will receive the payment after it has been claimed.
471                 /// This is useful to identify payments received via [phantom nodes].
472                 /// This field will always be filled in when the event was generated by LDK versions
473                 /// 0.0.113 and above.
474                 ///
475                 /// [phantom nodes]: crate::sign::PhantomKeysManager
476                 receiver_node_id: Option<PublicKey>,
477                 /// The hash for which the preimage should be handed to the ChannelManager. Note that LDK will
478                 /// not stop you from registering duplicate payment hashes for inbound payments.
479                 payment_hash: PaymentHash,
480                 /// The fields in the onion which were received with each HTLC. Only fields which were
481                 /// identical in each HTLC involved in the payment will be included here.
482                 ///
483                 /// Payments received on LDK versions prior to 0.0.115 will have this field unset.
484                 onion_fields: Option<RecipientOnionFields>,
485                 /// The value, in thousandths of a satoshi, that this payment is claimable for. May be greater
486                 /// than the invoice amount.
487                 ///
488                 /// May be less than the invoice amount if [`ChannelConfig::accept_underpaying_htlcs`] is set
489                 /// and the previous hop took an extra fee.
490                 ///
491                 /// # Note
492                 /// If [`ChannelConfig::accept_underpaying_htlcs`] is set and you claim without verifying this
493                 /// field, you may lose money!
494                 ///
495                 /// [`ChannelConfig::accept_underpaying_htlcs`]: crate::util::config::ChannelConfig::accept_underpaying_htlcs
496                 amount_msat: u64,
497                 /// The value, in thousands of a satoshi, that was skimmed off of this payment as an extra fee
498                 /// taken by our channel counterparty.
499                 ///
500                 /// Will always be 0 unless [`ChannelConfig::accept_underpaying_htlcs`] is set.
501                 ///
502                 /// [`ChannelConfig::accept_underpaying_htlcs`]: crate::util::config::ChannelConfig::accept_underpaying_htlcs
503                 counterparty_skimmed_fee_msat: u64,
504                 /// Information for claiming this received payment, based on whether the purpose of the
505                 /// payment is to pay an invoice or to send a spontaneous payment.
506                 purpose: PaymentPurpose,
507                 /// The `channel_id` indicating over which channel we received the payment.
508                 via_channel_id: Option<ChannelId>,
509                 /// The `user_channel_id` indicating over which channel we received the payment.
510                 via_user_channel_id: Option<u128>,
511                 /// The block height at which this payment will be failed back and will no longer be
512                 /// eligible for claiming.
513                 ///
514                 /// Prior to this height, a call to [`ChannelManager::claim_funds`] is guaranteed to
515                 /// succeed, however you should wait for [`Event::PaymentClaimed`] to be sure.
516                 ///
517                 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
518                 claim_deadline: Option<u32>,
519         },
520         /// Indicates a payment has been claimed and we've received money!
521         ///
522         /// This most likely occurs when [`ChannelManager::claim_funds`] has been called in response
523         /// to an [`Event::PaymentClaimable`]. However, if we previously crashed during a
524         /// [`ChannelManager::claim_funds`] call you may see this event without a corresponding
525         /// [`Event::PaymentClaimable`] event.
526         ///
527         /// # Note
528         /// LDK will not stop an inbound payment from being paid multiple times, so multiple
529         /// `PaymentClaimable` events may be generated for the same payment. If you then call
530         /// [`ChannelManager::claim_funds`] twice for the same [`Event::PaymentClaimable`] you may get
531         /// multiple `PaymentClaimed` events.
532         ///
533         /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
534         PaymentClaimed {
535                 /// The node that received the payment.
536                 /// This is useful to identify payments which were received via [phantom nodes].
537                 /// This field will always be filled in when the event was generated by LDK versions
538                 /// 0.0.113 and above.
539                 ///
540                 /// [phantom nodes]: crate::sign::PhantomKeysManager
541                 receiver_node_id: Option<PublicKey>,
542                 /// The payment hash of the claimed payment. Note that LDK will not stop you from
543                 /// registering duplicate payment hashes for inbound payments.
544                 payment_hash: PaymentHash,
545                 /// The value, in thousandths of a satoshi, that this payment is for. May be greater than the
546                 /// invoice amount.
547                 amount_msat: u64,
548                 /// The purpose of the claimed payment, i.e. whether the payment was for an invoice or a
549                 /// spontaneous payment.
550                 purpose: PaymentPurpose,
551                 /// The HTLCs that comprise the claimed payment. This will be empty for events serialized prior
552                 /// to LDK version 0.0.117.
553                 htlcs: Vec<ClaimedHTLC>,
554                 /// The sender-intended sum total of all the MPP parts. This will be `None` for events
555                 /// serialized prior to LDK version 0.0.117.
556                 sender_intended_total_msat: Option<u64>,
557         },
558         /// Indicates that a peer connection with a node is needed in order to send an [`OnionMessage`].
559         ///
560         /// Typically, this happens when a [`MessageRouter`] is unable to find a complete path to a
561         /// [`Destination`]. Once a connection is established, any messages buffered by an
562         /// [`OnionMessageHandler`] may be sent.
563         ///
564         /// This event will not be generated for onion message forwards; only for sends including
565         /// replies. Handlers should connect to the node otherwise any buffered messages may be lost.
566         ///
567         /// [`OnionMessage`]: msgs::OnionMessage
568         /// [`MessageRouter`]: crate::onion_message::messenger::MessageRouter
569         /// [`Destination`]: crate::onion_message::messenger::Destination
570         /// [`OnionMessageHandler`]: crate::ln::msgs::OnionMessageHandler
571         ConnectionNeeded {
572                 /// The node id for the node needing a connection.
573                 node_id: PublicKey,
574                 /// Sockets for connecting to the node.
575                 addresses: Vec<msgs::SocketAddress>,
576         },
577         /// Indicates a request for an invoice failed to yield a response in a reasonable amount of time
578         /// or was explicitly abandoned by [`ChannelManager::abandon_payment`]. This may be for an
579         /// [`InvoiceRequest`] sent for an [`Offer`] or for a [`Refund`] that hasn't been redeemed.
580         ///
581         /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
582         /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
583         /// [`Offer`]: crate::offers::offer::Offer
584         /// [`Refund`]: crate::offers::refund::Refund
585         InvoiceRequestFailed {
586                 /// The `payment_id` to have been associated with payment for the requested invoice.
587                 payment_id: PaymentId,
588         },
589         /// Indicates an outbound payment we made succeeded (i.e. it made it all the way to its target
590         /// and we got back the payment preimage for it).
591         ///
592         /// Note for MPP payments: in rare cases, this event may be preceded by a `PaymentPathFailed`
593         /// event. In this situation, you SHOULD treat this payment as having succeeded.
594         PaymentSent {
595                 /// The `payment_id` passed to [`ChannelManager::send_payment`].
596                 ///
597                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
598                 payment_id: Option<PaymentId>,
599                 /// The preimage to the hash given to ChannelManager::send_payment.
600                 /// Note that this serves as a payment receipt, if you wish to have such a thing, you must
601                 /// store it somehow!
602                 payment_preimage: PaymentPreimage,
603                 /// The hash that was given to [`ChannelManager::send_payment`].
604                 ///
605                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
606                 payment_hash: PaymentHash,
607                 /// The total fee which was spent at intermediate hops in this payment, across all paths.
608                 ///
609                 /// Note that, like [`Route::get_total_fees`] this does *not* include any potential
610                 /// overpayment to the recipient node.
611                 ///
612                 /// If the recipient or an intermediate node misbehaves and gives us free money, this may
613                 /// overstate the amount paid, though this is unlikely.
614                 ///
615                 /// [`Route::get_total_fees`]: crate::routing::router::Route::get_total_fees
616                 fee_paid_msat: Option<u64>,
617         },
618         /// Indicates an outbound payment failed. Individual [`Event::PaymentPathFailed`] events
619         /// provide failure information for each path attempt in the payment, including retries.
620         ///
621         /// This event is provided once there are no further pending HTLCs for the payment and the
622         /// payment is no longer retryable, due either to the [`Retry`] provided or
623         /// [`ChannelManager::abandon_payment`] having been called for the corresponding payment.
624         ///
625         /// In exceedingly rare cases, it is possible that an [`Event::PaymentFailed`] is generated for
626         /// a payment after an [`Event::PaymentSent`] event for this same payment has already been
627         /// received and processed. In this case, the [`Event::PaymentFailed`] event MUST be ignored,
628         /// and the payment MUST be treated as having succeeded.
629         ///
630         /// [`Retry`]: crate::ln::channelmanager::Retry
631         /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
632         PaymentFailed {
633                 /// The `payment_id` passed to [`ChannelManager::send_payment`].
634                 ///
635                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
636                 payment_id: PaymentId,
637                 /// The hash that was given to [`ChannelManager::send_payment`].
638                 ///
639                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
640                 payment_hash: PaymentHash,
641                 /// The reason the payment failed. This is only `None` for events generated or serialized
642                 /// by versions prior to 0.0.115.
643                 reason: Option<PaymentFailureReason>,
644         },
645         /// Indicates that a path for an outbound payment was successful.
646         ///
647         /// Always generated after [`Event::PaymentSent`] and thus useful for scoring channels. See
648         /// [`Event::PaymentSent`] for obtaining the payment preimage.
649         PaymentPathSuccessful {
650                 /// The `payment_id` passed to [`ChannelManager::send_payment`].
651                 ///
652                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
653                 payment_id: PaymentId,
654                 /// The hash that was given to [`ChannelManager::send_payment`].
655                 ///
656                 /// This will be `Some` for all payments which completed on LDK 0.0.104 or later.
657                 ///
658                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
659                 payment_hash: Option<PaymentHash>,
660                 /// The payment path that was successful.
661                 ///
662                 /// May contain a closed channel if the HTLC sent along the path was fulfilled on chain.
663                 path: Path,
664         },
665         /// Indicates an outbound HTLC we sent failed, likely due to an intermediary node being unable to
666         /// handle the HTLC.
667         ///
668         /// Note that this does *not* indicate that all paths for an MPP payment have failed, see
669         /// [`Event::PaymentFailed`].
670         ///
671         /// See [`ChannelManager::abandon_payment`] for giving up on this payment before its retries have
672         /// been exhausted.
673         ///
674         /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
675         PaymentPathFailed {
676                 /// The `payment_id` passed to [`ChannelManager::send_payment`].
677                 ///
678                 /// This will be `Some` for all payment paths which failed on LDK 0.0.103 or later.
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: Path,
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: Path,
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: Path,
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                 /// Forwarding less than this amount may break compatibility with LDK versions prior to 0.0.116.
782                 ///
783                 /// Note that LDK will NOT check that expected fees were factored into this value. You MUST
784                 /// check that whatever fee you want has been included here or subtract it as required. Further,
785                 /// LDK will not stop you from forwarding more than you received.
786                 expected_outbound_amount_msat: u64,
787         },
788         /// Used to indicate that an output which you should know how to spend was confirmed on chain
789         /// and is now spendable.
790         /// Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
791         /// counterparty spending them due to some kind of timeout. Thus, you need to store them
792         /// somewhere and spend them when you create on-chain transactions.
793         SpendableOutputs {
794                 /// The outputs which you should store as spendable by you.
795                 outputs: Vec<SpendableOutputDescriptor>,
796                 /// The `channel_id` indicating which channel the spendable outputs belong to.
797                 ///
798                 /// This will always be `Some` for events generated by LDK versions 0.0.117 and above.
799                 channel_id: Option<ChannelId>,
800         },
801         /// This event is generated when a payment has been successfully forwarded through us and a
802         /// forwarding fee earned.
803         PaymentForwarded {
804                 /// The channel id of the incoming channel between the previous node and us.
805                 ///
806                 /// This is only `None` for events generated or serialized by versions prior to 0.0.107.
807                 prev_channel_id: Option<ChannelId>,
808                 /// The channel id of the outgoing channel between the next node and us.
809                 ///
810                 /// This is only `None` for events generated or serialized by versions prior to 0.0.107.
811                 next_channel_id: Option<ChannelId>,
812                 /// The `user_channel_id` of the incoming channel between the previous node and us.
813                 ///
814                 /// This is only `None` for events generated or serialized by versions prior to 0.0.122.
815                 prev_user_channel_id: Option<u128>,
816                 /// The `user_channel_id` of the outgoing channel between the next node and us.
817                 ///
818                 /// This will be `None` if the payment was settled via an on-chain transaction. See the
819                 /// caveat described for the `total_fee_earned_msat` field. Moreover it will be `None` for
820                 /// events generated or serialized by versions prior to 0.0.122.
821                 next_user_channel_id: Option<u128>,
822                 /// The total fee, in milli-satoshis, which was earned as a result of the payment.
823                 ///
824                 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
825                 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
826                 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
827                 /// claimed the full value in millisatoshis from the source. In this case,
828                 /// `claim_from_onchain_tx` will be set.
829                 ///
830                 /// If the channel which sent us the payment has been force-closed, we will claim the funds
831                 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
832                 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
833                 /// `PaymentForwarded` events are generated for the same payment iff `total_fee_earned_msat` is
834                 /// `None`.
835                 total_fee_earned_msat: Option<u64>,
836                 /// The share of the total fee, in milli-satoshis, which was withheld in addition to the
837                 /// forwarding fee.
838                 ///
839                 /// This will only be `Some` if we forwarded an intercepted HTLC with less than the
840                 /// expected amount. This means our counterparty accepted to receive less than the invoice
841                 /// amount, e.g., by claiming the payment featuring a corresponding
842                 /// [`PaymentClaimable::counterparty_skimmed_fee_msat`].
843                 ///
844                 /// Will also always be `None` for events serialized with LDK prior to version 0.0.122.
845                 ///
846                 /// The caveat described above the `total_fee_earned_msat` field applies here as well.
847                 ///
848                 /// [`PaymentClaimable::counterparty_skimmed_fee_msat`]: Self::PaymentClaimable::counterparty_skimmed_fee_msat
849                 skimmed_fee_msat: Option<u64>,
850                 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
851                 /// transaction.
852                 claim_from_onchain_tx: bool,
853                 /// The final amount forwarded, in milli-satoshis, after the fee is deducted.
854                 ///
855                 /// The caveat described above the `total_fee_earned_msat` field applies here as well.
856                 outbound_amount_forwarded_msat: Option<u64>,
857         },
858         /// Used to indicate that a channel with the given `channel_id` is being opened and pending
859         /// confirmation on-chain.
860         ///
861         /// This event is emitted when the funding transaction has been signed and is broadcast to the
862         /// network. For 0conf channels it will be immediately followed by the corresponding
863         /// [`Event::ChannelReady`] event.
864         ChannelPending {
865                 /// The `channel_id` of the channel that is pending confirmation.
866                 channel_id: ChannelId,
867                 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
868                 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
869                 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
870                 /// `user_channel_id` will be randomized for an inbound channel.
871                 ///
872                 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
873                 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
874                 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
875                 user_channel_id: u128,
876                 /// The `temporary_channel_id` this channel used to be known by during channel establishment.
877                 ///
878                 /// Will be `None` for channels created prior to LDK version 0.0.115.
879                 former_temporary_channel_id: Option<ChannelId>,
880                 /// The `node_id` of the channel counterparty.
881                 counterparty_node_id: PublicKey,
882                 /// The outpoint of the channel's funding transaction.
883                 funding_txo: OutPoint,
884                 /// The features that this channel will operate with.
885                 ///
886                 /// Will be `None` for channels created prior to LDK version 0.0.122.
887                 channel_type: Option<ChannelTypeFeatures>,
888         },
889         /// Used to indicate that a channel with the given `channel_id` is ready to
890         /// be used. This event is emitted either when the funding transaction has been confirmed
891         /// on-chain, or, in case of a 0conf channel, when both parties have confirmed the channel
892         /// establishment.
893         ChannelReady {
894                 /// The `channel_id` of the channel that is ready.
895                 channel_id: ChannelId,
896                 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
897                 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
898                 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
899                 /// `user_channel_id` will be randomized for an inbound channel.
900                 ///
901                 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
902                 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
903                 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
904                 user_channel_id: u128,
905                 /// The `node_id` of the channel counterparty.
906                 counterparty_node_id: PublicKey,
907                 /// The features that this channel will operate with.
908                 channel_type: ChannelTypeFeatures,
909         },
910         /// Used to indicate that a previously opened channel with the given `channel_id` is in the
911         /// process of closure.
912         ///
913         /// Note that this event is only triggered for accepted channels: if the
914         /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true and the channel is
915         /// rejected, no `ChannelClosed` event will be sent.
916         ///
917         /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
918         /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
919         ChannelClosed {
920                 /// The `channel_id` of the channel which has been closed. Note that on-chain transactions
921                 /// resolving the channel are likely still awaiting confirmation.
922                 channel_id: ChannelId,
923                 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
924                 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
925                 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
926                 /// `user_channel_id` will be randomized for inbound channels.
927                 /// This may be zero for inbound channels serialized prior to 0.0.113 and will always be
928                 /// zero for objects serialized with LDK versions prior to 0.0.102.
929                 ///
930                 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
931                 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
932                 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
933                 user_channel_id: u128,
934                 /// The reason the channel was closed.
935                 reason: ClosureReason,
936                 /// Counterparty in the closed channel.
937                 ///
938                 /// This field will be `None` for objects serialized prior to LDK 0.0.117.
939                 counterparty_node_id: Option<PublicKey>,
940                 /// Channel capacity of the closing channel (sats).
941                 ///
942                 /// This field will be `None` for objects serialized prior to LDK 0.0.117.
943                 channel_capacity_sats: Option<u64>,
944                 /// The original channel funding TXO; this helps checking for the existence and confirmation
945                 /// status of the closing tx.
946                 /// Note that for instances serialized in v0.0.119 or prior this will be missing (None).
947                 channel_funding_txo: Option<transaction::OutPoint>,
948         },
949         /// Used to indicate to the user that they can abandon the funding transaction and recycle the
950         /// inputs for another purpose.
951         ///
952         /// This event is not guaranteed to be generated for channels that are closed due to a restart.
953         DiscardFunding {
954                 /// The channel_id of the channel which has been closed.
955                 channel_id: ChannelId,
956                 /// The full transaction received from the user
957                 transaction: Transaction
958         },
959         /// Indicates a request to open a new channel by a peer.
960         ///
961         /// To accept the request, call [`ChannelManager::accept_inbound_channel`]. To reject the request,
962         /// call [`ChannelManager::force_close_without_broadcasting_txn`]. Note that a ['ChannelClosed`]
963         /// event will _not_ be triggered if the channel is rejected.
964         ///
965         /// The event is only triggered when a new open channel request is received and the
966         /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true.
967         ///
968         /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
969         /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
970         /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
971         OpenChannelRequest {
972                 /// The temporary channel ID of the channel requested to be opened.
973                 ///
974                 /// When responding to the request, the `temporary_channel_id` should be passed
975                 /// back to the ChannelManager through [`ChannelManager::accept_inbound_channel`] to accept,
976                 /// or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject.
977                 ///
978                 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
979                 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
980                 temporary_channel_id: ChannelId,
981                 /// The node_id of the counterparty requesting to open the channel.
982                 ///
983                 /// When responding to the request, the `counterparty_node_id` should be passed
984                 /// back to the `ChannelManager` through [`ChannelManager::accept_inbound_channel`] to
985                 /// accept the request, or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject the
986                 /// request.
987                 ///
988                 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
989                 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
990                 counterparty_node_id: PublicKey,
991                 /// The channel value of the requested channel.
992                 funding_satoshis: u64,
993                 /// Our starting balance in the channel if the request is accepted, in milli-satoshi.
994                 push_msat: u64,
995                 /// The features that this channel will operate with. If you reject the channel, a
996                 /// well-behaved counterparty may automatically re-attempt the channel with a new set of
997                 /// feature flags.
998                 ///
999                 /// Note that if [`ChannelTypeFeatures::supports_scid_privacy`] returns true on this type,
1000                 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
1001                 /// 0.0.106.
1002                 ///
1003                 /// Furthermore, note that if [`ChannelTypeFeatures::supports_zero_conf`] returns true on this type,
1004                 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
1005                 /// 0.0.107. Channels setting this type also need to get manually accepted via
1006                 /// [`crate::ln::channelmanager::ChannelManager::accept_inbound_channel_from_trusted_peer_0conf`],
1007                 /// or will be rejected otherwise.
1008                 ///
1009                 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
1010                 channel_type: ChannelTypeFeatures,
1011         },
1012         /// Indicates that the HTLC was accepted, but could not be processed when or after attempting to
1013         /// forward it.
1014         ///
1015         /// Some scenarios where this event may be sent include:
1016         /// * Insufficient capacity in the outbound channel
1017         /// * While waiting to forward the HTLC, the channel it is meant to be forwarded through closes
1018         /// * When an unknown SCID is requested for forwarding a payment.
1019         /// * Expected MPP amount has already been reached
1020         /// * The HTLC has timed out
1021         ///
1022         /// This event, however, does not get generated if an HTLC fails to meet the forwarding
1023         /// requirements (i.e. insufficient fees paid, or a CLTV that is too soon).
1024         HTLCHandlingFailed {
1025                 /// The channel over which the HTLC was received.
1026                 prev_channel_id: ChannelId,
1027                 /// Destination of the HTLC that failed to be processed.
1028                 failed_next_destination: HTLCDestination,
1029         },
1030         /// Indicates that a transaction originating from LDK needs to have its fee bumped. This event
1031         /// requires confirmed external funds to be readily available to spend.
1032         ///
1033         /// LDK does not currently generate this event unless the
1034         /// [`ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx`] config flag is set to true.
1035         /// It is limited to the scope of channels with anchor outputs.
1036         ///
1037         /// [`ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx`]: crate::util::config::ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx
1038         BumpTransaction(BumpTransactionEvent),
1039 }
1040
1041 impl Writeable for Event {
1042         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1043                 match self {
1044                         &Event::FundingGenerationReady { .. } => {
1045                                 0u8.write(writer)?;
1046                                 // We never write out FundingGenerationReady events as, upon disconnection, peers
1047                                 // drop any channels which have not yet exchanged funding_signed.
1048                         },
1049                         &Event::PaymentClaimable { ref payment_hash, ref amount_msat, counterparty_skimmed_fee_msat,
1050                                 ref purpose, ref receiver_node_id, ref via_channel_id, ref via_user_channel_id,
1051                                 ref claim_deadline, ref onion_fields
1052                         } => {
1053                                 1u8.write(writer)?;
1054                                 let mut payment_secret = None;
1055                                 let payment_preimage;
1056                                 match &purpose {
1057                                         PaymentPurpose::InvoicePayment { payment_preimage: preimage, payment_secret: secret } => {
1058                                                 payment_secret = Some(secret);
1059                                                 payment_preimage = *preimage;
1060                                         },
1061                                         PaymentPurpose::SpontaneousPayment(preimage) => {
1062                                                 payment_preimage = Some(*preimage);
1063                                         }
1064                                 }
1065                                 let skimmed_fee_opt = if counterparty_skimmed_fee_msat == 0 { None }
1066                                         else { Some(counterparty_skimmed_fee_msat) };
1067                                 write_tlv_fields!(writer, {
1068                                         (0, payment_hash, required),
1069                                         (1, receiver_node_id, option),
1070                                         (2, payment_secret, option),
1071                                         (3, via_channel_id, option),
1072                                         (4, amount_msat, required),
1073                                         (5, via_user_channel_id, option),
1074                                         // Type 6 was `user_payment_id` on 0.0.103 and earlier
1075                                         (7, claim_deadline, option),
1076                                         (8, payment_preimage, option),
1077                                         (9, onion_fields, option),
1078                                         (10, skimmed_fee_opt, option),
1079                                 });
1080                         },
1081                         &Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
1082                                 2u8.write(writer)?;
1083                                 write_tlv_fields!(writer, {
1084                                         (0, payment_preimage, required),
1085                                         (1, payment_hash, required),
1086                                         (3, payment_id, option),
1087                                         (5, fee_paid_msat, option),
1088                                 });
1089                         },
1090                         &Event::PaymentPathFailed {
1091                                 ref payment_id, ref payment_hash, ref payment_failed_permanently, ref failure,
1092                                 ref path, ref short_channel_id,
1093                                 #[cfg(test)]
1094                                 ref error_code,
1095                                 #[cfg(test)]
1096                                 ref error_data,
1097                         } => {
1098                                 3u8.write(writer)?;
1099                                 #[cfg(test)]
1100                                 error_code.write(writer)?;
1101                                 #[cfg(test)]
1102                                 error_data.write(writer)?;
1103                                 write_tlv_fields!(writer, {
1104                                         (0, payment_hash, required),
1105                                         (1, None::<NetworkUpdate>, option), // network_update in LDK versions prior to 0.0.114
1106                                         (2, payment_failed_permanently, required),
1107                                         (3, false, required), // all_paths_failed in LDK versions prior to 0.0.114
1108                                         (4, path.blinded_tail, option),
1109                                         (5, path.hops, required_vec),
1110                                         (7, short_channel_id, option),
1111                                         (9, None::<RouteParameters>, option), // retry in LDK versions prior to 0.0.115
1112                                         (11, payment_id, option),
1113                                         (13, failure, required),
1114                                 });
1115                         },
1116                         &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
1117                                 4u8.write(writer)?;
1118                                 // Note that we now ignore these on the read end as we'll re-generate them in
1119                                 // ChannelManager, we write them here only for backwards compatibility.
1120                         },
1121                         &Event::SpendableOutputs { ref outputs, channel_id } => {
1122                                 5u8.write(writer)?;
1123                                 write_tlv_fields!(writer, {
1124                                         (0, WithoutLength(outputs), required),
1125                                         (1, channel_id, option),
1126                                 });
1127                         },
1128                         &Event::HTLCIntercepted { requested_next_hop_scid, payment_hash, inbound_amount_msat, expected_outbound_amount_msat, intercept_id } => {
1129                                 6u8.write(writer)?;
1130                                 let intercept_scid = InterceptNextHop::FakeScid { requested_next_hop_scid };
1131                                 write_tlv_fields!(writer, {
1132                                         (0, intercept_id, required),
1133                                         (2, intercept_scid, required),
1134                                         (4, payment_hash, required),
1135                                         (6, inbound_amount_msat, required),
1136                                         (8, expected_outbound_amount_msat, required),
1137                                 });
1138                         }
1139                         &Event::PaymentForwarded {
1140                                 prev_channel_id, next_channel_id, prev_user_channel_id, next_user_channel_id,
1141                                 total_fee_earned_msat, skimmed_fee_msat, claim_from_onchain_tx,
1142                                 outbound_amount_forwarded_msat,
1143                         } => {
1144                                 7u8.write(writer)?;
1145                                 write_tlv_fields!(writer, {
1146                                         (0, total_fee_earned_msat, option),
1147                                         (1, prev_channel_id, option),
1148                                         (2, claim_from_onchain_tx, required),
1149                                         (3, next_channel_id, option),
1150                                         (5, outbound_amount_forwarded_msat, option),
1151                                         (7, skimmed_fee_msat, option),
1152                                         (9, prev_user_channel_id, option),
1153                                         (11, next_user_channel_id, option),
1154                                 });
1155                         },
1156                         &Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason,
1157                                 ref counterparty_node_id, ref channel_capacity_sats, ref channel_funding_txo
1158                         } => {
1159                                 9u8.write(writer)?;
1160                                 // `user_channel_id` used to be a single u64 value. In order to remain backwards
1161                                 // compatible with versions prior to 0.0.113, the u128 is serialized as two
1162                                 // separate u64 values.
1163                                 let user_channel_id_low = *user_channel_id as u64;
1164                                 let user_channel_id_high = (*user_channel_id >> 64) as u64;
1165                                 write_tlv_fields!(writer, {
1166                                         (0, channel_id, required),
1167                                         (1, user_channel_id_low, required),
1168                                         (2, reason, required),
1169                                         (3, user_channel_id_high, required),
1170                                         (5, counterparty_node_id, option),
1171                                         (7, channel_capacity_sats, option),
1172                                         (9, channel_funding_txo, option),
1173                                 });
1174                         },
1175                         &Event::DiscardFunding { ref channel_id, ref transaction } => {
1176                                 11u8.write(writer)?;
1177                                 write_tlv_fields!(writer, {
1178                                         (0, channel_id, required),
1179                                         (2, transaction, required)
1180                                 })
1181                         },
1182                         &Event::PaymentPathSuccessful { ref payment_id, ref payment_hash, ref path } => {
1183                                 13u8.write(writer)?;
1184                                 write_tlv_fields!(writer, {
1185                                         (0, payment_id, required),
1186                                         (2, payment_hash, option),
1187                                         (4, path.hops, required_vec),
1188                                         (6, path.blinded_tail, option),
1189                                 })
1190                         },
1191                         &Event::PaymentFailed { ref payment_id, ref payment_hash, ref reason } => {
1192                                 15u8.write(writer)?;
1193                                 write_tlv_fields!(writer, {
1194                                         (0, payment_id, required),
1195                                         (1, reason, option),
1196                                         (2, payment_hash, required),
1197                                 })
1198                         },
1199                         &Event::OpenChannelRequest { .. } => {
1200                                 17u8.write(writer)?;
1201                                 // We never write the OpenChannelRequest events as, upon disconnection, peers
1202                                 // drop any channels which have not yet exchanged funding_signed.
1203                         },
1204                         &Event::PaymentClaimed { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id, ref htlcs, ref sender_intended_total_msat } => {
1205                                 19u8.write(writer)?;
1206                                 write_tlv_fields!(writer, {
1207                                         (0, payment_hash, required),
1208                                         (1, receiver_node_id, option),
1209                                         (2, purpose, required),
1210                                         (4, amount_msat, required),
1211                                         (5, *htlcs, optional_vec),
1212                                         (7, sender_intended_total_msat, option),
1213                                 });
1214                         },
1215                         &Event::ProbeSuccessful { ref payment_id, ref payment_hash, ref path } => {
1216                                 21u8.write(writer)?;
1217                                 write_tlv_fields!(writer, {
1218                                         (0, payment_id, required),
1219                                         (2, payment_hash, required),
1220                                         (4, path.hops, required_vec),
1221                                         (6, path.blinded_tail, option),
1222                                 })
1223                         },
1224                         &Event::ProbeFailed { ref payment_id, ref payment_hash, ref path, ref short_channel_id } => {
1225                                 23u8.write(writer)?;
1226                                 write_tlv_fields!(writer, {
1227                                         (0, payment_id, required),
1228                                         (2, payment_hash, required),
1229                                         (4, path.hops, required_vec),
1230                                         (6, short_channel_id, option),
1231                                         (8, path.blinded_tail, option),
1232                                 })
1233                         },
1234                         &Event::HTLCHandlingFailed { ref prev_channel_id, ref failed_next_destination } => {
1235                                 25u8.write(writer)?;
1236                                 write_tlv_fields!(writer, {
1237                                         (0, prev_channel_id, required),
1238                                         (2, failed_next_destination, required),
1239                                 })
1240                         },
1241                         &Event::BumpTransaction(ref event)=> {
1242                                 27u8.write(writer)?;
1243                                 match event {
1244                                         // We never write the ChannelClose|HTLCResolution events as they'll be replayed
1245                                         // upon restarting anyway if they remain unresolved.
1246                                         BumpTransactionEvent::ChannelClose { .. } => {}
1247                                         BumpTransactionEvent::HTLCResolution { .. } => {}
1248                                 }
1249                                 write_tlv_fields!(writer, {}); // Write a length field for forwards compat
1250                         }
1251                         &Event::ChannelReady { ref channel_id, ref user_channel_id, ref counterparty_node_id, ref channel_type } => {
1252                                 29u8.write(writer)?;
1253                                 write_tlv_fields!(writer, {
1254                                         (0, channel_id, required),
1255                                         (2, user_channel_id, required),
1256                                         (4, counterparty_node_id, required),
1257                                         (6, channel_type, required),
1258                                 });
1259                         },
1260                         &Event::ChannelPending { ref channel_id, ref user_channel_id,
1261                                 ref former_temporary_channel_id, ref counterparty_node_id, ref funding_txo,
1262                                 ref channel_type
1263                         } => {
1264                                 31u8.write(writer)?;
1265                                 write_tlv_fields!(writer, {
1266                                         (0, channel_id, required),
1267                                         (1, channel_type, option),
1268                                         (2, user_channel_id, required),
1269                                         (4, former_temporary_channel_id, required),
1270                                         (6, counterparty_node_id, required),
1271                                         (8, funding_txo, required),
1272                                 });
1273                         },
1274                         &Event::InvoiceRequestFailed { ref payment_id } => {
1275                                 33u8.write(writer)?;
1276                                 write_tlv_fields!(writer, {
1277                                         (0, payment_id, required),
1278                                 })
1279                         },
1280                         &Event::ConnectionNeeded { .. } => {
1281                                 35u8.write(writer)?;
1282                                 // Never write ConnectionNeeded events as buffered onion messages aren't serialized.
1283                         },
1284                         // Note that, going forward, all new events must only write data inside of
1285                         // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
1286                         // data via `write_tlv_fields`.
1287                 }
1288                 Ok(())
1289         }
1290 }
1291 impl MaybeReadable for Event {
1292         fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
1293                 match Readable::read(reader)? {
1294                         // Note that we do not write a length-prefixed TLV for FundingGenerationReady events.
1295                         0u8 => Ok(None),
1296                         1u8 => {
1297                                 let f = || {
1298                                         let mut payment_hash = PaymentHash([0; 32]);
1299                                         let mut payment_preimage = None;
1300                                         let mut payment_secret = None;
1301                                         let mut amount_msat = 0;
1302                                         let mut counterparty_skimmed_fee_msat_opt = None;
1303                                         let mut receiver_node_id = None;
1304                                         let mut _user_payment_id = None::<u64>; // Used in 0.0.103 and earlier, no longer written in 0.0.116+.
1305                                         let mut via_channel_id = None;
1306                                         let mut claim_deadline = None;
1307                                         let mut via_user_channel_id = None;
1308                                         let mut onion_fields = None;
1309                                         read_tlv_fields!(reader, {
1310                                                 (0, payment_hash, required),
1311                                                 (1, receiver_node_id, option),
1312                                                 (2, payment_secret, option),
1313                                                 (3, via_channel_id, option),
1314                                                 (4, amount_msat, required),
1315                                                 (5, via_user_channel_id, option),
1316                                                 (6, _user_payment_id, option),
1317                                                 (7, claim_deadline, option),
1318                                                 (8, payment_preimage, option),
1319                                                 (9, onion_fields, option),
1320                                                 (10, counterparty_skimmed_fee_msat_opt, option),
1321                                         });
1322                                         let purpose = match payment_secret {
1323                                                 Some(secret) => PaymentPurpose::InvoicePayment {
1324                                                         payment_preimage,
1325                                                         payment_secret: secret
1326                                                 },
1327                                                 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
1328                                                 None => return Err(msgs::DecodeError::InvalidValue),
1329                                         };
1330                                         Ok(Some(Event::PaymentClaimable {
1331                                                 receiver_node_id,
1332                                                 payment_hash,
1333                                                 amount_msat,
1334                                                 counterparty_skimmed_fee_msat: counterparty_skimmed_fee_msat_opt.unwrap_or(0),
1335                                                 purpose,
1336                                                 via_channel_id,
1337                                                 via_user_channel_id,
1338                                                 claim_deadline,
1339                                                 onion_fields,
1340                                         }))
1341                                 };
1342                                 f()
1343                         },
1344                         2u8 => {
1345                                 let f = || {
1346                                         let mut payment_preimage = PaymentPreimage([0; 32]);
1347                                         let mut payment_hash = None;
1348                                         let mut payment_id = None;
1349                                         let mut fee_paid_msat = None;
1350                                         read_tlv_fields!(reader, {
1351                                                 (0, payment_preimage, required),
1352                                                 (1, payment_hash, option),
1353                                                 (3, payment_id, option),
1354                                                 (5, fee_paid_msat, option),
1355                                         });
1356                                         if payment_hash.is_none() {
1357                                                 payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).to_byte_array()));
1358                                         }
1359                                         Ok(Some(Event::PaymentSent {
1360                                                 payment_id,
1361                                                 payment_preimage,
1362                                                 payment_hash: payment_hash.unwrap(),
1363                                                 fee_paid_msat,
1364                                         }))
1365                                 };
1366                                 f()
1367                         },
1368                         3u8 => {
1369                                 let f = || {
1370                                         #[cfg(test)]
1371                                         let error_code = Readable::read(reader)?;
1372                                         #[cfg(test)]
1373                                         let error_data = Readable::read(reader)?;
1374                                         let mut payment_hash = PaymentHash([0; 32]);
1375                                         let mut payment_failed_permanently = false;
1376                                         let mut network_update = None;
1377                                         let mut blinded_tail: Option<BlindedTail> = None;
1378                                         let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1379                                         let mut short_channel_id = None;
1380                                         let mut payment_id = None;
1381                                         let mut failure_opt = None;
1382                                         read_tlv_fields!(reader, {
1383                                                 (0, payment_hash, required),
1384                                                 (1, network_update, upgradable_option),
1385                                                 (2, payment_failed_permanently, required),
1386                                                 (4, blinded_tail, option),
1387                                                 // Added as a part of LDK 0.0.101 and always filled in since.
1388                                                 // Defaults to an empty Vec, though likely should have been `Option`al.
1389                                                 (5, path, optional_vec),
1390                                                 (7, short_channel_id, option),
1391                                                 (11, payment_id, option),
1392                                                 (13, failure_opt, upgradable_option),
1393                                         });
1394                                         let failure = failure_opt.unwrap_or_else(|| PathFailure::OnPath { network_update });
1395                                         Ok(Some(Event::PaymentPathFailed {
1396                                                 payment_id,
1397                                                 payment_hash,
1398                                                 payment_failed_permanently,
1399                                                 failure,
1400                                                 path: Path { hops: path.unwrap(), blinded_tail },
1401                                                 short_channel_id,
1402                                                 #[cfg(test)]
1403                                                 error_code,
1404                                                 #[cfg(test)]
1405                                                 error_data,
1406                                         }))
1407                                 };
1408                                 f()
1409                         },
1410                         4u8 => Ok(None),
1411                         5u8 => {
1412                                 let f = || {
1413                                         let mut outputs = WithoutLength(Vec::new());
1414                                         let mut channel_id: Option<ChannelId> = None;
1415                                         read_tlv_fields!(reader, {
1416                                                 (0, outputs, required),
1417                                                 (1, channel_id, option),
1418                                         });
1419                                         Ok(Some(Event::SpendableOutputs { outputs: outputs.0, channel_id }))
1420                                 };
1421                                 f()
1422                         },
1423                         6u8 => {
1424                                 let mut payment_hash = PaymentHash([0; 32]);
1425                                 let mut intercept_id = InterceptId([0; 32]);
1426                                 let mut requested_next_hop_scid = InterceptNextHop::FakeScid { requested_next_hop_scid: 0 };
1427                                 let mut inbound_amount_msat = 0;
1428                                 let mut expected_outbound_amount_msat = 0;
1429                                 read_tlv_fields!(reader, {
1430                                         (0, intercept_id, required),
1431                                         (2, requested_next_hop_scid, required),
1432                                         (4, payment_hash, required),
1433                                         (6, inbound_amount_msat, required),
1434                                         (8, expected_outbound_amount_msat, required),
1435                                 });
1436                                 let next_scid = match requested_next_hop_scid {
1437                                         InterceptNextHop::FakeScid { requested_next_hop_scid: scid } => scid
1438                                 };
1439                                 Ok(Some(Event::HTLCIntercepted {
1440                                         payment_hash,
1441                                         requested_next_hop_scid: next_scid,
1442                                         inbound_amount_msat,
1443                                         expected_outbound_amount_msat,
1444                                         intercept_id,
1445                                 }))
1446                         },
1447                         7u8 => {
1448                                 let f = || {
1449                                         let mut prev_channel_id = None;
1450                                         let mut next_channel_id = None;
1451                                         let mut prev_user_channel_id = None;
1452                                         let mut next_user_channel_id = None;
1453                                         let mut total_fee_earned_msat = None;
1454                                         let mut skimmed_fee_msat = None;
1455                                         let mut claim_from_onchain_tx = false;
1456                                         let mut outbound_amount_forwarded_msat = None;
1457                                         read_tlv_fields!(reader, {
1458                                                 (0, total_fee_earned_msat, option),
1459                                                 (1, prev_channel_id, option),
1460                                                 (2, claim_from_onchain_tx, required),
1461                                                 (3, next_channel_id, option),
1462                                                 (5, outbound_amount_forwarded_msat, option),
1463                                                 (7, skimmed_fee_msat, option),
1464                                                 (9, prev_user_channel_id, option),
1465                                                 (11, next_user_channel_id, option),
1466                                         });
1467                                         Ok(Some(Event::PaymentForwarded {
1468                                                 prev_channel_id, next_channel_id, prev_user_channel_id,
1469                                                 next_user_channel_id, total_fee_earned_msat, skimmed_fee_msat,
1470                                                 claim_from_onchain_tx, outbound_amount_forwarded_msat,
1471                                         }))
1472                                 };
1473                                 f()
1474                         },
1475                         9u8 => {
1476                                 let f = || {
1477                                         let mut channel_id = ChannelId::new_zero();
1478                                         let mut reason = UpgradableRequired(None);
1479                                         let mut user_channel_id_low_opt: Option<u64> = None;
1480                                         let mut user_channel_id_high_opt: Option<u64> = None;
1481                                         let mut counterparty_node_id = None;
1482                                         let mut channel_capacity_sats = None;
1483                                         let mut channel_funding_txo = None;
1484                                         read_tlv_fields!(reader, {
1485                                                 (0, channel_id, required),
1486                                                 (1, user_channel_id_low_opt, option),
1487                                                 (2, reason, upgradable_required),
1488                                                 (3, user_channel_id_high_opt, option),
1489                                                 (5, counterparty_node_id, option),
1490                                                 (7, channel_capacity_sats, option),
1491                                                 (9, channel_funding_txo, option),
1492                                         });
1493
1494                                         // `user_channel_id` used to be a single u64 value. In order to remain
1495                                         // backwards compatible with versions prior to 0.0.113, the u128 is serialized
1496                                         // as two separate u64 values.
1497                                         let user_channel_id = (user_channel_id_low_opt.unwrap_or(0) as u128) +
1498                                                 ((user_channel_id_high_opt.unwrap_or(0) as u128) << 64);
1499
1500                                         Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: _init_tlv_based_struct_field!(reason, upgradable_required),
1501                                                 counterparty_node_id, channel_capacity_sats, channel_funding_txo }))
1502                                 };
1503                                 f()
1504                         },
1505                         11u8 => {
1506                                 let f = || {
1507                                         let mut channel_id = ChannelId::new_zero();
1508                                         let mut transaction = Transaction{ version: 2, lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
1509                                         read_tlv_fields!(reader, {
1510                                                 (0, channel_id, required),
1511                                                 (2, transaction, required),
1512                                         });
1513                                         Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
1514                                 };
1515                                 f()
1516                         },
1517                         13u8 => {
1518                                 let f = || {
1519                                         _init_and_read_len_prefixed_tlv_fields!(reader, {
1520                                                 (0, payment_id, required),
1521                                                 (2, payment_hash, option),
1522                                                 (4, path, required_vec),
1523                                                 (6, blinded_tail, option),
1524                                         });
1525                                         Ok(Some(Event::PaymentPathSuccessful {
1526                                                 payment_id: payment_id.0.unwrap(),
1527                                                 payment_hash,
1528                                                 path: Path { hops: path, blinded_tail },
1529                                         }))
1530                                 };
1531                                 f()
1532                         },
1533                         15u8 => {
1534                                 let f = || {
1535                                         let mut payment_hash = PaymentHash([0; 32]);
1536                                         let mut payment_id = PaymentId([0; 32]);
1537                                         let mut reason = None;
1538                                         read_tlv_fields!(reader, {
1539                                                 (0, payment_id, required),
1540                                                 (1, reason, upgradable_option),
1541                                                 (2, payment_hash, required),
1542                                         });
1543                                         Ok(Some(Event::PaymentFailed {
1544                                                 payment_id,
1545                                                 payment_hash,
1546                                                 reason,
1547                                         }))
1548                                 };
1549                                 f()
1550                         },
1551                         17u8 => {
1552                                 // Value 17 is used for `Event::OpenChannelRequest`.
1553                                 Ok(None)
1554                         },
1555                         19u8 => {
1556                                 let f = || {
1557                                         let mut payment_hash = PaymentHash([0; 32]);
1558                                         let mut purpose = UpgradableRequired(None);
1559                                         let mut amount_msat = 0;
1560                                         let mut receiver_node_id = None;
1561                                         let mut htlcs: Option<Vec<ClaimedHTLC>> = Some(vec![]);
1562                                         let mut sender_intended_total_msat: Option<u64> = None;
1563                                         read_tlv_fields!(reader, {
1564                                                 (0, payment_hash, required),
1565                                                 (1, receiver_node_id, option),
1566                                                 (2, purpose, upgradable_required),
1567                                                 (4, amount_msat, required),
1568                                                 (5, htlcs, optional_vec),
1569                                                 (7, sender_intended_total_msat, option),
1570                                         });
1571                                         Ok(Some(Event::PaymentClaimed {
1572                                                 receiver_node_id,
1573                                                 payment_hash,
1574                                                 purpose: _init_tlv_based_struct_field!(purpose, upgradable_required),
1575                                                 amount_msat,
1576                                                 htlcs: htlcs.unwrap_or(vec![]),
1577                                                 sender_intended_total_msat,
1578                                         }))
1579                                 };
1580                                 f()
1581                         },
1582                         21u8 => {
1583                                 let f = || {
1584                                         _init_and_read_len_prefixed_tlv_fields!(reader, {
1585                                                 (0, payment_id, required),
1586                                                 (2, payment_hash, required),
1587                                                 (4, path, required_vec),
1588                                                 (6, blinded_tail, option),
1589                                         });
1590                                         Ok(Some(Event::ProbeSuccessful {
1591                                                 payment_id: payment_id.0.unwrap(),
1592                                                 payment_hash: payment_hash.0.unwrap(),
1593                                                 path: Path { hops: path, blinded_tail },
1594                                         }))
1595                                 };
1596                                 f()
1597                         },
1598                         23u8 => {
1599                                 let f = || {
1600                                         _init_and_read_len_prefixed_tlv_fields!(reader, {
1601                                                 (0, payment_id, required),
1602                                                 (2, payment_hash, required),
1603                                                 (4, path, required_vec),
1604                                                 (6, short_channel_id, option),
1605                                                 (8, blinded_tail, option),
1606                                         });
1607                                         Ok(Some(Event::ProbeFailed {
1608                                                 payment_id: payment_id.0.unwrap(),
1609                                                 payment_hash: payment_hash.0.unwrap(),
1610                                                 path: Path { hops: path, blinded_tail },
1611                                                 short_channel_id,
1612                                         }))
1613                                 };
1614                                 f()
1615                         },
1616                         25u8 => {
1617                                 let f = || {
1618                                         let mut prev_channel_id = ChannelId::new_zero();
1619                                         let mut failed_next_destination_opt = UpgradableRequired(None);
1620                                         read_tlv_fields!(reader, {
1621                                                 (0, prev_channel_id, required),
1622                                                 (2, failed_next_destination_opt, upgradable_required),
1623                                         });
1624                                         Ok(Some(Event::HTLCHandlingFailed {
1625                                                 prev_channel_id,
1626                                                 failed_next_destination: _init_tlv_based_struct_field!(failed_next_destination_opt, upgradable_required),
1627                                         }))
1628                                 };
1629                                 f()
1630                         },
1631                         27u8 => Ok(None),
1632                         29u8 => {
1633                                 let f = || {
1634                                         let mut channel_id = ChannelId::new_zero();
1635                                         let mut user_channel_id: u128 = 0;
1636                                         let mut counterparty_node_id = RequiredWrapper(None);
1637                                         let mut channel_type = RequiredWrapper(None);
1638                                         read_tlv_fields!(reader, {
1639                                                 (0, channel_id, required),
1640                                                 (2, user_channel_id, required),
1641                                                 (4, counterparty_node_id, required),
1642                                                 (6, channel_type, required),
1643                                         });
1644
1645                                         Ok(Some(Event::ChannelReady {
1646                                                 channel_id,
1647                                                 user_channel_id,
1648                                                 counterparty_node_id: counterparty_node_id.0.unwrap(),
1649                                                 channel_type: channel_type.0.unwrap()
1650                                         }))
1651                                 };
1652                                 f()
1653                         },
1654                         31u8 => {
1655                                 let f = || {
1656                                         let mut channel_id = ChannelId::new_zero();
1657                                         let mut user_channel_id: u128 = 0;
1658                                         let mut former_temporary_channel_id = None;
1659                                         let mut counterparty_node_id = RequiredWrapper(None);
1660                                         let mut funding_txo = RequiredWrapper(None);
1661                                         let mut channel_type = None;
1662                                         read_tlv_fields!(reader, {
1663                                                 (0, channel_id, required),
1664                                                 (1, channel_type, option),
1665                                                 (2, user_channel_id, required),
1666                                                 (4, former_temporary_channel_id, required),
1667                                                 (6, counterparty_node_id, required),
1668                                                 (8, funding_txo, required),
1669                                         });
1670
1671                                         Ok(Some(Event::ChannelPending {
1672                                                 channel_id,
1673                                                 user_channel_id,
1674                                                 former_temporary_channel_id,
1675                                                 counterparty_node_id: counterparty_node_id.0.unwrap(),
1676                                                 funding_txo: funding_txo.0.unwrap(),
1677                                                 channel_type,
1678                                         }))
1679                                 };
1680                                 f()
1681                         },
1682                         33u8 => {
1683                                 let f = || {
1684                                         _init_and_read_len_prefixed_tlv_fields!(reader, {
1685                                                 (0, payment_id, required),
1686                                         });
1687                                         Ok(Some(Event::InvoiceRequestFailed {
1688                                                 payment_id: payment_id.0.unwrap(),
1689                                         }))
1690                                 };
1691                                 f()
1692                         },
1693                         // Note that we do not write a length-prefixed TLV for ConnectionNeeded events.
1694                         35u8 => Ok(None),
1695                         // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
1696                         // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
1697                         // reads.
1698                         x if x % 2 == 1 => {
1699                                 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
1700                                 // which prefixes the whole thing with a length BigSize. Because the event is
1701                                 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
1702                                 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
1703                                 // exactly the number of bytes specified, ignoring them entirely.
1704                                 let tlv_len: BigSize = Readable::read(reader)?;
1705                                 FixedLengthReader::new(reader, tlv_len.0)
1706                                         .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
1707                                 Ok(None)
1708                         },
1709                         _ => Err(msgs::DecodeError::InvalidValue)
1710                 }
1711         }
1712 }
1713
1714 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
1715 /// broadcast to most peers).
1716 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
1717 #[derive(Clone, Debug)]
1718 #[cfg_attr(test, derive(PartialEq))]
1719 pub enum MessageSendEvent {
1720         /// Used to indicate that we've accepted a channel open and should send the accept_channel
1721         /// message provided to the given peer.
1722         SendAcceptChannel {
1723                 /// The node_id of the node which should receive this message
1724                 node_id: PublicKey,
1725                 /// The message which should be sent.
1726                 msg: msgs::AcceptChannel,
1727         },
1728         /// Used to indicate that we've accepted a V2 channel open and should send the accept_channel2
1729         /// message provided to the given peer.
1730         SendAcceptChannelV2 {
1731                 /// The node_id of the node which should receive this message
1732                 node_id: PublicKey,
1733                 /// The message which should be sent.
1734                 msg: msgs::AcceptChannelV2,
1735         },
1736         /// Used to indicate that we've initiated a channel open and should send the open_channel
1737         /// message provided to the given peer.
1738         SendOpenChannel {
1739                 /// The node_id of the node which should receive this message
1740                 node_id: PublicKey,
1741                 /// The message which should be sent.
1742                 msg: msgs::OpenChannel,
1743         },
1744         /// Used to indicate that we've initiated a V2 channel open and should send the open_channel2
1745         /// message provided to the given peer.
1746         SendOpenChannelV2 {
1747                 /// The node_id of the node which should receive this message
1748                 node_id: PublicKey,
1749                 /// The message which should be sent.
1750                 msg: msgs::OpenChannelV2,
1751         },
1752         /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
1753         SendFundingCreated {
1754                 /// The node_id of the node which should receive this message
1755                 node_id: PublicKey,
1756                 /// The message which should be sent.
1757                 msg: msgs::FundingCreated,
1758         },
1759         /// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
1760         SendFundingSigned {
1761                 /// The node_id of the node which should receive this message
1762                 node_id: PublicKey,
1763                 /// The message which should be sent.
1764                 msg: msgs::FundingSigned,
1765         },
1766         /// Used to indicate that a stfu message should be sent to the peer with the given node id.
1767         SendStfu {
1768                 /// The node_id of the node which should receive this message
1769                 node_id: PublicKey,
1770                 /// The message which should be sent.
1771                 msg: msgs::Stfu,
1772         },
1773         /// Used to indicate that a splice message should be sent to the peer with the given node id.
1774         SendSplice {
1775                 /// The node_id of the node which should receive this message
1776                 node_id: PublicKey,
1777                 /// The message which should be sent.
1778                 msg: msgs::Splice,
1779         },
1780         /// Used to indicate that a splice_ack message should be sent to the peer with the given node id.
1781         SendSpliceAck {
1782                 /// The node_id of the node which should receive this message
1783                 node_id: PublicKey,
1784                 /// The message which should be sent.
1785                 msg: msgs::SpliceAck,
1786         },
1787         /// Used to indicate that a splice_locked message should be sent to the peer with the given node id.
1788         SendSpliceLocked {
1789                 /// The node_id of the node which should receive this message
1790                 node_id: PublicKey,
1791                 /// The message which should be sent.
1792                 msg: msgs::SpliceLocked,
1793         },
1794         /// Used to indicate that a tx_add_input message should be sent to the peer with the given node_id.
1795         SendTxAddInput {
1796                 /// The node_id of the node which should receive this message
1797                 node_id: PublicKey,
1798                 /// The message which should be sent.
1799                 msg: msgs::TxAddInput,
1800         },
1801         /// Used to indicate that a tx_add_output message should be sent to the peer with the given node_id.
1802         SendTxAddOutput {
1803                 /// The node_id of the node which should receive this message
1804                 node_id: PublicKey,
1805                 /// The message which should be sent.
1806                 msg: msgs::TxAddOutput,
1807         },
1808         /// Used to indicate that a tx_remove_input message should be sent to the peer with the given node_id.
1809         SendTxRemoveInput {
1810                 /// The node_id of the node which should receive this message
1811                 node_id: PublicKey,
1812                 /// The message which should be sent.
1813                 msg: msgs::TxRemoveInput,
1814         },
1815         /// Used to indicate that a tx_remove_output message should be sent to the peer with the given node_id.
1816         SendTxRemoveOutput {
1817                 /// The node_id of the node which should receive this message
1818                 node_id: PublicKey,
1819                 /// The message which should be sent.
1820                 msg: msgs::TxRemoveOutput,
1821         },
1822         /// Used to indicate that a tx_complete message should be sent to the peer with the given node_id.
1823         SendTxComplete {
1824                 /// The node_id of the node which should receive this message
1825                 node_id: PublicKey,
1826                 /// The message which should be sent.
1827                 msg: msgs::TxComplete,
1828         },
1829         /// Used to indicate that a tx_signatures message should be sent to the peer with the given node_id.
1830         SendTxSignatures {
1831                 /// The node_id of the node which should receive this message
1832                 node_id: PublicKey,
1833                 /// The message which should be sent.
1834                 msg: msgs::TxSignatures,
1835         },
1836         /// Used to indicate that a tx_init_rbf message should be sent to the peer with the given node_id.
1837         SendTxInitRbf {
1838                 /// The node_id of the node which should receive this message
1839                 node_id: PublicKey,
1840                 /// The message which should be sent.
1841                 msg: msgs::TxInitRbf,
1842         },
1843         /// Used to indicate that a tx_ack_rbf message should be sent to the peer with the given node_id.
1844         SendTxAckRbf {
1845                 /// The node_id of the node which should receive this message
1846                 node_id: PublicKey,
1847                 /// The message which should be sent.
1848                 msg: msgs::TxAckRbf,
1849         },
1850         /// Used to indicate that a tx_abort message should be sent to the peer with the given node_id.
1851         SendTxAbort {
1852                 /// The node_id of the node which should receive this message
1853                 node_id: PublicKey,
1854                 /// The message which should be sent.
1855                 msg: msgs::TxAbort,
1856         },
1857         /// Used to indicate that a channel_ready message should be sent to the peer with the given node_id.
1858         SendChannelReady {
1859                 /// The node_id of the node which should receive these message(s)
1860                 node_id: PublicKey,
1861                 /// The channel_ready message which should be sent.
1862                 msg: msgs::ChannelReady,
1863         },
1864         /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
1865         SendAnnouncementSignatures {
1866                 /// The node_id of the node which should receive these message(s)
1867                 node_id: PublicKey,
1868                 /// The announcement_signatures message which should be sent.
1869                 msg: msgs::AnnouncementSignatures,
1870         },
1871         /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
1872         /// message should be sent to the peer with the given node_id.
1873         UpdateHTLCs {
1874                 /// The node_id of the node which should receive these message(s)
1875                 node_id: PublicKey,
1876                 /// The update messages which should be sent. ALL messages in the struct should be sent!
1877                 updates: msgs::CommitmentUpdate,
1878         },
1879         /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
1880         SendRevokeAndACK {
1881                 /// The node_id of the node which should receive this message
1882                 node_id: PublicKey,
1883                 /// The message which should be sent.
1884                 msg: msgs::RevokeAndACK,
1885         },
1886         /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
1887         SendClosingSigned {
1888                 /// The node_id of the node which should receive this message
1889                 node_id: PublicKey,
1890                 /// The message which should be sent.
1891                 msg: msgs::ClosingSigned,
1892         },
1893         /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
1894         SendShutdown {
1895                 /// The node_id of the node which should receive this message
1896                 node_id: PublicKey,
1897                 /// The message which should be sent.
1898                 msg: msgs::Shutdown,
1899         },
1900         /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
1901         SendChannelReestablish {
1902                 /// The node_id of the node which should receive this message
1903                 node_id: PublicKey,
1904                 /// The message which should be sent.
1905                 msg: msgs::ChannelReestablish,
1906         },
1907         /// Used to send a channel_announcement and channel_update to a specific peer, likely on
1908         /// initial connection to ensure our peers know about our channels.
1909         SendChannelAnnouncement {
1910                 /// The node_id of the node which should receive this message
1911                 node_id: PublicKey,
1912                 /// The channel_announcement which should be sent.
1913                 msg: msgs::ChannelAnnouncement,
1914                 /// The followup channel_update which should be sent.
1915                 update_msg: msgs::ChannelUpdate,
1916         },
1917         /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
1918         /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
1919         ///
1920         /// Note that after doing so, you very likely (unless you did so very recently) want to
1921         /// broadcast a node_announcement (e.g. via [`PeerManager::broadcast_node_announcement`]). This
1922         /// ensures that any nodes which see our channel_announcement also have a relevant
1923         /// node_announcement, including relevant feature flags which may be important for routing
1924         /// through or to us.
1925         ///
1926         /// [`PeerManager::broadcast_node_announcement`]: crate::ln::peer_handler::PeerManager::broadcast_node_announcement
1927         BroadcastChannelAnnouncement {
1928                 /// The channel_announcement which should be sent.
1929                 msg: msgs::ChannelAnnouncement,
1930                 /// The followup channel_update which should be sent.
1931                 update_msg: Option<msgs::ChannelUpdate>,
1932         },
1933         /// Used to indicate that a channel_update should be broadcast to all peers.
1934         BroadcastChannelUpdate {
1935                 /// The channel_update which should be sent.
1936                 msg: msgs::ChannelUpdate,
1937         },
1938         /// Used to indicate that a node_announcement should be broadcast to all peers.
1939         BroadcastNodeAnnouncement {
1940                 /// The node_announcement which should be sent.
1941                 msg: msgs::NodeAnnouncement,
1942         },
1943         /// Used to indicate that a channel_update should be sent to a single peer.
1944         /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
1945         /// private channel and we shouldn't be informing all of our peers of channel parameters.
1946         SendChannelUpdate {
1947                 /// The node_id of the node which should receive this message
1948                 node_id: PublicKey,
1949                 /// The channel_update which should be sent.
1950                 msg: msgs::ChannelUpdate,
1951         },
1952         /// Broadcast an error downstream to be handled
1953         HandleError {
1954                 /// The node_id of the node which should receive this message
1955                 node_id: PublicKey,
1956                 /// The action which should be taken.
1957                 action: msgs::ErrorAction
1958         },
1959         /// Query a peer for channels with funding transaction UTXOs in a block range.
1960         SendChannelRangeQuery {
1961                 /// The node_id of this message recipient
1962                 node_id: PublicKey,
1963                 /// The query_channel_range which should be sent.
1964                 msg: msgs::QueryChannelRange,
1965         },
1966         /// Request routing gossip messages from a peer for a list of channels identified by
1967         /// their short_channel_ids.
1968         SendShortIdsQuery {
1969                 /// The node_id of this message recipient
1970                 node_id: PublicKey,
1971                 /// The query_short_channel_ids which should be sent.
1972                 msg: msgs::QueryShortChannelIds,
1973         },
1974         /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
1975         /// emitted during processing of the query.
1976         SendReplyChannelRange {
1977                 /// The node_id of this message recipient
1978                 node_id: PublicKey,
1979                 /// The reply_channel_range which should be sent.
1980                 msg: msgs::ReplyChannelRange,
1981         },
1982         /// Sends a timestamp filter for inbound gossip. This should be sent on each new connection to
1983         /// enable receiving gossip messages from the peer.
1984         SendGossipTimestampFilter {
1985                 /// The node_id of this message recipient
1986                 node_id: PublicKey,
1987                 /// The gossip_timestamp_filter which should be sent.
1988                 msg: msgs::GossipTimestampFilter,
1989         },
1990 }
1991
1992 /// A trait indicating an object may generate message send events
1993 pub trait MessageSendEventsProvider {
1994         /// Gets the list of pending events which were generated by previous actions, clearing the list
1995         /// in the process.
1996         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
1997 }
1998
1999 /// A trait indicating an object may generate events.
2000 ///
2001 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
2002 ///
2003 /// Implementations of this trait may also feature an async version of event handling, as shown with
2004 /// [`ChannelManager::process_pending_events_async`] and
2005 /// [`ChainMonitor::process_pending_events_async`].
2006 ///
2007 /// # Requirements
2008 ///
2009 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
2010 /// event since the last invocation.
2011 ///
2012 /// In order to ensure no [`Event`]s are lost, implementors of this trait will persist [`Event`]s
2013 /// and replay any unhandled events on startup. An [`Event`] is considered handled when
2014 /// [`process_pending_events`] returns, thus handlers MUST fully handle [`Event`]s and persist any
2015 /// relevant changes to disk *before* returning.
2016 ///
2017 /// Further, because an application may crash between an [`Event`] being handled and the
2018 /// implementor of this trait being re-serialized, [`Event`] handling must be idempotent - in
2019 /// effect, [`Event`]s may be replayed.
2020 ///
2021 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
2022 /// consult the provider's documentation on the implication of processing events and how a handler
2023 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
2024 /// [`ChainMonitor::process_pending_events`]).
2025 ///
2026 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
2027 /// own type(s).
2028 ///
2029 /// [`process_pending_events`]: Self::process_pending_events
2030 /// [`handle_event`]: EventHandler::handle_event
2031 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
2032 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
2033 /// [`ChannelManager::process_pending_events_async`]: crate::ln::channelmanager::ChannelManager::process_pending_events_async
2034 /// [`ChainMonitor::process_pending_events_async`]: crate::chain::chainmonitor::ChainMonitor::process_pending_events_async
2035 pub trait EventsProvider {
2036         /// Processes any events generated since the last call using the given event handler.
2037         ///
2038         /// See the trait-level documentation for requirements.
2039         fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
2040 }
2041
2042 /// A trait implemented for objects handling events from [`EventsProvider`].
2043 ///
2044 /// An async variation also exists for implementations of [`EventsProvider`] that support async
2045 /// event handling. The async event handler should satisfy the generic bounds: `F:
2046 /// core::future::Future, H: Fn(Event) -> F`.
2047 pub trait EventHandler {
2048         /// Handles the given [`Event`].
2049         ///
2050         /// See [`EventsProvider`] for details that must be considered when implementing this method.
2051         fn handle_event(&self, event: Event);
2052 }
2053
2054 impl<F> EventHandler for F where F: Fn(Event) {
2055         fn handle_event(&self, event: Event) {
2056                 self(event)
2057         }
2058 }
2059
2060 impl<T: EventHandler> EventHandler for Arc<T> {
2061         fn handle_event(&self, event: Event) {
2062                 self.deref().handle_event(event)
2063         }
2064 }