Skip to content

Commit

Permalink
[Consensus] use system time for clock
Browse files Browse the repository at this point in the history
  • Loading branch information
mwtian committed Aug 9, 2024
1 parent e3de950 commit 59e07dd
Showing 1 changed file with 8 additions and 16 deletions.
24 changes: 8 additions & 16 deletions consensus/core/src/context.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (c) Mysten Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use std::{sync::Arc, time::SystemTime};
use std::{sync::{atomic::{AtomicU64, Ordering}, Arc}, time::SystemTime};

use consensus_config::{AuthorityIndex, Committee, Parameters};
#[cfg(test)]
Expand Down Expand Up @@ -102,28 +102,20 @@ impl Context {
/// wherever is needed in order to make sure that consecutive calls to receive the system timestamp
/// will remain monotonically increasing.
pub(crate) struct Clock {
unix_epoch_instant: Instant,
last_ts: AtomicU64,
}

impl Clock {
pub fn new() -> Self {
let now = Instant::now();
let duration_since_unix_epoch =
match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
Ok(d) => d,
Err(e) => panic!("SystemTime before UNIX EPOCH! {e}"),
};
let unix_epoch_instant = now.checked_sub(duration_since_unix_epoch).unwrap();

Self { unix_epoch_instant }
let last_ts = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_millis() as u64;
Self { last_ts: AtomicU64::new(last_ts) }
}

// Returns the current time expressed as UNIX timestamp in milliseconds.
// Calculated with Rust Instant to ensure monotonicity.
// Ensure monotonicity even if system time goes back.
pub(crate) fn timestamp_utc_ms(&self) -> BlockTimestampMs {
Instant::now()
.checked_duration_since(self.unix_epoch_instant)
.unwrap()
.as_millis() as BlockTimestampMs
let now_ts = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_millis() as u64;
let prev_ts = self.last_ts.fetch_max(now_ts, Ordering::SeqCst);
now_ts.max(prev_ts)
}
}

0 comments on commit 59e07dd

Please sign in to comment.