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