Add timer_chan_freshness_every_min
[rust-lightning] / lightning / src / ln / channelmanager.rs
index c863f46b613c77c27198d85e8f3121d9a2eb5c20..32ae66c7353970342bbc7d7ce442b65b35a8a70f 100644 (file)
@@ -25,7 +25,7 @@ use secp256k1::Secp256k1;
 use secp256k1::ecdh::SharedSecret;
 use secp256k1;
 
-use chain::chaininterface::{BroadcasterInterface,ChainListener,ChainWatchInterface,FeeEstimator};
+use chain::chaininterface::{BroadcasterInterface,ChainListener,FeeEstimator};
 use chain::transaction::OutPoint;
 use ln::channel::{Channel, ChannelError};
 use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, ManyChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
@@ -318,12 +318,18 @@ const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assum
 /// the "reorg path" (ie call block_disconnected() until you get to a common block and then call
 /// block_connected() to step towards your best block) upon deserialization before using the
 /// object!
-pub struct ChannelManager {
+///
+/// Note that ChannelManager is responsible of tracking liveness of its channels and by so
+/// to generate ChannelUpdate messages intended to be broadcast on the gossip layer. To avoid
+/// spam due to quick connection/reconnection, updates should be first stagged then after a period
+/// of 1 min flushed to the network through call to timer_chan_freshness_every_min. You may
+/// delay or anticipate call to this method to suit your announcements requirements different than
+/// the 1 min period.
+pub struct ChannelManager<'a> {
        default_configuration: UserConfig,
        genesis_hash: Sha256dHash,
        fee_estimator: Arc<FeeEstimator>,
-       monitor: Arc<ManyChannelMonitor>,
-       chain_monitor: Arc<ChainWatchInterface>,
+       monitor: Arc<ManyChannelMonitor + 'a>,
        tx_broadcaster: Arc<BroadcasterInterface>,
 
        #[cfg(test)]
@@ -576,7 +582,7 @@ macro_rules! maybe_break_monitor_err {
        }
 }
 
