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