Sort `Event` variants somewhat more sensibly
[rust-lightning] / lightning / src / util / events.rs
index e90f443b0c2c42c1126bf4eb9805def24d4cf5bb..f35dc14e03555bed83d94e48c9702e6d50a36bc9 100644 (file)
@@ -17,6 +17,7 @@
 use chain::keysinterface::SpendableOutputDescriptor;
 use ln::channelmanager::PaymentId;
 use ln::channel::FUNDING_CONF_DEADLINE_BLOCKS;
+use ln::features::ChannelTypeFeatures;
 use ln::msgs;
 use ln::msgs::DecodeError;
 use ln::{PaymentPreimage, PaymentHash, PaymentSecret};
@@ -29,7 +30,6 @@ use bitcoin::blockdata::script::Script;
 use bitcoin::hashes::Hash;
 use bitcoin::hashes::sha256::Hash as Sha256;
 use bitcoin::secp256k1::key::PublicKey;
-
 use io;
 use prelude::*;
 use core::time::Duration;
@@ -153,10 +153,13 @@ impl_writeable_tlv_based_enum_upgradable!(ClosureReason,
 #[derive(Clone, Debug)]
 pub enum Event {
        /// Used to indicate that the client should generate a funding transaction with the given
-       /// parameters and then call ChannelManager::funding_transaction_generated.
-       /// Generated in ChannelManager message handling.
+       /// parameters and then call [`ChannelManager::funding_transaction_generated`].
+       /// Generated in [`ChannelManager`] message handling.
        /// Note that *all inputs* in the funding transaction must spend SegWit outputs or your
        /// counterparty can steal your funds!
+       ///
+       /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
+       /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
        FundingGenerationReady {
                /// The random channel_id we picked which you'll need to pass into
                /// ChannelManager::funding_transaction_generated.
@@ -180,10 +183,15 @@ pub enum Event {
        /// [`ChannelManager::fail_htlc_backwards`] within the HTLC's timeout, the HTLC will be
        /// automatically failed.
        ///
+       /// # Note
+       /// LDK will not stop an inbound payment from being paid multiple times, so multiple
+       /// `PaymentReceived` events may be generated for the same payment.
+       ///
        /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
        /// [`ChannelManager::fail_htlc_backwards`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards
        PaymentReceived {
-               /// The hash for which the preimage should be handed to the ChannelManager.
+               /// The hash for which the preimage should be handed to the ChannelManager. Note that LDK will
+               /// not stop you from registering duplicate payment hashes for inbound payments.
                payment_hash: PaymentHash,
                /// The value, in thousandths of a satoshi, that this payment is for.
                amt: u64,
@@ -222,14 +230,61 @@ pub enum Event {
                /// [`Route::get_total_fees`]: crate::routing::router::Route::get_total_fees
                fee_paid_msat: Option<u64>,
        },
-       /// Indicates an outbound payment we made failed. Probably some intermediary node dropped
+       /// Indicates an outbound payment failed. Individual [`Event::PaymentPathFailed`] events
+       /// provide failure information for each MPP part in the payment.
+       ///
+       /// This event is provided once there are no further pending HTLCs for the payment and the
+       /// payment is no longer retryable, either due to a several-block timeout or because
+       /// [`ChannelManager::abandon_payment`] was previously called for the corresponding payment.
+       ///
+       /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
+       PaymentFailed {
+               /// The id returned by [`ChannelManager::send_payment`] and used with
+               /// [`ChannelManager::retry_payment`] and [`ChannelManager::abandon_payment`].
+               ///
+               /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
+               /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
+               /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
+               payment_id: PaymentId,
+               /// The hash that was given to [`ChannelManager::send_payment`].
+               ///
+               /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
+               payment_hash: PaymentHash,
+       },
+       /// Indicates that a path for an outbound payment was successful.
+       ///
+       /// Always generated after [`Event::PaymentSent`] and thus useful for scoring channels. See
+       /// [`Event::PaymentSent`] for obtaining the payment preimage.
+       PaymentPathSuccessful {
+               /// The id returned by [`ChannelManager::send_payment`] and used with
+               /// [`ChannelManager::retry_payment`].
+               ///
+               /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
+               /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
+               payment_id: PaymentId,
+               /// The hash that was given to [`ChannelManager::send_payment`].
+               ///
+               /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
+               payment_hash: Option<PaymentHash>,
+               /// The payment path that was successful.
+               ///
+               /// May contain a closed channel if the HTLC sent along the path was fulfilled on chain.
+               path: Vec<RouteHop>,
+       },
+       /// Indicates an outbound HTLC we sent failed. Probably some intermediary node dropped
        /// something. You may wish to retry with a different route.
+       ///
+       /// Note that this does *not* indicate that all paths for an MPP payment have failed, see
+       /// [`Event::PaymentFailed`] and [`all_paths_failed`].
+       ///
+       /// [`all_paths_failed`]: Self::PaymentPathFailed::all_paths_failed
        PaymentPathFailed {
                /// The id returned by [`ChannelManager::send_payment`] and used with
-               /// [`ChannelManager::retry_payment`].
+               /// [`ChannelManager::retry_payment`] and [`ChannelManager::abandon_payment`].
                ///
                /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
                /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
+               /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
                payment_id: Option<PaymentId>,
                /// The hash that was given to [`ChannelManager::send_payment`].
                ///
@@ -251,6 +306,20 @@ pub enum Event {
                /// For both single-path and multi-path payments, this is set if all paths of the payment have
                /// failed. This will be set to false if (1) this is an MPP payment and (2) other parts of the
                /// larger MPP payment were still in flight when this event was generated.
+               ///
+               /// Note that if you are retrying individual MPP parts, using this value to determine if a
+               /// payment has fully failed is race-y. Because multiple failures can happen prior to events
+               /// being processed, you may retry in response to a first failure, with a second failure
+               /// (with `all_paths_failed` set) still pending. Then, when the second failure is processed
+               /// you will see `all_paths_failed` set even though the retry of the first failure still
+               /// has an associated in-flight HTLC. See (1) for an example of such a failure.
+               ///
+               /// If you wish to retry individual MPP parts and learn when a payment has failed, you must
+               /// call [`ChannelManager::abandon_payment`] and wait for a [`Event::PaymentFailed`] event.
+               ///
+               /// (1) <https://github.com/lightningdevkit/rust-lightning/issues/1164>
+               ///
+               /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
                all_paths_failed: bool,
                /// The payment path that failed.
                path: Vec<RouteHop>,
@@ -271,8 +340,10 @@ pub enum Event {
 #[cfg(test)]
                error_data: Option<Vec<u8>>,
        },
-       /// Used to indicate that ChannelManager::process_pending_htlc_forwards should be called at a
-       /// time in the future.
+       /// Used to indicate that [`ChannelManager::process_pending_htlc_forwards`] should be called at
+       /// a time in the future.
+       ///
+       /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
        PendingHTLCsForwardable {
                /// The minimum amount of time that should be waited prior to calling
                /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
@@ -292,6 +363,9 @@ pub enum Event {
        /// This event is generated when a payment has been successfully forwarded through us and a
        /// forwarding fee earned.
        PaymentForwarded {
+               /// The channel between the source node and us. Optional because versions prior to 0.0.107
+               /// do not serialize this field.
+               source_channel_id: Option<[u8; 32]>,
                /// The fee, in milli-satoshis, which was earned as a result of the payment.
                ///
                /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
@@ -315,11 +389,15 @@ pub enum Event {
                /// The channel_id of the channel which has been closed. Note that on-chain transactions
                /// resolving the channel are likely still awaiting confirmation.
                channel_id: [u8; 32],
-               /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`], or 0 for
-               /// an inbound channel. This will always be zero for objects serialized with LDK versions
-               /// prior to 0.0.102.
+               /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
+               /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
+               /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
+               /// `user_channel_id` will be 0 for an inbound channel.
+               /// This will always be zero for objects serialized with LDK versions prior to 0.0.102.
                ///
                /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
+               /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
+               /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
                user_channel_id: u64,
                /// The reason the channel was closed.
                reason: ClosureReason
@@ -332,25 +410,43 @@ pub enum Event {
                /// The full transaction received from the user
                transaction: Transaction
        },
-       /// Indicates that a path for an outbound payment was successful.
+       /// Indicates a request to open a new channel by a peer.
        ///
-       /// Always generated after [`Event::PaymentSent`] and thus useful for scoring channels. See
-       /// [`Event::PaymentSent`] for obtaining the payment preimage.
-       PaymentPathSuccessful {
-               /// The id returned by [`ChannelManager::send_payment`] and used with
-               /// [`ChannelManager::retry_payment`].
+       /// To accept the request, call [`ChannelManager::accept_inbound_channel`]. To reject the
+       /// request, call [`ChannelManager::force_close_channel`].
+       ///
+       /// The event is only triggered when a new open channel request is received and the
+       /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true.
+       ///
+       /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
+       /// [`ChannelManager::force_close_channel`]: crate::ln::channelmanager::ChannelManager::force_close_channel
+       /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
+       OpenChannelRequest {
+               /// The temporary channel ID of the channel requested to be opened.
                ///
-               /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
-               /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
-               payment_id: PaymentId,
-               /// The hash that was given to [`ChannelManager::send_payment`].
+               /// When responding to the request, the `temporary_channel_id` should be passed
+               /// back to the ChannelManager with [`ChannelManager::accept_inbound_channel`] to accept,
+               /// or to [`ChannelManager::force_close_channel`] to reject.
                ///
-               /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
-               payment_hash: Option<PaymentHash>,
-               /// The payment path that was successful.
+               /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
+               /// [`ChannelManager::force_close_channel`]: crate::ln::channelmanager::ChannelManager::force_close_channel
+               temporary_channel_id: [u8; 32],
+               /// The node_id of the counterparty requesting to open the channel.
+               counterparty_node_id: PublicKey,
+               /// The channel value of the requested channel.
+               funding_satoshis: u64,
+               /// Our starting balance in the channel if the request is accepted, in milli-satoshi.
+               push_msat: u64,
+               /// The features that this channel will operate with. If you reject the channel, a
+               /// well-behaved counterparty may automatically re-attempt the channel with a new set of
+               /// feature flags.
                ///
-               /// May contain a closed channel if the HTLC sent along the path was fulfilled on chain.
-               path: Vec<RouteHop>,
+               /// Note that if [`ChannelTypeFeatures::supports_scid_privacy`] returns true on this type,
+               /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
+               /// 0.0.106.
+               ///
+               /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
+               channel_type: ChannelTypeFeatures,
        },
 }
 
@@ -427,10 +523,11 @@ impl Writeable for Event {
                                        (0, VecWriteWrapper(outputs), required),
                                });
                        },
-                       &Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx } => {
+                       &Event::PaymentForwarded { fee_earned_msat, source_channel_id, claim_from_onchain_tx } => {
                                7u8.write(writer)?;
                                write_tlv_fields!(writer, {
                                        (0, fee_earned_msat, option),
+                                       (1, source_channel_id, option),
                                        (2, claim_from_onchain_tx, required),
                                });
                        },
@@ -457,6 +554,18 @@ impl Writeable for Event {
                                        (4, path, vec_type)
                                })
                        },
+                       &Event::PaymentFailed { ref payment_id, ref payment_hash } => {
+                               15u8.write(writer)?;
+                               write_tlv_fields!(writer, {
+                                       (0, payment_id, required),
+                                       (2, payment_hash, required),
+                               })
+                       },
+                       &Event::OpenChannelRequest { .. } => {
+                               17u8.write(writer)?;
+                               // We never write the OpenChannelRequest events as, upon disconnection, peers
+                               // drop any channels which have not yet exchanged funding_signed.
+                       },
                        // Note that, going forward, all new events must only write data inside of
                        // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
                        // data via `write_tlv_fields`.
@@ -476,7 +585,7 @@ impl MaybeReadable for Event {
                                        let mut payment_preimage = None;
                                        let mut payment_secret = None;
                                        let mut amt = 0;
-                                       let mut _user_payment_id = None; // For compatibility with 0.0.103 and earlier
+                                       let mut _user_payment_id = None::<u64>; // For compatibility with 0.0.103 and earlier
                                        read_tlv_fields!(reader, {
                                                (0, payment_hash, required),
                                                (2, payment_secret, option),
@@ -579,12 +688,14 @@ impl MaybeReadable for Event {
                        7u8 => {
                                let f = || {
                                        let mut fee_earned_msat = None;
+                                       let mut source_channel_id = None;
                                        let mut claim_from_onchain_tx = false;
                                        read_tlv_fields!(reader, {
                                                (0, fee_earned_msat, option),
+                                               (1, source_channel_id, option),
                                                (2, claim_from_onchain_tx, required),
                                        });
-                                       Ok(Some(Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx }))
+                                       Ok(Some(Event::PaymentForwarded { fee_earned_msat, source_channel_id, claim_from_onchain_tx }))
                                };
                                f()
                        },
@@ -634,6 +745,25 @@ impl MaybeReadable for Event {
                                };
                                f()
                        },
+                       15u8 => {
+                               let f = || {
+                                       let mut payment_hash = PaymentHash([0; 32]);
+                                       let mut payment_id = PaymentId([0; 32]);
+                                       read_tlv_fields!(reader, {
+                                               (0, payment_id, required),
+                                               (2, payment_hash, required),
+                                       });
+                                       Ok(Some(Event::PaymentFailed {
+                                               payment_id,
+                                               payment_hash,
+                                       }))
+                               };
+                               f()
+                       },
+                       17u8 => {
+                               // Value 17 is used for `Event::OpenChannelRequest`.
+                               Ok(None)
+                       },
                        // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
                        // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
                        // reads.
@@ -800,7 +930,15 @@ pub enum MessageSendEvent {
                node_id: PublicKey,
                /// The reply_channel_range which should be sent.
                msg: msgs::ReplyChannelRange,
-       }
+       },
+       /// Sends a timestamp filter for inbound gossip. This should be sent on each new connection to
+       /// enable receiving gossip messages from the peer.
+       SendGossipTimestampFilter {
+               /// The node_id of this message recipient
+               node_id: PublicKey,
+               /// The gossip_timestamp_filter which should be sent.
+               msg: msgs::GossipTimestampFilter,
+       },
 }
 
 /// A trait indicating an object may generate message send events