Skip to content

Commit 9e59322

Browse files
fixup: introduce SLOW_DOWN error so we don't silently fail to send a notification
1 parent f30f85b commit 9e59322

File tree

4 files changed

+66
-28
lines changed

4 files changed

+66
-28
lines changed

lightning-liquidity/src/lsps5/event.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,15 +31,13 @@ pub enum LSPS5ServiceEvent {
3131
/// The LSP should send an HTTP POST to the [`url`], using the
3232
/// JSON-serialized [`notification`] as the body and including the `headers`.
3333
/// If the HTTP request fails, the LSP may implement a retry policy according to its
34-
/// implementation preferences, but must respect rate-limiting as defined in
35-
/// [`notification_cooldown_hours`].
34+
/// implementation preferences.
3635
///
3736
/// The notification is signed using the LSP's node ID to ensure authenticity
3837
/// when received by the client. The client verifies this signature using
3938
/// [`validate`], which guards against replay attacks and tampering.
4039
///
4140
/// [`validate`]: super::validator::LSPS5Validator::validate
42-
/// [`notification_cooldown_hours`]: super::service::LSPS5ServiceConfig::notification_cooldown_hours
4341
/// [`url`]: super::msgs::LSPS5WebhookUrl
4442
/// [`notification`]: super::msgs::WebhookNotification
4543
SendWebhookNotification {

lightning-liquidity/src/lsps5/msgs.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,8 @@ pub const LSPS5_APP_NAME_NOT_FOUND_ERROR_CODE: i32 = 1010;
5151
pub const LSPS5_UNKNOWN_ERROR_CODE: i32 = 1000;
5252
/// An error occurred during serialization of LSPS5 webhook notification.
5353
pub const LSPS5_SERIALIZATION_ERROR_CODE: i32 = 1001;
54+
/// A notification was sent too frequently.
55+
pub const LSPS5_SLOW_DOWN_ERROR_CODE: i32 = 1002;
5456

5557
pub(crate) const LSPS5_SET_WEBHOOK_METHOD_NAME: &str = "lsps5.set_webhook";
5658
pub(crate) const LSPS5_LIST_WEBHOOKS_METHOD_NAME: &str = "lsps5.list_webhooks";
@@ -103,6 +105,14 @@ pub enum LSPS5ProtocolError {
103105

104106
/// Error during serialization of LSPS5 webhook notification.
105107
SerializationError,
108+
109+
/// A notification was sent too frequently.
110+
///
111+
/// This error indicates that the LSP is sending notifications
112+
/// too quickly, violating the notification cooldown [`DEFAULT_NOTIFICATION_COOLDOWN_HOURS`]
113+
///
114+
/// [`DEFAULT_NOTIFICATION_COOLDOWN_HOURS`]: super::service::LSPS5ServiceConfig::DEFAULT_NOTIFICATION_COOLDOWN_HOURS
115+
SlowDownError,
106116
}
107117

108118
impl LSPS5ProtocolError {
@@ -118,6 +128,7 @@ impl LSPS5ProtocolError {
118128
LSPS5ProtocolError::AppNameNotFound => LSPS5_APP_NAME_NOT_FOUND_ERROR_CODE,
119129
LSPS5ProtocolError::UnknownError => LSPS5_UNKNOWN_ERROR_CODE,
120130
LSPS5ProtocolError::SerializationError => LSPS5_SERIALIZATION_ERROR_CODE,
131+
LSPS5ProtocolError::SlowDownError => LSPS5_SLOW_DOWN_ERROR_CODE,
121132
}
122133
}
123134
/// The error message for the LSPS5 protocol error.
@@ -133,6 +144,7 @@ impl LSPS5ProtocolError {
133144
LSPS5ProtocolError::SerializationError => {
134145
"Error serializing LSPS5 webhook notification"
135146
},
147+
LSPS5ProtocolError::SlowDownError => "Notification sent too frequently",
136148
}
137149
}
138150
}

lightning-liquidity/src/lsps5/service.rs

