Skip to content

Commit 3dff4ab

Browse files
committed
Expose API to update a channel's ChannelConfig
A new `update_channel_config` method is exposed on the `ChannelManger` to update the `ChannelConfig` for a set of channels atomically. New `ChannelUpdate` events are generated for each eligible channel. Note that as currently implemented, a buggy and/or auto-policy-management client could spam the network with updates as there is no rate-limiting in place. This could already be done with `broadcast_node_announcement`, though users are less inclined to update that as frequently as its data is mostly static.
1 parent dfd5679 commit 3dff4ab

File tree

3 files changed

+265
-7
lines changed

3 files changed

+265
-7
lines changed

lightning/src/ln/channel.rs

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4491,12 +4491,27 @@ impl<Signer: Sign> Channel<Signer> {
44914491
self.config.options.max_dust_htlc_exposure_msat
44924492
}
44934493

4494-
44954494
/// Returns the current [`ChannelConfig`] applied to the channel.
44964495
pub fn config(&self) -> ChannelConfig {
44974496
self.config.options
44984497
}
44994498

4499+
/// Updates the channel's config. A bool is returned indicating whether the config update
4500+
/// applied resulted in a new ChannelUpdate message.
4501+
pub fn update_config(&mut self, config: &ChannelConfig) -> bool {
4502+
let did_channel_update =
4503+
self.config.options.forwarding_fee_proportional_millionths != config.forwarding_fee_proportional_millionths ||
4504+
self.config.options.forwarding_fee_base_msat != config.forwarding_fee_base_msat ||
4505+
self.config.options.cltv_expiry_delta != config.cltv_expiry_delta;
4506+
if did_channel_update {
4507+
// Update the counter, which backs the ChannelUpdate timestamp, to allow the relay
4508+
// policy change to propagate throughout the network.
4509+
self.update_time_counter += 1;
4510+
}
4511+
self.config.options = *config;
4512+
did_channel_update
4513+
}
4514+
45004515
pub fn get_feerate(&self) -> u32 {
45014516
self.feerate_per_kw
45024517
}

lightning/src/ln/channelmanager.rs

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2919,6 +2919,73 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
29192919
}
29202920
}
29212921

2922+
/// Atomically updates the [`ChannelConfig`] for the given channels.
2923+
///
2924+
/// Once the updates are applied, each eligible channel (advertised with a known short channel
2925+
/// ID and a change in [`forwarding_fee_proportional_millionths`], [`forwarding_fee_base_msat`],
2926+
/// or [`cltv_expiry_delta`]) has a [`BroadcastChannelUpdate`] event message generated
2927+
/// containing the new [`ChannelUpdate`] message which should be broadcast to the network.
2928+
///
2929+
/// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect
2930+
/// `counterparty_node_id` is provided.
2931+
///
2932+
/// Returns [`APIMisuseError`] when a [`cltv_expiry_delta`] update is to be applied with a value
2933+
/// below [`MIN_CLTV_EXPIRY_DELTA`].
2934+
///
2935+
/// If an error is returned, none of the updates should be considered applied.
2936+
///
2937+
/// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
2938+
/// [`forwarding_fee_base_msat`]: ChannelConfig::forwarding_fee_base_msat
2939+
/// [`cltv_expiry_delta`]: ChannelConfig::cltv_expiry_delta
2940+
/// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate
2941+
/// [`ChannelUpdate`]: msgs::ChannelUpdate
2942+
/// [`ChannelUnavailable`]: APIError::ChannelUnavailable
2943+
/// [`APIMisuseError`]: APIError::APIMisuseError
2944+
pub fn update_channel_config(
2945+
&self, counterparty_node_id: &PublicKey, channel_ids: &[[u8; 32]], config: &ChannelConfig,
2946+
) -> Result<(), APIError> {
2947+
if config.cltv_expiry_delta < MIN_CLTV_EXPIRY_DELTA {
2948+
return Err(APIError::APIMisuseError {
2949+
err: format!("The chosen CLTV expiry delta is below the minimum of {}", MIN_CLTV_EXPIRY_DELTA),
2950+
});
2951+
}
2952+
2953+
let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(
2954+
&self.total_consistency_lock, &self.persistence_notifier,
2955+
);
2956+
{
2957+
let mut channel_state_lock = self.channel_state.lock().unwrap();
2958+
let channel_state = &mut *channel_state_lock;
2959+
for channel_id in channel_ids {
2960+
let channel_counterparty_node_id = channel_state.by_id.get(channel_id)
2961+
.ok_or(APIError::ChannelUnavailable {
2962+
err: format!("Channel with ID {} was not found", log_bytes!(*channel_id)),
2963+
})?
2964+
.get_counterparty_node_id();
2965+
if channel_counterparty_node_id != *counterparty_node_id {
2966+
return Err(APIError::APIMisuseError {
2967+
err: "counterparty node id mismatch".to_owned(),
2968+
});
2969+
}
2970+
}
2971+
for channel_id in channel_ids {
2972+
let channel = channel_state.by_id.get_mut(channel_id).unwrap();
2973+
if !channel.update_config(config) {
2974+
continue;
2975+
}
2976+
if let Ok(msg) = self.get_channel_update_for_broadcast(channel) {
2977+
channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate { msg });
2978+
} else if let Ok(msg) = self.get_channel_update_for_unicast(channel) {
2979+
channel_state.pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
2980+
node_id: channel.get_counterparty_node_id(),
2981+
msg,
2982+
});
2983+
}
2984+
}
2985+
}
2986+
Ok(())
2987+
}
2988+
29222989
/// Processes HTLCs which are pending waiting on random forward delay.
29232990
///
29242991
/// Should only really ever be called in response to a PendingHTLCsForwardable event.

