Skip to content

Add LSPS5 DOS protections. #3993

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions lightning-liquidity/src/lsps1/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,15 @@ where
&self.config
}

pub(crate) fn has_active_requests(&self, counterparty_node_id: &PublicKey) -> bool {
Copy link
Contributor

@tnull tnull Aug 12, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

May be a tad easier to read:

pub(crate) fn has_active_requests(&self, counterparty_node_id: &PublicKey) -> bool {
	let outer_state_lock = self.per_peer_state.read().unwrap();
	outer_state_lock.get(counterparty_node_id).map_or(false, |inner| {
		let inner_state_lock = inner.lock().unwrap();
		!(peer_state.pending_requests.is_empty()
			&& peer_state.outbound_channels_by_order_id.is_empty())
	})
}

(here and below)

let outer_state_lock = self.per_peer_state.read().unwrap();
outer_state_lock.get(counterparty_node_id).map_or(false, |inner| {
let peer_state = inner.lock().unwrap();
!(peer_state.pending_requests.is_empty()
&& peer_state.outbound_channels_by_order_id.is_empty())
})
}

fn handle_get_info_request(
&self, request_id: LSPSRequestId, counterparty_node_id: &PublicKey,
) -> Result<(), LightningError> {
Expand Down
104 changes: 102 additions & 2 deletions lightning-liquidity/src/lsps2/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,9 +107,18 @@ struct ForwardPaymentAction(ChannelId, FeePayment);
#[derive(Debug, PartialEq)]
struct ForwardHTLCsAction(ChannelId, Vec<InterceptedHTLC>);

#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub(crate) enum OutboundJITStage {
PendingInitialPayment,
PendingChannelOpen,
PendingPaymentForward,
PendingPayment,
PaymentForwarded,
}

/// The different states a requested JIT channel can be in.
#[derive(Debug)]
enum OutboundJITChannelState {
#[derive(Debug, PartialEq, Eq, Clone)]
pub(crate) enum OutboundJITChannelState {
/// The JIT channel SCID was created after a buy request, and we are awaiting an initial payment
/// of sufficient size to open the channel.
PendingInitialPayment { payment_queue: PaymentQueue },
Expand All @@ -134,6 +143,36 @@ enum OutboundJITChannelState {
PaymentForwarded { channel_id: ChannelId },
}

impl OutboundJITChannelState {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need this explicit implementation? Wouldn't derive(PartialOrd) do the ~the same thing?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this would need putting also the derive(Ord) and derive(PartialOrd) on PaymentQueue and InterceptId

happy to do it but wanted to minimize changes

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

seems like I can't define Ord but derive PartialOrd

from the linter:

error: you are implementing `Ord` explicitly but have derived `PartialOrd`
   --> lightning-liquidity/src/lsps2/service.rs:164:1
    |
164 | / impl Ord for OutboundJITChannelState {
165 | |     fn cmp(&self, other: &Self) -> core::cmp::Ordering {
166 | |         self.stage().cmp(&other.stage())
167 | |     }
168 | | }
    | |_^

pub(crate) fn stage(&self) -> OutboundJITStage {
match self {
OutboundJITChannelState::PendingInitialPayment { .. } => {
OutboundJITStage::PendingInitialPayment
},
OutboundJITChannelState::PendingChannelOpen { .. } => {
OutboundJITStage::PendingChannelOpen
},
OutboundJITChannelState::PendingPaymentForward { .. } => {
OutboundJITStage::PendingPaymentForward
},
OutboundJITChannelState::PendingPayment { .. } => OutboundJITStage::PendingPayment,
OutboundJITChannelState::PaymentForwarded { .. } => OutboundJITStage::PaymentForwarded,
}
}
}

impl PartialOrd for OutboundJITChannelState {
fn partial_cmp(&self, other: &Self) -> Option<CmpOrdering> {
Some(self.cmp(other))
}
}

impl Ord for OutboundJITChannelState {
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
self.stage().cmp(&other.stage())
}
}

impl OutboundJITChannelState {
fn new() -> Self {
OutboundJITChannelState::PendingInitialPayment { payment_queue: PaymentQueue::new() }
Expand Down Expand Up @@ -572,6 +611,16 @@ where
&self.config
}

pub(crate) fn highest_state_for_peer(
&self, counterparty_node_id: &PublicKey,
) -> Option<OutboundJITChannelState> {
let outer_state_lock = self.per_peer_state.read().unwrap();
outer_state_lock.get(counterparty_node_id).and_then(|inner| {
let peer_state = inner.lock().unwrap();
peer_state.outbound_channels_by_intercept_scid.values().map(|c| c.state.clone()).max()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't buy we need to clone here.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

error[E0507]: cannot move out of `c.state` which is behind a shared reference
   --> lightning-liquidity/src/lsps2/service.rs:599:68
    |
599 |             peer_state.outbound_channels_by_intercept_scid.values().map(|c| c.state).max()
    |                                                                             ^^^^^^^ move occurs because `c.state` has type `OutboundJITChannelState`, which does not implement the `Copy` trait
    |
help: consider cloning the value if the performance cost is acceptable
    |
599 |             peer_state.outbound_channels_by_intercept_scid.values().map(|c| c.state.clone()).max()
    |                                                                                    ++++++++

})
}

/// Used by LSP to inform a client requesting a JIT Channel the token they used is invalid.
///
/// Should be called in response to receiving a [`LSPS2ServiceEvent::GetInfo`] event.
Expand Down Expand Up @@ -1905,4 +1954,55 @@ mod tests {
);
}
}

