Skip to content

Commit cadf33a

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 59fd448 commit cadf33a

File tree

3 files changed

+217
-7
lines changed

3 files changed

+217
-7
lines changed

lightning/src/ln/channel.rs

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ use util::events::ClosureReason;
3939
use util::ser::{Readable, ReadableArgs, Writeable, Writer, VecWriter};
4040
use util::logger::Logger;
4141
use util::errors::APIError;
42-
use util::config::{UserConfig, LegacyChannelConfig, ChannelHandshakeConfig, ChannelHandshakeLimits};
42+
use util::config::{UserConfig, LegacyChannelConfig, ChannelConfig, ChannelHandshakeConfig, ChannelHandshakeLimits};
4343
use util::scid_utils::scid_from_parts;
4444

4545
use io;
@@ -4491,6 +4491,22 @@ impl<Signer: Sign> Channel<Signer> {
44914491
self.config.options.max_dust_htlc_exposure_msat
44924492
}
44934493

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

lightning/src/ln/channelmanager.rs

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2919,6 +2919,68 @@ 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. None of the updates should be
2930+
/// considered applied.
2931+
///
2932+
/// Returns [`APIMisuseError`] when an incorrect `counterparty_node_id` is provided or a
2933+
/// [`cltv_expiry_delta`] update is to be applied with a value below [`MIN_CLTV_EXPIRY_DELTA`].
2934+
///
2935+
/// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
2936+
/// [`forwarding_fee_base_msat`]: ChannelConfig::forwarding_fee_base_msat
2937+
/// [`cltv_expiry_delta`]: ChannelConfig::cltv_expiry_delta
2938+
/// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate
2939+
/// [`ChannelUpdate`]: msgs::ChannelUpdate
2940+
/// [`ChannelUnavailable`]: APIError::ChannelUnavailable
2941+
/// [`APIMisuseError`]: APIError::APIMisuseError
2942+
pub fn update_channel_config(
2943+
&self, counterparty_node_id: &PublicKey, channel_ids: &[[u8; 32]], config: &ChannelConfig,
2944+
) -> Result<(), APIError> {
2945+
if config.cltv_expiry_delta < MIN_CLTV_EXPIRY_DELTA {
2946+
return Err(APIError::APIMisuseError { err:
2947+
format!("cltv expiry delta below minimum {}", MIN_CLTV_EXPIRY_DELTA),
2948+
});
2949+
}
2950+
2951+
let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(
2952+
&self.total_consistency_lock, &self.persistence_notifier,
2953+
);
2954+
{
2955+
let mut channel_state_lock = self.channel_state.lock().unwrap();
2956+
let channel_state = &mut *channel_state_lock;
2957+
for channel_id in channel_ids {
2958+
let channel_counterparty_node_id = channel_state.by_id.get(channel_id)
2959+
.ok_or(APIError::ChannelUnavailable {
2960+
err: format!("Channel {} not found", log_bytes!(*channel_id)),
2961+
})?
2962+
.get_counterparty_node_id();
2963+
if channel_counterparty_node_id != *counterparty_node_id {
2964+
return Err(APIError::APIMisuseError {
2965+
err: "counterparty node id mismatch".to_owned(),
2966+
});
2967+
}
2968+
}
2969+
for channel_id in channel_ids {
2970+
let channel = channel_state.by_id.get_mut(channel_id).unwrap();
2971+
if !channel.update_config(config) {
2972+
continue;
2973+
}
2974+
if let Ok(msg) = self.get_channel_update_for_broadcast(channel) {
2975+
channel_state.pending_msg_events.push(
2976+
events::MessageSendEvent::BroadcastChannelUpdate { msg },
2977+
);
2978+
}
2979+
}
2980+
}
2981+
Ok(())
2982+
}
2983+
29222984
/// Processes HTLCs which are pending waiting on random forward delay.
29232985
///
29242986
/// Should only really ever be called in response to a PendingHTLCsForwardable event.

lightning/src/ln/onion_route_tests.rs

Lines changed: 138 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,139 @@ fn test_onion_failure() {
594593
}, true, Some(23), None, None);
595594
}
596595

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

0 commit comments

Comments
 (0)