-impl ChannelManager {
+impl<'a> ChannelManager<'a> {
        /// Constructs a new ChannelManager to hold several channels and route between them.
        ///
        /// This is the main "logic hub" for all channel-related actions, and implements
@@ -586,9 +592,16 @@ impl ChannelManager {
        ///
        /// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
        ///
-       /// User must provide the current blockchain height from which to track onchain channel
+       /// Users must provide the current blockchain height from which to track onchain channel
        /// funding outpoints and send payments with reliable timelocks.
-       pub fn new(network: Network, feeest: Arc<FeeEstimator>, monitor: Arc<ManyChannelMonitor>, chain_monitor: Arc<ChainWatchInterface>, tx_broadcaster: Arc<BroadcasterInterface>, logger: Arc<Logger>,keys_manager: Arc<KeysInterface>, config: UserConfig, current_blockchain_height: usize) -> Result<Arc<ChannelManager>, secp256k1::Error> {
+       ///
+       /// Users need to notify the new ChannelManager when a new block is connected or
+       /// disconnected using its `block_connected` and `block_disconnected` methods.
+       /// However, rather than calling these methods directly, the user should register
+       /// the ChannelManager as a listener to the BlockNotifier and call the BlockNotifier's
+       /// `block_(dis)connected` methods, which will notify all registered listeners in one
+       /// go.
+       pub fn new(network: Network, feeest: Arc<FeeEstimator>, monitor: Arc<ManyChannelMonitor + 'a>, tx_broadcaster: Arc<BroadcasterInterface>, logger: Arc<Logger>,keys_manager: Arc<KeysInterface>, config: UserConfig, current_blockchain_height: usize) -> Result<Arc<ChannelManager<'a>>, secp256k1::Error> {
                let secp_ctx = Secp256k1::new();
 
                let res = Arc::new(ChannelManager {
@@ -596,7 +609,6 @@ impl ChannelManager {
                        genesis_hash: genesis_block(network).header.bitcoin_hash(),
                        fee_estimator: feeest.clone(),
                        monitor: monitor.clone(),
-                       chain_monitor,
                        tx_broadcaster,
 
                        latest_block_height: AtomicUsize::new(current_blockchain_height),
@@ -619,8 +631,7 @@ impl ChannelManager {
 
                        logger,
                });
-               let weak_res = Arc::downgrade(&res);
-               res.chain_monitor.register_listener(weak_res);
+
                Ok(res)
        }
 
@@ -1483,6 +1494,30 @@ impl ChannelManager {
                events.append(&mut new_events);
        }
 
+       /// Latency/peer disconnection may trigger us to mark as disabled some
+       /// of our channels. After some time, if channels are still disabled
+       /// we need to broadcast ChannelUpdate to inform other network peers
+       /// about the uselessness of this channels.
+       pub fn timer_chan_freshness_every_min(&self) {
+               let _ = self.total_consistency_lock.read().unwrap();
+               let mut channel_state_lock = self.channel_state.lock().unwrap();
+               let channel_state = channel_state_lock.borrow_parts();
+               for (_, chan) in channel_state.by_id {
+                       if chan.is_disabled_staged() && !chan.is_live() {
+                               if let Ok(update) = self.get_channel_update(&chan) {
+                                       channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
+                                               msg: update
+                                       });
+                               }
+                               chan.to_fresh();
+                       } else if chan.is_disabled_staged() && chan.is_live() {
+                               chan.to_fresh();
+                       } else if chan.is_disabled_marked() {
+                               chan.to_disabled_staged();
+                       }
+               }
+       }
+
        /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
        /// after a PaymentReceived event, failing the HTLC back to its origin and freeing resources
        /// along the path (including in our own channel on which we received it).
@@ -1972,6 +2007,15 @@ impl ChannelManager {
                                }
                                try_chan_entry!(self, chan.get_mut().funding_locked(&msg), channel_state, chan);
                                if let Some(announcement_sigs) = self.get_announcement_sigs(chan.get()) {
+                                       // If we see locking block before receiving remote funding_locked, we broadcast our
+                                       // announcement_sigs at remote funding_locked reception. If we receive remote
+                                       // funding_locked before seeing locking block, we broadcast our announcement_sigs at locking
+                                       // block connection. We should guanrantee to broadcast announcement_sigs to our peer whatever
+                                       // the order of the events but our peer may not receive it due to disconnection. The specs
+                                       // lacking an acknowledgement for announcement_sigs we may have to re-send them at peer
+                                       // connection in the future if simultaneous misses by both peers due to network/hardware
+                                       // failures is an issue. Note, to achieve its goal, only one of the announcement_sigs needs
+                                       // to be received, from then sigs are going to be flood to the whole network.
                                        channel_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
                                                node_id: their_node_id.clone(),
                                                msg: announcement_sigs,
@@ -2505,7 +2549,7 @@ impl ChannelManager {
        }
 }
 
-impl events::MessageSendEventsProvider for ChannelManager {
+impl<'a> events::MessageSendEventsProvider for ChannelManager<'a> {
        fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
                // TODO: Event release to users and serialization is currently race-y: it's very easy for a
                // user to serialize a ChannelManager with pending events in it and lose those events on
@@ -2530,7 +2574,7 @@ impl events::MessageSendEventsProvider for ChannelManager {
        }
 }
 
-impl events::EventsProvider for ChannelManager {
+impl<'a> events::EventsProvider for ChannelManager<'a> {
        fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
                // TODO: Event release to users and serialization is currently race-y: it's very easy for a
                // user to serialize a ChannelManager with pending events in it and lose those events on
@@ -2555,7 +2599,7 @@ impl events::EventsProvider for ChannelManager {
        }
 }
 
-impl ChainListener for ChannelManager {
+impl<'a> ChainListener for ChannelManager<'a> {
        fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
                let header_hash = header.bitcoin_hash();
                log_trace!(self, "Block {} at height {} connected with {} txn matched", header_hash, height, txn_matched.len());
@@ -2669,7 +2713,7 @@ impl ChainListener for ChannelManager {
        }
 }
 
-impl ChannelMessageHandler for ChannelManager {
+impl<'a> ChannelMessageHandler for ChannelManager<'a> {
        //TODO: Handle errors and close channel (or so)
        fn handle_open_channel(&self, their_node_id: &PublicKey, their_local_features: LocalFeatures, msg: &msgs::OpenChannel) -> Result<(), LightningError> {
                let _ = self.total_consistency_lock.read().unwrap();
@@ -2782,8 +2826,8 @@ impl ChannelMessageHandler for ChannelManager {
                                log_debug!(self, "Marking channels with {} disconnected and generating channel_updates", log_pubkey!(their_node_id));
                                channel_state.by_id.retain(|_, chan| {
                                        if chan.get_their_node_id() == *their_node_id {
-                                               //TODO: mark channel disabled (and maybe announce such after a timeout).
                                                let failed_adds = chan.remove_uncommitted_htlcs_and_mark_paused();
+                                               chan.to_disabled_marked();
                                                if !failed_adds.is_empty() {
                                                        let chan_update = self.get_channel_update(&chan).map(|u| u.encode_with_len()).unwrap(); // Cannot add/recv HTLCs before we have a short_id so unwrap is safe
                                                        failed_payments.push((chan_update, failed_adds));
@@ -3054,7 +3098,7 @@ impl<R: ::std::io::Read> Readable<R> for HTLCForwardInfo {
        }
 }
 
-impl Writeable for ChannelManager {
+impl<'a> Writeable for ChannelManager<'a> {
        fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
                let _ = self.total_consistency_lock.write().unwrap();
 
@@ -3116,9 +3160,8 @@ impl Writeable for ChannelManager {
 /// 4) Reconnect blocks on your ChannelMonitors.
 /// 5) Move the ChannelMonitors into your local ManyChannelMonitor.
 /// 6) Disconnect/connect blocks on the ChannelManager.
-/// 7) Register the new ChannelManager with your ChainWatchInterface (this does not happen
-///    automatically as it does in ChannelManager::new()).
-pub struct ChannelManagerReadArgs<'a> {
+/// 7) Register the new ChannelManager with your ChainWatchInterface.
+pub struct ChannelManagerReadArgs<'a, 'b> {
        /// The keys provider which will give us relevant keys. Some keys will be loaded during
        /// deserialization.
        pub keys_manager: Arc<KeysInterface>,
@@ -3132,11 +3175,8 @@ pub struct ChannelManagerReadArgs<'a> {
        /// No calls to the ManyChannelMonitor will be made during deserialization. It is assumed that
        /// you have deserialized ChannelMonitors separately and will add them to your
        /// ManyChannelMonitor after deserializing this ChannelManager.
-       pub monitor: Arc<ManyChannelMonitor>,
-       /// The ChainWatchInterface for use in the ChannelManager in the future.
-       ///
-       /// No calls to the ChainWatchInterface will be made during deserialization.
-       pub chain_monitor: Arc<ChainWatchInterface>,
+       pub monitor: Arc<ManyChannelMonitor + 'b>,
+
        /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
        /// used to broadcast the latest local commitment transactions of channels which must be
        /// force-closed during deserialization.
@@ -3161,8 +3201,8 @@ pub struct ChannelManagerReadArgs<'a> {
        pub channel_monitors: &'a HashMap<OutPoint, &'a ChannelMonitor>,
 }
 
-impl<'a, R : ::std::io::Read> ReadableArgs<R, ChannelManagerReadArgs<'a>> for (Sha256dHash, ChannelManager) {
-       fn read(reader: &mut R, args: ChannelManagerReadArgs<'a>) -> Result<Self, DecodeError> {
+impl<'a, 'b, R : ::std::io::Read> ReadableArgs<R, ChannelManagerReadArgs<'a, 'b>> for (Sha256dHash, ChannelManager<'b>) {
+       fn read(reader: &mut R, args: ChannelManagerReadArgs<'a, 'b>) -> Result<Self, DecodeError> {
                let _ver: u8 = Readable::read(reader)?;
                let min_ver: u8 = Readable::read(reader)?;
                if min_ver > SERIALIZATION_VERSION {
@@ -3239,7 +3279,6 @@ impl<'a, R : ::std::io::Read> ReadableArgs<R, ChannelManagerReadArgs<'a>> for (S
                        genesis_hash,
                        fee_estimator: args.fee_estimator,
                        monitor: args.monitor,
-                       chain_monitor: args.chain_monitor,
                        tx_broadcaster: args.tx_broadcaster,
 
                        latest_block_height: AtomicUsize::new(latest_block_height as usize),