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