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