Skip to content
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
16 changes: 13 additions & 3 deletions src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,9 @@ use crate::io::{
use crate::liquidity::LiquiditySource;
use crate::logger::{log_debug, log_error, log_info, log_trace, LdkLogger, Logger};
use crate::payment::asynchronous::om_mailbox::OnionMessageMailbox;
use crate::payment::asynchronous::static_invoice_store::StaticInvoiceStore;
use crate::payment::asynchronous::static_invoice_store::{
StaticInvoiceStore, StaticInvoiceStoreError,
};
use crate::payment::forwarding_store::{ForwardRecord, ForwardingStore};
use crate::payment::store::{
Channel, PaymentDetails, PaymentDetailsUpdate, PaymentDirection, PaymentKind, PaymentStatus,
Expand Down Expand Up @@ -2518,7 +2520,11 @@ where
Ok(_) => {
self.channel_manager.static_invoice_persisted(invoice_persisted_path);
},
Err(e) => {
Err(StaticInvoiceStoreError::RateLimited) => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Don't we want to skip the rate limiter once we are retrying persistence, so that we don't exit the retry loop because new requests came in?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Added a fixup for this.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Agree with not logging every rejected request, but right now rate limiting is completely invisible: an operator debugging failed async payments sees nothing at any log level. Could we log once when a recipient's bucket first runs empty (or keep a simple counter), so the condition is observable without per-request logging? Same for the arm at L2563.

// Drop silently: logging each rejected request, even at trace level,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Claude had one thing on this still:

An async recipient comes online and requests offer paths for ~10 cached offer slots, which produces ~10 PersistStaticInvoice events for one recipient_id in one batch. The first 5 are persisted; the rest hit RateLimited and are dropped with no ack. Those slots are not stored until the client's retry timer fires, so payers asking for those slots get no invoice in the meantime. Before this PR the same events were replayed and succeeded about 100ms later.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

That mostly means we should align the rate limit to allow for this, no?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Maybe it's a bit of a weird coupling, but it seems the pragmatic fix for now

// can cause excessive log output and I/O under sustained load.
},
Err(StaticInvoiceStoreError::Io(e)) => {
log_error!(self.logger, "Failed to persist static invoice: {}", e);
return Err(ReplayEvent());
},
Expand Down Expand Up @@ -2554,7 +2560,11 @@ where
invoice_slot
);
},
Err(e) => {
Err(StaticInvoiceStoreError::RateLimited) => {
// Drop silently: logging each rejected request, even at trace level,
// can cause excessive log output and I/O under sustained load.
},
Err(StaticInvoiceStoreError::Io(e)) => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

A decode failure (InvalidData) also lands here, so a corrupted record gets replayed forever and holds up every later event, though this isn't new with this PR. Since it won't recover, should we log it and drop the request instead, and only replay real storage errors?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

For StaticInvoiceRequested, replaying on a storage read error means a slow or temporarily failing store holds up every event behind it, including time-critical ones like HTLC claims. Nothing is lost by dropping the request instead, as the payer can retry. Would it make sense to log and drop on read errors here, and keep ReplayEvent only for PersistStaticInvoice (L2527), where we can't lose the write?

log_error!(self.logger, "Failed to retrieve static invoice: {}", e);
return Err(ReplayEvent());
},
Expand Down
14 changes: 14 additions & 0 deletions src/payment/asynchronous/rate_limiter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,24 @@ impl RateLimiter {
allow
}

/// Returns a token consumed by an admitted request that could not be completed.
pub(crate) fn refund(&mut self, user_id: &[u8]) {
if let Some(bucket) = self.users.get_mut(user_id) {
bucket.tokens = bucket.tokens.saturating_add(1).min(self.capacity);
}
}

fn garbage_collect(&mut self, max_idle: Duration) {
let now = Instant::now();
self.users.retain(|_, bucket| now.duration_since(bucket.last_refill) < max_idle);
}

#[cfg(test)]
pub(super) fn advance_refill_interval(&mut self) {
for bucket in self.users.values_mut() {
bucket.last_refill -= self.refill_interval;
}
}
}

#[cfg(test)]
Expand Down
209 changes: 183 additions & 26 deletions src/payment/asynchronous/static_invoice_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,18 @@ impl_writeable_tlv_based!(PersistedStaticInvoice, {
(2, request_path, required)
});

#[derive(Debug)]
pub(crate) enum StaticInvoiceStoreError {
Comment thread
tnull marked this conversation as resolved.
Resolved
RateLimited,
Io(lightning::io::Error),
}

pub(crate) struct StaticInvoiceStore {
kv_store: Arc<DynStore>,
// A request whose storage operation fails returns its token. ChannelManager processes these
// events serially and replays a failed event before handling later ones, so this keeps
// retries admitted until storage recovers. If these operations are ever processed
// concurrently, admission must be tracked per request instead.
request_rate_limiter: Mutex<RateLimiter>,
persist_rate_limiter: Mutex<RateLimiter>,
}
Expand All @@ -60,22 +70,40 @@ impl StaticInvoiceStore {
}
}