lightning/src/ln/onion_route_tests.rs

Lines changed: 182 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,10 @@
1111
//! These tests work by standing up full nodes and route payments across the network, checking the
1212
//! returned errors decode to the correct thing.
1313
14-
use chain::channelmonitor::{CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS};
14+
use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS};
1515
use chain::keysinterface::{KeysInterface, Recipient};
1616
use ln::{PaymentHash, PaymentSecret};
17-
use ln::channelmanager::{HTLCForwardInfo, CLTV_FAR_FAR_AWAY, MIN_CLTV_EXPIRY_DELTA, PendingHTLCInfo, PendingHTLCRouting};
17+
use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, HTLCForwardInfo, CLTV_FAR_FAR_AWAY, MIN_CLTV_EXPIRY_DELTA, PendingHTLCInfo, PendingHTLCRouting};
1818
use ln::onion_utils;
1919
use routing::gossip::{NetworkUpdate, RoutingFees, NodeId};
2020
use routing::router::{get_route, PaymentParameters, Route, RouteHint, RouteHintHop};
@@ -23,9 +23,10 @@ use ln::msgs;
2323
use ln::msgs::{ChannelMessageHandler, ChannelUpdate, OptionalField};
2424
use ln::wire::Encode;
2525
use util::events::{Event, MessageSendEvent, MessageSendEventsProvider};
26-
use util::ser::{Writeable, Writer};
26+
use util::ser::{ReadableArgs, Writeable, Writer};
2727
use util::{byte_utils, test_utils};
28-
use util::config::UserConfig;
28+
use util::config::{UserConfig, ChannelConfig};
29+
use util::errors::APIError;
2930

3031
use bitcoin::hash_types::BlockHash;
3132

@@ -506,8 +507,6 @@ fn test_onion_failure() {
506507
let preimage = send_along_route(&nodes[0], bogus_route, &[&nodes[1], &nodes[2]], amt_to_forward+1).0;
507508
claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], preimage);
508509

509-
//TODO: with new config API, we will be able to generate both valid and
510-
//invalid channel_update cases.
511510
let short_channel_id = channels[0].0.contents.short_channel_id;
512511
run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| {
513512
msg.amount_msat -= 1;
@@ -594,6 +593,183 @@ fn test_onion_failure() {
594593
}, true, Some(23), None, None);
595594
}
596595

