X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=lightning%2Fsrc%2Fln%2Fchannelmanager.rs;h=5a59d0c45af798aa22f0291b88eeb1b242dff52e;hb=fd1d5fd62c748ced131c3c7f8c0d9334c49884cc;hp=5452e365df087670ce14547b5a7250fd8dd87750;hpb=8d2c4e7c966a6cf53491ee5a22d05e016bf60f12;p=rust-lightning diff --git a/lightning/src/ln/channelmanager.rs b/lightning/src/ln/channelmanager.rs index 5452e365..5a59d0c4 100644 --- a/lightning/src/ln/channelmanager.rs +++ b/lightning/src/ln/channelmanager.rs @@ -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,17 @@ 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 for tracking liveness of its channels and generating +/// ChannelUpdate messages informing peers that the channel is temporarily disabled. To avoid +/// spam due to quick disconnection/reconnection, updates are not sent until the channel has been +/// offline for a full minute. In order to track this, you must call +/// timer_chan_freshness_every_min roughly once per minute, though it doesn't have to be perfec. +pub struct ChannelManager<'a> { default_configuration: UserConfig, genesis_hash: Sha256dHash, fee_estimator: Arc, - monitor: Arc, - chain_monitor: Arc, + monitor: Arc, tx_broadcaster: Arc, #[cfg(test)] @@ -576,7 +581,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 +591,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, monitor: Arc, chain_monitor: Arc, tx_broadcaster: Arc, logger: Arc,keys_manager: Arc, config: UserConfig, current_blockchain_height: usize) -> Result, 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, monitor: Arc, tx_broadcaster: Arc, logger: Arc,keys_manager: Arc, config: UserConfig, current_blockchain_height: usize) -> Result>, secp256k1::Error> { let secp_ctx = Secp256k1::new(); let res = Arc::new(ChannelManager { @@ -596,7 +608,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 +630,7 @@ impl ChannelManager { logger, }); - let weak_res = Arc::downgrade(&res); - res.chain_monitor.register_listener(weak_res); + Ok(res) } @@ -768,6 +778,7 @@ impl ChannelManager { self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() }); } for tx in local_txn { + log_trace!(self, "Broadcast onchain {}", log_tx!(tx)); self.tx_broadcaster.broadcast_transaction(&tx); } } @@ -885,6 +896,21 @@ impl ChannelManager { }; let pending_forward_info = if next_hop_data.hmac == [0; 32] { + #[cfg(test)] + { + // In tests, make sure that the initial onion pcket data is, at least, non-0. + // We could do some fancy randomness test here, but, ehh, whatever. + // This checks for the issue where you can calculate the path length given the + // onion data as all the path entries that the originator sent will be here + // as-is (and were originally 0s). + // Of course reverse path calculation is still pretty easy given naive routing + // algorithms, but this fixes the most-obvious case. + let mut new_packet_data = [0; 19*65]; + chacha.process(&msg.onion_routing_packet.hop_data[65..], &mut new_packet_data[0..19*65]); + assert_ne!(new_packet_data[0..65], [0; 65][..]); + assert_ne!(new_packet_data[..], [0; 19*65][..]); + } + // OUR PAYMENT! // final_expiry_too_soon if (msg.cltv_expiry as u64) < self.latest_block_height.load(Ordering::Acquire) as u64 + (CLTV_CLAIM_BUFFER + LATENCY_GRACE_PERIOD_BLOCKS) as u64 { @@ -1078,14 +1104,14 @@ impl ChannelManager { } } - let session_priv = self.keys_manager.get_session_key(); + let (session_priv, prng_seed) = self.keys_manager.get_onion_rand(); let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1; let onion_keys = secp_call!(onion_utils::construct_onion_keys(&self.secp_ctx, &route, &session_priv), APIError::RouteError{err: "Pubkey along hop was maliciously selected"}); let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height)?; - let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &payment_hash); + let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, prng_seed, &payment_hash); let _ = self.total_consistency_lock.read().unwrap(); @@ -1483,6 +1509,31 @@ impl ChannelManager { events.append(&mut new_events); } + /// If a peer is disconnected we mark any channels with that peer as 'disabled'. + /// After some time, if channels are still disabled we need to broadcast a ChannelUpdate + /// to inform the network about the uselessness of these channels. + /// + /// This method handles all the details, and must be called roughly once per minute. + 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). @@ -2073,6 +2124,7 @@ impl ChannelManager { } }; if let Some(broadcast_tx) = tx { + log_trace!(self, "Broadcast onchain {}", log_tx!(broadcast_tx)); self.tx_broadcaster.broadcast_transaction(&broadcast_tx); } if let Some(chan) = chan_option { @@ -2514,7 +2566,7 @@ impl ChannelManager { } } -impl events::MessageSendEventsProvider for ChannelManager { +impl<'a> events::MessageSendEventsProvider for ChannelManager<'a> { fn get_and_clear_pending_msg_events(&self) -> Vec { // 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 @@ -2539,7 +2591,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 { // 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 @@ -2564,7 +2616,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()); @@ -2678,7 +2730,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(); @@ -2791,8 +2843,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)); @@ -3063,7 +3115,7 @@ impl Readable for HTLCForwardInfo { } } -impl Writeable for ChannelManager { +impl<'a> Writeable for ChannelManager<'a> { fn write(&self, writer: &mut W) -> Result<(), ::std::io::Error> { let _ = self.total_consistency_lock.write().unwrap(); @@ -3125,9 +3177,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, @@ -3141,11 +3192,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, - /// The ChainWatchInterface for use in the ChannelManager in the future. - /// - /// No calls to the ChainWatchInterface will be made during deserialization. - pub chain_monitor: Arc, + pub monitor: Arc, + /// 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. @@ -3170,8 +3218,8 @@ pub struct ChannelManagerReadArgs<'a> { pub channel_monitors: &'a HashMap, } -impl<'a, R : ::std::io::Read> ReadableArgs> for (Sha256dHash, ChannelManager) { - fn read(reader: &mut R, args: ChannelManagerReadArgs<'a>) -> Result { +impl<'a, 'b, R : ::std::io::Read> ReadableArgs> for (Sha256dHash, ChannelManager<'b>) { + fn read(reader: &mut R, args: ChannelManagerReadArgs<'a, 'b>) -> Result { let _ver: u8 = Readable::read(reader)?; let min_ver: u8 = Readable::read(reader)?; if min_ver > SERIALIZATION_VERSION { @@ -3248,7 +3296,6 @@ impl<'a, R : ::std::io::Read> ReadableArgs> 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),