Skip to content

Commit a9f5498

Browse files
committed
Use MonotonicTime as Instant shifted by 10 years forward
Such implementation allows `MonotonicTime` to go backward up to 10 years on all platforms. On some platforms (e.g. iOS) `Instant` is represented as `u64` of nanoseconds since the boot of the system. Obviously such implementation does not allow to go backward before the time of the boot.
1 parent 4dce209 commit a9f5498

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

lightning/src/routing/scoring.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -325,7 +325,7 @@ impl ReadableArgs<u64> for FixedPenaltyScorer {
325325
}
326326

327327
#[cfg(not(feature = "no-std"))]
328-
type ConfiguredTime = std::time::Instant;
328+
type ConfiguredTime = crate::util::time::MonotonicTime;
329329
#[cfg(feature = "no-std")]
330330
use crate::util::time::Eternity;
331331
#[cfg(feature = "no-std")]

lightning/src/util/time.rs

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,49 @@ impl Sub<Duration> for Eternity {
5858
}
5959
}
6060

61+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
62+
#[cfg(not(feature = "no-std"))]
63+
pub struct MonotonicTime(std::time::Instant);
64+
#[cfg(not(feature = "no-std"))]
65+
static SHIFT: Duration = Duration::from_secs(10 * 365 * 24 * 60 * 60); // 10 years.
66+
67+
#[cfg(not(feature = "no-std"))]
68+
impl Time for MonotonicTime {
69+
70+
fn now() -> Self {
71+
let instant = std::time::Instant::now().checked_add(SHIFT).expect("Overflow on MonotonicTime instantiation");
72+
Self(instant)
73+
}
74+
75+
fn duration_since(&self, earlier: Self) -> Duration {
76+
// On rust prior to 1.60 `Instant::duration_since` will panic if time goes backwards.
77+
// However, we support rust versions prior to 1.60 and some users appear to have "monotonic
78+
// clocks" that go backwards in practice (likely relatively ancient kernels/etc). Thus, we
79+
// manually check for time going backwards here and return a duration of zero in that case.
80+
let now = Self::now();
81+
if now.0 > earlier.0 { now.0 - earlier.0 } else { Duration::from_secs(0) }
82+
}
83+
84+
fn duration_since_epoch() -> Duration {
85+
use std::time::SystemTime;
86+
SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap()
87+
}
88+
89+
fn elapsed(&self) -> Duration {
90+
self.0.elapsed()
91+
}
92+
}
93+
94+
#[cfg(not(feature = "no-std"))]
95+
impl Sub<Duration> for MonotonicTime {
96+
type Output = Self;
97+
98+
fn sub(self, other: Duration) -> Self {
99+
let instant = self.0.checked_sub(other).expect("MonotonicTime is not supposed to go backward futher than 10 years");
100+
Self(instant)
101+
}
102+
}
103+
61104
#[cfg(not(feature = "no-std"))]
62105
impl Time for std::time::Instant {
63106
fn now() -> Self {

0 commit comments

Comments
 (0)