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