Skip to content
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

Add helper functions for invoice expiry #2125

Merged
merged 1 commit into from
Mar 27, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 20 additions & 0 deletions lightning-invoice/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1213,6 +1213,12 @@ impl Invoice {
self.signed_invoice.recover_payee_pub_key().expect("was checked by constructor").0
}

/// Returns the Duration since the Unix epoch at which the invoice expires.
benthecarman marked this conversation as resolved.
Show resolved Hide resolved
/// Returning None if overflow occurred.
pub fn expires_at(&self) -> Option<Duration> {
self.duration_since_epoch().checked_add(self.expiry_time())
}

/// Returns the invoice's expiry time, if present, otherwise [`DEFAULT_EXPIRY_TIME`].
pub fn expiry_time(&self) -> Duration {
self.signed_invoice.expiry_time()
Expand All @@ -1235,6 +1241,20 @@ impl Invoice {
}
}

/// Returns the Duration remaining until the invoice expires.
#[cfg(feature = "std")]
pub fn duration_until_expiry(&self) -> Duration {
SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)
.map(|now| self.expiration_remaining_from_epoch(now))
.unwrap_or(Duration::from_nanos(0))
}

/// Returns the Duration remaining until the invoice expires given the current time.
/// `time` is the timestamp as a duration since the Unix epoch.
pub fn expiration_remaining_from_epoch(&self, time: Duration) -> Duration {
self.expires_at().map(|x| x.checked_sub(time)).flatten().unwrap_or(Duration::from_nanos(0))
}

/// Returns whether the expiry time would pass at the given point in time.
/// `at_time` is the timestamp as a duration since the Unix epoch.
pub fn would_expire(&self, at_time: Duration) -> bool {
Expand Down