Lines changed: 45 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -92,8 +92,6 @@ impl Default for LSPS5ServiceConfig {
9292
/// - `lsps5.remove_webhook` -> delete a named webhook or return [`app_name_not_found`] error.
9393
/// - Prune stale webhooks after a client has no open channels and no activity for at least
9494
/// [`MIN_WEBHOOK_RETENTION_DAYS`].
95-
/// - Rate-limit repeat notifications of the same method to a client by
96-
/// [`notification_cooldown_hours`].
9795
/// - Sign and enqueue outgoing webhook notifications:
9896
/// - Construct JSON-RPC 2.0 Notification objects [`WebhookNotification`],
9997
/// - Timestamp and LN-style zbase32-sign each payload,
@@ -108,7 +106,6 @@ impl Default for LSPS5ServiceConfig {
108106
/// [`bLIP-55 / LSPS5`]: https://github.com/lightning/blips/pull/55/files
109107
/// [`max_webhooks_per_client`]: super::service::LSPS5ServiceConfig::max_webhooks_per_client
110108
/// [`app_name_not_found`]: super::msgs::LSPS5ProtocolError::AppNameNotFound
111-
/// [`notification_cooldown_hours`]: super::service::LSPS5ServiceConfig::notification_cooldown_hours
112109
/// [`WebhookNotification`]: super::msgs::WebhookNotification
113110
/// [`LSPS5ServiceEvent::SendWebhookNotification`]: super::event::LSPS5ServiceEvent::SendWebhookNotification
114111
/// [`app_name`]: super::msgs::LSPS5AppName
@@ -224,23 +221,27 @@ where
224221
}
225222

226223
if !no_change {
227-
self.send_webhook_registered_notification(
224+
let result = self.send_webhook_registered_notification(
228225
counterparty_node_id,
229226
params.app_name,
230227
params.webhook,
231-
)
232-
.map_err(|e| {
228+
);
229+
230+
// If the send_notification failed because of a SLOW_DOWN_ERROR, it means we sent this
231+
// notification recently, and the user has not seen it yet. It's safe to continue, but we still need to handle other error types.
232+
if result.is_err() && !matches!(result, Err(LSPS5ProtocolError::SlowDownError)) {
233+
let e = result.unwrap_err();
233234
let msg = LSPS5Message::Response(
234235
request_id.clone(),
235236
LSPS5Response::SetWebhookError(e.clone().into()),
236237
)
237238
.into();
238239
self.pending_messages.enqueue(&counterparty_node_id, msg);
239-
LightningError {
240+
return Err(LightningError {
240241
err: e.message().into(),
241242
action: ErrorAction::IgnoreAndLog(Level::Info),
242-
}
243-
})?;
243+
});
244+
}
244245
}
245246

246247
let msg = LSPS5Message::Response(
@@ -326,10 +327,14 @@ where
326327
/// This builds a [`WebhookNotificationMethod::LSPS5PaymentIncoming`] webhook notification, signs it with your
327328
/// node key, and enqueues HTTP POSTs to all registered webhook URLs for that client.
328329
///
330+
/// This may fail if a similar notification was sent too recently,
331+
/// violating the notification cooldown period defined in [`DEFAULT_NOTIFICATION_COOLDOWN_HOURS`].
332+
///
329333
/// # Parameters
330334
/// - `client_id`: the client's node-ID whose webhooks should be invoked.
331335
///
332336
/// [`WebhookNotificationMethod::LSPS5PaymentIncoming`]: super::msgs::WebhookNotificationMethod::LSPS5PaymentIncoming
337+
/// [`DEFAULT_NOTIFICATION_COOLDOWN_HOURS`]: super::service::LSPS5ServiceConfig::DEFAULT_NOTIFICATION_COOLDOWN_HOURS
333338
pub fn notify_payment_incoming(&self, client_id: PublicKey) -> Result<(), LSPS5ProtocolError> {
334339
let notification = WebhookNotification::payment_incoming();
335340
self.send_notifications_to_client_webhooks(client_id, notification)
@@ -343,11 +348,15 @@ where
343348
/// the `timeout` block height, signs it, and enqueues HTTP POSTs to the client's
344349
/// registered webhooks.
345350
///
351+
/// This may fail if a similar notification was sent too recently,
352+
/// violating the notification cooldown period defined in [`DEFAULT_NOTIFICATION_COOLDOWN_HOURS`].
353+
///
346354
/// # Parameters
347355
/// - `client_id`: the client's node-ID whose webhooks should be invoked.
348356
/// - `timeout`: the block height at which the channel contract will expire.
349357
///
350358
/// [`WebhookNotificationMethod::LSPS5ExpirySoon`]: super::msgs::WebhookNotificationMethod::LSPS5ExpirySoon
359+
/// [`DEFAULT_NOTIFICATION_COOLDOWN_HOURS`]: super::service::LSPS5ServiceConfig::DEFAULT_NOTIFICATION_COOLDOWN_HOURS
351360
pub fn notify_expiry_soon(
352361
&self, client_id: PublicKey, timeout: u32,
353362
) -> Result<(), LSPS5ProtocolError> {
@@ -361,10 +370,14 @@ where
361370
/// liquidity for `client_id`. Builds a [`WebhookNotificationMethod::LSPS5LiquidityManagementRequest`] notification,
362371
/// signs it, and sends it to all of the client's registered webhook URLs.
363372
///
373+
/// This may fail if a similar notification was sent too recently,
374+
/// violating the notification cooldown period defined in [`DEFAULT_NOTIFICATION_COOLDOWN_HOURS`].
375+
///
364376
/// # Parameters
365377
/// - `client_id`: the client's node-ID whose webhooks should be invoked.
366378
///
367379
/// [`WebhookNotificationMethod::LSPS5LiquidityManagementRequest`]: super::msgs::WebhookNotificationMethod::LSPS5LiquidityManagementRequest
380+
/// [`DEFAULT_NOTIFICATION_COOLDOWN_HOURS`]: super::service::LSPS5ServiceConfig::DEFAULT_NOTIFICATION_COOLDOWN_HOURS
368381
pub fn notify_liquidity_management_request(
369382
&self, client_id: PublicKey,
370383
) -> Result<(), LSPS5ProtocolError> {
@@ -378,10 +391,14 @@ where
378391
/// for `client_id` while the client is offline. Builds a [`WebhookNotificationMethod::LSPS5OnionMessageIncoming`]
379392
/// notification, signs it, and enqueues HTTP POSTs to each registered webhook.
380393
///
394+
/// This may fail if a similar notification was sent too recently,
395+
/// violating the notification cooldown period defined in [`DEFAULT_NOTIFICATION_COOLDOWN_HOURS`].
396+
///
381397
/// # Parameters
382398
/// - `client_id`: the client's node-ID whose webhooks should be invoked.
383399
///
384400
/// [`WebhookNotificationMethod::LSPS5OnionMessageIncoming`]: super::msgs::WebhookNotificationMethod::LSPS5OnionMessageIncoming
401+
/// [`DEFAULT_NOTIFICATION_COOLDOWN_HOURS`]: super::service::LSPS5ServiceConfig::DEFAULT_NOTIFICATION_COOLDOWN_HOURS
385402
pub fn notify_onion_message_incoming(
386403
&self, client_id: PublicKey,
387404
) -> Result<(), LSPS5ProtocolError> {
@@ -402,22 +419,27 @@ where
402419
let now =
403420
LSPSDateTime::new_from_duration_since_epoch(self.time_provider.duration_since_epoch());
404421

405-
for (app_name, webhook) in client_webhooks.iter_mut() {
406-
if webhook
422+
let rate_limit_applies = client_webhooks.iter().any(|(_, webhook)| {
423+
webhook
407424
.last_notification_sent
408425
.get(&notification.method)
409-
.map(|last_sent| now.clone().abs_diff(&last_sent))
410-
.map_or(true, |duration| duration >= DEFAULT_NOTIFICATION_COOLDOWN_HOURS.as_secs())
411-
{
412-
webhook.last_notification_sent.insert(notification.method.clone(), now.clone());
413-
webhook.last_used = now.clone();
414-
self.send_notification(
415-
client_id,
416-
app_name.clone(),
417-
webhook.url.clone(),
418-
notification.clone(),
419-
)?;
420-
}
426+
.map(|last_sent| now.abs_diff(&last_sent))
427+
.map_or(false, |duration| duration < DEFAULT_NOTIFICATION_COOLDOWN_HOURS.as_secs())
428+
});
429+
430+
if rate_limit_applies {
431+
return Err(LSPS5ProtocolError::SlowDownError);
432+
}
433+
434+
for (app_name, webhook) in client_webhooks.iter_mut() {
435+
webhook.last_notification_sent.insert(notification.method.clone(), now.clone());
436+
webhook.last_used = now.clone();
437+
self.send_notification(
438+
client_id,
439+
app_name.clone(),
440+
webhook.url.clone(),
441+
notification.clone(),
442+
)?;
421443
}
422444
Ok(())
423445
}

lightning-liquidity/tests/lsps5_integration_tests.rs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1093,7 +1093,9 @@ fn test_send_notifications_and_peer_connected_resets_cooldown() {
10931093
}
10941094

10951095
// 2. Second notification before cooldown should NOT be sent
1096-
let _ = service_handler.notify_payment_incoming(client_node_id);
1096+
let result = service_handler.notify_payment_incoming(client_node_id);
1097+
let error = result.unwrap_err();
1098+
assert_eq!(error, LSPS5ProtocolError::SlowDownError);
10971099
assert!(
10981100
service_node.liquidity_manager.next_event().is_none(),
10991101
"Should not emit event due to cooldown"
@@ -1132,7 +1134,11 @@ fn test_send_notifications_and_peer_connected_resets_cooldown() {
11321134
}
11331135

11341136
// 5. Can't send payment_incoming notification again immediately after cooldown
1135-
let _ = service_handler.notify_payment_incoming(client_node_id);
1137+
let result = service_handler.notify_payment_incoming(client_node_id);
1138+
1139+
let error = result.unwrap_err();
1140+
assert_eq!(error, LSPS5ProtocolError::SlowDownError);
1141+
11361142
assert!(
11371143
service_node.liquidity_manager.next_event().is_none(),
11381144
"Should not emit event due to cooldown"

0 commit comments

Comments
 (0)