fn check_rate_limit(
limiter: &Mutex<RateLimiter>, recipient_id: &[u8],
) -> Result<(), lightning::io::Error> {
let mut limiter = limiter.lock().expect("lock");
if !limiter.allow(recipient_id) {
Err(lightning::io::Error::new(lightning::io::ErrorKind::Other, "Rate limit exceeded"))
} else {
Ok(())
pub(crate) async fn handle_static_invoice_requested(
&self, recipient_id: &[u8], invoice_slot: u16,
) -> Result<Option<(StaticInvoice, BlindedMessagePath)>, StaticInvoiceStoreError> {
if !self.request_rate_limiter.lock().expect("lock").allow(recipient_id) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Since the request limiter is keyed only by recipient_id (5 tokens, refilled every 100ms), all payers of a recipient share one bucket. Anyone sending more than ~10 requests/s for a public offer keeps it empty, and with this change honest payers' requests for that recipient are then silently dropped.

Not new to this PR, but worth considering whether the limit should also be scoped per requester/reply path, or at least documenting that it is shared across payers.

return Err(StaticInvoiceStoreError::RateLimited);
}

let res = self.read_static_invoice(recipient_id, invoice_slot).await;
if res.is_err() {
self.request_rate_limiter.lock().expect("lock").refund(recipient_id);
}
res.map_err(StaticInvoiceStoreError::Io)
}

pub(crate) async fn handle_static_invoice_requested(
pub(crate) async fn handle_persist_static_invoice(
&self, invoice: StaticInvoice, invoice_request_path: BlindedMessagePath, invoice_slot: u16,
recipient_id: Vec<u8>,
) -> Result<(), StaticInvoiceStoreError> {
if !self.persist_rate_limiter.lock().expect("lock").allow(&recipient_id) {
return Err(StaticInvoiceStoreError::RateLimited);
}

let res = self
.write_static_invoice(invoice, invoice_request_path, invoice_slot, &recipient_id)
.await;
if res.is_err() {
self.persist_rate_limiter.lock().expect("lock").refund(&recipient_id);
}
res.map_err(StaticInvoiceStoreError::Io)
}

async fn read_static_invoice(
&self, recipient_id: &[u8], invoice_slot: u16,
) -> Result<Option<(StaticInvoice, BlindedMessagePath)>, lightning::io::Error> {
Self::check_rate_limit(&self.request_rate_limiter, &recipient_id)?;

let (secondary_namespace, key) = Self::get_storage_location(invoice_slot, recipient_id);

KVStore::read(
Expand All @@ -97,24 +125,14 @@ impl StaticInvoiceStore {
)
})
})
.or_else(
|e| {
if e.kind() == lightning::io::ErrorKind::NotFound {
Ok(None)
} else {
Err(e)
}
},
)
.or_else(|e| if e.kind() == lightning::io::ErrorKind::NotFound { Ok(None) } else { Err(e) })

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

A persisted invoice that fails to decode still blocks the event queue: the decode error (L123) becomes InvalidData, passes through here as a regular error, surfaces as StaticInvoiceStoreError::Io, and StaticInvoiceRequested returns ReplayEvent for it. With the refund, every replay is admitted, so the event is retried indefinitely and nothing queued behind it (e.g. PaymentClaimable) gets handled until the key is removed by hand.

Since a decode failure won't fix itself on retry, could we treat it as permanent, i.e. log it and return Ok(None) (or remove the entry)? Happy for this to be a follow-up, as it predates this PR.

}

