Skip to content

Commit 7394b93

Browse files
author
Wilmer Paulino
committed
Expose API to update HTLC relay policy
A new `update_htlc_relay_policy` method is exposed on the `ChannelManger` to update the HTLC relay policy 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. Signed-off-by: Wilmer Paulino <[email protected]>
1 parent 8e5cf75 commit 7394b93

File tree

4 files changed

+219
-5
lines changed

4 files changed

+219
-5
lines changed

lightning/src/ln/channel.rs

Lines changed: 31 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, ChannelConfig, ChannelHandshakeConfig, ChannelHandshakeLimits};
42+
use util::config::{UserConfig, ChannelConfig, ChannelHandshakeConfig, ChannelHandshakeLimits, HTLCRelayPolicyUpdate};
4343
use util::scid_utils::scid_from_parts;
4444

4545
use io;
@@ -4482,6 +4482,36 @@ impl<Signer: Sign> Channel<Signer> {
44824482
self.config.max_dust_htlc_exposure_msat
44834483
}
44844484

4485+
/// Updates the channel's relay policy for forwarding HTLCs. A bool is returned indicating
4486+
/// whether the updates applied resulted in a policy change.
4487+
pub fn update_htlc_relay_policy(&mut self, updates: &[HTLCRelayPolicyUpdate]) -> bool {
4488+
let default = ChannelConfig::default();
4489+
let prev_base_fee = self.get_outbound_forwarding_fee_base_msat();
4490+
let prev_proportional_fee = self.get_fee_proportional_millionths();
4491+
let prev_cltv_expiry_delta = self.get_cltv_expiry_delta();
4492+
for update in updates {
4493+
match update {
4494+
HTLCRelayPolicyUpdate::ForwardingFeeProportionalMillionths(val) =>
4495+
self.config.forwarding_fee_proportional_millionths =
4496+
val.unwrap_or(default.forwarding_fee_proportional_millionths),
4497+
HTLCRelayPolicyUpdate::ForwardingFeeBaseMsat(val) =>
4498+
self.config.forwarding_fee_base_msat =
4499+
val.unwrap_or(default.forwarding_fee_base_msat),
4500+
HTLCRelayPolicyUpdate::CltvExpiryDelta(val) =>
4501+
self.config.cltv_expiry_delta = val.unwrap_or(default.cltv_expiry_delta),
4502+
}
4503+
}
4504+
let did_change = prev_base_fee != self.get_outbound_forwarding_fee_base_msat() ||
4505+
prev_proportional_fee != self.get_fee_proportional_millionths() ||
4506+
prev_cltv_expiry_delta != self.get_cltv_expiry_delta();
4507+
if did_change {
4508+
// Update the counter, which backs the ChannelUpdate timestamp, to allow the relay
4509+
// policy change to propagate throughout the network.
4510+
self.update_time_counter += 1;
4511+
}
4512+
did_change
4513+
}
4514+
44854515
pub fn get_feerate(&self) -> u32 {
44864516
self.feerate_per_kw
44874517
}

lightning/src/ln/channelmanager.rs

Lines changed: 60 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ use ln::onion_utils;
5151
use ln::msgs::{ChannelMessageHandler, DecodeError, LightningError, MAX_VALUE_MSAT, OptionalField};
5252
use ln::wire::Encode;
5353
use chain::keysinterface::{Sign, KeysInterface, KeysManager, InMemorySigner, Recipient};
54-
use util::config::UserConfig;
54+
use util::config::{UserConfig, HTLCRelayPolicyUpdate};
5555
use util::events::{EventHandler, EventsProvider, MessageSendEvent, MessageSendEventsProvider, ClosureReason};
5656
use util::{byte_utils, events};
5757
use util::scid_utils::fake_scid;
@@ -2920,6 +2920,65 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
29202920
}
29212921
}
29222922