#[test]
fn highest_state_for_peer_orders() {
let opening_fee_params = LSPS2OpeningFeeParams {
min_fee_msat: 0,
proportional: 0,
valid_until: LSPSDateTime::from_str("1970-01-01T00:00:00Z").unwrap(),
min_lifetime: 0,
max_client_to_self_delay: 0,
min_payment_size_msat: 0,
max_payment_size_msat: 0,
promise: String::new(),
};

let mut map = new_hash_map();
map.insert(
0,
OutboundJITChannel {
state: OutboundJITChannelState::PendingInitialPayment {
payment_queue: PaymentQueue::new(),
},
user_channel_id: 0,
opening_fee_params: opening_fee_params.clone(),
payment_size_msat: None,
},
);
map.insert(
1,
OutboundJITChannel {
state: OutboundJITChannelState::PendingChannelOpen {
payment_queue: PaymentQueue::new(),
opening_fee_msat: 0,
},
user_channel_id: 1,
opening_fee_params: opening_fee_params.clone(),
payment_size_msat: None,
},
);
map.insert(
2,
OutboundJITChannel {
state: OutboundJITChannelState::PaymentForwarded { channel_id: ChannelId([0; 32]) },
user_channel_id: 2,
opening_fee_params,
payment_size_msat: None,
},
);

let max_state = map.values().map(|c| c.state.clone()).max().unwrap();
assert!(matches!(max_state, OutboundJITChannelState::PaymentForwarded { .. }));
}
}
17 changes: 16 additions & 1 deletion lightning-liquidity/src/lsps5/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ use crate::prelude::*;
use crate::sync::{Arc, Mutex};
use crate::utils::time::TimeProvider;

use crate::lsps2::service::{OutboundJITChannelState, OutboundJITStage};
use bitcoin::secp256k1::PublicKey;

use lightning::ln::channelmanager::AChannelManager;
Expand Down Expand Up @@ -150,6 +151,20 @@ where
}
}

/// Returns whether a request from the given client should be accepted.
///
/// Prior activity includes an existing open channel, an active LSPS1 flow,
/// or an LSPS2 flow that has progressed to at least
/// [`OutboundJITChannelState::PendingChannelOpen`].
pub(crate) fn can_accept_request(
&self, client_id: &PublicKey, lsps2_max_state: Option<OutboundJITChannelState>,
lsps1_has_activity: bool,
) -> bool {
self.client_has_open_channel(client_id)
|| lsps1_has_activity
|| lsps2_max_state.map_or(false, |s| s.stage() >= OutboundJITStage::PendingChannelOpen)
}

fn check_prune_stale_webhooks(&self) {
let now =
LSPSDateTime::new_from_duration_since_epoch(self.time_provider.duration_since_epoch());
Expand Down Expand Up @@ -515,7 +530,7 @@ where
*last_pruning = Some(now);
}

fn client_has_open_channel(&self, client_id: &PublicKey) -> bool {
pub(crate) fn client_has_open_channel(&self, client_id: &PublicKey) -> bool {
self.channel_manager
.get_cm()
.list_channels()
Expand Down
26 changes: 26 additions & 0 deletions lightning-liquidity/src/manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -559,6 +559,32 @@ where
LSPSMessage::LSPS5(msg @ LSPS5Message::Request(..)) => {
match &self.lsps5_service_handler {
Some(lsps5_service_handler) => {
let lsps2_max_state = self
.lsps2_service_handler
.as_ref()
.and_then(|h| h.highest_state_for_peer(sender_node_id));
#[cfg(lsps1_service)]
let lsps1_has_active_requests = self
.lsps1_service_handler
.as_ref()
.map_or(false, |h| h.has_active_requests(sender_node_id));
#[cfg(not(lsps1_service))]
let lsps1_has_active_requests = false;

if !lsps5_service_handler.can_accept_request(
sender_node_id,
lsps2_max_state,
lsps1_has_active_requests,
) {
return Err(LightningError {
err: format!(
"Rejecting LSPS5 request from {:?} without prior activity (requires open channel or active LSPS1 or LSPS2 flow)",
sender_node_id
),
action: ErrorAction::IgnoreAndLog(Level::Debug),
});
}

lsps5_service_handler.handle_message(msg, sender_node_id)?;
},
None => {
Expand Down
Loading
Loading