pub(crate) async fn handle_persist_static_invoice(
async fn write_static_invoice(
&self, invoice: StaticInvoice, invoice_request_path: BlindedMessagePath, invoice_slot: u16,
recipient_id: Vec<u8>,
recipient_id: &[u8],
) -> Result<(), lightning::io::Error> {
Self::check_rate_limit(&self.persist_rate_limiter, &recipient_id)?;

let (secondary_namespace, key) = Self::get_storage_location(invoice_slot, &recipient_id);
let (secondary_namespace, key) = Self::get_storage_location(invoice_slot, recipient_id);

let persisted_invoice =
PersistedStaticInvoice { invoice, request_path: invoice_request_path };
Expand Down Expand Up @@ -146,6 +164,8 @@ impl StaticInvoiceStore {

#[cfg(test)]
mod tests {
use std::future::Future;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;

Expand All @@ -154,17 +174,82 @@ mod tests {
use lightning::blinded_path::message::BlindedMessagePath;
use lightning::blinded_path::payment::{BlindedPayInfo, BlindedPaymentPath};
use lightning::blinded_path::BlindedHop;
use lightning::io;
use lightning::ln::inbound_payment::ExpandedKey;
use lightning::offers::nonce::Nonce;
use lightning::offers::offer::OfferBuilder;
use lightning::offers::static_invoice::{StaticInvoice, StaticInvoiceBuilder};
use lightning::sign::EntropySource;
use lightning::util::persist::{KVStore, PageToken, PaginatedKVStore, PaginatedListResponse};
use lightning_types::features::BlindedHopFeatures;

use crate::io::test_utils::InMemoryStore;
use crate::payment::asynchronous::static_invoice_store::StaticInvoiceStore;
use crate::payment::asynchronous::rate_limiter::RateLimiter;
use crate::payment::asynchronous::static_invoice_store::{
StaticInvoiceStore, StaticInvoiceStoreError,
};
use crate::types::{DynStore, DynStoreWrapper};

struct FailingStore {
inner: InMemoryStore,
fail: Arc<AtomicBool>,
}

impl FailingStore {
fn check(&self) -> Result<(), io::Error> {
if self.fail.load(Ordering::Relaxed) {
Err(io::Error::new(io::ErrorKind::Other, "injected storage failure"))
} else {
Ok(())
}
}
}

impl KVStore for FailingStore {
fn read(
&self, primary: &str, secondary: &str, key: &str,
) -> impl Future<Output = Result<Vec<u8>, io::Error>> + Send + 'static {
let res = self.check().map(|()| self.inner.read(primary, secondary, key));
async move { res?.await }
}

fn write(
&self, primary: &str, secondary: &str, key: &str, buf: Vec<u8>,
) -> impl Future<Output = Result<(), io::Error>> + Send + 'static {
let res = self.check().map(|()| self.inner.write(primary, secondary, key, buf));
async move { res?.await }
}

fn remove(
&self, primary: &str, secondary: &str, key: &str, lazy: bool,
) -> impl Future<Output = Result<(), io::Error>> + Send + 'static {
self.inner.remove(primary, secondary, key, lazy)
}

fn list(
&self, primary: &str, secondary: &str,
) -> impl Future<Output = Result<Vec<String>, io::Error>> + Send + 'static {
self.inner.list(primary, secondary)
}
}

impl PaginatedKVStore for FailingStore {
fn list_paginated(
&self, primary: &str, secondary: &str, page_token: Option<PageToken>,
) -> impl Future<Output = Result<PaginatedListResponse, io::Error>> + Send + 'static {
self.inner.list_paginated(primary, secondary, page_token)
}
}

fn single_token_store(kv_store: Arc<DynStore>) -> StaticInvoiceStore {
let mut store = StaticInvoiceStore::new(kv_store);
for limiter in [&mut store.request_rate_limiter, &mut store.persist_rate_limiter] {
*limiter.get_mut().unwrap() =
RateLimiter::new(1, Duration::from_secs(3600), Duration::from_secs(7200));
}
store
}

#[tokio::test]
async fn static_invoice_store_test() {
let store: Arc<DynStore> = Arc::new(DynStoreWrapper(InMemoryStore::new()));
Expand Down Expand Up @@ -201,6 +286,78 @@ mod tests {
.is_none());
}

#[tokio::test]
async fn static_invoice_rate_limiting() {
let kv_store: Arc<DynStore> = Arc::new(DynStoreWrapper(InMemoryStore::new()));
let mut store = single_token_store(kv_store);
let recipient_id = vec![1, 1, 1];

store
.handle_persist_static_invoice(invoice(), blinded_path(), 0, recipient_id.clone())
.await
.unwrap();
assert!(matches!(
store
.handle_persist_static_invoice(invoice(), blinded_path(), 0, recipient_id.clone())
.await,
Err(StaticInvoiceStoreError::RateLimited)
));

// Missing invoices consume quota too, and rejected requests must not refund it.
assert!(store.handle_static_invoice_requested(&recipient_id, 1).await.unwrap().is_none());
for _ in 0..2 {
assert!(matches!(
store.handle_static_invoice_requested(&recipient_id, 0).await,
Err(StaticInvoiceStoreError::RateLimited)
));
}
assert!(store.handle_static_invoice_requested(&[2, 2, 2], 0).await.is_ok());

store.request_rate_limiter.get_mut().unwrap().advance_refill_interval();
assert!(store.handle_static_invoice_requested(&recipient_id, 0).await.unwrap().is_some());
}

#[tokio::test]
async fn static_invoice_storage_errors_retain_admission() {
let fail = Arc::new(AtomicBool::new(true));
let kv_store: Arc<DynStore> = Arc::new(DynStoreWrapper(FailingStore {
inner: InMemoryStore::new(),
fail: Arc::clone(&fail),
}));
let store = single_token_store(kv_store);
let recipient_id = vec![1, 1, 1];
let invoice = invoice();

// Retries of a failed event must not exhaust the recipient's quota.
for _ in 0..3 {
assert!(matches!(
store
.handle_persist_static_invoice(
invoice.clone(),
blinded_path(),
0,
recipient_id.clone()
)
.await,
Err(StaticInvoiceStoreError::Io(_))
));
assert!(matches!(
store.handle_static_invoice_requested(&recipient_id, 0).await,
Err(StaticInvoiceStoreError::Io(_))
));
}

fail.store(false, Ordering::Relaxed);
store
.handle_persist_static_invoice(invoice.clone(), blinded_path(), 0, recipient_id.clone())
.await
.unwrap();
assert_eq!(
store.handle_static_invoice_requested(&recipient_id, 0).await.unwrap(),
Some((invoice, blinded_path()))
);
}

fn invoice() -> StaticInvoice {
let node_id = recipient_pubkey();
let payment_paths = payment_paths();
Expand Down
Loading