2923+
/// Atomically updates the relay policy for forwarding HTLCs on the given channels.
2924+
///
2925+
/// Once the updates are applied, each eligible channel (advertised with a known short channel
2926+
/// ID and a change in relay policy) 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 a [`CltvExpiryDelta`] update is to be applied with a value
2933+
/// below [`MIN_CLTV_EXPIRY_DELTA`].
2934+
///
2935+
/// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate
2936+
/// [`ChannelUpdate`]: msgs::ChannelUpdate
2937+
/// [`ChannelUnavailable`]: APIError::ChannelUnavailable
2938+
/// [`APIMisuseError`]: APIError::APIMisuseError
2939+
/// [`CltvExpiryDelta`]: HTLCRelayPolicyUpdate::CltvExpiryDelta
2940+
pub fn update_htlc_relay_policy(
2941+
&self, channel_ids: &[[u8; 32]], updates: &[HTLCRelayPolicyUpdate]
2942+
) -> Result<(), APIError> {
2943+
let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(
2944+
&self.total_consistency_lock, &self.persistence_notifier,
2945+
);
2946+
{
2947+
let mut channel_state_lock = self.channel_state.lock().unwrap();
2948+
let channel_state = &mut *channel_state_lock;
2949+
for channel_id in channel_ids {
2950+
if !channel_state.by_id.contains_key(channel_id) {
2951+
return Err(APIError::ChannelUnavailable {
2952+
err: format!("Channel {} not found", log_bytes!(*channel_id)),
2953+
});
2954+
}
2955+
}
2956+
for update in updates {
2957+
match update {
2958+
HTLCRelayPolicyUpdate::CltvExpiryDelta(Some(val)) =>
2959+
if *val < MIN_CLTV_EXPIRY_DELTA {
2960+
return Err(APIError::APIMisuseError { err:
2961+
format!("cltv expiry delta below minimum {}", MIN_CLTV_EXPIRY_DELTA),
2962+
});
2963+
},
2964+
_ => continue,
2965+
}
2966+
}
2967+
for channel_id in channel_ids {
2968+
let channel = channel_state.by_id.get_mut(channel_id).unwrap();
2969+
if !channel.update_htlc_relay_policy(updates) {
2970+
continue;
2971+
}
2972+
if let Ok(msg) = self.get_channel_update_for_broadcast(channel) {
2973+
channel_state.pending_msg_events.push(
2974+
events::MessageSendEvent::BroadcastChannelUpdate { msg },
2975+
);
2976+
}
2977+
}
2978+
}
2979+
Ok(())
2980+
}
2981+
29232982
/// Processes HTLCs which are pending waiting on random forward delay.
29242983
///
29252984
/// Should only really ever be called in response to a PendingHTLCsForwardable event.

lightning/src/ln/onion_route_tests.rs

