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