Skip to content

Commit 9e30f25

Browse files
committed
Stop sending channel_update in onion failures
Per <lightning/bolts#1173>. Fixes #3277
1 parent c7627df commit 9e30f25

File tree

4 files changed

+70
-143
lines changed

4 files changed

+70
-143
lines changed

lightning/src/ln/channel.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2142,6 +2142,14 @@ impl<SP: Deref> ChannelContext<SP> where SP::Target: SignerProvider {
21422142
self.is_usable() && !self.channel_state.is_peer_disconnected()
21432143
}
21442144

2145+
/// Returns false if our last broadcasted channel_update message has the "channel disabled" bit set
2146+
pub fn is_enabled(&self) -> bool {
2147+
self.is_usable() && match self.channel_update_status {
2148+
ChannelUpdateStatus::Enabled | ChannelUpdateStatus::DisabledStaged(_) => true,
2149+
ChannelUpdateStatus::Disabled | ChannelUpdateStatus::EnabledStaged(_) => false,
2150+
}
2151+
}
2152+
21452153
// Public utilities:
21462154

21472155
pub fn channel_id(&self) -> ChannelId {

lightning/src/ln/channelmanager.rs

Lines changed: 52 additions & 105 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,6 @@ use crate::ln::msgs::{ChannelMessageHandler, DecodeError, LightningError};
6262
#[cfg(test)]
6363
use crate::ln::outbound_payment;
6464
use crate::ln::outbound_payment::{OutboundPayments, PendingOutboundPayment, RetryableInvoiceRequest, SendAlongPathArgs, StaleExpiration};
65-
use crate::ln::wire::Encode;
6665
use crate::offers::invoice::{Bolt12Invoice, DEFAULT_RELATIVE_EXPIRY, DerivedSigningPubkey, ExplicitSigningPubkey, InvoiceBuilder, UnsignedBolt12Invoice};
6766
use crate::offers::invoice_error::InvoiceError;
6867
use crate::offers::invoice_request::{DerivedPayerSigningPubkey, InvoiceRequest, InvoiceRequestBuilder};
@@ -677,7 +676,7 @@ pub enum FailureCode {
677676
}
678677

679678
impl Into<u16> for FailureCode {
680-
fn into(self) -> u16 {
679+
fn into(self) -> u16 {
681680
match self {
682681
FailureCode::TemporaryNodeFailure => 0x2000 | 2,
683682
FailureCode::RequiredNodeFeatureMissing => 0x4000 | 0x2000 | 3,
@@ -3841,43 +3840,39 @@ where
38413840

38423841
fn can_forward_htlc_to_outgoing_channel(
38433842
&self, chan: &mut Channel<SP>, msg: &msgs::UpdateAddHTLC, next_packet: &NextPacketDetails
3844-
) -> Result<(), (&'static str, u16, Option<msgs::ChannelUpdate>)> {
3843+
) -> Result<(), (&'static str, u16)> {
38453844
if !chan.context.should_announce() && !self.default_configuration.accept_forwards_to_priv_channels {
38463845
// Note that the behavior here should be identical to the above block - we
38473846
// should NOT reveal the existence or non-existence of a private channel if
38483847
// we don't allow forwards outbound over them.
3849-
return Err(("Refusing to forward to a private channel based on our config.", 0x4000 | 10, None));
3848+
return Err(("Refusing to forward to a private channel based on our config.", 0x4000 | 10));
38503849
}
38513850
if chan.context.get_channel_type().supports_scid_privacy() && next_packet.outgoing_scid != chan.context.outbound_scid_alias() {
38523851
// `option_scid_alias` (referred to in LDK as `scid_privacy`) means
38533852
// "refuse to forward unless the SCID alias was used", so we pretend
38543853
// we don't have the channel here.
3855-
return Err(("Refusing to forward over real channel SCID as our counterparty requested.", 0x4000 | 10, None));
3854+
return Err(("Refusing to forward over real channel SCID as our counterparty requested.", 0x4000 | 10));
38563855
}
38573856

38583857
// Note that we could technically not return an error yet here and just hope
38593858
// that the connection is reestablished or monitor updated by the time we get
38603859
// around to doing the actual forward, but better to fail early if we can and
38613860
// hopefully an attacker trying to path-trace payments cannot make this occur
38623861
// on a small/per-node/per-channel scale.
3863-
if !chan.context.is_live() { // channel_disabled
3864-
// If the channel_update we're going to return is disabled (i.e. the
3865-
// peer has been disabled for some time), return `channel_disabled`,
3866-
// otherwise return `temporary_channel_failure`.
3867-
let chan_update_opt = self.get_channel_update_for_onion(next_packet.outgoing_scid, chan).ok();
3868-
if chan_update_opt.as_ref().map(|u| u.contents.channel_flags & 2 == 2).unwrap_or(false) {
3869-
return Err(("Forwarding channel has been disconnected for some time.", 0x1000 | 20, chan_update_opt));
3862+
if !chan.context.is_live() {
3863+
if !chan.context.is_enabled() {
3864+
// channel_disabled
3865+
return Err(("Forwarding channel has been disconnected for some time.", 0x1000 | 20));
38703866
} else {
3871-
return Err(("Forwarding channel is not in a ready state.", 0x1000 | 7, chan_update_opt));
3867+
// temporary_channel_failure
3868+
return Err(("Forwarding channel is not in a ready state.", 0x1000 | 7));
38723869
}
38733870
}
38743871
if next_packet.outgoing_amt_msat < chan.context.get_counterparty_htlc_minimum_msat() { // amount_below_minimum
3875-
let chan_update_opt = self.get_channel_update_for_onion(next_packet.outgoing_scid, chan).ok();
3876-
return Err(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, chan_update_opt));
3872+
return Err(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11));
38773873
}
38783874
if let Err((err, code)) = chan.htlc_satisfies_config(msg, next_packet.outgoing_amt_msat, next_packet.outgoing_cltv_value) {
3879-
let chan_update_opt = self.get_channel_update_for_onion(next_packet.outgoing_scid, chan).ok();
3880-
return Err((err, code, chan_update_opt));
3875+
return Err((err, code));
38813876
}
38823877

38833878
Ok(())
@@ -3909,7 +3904,7 @@ where
39093904

39103905
fn can_forward_htlc(
39113906
&self, msg: &msgs::UpdateAddHTLC, next_packet_details: &NextPacketDetails
3912-
) -> Result<(), (&'static str, u16, Option<msgs::ChannelUpdate>)> {
3907+
) -> Result<(), (&'static str, u16)> {
39133908
match self.do_funded_channel_callback(next_packet_details.outgoing_scid, |chan: &mut Channel<SP>| {
39143909
self.can_forward_htlc_to_outgoing_channel(chan, msg, next_packet_details)
39153910
}) {
@@ -3922,7 +3917,7 @@ where
39223917
fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, next_packet_details.outgoing_scid, &self.chain_hash)) ||
39233918
fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, next_packet_details.outgoing_scid, &self.chain_hash)
39243919
{} else {
3925-
return Err(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
3920+
return Err(("Don't have available channel for forwarding as requested.", 0x4000 | 10));
39263921
}
39273922
}
39283923
}
@@ -3931,23 +3926,20 @@ where
39313926
if let Err((err_msg, err_code)) = check_incoming_htlc_cltv(
39323927
cur_height, next_packet_details.outgoing_cltv_value, msg.cltv_expiry
39333928
) {
3934-
let chan_update_opt = self.do_funded_channel_callback(next_packet_details.outgoing_scid, |chan: &mut Channel<SP>| {
3935-
self.get_channel_update_for_onion(next_packet_details.outgoing_scid, chan).ok()
3936-
}).flatten();
3937-
return Err((err_msg, err_code, chan_update_opt));
3929+
return Err((err_msg, err_code));
39383930
}
39393931

39403932
Ok(())
39413933
}
39423934

39433935
fn htlc_failure_from_update_add_err(
39443936
&self, msg: &msgs::UpdateAddHTLC, counterparty_node_id: &PublicKey, err_msg: &'static str,
3945-
mut err_code: u16, chan_update: Option<msgs::ChannelUpdate>, is_intro_node_blinded_forward: bool,
3937+
err_code: u16, is_intro_node_blinded_forward: bool,
39463938
shared_secret: &[u8; 32]
39473939
) -> HTLCFailureMsg {
3948-
let mut res = VecWriter(Vec::with_capacity(chan_update.serialized_length() + 2 + 8 + 2));
3949-
if chan_update.is_some() && err_code & 0x1000 == 0x1000 {
3950-
let chan_update = chan_update.unwrap();
3940+
// at capacity, we write fields `htlc_msat` and `len`
3941+
let mut res = VecWriter(Vec::with_capacity(8 + 2));
3942+
if err_code & 0x1000 == 0x1000 {
39513943
if err_code == 0x1000 | 11 || err_code == 0x1000 | 12 {
39523944
msg.amount_msat.write(&mut res).expect("Writes cannot fail");
39533945
}
@@ -3958,15 +3950,8 @@ where
39583950
// TODO: underspecified, follow https://github.com/lightning/bolts/issues/791
39593951
0u16.write(&mut res).expect("Writes cannot fail");
39603952
}
3961-
(chan_update.serialized_length() as u16 + 2).write(&mut res).expect("Writes cannot fail");
3962-
msgs::ChannelUpdate::TYPE.write(&mut res).expect("Writes cannot fail");
3963-
chan_update.write(&mut res).expect("Writes cannot fail");
3964-
} else if err_code & 0x1000 == 0x1000 {
3965-
// If we're trying to return an error that requires a `channel_update` but
3966-
// we're forwarding to a phantom or intercept "channel" (i.e. cannot
3967-
// generate an update), just use the generic "temporary_node_failure"
3968-
// instead.
3969-
err_code = 0x2000 | 2;
3953+
// See https://github.com/lightning/bolts/blob/247e83d/04-onion-routing.md?plain=1#L1414-L1415
3954+
(0u16).write(&mut res).expect("Writes cannot fail");
39703955
}
39713956

39723957
log_info!(
@@ -4014,9 +3999,9 @@ where
40143999
// Perform outbound checks here instead of in [`Self::construct_pending_htlc_info`] because we
40154000
// can't hold the outbound peer state lock at the same time as the inbound peer state lock.
40164001
self.can_forward_htlc(&msg, &next_packet_details).map_err(|e| {
4017-
let (err_msg, err_code, chan_update_opt) = e;
4002+
let (err_msg, err_code) = e;
40184003
self.htlc_failure_from_update_add_err(
4019-
msg, counterparty_node_id, err_msg, err_code, chan_update_opt,
4004+
msg, counterparty_node_id, err_msg, err_code,
40204005
next_hop.is_intro_node_blinded_forward(), &shared_secret
40214006
)
40224007
})?;
@@ -4125,20 +4110,10 @@ where
41254110
Some(id) => id,
41264111
};
41274112

4128-
self.get_channel_update_for_onion(short_channel_id, chan)
4129-
}
4130-
4131-
fn get_channel_update_for_onion(&self, short_channel_id: u64, chan: &Channel<SP>) -> Result<msgs::ChannelUpdate, LightningError> {
41324113
let logger = WithChannelContext::from(&self.logger, &chan.context, None);
41334114
log_trace!(logger, "Generating channel update for channel {}", chan.context.channel_id());
41344115
let were_node_one = self.our_network_pubkey.serialize()[..] < chan.context.get_counterparty_node_id().serialize()[..];
4135-
4136-
let enabled = chan.context.is_usable() && match chan.channel_update_status() {
4137-
ChannelUpdateStatus::Enabled => true,
4138-
ChannelUpdateStatus::DisabledStaged(_) => true,
4139-
ChannelUpdateStatus::Disabled => false,
4140-
ChannelUpdateStatus::EnabledStaged(_) => false,
4141-
};
4116+
let enabled = chan.context.is_enabled();
41424117

41434118
let unsigned = msgs::UnsignedChannelUpdate {
41444119
chain_hash: self.chain_hash,
@@ -5326,16 +5301,9 @@ where
53265301
}) {
53275302
Some(Ok(_)) => {},
53285303
Some(Err((err, code))) => {
5329-
let outgoing_chan_update_opt = if let Some(outgoing_scid) = outgoing_scid_opt.as_ref() {
5330-
self.do_funded_channel_callback(*outgoing_scid, |chan: &mut Channel<SP>| {
5331-
self.get_channel_update_for_onion(*outgoing_scid, chan).ok()
5332-
}).flatten()
5333-
} else {
5334-
None
5335-
};
53365304
let htlc_fail = self.htlc_failure_from_update_add_err(
53375305
&update_add_htlc, &incoming_counterparty_node_id, err, code,
5338-
outgoing_chan_update_opt, is_intro_node_blinded_forward, &shared_secret,
5306+
is_intro_node_blinded_forward, &shared_secret,
53395307
);
53405308
let htlc_destination = get_failed_htlc_destination(outgoing_scid_opt, update_add_htlc.payment_hash);
53415309
htlc_fails.push((htlc_fail, htlc_destination));
@@ -5347,12 +5315,12 @@ where
53475315

53485316
// Now process the HTLC on the outgoing channel if it's a forward.
53495317
if let Some(next_packet_details) = next_packet_details_opt.as_ref() {
5350-
if let Err((err, code, chan_update_opt)) = self.can_forward_htlc(
5318+
if let Err((err, code)) = self.can_forward_htlc(
53515319
&update_add_htlc, next_packet_details
53525320
) {
53535321
let htlc_fail = self.htlc_failure_from_update_add_err(
53545322
&update_add_htlc, &incoming_counterparty_node_id, err, code,
5355-
chan_update_opt, is_intro_node_blinded_forward, &shared_secret,
5323+
is_intro_node_blinded_forward, &shared_secret,
53565324
);
53575325
let htlc_destination = get_failed_htlc_destination(outgoing_scid_opt, update_add_htlc.payment_hash);
53585326
htlc_fails.push((htlc_fail, htlc_destination));
@@ -5633,7 +5601,8 @@ where
56335601
}
56345602

56355603
if let Some(ChannelPhase::Funded(ref mut chan)) = peer_state.channel_by_id.get_mut(&forward_chan_id) {
5636-
let (failure_code, data) = self.get_htlc_temp_fail_err_and_data(0x1000|7, short_chan_id, chan);
5604+
let failure_code = 0x1000|7;
5605+
let data = self.get_htlc_inbound_temp_fail_data(failure_code);
56375606
failed_forwards.push((htlc_source, payment_hash,
56385607
HTLCFailReason::reason(failure_code, data),
56395608
HTLCDestination::NextHopChannel { node_id: Some(chan.context.get_counterparty_node_id()), channel_id: forward_chan_id }
@@ -6448,46 +6417,21 @@ where
64486417
///
64496418
/// This is for failures on the channel on which the HTLC was *received*, not failures
64506419
/// forwarding
6451-
fn get_htlc_inbound_temp_fail_err_and_data(&self, desired_err_code: u16, chan: &Channel<SP>) -> (u16, Vec<u8>) {
6452-
// We can't be sure what SCID was used when relaying inbound towards us, so we have to
6453-
// guess somewhat. If its a public channel, we figure best to just use the real SCID (as
6454-
// we're not leaking that we have a channel with the counterparty), otherwise we try to use
6455-
// an inbound SCID alias before the real SCID.
6456-
let scid_pref = if chan.context.should_announce() {
6457-
chan.context.get_short_channel_id().or(chan.context.latest_inbound_scid_alias())
6458-
} else {
6459-
chan.context.latest_inbound_scid_alias().or(chan.context.get_short_channel_id())
6460-
};
6461-
if let Some(scid) = scid_pref {
6462-
self.get_htlc_temp_fail_err_and_data(desired_err_code, scid, chan)
6463-
} else {
6464-
(0x4000|10, Vec::new())
6465-
}
6466-
}
6467-
6468-
6469-
/// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code
6470-
/// that we want to return and a channel.
6471-
fn get_htlc_temp_fail_err_and_data(&self, desired_err_code: u16, scid: u64, chan: &Channel<SP>) -> (u16, Vec<u8>) {
6472-
debug_assert_eq!(desired_err_code & 0x1000, 0x1000);
6473-
if let Ok(upd) = self.get_channel_update_for_onion(scid, chan) {
6474-
let mut enc = VecWriter(Vec::with_capacity(upd.serialized_length() + 6));
6475-
if desired_err_code == 0x1000 | 20 {
6476-
// No flags for `disabled_flags` are currently defined so they're always two zero bytes.
6477-
// See https://github.com/lightning/bolts/blob/341ec84/04-onion-routing.md?plain=1#L1008
6478-
0u16.write(&mut enc).expect("Writes cannot fail");
6479-
}
6480-
(upd.serialized_length() as u16 + 2).write(&mut enc).expect("Writes cannot fail");
6481-
msgs::ChannelUpdate::TYPE.write(&mut enc).expect("Writes cannot fail");
6482-
upd.write(&mut enc).expect("Writes cannot fail");
6483-
(desired_err_code, enc.0)
6484-
} else {
6485-
// If we fail to get a unicast channel_update, it implies we don't yet have an SCID,
6486-
// which means we really shouldn't have gotten a payment to be forwarded over this
6487-
// channel yet, or if we did it's from a route hint. Either way, returning an error of
6488-
// PERM|no_such_channel should be fine.
6489-
(0x4000|10, Vec::new())
6490-
}
6420+
fn get_htlc_inbound_temp_fail_data(&self, err_code: u16) -> Vec<u8> {
6421+
debug_assert_eq!(err_code & 0x1000, 0x1000);
6422+
debug_assert_ne!(err_code, 0x1000|11);
6423+
debug_assert_ne!(err_code, 0x1000|12);
6424+
debug_assert_ne!(err_code, 0x1000|13);
6425+
// at capacity, we write fields `disabled_flags` and `len`
6426+
let mut enc = VecWriter(Vec::with_capacity(4));
6427+
if err_code == 0x1000 | 20 {
6428+
// No flags for `disabled_flags` are currently defined so they're always two zero bytes.
6429+
// See https://github.com/lightning/bolts/blob/341ec84/04-onion-routing.md?plain=1#L1008
6430+
0u16.write(&mut enc).expect("Writes cannot fail");
6431+
}
6432+
// See https://github.com/lightning/bolts/blob/247e83d/04-onion-routing.md?plain=1#L1414-L1415
6433+
(0u16).write(&mut enc).expect("Writes cannot fail");
6434+
enc.0
64916435
}
64926436

64936437
// Fail a list of HTLCs that were just freed from the holding cell. The HTLCs need to be
@@ -6504,8 +6448,10 @@ where
65046448
let peer_state = &mut *peer_state_lock;
65056449
match peer_state.channel_by_id.entry(channel_id) {
65066450
hash_map::Entry::Occupied(chan_phase_entry) => {
6507-
if let ChannelPhase::Funded(chan) = chan_phase_entry.get() {
6508-
self.get_htlc_inbound_temp_fail_err_and_data(0x1000|7, &chan)
6451+
if let ChannelPhase::Funded(_chan) = chan_phase_entry.get() {
6452+
let failure_code = 0x1000|7;
6453+
let data = self.get_htlc_inbound_temp_fail_data(failure_code);
6454+
(failure_code, data)
65096455
} else {
65106456
// We shouldn't be trying to fail holding cell HTLCs on an unfunded channel.
65116457
debug_assert!(false);
@@ -8164,8 +8110,8 @@ where
81648110
let reason = if routing.blinded_failure().is_some() {
81658111
HTLCFailReason::reason(INVALID_ONION_BLINDING, vec![0; 32])
81668112
} else if (error_code & 0x1000) != 0 {
8167-
let (real_code, error_data) = self.get_htlc_inbound_temp_fail_err_and_data(error_code, chan);
8168-
HTLCFailReason::reason(real_code, error_data)
8113+
let error_data = self.get_htlc_inbound_temp_fail_data(error_code);
8114+
HTLCFailReason::reason(error_code, error_data)
81698115
} else {
81708116
HTLCFailReason::from_failure_code(error_code)
81718117
}.get_encrypted_failure_packet(incoming_shared_secret, &None);
@@ -10190,7 +10136,8 @@ where
1019010136
let res = f(channel);
1019110137
if let Ok((channel_ready_opt, mut timed_out_pending_htlcs, announcement_sigs)) = res {
1019210138
for (source, payment_hash) in timed_out_pending_htlcs.drain(..) {
10193-
let (failure_code, data) = self.get_htlc_inbound_temp_fail_err_and_data(0x1000|14 /* expiry_too_soon */, &channel);
10139+
let failure_code = 0x1000|14; /* expiry_too_soon */
10140+
let data = self.get_htlc_inbound_temp_fail_data(failure_code);
1019410141
timed_out_htlcs.push((source, payment_hash, HTLCFailReason::reason(failure_code, data),
1019510142
HTLCDestination::NextHopChannel { node_id: Some(channel.context.get_counterparty_node_id()), channel_id: channel.context.channel_id() }));
1019610143
}

lightning/src/ln/onion_route_tests.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1397,9 +1397,12 @@ fn test_phantom_failure_modified_cltv() {
13971397
commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
13981398

13991399
// Ensure the payment fails with the expected error.
1400+
let mut err_data = Vec::new();
1401+
err_data.extend_from_slice(&update_add.cltv_expiry.to_be_bytes());
1402+
err_data.extend_from_slice(&0u16.to_be_bytes());
14001403
let mut fail_conditions = PaymentFailedConditions::new()
14011404
.blamed_scid(phantom_scid)
1402-
.expected_htlc_error_data(0x2000 | 2, &[]);
1405+
.expected_htlc_error_data(0x1000 | 13, &err_data);
14031406
expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
14041407
}
14051408

@@ -1437,9 +1440,10 @@ fn test_phantom_failure_expires_too_soon() {
14371440
commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
14381441

14391442
// Ensure the payment fails with the expected error.
1443+
let err_data = 0u16.to_be_bytes();
14401444
let mut fail_conditions = PaymentFailedConditions::new()
14411445
.blamed_scid(phantom_scid)
1442-
.expected_htlc_error_data(0x2000 | 2, &[]);
1446+
.expected_htlc_error_data(0x1000 | 14, &err_data);
14431447
expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
14441448
}
14451449

@@ -1535,11 +1539,7 @@ fn do_test_phantom_dust_exposure_failure(multiplier_dust_limit: bool) {
15351539
commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
15361540

15371541
// Ensure the payment fails with the expected error.
1538-
let mut err_data = Vec::new();
1539-
err_data.extend_from_slice(&(channel.1.serialized_length() as u16 + 2).to_be_bytes());
1540-
err_data.extend_from_slice(&ChannelUpdate::TYPE.to_be_bytes());
1541-
err_data.extend_from_slice(&channel.1.encode());
1542-
1542+
let err_data = 0u16.to_be_bytes();
15431543
let mut fail_conditions = PaymentFailedConditions::new()
15441544
.blamed_scid(route.paths[0].hops.last().as_ref().unwrap().short_channel_id)
15451545
.blamed_chan_closed(false)

0 commit comments

Comments
 (0)