Merge pull request #1165 from lightning-signer/2021-11-fix-anchors
[rust-lightning] / lightning / src / util / events.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 use chain::keysinterface::SpendableOutputDescriptor;
18 use ln::channelmanager::PaymentId;
19 use ln::msgs;
20 use ln::msgs::DecodeError;
21 use ln::{PaymentPreimage, PaymentHash, PaymentSecret};
22 use routing::network_graph::NetworkUpdate;
23 use util::ser::{BigSize, FixedLengthReader, Writeable, Writer, MaybeReadable, Readable, VecReadWrapper, VecWriteWrapper};
24 use routing::router::{RouteHop, RouteParameters};
25
26 use bitcoin::Transaction;
27 use bitcoin::blockdata::script::Script;
28 use bitcoin::hashes::Hash;
29 use bitcoin::hashes::sha256::Hash as Sha256;
30 use bitcoin::secp256k1::key::PublicKey;
31
32 use io;
33 use prelude::*;
34 use core::time::Duration;
35 use core::ops::Deref;
36 use sync::Arc;
37
38 /// Some information provided on receipt of payment depends on whether the payment received is a
39 /// spontaneous payment or a "conventional" lightning payment that's paying an invoice.
40 #[derive(Clone, Debug)]
41 pub enum PaymentPurpose {
42         /// Information for receiving a payment that we generated an invoice for.
43         InvoicePayment {
44                 /// The preimage to the payment_hash, if the payment hash (and secret) were fetched via
45                 /// [`ChannelManager::create_inbound_payment`]. If provided, this can be handed directly to
46                 /// [`ChannelManager::claim_funds`].
47                 ///
48                 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
49                 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
50                 payment_preimage: Option<PaymentPreimage>,
51                 /// The "payment secret". This authenticates the sender to the recipient, preventing a
52                 /// number of deanonymization attacks during the routing process.
53                 /// It is provided here for your reference, however its accuracy is enforced directly by
54                 /// [`ChannelManager`] using the values you previously provided to
55                 /// [`ChannelManager::create_inbound_payment`] or
56                 /// [`ChannelManager::create_inbound_payment_for_hash`].
57                 ///
58                 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
59                 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
60                 /// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
61                 payment_secret: PaymentSecret,
62                 /// This is the `user_payment_id` which was provided to
63                 /// [`ChannelManager::create_inbound_payment_for_hash`] or
64                 /// [`ChannelManager::create_inbound_payment`]. It has no meaning inside of LDK and is
65                 /// simply copied here. It may be used to correlate PaymentReceived events with invoice
66                 /// metadata stored elsewhere.
67                 ///
68                 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
69                 /// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
70                 user_payment_id: u64,
71         },
72         /// Because this is a spontaneous payment, the payer generated their own preimage rather than us
73         /// (the payee) providing a preimage.
74         SpontaneousPayment(PaymentPreimage),
75 }
76
77 #[derive(Clone, Debug, PartialEq)]
78 /// The reason the channel was closed. See individual variants more details.
79 pub enum ClosureReason {
80         /// Closure generated from receiving a peer error message.
81         ///
82         /// Our counterparty may have broadcasted their latest commitment state, and we have
83         /// as well.
84         CounterpartyForceClosed {
85                 /// The error which the peer sent us.
86                 ///
87                 /// The string should be sanitized before it is used (e.g emitted to logs
88                 /// or printed to stdout). Otherwise, a well crafted error message may exploit
89                 /// a security vulnerability in the terminal emulator or the logging subsystem.
90                 peer_msg: String,
91         },
92         /// Closure generated from [`ChannelManager::force_close_channel`], called by the user.
93         ///
94         /// [`ChannelManager::force_close_channel`]: crate::ln::channelmanager::ChannelManager::force_close_channel.
95         HolderForceClosed,
96         /// The channel was closed after negotiating a cooperative close and we've now broadcasted
97         /// the cooperative close transaction. Note the shutdown may have been initiated by us.
98         //TODO: split between CounterpartyInitiated/LocallyInitiated
99         CooperativeClosure,
100         /// A commitment transaction was confirmed on chain, closing the channel. Most likely this
101         /// commitment transaction came from our counterparty, but it may also have come from
102         /// a copy of our own `ChannelMonitor`.
103         CommitmentTxConfirmed,
104         /// Closure generated from processing an event, likely a HTLC forward/relay/reception.
105         ProcessingError {
106                 /// A developer-readable error message which we generated.
107                 err: String,
108         },
109         /// The `PeerManager` informed us that we've disconnected from the peer. We close channels
110         /// if the `PeerManager` informed us that it is unlikely we'll be able to connect to the
111         /// peer again in the future or if the peer disconnected before we finished negotiating
112         /// the channel open. The first case may be caused by incompatible features which our
113         /// counterparty, or we, require.
114         //TODO: split between PeerUnconnectable/PeerDisconnected ?
115         DisconnectedPeer,
116         /// Closure generated from `ChannelManager::read` if the ChannelMonitor is newer than
117         /// the ChannelManager deserialized.
118         OutdatedChannelManager
119 }
120
121 impl_writeable_tlv_based_enum_upgradable!(ClosureReason,
122         (0, CounterpartyForceClosed) => { (1, peer_msg, required) },
123         (2, HolderForceClosed) => {},
124         (6, CommitmentTxConfirmed) => {},
125         (4, CooperativeClosure) => {},
126         (8, ProcessingError) => { (1, err, required) },
127         (10, DisconnectedPeer) => {},
128         (12, OutdatedChannelManager) => {},
129 );
130
131 /// An Event which you should probably take some action in response to.
132 ///
133 /// Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
134 /// them directly as they don't round-trip exactly (for example FundingGenerationReady is never
135 /// written as it makes no sense to respond to it after reconnecting to peers).
136 #[derive(Clone, Debug)]
137 pub enum Event {
138         /// Used to indicate that the client should generate a funding transaction with the given
139         /// parameters and then call ChannelManager::funding_transaction_generated.
140         /// Generated in ChannelManager message handling.
141         /// Note that *all inputs* in the funding transaction must spend SegWit outputs or your
142         /// counterparty can steal your funds!
143         FundingGenerationReady {
144                 /// The random channel_id we picked which you'll need to pass into
145                 /// ChannelManager::funding_transaction_generated.
146                 temporary_channel_id: [u8; 32],
147                 /// The value, in satoshis, that the output should have.
148                 channel_value_satoshis: u64,
149                 /// The script which should be used in the transaction output.
150                 output_script: Script,
151                 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`], or 0 for
152                 /// an inbound channel.
153                 ///
154                 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
155                 user_channel_id: u64,
156         },
157         /// Indicates we've received money! Just gotta dig out that payment preimage and feed it to
158         /// [`ChannelManager::claim_funds`] to get it....
159         /// Note that if the preimage is not known, you should call
160         /// [`ChannelManager::fail_htlc_backwards`] to free up resources for this HTLC and avoid
161         /// network congestion.
162         /// If you fail to call either [`ChannelManager::claim_funds`] or
163         /// [`ChannelManager::fail_htlc_backwards`] within the HTLC's timeout, the HTLC will be
164         /// automatically failed.
165         ///
166         /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
167         /// [`ChannelManager::fail_htlc_backwards`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards
168         PaymentReceived {
169                 /// The hash for which the preimage should be handed to the ChannelManager.
170                 payment_hash: PaymentHash,
171                 /// The value, in thousandths of a satoshi, that this payment is for.
172                 amt: u64,
173                 /// Information for claiming this received payment, based on whether the purpose of the
174                 /// payment is to pay an invoice or to send a spontaneous payment.
175                 purpose: PaymentPurpose,
176         },
177         /// Indicates an outbound payment we made succeeded (i.e. it made it all the way to its target
178         /// and we got back the payment preimage for it).
179         ///
180         /// Note for MPP payments: in rare cases, this event may be preceded by a `PaymentPathFailed`
181         /// event. In this situation, you SHOULD treat this payment as having succeeded.
182         PaymentSent {
183                 /// The id returned by [`ChannelManager::send_payment`] and used with
184                 /// [`ChannelManager::retry_payment`].
185                 ///
186                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
187                 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
188                 payment_id: Option<PaymentId>,
189                 /// The preimage to the hash given to ChannelManager::send_payment.
190                 /// Note that this serves as a payment receipt, if you wish to have such a thing, you must
191                 /// store it somehow!
192                 payment_preimage: PaymentPreimage,
193                 /// The hash which was given to [`ChannelManager::send_payment`].
194                 ///
195                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
196                 payment_hash: PaymentHash,
197                 /// The total fee which was spent at intermediate hops in this payment, across all paths.
198                 ///
199                 /// Note that, like [`Route::get_total_fees`] this does *not* include any potential
200                 /// overpayment to the recipient node.
201                 ///
202                 /// If the recipient or an intermediate node misbehaves and gives us free money, this may
203                 /// overstate the amount paid, though this is unlikely.
204                 ///
205                 /// [`Route::get_total_fees`]: crate::routing::router::Route::get_total_fees
206                 fee_paid_msat: Option<u64>,
207         },
208         /// Indicates an outbound payment we made failed. Probably some intermediary node dropped
209         /// something. You may wish to retry with a different route.
210         PaymentPathFailed {
211                 /// The id returned by [`ChannelManager::send_payment`] and used with
212                 /// [`ChannelManager::retry_payment`].
213                 ///
214                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
215                 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
216                 payment_id: Option<PaymentId>,
217                 /// The hash which was given to ChannelManager::send_payment.
218                 payment_hash: PaymentHash,
219                 /// Indicates the payment was rejected for some reason by the recipient. This implies that
220                 /// the payment has failed, not just the route in question. If this is not set, you may
221                 /// retry the payment via a different route.
222                 rejected_by_dest: bool,
223                 /// Any failure information conveyed via the Onion return packet by a node along the failed
224                 /// payment route.
225                 ///
226                 /// Should be applied to the [`NetworkGraph`] so that routing decisions can take into
227                 /// account the update. [`NetGraphMsgHandler`] is capable of doing this.
228                 ///
229                 /// [`NetworkGraph`]: crate::routing::network_graph::NetworkGraph
230                 /// [`NetGraphMsgHandler`]: crate::routing::network_graph::NetGraphMsgHandler
231                 network_update: Option<NetworkUpdate>,
232                 /// For both single-path and multi-path payments, this is set if all paths of the payment have
233                 /// failed. This will be set to false if (1) this is an MPP payment and (2) other parts of the
234                 /// larger MPP payment were still in flight when this event was generated.
235                 all_paths_failed: bool,
236                 /// The payment path that failed.
237                 path: Vec<RouteHop>,
238                 /// The channel responsible for the failed payment path.
239                 ///
240                 /// If this is `Some`, then the corresponding channel should be avoided when the payment is
241                 /// retried. May be `None` for older [`Event`] serializations.
242                 short_channel_id: Option<u64>,
243                 /// Parameters needed to compute a new [`Route`] when retrying the failed payment path.
244                 ///
245                 /// See [`find_route`] for details.
246                 ///
247                 /// [`Route`]: crate::routing::router::Route
248                 /// [`find_route`]: crate::routing::router::find_route
249                 retry: Option<RouteParameters>,
250 #[cfg(test)]
251                 error_code: Option<u16>,
252 #[cfg(test)]
253                 error_data: Option<Vec<u8>>,
254         },
255         /// Used to indicate that ChannelManager::process_pending_htlc_forwards should be called at a
256         /// time in the future.
257         PendingHTLCsForwardable {
258                 /// The minimum amount of time that should be waited prior to calling
259                 /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
260                 /// you should wait a random amount of time in roughly the range (now + time_forwardable,
261                 /// now + 5*time_forwardable).
262                 time_forwardable: Duration,
263         },
264         /// Used to indicate that an output which you should know how to spend was confirmed on chain
265         /// and is now spendable.
266         /// Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
267         /// counterparty spending them due to some kind of timeout. Thus, you need to store them
268         /// somewhere and spend them when you create on-chain transactions.
269         SpendableOutputs {
270                 /// The outputs which you should store as spendable by you.
271                 outputs: Vec<SpendableOutputDescriptor>,
272         },
273         /// This event is generated when a payment has been successfully forwarded through us and a
274         /// forwarding fee earned.
275         PaymentForwarded {
276                 /// The fee, in milli-satoshis, which was earned as a result of the payment.
277                 ///
278                 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
279                 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
280                 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
281                 /// claimed the full value in millisatoshis from the source. In this case,
282                 /// `claim_from_onchain_tx` will be set.
283                 ///
284                 /// If the channel which sent us the payment has been force-closed, we will claim the funds
285                 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
286                 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
287                 /// `PaymentForwarded` events are generated for the same payment iff `fee_earned_msat` is
288                 /// `None`.
289                 fee_earned_msat: Option<u64>,
290                 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
291                 /// transaction.
292                 claim_from_onchain_tx: bool,
293         },
294         /// Used to indicate that a channel with the given `channel_id` is in the process of closure.
295         ChannelClosed  {
296                 /// The channel_id of the channel which has been closed. Note that on-chain transactions
297                 /// resolving the channel are likely still awaiting confirmation.
298                 channel_id: [u8; 32],
299                 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`], or 0 for
300                 /// an inbound channel. This will always be zero for objects serialized with LDK versions
301                 /// prior to 0.0.102.
302                 ///
303                 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
304                 user_channel_id: u64,
305                 /// The reason the channel was closed.
306                 reason: ClosureReason
307         },
308         /// Used to indicate to the user that they can abandon the funding transaction and recycle the
309         /// inputs for another purpose.
310         DiscardFunding {
311                 /// The channel_id of the channel which has been closed.
312                 channel_id: [u8; 32],
313                 /// The full transaction received from the user
314                 transaction: Transaction
315         }
316 }
317
318 impl Writeable for Event {
319         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
320                 match self {
321                         &Event::FundingGenerationReady { .. } => {
322                                 0u8.write(writer)?;
323                                 // We never write out FundingGenerationReady events as, upon disconnection, peers
324                                 // drop any channels which have not yet exchanged funding_signed.
325                         },
326                         &Event::PaymentReceived { ref payment_hash, ref amt, ref purpose } => {
327                                 1u8.write(writer)?;
328                                 let mut payment_secret = None;
329                                 let mut user_payment_id = None;
330                                 let payment_preimage;
331                                 match &purpose {
332                                         PaymentPurpose::InvoicePayment { payment_preimage: preimage, payment_secret: secret, user_payment_id: id } => {
333                                                 payment_secret = Some(secret);
334                                                 payment_preimage = *preimage;
335                                                 user_payment_id = Some(id);
336                                         },
337                                         PaymentPurpose::SpontaneousPayment(preimage) => {
338                                                 payment_preimage = Some(*preimage);
339                                         }
340                                 }
341                                 write_tlv_fields!(writer, {
342                                         (0, payment_hash, required),
343                                         (2, payment_secret, option),
344                                         (4, amt, required),
345                                         (6, user_payment_id, option),
346                                         (8, payment_preimage, option),
347                                 });
348                         },
349                         &Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
350                                 2u8.write(writer)?;
351                                 write_tlv_fields!(writer, {
352                                         (0, payment_preimage, required),
353                                         (1, payment_hash, required),
354                                         (3, payment_id, option),
355                                         (5, fee_paid_msat, option),
356                                 });
357                         },
358                         &Event::PaymentPathFailed {
359                                 ref payment_id, ref payment_hash, ref rejected_by_dest, ref network_update,
360                                 ref all_paths_failed, ref path, ref short_channel_id, ref retry,
361                                 #[cfg(test)]
362                                 ref error_code,
363                                 #[cfg(test)]
364                                 ref error_data,
365                         } => {
366                                 3u8.write(writer)?;
367                                 #[cfg(test)]
368                                 error_code.write(writer)?;
369                                 #[cfg(test)]
370                                 error_data.write(writer)?;
371                                 write_tlv_fields!(writer, {
372                                         (0, payment_hash, required),
373                                         (1, network_update, option),
374                                         (2, rejected_by_dest, required),
375                                         (3, all_paths_failed, required),
376                                         (5, path, vec_type),
377                                         (7, short_channel_id, option),
378                                         (9, retry, option),
379                                         (11, payment_id, option),
380                                 });
381                         },
382                         &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
383                                 4u8.write(writer)?;
384                                 // Note that we now ignore these on the read end as we'll re-generate them in
385                                 // ChannelManager, we write them here only for backwards compatibility.
386                         },
387                         &Event::SpendableOutputs { ref outputs } => {
388                                 5u8.write(writer)?;
389                                 write_tlv_fields!(writer, {
390                                         (0, VecWriteWrapper(outputs), required),
391                                 });
392                         },
393                         &Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx } => {
394                                 7u8.write(writer)?;
395                                 write_tlv_fields!(writer, {
396                                         (0, fee_earned_msat, option),
397                                         (2, claim_from_onchain_tx, required),
398                                 });
399                         },
400                         &Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason } => {
401                                 9u8.write(writer)?;
402                                 write_tlv_fields!(writer, {
403                                         (0, channel_id, required),
404                                         (1, user_channel_id, required),
405                                         (2, reason, required)
406                                 });
407                         },
408                         &Event::DiscardFunding { ref channel_id, ref transaction } => {
409                                 11u8.write(writer)?;
410                                 write_tlv_fields!(writer, {
411                                         (0, channel_id, required),
412                                         (2, transaction, required)
413                                 })
414                         },
415                         // Note that, going forward, all new events must only write data inside of
416                         // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
417                         // data via `write_tlv_fields`.
418                 }
419                 Ok(())
420         }
421 }
422 impl MaybeReadable for Event {
423         fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
424                 match Readable::read(reader)? {
425                         // Note that we do not write a length-prefixed TLV for FundingGenerationReady events,
426                         // unlike all other events, thus we return immediately here.
427                         0u8 => Ok(None),
428                         1u8 => {
429                                 let f = || {
430                                         let mut payment_hash = PaymentHash([0; 32]);
431                                         let mut payment_preimage = None;
432                                         let mut payment_secret = None;
433                                         let mut amt = 0;
434                                         let mut user_payment_id = None;
435                                         read_tlv_fields!(reader, {
436                                                 (0, payment_hash, required),
437                                                 (2, payment_secret, option),
438                                                 (4, amt, required),
439                                                 (6, user_payment_id, option),
440                                                 (8, payment_preimage, option),
441                                         });
442                                         let purpose = match payment_secret {
443                                                 Some(secret) => PaymentPurpose::InvoicePayment {
444                                                         payment_preimage,
445                                                         payment_secret: secret,
446                                                         user_payment_id: if let Some(id) = user_payment_id {
447                                                                 id
448                                                         } else { return Err(msgs::DecodeError::InvalidValue) }
449                                                 },
450                                                 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
451                                                 None => return Err(msgs::DecodeError::InvalidValue),
452                                         };
453                                         Ok(Some(Event::PaymentReceived {
454                                                 payment_hash,
455                                                 amt,
456                                                 purpose,
457                                         }))
458                                 };
459                                 f()
460                         },
461                         2u8 => {
462                                 let f = || {
463                                         let mut payment_preimage = PaymentPreimage([0; 32]);
464                                         let mut payment_hash = None;
465                                         let mut payment_id = None;
466                                         let mut fee_paid_msat = None;
467                                         read_tlv_fields!(reader, {
468                                                 (0, payment_preimage, required),
469                                                 (1, payment_hash, option),
470                                                 (3, payment_id, option),
471                                                 (5, fee_paid_msat, option),
472                                         });
473                                         if payment_hash.is_none() {
474                                                 payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()));
475                                         }
476                                         Ok(Some(Event::PaymentSent {
477                                                 payment_id,
478                                                 payment_preimage,
479                                                 payment_hash: payment_hash.unwrap(),
480                                                 fee_paid_msat,
481                                         }))
482                                 };
483                                 f()
484                         },
485                         3u8 => {
486                                 let f = || {
487                                         #[cfg(test)]
488                                         let error_code = Readable::read(reader)?;
489                                         #[cfg(test)]
490                                         let error_data = Readable::read(reader)?;
491                                         let mut payment_hash = PaymentHash([0; 32]);
492                                         let mut rejected_by_dest = false;
493                                         let mut network_update = None;
494                                         let mut all_paths_failed = Some(true);
495                                         let mut path: Option<Vec<RouteHop>> = Some(vec![]);
496                                         let mut short_channel_id = None;
497                                         let mut retry = None;
498                                         let mut payment_id = None;
499                                         read_tlv_fields!(reader, {
500                                                 (0, payment_hash, required),
501                                                 (1, network_update, ignorable),
502                                                 (2, rejected_by_dest, required),
503                                                 (3, all_paths_failed, option),
504                                                 (5, path, vec_type),
505                                                 (7, short_channel_id, option),
506                                                 (9, retry, option),
507                                                 (11, payment_id, option),
508                                         });
509                                         Ok(Some(Event::PaymentPathFailed {
510                                                 payment_id,
511                                                 payment_hash,
512                                                 rejected_by_dest,
513                                                 network_update,
514                                                 all_paths_failed: all_paths_failed.unwrap(),
515                                                 path: path.unwrap(),
516                                                 short_channel_id,
517                                                 retry,
518                                                 #[cfg(test)]
519                                                 error_code,
520                                                 #[cfg(test)]
521                                                 error_data,
522                                         }))
523                                 };
524                                 f()
525                         },
526                         4u8 => Ok(None),
527                         5u8 => {
528                                 let f = || {
529                                         let mut outputs = VecReadWrapper(Vec::new());
530                                         read_tlv_fields!(reader, {
531                                                 (0, outputs, required),
532                                         });
533                                         Ok(Some(Event::SpendableOutputs { outputs: outputs.0 }))
534                                 };
535                                 f()
536                         },
537                         7u8 => {
538                                 let f = || {
539                                         let mut fee_earned_msat = None;
540                                         let mut claim_from_onchain_tx = false;
541                                         read_tlv_fields!(reader, {
542                                                 (0, fee_earned_msat, option),
543                                                 (2, claim_from_onchain_tx, required),
544                                         });
545                                         Ok(Some(Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx }))
546                                 };
547                                 f()
548                         },
549                         9u8 => {
550                                 let f = || {
551                                         let mut channel_id = [0; 32];
552                                         let mut reason = None;
553                                         let mut user_channel_id_opt = None;
554                                         read_tlv_fields!(reader, {
555                                                 (0, channel_id, required),
556                                                 (1, user_channel_id_opt, option),
557                                                 (2, reason, ignorable),
558                                         });
559                                         if reason.is_none() { return Ok(None); }
560                                         let user_channel_id = if let Some(id) = user_channel_id_opt { id } else { 0 };
561                                         Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: reason.unwrap() }))
562                                 };
563                                 f()
564                         },
565                         11u8 => {
566                                 let f = || {
567                                         let mut channel_id = [0; 32];
568                                         let mut transaction = Transaction{ version: 2, lock_time: 0, input: Vec::new(), output: Vec::new() };
569                                         read_tlv_fields!(reader, {
570                                                 (0, channel_id, required),
571                                                 (2, transaction, required),
572                                         });
573                                         Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
574                                 };
575                                 f()
576                         },
577                         // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
578                         // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
579                         // reads.
580                         x if x % 2 == 1 => {
581                                 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
582                                 // which prefixes the whole thing with a length BigSize. Because the event is
583                                 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
584                                 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
585                                 // exactly the number of bytes specified, ignoring them entirely.
586                                 let tlv_len: BigSize = Readable::read(reader)?;
587                                 FixedLengthReader::new(reader, tlv_len.0)
588                                         .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
589                                 Ok(None)
590                         },
591                         _ => Err(msgs::DecodeError::InvalidValue)
592                 }
593         }
594 }
595
596 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
597 /// broadcast to most peers).
598 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
599 #[derive(Clone, Debug)]
600 pub enum MessageSendEvent {
601         /// Used to indicate that we've accepted a channel open and should send the accept_channel
602         /// message provided to the given peer.
603         SendAcceptChannel {
604                 /// The node_id of the node which should receive this message
605                 node_id: PublicKey,
606                 /// The message which should be sent.
607                 msg: msgs::AcceptChannel,
608         },
609         /// Used to indicate that we've initiated a channel open and should send the open_channel
610         /// message provided to the given peer.
611         SendOpenChannel {
612                 /// The node_id of the node which should receive this message
613                 node_id: PublicKey,
614                 /// The message which should be sent.
615                 msg: msgs::OpenChannel,
616         },
617         /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
618         SendFundingCreated {
619                 /// The node_id of the node which should receive this message
620                 node_id: PublicKey,
621                 /// The message which should be sent.
622                 msg: msgs::FundingCreated,
623         },
624         /// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
625         SendFundingSigned {
626                 /// The node_id of the node which should receive this message
627                 node_id: PublicKey,
628                 /// The message which should be sent.
629                 msg: msgs::FundingSigned,
630         },
631         /// Used to indicate that a funding_locked message should be sent to the peer with the given node_id.
632         SendFundingLocked {
633                 /// The node_id of the node which should receive these message(s)
634                 node_id: PublicKey,
635                 /// The funding_locked message which should be sent.
636                 msg: msgs::FundingLocked,
637         },
638         /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
639         SendAnnouncementSignatures {
640                 /// The node_id of the node which should receive these message(s)
641                 node_id: PublicKey,
642                 /// The announcement_signatures message which should be sent.
643                 msg: msgs::AnnouncementSignatures,
644         },
645         /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
646         /// message should be sent to the peer with the given node_id.
647         UpdateHTLCs {
648                 /// The node_id of the node which should receive these message(s)
649                 node_id: PublicKey,
650                 /// The update messages which should be sent. ALL messages in the struct should be sent!
651                 updates: msgs::CommitmentUpdate,
652         },
653         /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
654         SendRevokeAndACK {
655                 /// The node_id of the node which should receive this message
656                 node_id: PublicKey,
657                 /// The message which should be sent.
658                 msg: msgs::RevokeAndACK,
659         },
660         /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
661         SendClosingSigned {
662                 /// The node_id of the node which should receive this message
663                 node_id: PublicKey,
664                 /// The message which should be sent.
665                 msg: msgs::ClosingSigned,
666         },
667         /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
668         SendShutdown {
669                 /// The node_id of the node which should receive this message
670                 node_id: PublicKey,
671                 /// The message which should be sent.
672                 msg: msgs::Shutdown,
673         },
674         /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
675         SendChannelReestablish {
676                 /// The node_id of the node which should receive this message
677                 node_id: PublicKey,
678                 /// The message which should be sent.
679                 msg: msgs::ChannelReestablish,
680         },
681         /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
682         /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
683         ///
684         /// Note that after doing so, you very likely (unless you did so very recently) want to call
685         /// ChannelManager::broadcast_node_announcement to trigger a BroadcastNodeAnnouncement event.
686         /// This ensures that any nodes which see our channel_announcement also have a relevant
687         /// node_announcement, including relevant feature flags which may be important for routing
688         /// through or to us.
689         BroadcastChannelAnnouncement {
690                 /// The channel_announcement which should be sent.
691                 msg: msgs::ChannelAnnouncement,
692                 /// The followup channel_update which should be sent.
693                 update_msg: msgs::ChannelUpdate,
694         },
695         /// Used to indicate that a node_announcement should be broadcast to all peers.
696         BroadcastNodeAnnouncement {
697                 /// The node_announcement which should be sent.
698                 msg: msgs::NodeAnnouncement,
699         },
700         /// Used to indicate that a channel_update should be broadcast to all peers.
701         BroadcastChannelUpdate {
702                 /// The channel_update which should be sent.
703                 msg: msgs::ChannelUpdate,
704         },
705         /// Used to indicate that a channel_update should be sent to a single peer.
706         /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
707         /// private channel and we shouldn't be informing all of our peers of channel parameters.
708         SendChannelUpdate {
709                 /// The node_id of the node which should receive this message
710                 node_id: PublicKey,
711                 /// The channel_update which should be sent.
712                 msg: msgs::ChannelUpdate,
713         },
714         /// Broadcast an error downstream to be handled
715         HandleError {
716                 /// The node_id of the node which should receive this message
717                 node_id: PublicKey,
718                 /// The action which should be taken.
719                 action: msgs::ErrorAction
720         },
721         /// Query a peer for channels with funding transaction UTXOs in a block range.
722         SendChannelRangeQuery {
723                 /// The node_id of this message recipient
724                 node_id: PublicKey,
725                 /// The query_channel_range which should be sent.
726                 msg: msgs::QueryChannelRange,
727         },
728         /// Request routing gossip messages from a peer for a list of channels identified by
729         /// their short_channel_ids.
730         SendShortIdsQuery {
731                 /// The node_id of this message recipient
732                 node_id: PublicKey,
733                 /// The query_short_channel_ids which should be sent.
734                 msg: msgs::QueryShortChannelIds,
735         },
736         /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
737         /// emitted during processing of the query.
738         SendReplyChannelRange {
739                 /// The node_id of this message recipient
740                 node_id: PublicKey,
741                 /// The reply_channel_range which should be sent.
742                 msg: msgs::ReplyChannelRange,
743         }
744 }
745
746 /// A trait indicating an object may generate message send events
747 pub trait MessageSendEventsProvider {
748         /// Gets the list of pending events which were generated by previous actions, clearing the list
749         /// in the process.
750         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
751 }
752
753 /// A trait indicating an object may generate events.
754 ///
755 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
756 ///
757 /// # Requirements
758 ///
759 /// See [`process_pending_events`] for requirements around event processing.
760 ///
761 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
762 /// event since the last invocation. The handler must either act upon the event immediately
763 /// or preserve it for later handling.
764 ///
765 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
766 /// consult the provider's documentation on the implication of processing events and how a handler
767 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
768 /// [`ChainMonitor::process_pending_events`]).
769 ///
770 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
771 /// own type(s).
772 ///
773 /// [`process_pending_events`]: Self::process_pending_events
774 /// [`handle_event`]: EventHandler::handle_event
775 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
776 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
777 pub trait EventsProvider {
778         /// Processes any events generated since the last call using the given event handler.
779         ///
780         /// Subsequent calls must only process new events. However, handlers must be capable of handling
781         /// duplicate events across process restarts. This may occur if the provider was recovered from
782         /// an old state (i.e., it hadn't been successfully persisted after processing pending events).
783         fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
784 }
785
786 /// A trait implemented for objects handling events from [`EventsProvider`].
787 pub trait EventHandler {
788         /// Handles the given [`Event`].
789         ///
790         /// See [`EventsProvider`] for details that must be considered when implementing this method.
791         fn handle_event(&self, event: &Event);
792 }
793
794 impl<F> EventHandler for F where F: Fn(&Event) {
795         fn handle_event(&self, event: &Event) {
796                 self(event)
797         }
798 }
799
800 impl<T: EventHandler> EventHandler for Arc<T> {
801         fn handle_event(&self, event: &Event) {
802                 self.deref().handle_event(event)
803         }
804 }