X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=lightning%2Fsrc%2Fln%2Fchannelmanager.rs;h=8ff6918d4ffc7e814c871f9305a979f7e29a73c0;hb=f2a2fd0d48be78972ed81481c2dfbfb68ecda44e;hp=21eab0c48df447e5a2df0eab7947737043db697c;hpb=7591eda7a80ba7ef7d66d03dc409542a3f284bdb;p=rust-lightning diff --git a/lightning/src/ln/channelmanager.rs b/lightning/src/ln/channelmanager.rs index 21eab0c4..8ff6918d 100644 --- a/lightning/src/ln/channelmanager.rs +++ b/lightning/src/ln/channelmanager.rs @@ -34,7 +34,7 @@ use ln::msgs; use ln::msgs::LocalFeatures; use ln::onion_utils; use ln::msgs::{ChannelMessageHandler, DecodeError, LightningError}; -use chain::keysinterface::KeysInterface; +use chain::keysinterface::{ChannelKeys, KeysInterface}; use util::config::UserConfig; use util::{byte_utils, events}; use util::ser::{Readable, ReadableArgs, Writeable, Writer}; @@ -49,6 +49,8 @@ use std::sync::{Arc, Mutex, MutexGuard, RwLock}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::Duration; +const SIXTY_FIVE_ZEROS: [u8; 65] = [0; 65]; + // We hold various information about HTLC relay in the HTLC objects in Channel itself: // // Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should @@ -254,8 +256,8 @@ pub(super) enum RAACommitmentOrder { } // Note this is only exposed in cfg(test): -pub(super) struct ChannelHolder { - pub(super) by_id: HashMap<[u8; 32], Channel>, +pub(super) struct ChannelHolder { + pub(super) by_id: HashMap<[u8; 32], Channel>, pub(super) short_to_id: HashMap, /// short channel id -> forward infos. Key of 0 means payments received /// Note that while this is held in the same mutex as the channels themselves, no consistency @@ -272,15 +274,15 @@ pub(super) struct ChannelHolder { /// for broadcast messages, where ordering isn't as strict). pub(super) pending_msg_events: Vec, } -pub(super) struct MutChannelHolder<'a> { - pub(super) by_id: &'a mut HashMap<[u8; 32], Channel>, +pub(super) struct MutChannelHolder<'a, ChanSigner: ChannelKeys + 'a> { + pub(super) by_id: &'a mut HashMap<[u8; 32], Channel>, pub(super) short_to_id: &'a mut HashMap, pub(super) forward_htlcs: &'a mut HashMap>, pub(super) claimable_htlcs: &'a mut HashMap>, pub(super) pending_msg_events: &'a mut Vec, } -impl ChannelHolder { - pub(super) fn borrow_parts(&mut self) -> MutChannelHolder { +impl ChannelHolder { + pub(super) fn borrow_parts(&mut self) -> MutChannelHolder { MutChannelHolder { by_id: &mut self.by_id, short_to_id: &mut self.short_to_id, @@ -324,7 +326,7 @@ const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assum /// 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> { +pub struct ChannelManager<'a, ChanSigner: ChannelKeys> { default_configuration: UserConfig, genesis_hash: Sha256dHash, fee_estimator: Arc, @@ -339,9 +341,9 @@ pub struct ChannelManager<'a> { secp_ctx: Secp256k1, #[cfg(test)] - pub(super) channel_state: Mutex, + pub(super) channel_state: Mutex>, #[cfg(not(test))] - channel_state: Mutex, + channel_state: Mutex>, our_network_key: SecretKey, pending_events: Mutex>, @@ -350,7 +352,7 @@ pub struct ChannelManager<'a> { /// Taken first everywhere where we are making changes before any other locks. total_consistency_lock: RwLock<()>, - keys_manager: Arc, + keys_manager: Arc>, logger: Arc, } @@ -581,7 +583,7 @@ macro_rules! maybe_break_monitor_err { } } -impl<'a> ChannelManager<'a> { +impl<'a, ChanSigner: ChannelKeys> ChannelManager<'a, ChanSigner> { /// 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 @@ -600,7 +602,7 @@ impl<'a> ChannelManager<'a> { /// 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> { + 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 { @@ -818,8 +820,7 @@ impl<'a> ChannelManager<'a> { } } - const ZERO:[u8; 65] = [0; 65]; - fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard) { + fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard>) { macro_rules! return_malformed_err { ($msg: expr, $err_code: expr) => { { @@ -896,6 +897,21 @@ impl<'a> ChannelManager<'a> { }; 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 { @@ -926,7 +942,7 @@ impl<'a> ChannelManager<'a> { } else { let mut new_packet_data = [0; 20*65]; chacha.process(&msg.onion_routing_packet.hop_data[65..], &mut new_packet_data[0..19*65]); - chacha.process(&ChannelManager::ZERO[..], &mut new_packet_data[19*65..]); + chacha.process(&SIXTY_FIVE_ZEROS[..], &mut new_packet_data[19*65..]); let mut new_pubkey = msg.onion_routing_packet.public_key.unwrap(); @@ -1023,7 +1039,7 @@ impl<'a> ChannelManager<'a> { /// only fails if the channel does not yet have an assigned short_id /// May be called with channel_state already locked! - fn get_channel_update(&self, chan: &Channel) -> Result { + fn get_channel_update(&self, chan: &Channel) -> Result { let short_channel_id = match chan.get_short_channel_id() { None => return Err(LightningError{err: "Channel not yet established", action: msgs::ErrorAction::IgnoreError}), Some(id) => id, @@ -1089,14 +1105,14 @@ impl<'a> ChannelManager<'a> { } } - 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(); @@ -1252,7 +1268,7 @@ impl<'a> ChannelManager<'a> { } } - fn get_announcement_sigs(&self, chan: &Channel) -> Option { + fn get_announcement_sigs(&self, chan: &Channel) -> Option { if !chan.should_announce() { return None } let (announcement, our_bitcoin_sig) = match chan.get_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone()) { @@ -1546,7 +1562,7 @@ impl<'a> ChannelManager<'a> { /// to fail and take the channel_state lock for each iteration (as we take ownership and may /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to /// still-available channels. - fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard, source: HTLCSource, payment_hash: &PaymentHash, onion_error: HTLCFailReason) { + fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard>, source: HTLCSource, payment_hash: &PaymentHash, onion_error: HTLCFailReason) { //TODO: There is a timing attack here where if a node fails an HTLC back to us they can //identify whether we sent it or not based on the (I presume) very different runtime //between the branches here. We should make this async and move it into the forward HTLCs @@ -1674,7 +1690,7 @@ impl<'a> ChannelManager<'a> { true } else { false } } - fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard, source: HTLCSource, payment_preimage: PaymentPreimage) { + fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard>, source: HTLCSource, payment_preimage: PaymentPreimage) { let (their_node_id, err) = loop { match source { HTLCSource::OutboundRoute { .. } => { @@ -2551,7 +2567,7 @@ impl<'a> ChannelManager<'a> { } } -impl<'a> events::MessageSendEventsProvider for ChannelManager<'a> { +impl<'a, ChanSigner: ChannelKeys> events::MessageSendEventsProvider for ChannelManager<'a, ChanSigner> { 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 @@ -2576,7 +2592,7 @@ impl<'a> events::MessageSendEventsProvider for ChannelManager<'a> { } } -impl<'a> events::EventsProvider for ChannelManager<'a> { +impl<'a, ChanSigner: ChannelKeys> events::EventsProvider for ChannelManager<'a, ChanSigner> { 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 @@ -2601,7 +2617,7 @@ impl<'a> events::EventsProvider for ChannelManager<'a> { } } -impl<'a> ChainListener for ChannelManager<'a> { +impl<'a, ChanSigner: ChannelKeys> ChainListener for ChannelManager<'a, ChanSigner> { 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()); @@ -2715,7 +2731,7 @@ impl<'a> ChainListener for ChannelManager<'a> { } } -impl<'a> ChannelMessageHandler for ChannelManager<'a> { +impl<'a, ChanSigner: ChannelKeys> ChannelMessageHandler for ChannelManager<'a, ChanSigner> { //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(); @@ -3100,7 +3116,7 @@ impl Readable for HTLCForwardInfo { } } -impl<'a> Writeable for ChannelManager<'a> { +impl<'a, ChanSigner: ChannelKeys + Writeable> Writeable for ChannelManager<'a, ChanSigner> { fn write(&self, writer: &mut W) -> Result<(), ::std::io::Error> { let _ = self.total_consistency_lock.write().unwrap(); @@ -3163,10 +3179,10 @@ impl<'a> Writeable for ChannelManager<'a> { /// 5) Move the ChannelMonitors into your local ManyChannelMonitor. /// 6) Disconnect/connect blocks on the ChannelManager. /// 7) Register the new ChannelManager with your ChainWatchInterface. -pub struct ChannelManagerReadArgs<'a, 'b> { +pub struct ChannelManagerReadArgs<'a, 'b, ChanSigner: ChannelKeys> { /// The keys provider which will give us relevant keys. Some keys will be loaded during /// deserialization. - pub keys_manager: Arc, + pub keys_manager: Arc>, /// The fee_estimator for use in the ChannelManager in the future. /// @@ -3203,8 +3219,8 @@ pub struct ChannelManagerReadArgs<'a, 'b> { pub channel_monitors: &'a HashMap, } -impl<'a, 'b, R : ::std::io::Read> ReadableArgs> for (Sha256dHash, ChannelManager<'b>) { - fn read(reader: &mut R, args: ChannelManagerReadArgs<'a, 'b>) -> Result { +impl<'a, 'b, R : ::std::io::Read, ChanSigner: ChannelKeys + Readable> ReadableArgs> for (Sha256dHash, ChannelManager<'b, ChanSigner>) { + fn read(reader: &mut R, args: ChannelManagerReadArgs<'a, 'b, ChanSigner>) -> Result { let _ver: u8 = Readable::read(reader)?; let min_ver: u8 = Readable::read(reader)?; if min_ver > SERIALIZATION_VERSION { @@ -3222,7 +3238,7 @@ impl<'a, 'b, R : ::std::io::Read> ReadableArgs let mut by_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128)); let mut short_to_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128)); for _ in 0..channel_count { - let mut channel: Channel = ReadableArgs::read(reader, args.logger.clone())?; + let mut channel: Channel = ReadableArgs::read(reader, args.logger.clone())?; if channel.last_block_connected != last_block_hash { return Err(DecodeError::InvalidValue); }