Skip to content

Commit d9b9916

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 e523e58 commit d9b9916

File tree

3 files changed

+117
-1
lines changed

3 files changed

+117
-1
lines changed

lightning-invoice/src/lib.rs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1188,6 +1188,19 @@ 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+
Self::is_expired_from_epoch(self.timestamp(), self.expiry_time())
1194+
}
1195+
1196+
/// Returns whether the expiry time from the given epoch has passed.
1197+
pub(crate) fn is_expired_from_epoch(epoch: &SystemTime, expiry_time: Duration) -> bool {
1198+
match epoch.elapsed() {
1199+
Ok(elapsed) => elapsed > expiry_time,
1200+
Err(_) => false,
1201+
}
1202+
}
1203+
11911204
/// Returns the invoice's `min_final_cltv_expiry` time, if present, otherwise
11921205
/// [`DEFAULT_MIN_FINAL_CLTV_EXPIRY`].
11931206
pub fn min_final_cltv_expiry(&self) -> u64 {
@@ -1920,5 +1933,33 @@ mod test {
19201933

19211934
assert_eq!(invoice.min_final_cltv_expiry(), DEFAULT_MIN_FINAL_CLTV_EXPIRY);
19221935
assert_eq!(invoice.expiry_time(), Duration::from_secs(DEFAULT_EXPIRY_TIME));
1936+
assert!(!invoice.is_expired());
1937+
}
1938+
1939+
#[test]
1940+
fn test_expiration() {
1941+
use ::*;
1942+
use secp256k1::Secp256k1;
1943+
use secp256k1::key::SecretKey;
1944+
1945+
let timestamp = SystemTime::now()
1946+
.checked_sub(Duration::from_secs(DEFAULT_EXPIRY_TIME * 2))
1947+
.unwrap();
1948+
let signed_invoice = InvoiceBuilder::new(Currency::Bitcoin)
1949+
.description("Test".into())
1950+
.payment_hash(sha256::Hash::from_slice(&[0;32][..]).unwrap())
1951+
.payment_secret(PaymentSecret([0; 32]))
1952+
.timestamp(timestamp)
1953+
.build_raw()
1954+
.unwrap()
1955+
.sign::<_, ()>(|hash| {
1956+
let privkey = SecretKey::from_slice(&[41; 32]).unwrap();
1957+
let secp_ctx = Secp256k1::new();
1958+
Ok(secp_ctx.sign_recoverable(hash, &privkey))
1959+
})
1960+
.unwrap();
1961+
let invoice = Invoice::from_signed(signed_invoice).unwrap();
1962+
1963+
assert!(invoice.is_expired());
19231964
}
19241965
}

lightning-invoice/src/payment.rs

Lines changed: 66 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,7 @@ use secp256k1::key::PublicKey;
114114
use std::collections::hash_map::{self, HashMap};
115115
use std::ops::Deref;
116116
use std::sync::Mutex;
117+
use std::time::{Duration, SystemTime};
117118

118119
/// A utility for paying [`Invoice]`s.
119120
pub struct InvoicePayer<P: Deref, R, L: Deref, E>
@@ -226,6 +227,7 @@ where
226227
hash_map::Entry::Vacant(entry) => {
227228
let payer = self.payer.node_id();
228229
let mut payee = Payee::new(invoice.recover_payee_pub_key())
230+
.with_expiry_time(expiry_time_from_unix_epoch(&invoice).as_secs())
229231
.with_route_hints(invoice.route_hints());
230232
if let Some(features) = invoice.features() {
231233
payee = payee.with_features(features.clone());
@@ -273,6 +275,15 @@ where
273275
}
274276
}
275277

