X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=lightning%2Fsrc%2Fln%2Fonion_utils.rs;h=ebcf83bd90dc2d0db68c5300e50cf2f6b06dd718;hb=adc1b55a6fa064852d838ceb91b11e6b228d169e;hp=6f85e2db8d60f2684bc867bb5636cfa22b00f168;hpb=52edb351575ec997c414a66df0142f46a39aeba3;p=rust-lightning diff --git a/lightning/src/ln/onion_utils.rs b/lightning/src/ln/onion_utils.rs index 6f85e2db..ebcf83bd 100644 --- a/lightning/src/ln/onion_utils.rs +++ b/lightning/src/ln/onion_utils.rs @@ -7,15 +7,15 @@ // You may not use this file except in accordance with one or both of these // licenses. -use crate::ln::{PaymentHash, PaymentPreimage, PaymentSecret}; -use crate::ln::channelmanager::HTLCSource; +use crate::ln::{PaymentHash, PaymentPreimage}; +use crate::ln::channelmanager::{HTLCSource, RecipientOnionFields}; use crate::ln::msgs; use crate::ln::wire::Encode; use crate::routing::gossip::NetworkUpdate; -use crate::routing::router::RouteHop; +use crate::routing::router::{Path, RouteHop}; use crate::util::chacha20::{ChaCha20, ChaChaReader}; use crate::util::errors::{self, APIError}; -use crate::util::ser::{Readable, ReadableArgs, Writeable, LengthCalculatingWriter}; +use crate::util::ser::{Readable, ReadableArgs, Writeable, Writer, LengthCalculatingWriter}; use crate::util::logger::Logger; use bitcoin::hashes::{Hash, HashEngine}; @@ -128,10 +128,10 @@ pub(super) fn construct_onion_keys_callback(secp_ctx: &Secp256k1, path: &Vec, session_priv: &SecretKey) -> Result, secp256k1::Error> { - let mut res = Vec::with_capacity(path.len()); +pub(super) fn construct_onion_keys(secp_ctx: &Secp256k1, path: &Path, session_priv: &SecretKey) -> Result, secp256k1::Error> { + let mut res = Vec::with_capacity(path.hops.len()); - construct_onion_keys_callback(secp_ctx, path, session_priv, |shared_secret, _blinding_factor, ephemeral_pubkey, _, _| { + construct_onion_keys_callback(secp_ctx, &path.hops, session_priv, |shared_secret, _blinding_factor, ephemeral_pubkey, _, _| { let (rho, mu) = gen_rho_mu_from_shared_secret(shared_secret.as_ref()); res.push(OnionKeys { @@ -149,13 +149,13 @@ pub(super) fn construct_onion_keys(secp_ctx: &Secp256k1, total_msat: u64, payment_secret_option: &Option, starting_htlc_offset: u32, keysend_preimage: &Option) -> Result<(Vec, u64, u32), APIError> { +pub(super) fn build_onion_payloads(path: &Path, total_msat: u64, mut recipient_onion: RecipientOnionFields, starting_htlc_offset: u32, keysend_preimage: &Option) -> Result<(Vec, u64, u32), APIError> { let mut cur_value_msat = 0u64; let mut cur_cltv = starting_htlc_offset; let mut last_short_channel_id = 0; - let mut res: Vec = Vec::with_capacity(path.len()); + let mut res: Vec = Vec::with_capacity(path.hops.len()); - for (idx, hop) in path.iter().rev().enumerate() { + for (idx, hop) in path.hops.iter().rev().enumerate() { // First hop gets special values so that it can check, on receipt, that everything is // exactly as it should be (and the next hop isn't trying to probe to find out if we're // the intended recipient). @@ -164,12 +164,13 @@ pub(super) fn build_onion_payloads(path: &Vec, total_msat: u64, paymen res.insert(0, msgs::OnionHopData { format: if idx == 0 { msgs::OnionHopDataFormat::FinalNode { - payment_data: if let &Some(ref payment_secret) = payment_secret_option { + payment_data: if let Some(secret) = recipient_onion.payment_secret.take() { Some(msgs::FinalOnionHopData { - payment_secret: payment_secret.clone(), + payment_secret: secret, total_msat, }) } else { None }, + payment_metadata: recipient_onion.payment_metadata.take(), keysend_preimage: *keysend_preimage, } } else { @@ -182,11 +183,11 @@ pub(super) fn build_onion_payloads(path: &Vec, total_msat: u64, paymen }); cur_value_msat += hop.fee_msat; if cur_value_msat >= 21000000 * 100000000 * 1000 { - return Err(APIError::InvalidRoute{err: "Channel fees overflowed?"}); + return Err(APIError::InvalidRoute{err: "Channel fees overflowed?".to_owned()}); } cur_cltv += hop.cltv_expiry_delta as u32; if cur_cltv >= 500000000 { - return Err(APIError::InvalidRoute{err: "Channel CLTV overflowed?"}); + return Err(APIError::InvalidRoute{err: "Channel CLTV overflowed?".to_owned()}); } last_short_channel_id = hop.short_channel_id; } @@ -382,7 +383,7 @@ pub(super) fn build_failure_packet(shared_secret: &[u8], failure_type: u16, fail packet } -#[inline] +#[cfg(test)] pub(super) fn build_first_hop_failure_packet(shared_secret: &[u8], failure_type: u16, failure_data: &[u8]) -> msgs::OnionErrorPacket { let failure_packet = build_failure_packet(shared_secret, failure_type, failure_data); encrypt_failure_packet(shared_secret, &failure_packet.encode()[..]) @@ -402,7 +403,7 @@ pub(super) fn process_onion_failure(secp_ctx: & let mut is_from_final_node = false; // Handle packed channel/node updates for passing back for the route handler - construct_onion_keys_callback(secp_ctx, path, session_priv, |shared_secret, _, _, route_hop, route_hop_idx| { + construct_onion_keys_callback(secp_ctx, &path.hops, session_priv, |shared_secret, _, _, route_hop, route_hop_idx| { if res.is_some() { return; } let amt_to_forward = htlc_msat - route_hop.fee_msat; @@ -418,8 +419,8 @@ pub(super) fn process_onion_failure(secp_ctx: & // The failing hop includes either the inbound channel to the recipient or the outbound // channel from the current hop (i.e., the next hop's inbound channel). - is_from_final_node = route_hop_idx + 1 == path.len(); - let failing_route_hop = if is_from_final_node { route_hop } else { &path[route_hop_idx + 1] }; + is_from_final_node = route_hop_idx + 1 == path.hops.len(); + let failing_route_hop = if is_from_final_node { route_hop } else { &path.hops[route_hop_idx + 1] }; if let Ok(err_packet) = msgs::DecodedOnionErrorPacket::read(&mut Cursor::new(&packet_decrypted)) { let um = gen_um_from_shared_secret(shared_secret.as_ref()); @@ -492,21 +493,28 @@ pub(super) fn process_onion_failure(secp_ctx: & } else { log_trace!(logger, "Failure provided features a channel update without type prefix. Deprecated, but allowing for now."); } - if let Ok(chan_update) = msgs::ChannelUpdate::read(&mut Cursor::new(&update_slice)) { + let update_opt = msgs::ChannelUpdate::read(&mut Cursor::new(&update_slice)); + if update_opt.is_ok() || update_slice.is_empty() { // if channel_update should NOT have caused the failure: // MAY treat the channel_update as invalid. let is_chan_update_invalid = match error_code & 0xff { 7 => false, - 11 => amt_to_forward > chan_update.contents.htlc_minimum_msat, - 12 => amt_to_forward - .checked_mul(chan_update.contents.fee_proportional_millionths as u64) + 11 => update_opt.is_ok() && + amt_to_forward > + update_opt.as_ref().unwrap().contents.htlc_minimum_msat, + 12 => update_opt.is_ok() && amt_to_forward + .checked_mul(update_opt.as_ref().unwrap() + .contents.fee_proportional_millionths as u64) .map(|prop_fee| prop_fee / 1_000_000) - .and_then(|prop_fee| prop_fee.checked_add(chan_update.contents.fee_base_msat as u64)) + .and_then(|prop_fee| prop_fee.checked_add( + update_opt.as_ref().unwrap().contents.fee_base_msat as u64)) .map(|fee_msats| route_hop.fee_msat >= fee_msats) .unwrap_or(false), - 13 => route_hop.cltv_expiry_delta as u16 >= chan_update.contents.cltv_expiry_delta, + 13 => update_opt.is_ok() && + route_hop.cltv_expiry_delta as u16 >= + update_opt.as_ref().unwrap().contents.cltv_expiry_delta, 14 => false, // expiry_too_soon; always valid? - 20 => chan_update.contents.flags & 2 == 0, + 20 => update_opt.as_ref().unwrap().contents.flags & 2 == 0, _ => false, // unknown error code; take channel_update as valid }; if is_chan_update_invalid { @@ -517,17 +525,31 @@ pub(super) fn process_onion_failure(secp_ctx: & is_permanent: true, }); } else { - // Make sure the ChannelUpdate contains the expected - // short channel id. - if failing_route_hop.short_channel_id == chan_update.contents.short_channel_id { - short_channel_id = Some(failing_route_hop.short_channel_id); + if let Ok(chan_update) = update_opt { + // Make sure the ChannelUpdate contains the expected + // short channel id. + if failing_route_hop.short_channel_id == chan_update.contents.short_channel_id { + short_channel_id = Some(failing_route_hop.short_channel_id); + } else { + log_info!(logger, "Node provided a channel_update for which it was not authoritative, ignoring."); + } + network_update = Some(NetworkUpdate::ChannelUpdateMessage { + msg: chan_update, + }) } else { - log_info!(logger, "Node provided a channel_update for which it was not authoritative, ignoring."); + network_update = Some(NetworkUpdate::ChannelFailure { + short_channel_id: route_hop.short_channel_id, + is_permanent: false, + }); } - network_update = Some(NetworkUpdate::ChannelUpdateMessage { - msg: chan_update, - }) }; + } else { + // If the channel_update had a non-zero length (i.e. was + // present) but we couldn't read it, treat it as a total + // node failure. + log_info!(logger, + "Failed to read a channel_update of len {} in an onion", + update_slice.len()); } } } @@ -592,6 +614,146 @@ pub(super) fn process_onion_failure(secp_ctx: & } else { unreachable!(); } } +#[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug +pub(super) struct HTLCFailReason(HTLCFailReasonRepr); + +#[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug +enum HTLCFailReasonRepr { + LightningError { + err: msgs::OnionErrorPacket, + }, + Reason { + failure_code: u16, + data: Vec, + } +} + +impl core::fmt::Debug for HTLCFailReason { + fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> { + match self.0 { + HTLCFailReasonRepr::Reason { ref failure_code, .. } => { + write!(f, "HTLC error code {}", failure_code) + }, + HTLCFailReasonRepr::LightningError { .. } => { + write!(f, "pre-built LightningError") + } + } + } +} + +impl Writeable for HTLCFailReason { + fn write(&self, writer: &mut W) -> Result<(), crate::io::Error> { + self.0.write(writer) + } +} +impl Readable for HTLCFailReason { + fn read(reader: &mut R) -> Result { + Ok(Self(Readable::read(reader)?)) + } +} + +impl_writeable_tlv_based_enum!(HTLCFailReasonRepr, + (0, LightningError) => { + (0, err, required), + }, + (1, Reason) => { + (0, failure_code, required), + (2, data, vec_type), + }, +;); + +impl HTLCFailReason { + pub(super) fn reason(failure_code: u16, data: Vec) -> Self { + const BADONION: u16 = 0x8000; + const PERM: u16 = 0x4000; + const NODE: u16 = 0x2000; + const UPDATE: u16 = 0x1000; + + if failure_code == 1 | PERM { debug_assert!(data.is_empty()) } + else if failure_code == 2 | NODE { debug_assert!(data.is_empty()) } + else if failure_code == 2 | PERM | NODE { debug_assert!(data.is_empty()) } + else if failure_code == 3 | PERM | NODE { debug_assert!(data.is_empty()) } + else if failure_code == 4 | BADONION | PERM { debug_assert_eq!(data.len(), 32) } + else if failure_code == 5 | BADONION | PERM { debug_assert_eq!(data.len(), 32) } + else if failure_code == 6 | BADONION | PERM { debug_assert_eq!(data.len(), 32) } + else if failure_code == 7 | UPDATE { + debug_assert_eq!(data.len() - 2, u16::from_be_bytes(data[0..2].try_into().unwrap()) as usize) } + else if failure_code == 8 | PERM { debug_assert!(data.is_empty()) } + else if failure_code == 9 | PERM { debug_assert!(data.is_empty()) } + else if failure_code == 10 | PERM { debug_assert!(data.is_empty()) } + else if failure_code == 11 | UPDATE { + debug_assert_eq!(data.len() - 2 - 8, u16::from_be_bytes(data[8..10].try_into().unwrap()) as usize) } + else if failure_code == 12 | UPDATE { + debug_assert_eq!(data.len() - 2 - 8, u16::from_be_bytes(data[8..10].try_into().unwrap()) as usize) } + else if failure_code == 13 | UPDATE { + debug_assert_eq!(data.len() - 2 - 4, u16::from_be_bytes(data[4..6].try_into().unwrap()) as usize) } + else if failure_code == 14 | UPDATE { + debug_assert_eq!(data.len() - 2, u16::from_be_bytes(data[0..2].try_into().unwrap()) as usize) } + else if failure_code == 15 | PERM { debug_assert_eq!(data.len(), 12) } + else if failure_code == 18 { debug_assert_eq!(data.len(), 4) } + else if failure_code == 19 { debug_assert_eq!(data.len(), 8) } + else if failure_code == 20 | UPDATE { + debug_assert_eq!(data.len() - 2 - 2, u16::from_be_bytes(data[2..4].try_into().unwrap()) as usize) } + else if failure_code == 21 { debug_assert!(data.is_empty()) } + else if failure_code == 22 | PERM { debug_assert!(data.len() <= 11) } + else if failure_code == 23 { debug_assert!(data.is_empty()) } + else if failure_code & BADONION != 0 { + // We set some bogus BADONION failure codes in test, so ignore unknown ones. + } + else { debug_assert!(false, "Unknown failure code: {}", failure_code) } + + Self(HTLCFailReasonRepr::Reason { failure_code, data }) + } + + pub(super) fn from_failure_code(failure_code: u16) -> Self { + Self::reason(failure_code, Vec::new()) + } + + pub(super) fn from_msg(msg: &msgs::UpdateFailHTLC) -> Self { + Self(HTLCFailReasonRepr::LightningError { err: msg.reason.clone() }) + } + + pub(super) fn get_encrypted_failure_packet(&self, incoming_packet_shared_secret: &[u8; 32], phantom_shared_secret: &Option<[u8; 32]>) + -> msgs::OnionErrorPacket { + match self.0 { + HTLCFailReasonRepr::Reason { ref failure_code, ref data } => { + if let Some(phantom_ss) = phantom_shared_secret { + let phantom_packet = build_failure_packet(phantom_ss, *failure_code, &data[..]).encode(); + let encrypted_phantom_packet = encrypt_failure_packet(phantom_ss, &phantom_packet); + encrypt_failure_packet(incoming_packet_shared_secret, &encrypted_phantom_packet.data[..]) + } else { + let packet = build_failure_packet(incoming_packet_shared_secret, *failure_code, &data[..]).encode(); + encrypt_failure_packet(incoming_packet_shared_secret, &packet) + } + }, + HTLCFailReasonRepr::LightningError { ref err } => { + encrypt_failure_packet(incoming_packet_shared_secret, &err.data) + } + } + } + + pub(super) fn decode_onion_failure( + &self, secp_ctx: &Secp256k1, logger: &L, htlc_source: &HTLCSource + ) -> (Option, Option, bool, Option, Option>) + where L::Target: Logger { + match self.0 { + HTLCFailReasonRepr::LightningError { ref err } => { + process_onion_failure(secp_ctx, logger, &htlc_source, err.data.clone()) + }, + HTLCFailReasonRepr::Reason { ref failure_code, ref data, .. } => { + // we get a fail_malformed_htlc from the first hop + // TODO: We'd like to generate a NetworkUpdate for temporary + // failures here, but that would be insufficient as find_route + // generally ignores its view of our own channels as we provide them via + // ChannelDetails. + if let &HTLCSource::OutboundRoute { ref path, .. } = htlc_source { + (None, Some(path.hops[0].short_channel_id), true, Some(*failure_code), Some(data.clone())) + } else { unreachable!(); } + } + } + } +} + /// Allows `decode_next_hop` to return the next hop packet bytes for either payments or onion /// message forwards. pub(crate) trait NextPacketBytes: AsMut<[u8]> { @@ -742,7 +904,7 @@ mod tests { use crate::prelude::*; use crate::ln::PaymentHash; use crate::ln::features::{ChannelFeatures, NodeFeatures}; - use crate::routing::router::{Route, RouteHop}; + use crate::routing::router::{Path, Route, RouteHop}; use crate::ln::msgs; use crate::util::ser::{Writeable, Writer, VecWriter}; @@ -762,7 +924,7 @@ mod tests { let secp_ctx = Secp256k1::new(); let route = Route { - paths: vec![vec![ + paths: vec![Path { hops: vec![ RouteHop { pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(), channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(), @@ -788,12 +950,12 @@ mod tests { channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(), short_channel_id: 0, fee_msat: 0, cltv_expiry_delta: 0 // We fill in the payloads manually instead of generating them from RouteHops. }, - ]], + ], blinded_tail: None }], payment_params: None, }; let onion_keys = super::construct_onion_keys(&secp_ctx, &route.paths[0], &get_test_session_key()).unwrap(); - assert_eq!(onion_keys.len(), route.paths[0].len()); + assert_eq!(onion_keys.len(), route.paths[0].hops.len()); onion_keys }