فهرست منبع

util/time: simplyfied Timestamp

aggstam 3 سال پیش
والد
کامیت
ec3bc88fb7
4فایلهای تغییر یافته به همراه23 افزوده شده و 41 حذف شده
  1. 1 1
      src/consensus/clock.rs
  2. 7 10
      src/consensus/task/proposal.rs
  3. 4 4
      src/rpc/clock_sync.rs
  4. 11 26
      src/util/time.rs

+ 1 - 1
src/consensus/clock.rs

@@ -79,7 +79,7 @@ impl Clock {
     /// returns time since genesis in seconds.
     async fn time_to_genesis(&self) -> Timestamp {
         //TODO this value need to be assigned to kickoff time.
-        let genesis_time: i64 = self.genesis_time.0;
+        let genesis_time = self.genesis_time.0;
         let abs_time = self.time().await.unwrap();
         Timestamp(abs_time.0 - genesis_time)
     }

+ 7 - 10
src/consensus/task/proposal.rs

@@ -16,8 +16,6 @@
  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
  */
 
-use std::time::Duration;
-
 use async_std::sync::Arc;
 use log::{debug, error, info, warn};
 
@@ -47,18 +45,18 @@ pub async fn proposal_task(
         sleep(diff as u64).await;
     } else {
         let mut sleep_time = state.read().await.consensus.time_keeper.next_n_slot_start(1);
-        let sync_offset = Duration::new(constants::FINAL_SYNC_DUR, 0);
+        let sync_offset = constants::FINAL_SYNC_DUR;
         loop {
             if sleep_time > sync_offset {
                 sleep_time -= sync_offset;
                 break
             }
             info!(target: "consensus::proposal", "consensus: Waiting for next slot ({:?})", sleep_time);
-            sleep(sleep_time.as_secs()).await;
+            sleep(sleep_time).await;
             sleep_time = state.read().await.consensus.time_keeper.next_n_slot_start(1);
         }
         info!(target: "consensus::proposal", "consensus: Waiting for finalization sync period ({:?})", sleep_time);
-        sleep(sleep_time.as_secs()).await;
+        sleep(sleep_time).await;
     }
 
     let mut retries = 0;
@@ -181,7 +179,7 @@ async fn consensus_loop(
 /// Returns flag in case node needs to resync.
 async fn propose_period(consensus_p2p: P2pPtr, state: ValidatorStatePtr) -> bool {
     // Node sleeps until next slot
-    let seconds_next_slot = state.read().await.consensus.time_keeper.next_n_slot_start(1).as_secs();
+    let seconds_next_slot = state.read().await.consensus.time_keeper.next_n_slot_start(1);
     info!(target: "consensus::proposal", "consensus: Waiting for next slot ({} sec)", seconds_next_slot);
     sleep(seconds_next_slot).await;
 
@@ -229,7 +227,7 @@ async fn propose_period(consensus_p2p: P2pPtr, state: ValidatorStatePtr) -> bool
 
     // Node checks if it missed finalization period due to proposal creation
     let next_slot_start = state.read().await.consensus.time_keeper.next_n_slot_start(1);
-    if next_slot_start.as_secs() <= constants::FINAL_SYNC_DUR {
+    if next_slot_start <= constants::FINAL_SYNC_DUR {
         warn!(
             target: "consensus::proposal",
             "consensus: Node missed slot {} finalization period due to proposal creation, resyncing...",
@@ -280,9 +278,8 @@ async fn finalization_period(
 ) -> bool {
     // Node sleeps until finalization sync period starts
     let next_slot_start = state.read().await.consensus.time_keeper.next_n_slot_start(1);
-    if next_slot_start.as_secs() > constants::FINAL_SYNC_DUR {
-        let seconds_sync_period =
-            (next_slot_start - Duration::new(constants::FINAL_SYNC_DUR, 0)).as_secs();
+    if next_slot_start > constants::FINAL_SYNC_DUR {
+        let seconds_sync_period = next_slot_start - constants::FINAL_SYNC_DUR;
         info!(target: "consensus::proposal", "consensus: Waiting for finalization sync period ({} sec)", seconds_sync_period);
         sleep(seconds_sync_period).await;
     } else {

+ 4 - 4
src/rpc/clock_sync.rs

@@ -31,7 +31,7 @@ use crate::{util::time::Timestamp, Error, Result};
 const RETRIES: u8 = 10;
 /// TODO: Loop through set of ntps, get their average response concurrenyly.
 const NTP_ADDRESS: &str = "pool.ntp.org:123";
-const EPOCH: i64 = 2208988800; // 1900
+const EPOCH: u32 = 2208988800; // 1900
 
 /// JSON-RPC request to a network peer (randomly selected), to
 /// retrieve their current system clock.
@@ -72,7 +72,7 @@ pub async fn ntp_request() -> Result<Timestamp> {
     sock.recv(&mut packet[..])?;
     let (bytes, _) = packet[40..44].split_at(core::mem::size_of::<u32>());
     let num = u32::from_be_bytes(bytes.try_into().unwrap());
-    let timestamp = Timestamp(num as i64 - EPOCH);
+    let timestamp = Timestamp((num - EPOCH) as u64);
 
     Ok(timestamp)
 }
@@ -113,8 +113,8 @@ async fn clock_check(peers: &[Url]) -> Result<()> {
     let mut ntp_time = ntp_request().await?;
 
     // Stop elapsed time counters
-    let ntp_elapsed_time = ntp_request_start.elapsed() as i64;
-    let requests_elapsed_time = requests_start.elapsed() as i64;
+    let ntp_elapsed_time = ntp_request_start.elapsed();
+    let requests_elapsed_time = requests_start.elapsed();
 
     // Current system time
     let system_time = Timestamp::current_time();

+ 11 - 26
src/util/time.rs

@@ -16,7 +16,7 @@
  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
  */
 
-use std::time::{Duration, UNIX_EPOCH};
+use std::time::UNIX_EPOCH;
 
 use chrono::{NaiveDateTime, Utc};
 use darkfi_serial::{SerialDecodable, SerialEncodable};
@@ -61,16 +61,10 @@ impl TimeKeeper {
     }
 
     /// Calculates seconds until next Nth slot starting time.
-    pub fn next_n_slot_start(&self, n: u64) -> Duration {
+    pub fn next_n_slot_start(&self, n: u64) -> u64 {
         assert!(n > 0);
-        let start_time = NaiveDateTime::from_timestamp_opt(self.genesis_ts.0, 0).unwrap();
-        let current_slot = self.current_slot() + n;
-        let next_slot_start = (current_slot * self.slot_time) + (start_time.timestamp() as u64);
-        let next_slot_start = NaiveDateTime::from_timestamp_opt(next_slot_start as i64, 0).unwrap();
-        let current_time = NaiveDateTime::from_timestamp_opt(Utc::now().timestamp(), 0).unwrap();
-        let diff = next_slot_start - current_time;
-
-        Duration::new(diff.num_seconds().try_into().unwrap(), 0)
+        let next_slot_start = self.genesis_ts.0 + (self.current_slot() + n) * self.slot_time;
+        next_slot_start - Timestamp::current_time().0
     }
 
     /// Calculate slots until next Nth epoch.
@@ -82,7 +76,7 @@ impl TimeKeeper {
     }
 
     /// Calculates seconds until next Nth epoch starting time.
-    pub fn next_n_epoch_start(&self, n: u64) -> Duration {
+    pub fn next_n_epoch_start(&self, n: u64) -> u64 {
         self.next_n_slot_start(self.slots_to_next_n_epoch(n))
     }
 
@@ -91,7 +85,7 @@ impl TimeKeeper {
     }
 }
 
-/// Wrapper struct to represent [`chrono`] UTC timestamps.
+/// Wrapper struct to represent system timestamps.
 #[derive(
     Clone,
     Copy,
@@ -104,35 +98,26 @@ impl TimeKeeper {
     PartialOrd,
     Eq,
 )]
-pub struct Timestamp(pub i64);
+pub struct Timestamp(pub u64);
 
 impl Timestamp {
     /// Generate a `Timestamp` of the current time.
     pub fn current_time() -> Self {
-        Self(Utc::now().timestamp())
+        Self(UNIX_EPOCH.elapsed().unwrap().as_secs())
     }
 
     /// Calculates elapsed time of a `Timestamp`.
     pub fn elapsed(&self) -> u64 {
-        let start_time = NaiveDateTime::from_timestamp_opt(self.0, 0).unwrap();
-        let end_time = NaiveDateTime::from_timestamp_opt(Utc::now().timestamp(), 0).unwrap();
-        let diff = end_time - start_time;
-        diff.num_seconds() as u64
+        UNIX_EPOCH.elapsed().unwrap().as_secs() - self.0
     }
 
     /// Increment a 'Timestamp'.
-    pub fn add(&mut self, inc: i64) {
+    pub fn add(&mut self, inc: u64) {
         self.0 += inc;
     }
 }
 
-impl std::fmt::Display for Timestamp {
-    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
-        let date = timestamp_to_date(self.0, DateFormat::DateTime);
-        write!(f, "{}", date)
-    }
-}
-
+// TODO: NanoTimestamp to not use chrono
 #[derive(
     Clone,
     Copy,