Lines changed: 89 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,8 @@ use ln::wire::Encode;
2525
use util::events::{Event, MessageSendEvent, MessageSendEventsProvider};
2626
use util::ser::{Writeable, Writer};
2727
use util::{byte_utils, test_utils};
28-
use util::config::UserConfig;
28+
use util::config::{UserConfig, HTLCRelayPolicyUpdate};
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,93 @@ 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+
// second channel with insane HTLC relay parameters, causing forwarding failures at the first
600+
// hop.
601+
let chanmon_cfgs = create_chanmon_cfgs(3);
602+
let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
603+
let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
604+
let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
605+
create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
606+
let channel_to_update = create_announced_chan_between_nodes(
607+
&nodes, 1, 2, InitFeatures::known(), InitFeatures::known(),
608+
);
609+
610+
// A test payment should succeed as the HTLC relay paramters have not been changed yet.
611+
const PAYMENT_AMT: u64 = 40000;
612+
send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], PAYMENT_AMT);
613+
614+
// Closure to update and retrieve the latest ChannelUpdate.
615+
let update_and_get_channel_update =
616+
|updates: &[HTLCRelayPolicyUpdate], expect_new_update: bool,
617+
prev_update: Option<&msgs::ChannelUpdate>| -> Option<msgs::ChannelUpdate> {
618+
nodes[1].node.update_htlc_relay_policy(&[channel_to_update.2], updates).unwrap();
619+
let events = nodes[1].node.get_and_clear_pending_msg_events();
620+
assert_eq!(events.len(), expect_new_update as usize);
621+
if !expect_new_update {
622+
return None;
623+
}
624+
let new_update = match &events[0] {
625+
MessageSendEvent::BroadcastChannelUpdate { msg, .. } => msg.clone(),
626+
_ => panic!("expected BroadcastChannelUpdate event"),
627+
};
628+
if prev_update.is_some() {
629+
assert!(new_update.contents.timestamp > prev_update.unwrap().contents.timestamp)
630+
}
631+
Some(new_update)
632+
};
633+
634+
// We'll be attempting to route payments using the default ChannelUpdate for channels. This will
635+
// lead to onion failures at the first hop once we update the HTLC relay parameters for the
636+
// second hop.
637+
let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(
638+
nodes[0], nodes[2], PAYMENT_AMT
639+
);
640+
let expect_onion_failure = |name: &str, error_code: u16, channel_update: &msgs::ChannelUpdate| {
641+
let short_channel_id = channel_to_update.0.contents.short_channel_id;
642+
let network_update = NetworkUpdate::ChannelUpdateMessage { msg: channel_update.clone() };
643+
run_onion_failure_test(
644+
name, 0, &nodes, &route, &payment_hash, &payment_secret, |_| {}, || {}, true,
645+
Some(error_code), Some(network_update), Some(short_channel_id),
646+
);
647+
};
648+
649+
// Updates to cltv_expiry_delta below MIN_CLTV_EXPIRY_DELTA should fail with APIMisuseError.
650+
let updates = &[HTLCRelayPolicyUpdate::CltvExpiryDelta(Some(MIN_CLTV_EXPIRY_DELTA - 1))];
651+
match nodes[1].node.update_htlc_relay_policy(&[channel_to_update.2], updates) {
652+
Err(APIError::APIMisuseError{ .. }) => {},
653+
_ => panic!("unexpected result applying invalid cltv_expiry_delta"),
654+
}
655+
656+
// Increase the base fee which should trigger a new ChannelUpdate.
657+
let updates = &[HTLCRelayPolicyUpdate::ForwardingFeeBaseMsat(Some(u32::MAX))];
658+
let msg = update_and_get_channel_update(updates, true, None).unwrap();
659+
expect_onion_failure("fee_insufficient", UPDATE|12, &msg);
660+
661+
// Redundant updates should not trigger a new ChannelUpdate.
662+
assert!(update_and_get_channel_update(updates, false, None).is_none());
663+
664+
// Reset the base fee to the default and increase the proportional fee which should trigger a
665+
// new ChannelUpdate.
666+
let updates = &[
667+
HTLCRelayPolicyUpdate::ForwardingFeeBaseMsat(None),
668+
HTLCRelayPolicyUpdate::CltvExpiryDelta(Some(u16::MAX)),
669+
];
670+
let msg = update_and_get_channel_update(updates, true, Some(&msg)).unwrap();
671+
expect_onion_failure("incorrect_cltv_expiry", UPDATE|13, &msg);
672+
673+
// Reset the proportional fee and increase the CLTV expiry delta which should trigger a new
674+
// ChannelUpdate.
675+
let updates = &[
676+
HTLCRelayPolicyUpdate::CltvExpiryDelta(None),
677+
HTLCRelayPolicyUpdate::ForwardingFeeProportionalMillionths(Some(u32::MAX)),
678+
];
679+
let msg = update_and_get_channel_update(updates, true, Some(&msg)).unwrap();
680+
expect_onion_failure("fee_insufficient", UPDATE|12, &msg);
681+
}
682+
597683
#[test]
598684
fn test_default_to_onion_payload_tlv_format() {
599685
// Tests that we default to creating tlv format onion payloads when no `NodeAnnouncementInfo`

lightning/src/util/config.rs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -355,6 +355,45 @@ impl_writeable_tlv_based!(ChannelConfig, {
355355
(8, forwarding_fee_base_msat, required),
356356
});
357357

358+
/// Updates that can be made to a channel's relay policy for forwarding HTLCs. Each variant is
359+
/// represented as an Option, and when None is used, the variant's default value will be applied.
360+
pub enum HTLCRelayPolicyUpdate {
361+
/// Amount (in millionths of a satoshi) charged per satoshi for payments forwarded outbound
362+
/// over the channel.
363+
///
364+
/// Default value: 0.
365+
ForwardingFeeProportionalMillionths(Option<u32>),
366+
/// Amount (in milli-satoshi) charged for payments forwarded outbound over the channel, in
367+
/// excess of [`forwarding_fee_proportional_millionths`].
368+
/// This may be allowed to change at runtime in a later update, however doing so must result in
369+
/// update messages sent to notify all nodes of our updated relay fee.
370+
///
371+
/// Default value: 1000.
372+
///
373+
/// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
374+
ForwardingFeeBaseMsat(Option<u32>),
375+
/// The difference in the CLTV value between incoming HTLCs and an outbound HTLC forwarded over
376+
/// the channel this config applies to.
377+
///
378+
/// This is analogous to [`ChannelHandshakeConfig::our_to_self_delay`] but applies to in-flight
379+
/// HTLC balance when a channel appears on-chain whereas
380+
/// [`ChannelHandshakeConfig::our_to_self_delay`] applies to the remaining
381+
/// (non-HTLC-encumbered) balance.
382+
///
383+
/// Thus, for HTLC-encumbered balances to be enforced on-chain when a channel is force-closed,
384+
/// we (or one of our watchtowers) MUST be online to check for broadcast of the current
385+
/// commitment transaction at least once per this many blocks (minus some margin to allow us
386+
/// enough time to broadcast and confirm a transaction, possibly with time in between to RBF
387+
/// the spending transaction).
388+
///
389+
/// Default value: 72 (12 hours at an average of 6 blocks/hour).
390+
/// Minimum value: [`MIN_CLTV_EXPIRY_DELTA`], any values less than this will be treated as
391+
/// [`MIN_CLTV_EXPIRY_DELTA`] instead.
392+
///
393+
/// [`MIN_CLTV_EXPIRY_DELTA`]: crate::ln::channelmanager::MIN_CLTV_EXPIRY_DELTA
394+
CltvExpiryDelta(Option<u16>),
395+
}
396+
358397
/// Top-level config which holds ChannelHandshakeLimits and ChannelConfig.
359398
///
360399
/// Default::default() provides sane defaults for most configurations

0 commit comments

Comments
 (0)