278+
fn expiry_time_from_unix_epoch(invoice: &Invoice) -> Duration {
279+
invoice.timestamp().duration_since(SystemTime::UNIX_EPOCH).unwrap() + invoice.expiry_time()
280+
}
281+
282+
fn has_expired(params: &RouteParameters) -> bool {
283+
let expiry_time = Duration::from_secs(params.payee.expiry_time.unwrap());
284+
Invoice::is_expired_from_epoch(&SystemTime::UNIX_EPOCH, expiry_time)
285+
}
286+
276287
impl<P: Deref, R, L: Deref, E> EventHandler for InvoicePayer<P, R, L, E>
277288
where
278289
P::Target: Payer,
@@ -304,6 +315,8 @@ where
304315
log_trace!(self.logger, "Payment {} exceeded maximum attempts; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
305316
} else if retry.is_none() {
306317
log_trace!(self.logger, "Payment {} missing retry params; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
318+
} else if has_expired(retry.as_ref().unwrap()) {
319+
log_trace!(self.logger, "Invoice expired for payment {}; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
307320
} else if self.retry_payment(*payment_id.as_ref().unwrap(), retry.as_ref().unwrap()).is_err() {
308321
log_trace!(self.logger, "Error retrying payment {}; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
309322
} else {
@@ -336,7 +349,7 @@ where
336349
#[cfg(test)]
337350
mod tests {
338351
use super::*;
339-
use crate::{InvoiceBuilder, Currency};
352+
use crate::{DEFAULT_EXPIRY_TIME, InvoiceBuilder, Currency};
340353
use bitcoin_hashes::sha256::Hash as Sha256;
341354
use lightning::ln::PaymentPreimage;
342355
use lightning::ln::features::{ChannelFeatures, NodeFeatures};
@@ -346,6 +359,7 @@ mod tests {
346359
use lightning::util::errors::APIError;
347360
use lightning::util::events::Event;
348361
use secp256k1::{SecretKey, PublicKey, Secp256k1};
362+
use std::time::{SystemTime, Duration};
349363

350364
fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
351365
let payment_hash = Sha256::hash(&payment_preimage.0);
@@ -378,6 +392,25 @@ mod tests {
378392
.unwrap()
379393
}
380394

395+
fn expired_invoice(payment_preimage: PaymentPreimage) -> Invoice {
396+
let payment_hash = Sha256::hash(&payment_preimage.0);
397+
let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
398+
let timestamp = SystemTime::now()
399+
.checked_sub(Duration::from_secs(DEFAULT_EXPIRY_TIME * 2))
400+
.unwrap();
401+
InvoiceBuilder::new(Currency::Bitcoin)
402+
.description("test".into())
403+
.payment_hash(payment_hash)
404+
.payment_secret(PaymentSecret([0; 32]))
405+
.timestamp(timestamp)
406+
.min_final_cltv_expiry(144)
407+
.amount_milli_satoshis(128)
408+
.build_signed(|hash| {
409+
Secp256k1::new().sign_recoverable(hash, &private_key)
410+
})
411+
.unwrap()
412+
}
413+
381414
#[test]
382415
fn pays_invoice_on_first_attempt() {
383416
let event_handled = core::cell::RefCell::new(false);
@@ -574,6 +607,37 @@ mod tests {
574607
assert_eq!(*payer.attempts.borrow(), 1);
575608
}
576609

610+
#[test]
611+
fn fails_paying_invoice_after_expiration() {
612+
let event_handled = core::cell::RefCell::new(false);
613+
let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
614+
615+
let payer = TestPayer::new();
616+
let router = TestRouter {};
617+
let logger = TestLogger::new();
618+
let invoice_payer =
619+
InvoicePayer::new(&payer, router, &logger, event_handler, RetryAttempts(2));
620+
621+
let payment_preimage = PaymentPreimage([1; 32]);
622+
let invoice = expired_invoice(payment_preimage);
623+
let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
624+
assert_eq!(*payer.attempts.borrow(), 1);
625+
626+
let event = Event::PaymentPathFailed {
627+
payment_id,
628+
payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
629+
network_update: None,
630+
rejected_by_dest: false,
631+
all_paths_failed: false,
632+
path: vec![],
633+
short_channel_id: None,
634+
retry: Some(TestRouter::retry_for_invoice(&invoice)),
635+
};
636+
invoice_payer.handle_event(&event);
637+
assert_eq!(*event_handled.borrow(), true);
638+
assert_eq!(*payer.attempts.borrow(), 1);
639+
}
640+
577641
#[test]
578642
fn fails_paying_invoice_after_retry_error() {
579643
let event_handled = core::cell::RefCell::new(false);
@@ -795,6 +859,7 @@ mod tests {
795859

796860
fn retry_for_invoice(invoice: &Invoice) -> RouteParameters {
797861
let mut payee = Payee::new(invoice.recover_payee_pub_key())
862+
.with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
798863
.with_route_hints(invoice.route_hints());
799864
if let Some(features) = invoice.features() {
800865
payee = payee.with_features(features.clone());

lightning/src/routing/router.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,12 +180,16 @@ pub struct Payee {
180180

181181
/// Hints for routing to the payee, containing channels connecting the payee to public nodes.
182182
pub route_hints: Vec<RouteHint>,
183+
184+
/// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
185+
pub expiry_time: Option<u64>,
183186
}
184187

185188
impl_writeable_tlv_based!(Payee, {
186189
(0, pubkey, required),
187190
(2, features, option),
188191
(4, route_hints, vec_type),
192+
(6, expiry_time, option),
189193
});
190194

191195
impl Payee {
@@ -195,6 +199,7 @@ impl Payee {
195199
pubkey,
196200
features: None,
197201
route_hints: vec![],
202+
expiry_time: None,
198203
}
199204
}
200205

@@ -216,6 +221,11 @@ impl Payee {
216221
pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Self {
217222
Self { route_hints, ..self }
218223
}
224+
225+
/// Includes a payment expiration in seconds relative to the UNIX epoch.
226+
pub fn with_expiry_time(self, expiry_time: u64) -> Self {
227+
Self { expiry_time: Some(expiry_time), ..self }
228+
}
219229
}
220230

221231
/// A list of hops along a payment path terminating with a channel to the recipient.

0 commit comments

Comments
 (0)