diff --git a/script/research/consensusd/src/main.rs b/script/research/consensusd/src/main.rs index deb19a2b8..5f2dbadf3 100644 --- a/script/research/consensusd/src/main.rs +++ b/script/research/consensusd/src/main.rs @@ -81,9 +81,13 @@ fn consensus_task(config: &ConsensusdConfig) { let nodes_count = 1; println!("Waiting for state initialization..."); - thread::sleep(time::Duration::from_secs(20)); + thread::sleep(time::Duration::from_secs(10)); // After initialization node should wait for next epoch + let state = State::load_current_state(id, &state_path).unwrap(); + let seconds_until_next_epoch = state.get_seconds_until_next_epoch_start(); + println!("Waiting for next epoch({:?} sec)...", seconds_until_next_epoch); + thread::sleep(seconds_until_next_epoch); loop { let state = State::load_current_state(id, &state_path).unwrap(); @@ -96,8 +100,9 @@ fn consensus_task(config: &ConsensusdConfig) { println!("Node is the epoch leader. Proposed block: {:?}", proposed_block); } - // node should sleep till text epoch - thread::sleep(time::Duration::from_secs(20)); // 2 * delta + let seconds_until_next_epoch = state.get_seconds_until_next_epoch_start(); + println!("Waiting for next epoch({:?} sec)...", seconds_until_next_epoch); + thread::sleep(seconds_until_next_epoch); }; } diff --git a/script/research/consensusd/src/service/state.rs b/script/research/consensusd/src/service/state.rs index b470954d1..6d1598794 100644 --- a/script/research/consensusd/src/service/state.rs +++ b/script/research/consensusd/src/service/state.rs @@ -3,7 +3,9 @@ use std::{ collections::hash_map::DefaultHasher, hash::{Hash, Hasher}, path::PathBuf, + time::Duration, }; +use chrono::{NaiveDateTime, Utc}; use super::{ block::Block, @@ -56,6 +58,19 @@ impl State { pub fn append_tx(&mut self, tx: String) { self.unconfirmed_txs.push(tx); } + + /// Node calculates seconds until next epoch starting time. + /// Epochs duration is configured using the delta value. + pub fn get_seconds_until_next_epoch_start(&self) -> Duration { + let delta = 10; + let start_time = NaiveDateTime::from_timestamp(self.genesis_time.0, 0); + let current_epoch = self.get_current_epoch() + 1; + let next_epoch_start_timestamp = (current_epoch * (2 * delta)) + (start_time.timestamp() as u64); + let next_epoch_start = NaiveDateTime::from_timestamp(next_epoch_start_timestamp.try_into().unwrap(), 0); + let current_time = NaiveDateTime::from_timestamp(Utc::now().timestamp(), 0); + let diff = next_epoch_start - current_time; + Duration::new(diff.num_seconds().try_into().unwrap(), 0) + } /// Node calculates current epoch, based on elapsed time from the genesis block. /// Epochs duration is configured using the delta value.