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