Skip to content

Commit 3bf9cea

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 383725d commit 3bf9cea

File tree

4 files changed

+109
-11
lines changed

4 files changed

+109
-11
lines changed

lightning/src/ln/channelmanager.rs

Lines changed: 34 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2524,6 +2524,10 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
25242524
Some(id) => id,
25252525
};
25262526

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

25292533
let unsigned = msgs::UnsignedChannelUpdate {
@@ -3213,7 +3217,7 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
32133217
} else {
32143218
panic!("Stated return value requirements in send_htlc() were not met");
32153219
}
3216-
let (failure_code, data) = self.get_htlc_temp_fail_err_and_data(0x1000|7, chan.get());
3220+
let (failure_code, data) = self.get_htlc_temp_fail_err_and_data(0x1000|7, short_chan_id, chan.get());
32173221
failed_forwards.push((htlc_source, payment_hash,
32183222
HTLCFailReason::Reason { failure_code, data }
32193223
));
@@ -3713,9 +3717,32 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
37133717

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

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};
@@ -1850,7 +1850,7 @@ pub fn test_default_channel_config() -> UserConfig {
18501850
let mut default_config = UserConfig::default();
18511851
// Set cltv_expiry_delta slightly lower to keep the final CLTV values inside one byte in our
18521852
// tests so that our script-length checks don't fail (see ACCEPTED_HTLC_SCRIPT_WEIGHT).
1853-
default_config.channel_options.cltv_expiry_delta = 6*6;
1853+
default_config.channel_options.cltv_expiry_delta = MIN_CLTV_EXPIRY_DELTA;
18541854
default_config.channel_options.announced_channel = true;
18551855
default_config.peer_channel_config_limits.force_announced_channel_preference = false;
18561856
// 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: 73 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,69 @@ fn test_inbound_scid_alias() {
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+
let chanmon_cfgs = create_chanmon_cfgs(3);
458+
let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
459+
let mut accept_forward_cfg = test_default_channel_config();
460+
accept_forward_cfg.accept_forwards_to_priv_channels = true;
461+
let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(accept_forward_cfg), None]);
462+
let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
463+
464+
create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0, InitFeatures::known(), InitFeatures::known());
465+
create_unannounced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000, 0, InitFeatures::known(), InitFeatures::known());
466+
467+
let last_hop = nodes[2].node.list_usable_channels();
468+
let mut hop_hints = vec![RouteHint(vec![RouteHintHop {
469+
src_node_id: nodes[1].node.get_our_node_id(),
470+
short_channel_id: last_hop[0].inbound_scid_alias.unwrap(),
471+
fees: RoutingFees {
472+
base_msat: last_hop[0].counterparty.forwarding_info.as_ref().unwrap().fee_base_msat,
473+
proportional_millionths: last_hop[0].counterparty.forwarding_info.as_ref().unwrap().fee_proportional_millionths,
474+
},
475+
cltv_expiry_delta: last_hop[0].counterparty.forwarding_info.as_ref().unwrap().cltv_expiry_delta,
476+
htlc_maximum_msat: None,
477+
htlc_minimum_msat: None,
478+
}])];
479+
let (mut route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], hop_hints, 10_000, 42);
480+
assert_eq!(route.paths[0][1].short_channel_id, nodes[2].node.list_usable_channels()[0].inbound_scid_alias.unwrap());
481+
482+
route.paths[0][1].fee_msat = 10_000_000; // Overshoot the last channel's value
483+
484+
// Route the HTLC through to the destination.
485+
nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
486+
check_added_monitors!(nodes[0], 1);
487+
let as_updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
488+
nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_updates.update_add_htlcs[0]);
489+
commitment_signed_dance!(nodes[1], nodes[0], &as_updates.commitment_signed, false, true);
490+
491+
expect_pending_htlcs_forwardable!(nodes[1]);
492+
expect_pending_htlcs_forwardable!(nodes[1]);
493+
check_added_monitors!(nodes[1], 1);
494+
495+
let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
496+
nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
497+
commitment_signed_dance!(nodes[0], nodes[1], bs_updates.commitment_signed, false, true);
498+
499+
// Build the expected channel update
500+
let contents = msgs::UnsignedChannelUpdate {
501+
chain_hash: genesis_block(Network::Testnet).header.block_hash(),
502+
short_channel_id: last_hop[0].inbound_scid_alias.unwrap(),
503+
timestamp: 21,
504+
flags: 1,
505+
cltv_expiry_delta: accept_forward_cfg.channel_options.cltv_expiry_delta,
506+
htlc_minimum_msat: 1_000,
507+
htlc_maximum_msat: OptionalField::Present(1_000_000), // Defaults to 10% of the channel value
508+
fee_base_msat: last_hop[0].counterparty.forwarding_info.as_ref().unwrap().fee_base_msat,
509+
fee_proportional_millionths: last_hop[0].counterparty.forwarding_info.as_ref().unwrap().fee_proportional_millionths,
510+
excess_data: Vec::new(),
511+
};
512+
let msg_hash = Sha256dHash::hash(&contents.encode()[..]);
513+
let signature = Secp256k1::new().sign(&hash_to_message!(&msg_hash[..]), &nodes[1].keys_manager.get_node_secret(Recipient::Node).unwrap());
514+
let msg = msgs::ChannelUpdate { signature, contents };
515+
516+
expect_payment_failed_conditions!(nodes[0], payment_hash, false,
517+
PaymentFailedConditions::new().blamed_scid(last_hop[0].inbound_scid_alias.unwrap())
518+
.blamed_chan_closed(false).expected_htlc_error_data(0x1000|7, &msg.encode_with_len()));
519+
}

0 commit comments

Comments
 (0)