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