Skip to content

Commit c7d2086

Browse files
committed
Fail payment retry if Invoice is expired
According to BOLT 11: - after the `timestamp` plus `expiry` has passed - SHOULD NOT attempt a payment Add a convenience method for checking if an Invoice has expired, and use it to short-circuit payment retries.
1 parent 0b1ae6b commit c7d2086

File tree

2 files changed

+87
-1
lines changed

2 files changed

+87
-1
lines changed

lightning-invoice/src/lib.rs

+36
Original file line numberDiff line numberDiff line change
@@ -1188,6 +1188,14 @@ impl Invoice {
11881188
.unwrap_or(Duration::from_secs(DEFAULT_EXPIRY_TIME))
11891189
}
11901190

1191+
/// Returns whether the invoice has expired.
1192+
pub fn is_expired(&self) -> bool {
1193+
match self.timestamp().elapsed() {
1194+
Ok(elapsed) => elapsed > self.expiry_time(),
1195+
Err(_) => false,
1196+
}
1197+
}
1198+
11911199
/// Returns the invoice's `min_final_cltv_expiry` time, if present, otherwise
11921200
/// [`DEFAULT_MIN_FINAL_CLTV_EXPIRY`].
11931201
pub fn min_final_cltv_expiry(&self) -> u64 {
@@ -1914,5 +1922,33 @@ mod test {
19141922

19151923
assert_eq!(invoice.min_final_cltv_expiry(), DEFAULT_MIN_FINAL_CLTV_EXPIRY);
19161924
assert_eq!(invoice.expiry_time(), Duration::from_secs(DEFAULT_EXPIRY_TIME));
1925+
assert!(!invoice.is_expired());
1926+
}
1927+
1928+
#[test]
1929+
fn test_expiration() {
1930+
use ::*;
1931+
use secp256k1::Secp256k1;
1932+
use secp256k1::key::SecretKey;
1933+
1934+
let timestamp = SystemTime::now()
1935+
.checked_sub(Duration::from_secs(DEFAULT_EXPIRY_TIME * 2))
1936+
.unwrap();
1937+
let signed_invoice = InvoiceBuilder::new(Currency::Bitcoin)
1938+
.description("Test".into())
1939+
.payment_hash(sha256::Hash::from_slice(&[0;32][..]).unwrap())
1940+
.payment_secret(PaymentSecret([0; 32]))
1941+
.timestamp(timestamp)
1942+
.build_raw()
1943+
.unwrap()
1944+
.sign::<_, ()>(|hash| {
1945+
let privkey = SecretKey::from_slice(&[41; 32]).unwrap();
1946+
let secp_ctx = Secp256k1::new();
1947+
Ok(secp_ctx.sign_recoverable(hash, &privkey))
1948+
})
1949+
.unwrap();
1950+
let invoice = Invoice::from_signed(signed_invoice).unwrap();
1951+
1952+
assert!(invoice.is_expired());
19171953
}
19181954
}

lightning-invoice/src/payment.rs

+51-1
Original file line numberDiff line numberDiff line change
@@ -270,6 +270,8 @@ where
270270
log_trace!(self.logger, "Payment {} rejected by destination; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
271271
} else if *attempts == max_payment_attempts {
272272
log_trace!(self.logger, "Payment {} failed; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
273+
} else if invoice.is_expired() {
274+
log_trace!(self.logger, "Invoice expired for payment {}; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
273275
} else if self.pay_cached_invoice(invoice).is_err() {
274276
log_trace!(self.logger, "Error retrying payment {}; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
275277
} else {
@@ -303,13 +305,14 @@ where
303305
#[cfg(test)]
304306
mod tests {
305307
use super::*;
306-
use crate::{InvoiceBuilder, Currency};
308+
use crate::{DEFAULT_EXPIRY_TIME, InvoiceBuilder, Currency};
307309
use lightning::ln::PaymentPreimage;
308310
use lightning::ln::msgs::{ErrorAction, LightningError};
309311
use lightning::util::test_utils::TestLogger;
310312
use lightning::util::errors::APIError;
311313
use lightning::util::events::Event;
312314
use secp256k1::{SecretKey, PublicKey, Secp256k1};
315+
use std::time::{SystemTime, Duration};
313316

314317
fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
315318
let payment_hash = Sha256::hash(&payment_preimage.0);
@@ -327,6 +330,25 @@ mod tests {
327330
.unwrap()
328331
}
329332

333+
fn expired_invoice(payment_preimage: PaymentPreimage) -> Invoice {
334+
let payment_hash = Sha256::hash(&payment_preimage.0);
335+
let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
336+
let timestamp = SystemTime::now()
337+
.checked_sub(Duration::from_secs(DEFAULT_EXPIRY_TIME * 2))
338+
.unwrap();
339+
InvoiceBuilder::new(Currency::Bitcoin)
340+
.description("test".into())
341+
.payment_hash(payment_hash)
342+
.payment_secret(PaymentSecret([0; 32]))
343+
.timestamp(timestamp)
344+
.min_final_cltv_expiry(144)
345+
.amount_milli_satoshis(100)
346+
.build_signed(|hash| {
347+
Secp256k1::new().sign_recoverable(hash, &private_key)
348+
})
349+
.unwrap()
350+
}
351+
330352
#[test]
331353
fn pays_invoice_on_first_attempt() {
332354
let event_handled = core::cell::RefCell::new(false);
@@ -415,6 +437,34 @@ mod tests {
415437
assert_eq!(*payer.attempts.borrow(), 3);
416438
}
417439

440+
#[test]
441+
fn fails_paying_invoice_after_expiration() {
442+
let event_handled = core::cell::RefCell::new(false);
443+
let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
444+
445+
let payer = TestPayer::new();
446+
let router = NullRouter {};
447+
let logger = TestLogger::new();
448+
let invoice_payer = InvoicePayer::new(&payer, router, &logger, event_handler)
449+
.with_retry_attempts(2);
450+
451+
let payment_preimage = PaymentPreimage([1; 32]);
452+
let invoice = expired_invoice(payment_preimage);
453+
assert!(invoice_payer.pay_invoice(&invoice).is_ok());
454+
assert_eq!(*payer.attempts.borrow(), 1);
455+
456+
let event = Event::PaymentPathFailed {
457+
payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
458+
network_update: None,
459+
rejected_by_dest: false,
460+
all_paths_failed: true,
461+
path: vec![],
462+
};
463+
invoice_payer.handle_event(&event);
464+
assert_eq!(*event_handled.borrow(), true);
465+
assert_eq!(*payer.attempts.borrow(), 1);
466+
}
467+
418468
#[test]
419469
fn fails_paying_invoice_after_retry_error() {
420470
let event_handled = core::cell::RefCell::new(false);

0 commit comments

Comments
 (0)