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