Skip to content

Commit

Permalink
refactor: Use SystemTime for timestamps
Browse files Browse the repository at this point in the history
Signed-off-by: Dmitry Murzin <diralik@yandex.ru>
  • Loading branch information
dima74 committed Aug 27, 2024
1 parent 6f339ab commit 07ee499
Show file tree
Hide file tree
Showing 11 changed files with 134 additions and 115 deletions.
24 changes: 10 additions & 14 deletions client/tests/integration/triggers/time_trigger.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::time::Duration;
use std::time::{Duration, SystemTime};

use eyre::Result;
use iroha::{
Expand Down Expand Up @@ -31,14 +31,6 @@ pub fn default_consensus_estimation() -> Duration {
.map_or_else(|| unreachable!(), |x| x)
}

fn curr_time() -> core::time::Duration {
use std::time::SystemTime;

SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap()
}

/// Macro to abort compilation, if `e` isn't `true`
macro_rules! const_assert {
($e:expr) => {
Expand All @@ -61,7 +53,7 @@ fn time_trigger_execution_count_error_should_be_less_than_15_percent() -> Result

let (_rt, _peer, mut test_client) = <PeerBuilder>::new().with_port(10_775).start_with_runtime();
wait_for_genesis_committed(&vec![test_client.clone()], 0);
let start_time = curr_time();
let start_time = SystemTime::now();

// Start listening BEFORE submitting any transaction not to miss any block committed event
let event_listener = get_block_committed_event_listener(&test_client)?;
Expand Down Expand Up @@ -94,8 +86,12 @@ fn time_trigger_execution_count_error_should_be_less_than_15_percent() -> Result
)?;
std::thread::sleep(default_consensus_estimation());

let finish_time = curr_time();
let average_count = finish_time.saturating_sub(start_time).as_millis() / PERIOD.as_millis();
let finish_time = SystemTime::now();
let average_count = finish_time
.duration_since(start_time)
.unwrap_or_else(|_| Duration::from_secs(0))
.as_millis()
/ PERIOD.as_millis();

let actual_value = get_asset_value(&mut test_client, asset_id);
let expected_value = prev_value
Expand Down Expand Up @@ -131,7 +127,7 @@ fn mint_asset_after_3_sec() -> Result<()> {
id: asset_id.clone(),
})?;

let start_time = curr_time();
let start_time = SystemTime::now();
// Create trigger with schedule which is in the future to the new block but within block estimation time
let schedule = TimeSchedule::starting_at(start_time + Duration::from_secs(3));
let instruction = Mint::asset_numeric(1_u32, asset_id.clone());
Expand Down Expand Up @@ -257,7 +253,7 @@ fn mint_nft_for_every_user_every_1_sec() -> Result<()> {
// Registering trigger
// Offset into the future to be able to register trigger
let offset = Duration::from_secs(10);
let start_time = curr_time() + offset;
let start_time = SystemTime::now() + offset;
let schedule = TimeSchedule::starting_at(start_time).with_period(TRIGGER_PERIOD);

let filter = TimeEventFilter(ExecutionTime::Schedule(schedule));
Expand Down
4 changes: 2 additions & 2 deletions client/tests/integration/tx_history.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{str::FromStr as _, thread};
use std::{str::FromStr as _, thread, time::SystemTime};

use eyre::Result;
use iroha::{
Expand Down Expand Up @@ -60,7 +60,7 @@ fn client_has_rejected_and_acepted_txs_should_return_tx_history() -> Result<()>
.execute_all()?;
assert_eq!(transactions.len(), 50);

let mut prev_creation_time = core::time::Duration::from_millis(0);
let mut prev_creation_time = SystemTime::UNIX_EPOCH;
transactions
.iter()
.map(AsRef::as_ref)
Expand Down
17 changes: 8 additions & 9 deletions core/src/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,18 +159,17 @@ mod pending {
transactions: &[CommittedTransaction],
consensus_estimation: Duration,
) -> BlockHeader {
let prev_block_time =
prev_block.map_or(Duration::ZERO, |block| block.header().creation_time());
let prev_block_time = prev_block.map_or(SystemTime::UNIX_EPOCH, |block| {
block.header().creation_time()
});

let latest_txn_time = transactions
.iter()
.map(|tx| tx.as_ref().creation_time())
.max()
.expect("INTERNAL BUG: Block empty");

let now = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap();
let now = SystemTime::now();

// NOTE: Lower time bound must always be upheld for a valid block
// If the clock has drifted too far this block will be rejected
Expand Down Expand Up @@ -200,6 +199,8 @@ mod pending {
.hash()
.expect("INTERNAL BUG: Empty block created"),
creation_time_ms: creation_time
.duration_since(SystemTime::UNIX_EPOCH)
.expect("INTERNAL BUG: Failed to get the current system time")
.as_millis()
.try_into()
.expect("Time should fit into u64"),
Expand Down Expand Up @@ -526,11 +527,9 @@ mod valid {
});
}

let now = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap();
let now = SystemTime::now();
let max_clock_drift = state.world().parameters().sumeragi.max_clock_drift();
if block.header().creation_time().saturating_sub(now) > max_clock_drift {
if block.header().creation_time() > now + max_clock_drift {
return Err(BlockValidationError::BlockInTheFuture);
}

Expand Down
8 changes: 4 additions & 4 deletions core/src/metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,13 +114,13 @@ impl MetricsReporter {

#[allow(clippy::cast_possible_truncation)]
if let Some(timestamp) = state_view.genesis_timestamp() {
let curr_time = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap();
let curr_time = SystemTime::now();

// this will overflow in 584942417years.
self.metrics.uptime_since_genesis_ms.set(
(curr_time - timestamp)
curr_time
.duration_since(timestamp)
.expect("Failed to get the current system time")
.as_millis()
.try_into()
.expect("Timestamp should fit into u64"),
Expand Down
6 changes: 3 additions & 3 deletions core/src/queue.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Module with queue actor
use core::time::Duration;
use std::{num::NonZeroUsize, ops::Deref, sync::Arc};
use std::{num::NonZeroUsize, ops::Deref, sync::Arc, time::SystemTime};

use crossbeam_queue::ArrayQueue;
use dashmap::{mapref::entry::Entry, DashMap};
Expand Down Expand Up @@ -133,8 +133,8 @@ impl Queue {
|tx_time_to_live| core::cmp::min(self.tx_time_to_live, tx_time_to_live),
);

let curr_time = self.time_source.get_unix_time();
curr_time.saturating_sub(tx_creation_time) > time_limit
let curr_time = SystemTime::UNIX_EPOCH + self.time_source.get_unix_time();
curr_time > tx_creation_time + time_limit
}

/// Returns all pending transactions.
Expand Down
4 changes: 2 additions & 2 deletions core/src/state.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! This module provides the [`State`] — an in-memory representation of the current blockchain state.
use std::{
collections::BTreeSet, marker::PhantomData, num::NonZeroUsize, sync::Arc, time::Duration,
collections::BTreeSet, marker::PhantomData, num::NonZeroUsize, sync::Arc, time::SystemTime,
};

use eyre::Result;
Expand Down Expand Up @@ -1285,7 +1285,7 @@ pub trait StateReadOnly {
/// Returns [`Some`] milliseconds since the genesis block was
/// committed, or [`None`] if it wasn't.
#[inline]
fn genesis_timestamp(&self) -> Option<Duration> {
fn genesis_timestamp(&self) -> Option<SystemTime> {
if self.block_hashes().is_empty() {
None
} else {
Expand Down
6 changes: 2 additions & 4 deletions core/src/tx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,8 @@ impl AcceptedTransaction {
}));
}

let now = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap();
if tx.creation_time().saturating_sub(now) > max_clock_drift {
let now = SystemTime::now();
if tx.creation_time() > now + max_clock_drift {
return Err(AcceptTransactionFail::TransactionInTheFuture);
}

Expand Down
7 changes: 4 additions & 3 deletions data_model/benches/time_event_filter.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#![allow(missing_docs)]

use std::time::Duration;
use std::time::{Duration, SystemTime};

use criterion::{criterion_group, criterion_main, Criterion};
use iroha_data_model::prelude::*;
Expand All @@ -12,14 +12,15 @@ fn schedule_from_zero_with_little_period(criterion: &mut Criterion) {

const TIMESTAMP: u64 = 1_647_443_386;

let since = Duration::from_secs(TIMESTAMP);
let since = SystemTime::UNIX_EPOCH + Duration::from_secs(TIMESTAMP);
let length = Duration::from_secs(1);
let interval = TimeInterval::new(since, length);
let event = TimeEvent {
prev_interval: None,
interval,
};
let schedule = TimeSchedule::starting_at(Duration::ZERO).with_period(Duration::from_millis(1));
let schedule =
TimeSchedule::starting_at(SystemTime::UNIX_EPOCH).with_period(Duration::from_millis(1));
let filter = TimeEventFilter::new(ExecutionTime::Schedule(schedule));

criterion.bench_function("count_matches_from_zero", |b| {
Expand Down
7 changes: 5 additions & 2 deletions data_model/src/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
#[cfg(not(feature = "std"))]
use alloc::{boxed::Box, format, string::String, vec::Vec};
use core::{fmt::Display, time::Duration};
#[cfg(feature = "std")]
use std::time::SystemTime;

use derive_more::Display;
use iroha_crypto::{HashOf, MerkleTree, SignatureOf};
Expand Down Expand Up @@ -133,8 +135,9 @@ impl BlockHeader {
}

/// Creation timestamp
pub const fn creation_time(&self) -> Duration {
Duration::from_millis(self.creation_time_ms)
#[cfg(feature = "std")]
pub fn creation_time(&self) -> SystemTime {
SystemTime::UNIX_EPOCH + Duration::from_millis(self.creation_time_ms)
}

/// Consensus estimation
Expand Down
Loading

0 comments on commit 07ee499

Please sign in to comment.