X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=src%2Fln%2Fchannel.rs;h=0477f68a3a75d858f9534f2d4c404113ed9adc96;hb=3b498378620d4294f188804c97497112e3693297;hp=47c05de2ab989ab69c00a8f219efb63adebb527a;hpb=dfc04ad0b4a70649c07625aa80c8bb8587718cc2;p=rust-lightning diff --git a/src/ln/channel.rs b/src/ln/channel.rs index 47c05de2..0477f68a 100644 --- a/src/ln/channel.rs +++ b/src/ln/channel.rs @@ -16,7 +16,7 @@ use crypto::hkdf::{hkdf_extract,hkdf_expand}; use ln::msgs; use ln::msgs::{ErrorAction, HandleError, MsgEncodable}; use ln::channelmonitor::ChannelMonitor; -use ln::channelmanager::{PendingHTLCStatus, PendingForwardHTLCInfo, HTLCFailReason}; +use ln::channelmanager::{PendingHTLCStatus, PendingForwardHTLCInfo, HTLCFailReason, HTLCFailureMsg}; use ln::chan_utils::{TxCreationKeys,HTLCOutputInCommitment,HTLC_SUCCESS_TX_WEIGHT,HTLC_TIMEOUT_TX_WEIGHT}; use ln::chan_utils; use chain::chaininterface::{FeeEstimator,ConfirmationTarget}; @@ -87,24 +87,49 @@ impl ChannelKeys { } #[derive(PartialEq)] -enum HTLCState { +enum InboundHTLCState { /// Added by remote, to be included in next local commitment tx. - /// Implies HTLCOutput::outbound: false RemoteAnnounced, /// Included in a received commitment_signed message (implying we've revoke_and_ack'ed it), but /// the remote side hasn't yet revoked their previous state, which we need them to do before we /// accept this HTLC. Implies AwaitingRemoteRevoke. /// We also have not yet included this HTLC in a commitment_signed message, and are waiting on /// a remote revoke_and_ack on a previous state before we can do so. - /// Implies HTLCOutput::outbound: false AwaitingRemoteRevokeToAnnounce, /// Included in a received commitment_signed message (implying we've revoke_and_ack'ed it), but /// the remote side hasn't yet revoked their previous state, which we need them to do before we /// accept this HTLC. Implies AwaitingRemoteRevoke. /// We have included this HTLC in our latest commitment_signed and are now just waiting on a /// revoke_and_ack. - /// Implies HTLCOutput::outbound: true AwaitingAnnouncedRemoteRevoke, + Committed, + /// Removed by us and a new commitment_signed was sent (if we were AwaitingRemoteRevoke when we + /// created it we would have put it in the holding cell instead). When they next revoke_and_ack + /// we'll drop it. + /// Note that we have to keep an eye on the HTLC until we've received a broadcastable + /// commitment transaction without it as otherwise we'll have to force-close the channel to + /// claim it before the timeout (obviously doesn't apply to revoked HTLCs that we can't claim + /// anyway). That said, ChannelMonitor does this for us (see + /// ChannelMonitor::would_broadcast_at_height) so we actually remove the HTLC from our own + /// local state before then, once we're sure that the next commitment_signed and + /// ChannelMonitor::provide_latest_local_commitment_tx_info will not include this HTLC. + LocalRemoved, +} + +struct InboundHTLCOutput { + htlc_id: u64, + amount_msat: u64, + cltv_expiry: u32, + payment_hash: [u8; 32], + state: InboundHTLCState, + /// If we're in LocalRemoved, set to true if we fulfilled the HTLC, and can claim money + local_removed_fulfilled: bool, + /// state pre-Committed implies pending_forward_state, otherwise it must be None + pending_forward_state: Option, +} + +#[derive(PartialEq)] +enum OutboundHTLCState { /// Added by us and included in a commitment_signed (if we were AwaitingRemoteRevoke when we /// created it we would have put it in the holding cell instead). When they next revoke_and_ack /// we will promote to Committed (note that they may not accept it until the next time we @@ -115,65 +140,42 @@ enum HTLCState { /// allowed to remove it, the "can only be removed once committed on both sides" requirement /// doesn't matter to us and its up to them to enforce it, worst-case they jump ahead but /// we'll never get out of sync). - /// Implies HTLCOutput::outbound: true LocalAnnounced, Committed, /// Remote removed this (outbound) HTLC. We're waiting on their commitment_signed to finalize /// the change (though they'll need to revoke before we fail the payment). - /// Implies HTLCOutput::outbound: true RemoteRemoved, /// Remote removed this and sent a commitment_signed (implying we've revoke_and_ack'ed it), but /// the remote side hasn't yet revoked their previous state, which we need them to do before we /// can do any backwards failing. Implies AwaitingRemoteRevoke. /// We also have not yet removed this HTLC in a commitment_signed message, and are waiting on a /// remote revoke_and_ack on a previous state before we can do so. - /// Implies HTLCOutput::outbound: true AwaitingRemoteRevokeToRemove, /// Remote removed this and sent a commitment_signed (implying we've revoke_and_ack'ed it), but /// the remote side hasn't yet revoked their previous state, which we need them to do before we /// can do any backwards failing. Implies AwaitingRemoteRevoke. /// We have removed this HTLC in our latest commitment_signed and are now just waiting on a /// revoke_and_ack to drop completely. - /// Implies HTLCOutput::outbound: true AwaitingRemovedRemoteRevoke, - /// Removed by us and a new commitment_signed was sent (if we were AwaitingRemoteRevoke when we - /// created it we would have put it in the holding cell instead). When they next revoke_and_ack - /// we'll promote to LocalRemovedAwaitingCommitment if we fulfilled, otherwise we'll drop at - /// that point. - /// Note that we have to keep an eye on the HTLC until we've received a broadcastable - /// commitment transaction without it as otherwise we'll have to force-close the channel to - /// claim it before the timeout (obviously doesn't apply to revoked HTLCs that we can't claim - /// anyway). - /// Implies HTLCOutput::outbound: false - LocalRemoved, - /// Removed by us, sent a new commitment_signed and got a revoke_and_ack. Just waiting on an - /// updated local commitment transaction. Implies local_removed_fulfilled. - /// Implies HTLCOutput::outbound: false - LocalRemovedAwaitingCommitment, } -struct HTLCOutput { //TODO: Refactor into Outbound/InboundHTLCOutput (will save memory and fewer panics) - outbound: bool, // ie to an HTLC-Timeout transaction +struct OutboundHTLCOutput { htlc_id: u64, amount_msat: u64, cltv_expiry: u32, payment_hash: [u8; 32], - state: HTLCState, - /// If we're in a Remote* removed state, set if they failed, otherwise None + state: OutboundHTLCState, + /// If we're in a removed state, set if they failed, otherwise None fail_reason: Option, - /// If we're in LocalRemoved*, set to true if we fulfilled the HTLC, and can claim money - local_removed_fulfilled: bool, - /// state pre-committed Remote* implies pending_forward_state, otherwise it must be None - pending_forward_state: Option, } -impl HTLCOutput { - fn get_in_commitment(&self, offered: bool) -> HTLCOutputInCommitment { +macro_rules! get_htlc_in_commitment { + ($htlc: expr, $offered: expr) => { HTLCOutputInCommitment { - offered: offered, - amount_msat: self.amount_msat, - cltv_expiry: self.cltv_expiry, - payment_hash: self.payment_hash, + offered: $offered, + amount_msat: $htlc.amount_msat, + cltv_expiry: $htlc.cltv_expiry, + payment_hash: $htlc.payment_hash, transaction_output_index: 0 } } @@ -264,7 +266,8 @@ pub struct Channel { cur_local_commitment_transaction_number: u64, cur_remote_commitment_transaction_number: u64, value_to_self_msat: u64, // Excluding all pending_htlcs, excluding fees - pending_htlcs: Vec, + pending_inbound_htlcs: Vec, + pending_outbound_htlcs: Vec, holding_cell_htlc_updates: Vec, next_local_htlc_id: u64, next_remote_htlc_id: u64, @@ -338,18 +341,17 @@ const B_OUTPUT_PLUS_SPENDING_INPUT_WEIGHT: u64 = 104; // prevout: 40, nSequence: pub const MAX_FUNDING_SATOSHIS: u64 = (1 << 24); macro_rules! secp_call { - ( $res: expr, $err: expr ) => { + ( $res: expr, $err: expr, $chan_id: expr ) => { match $res { Ok(key) => key, - //TODO: make the error a parameter - Err(_) => return Err(HandleError{err: $err, action: Some(msgs::ErrorAction::DisconnectPeer{ msg: None })}) + Err(_) => return Err(HandleError {err: $err, action: Some(msgs::ErrorAction::SendErrorMessage {msg: msgs::ErrorMessage {channel_id: $chan_id, data: $err.to_string()}})}) } }; } macro_rules! secp_derived_key { - ( $res: expr ) => { - secp_call!($res, "Derived invalid key, peer is maliciously selecting parameters") + ( $res: expr, $chan_id: expr ) => { + secp_call!($res, "Derived invalid key, peer is maliciously selecting parameters", $chan_id) } } impl Channel { @@ -373,6 +375,8 @@ impl Channel { } fn derive_minimum_depth(_channel_value_satoshis_msat: u64, _value_to_self_msat: u64) -> u32 { + // Note that in order to comply with BOLT 7 announcement_signatures requirements this must + // be at least 6. const CONF_TARGET: u32 = 12; //TODO: Should be much higher CONF_TARGET } @@ -422,7 +426,8 @@ impl Channel { cur_local_commitment_transaction_number: (1 << 48) - 1, cur_remote_commitment_transaction_number: (1 << 48) - 1, value_to_self_msat: channel_value_satoshis * 1000 - push_msat, - pending_htlcs: Vec::new(), + pending_inbound_htlcs: Vec::new(), + pending_outbound_htlcs: Vec::new(), holding_cell_htlc_updates: Vec::new(), next_local_htlc_id: 0, next_remote_htlc_id: 0, @@ -523,10 +528,10 @@ impl Channel { let their_announce = if (msg.channel_flags & 1) == 1 { true } else { false }; if require_announce && !their_announce { - return Err(HandleError{err: "Peer tried to open unannounced channel, but we require public ones", action: Some(msgs::ErrorAction::IgnoreError) }); + return_error_message!("Peer tried to open unannounced channel, but we require public ones"); } if !allow_announce && their_announce { - return Err(HandleError{err: "Peer tried to open announced channel, but we require private ones", action: Some(msgs::ErrorAction::IgnoreError) }); + return_error_message!("Peer tried to open announced channel, but we require private ones"); } let background_feerate = fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Background); @@ -579,7 +584,8 @@ impl Channel { cur_local_commitment_transaction_number: (1 << 48) - 1, cur_remote_commitment_transaction_number: (1 << 48) - 1, value_to_self_msat: msg.push_msat, - pending_htlcs: Vec::new(), + pending_inbound_htlcs: Vec::new(), + pending_outbound_htlcs: Vec::new(), holding_cell_htlc_updates: Vec::new(), next_local_htlc_id: 0, next_remote_htlc_id: 0, @@ -687,71 +693,83 @@ impl Channel { ins }; - let mut txouts: Vec<(TxOut, Option)> = Vec::with_capacity(self.pending_htlcs.len() + 2); + let mut txouts: Vec<(TxOut, Option)> = Vec::with_capacity(self.pending_inbound_htlcs.len() + self.pending_outbound_htlcs.len() + 2); let dust_limit_satoshis = if local { self.our_dust_limit_satoshis } else { self.their_dust_limit_satoshis }; let mut remote_htlc_total_msat = 0; let mut local_htlc_total_msat = 0; let mut value_to_self_msat_offset = 0; - for ref htlc in self.pending_htlcs.iter() { - let include = match htlc.state { - HTLCState::RemoteAnnounced => !generated_by_local, - HTLCState::AwaitingRemoteRevokeToAnnounce => !generated_by_local, - HTLCState::AwaitingAnnouncedRemoteRevoke => true, - HTLCState::LocalAnnounced => generated_by_local, - HTLCState::Committed => true, - HTLCState::RemoteRemoved => generated_by_local, - HTLCState::AwaitingRemoteRevokeToRemove => generated_by_local, - HTLCState::AwaitingRemovedRemoteRevoke => false, - HTLCState::LocalRemoved => !generated_by_local, - HTLCState::LocalRemovedAwaitingCommitment => false, - }; - - if include { - if htlc.outbound == local { // "offered HTLC output" - if htlc.amount_msat / 1000 >= dust_limit_satoshis + (self.feerate_per_kw * HTLC_TIMEOUT_TX_WEIGHT / 1000) { - let htlc_in_tx = htlc.get_in_commitment(true); + macro_rules! add_htlc_output { + ($htlc: expr, $outbound: expr) => { + if $outbound == local { // "offered HTLC output" + if $htlc.amount_msat / 1000 >= dust_limit_satoshis + (self.feerate_per_kw * HTLC_TIMEOUT_TX_WEIGHT / 1000) { + let htlc_in_tx = get_htlc_in_commitment!($htlc, true); txouts.push((TxOut { script_pubkey: chan_utils::get_htlc_redeemscript(&htlc_in_tx, &keys).to_v0_p2wsh(), - value: htlc.amount_msat / 1000 + value: $htlc.amount_msat / 1000 }, Some(htlc_in_tx))); } } else { - if htlc.amount_msat / 1000 >= dust_limit_satoshis + (self.feerate_per_kw * HTLC_SUCCESS_TX_WEIGHT / 1000) { - let htlc_in_tx = htlc.get_in_commitment(false); + if $htlc.amount_msat / 1000 >= dust_limit_satoshis + (self.feerate_per_kw * HTLC_SUCCESS_TX_WEIGHT / 1000) { + let htlc_in_tx = get_htlc_in_commitment!($htlc, false); txouts.push((TxOut { // "received HTLC output" script_pubkey: chan_utils::get_htlc_redeemscript(&htlc_in_tx, &keys).to_v0_p2wsh(), - value: htlc.amount_msat / 1000 + value: $htlc.amount_msat / 1000 }, Some(htlc_in_tx))); } - }; - if htlc.outbound { - local_htlc_total_msat += htlc.amount_msat; - } else { - remote_htlc_total_msat += htlc.amount_msat; } + } + } + + for ref htlc in self.pending_inbound_htlcs.iter() { + let include = match htlc.state { + InboundHTLCState::RemoteAnnounced => !generated_by_local, + InboundHTLCState::AwaitingRemoteRevokeToAnnounce => !generated_by_local, + InboundHTLCState::AwaitingAnnouncedRemoteRevoke => true, + InboundHTLCState::Committed => true, + InboundHTLCState::LocalRemoved => !generated_by_local, + }; + + if include { + add_htlc_output!(htlc, false); + remote_htlc_total_msat += htlc.amount_msat; + } else { + match htlc.state { + InboundHTLCState::LocalRemoved => { + if generated_by_local && htlc.local_removed_fulfilled { + value_to_self_msat_offset += htlc.amount_msat as i64; + } + }, + _ => {}, + } + } + } + + for ref htlc in self.pending_outbound_htlcs.iter() { + let include = match htlc.state { + OutboundHTLCState::LocalAnnounced => generated_by_local, + OutboundHTLCState::Committed => true, + OutboundHTLCState::RemoteRemoved => generated_by_local, + OutboundHTLCState::AwaitingRemoteRevokeToRemove => generated_by_local, + OutboundHTLCState::AwaitingRemovedRemoteRevoke => false, + }; + + if include { + add_htlc_output!(htlc, true); + local_htlc_total_msat += htlc.amount_msat; } else { match htlc.state { - HTLCState::AwaitingRemoteRevokeToRemove|HTLCState::AwaitingRemovedRemoteRevoke => { + OutboundHTLCState::AwaitingRemoteRevokeToRemove|OutboundHTLCState::AwaitingRemovedRemoteRevoke => { if htlc.fail_reason.is_none() { value_to_self_msat_offset -= htlc.amount_msat as i64; } }, - HTLCState::RemoteRemoved => { + OutboundHTLCState::RemoteRemoved => { if !generated_by_local && htlc.fail_reason.is_none() { value_to_self_msat_offset -= htlc.amount_msat as i64; } }, - HTLCState::LocalRemoved => { - if generated_by_local && htlc.local_removed_fulfilled { - value_to_self_msat_offset += htlc.amount_msat as i64; - } - }, - HTLCState::LocalRemovedAwaitingCommitment => { - assert!(htlc.local_removed_fulfilled); - value_to_self_msat_offset += htlc.amount_msat as i64; - }, _ => {}, } } @@ -826,7 +844,8 @@ impl Channel { ins }; - assert!(self.pending_htlcs.is_empty()); + assert!(self.pending_inbound_htlcs.is_empty()); + assert!(self.pending_outbound_htlcs.is_empty()); let mut txouts: Vec<(TxOut, ())> = Vec::new(); let mut total_fee_satoshis = proposed_total_fee_satoshis; @@ -881,7 +900,7 @@ impl Channel { let delayed_payment_base = PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.delayed_payment_base_key); let htlc_basepoint = PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.htlc_base_key); - Ok(secp_derived_key!(TxCreationKeys::new(&self.secp_ctx, &per_commitment_point, &delayed_payment_base, &htlc_basepoint, &self.their_revocation_basepoint.unwrap(), &self.their_payment_basepoint.unwrap(), &self.their_htlc_basepoint.unwrap()))) + Ok(secp_derived_key!(TxCreationKeys::new(&self.secp_ctx, &per_commitment_point, &delayed_payment_base, &htlc_basepoint, &self.their_revocation_basepoint.unwrap(), &self.their_payment_basepoint.unwrap(), &self.their_htlc_basepoint.unwrap()), self.channel_id())) } #[inline] @@ -894,15 +913,16 @@ impl Channel { let revocation_basepoint = PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.revocation_base_key); let htlc_basepoint = PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.htlc_base_key); - Ok(secp_derived_key!(TxCreationKeys::new(&self.secp_ctx, &self.their_cur_commitment_point.unwrap(), &self.their_delayed_payment_basepoint.unwrap(), &self.their_htlc_basepoint.unwrap(), &revocation_basepoint, &payment_basepoint, &htlc_basepoint))) + Ok(secp_derived_key!(TxCreationKeys::new(&self.secp_ctx, &self.their_cur_commitment_point.unwrap(), &self.their_delayed_payment_basepoint.unwrap(), &self.their_htlc_basepoint.unwrap(), &revocation_basepoint, &payment_basepoint, &htlc_basepoint), self.channel_id())) } /// Gets the redeemscript for the funding transaction output (ie the funding transaction output /// pays to get_funding_redeemscript().to_v0_p2wsh()). + /// Panics if called before accept_channel/new_from_req pub fn get_funding_redeemscript(&self) -> Script { let builder = Builder::new().push_opcode(opcodes::All::OP_PUSHNUM_2); let our_funding_key = PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.funding_key).serialize(); - let their_funding_key = self.their_funding_pubkey.unwrap().serialize(); + let their_funding_key = self.their_funding_pubkey.expect("get_funding_redeemscript only allowed after accept_channel").serialize(); if our_funding_key[..] < their_funding_key[..] { builder.push_slice(&our_funding_key) .push_slice(&their_funding_key) @@ -958,7 +978,7 @@ impl Channel { let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, &keys); - let our_htlc_key = secp_derived_key!(chan_utils::derive_private_key(&self.secp_ctx, &keys.per_commitment_point, &self.local_keys.htlc_base_key)); + let our_htlc_key = secp_derived_key!(chan_utils::derive_private_key(&self.secp_ctx, &keys.per_commitment_point, &self.local_keys.htlc_base_key), self.channel_id()); let sighash = Message::from_slice(&bip143::SighashComponents::new(&tx).sighash_all(&tx.input[0], &htlc_redeemscript, htlc.amount_msat / 1000)[..]).unwrap(); let is_local_tx = PublicKey::from_secret_key(&self.secp_ctx, &our_htlc_key) == keys.a_htlc_key; Ok((htlc_redeemscript, self.secp_ctx.sign(&sighash, &our_htlc_key), is_local_tx)) @@ -1015,13 +1035,16 @@ impl Channel { sha.result(&mut payment_hash_calc); let mut pending_idx = std::usize::MAX; - for (idx, htlc) in self.pending_htlcs.iter().enumerate() { - if !htlc.outbound && htlc.payment_hash == payment_hash_calc && - htlc.state != HTLCState::LocalRemoved && htlc.state != HTLCState::LocalRemovedAwaitingCommitment { - if pending_idx != std::usize::MAX { - panic!("Duplicate HTLC payment_hash, ChannelManager should have prevented this!"); + for (idx, htlc) in self.pending_inbound_htlcs.iter().enumerate() { + if htlc.payment_hash == payment_hash_calc && + htlc.state != InboundHTLCState::LocalRemoved { + if let Some(PendingHTLCStatus::Fail(_)) = htlc.pending_forward_state { + } else { + if pending_idx != std::usize::MAX { + panic!("Duplicate HTLC payment_hash, ChannelManager should have prevented this!"); + } + pending_idx = idx; } - pending_idx = idx; } } if pending_idx == std::usize::MAX { @@ -1057,11 +1080,11 @@ impl Channel { } let htlc_id = { - let htlc = &mut self.pending_htlcs[pending_idx]; - if htlc.state == HTLCState::Committed { - htlc.state = HTLCState::LocalRemoved; + let htlc = &mut self.pending_inbound_htlcs[pending_idx]; + if htlc.state == InboundHTLCState::Committed { + htlc.state = InboundHTLCState::LocalRemoved; htlc.local_removed_fulfilled = true; - } else if htlc.state == HTLCState::RemoteAnnounced || htlc.state == HTLCState::AwaitingRemoteRevokeToAnnounce || htlc.state == HTLCState::AwaitingAnnouncedRemoteRevoke { + } else if htlc.state == InboundHTLCState::RemoteAnnounced || htlc.state == InboundHTLCState::AwaitingRemoteRevokeToAnnounce || htlc.state == InboundHTLCState::AwaitingAnnouncedRemoteRevoke { // Theoretically we can hit this if we get the preimage on an HTLC prior to us // having forwarded it to anyone. This implies that the sender is busted as someone // else knows the preimage, but handling this case and implementing the logic to @@ -1070,7 +1093,7 @@ impl Channel { // channel_monitor and pretend we didn't just see the preimage. return Ok((None, Some(self.channel_monitor.clone()))); } else { - // LocalRemoved/LocalRemovedAwaitingCOmmitment handled in the search loop + // LocalRemoved handled in the search loop panic!("Have an inbound HTLC when not awaiting remote revoke that had a garbage state"); } htlc.htlc_id @@ -1096,7 +1119,7 @@ impl Channel { pub fn get_update_fail_htlc(&mut self, payment_hash_arg: &[u8; 32], err_packet: msgs::OnionErrorPacket) -> Result, HandleError> { if (self.channel_state & (ChannelState::ChannelFunded as u32)) != (ChannelState::ChannelFunded as u32) { - return Err(HandleError{err: "Was asked to fail an HTLC when channel was not in an operational state", action: None}); + panic!("Was asked to fail an HTLC when channel was not in an operational state"); } assert_eq!(self.channel_state & ChannelState::ShutdownComplete as u32, 0); @@ -1126,14 +1149,11 @@ impl Channel { let mut htlc_id = 0; let mut htlc_amount_msat = 0; - for htlc in self.pending_htlcs.iter_mut() { - if !htlc.outbound && htlc.payment_hash == *payment_hash_arg { - if htlc_id != 0 { - panic!("Duplicate HTLC payment_hash, you probably re-used payment preimages, NEVER DO THIS!"); - } - if htlc.state == HTLCState::Committed { - htlc.state = HTLCState::LocalRemoved; - } else if htlc.state == HTLCState::RemoteAnnounced { + for htlc in self.pending_inbound_htlcs.iter_mut() { + if htlc.payment_hash == *payment_hash_arg { + if htlc.state == InboundHTLCState::Committed { + htlc.state = InboundHTLCState::LocalRemoved; + } else if htlc.state == InboundHTLCState::RemoteAnnounced { if let Some(PendingHTLCStatus::Forward(_)) = htlc.pending_forward_state { panic!("Somehow forwarded HTLC prior to remote revocation!"); } else { @@ -1142,11 +1162,14 @@ impl Channel { // we'll fail this one as soon as remote commits to it. continue; } - } else if htlc.state == HTLCState::LocalRemoved || htlc.state == HTLCState::LocalRemovedAwaitingCommitment { + } else if htlc.state == InboundHTLCState::LocalRemoved { return Err(HandleError{err: "Unable to find a pending HTLC which matched the given payment preimage", action: None}); } else { panic!("Have an inbound HTLC when not awaiting remote revoke that had a garbage state"); } + if htlc_id != 0 { + panic!("Duplicate HTLC payment_hash, you probably re-used payment preimages, NEVER DO THIS!"); + } htlc_id = htlc.htlc_id; htlc_amount_msat += htlc.amount_msat; } @@ -1263,7 +1286,7 @@ impl Channel { let local_sighash = Message::from_slice(&bip143::SighashComponents::new(&local_initial_commitment_tx).sighash_all(&local_initial_commitment_tx.input[0], &funding_script, self.channel_value_satoshis)[..]).unwrap(); // They sign the "local" commitment transaction, allowing us to broadcast the tx if we wish. - secp_call!(self.secp_ctx.verify(&local_sighash, &sig, &self.their_funding_pubkey.unwrap()), "Invalid funding_created signature from peer"); + secp_call!(self.secp_ctx.verify(&local_sighash, &sig, &self.their_funding_pubkey.unwrap()), "Invalid funding_created signature from peer", self.channel_id()); // We sign the "remote" commitment transaction, allowing them to broadcast the tx if they wish. Ok((remote_initial_commitment_tx, self.secp_ctx.sign(&remote_sighash, &self.local_keys.funding_key))) @@ -1271,10 +1294,13 @@ impl Channel { pub fn funding_created(&mut self, msg: &msgs::FundingCreated) -> Result<(msgs::FundingSigned, ChannelMonitor), HandleError> { if self.channel_outbound { - return Err(HandleError{err: "Received funding_created for an outbound channel?", action: None}); + return Err(HandleError{err: "Received funding_created for an outbound channel?", action: Some(msgs::ErrorAction::SendErrorMessage {msg: msgs::ErrorMessage {channel_id: self.channel_id, data: "Received funding_created for an outbound channel?".to_string()}})}); } if self.channel_state != (ChannelState::OurInitSent as u32 | ChannelState::TheirInitSent as u32) { - return Err(HandleError{err: "Received funding_created after we got the channel!", action: None}); + // BOLT 2 says that if we disconnect before we send funding_signed we SHOULD NOT + // remember the channel, so its safe to just send an error_message here and drop the + // channel. + return Err(HandleError{err: "Received funding_created after we got the channel!", action: Some(msgs::ErrorAction::SendErrorMessage {msg: msgs::ErrorMessage {channel_id: self.channel_id, data: "Received funding_created after we got the channel!".to_string()}})}); } if self.channel_monitor.get_min_seen_secret() != (1 << 48) || self.cur_remote_commitment_transaction_number != (1 << 48) - 1 || self.cur_local_commitment_transaction_number != (1 << 48) - 1 { panic!("Should not have advanced channel commitment tx numbers prior to funding_created"); @@ -1326,7 +1352,7 @@ impl Channel { let local_sighash = Message::from_slice(&bip143::SighashComponents::new(&local_initial_commitment_tx).sighash_all(&local_initial_commitment_tx.input[0], &funding_script, self.channel_value_satoshis)[..]).unwrap(); // They sign the "local" commitment transaction, allowing us to broadcast the tx if we wish. - secp_call!(self.secp_ctx.verify(&local_sighash, &msg.signature, &self.their_funding_pubkey.unwrap()), "Invalid funding_signed signature from peer"); + secp_call!(self.secp_ctx.verify(&local_sighash, &msg.signature, &self.their_funding_pubkey.unwrap()), "Invalid funding_signed signature from peer", self.channel_id()); self.sign_commitment_transaction(&mut local_initial_commitment_tx, &msg.signature); self.channel_monitor.provide_latest_local_commitment_tx_info(local_initial_commitment_tx.clone(), local_keys, self.feerate_per_kw, Vec::new()); @@ -1360,31 +1386,34 @@ impl Channel { /// totals, though there is little reason to outside of further avoiding any race condition /// issues. fn get_pending_htlc_stats(&self, for_remote_update_check: bool) -> (u32, u32, u64, u64) { + //TODO: Can probably split this into inbound/outbound let mut inbound_htlc_count: u32 = 0; let mut outbound_htlc_count: u32 = 0; let mut htlc_outbound_value_msat = 0; let mut htlc_inbound_value_msat = 0; - for ref htlc in self.pending_htlcs.iter() { + for ref htlc in self.pending_inbound_htlcs.iter() { match htlc.state { - HTLCState::RemoteAnnounced => {}, - HTLCState::AwaitingRemoteRevokeToAnnounce => {}, - HTLCState::AwaitingAnnouncedRemoteRevoke => {}, - HTLCState::LocalAnnounced => { if for_remote_update_check { continue; } }, - HTLCState::Committed => {}, - HTLCState::RemoteRemoved => { if for_remote_update_check { continue; } }, - HTLCState::AwaitingRemoteRevokeToRemove => { if for_remote_update_check { continue; } }, - HTLCState::AwaitingRemovedRemoteRevoke => { if for_remote_update_check { continue; } }, - HTLCState::LocalRemoved => {}, - HTLCState::LocalRemovedAwaitingCommitment => { if for_remote_update_check { continue; } }, + InboundHTLCState::RemoteAnnounced => {}, + InboundHTLCState::AwaitingRemoteRevokeToAnnounce => {}, + InboundHTLCState::AwaitingAnnouncedRemoteRevoke => {}, + InboundHTLCState::Committed => {}, + InboundHTLCState::LocalRemoved => {}, } - if !htlc.outbound { - inbound_htlc_count += 1; - htlc_inbound_value_msat += htlc.amount_msat; - } else { - outbound_htlc_count += 1; - htlc_outbound_value_msat += htlc.amount_msat; + inbound_htlc_count += 1; + htlc_inbound_value_msat += htlc.amount_msat; + } + for ref htlc in self.pending_outbound_htlcs.iter() { + match htlc.state { + OutboundHTLCState::LocalAnnounced => { if for_remote_update_check { continue; } }, + OutboundHTLCState::Committed => {}, + OutboundHTLCState::RemoteRemoved => { if for_remote_update_check { continue; } }, + OutboundHTLCState::AwaitingRemoteRevokeToRemove => { if for_remote_update_check { continue; } }, + OutboundHTLCState::AwaitingRemovedRemoteRevoke => { if for_remote_update_check { continue; } }, } + outbound_htlc_count += 1; + htlc_outbound_value_msat += htlc.amount_msat; } + (inbound_htlc_count, outbound_htlc_count, htlc_outbound_value_msat, htlc_inbound_value_msat) } @@ -1425,14 +1454,12 @@ impl Channel { // Now update local state: self.next_remote_htlc_id += 1; - self.pending_htlcs.push(HTLCOutput { - outbound: false, + self.pending_inbound_htlcs.push(InboundHTLCOutput { htlc_id: msg.htlc_id, amount_msat: msg.amount_msat, payment_hash: msg.payment_hash, cltv_expiry: msg.cltv_expiry, - state: HTLCState::RemoteAnnounced, - fail_reason: None, + state: InboundHTLCState::RemoteAnnounced, local_removed_fulfilled: false, pending_forward_state: Some(pending_forward_state), }); @@ -1443,8 +1470,8 @@ impl Channel { /// Removes an outbound HTLC which has been commitment_signed by the remote end #[inline] fn mark_outbound_htlc_removed(&mut self, htlc_id: u64, check_preimage: Option<[u8; 32]>, fail_reason: Option) -> Result<[u8; 32], HandleError> { - for htlc in self.pending_htlcs.iter_mut() { - if htlc.outbound && htlc.htlc_id == htlc_id { + for htlc in self.pending_outbound_htlcs.iter_mut() { + if htlc.htlc_id == htlc_id { match check_preimage { None => {}, Some(payment_hash) => @@ -1452,15 +1479,15 @@ impl Channel { return Err(HandleError{err: "Remote tried to fulfill HTLC with an incorrect preimage", action: None}); } }; - if htlc.state == HTLCState::LocalAnnounced { - return Err(HandleError{err: "Remote tried to fulfill HTLC before it had been committed", action: None}); - } else if htlc.state == HTLCState::Committed { - htlc.state = HTLCState::RemoteRemoved; - htlc.fail_reason = fail_reason; - } else if htlc.state == HTLCState::AwaitingRemoteRevokeToRemove || htlc.state == HTLCState::AwaitingRemovedRemoteRevoke || htlc.state == HTLCState::RemoteRemoved { - return Err(HandleError{err: "Remote tried to fulfill HTLC that they'd already fulfilled", action: None}); - } else { - panic!("Got a non-outbound state on an outbound HTLC"); + match htlc.state { + OutboundHTLCState::LocalAnnounced => + return Err(HandleError{err: "Remote tried to fulfill HTLC before it had been committed", action: None}), + OutboundHTLCState::Committed => { + htlc.state = OutboundHTLCState::RemoteRemoved; + htlc.fail_reason = fail_reason; + }, + OutboundHTLCState::AwaitingRemoteRevokeToRemove | OutboundHTLCState::AwaitingRemovedRemoteRevoke | OutboundHTLCState::RemoteRemoved => + return Err(HandleError{err: "Remote tried to fulfill HTLC that they'd already fulfilled", action: None}), } return Ok(htlc.payment_hash.clone()); } @@ -1510,7 +1537,7 @@ impl Channel { let mut local_commitment_tx = self.build_commitment_transaction(self.cur_local_commitment_transaction_number, &local_keys, true, false); let local_commitment_txid = local_commitment_tx.0.txid(); let local_sighash = Message::from_slice(&bip143::SighashComponents::new(&local_commitment_tx.0).sighash_all(&local_commitment_tx.0.input[0], &funding_script, self.channel_value_satoshis)[..]).unwrap(); - secp_call!(self.secp_ctx.verify(&local_sighash, &msg.signature, &self.their_funding_pubkey.unwrap()), "Invalid commitment tx signature from peer"); + secp_call!(self.secp_ctx.verify(&local_sighash, &msg.signature, &self.their_funding_pubkey.unwrap()), "Invalid commitment tx signature from peer", self.channel_id()); if msg.htlc_signatures.len() != local_commitment_tx.1.len() { return Err(HandleError{err: "Got wrong number of HTLC signatures from remote", action: None}); @@ -1525,7 +1552,7 @@ impl Channel { let mut htlc_tx = self.build_htlc_transaction(&local_commitment_txid, htlc, true, &local_keys); let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, &local_keys); let htlc_sighash = Message::from_slice(&bip143::SighashComponents::new(&htlc_tx).sighash_all(&htlc_tx.input[0], &htlc_redeemscript, htlc.amount_msat / 1000)[..]).unwrap(); - secp_call!(self.secp_ctx.verify(&htlc_sighash, &msg.htlc_signatures[idx], &local_keys.b_htlc_key), "Invalid HTLC tx siganture from peer"); + secp_call!(self.secp_ctx.verify(&htlc_sighash, &msg.htlc_signatures[idx], &local_keys.b_htlc_key), "Invalid HTLC tx siganture from peer", self.channel_id()); let htlc_sig = if htlc.offered { let htlc_sig = self.sign_htlc_transaction(&mut htlc_tx, &msg.htlc_signatures[idx], &None, htlc, &local_keys)?; new_local_commitment_txn.push(htlc_tx); @@ -1543,25 +1570,18 @@ impl Channel { self.channel_monitor.provide_latest_local_commitment_tx_info(local_commitment_tx.0, local_keys, self.feerate_per_kw, htlcs_and_sigs); let mut need_our_commitment = false; - for htlc in self.pending_htlcs.iter_mut() { - if htlc.state == HTLCState::RemoteAnnounced { - htlc.state = HTLCState::AwaitingRemoteRevokeToAnnounce; + for htlc in self.pending_inbound_htlcs.iter_mut() { + if htlc.state == InboundHTLCState::RemoteAnnounced { + htlc.state = InboundHTLCState::AwaitingRemoteRevokeToAnnounce; need_our_commitment = true; - } else if htlc.state == HTLCState::RemoteRemoved { - htlc.state = HTLCState::AwaitingRemoteRevokeToRemove; + } + } + for htlc in self.pending_outbound_htlcs.iter_mut() { + if htlc.state == OutboundHTLCState::RemoteRemoved { + htlc.state = OutboundHTLCState::AwaitingRemoteRevokeToRemove; need_our_commitment = true; } } - // Finally delete all the LocalRemovedAwaitingCommitment HTLCs - // We really shouldnt have two passes here, but retain gives a non-mutable ref (Rust bug) - let mut claimed_value_msat = 0; - self.pending_htlcs.retain(|htlc| { - if htlc.state == HTLCState::LocalRemovedAwaitingCommitment { - claimed_value_msat += htlc.amount_msat; - false - } else { true } - }); - self.value_to_self_msat += claimed_value_msat; self.cur_local_commitment_transaction_number -= 1; self.last_local_commitment_txn = new_local_commitment_txn; @@ -1640,6 +1660,7 @@ impl Channel { update_add_htlcs, update_fulfill_htlcs, update_fail_htlcs, + update_fail_malformed_htlcs: Vec::new(), commitment_signed, }, monitor_update))) }, @@ -1660,7 +1681,7 @@ impl Channel { return Err(HandleError{err: "Got revoke/ACK message when channel was not in an operational state", action: None}); } if let Some(their_prev_commitment_point) = self.their_prev_commitment_point { - if PublicKey::from_secret_key(&self.secp_ctx, &secp_call!(SecretKey::from_slice(&self.secp_ctx, &msg.per_commitment_secret), "Peer provided an invalid per_commitment_secret")) != their_prev_commitment_point { + if PublicKey::from_secret_key(&self.secp_ctx, &secp_call!(SecretKey::from_slice(&self.secp_ctx, &msg.per_commitment_secret), "Peer provided an invalid per_commitment_secret", self.channel_id())) != their_prev_commitment_point { return Err(HandleError{err: "Got a revoke commitment secret which didn't correspond to their current pubkey", action: None}); } } @@ -1677,14 +1698,21 @@ impl Channel { let mut to_forward_infos = Vec::new(); let mut revoked_htlcs = Vec::new(); - let mut failed_htlcs = Vec::new(); + let mut update_fail_htlcs = Vec::new(); + let mut update_fail_malformed_htlcs = Vec::new(); let mut require_commitment = false; let mut value_to_self_msat_diff: i64 = 0; // We really shouldnt have two passes here, but retain gives a non-mutable ref (Rust bug) - self.pending_htlcs.retain(|htlc| { - if htlc.state == HTLCState::LocalRemoved { - if htlc.local_removed_fulfilled { true } else { false } - } else if htlc.state == HTLCState::AwaitingRemovedRemoteRevoke { + self.pending_inbound_htlcs.retain(|htlc| { + if htlc.state == InboundHTLCState::LocalRemoved { + if htlc.local_removed_fulfilled { + value_to_self_msat_diff += htlc.amount_msat as i64; + } + false + } else { true } + }); + self.pending_outbound_htlcs.retain(|htlc| { + if htlc.state == OutboundHTLCState::AwaitingRemovedRemoteRevoke { if let Some(reason) = htlc.fail_reason.clone() { // We really want take() here, but, again, non-mut ref :( revoked_htlcs.push((htlc.payment_hash, reason)); } else { @@ -1694,40 +1722,47 @@ impl Channel { false } else { true } }); - for htlc in self.pending_htlcs.iter_mut() { - if htlc.state == HTLCState::LocalAnnounced { - htlc.state = HTLCState::Committed; - } else if htlc.state == HTLCState::AwaitingRemoteRevokeToAnnounce { - htlc.state = HTLCState::AwaitingAnnouncedRemoteRevoke; + for htlc in self.pending_inbound_htlcs.iter_mut() { + if htlc.state == InboundHTLCState::AwaitingRemoteRevokeToAnnounce { + htlc.state = InboundHTLCState::AwaitingAnnouncedRemoteRevoke; require_commitment = true; - } else if htlc.state == HTLCState::AwaitingAnnouncedRemoteRevoke { + } else if htlc.state == InboundHTLCState::AwaitingAnnouncedRemoteRevoke { match htlc.pending_forward_state.take().unwrap() { PendingHTLCStatus::Fail(fail_msg) => { - htlc.state = HTLCState::LocalRemoved; + htlc.state = InboundHTLCState::LocalRemoved; require_commitment = true; - failed_htlcs.push(fail_msg); + match fail_msg { + HTLCFailureMsg::Relay(msg) => update_fail_htlcs.push(msg), + HTLCFailureMsg::Malformed(msg) => update_fail_malformed_htlcs.push(msg), + } }, PendingHTLCStatus::Forward(forward_info) => { to_forward_infos.push(forward_info); - htlc.state = HTLCState::Committed; + htlc.state = InboundHTLCState::Committed; } } - } else if htlc.state == HTLCState::AwaitingRemoteRevokeToRemove { - htlc.state = HTLCState::AwaitingRemovedRemoteRevoke; + } + } + for htlc in self.pending_outbound_htlcs.iter_mut() { + if htlc.state == OutboundHTLCState::LocalAnnounced { + htlc.state = OutboundHTLCState::Committed; + } else if htlc.state == OutboundHTLCState::AwaitingRemoteRevokeToRemove { + htlc.state = OutboundHTLCState::AwaitingRemovedRemoteRevoke; require_commitment = true; - } else if htlc.state == HTLCState::LocalRemoved { - assert!(htlc.local_removed_fulfilled); - htlc.state = HTLCState::LocalRemovedAwaitingCommitment; } } self.value_to_self_msat = (self.value_to_self_msat as i64 + value_to_self_msat_diff) as u64; match self.free_holding_cell_htlcs()? { Some(mut commitment_update) => { - commitment_update.0.update_fail_htlcs.reserve(failed_htlcs.len()); - for fail_msg in failed_htlcs.drain(..) { + commitment_update.0.update_fail_htlcs.reserve(update_fail_htlcs.len()); + for fail_msg in update_fail_htlcs.drain(..) { commitment_update.0.update_fail_htlcs.push(fail_msg); } + commitment_update.0.update_fail_malformed_htlcs.reserve(update_fail_malformed_htlcs.len()); + for fail_msg in update_fail_malformed_htlcs.drain(..) { + commitment_update.0.update_fail_malformed_htlcs.push(fail_msg); + } Ok((Some(commitment_update.0), to_forward_infos, revoked_htlcs, commitment_update.1)) }, None => { @@ -1736,7 +1771,8 @@ impl Channel { Ok((Some(msgs::CommitmentUpdate { update_add_htlcs: Vec::new(), update_fulfill_htlcs: Vec::new(), - update_fail_htlcs: failed_htlcs, + update_fail_htlcs, + update_fail_malformed_htlcs, commitment_signed }), to_forward_infos, revoked_htlcs, monitor_update)) } else { @@ -1762,8 +1798,8 @@ impl Channel { self.channel_update_count += 1; return Ok((None, None, Vec::new())); } - for htlc in self.pending_htlcs.iter() { - if htlc.state == HTLCState::RemoteAnnounced { + for htlc in self.pending_inbound_htlcs.iter() { + if htlc.state == InboundHTLCState::RemoteAnnounced { return Err(HandleError{err: "Got shutdown with remote pending HTLCs", action: None}); } } @@ -1789,7 +1825,7 @@ impl Channel { let our_closing_script = self.get_closing_scriptpubkey(); - let (proposed_feerate, proposed_fee, our_sig) = if self.channel_outbound && self.pending_htlcs.is_empty() { + let (proposed_feerate, proposed_fee, our_sig) = if self.channel_outbound && self.pending_inbound_htlcs.is_empty() && self.pending_outbound_htlcs.is_empty() { let mut proposed_feerate = fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Background); if self.feerate_per_kw > proposed_feerate { proposed_feerate = self.feerate_per_kw; @@ -1822,8 +1858,8 @@ impl Channel { _ => true } }); - for htlc in self.pending_htlcs.iter() { - if htlc.state == HTLCState::LocalAnnounced { + for htlc in self.pending_outbound_htlcs.iter() { + if htlc.state == OutboundHTLCState::LocalAnnounced { return Ok((None, None, dropped_outbound_htlcs)); } } @@ -1839,7 +1875,7 @@ impl Channel { self.channel_state |= ChannelState::LocalShutdownSent as u32; self.channel_update_count += 1; - if self.pending_htlcs.is_empty() && self.channel_outbound { + if self.pending_inbound_htlcs.is_empty() && self.pending_outbound_htlcs.is_empty() && self.channel_outbound { // There are no more HTLCs and we're the funder, this means we start the closing_signed // dance with an initial fee proposal! self.last_sent_closing_fee = Some((proposed_feerate.unwrap(), proposed_fee.unwrap())); @@ -1857,7 +1893,7 @@ impl Channel { if self.channel_state & BOTH_SIDES_SHUTDOWN_MASK != BOTH_SIDES_SHUTDOWN_MASK { return Err(HandleError{err: "Remote end sent us a closing_signed before both sides provided a shutdown", action: None}); } - if !self.pending_htlcs.is_empty() { + if !self.pending_inbound_htlcs.is_empty() || !self.pending_outbound_htlcs.is_empty() { return Err(HandleError{err: "Remote end sent us a closing_signed while there were still pending HTLCs", action: None}); } if msg.fee_satoshis > 21000000 * 10000000 { @@ -1878,7 +1914,7 @@ impl Channel { // limits, so check for that case by re-checking the signature here. closing_tx = self.build_closing_transaction(msg.fee_satoshis, true).0; sighash = Message::from_slice(&bip143::SighashComponents::new(&closing_tx).sighash_all(&closing_tx.input[0], &funding_redeemscript, self.channel_value_satoshis)[..]).unwrap(); - secp_call!(self.secp_ctx.verify(&sighash, &msg.signature, &self.their_funding_pubkey.unwrap()), "Invalid closing tx signature from peer"); + secp_call!(self.secp_ctx.verify(&sighash, &msg.signature, &self.their_funding_pubkey.unwrap()), "Invalid closing tx signature from peer", self.channel_id()); }, }; @@ -1987,6 +2023,12 @@ impl Channel { self.channel_value_satoshis } + //TODO: Testing purpose only, should be changed in another way after #81 + #[cfg(test)] + pub fn get_local_keys(&self) -> &ChannelKeys { + &self.local_keys + } + /// Allowed in any state (including after shutdown) pub fn get_channel_update_count(&self) -> u32 { self.channel_update_count @@ -2098,7 +2140,16 @@ impl Channel { if tx.txid() == self.channel_monitor.get_funding_txo().unwrap().txid { let txo_idx = self.channel_monitor.get_funding_txo().unwrap().index as usize; if txo_idx >= tx.output.len() || tx.output[txo_idx].script_pubkey != self.get_funding_redeemscript().to_v0_p2wsh() || - tx.output[txo_idx].value != self.channel_value_satoshis { + tx.output[txo_idx].value != self.channel_value_satoshis { + if self.channel_outbound { + // If we generated the funding transaction and it doesn't match what it + // should, the client is really broken and we should just panic and + // tell them off. That said, because hash collisions happen with high + // probability in fuzztarget mode, if we're fuzzing we just close the + // channel and move on. + #[cfg(not(feature = "fuzztarget"))] + panic!("Client called ChannelManager::funding_transaction_generated with bogus transaction!"); + } self.channel_state = ChannelState::ShutdownComplete as u32; self.channel_update_count += 1; return Err(HandleError{err: "funding tx had wrong script/value", action: Some(ErrorAction::DisconnectPeer{msg: None})}); @@ -2170,7 +2221,7 @@ impl Channel { }) } - pub fn get_accept_channel(&self) -> Result { + pub fn get_accept_channel(&self) -> msgs::AcceptChannel { if self.channel_outbound { panic!("Tried to send accept_channel for an outbound channel?"); } @@ -2183,7 +2234,7 @@ impl Channel { let local_commitment_secret = self.build_local_commitment_secret(self.cur_local_commitment_transaction_number); - Ok(msgs::AcceptChannel { + msgs::AcceptChannel { temporary_channel_id: self.channel_id, dust_limit_satoshis: self.our_dust_limit_satoshis, max_htlc_value_in_flight_msat: Channel::get_our_max_htlc_value_in_flight_msat(self.channel_value_satoshis), @@ -2199,7 +2250,7 @@ impl Channel { htlc_basepoint: PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.htlc_base_key), first_per_commitment_point: PublicKey::from_secret_key(&self.secp_ctx, &local_commitment_secret), shutdown_scriptpubkey: None, - }) + } } fn get_outbound_funding_created_signature(&mut self) -> Result<(Signature, Transaction), HandleError> { @@ -2260,17 +2311,21 @@ impl Channel { /// Gets an UnsignedChannelAnnouncement, as well as a signature covering it using our /// bitcoin_key, if available, for this channel. The channel must be publicly announceable and - /// available for use (have exchanged FundingLocked messages in both directions. Should be used + /// available for use (have exchanged FundingLocked messages in both directions). Should be used /// for both loose and in response to an AnnouncementSignatures message from the remote peer. - /// Note that you can get an announcement for a channel which is closing, though you should - /// likely not announce such a thing. In case its already been announced, a channel_update - /// message can mark the channel disabled. + /// Will only fail if we're not in a state where channel_announcement may be sent (including + /// closing). + /// Note that the "channel must be funded" requirement is stricter than BOLT 7 requires - see + /// https://github.com/lightningnetwork/lightning-rfc/issues/468 pub fn get_channel_announcement(&self, our_node_id: PublicKey, chain_hash: Sha256dHash) -> Result<(msgs::UnsignedChannelAnnouncement, Signature), HandleError> { if !self.announce_publicly { - return Err(HandleError{err: "Channel is not available for public announcements", action: None}); + return Err(HandleError{err: "Channel is not available for public announcements", action: Some(msgs::ErrorAction::IgnoreError)}); } - if self.channel_state & (ChannelState::ChannelFunded as u32) != (ChannelState::ChannelFunded as u32) { - return Err(HandleError{err: "Cannot get a ChannelAnnouncement until the channel funding has been locked", action: None}); + if self.channel_state & (ChannelState::ChannelFunded as u32) == 0 { + return Err(HandleError{err: "Cannot get a ChannelAnnouncement until the channel funding has been locked", action: Some(msgs::ErrorAction::IgnoreError)}); + } + if (self.channel_state & (ChannelState::LocalShutdownSent as u32 | ChannelState::ShutdownComplete as u32)) != 0 { + return Err(HandleError{err: "Cannot get a ChannelAnnouncement once the channel is closing", action: Some(msgs::ErrorAction::IgnoreError)}); } let were_node_one = our_node_id.serialize()[..] < self.their_node_id.serialize()[..]; @@ -2284,6 +2339,7 @@ impl Channel { node_id_2: if were_node_one { self.get_their_node_id() } else { our_node_id }, bitcoin_key_1: if were_node_one { our_bitcoin_key } else { self.their_funding_pubkey.unwrap() }, bitcoin_key_2: if were_node_one { self.their_funding_pubkey.unwrap() } else { our_bitcoin_key }, + excess_data: Vec::new(), }; let msghash = Message::from_slice(&Sha256dHash::from_data(&msg.encode()[..])[..]).unwrap(); @@ -2300,6 +2356,7 @@ impl Channel { /// This returns an option instead of a pure UpdateAddHTLC as we may be in a state where we are /// waiting on the remote peer to send us a revoke_and_ack during which time we cannot add new /// HTLCs on the wire or we wouldn't be able to determine what they actually ACK'ed. + /// You MUST call send_commitment prior to any other calls on this Channel pub fn send_htlc(&mut self, amount_msat: u64, payment_hash: [u8; 32], cltv_expiry: u32, onion_routing_packet: msgs::OnionPacket) -> Result, HandleError> { if (self.channel_state & (ChannelState::ChannelFunded as u32 | BOTH_SIDES_SHUTDOWN_MASK)) != (ChannelState::ChannelFunded as u32) { return Err(HandleError{err: "Cannot send HTLC until channel is fully established and we haven't started shutting down", action: None}); @@ -2341,16 +2398,13 @@ impl Channel { return Ok(None); } - self.pending_htlcs.push(HTLCOutput { - outbound: true, + self.pending_outbound_htlcs.push(OutboundHTLCOutput { htlc_id: self.next_local_htlc_id, amount_msat: amount_msat, payment_hash: payment_hash.clone(), cltv_expiry: cltv_expiry, - state: HTLCState::LocalAnnounced, + state: OutboundHTLCState::LocalAnnounced, fail_reason: None, - local_removed_fulfilled: false, - pending_forward_state: None }); let res = msgs::UpdateAddHTLC { @@ -2367,22 +2421,25 @@ impl Channel { } /// Creates a signed commitment transaction to send to the remote peer. + /// Always returns a Channel-failing HandleError::action if an immediately-preceding (read: the + /// last call to this Channel) send_htlc returned Ok(Some(_)) and there is an Err. + /// May panic if called except immediately after a successful, Ok(Some(_))-returning send_htlc. pub fn send_commitment(&mut self) -> Result<(msgs::CommitmentSigned, ChannelMonitor), HandleError> { if (self.channel_state & (ChannelState::ChannelFunded as u32)) != (ChannelState::ChannelFunded as u32) { - return Err(HandleError{err: "Cannot create commitment tx until channel is fully established", action: None}); + panic!("Cannot create commitment tx until channel is fully established"); } if (self.channel_state & (ChannelState::AwaitingRemoteRevoke as u32)) == (ChannelState::AwaitingRemoteRevoke as u32) { - return Err(HandleError{err: "Cannot create commitment tx until remote revokes their previous commitment", action: None}); + panic!("Cannot create commitment tx until remote revokes their previous commitment"); } let mut have_updates = false; // TODO initialize with "have we sent a fee update?" - for htlc in self.pending_htlcs.iter() { - if htlc.state == HTLCState::LocalAnnounced { + for htlc in self.pending_outbound_htlcs.iter() { + if htlc.state == OutboundHTLCState::LocalAnnounced { have_updates = true; } if have_updates { break; } } if !have_updates { - return Err(HandleError{err: "Cannot create commitment tx until we have some updates to send", action: None}); + panic!("Cannot create commitment tx until we have some updates to send"); } self.send_commitment_no_status_check() } @@ -2393,11 +2450,14 @@ impl Channel { // We can upgrade the status of some HTLCs that are waiting on a commitment, even if we // fail to generate this, we still are at least at a position where upgrading their status // is acceptable. - for htlc in self.pending_htlcs.iter_mut() { - if htlc.state == HTLCState::AwaitingRemoteRevokeToAnnounce { - htlc.state = HTLCState::AwaitingAnnouncedRemoteRevoke; - } else if htlc.state == HTLCState::AwaitingRemoteRevokeToRemove { - htlc.state = HTLCState::AwaitingRemovedRemoteRevoke; + for htlc in self.pending_inbound_htlcs.iter_mut() { + if htlc.state == InboundHTLCState::AwaitingRemoteRevokeToAnnounce { + htlc.state = InboundHTLCState::AwaitingAnnouncedRemoteRevoke; + } + } + for htlc in self.pending_outbound_htlcs.iter_mut() { + if htlc.state == OutboundHTLCState::AwaitingRemoteRevokeToRemove { + htlc.state = OutboundHTLCState::AwaitingRemovedRemoteRevoke; } } @@ -2413,7 +2473,7 @@ impl Channel { let htlc_tx = self.build_htlc_transaction(&remote_commitment_txid, htlc, false, &remote_keys); let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, &remote_keys); let htlc_sighash = Message::from_slice(&bip143::SighashComponents::new(&htlc_tx).sighash_all(&htlc_tx.input[0], &htlc_redeemscript, htlc.amount_msat / 1000)[..]).unwrap(); - let our_htlc_key = secp_derived_key!(chan_utils::derive_private_key(&self.secp_ctx, &remote_keys.per_commitment_point, &self.local_keys.htlc_base_key)); + let our_htlc_key = secp_derived_key!(chan_utils::derive_private_key(&self.secp_ctx, &remote_keys.per_commitment_point, &self.local_keys.htlc_base_key), self.channel_id()); htlc_sigs.push(self.secp_ctx.sign(&htlc_sighash, &our_htlc_key)); } @@ -2445,8 +2505,8 @@ impl Channel { /// Begins the shutdown process, getting a message for the remote peer and returning all /// holding cell HTLCs for payment failure. pub fn get_shutdown(&mut self) -> Result<(msgs::Shutdown, Vec<[u8; 32]>), HandleError> { - for htlc in self.pending_htlcs.iter() { - if htlc.state == HTLCState::LocalAnnounced { + for htlc in self.pending_outbound_htlcs.iter() { + if htlc.state == OutboundHTLCState::LocalAnnounced { return Err(HandleError{err: "Cannot begin shutdown with pending HTLCs, call send_commitment first", action: None}); } } @@ -2505,8 +2565,8 @@ impl Channel { } } - for htlc in self.pending_htlcs.drain(..) { - if htlc.state == HTLCState::LocalAnnounced { + for htlc in self.pending_outbound_htlcs.drain(..) { + if htlc.state == OutboundHTLCState::LocalAnnounced { dropped_outbound_htlcs.push(htlc.payment_hash); } //TODO: Do something with the remaining HTLCs @@ -2530,7 +2590,7 @@ mod tests { use bitcoin::blockdata::script::Script; use bitcoin::blockdata::transaction::Transaction; use hex; - use ln::channel::{Channel,ChannelKeys,HTLCOutput,HTLCState,HTLCOutputInCommitment,TxCreationKeys}; + use ln::channel::{Channel,ChannelKeys,InboundHTLCOutput,OutboundHTLCOutput,InboundHTLCState,OutboundHTLCState,HTLCOutputInCommitment,TxCreationKeys}; use ln::channel::MAX_FUNDING_SATOSHIS; use ln::chan_utils; use chain::chaininterface::{FeeEstimator,ConfirmationTarget}; @@ -2669,15 +2729,13 @@ mod tests { "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b8002c0c62d0000000000160014ccf1af2f2aabee14bb40fa3851ab2301de84311054a56a00000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0400473044022051b75c73198c6deee1a875871c3961832909acd297c6b908d59e3319e5185a46022055c419379c5051a78d00dbbce11b5b664a0c22815fbcc6fcef6b1937c383693901483045022100f51d2e566a70ba740fc5d8c0f07b9b93d2ed741c3c0860c613173de7d39e7968022041376d520e9c0e1ad52248ddf4b22e12be8763007df977253ef45a4ca3bdb7c001475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220"); } - chan.pending_htlcs.push({ - let mut out = HTLCOutput{ + chan.pending_inbound_htlcs.push({ + let mut out = InboundHTLCOutput{ htlc_id: 0, - outbound: false, amount_msat: 1000000, cltv_expiry: 500, payment_hash: [0; 32], - state: HTLCState::Committed, - fail_reason: None, + state: InboundHTLCState::Committed, local_removed_fulfilled: false, pending_forward_state: None, }; @@ -2686,15 +2744,13 @@ mod tests { sha.result(&mut out.payment_hash); out }); - chan.pending_htlcs.push({ - let mut out = HTLCOutput{ + chan.pending_inbound_htlcs.push({ + let mut out = InboundHTLCOutput{ htlc_id: 1, - outbound: false, amount_msat: 2000000, cltv_expiry: 501, payment_hash: [0; 32], - state: HTLCState::Committed, - fail_reason: None, + state: InboundHTLCState::Committed, local_removed_fulfilled: false, pending_forward_state: None, }; @@ -2703,49 +2759,41 @@ mod tests { sha.result(&mut out.payment_hash); out }); - chan.pending_htlcs.push({ - let mut out = HTLCOutput{ + chan.pending_outbound_htlcs.push({ + let mut out = OutboundHTLCOutput{ htlc_id: 2, - outbound: true, amount_msat: 2000000, cltv_expiry: 502, payment_hash: [0; 32], - state: HTLCState::Committed, + state: OutboundHTLCState::Committed, fail_reason: None, - local_removed_fulfilled: false, - pending_forward_state: None, }; let mut sha = Sha256::new(); sha.input(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()); sha.result(&mut out.payment_hash); out }); - chan.pending_htlcs.push({ - let mut out = HTLCOutput{ + chan.pending_outbound_htlcs.push({ + let mut out = OutboundHTLCOutput{ htlc_id: 3, - outbound: true, amount_msat: 3000000, cltv_expiry: 503, payment_hash: [0; 32], - state: HTLCState::Committed, + state: OutboundHTLCState::Committed, fail_reason: None, - local_removed_fulfilled: false, - pending_forward_state: None, }; let mut sha = Sha256::new(); sha.input(&hex::decode("0303030303030303030303030303030303030303030303030303030303030303").unwrap()); sha.result(&mut out.payment_hash); out }); - chan.pending_htlcs.push({ - let mut out = HTLCOutput{ + chan.pending_inbound_htlcs.push({ + let mut out = InboundHTLCOutput{ htlc_id: 4, - outbound: false, amount_msat: 4000000, cltv_expiry: 504, payment_hash: [0; 32], - state: HTLCState::Committed, - fail_reason: None, + state: InboundHTLCState::Committed, local_removed_fulfilled: false, pending_forward_state: None, };