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