oasis_core_runtime/common/
time.rs

1//! Runtime time source.
2use std::{
3    sync::Mutex,
4    time::{Duration, SystemTime, UNIX_EPOCH},
5};
6
7use lazy_static::lazy_static;
8use slog::error;
9
10use crate::common::{logger::get_logger, process};
11
12const INITIAL_MINIMUM_TIME: i64 = 1704067200; // Mon, 01 Jan 2024 00:00:00 UTC
13
14struct TimeSource {
15    inner: Mutex<Inner>,
16}
17
18struct Inner {
19    timestamp: i64,
20}
21
22/// Returns the number of seconds since the UNIX epoch.  The time returned
23/// is guaranteed to never decrease within each enclave instance (though it
24/// may decrease iff the enclave is re-launched).
25///
26/// The returned timestamp MUST NOT be trusted on in any way, as the underlying
27/// time source is reliant on the host operating system.
28pub fn insecure_posix_time() -> i64 {
29    let mut inner = TIME_SOURCE.inner.lock().unwrap();
30
31    let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
32    let now = now.as_secs() as i64;
33
34    if now < inner.timestamp {
35        error!(
36            get_logger("runtime/time"),
37            "clock appeared to have ran backwards"
38        );
39        process::abort();
40    }
41    inner.timestamp = now;
42
43    inner.timestamp
44}
45
46// Returns `insecure_posix_time` as SystemTime.
47pub fn insecure_posix_system_time() -> SystemTime {
48    UNIX_EPOCH + Duration::from_secs(insecure_posix_time() as u64)
49}
50
51/// Force update the minimum timestamp from a semi-trusted source (eg: the AVR
52/// timestamp), under the assumption that the semi-trusted source is more trust
53/// worthy than the host operating system.
54pub(crate) fn update_insecure_posix_time(timestamp: i64) {
55    let mut inner = TIME_SOURCE.inner.lock().unwrap();
56
57    if timestamp > inner.timestamp {
58        inner.timestamp = timestamp;
59    }
60
61    // The IAS clock and local clock should be closely synced, and minor
62    // differences in NTP implementations (eg: smear vs no smear), should
63    // be masked by the fact that the AVR timestamp will be a minimum of
64    // 1 RTT in the past.
65}
66
67lazy_static! {
68    static ref TIME_SOURCE: TimeSource = TimeSource {
69        inner: Mutex::new(Inner {
70            timestamp: INITIAL_MINIMUM_TIME,
71        })
72    };
73}