Skip to content

Commit d225630

Browse files
committed
Use the correct SCID when failing HTLCs to aliased channels
When we fail an HTLC which was destined for a channel that the HTLC sender didn't know the real SCID for, we should ensure we continue to use the alias in the channel_update we provide them. Otherwise we will leak the channel's real SCID to HTLC senders.
1 parent 99b7219 commit d225630

File tree

4 files changed

+134
-12
lines changed

4 files changed

+134
-12
lines changed

lightning/src/ln/channelmanager.rs

Lines changed: 35 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2413,7 +2413,6 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
24132413
};
24142414
let (chan_update_opt, forwardee_cltv_expiry_delta) = if let Some(forwarding_id) = forwarding_id_opt {
24152415
let chan = channel_state.as_mut().unwrap().by_id.get_mut(&forwarding_id).unwrap();
2416-
let chan_update_opt = self.get_channel_update_for_broadcast(chan).ok();
24172416
if !chan.should_announce() && !self.default_configuration.accept_forwards_to_priv_channels {
24182417
// Note that the behavior here should be identical to the above block - we
24192418
// should NOT reveal the existence or non-existence of a private channel if
@@ -2426,6 +2425,7 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
24262425
// we don't have the channel here.
24272426
break Some(("Refusing to forward over real channel SCID as our counterparty requested.", 0x4000 | 10, None));
24282427
}
2428+
let chan_update_opt = self.get_channel_update_for_onion(*short_channel_id, chan).ok();
24292429

24302430
// Note that we could technically not return an error yet here and just hope
24312431
// that the connection is reestablished or monitor updated by the time we get
@@ -2525,6 +2525,10 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
25252525
Some(id) => id,
25262526
};
25272527

