Skip to content

Commit 14c8c4c

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 f1ab771 commit 14c8c4c

File tree

3 files changed

+246
-6
lines changed

3 files changed

+246
-6
lines changed

lightning/src/ln/channel.rs

+45
Original file line numberDiff line numberDiff line change
@@ -495,6 +495,11 @@ pub(super) struct Channel<Signer: Sign> {
495495
#[cfg(not(any(test, feature = "_test_utils")))]
496496
config: LegacyChannelConfig,
497497

498+
// Track the previous `ChannelConfig` so that we can continue forwarding HTLCs that were
499+
// constructed using it. The `ChannelManager` should determine when to expire it via
500+
// `clear_prev_config`.
501+
prev_config: Option<(ChannelConfig, u32)>,
502+
498503
inbound_handshake_limits_override: Option<ChannelHandshakeLimits>,
499504

500505
user_id: u64,
@@ -937,6 +942,8 @@ impl<Signer: Sign> Channel<Signer> {
937942
commit_upfront_shutdown_pubkey: config.channel_handshake_config.commit_upfront_shutdown_pubkey,
938943
},
939944

945+
prev_config: None,
946+
940947
inbound_handshake_limits_override: Some(config.channel_handshake_limits.clone()),
941948

942949
channel_id: keys_provider.get_secure_random_bytes(),
@@ -1264,6 +1271,8 @@ impl<Signer: Sign> Channel<Signer> {
12641271
commit_upfront_shutdown_pubkey: config.channel_handshake_config.commit_upfront_shutdown_pubkey,
12651272
},
12661273

1274+
prev_config: None,
1275+
12671276
inbound_handshake_limits_override: None,
12681277

12691278
channel_id: msg.temporary_channel_id,
@@ -4491,11 +4500,45 @@ impl<Signer: Sign> Channel<Signer> {
44914500
self.config.options.max_dust_htlc_exposure_msat
44924501
}
44934502

4503+
/// Returns the previous [`ChannelConfig`] applied to this channel, if any. The second element
4504+
/// in the tuple corresponds to the [`get_update_time_counter`] value prior to the
4505+
/// [`update_config`] call.
4506+
pub fn get_prev_config(&self) -> Option<(ChannelConfig, u32)> {
4507+
self.prev_config
4508+
}
4509+
4510+
/// Clears the previous [`ChannelConfig`] from a channel, such that it can no longer be used as
4511+
/// a fallback when forwarding HTLCs.
4512+
pub fn clear_prev_config(&mut self) {
4513+
self.prev_config = None;
4514+
}
4515+
44944516
// Returns the current [`ChannelConfig`] applied to the channel.
44954517
pub fn get_config(&self) -> ChannelConfig {
44964518
self.config.options
44974519
}
44984520

4521+
/// Updates the channel's config. `keep_prev_config` indicates whether the channel's previous
4522+
/// config should still be used to accept forwarded HTLCs for a short period of time. A bool is
4523+
/// returned indicating whether the config update applied resulted in a new ChannelUpdate
4524+
/// message.
4525+
pub fn update_config(&mut self, config: &ChannelConfig, keep_prev_config: bool) -> bool {
4526+
let did_channel_update =
4527+
self.config.options.forwarding_fee_proportional_millionths != config.forwarding_fee_proportional_millionths ||
4528+
self.config.options.forwarding_fee_base_msat != config.forwarding_fee_base_msat ||
4529+
self.config.options.cltv_expiry_delta != config.cltv_expiry_delta;
4530+
if did_channel_update {
4531+
if keep_prev_config {
4532+
self.prev_config = Some((self.config.options, self.update_time_counter));
4533+
}
4534+
// Update the counter, which backs the ChannelUpdate timestamp, to allow the relay
4535+
// policy change to propagate throughout the network.
4536+
self.update_time_counter += 1;
4537+
}
4538+
self.config.options = *config;
4539+
did_channel_update
4540+
}
4541+
44994542
pub fn get_feerate(&self) -> u32 {
45004543
self.feerate_per_kw
45014544
}
@@ -6344,6 +6387,8 @@ impl<'a, Signer: Sign, K: Deref> ReadableArgs<(&'a K, u32)> for Channel<Signer>
63446387

63456388
config: config.unwrap(),
63466389

6390+
prev_config: None,
6391+
63476392
// Note that we don't care about serializing handshake limits as we only ever serialize
63486393
// channel data after the handshake has completed.
63496394
inbound_handshake_limits_override: None,

lightning/src/ln/channelmanager.rs

+62
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. In this case, none of the
2930+
/// updates should be 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 {
2947+
err: format!("The chosen CLTV expiry delta is below the minimum of {}", 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 with ID {} was 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, true) {
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

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

0 commit comments

Comments
 (0)