596+
fn do_test_onion_failure_stale_channel_update(announced_channel: bool) {
597+
// Create a network of three nodes and two channels connecting them. We'll be updating the
598+
// HTLC relay policy of the second channel, causing forwarding failures at the first hop.
599+
let mut config = UserConfig::default();
600+
config.channel_handshake_config.announced_channel = announced_channel;
601+
config.channel_handshake_limits.force_announced_channel_preference = false;
602+
config.accept_forwards_to_priv_channels = !announced_channel;
603+
let chanmon_cfgs = create_chanmon_cfgs(3);
604+
let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
605+
let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(config), None]);
606+
let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
607+
608+
let other_channel = create_chan_between_nodes(
609+
&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known(),
610+
);
611+
let channel_to_update = if announced_channel {
612+
let channel = create_announced_chan_between_nodes(
613+
&nodes, 1, 2, InitFeatures::known(), InitFeatures::known(),
614+
);
615+
(channel.2, channel.0.contents.short_channel_id)
616+
} else {
617+
let channel = create_unannounced_chan_between_nodes_with_value(
618+
&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known(),
619+
);
620+
(channel.0.channel_id, channel.0.short_channel_id_alias.unwrap())
621+
};
622+
let channel_to_update_counterparty = &nodes[2].node.get_our_node_id();
623+
624+
let default_config = ChannelConfig::default();
625+
626+
// A test payment should succeed as the ChannelConfig has not been changed yet.
627+
const PAYMENT_AMT: u64 = 40000;
628+
let (route, payment_hash, payment_preimage, payment_secret) = if announced_channel {
629+
get_route_and_payment_hash!(nodes[0], nodes[2], PAYMENT_AMT)
630+
} else {
631+
let hop_hints = vec![RouteHint(vec![RouteHintHop {
632+
src_node_id: nodes[1].node.get_our_node_id(),
633+
short_channel_id: channel_to_update.1,
634+
fees: RoutingFees {
635+
base_msat: default_config.forwarding_fee_base_msat,
636+
proportional_millionths: default_config.forwarding_fee_proportional_millionths,
637+
},
638+
cltv_expiry_delta: default_config.cltv_expiry_delta,
639+
htlc_maximum_msat: None,
640+
htlc_minimum_msat: None,
641+
}])];
642+
let payment_params = PaymentParameters::from_node_id(*channel_to_update_counterparty)
643+
.with_features(InvoiceFeatures::known())
644+
.with_route_hints(hop_hints);
645+
get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, PAYMENT_AMT, TEST_FINAL_CLTV)
646+
};
647+
send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[2]]], PAYMENT_AMT,
648+
payment_hash, payment_secret);
649+
claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
650+
651+
// Closure to update and retrieve the latest ChannelUpdate.
652+
let update_and_get_channel_update = |config: &ChannelConfig, expect_new_update: bool,
653+
prev_update: Option<&msgs::ChannelUpdate>| -> Option<msgs::ChannelUpdate> {
654+
nodes[1].node.update_channel_config(
655+
channel_to_update_counterparty, &[channel_to_update.0], config,
656+
).unwrap();
657+
let events = nodes[1].node.get_and_clear_pending_msg_events();
658+
assert_eq!(events.len(), expect_new_update as usize);
659+
if !expect_new_update {
660+
return None;
661+
}
662+
let new_update = match &events[0] {
663+
MessageSendEvent::BroadcastChannelUpdate { msg } => {
664+
assert!(announced_channel);
665+
msg.clone()
666+
},
667+
MessageSendEvent::SendChannelUpdate { node_id, msg } => {
668+
assert_eq!(node_id, channel_to_update_counterparty);
669+
assert!(!announced_channel);
670+
msg.clone()
671+
},
672+
_ => panic!("expected Broadcast/SendChannelUpdate event"),
673+
};
674+
if prev_update.is_some() {
675+
assert!(new_update.contents.timestamp > prev_update.unwrap().contents.timestamp)
676+
}
677+
Some(new_update)
678+
};
679+
680+
// We'll be attempting to route payments using the default ChannelUpdate for channels. This will
681+
// lead to onion failures at the first hop once we update the ChannelConfig for the
682+
// second hop.
683+
let expect_onion_failure = |name: &str, error_code: u16, channel_update: &msgs::ChannelUpdate| {
684+
let short_channel_id = channel_to_update.1;
685+
let network_update = NetworkUpdate::ChannelUpdateMessage { msg: channel_update.clone() };
686+
run_onion_failure_test(
687+
name, 0, &nodes, &route, &payment_hash, &payment_secret, |_| {}, || {}, true,
688+
Some(error_code), Some(network_update), Some(short_channel_id),
689+
);
690+
};
691+
692+
// Updates to cltv_expiry_delta below MIN_CLTV_EXPIRY_DELTA should fail with APIMisuseError.
693+
let mut invalid_config = default_config.clone();
694+
invalid_config.cltv_expiry_delta = 0;
695+
match nodes[1].node.update_channel_config(
696+
channel_to_update_counterparty, &[channel_to_update.0], &invalid_config,
697+
) {
698+
Err(APIError::APIMisuseError{ .. }) => {},
699+
_ => panic!("unexpected result applying invalid cltv_expiry_delta"),
700+
}
701+
702+
// Increase the base fee which should trigger a new ChannelUpdate.
703+
let mut config = nodes[1].node.list_usable_channels().iter()
704+
.find(|channel| channel.channel_id == channel_to_update.0).unwrap()
705+
.config.unwrap();
706+
config.forwarding_fee_base_msat = u32::max_value();
707+
let msg = update_and_get_channel_update(&config, true, None).unwrap();
708+
expect_onion_failure("fee_insufficient", UPDATE|12, &msg);
709+
710+
// Redundant updates should not trigger a new ChannelUpdate.
711+
assert!(update_and_get_channel_update(&config, false, None).is_none());
712+
713+
// Similarly, updates that do not have an affect on ChannelUpdate should not trigger a new one.
714+
config.force_close_avoidance_max_fee_satoshis *= 2;
715+
assert!(update_and_get_channel_update(&config, false, None).is_none());
716+
717+
// Reset the base fee to the default and increase the proportional fee which should trigger a
718+
// new ChannelUpdate.
719+
config.forwarding_fee_base_msat = default_config.forwarding_fee_base_msat;
720+
config.cltv_expiry_delta = u16::max_value();
721+
let msg = update_and_get_channel_update(&config, true, Some(&msg)).unwrap();
722+
expect_onion_failure("incorrect_cltv_expiry", UPDATE|13, &msg);
723+
724+
// Reset the proportional fee and increase the CLTV expiry delta which should trigger a new
725+
// ChannelUpdate.
726+
config.cltv_expiry_delta = default_config.cltv_expiry_delta;
727+
config.forwarding_fee_proportional_millionths = u32::max_value();
728+
let msg = update_and_get_channel_update(&config, true, Some(&msg)).unwrap();
729+
expect_onion_failure("fee_insufficient", UPDATE|12, &msg);
730+
731+
// To test persistence of the updated config, we'll re-initialize the ChannelManager.
732+
let config_after_restart = {
733+
let persister = test_utils::TestPersister::new();
734+
let chain_monitor = test_utils::TestChainMonitor::new(
735+
Some(nodes[1].chain_source), nodes[1].tx_broadcaster.clone(), nodes[1].logger,
736+
node_cfgs[1].fee_estimator, &persister, nodes[1].keys_manager,
737+
);
738+
739+
let mut chanmon_1 = <(_, ChannelMonitor<_>)>::read(
740+
&mut &get_monitor!(nodes[1], other_channel.3).encode()[..], nodes[1].keys_manager,
741+
).unwrap().1;
742+
let mut chanmon_2 = <(_, ChannelMonitor<_>)>::read(
743+
&mut &get_monitor!(nodes[1], channel_to_update.0).encode()[..], nodes[1].keys_manager,
744+
).unwrap().1;
745+
let mut channel_monitors = HashMap::new();
746+
channel_monitors.insert(chanmon_1.get_funding_txo().0, &mut chanmon_1);
747+
channel_monitors.insert(chanmon_2.get_funding_txo().0, &mut chanmon_2);
748+
749+
let chanmgr = <(_, ChannelManager<_, _, _, _, _, _>)>::read(
750+
&mut &nodes[1].node.encode()[..], ChannelManagerReadArgs {
751+
default_config: *nodes[1].node.get_current_default_configuration(),
752+
keys_manager: nodes[1].keys_manager,
753+
fee_estimator: node_cfgs[1].fee_estimator,
754+
chain_monitor: &chain_monitor,
755+
tx_broadcaster: nodes[1].tx_broadcaster.clone(),
756+
logger: nodes[1].logger,
757+
channel_monitors: channel_monitors,
758+
},
759+
).unwrap().1;
760+
chanmgr.list_channels().iter()
761+
.find(|channel| channel.channel_id == channel_to_update.0).unwrap()
762+
.config.unwrap()
763+
};
764+
assert_eq!(config, config_after_restart);
765+
}
766+
767+
#[test]
768+
fn test_onion_failure_stale_channel_update() {
769+
do_test_onion_failure_stale_channel_update(false);
770+
do_test_onion_failure_stale_channel_update(true);
771+
}
772+
597773
#[test]
598774
fn test_default_to_onion_payload_tlv_format() {
599775
// Tests that we default to creating tlv format onion payloads when no `NodeAnnouncementInfo`

0 commit comments

Comments
 (0)