2528+
self.get_channel_update_for_onion(short_channel_id, chan)
2529+
}
2530+
fn get_channel_update_for_onion(&self, short_channel_id: u64, chan: &Channel<Signer>) -> Result<msgs::ChannelUpdate, LightningError> {
2531+
log_trace!(self.logger, "Generating channel update for channel {}", log_bytes!(chan.channel_id()));
25282532
let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_counterparty_node_id().serialize()[..];
25292533

25302534
let unsigned = msgs::UnsignedChannelUpdate {
@@ -3214,7 +3218,7 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
32143218
} else {
32153219
panic!("Stated return value requirements in send_htlc() were not met");
32163220
}
3217-
let (failure_code, data) = self.get_htlc_temp_fail_err_and_data(0x1000|7, chan.get());
3221+
let (failure_code, data) = self.get_htlc_temp_fail_err_and_data(0x1000|7, short_chan_id, chan.get());
32183222
failed_forwards.push((htlc_source, payment_hash,
32193223
HTLCFailReason::Reason { failure_code, data }
32203224
));
@@ -3714,9 +3718,32 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
37143718

37153719
/// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code
37163720
/// that we want to return and a channel.
3717-
fn get_htlc_temp_fail_err_and_data(&self, desired_err_code: u16, chan: &Channel<Signer>) -> (u16, Vec<u8>) {
3721+
///
3722+
/// This is for failures on the channel on which the HTLC was *received*, not failures
3723+
/// forwarding
3724+
fn get_htlc_inbound_temp_fail_err_and_data(&self, desired_err_code: u16, chan: &Channel<Signer>) -> (u16, Vec<u8>) {
3725+
// We can't be sure what SCID was used when relaying inbound towards us, so we have to
3726+
// guess somewhat. If its a public channel, we figure best to just use the real SCID (as
3727+
// we're not leaking that we have a channel with the counterparty), otherwise we try to use
3728+
// an inbound SCID alias before the real SCID.
3729+
let scid_pref = if chan.should_announce() {
3730+
chan.get_short_channel_id().or(chan.latest_inbound_scid_alias())
3731+
} else {
3732+
chan.latest_inbound_scid_alias().or(chan.get_short_channel_id())
3733+
};
3734+
if let Some(scid) = scid_pref {
3735+
self.get_htlc_temp_fail_err_and_data(desired_err_code, scid, chan)
3736+
} else {
3737+
(0x4000|10, Vec::new())
3738+
}
3739+
}
3740+
3741+
3742+
/// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code
3743+
/// that we want to return and a channel.
3744+
fn get_htlc_temp_fail_err_and_data(&self, desired_err_code: u16, scid: u64, chan: &Channel<Signer>) -> (u16, Vec<u8>) {
37183745
debug_assert_eq!(desired_err_code & 0x1000, 0x1000);
3719-
if let Ok(upd) = self.get_channel_update_for_unicast(chan) {
3746+
if let Ok(upd) = self.get_channel_update_for_onion(scid, chan) {
37203747
let mut enc = VecWriter(Vec::with_capacity(upd.serialized_length() + 4));
37213748
if desired_err_code == 0x1000 | 20 {
37223749
// TODO: underspecified, follow https://github.com/lightning/bolts/issues/791
@@ -3744,7 +3771,7 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
37443771
let (failure_code, onion_failure_data) =
37453772
match self.channel_state.lock().unwrap().by_id.entry(channel_id) {
37463773
hash_map::Entry::Occupied(chan_entry) => {
3747-
self.get_htlc_temp_fail_err_and_data(0x1000|7, &chan_entry.get())
3774+
self.get_htlc_inbound_temp_fail_err_and_data(0x1000|7, &chan_entry.get())
37483775
},
37493776
hash_map::Entry::Vacant(_) => (0x4000|10, Vec::new())
37503777
};
@@ -4634,7 +4661,7 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
46344661
match pending_forward_info {
46354662
PendingHTLCStatus::Forward(PendingHTLCInfo { ref incoming_shared_secret, .. }) => {
46364663
let reason = if (error_code & 0x1000) != 0 {
4637-
let (real_code, error_data) = self.get_htlc_temp_fail_err_and_data(error_code, chan);
4664+
let (real_code, error_data) = self.get_htlc_inbound_temp_fail_err_and_data(error_code, chan);
46384665
onion_utils::build_first_hop_failure_packet(incoming_shared_secret, real_code, &error_data)
46394666
} else {
46404667
onion_utils::build_first_hop_failure_packet(incoming_shared_secret, error_code, &[])
@@ -5627,8 +5654,8 @@ where
56275654
let res = f(channel);
56285655
if let Ok((funding_locked_opt, mut timed_out_pending_htlcs, announcement_sigs)) = res {
56295656
for (source, payment_hash) in timed_out_pending_htlcs.drain(..) {
5630-
let (failure_code, data) = self.get_htlc_temp_fail_err_and_data(0x1000|14 /* expiry_too_soon */, &channel);
5631-
timed_out_htlcs.push((source, payment_hash, HTLCFailReason::Reason {
5657+
let (failure_code, data) = self.get_htlc_inbound_temp_fail_err_and_data(0x1000|14 /* expiry_too_soon */, &channel);
5658+
timed_out_htlcs.push((source, payment_hash, HTLCFailReason::Reason {
56325659
failure_code, data,
56335660
}));
56345661
}

lightning/src/ln/functional_test_utils.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use chain::{BestBlock, Confirm, Listen, Watch, keysinterface::KeysInterface};
1414
use chain::channelmonitor::ChannelMonitor;
1515
use chain::transaction::OutPoint;
1616
use ln::{PaymentPreimage, PaymentHash, PaymentSecret};
17-
use ln::channelmanager::{ChainParameters, ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentSendFailure, PaymentId};
17+
use ln::channelmanager::{ChainParameters, ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentSendFailure, PaymentId, MIN_CLTV_EXPIRY_DELTA};
1818
use routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
1919
use routing::router::{PaymentParameters, Route, get_route};
2020
use ln::features::{InitFeatures, InvoiceFeatures};
@@ -1848,7 +1848,7 @@ pub fn test_default_channel_config() -> UserConfig {
18481848
let mut default_config = UserConfig::default();
18491849
// Set cltv_expiry_delta slightly lower to keep the final CLTV values inside one byte in our
18501850
// tests so that our script-length checks don't fail (see ACCEPTED_HTLC_SCRIPT_WEIGHT).
1851-
default_config.channel_options.cltv_expiry_delta = 6*6;
1851+
default_config.channel_options.cltv_expiry_delta = MIN_CLTV_EXPIRY_DELTA;
18521852
default_config.channel_options.announced_channel = true;
18531853
default_config.peer_channel_config_limits.force_announced_channel_preference = false;
18541854
// When most of our tests were written, the default HTLC minimum was fixed at 1000.

lightning/src/ln/onion_route_tests.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -993,4 +993,3 @@ fn test_phantom_failure_reject_payment() {
993993
.expected_htlc_error_data(0x4000 | 15, &error_data);
994994
expect_payment_failed_conditions!(nodes[0], payment_hash, true, fail_conditions);
995995
}
996-

lightning/src/ln/priv_short_conf_tests.rs

Lines changed: 97 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,13 @@
1313
1414
use chain::Watch;
1515
use chain::channelmonitor::ChannelMonitor;
16+
use chain::keysinterface::{Recipient, KeysInterface};
1617
use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, MIN_CLTV_EXPIRY_DELTA};
1718
use routing::network_graph::RoutingFees;
1819
use routing::router::{RouteHint, RouteHintHop};
1920
use ln::features::InitFeatures;
2021
use ln::msgs;
21-
use ln::msgs::{ChannelMessageHandler, RoutingMessageHandler};
22+
use ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, OptionalField};
2223
use util::enforcing_trait_impls::EnforcingSigner;
2324
use util::events::{Event, MessageSendEvent, MessageSendEventsProvider};
2425
use util::config::UserConfig;
@@ -30,7 +31,12 @@ use core::default::Default;
3031

3132
use ln::functional_test_utils::*;
3233

34+
use bitcoin::blockdata::constants::genesis_block;
3335
use bitcoin::hash_types::BlockHash;
36+
use bitcoin::hashes::Hash;
37+
use bitcoin::hashes::sha256d::Hash as Sha256dHash;
38+
use bitcoin::network::constants::Network;
39+
use bitcoin::secp256k1::Secp256k1;
3440

3541
#[test]
3642
fn test_priv_forwarding_rejection() {
@@ -445,3 +451,93 @@ fn test_inbound_scid_privacy() {
445451
PaymentFailedConditions::new().blamed_scid(last_hop[0].short_channel_id.unwrap())
446452
.blamed_chan_closed(true).expected_htlc_error_data(0x4000|10, &[0; 0]));
447453
}
454+
455+
#[test]
456+
fn test_scid_alias_returned() {
457+
// Tests that when we fail an HTLC (in this case due to attempting to forward more than the
458+
// channel's available balance) we use the correct (in this case the aliased) SCID in the
459+
// channel_update which is returned in the onion to the sender.
460+
let chanmon_cfgs = create_chanmon_cfgs(3);
461+
let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
462+
let mut accept_forward_cfg = test_default_channel_config();
463+
accept_forward_cfg.accept_forwards_to_priv_channels = true;
464+
let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(accept_forward_cfg), None]);
465+
let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
466+
467+
create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0, InitFeatures::known(), InitFeatures::known());
468+
create_unannounced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000, 0, InitFeatures::known(), InitFeatures::known());
469+
470+
let last_hop = nodes[2].node.list_usable_channels();
471+
let mut hop_hints = vec![RouteHint(vec![RouteHintHop {
472+
src_node_id: nodes[1].node.get_our_node_id(),
473+
short_channel_id: last_hop[0].inbound_scid_alias.unwrap(),
474+
fees: RoutingFees {
475+
base_msat: last_hop[0].counterparty.forwarding_info.as_ref().unwrap().fee_base_msat,
476+
proportional_millionths: last_hop[0].counterparty.forwarding_info.as_ref().unwrap().fee_proportional_millionths,
477+
},
478+
cltv_expiry_delta: last_hop[0].counterparty.forwarding_info.as_ref().unwrap().cltv_expiry_delta,
479+
htlc_maximum_msat: None,
480+
htlc_minimum_msat: None,
481+
}])];
482+
let (mut route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], hop_hints, 10_000, 42);
483+
assert_eq!(route.paths[0][1].short_channel_id, nodes[2].node.list_usable_channels()[0].inbound_scid_alias.unwrap());
484+
485+
route.paths[0][1].fee_msat = 10_000_000; // Overshoot the last channel's value
486+
487+
// Route the HTLC through to the destination.
488+
nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
489+
check_added_monitors!(nodes[0], 1);
490+
let as_updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
491+
nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_updates.update_add_htlcs[0]);
492+
commitment_signed_dance!(nodes[1], nodes[0], &as_updates.commitment_signed, false, true);
493+
494+
expect_pending_htlcs_forwardable!(nodes[1]);
495+
expect_pending_htlcs_forwardable!(nodes[1]);
496+
check_added_monitors!(nodes[1], 1);
497+
498+
let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
499+
nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
500+
commitment_signed_dance!(nodes[0], nodes[1], bs_updates.commitment_signed, false, true);
501+
502+
// Build the expected channel update
503+
let contents = msgs::UnsignedChannelUpdate {
504+
chain_hash: genesis_block(Network::Testnet).header.block_hash(),
505+
short_channel_id: last_hop[0].inbound_scid_alias.unwrap(),
506+
timestamp: 21,
507+
flags: 1,
508+
cltv_expiry_delta: accept_forward_cfg.channel_options.cltv_expiry_delta,
509+
htlc_minimum_msat: 1_000,
510+
htlc_maximum_msat: OptionalField::Present(1_000_000), // Defaults to 10% of the channel value
511+
fee_base_msat: last_hop[0].counterparty.forwarding_info.as_ref().unwrap().fee_base_msat,
512+
fee_proportional_millionths: last_hop[0].counterparty.forwarding_info.as_ref().unwrap().fee_proportional_millionths,
513+
excess_data: Vec::new(),
514+
};
515+
let msg_hash = Sha256dHash::hash(&contents.encode()[..]);
516+
let signature = Secp256k1::new().sign(&hash_to_message!(&msg_hash[..]), &nodes[1].keys_manager.get_node_secret(Recipient::Node).unwrap());
517+
let msg = msgs::ChannelUpdate { signature, contents };
518+
519+
expect_payment_failed_conditions!(nodes[0], payment_hash, false,
520+
PaymentFailedConditions::new().blamed_scid(last_hop[0].inbound_scid_alias.unwrap())
521+
.blamed_chan_closed(false).expected_htlc_error_data(0x1000|7, &msg.encode_with_len()));
522+
523+
route.paths[0][1].fee_msat = 10_000; // Reset to the correct payment amount
524+
route.paths[0][0].fee_msat = 0; // But set fee paid to the middle hop to 0
525+
526+
// Route the HTLC through to the destination.
527+
nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
528+
check_added_monitors!(nodes[0], 1);
529+
let as_updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
530+
nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_updates.update_add_htlcs[0]);
531+
commitment_signed_dance!(nodes[1], nodes[0], &as_updates.commitment_signed, false, true);
532+
533+
let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
534+
nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
535+
commitment_signed_dance!(nodes[0], nodes[1], bs_updates.commitment_signed, false, true);
536+
537+
let mut err_data = Vec::new();
538+
err_data.extend_from_slice(&10_000u64.to_be_bytes());
539+
err_data.extend_from_slice(&msg.encode_with_len());
540+
expect_payment_failed_conditions!(nodes[0], payment_hash, false,
541+
PaymentFailedConditions::new().blamed_scid(last_hop[0].inbound_scid_alias.unwrap())
542+
.blamed_chan_closed(false).expected_htlc_error_data(0x1000|12, &err_data));
543+
}

0 commit comments

Comments
 (0)