From 4b7c9929ee2476932227634026cf1574a6319a5c Mon Sep 17 00:00:00 2001 From: Gautam Dhameja Date: Mon, 22 Jul 2019 13:32:24 +0200 Subject: [PATCH] Timestamp off-chain API (#3144) * timestamp offchain api impl * Addressed review comments * fixed expect message * fixed compile error * fixed line width --- substrate/core/offchain/src/api.rs | 38 ++++++++++++++++++++++++++++-- 1 file changed, 36 insertions(+), 2 deletions(-) diff --git a/substrate/core/offchain/src/api.rs b/substrate/core/offchain/src/api.rs index 64c6427750..2598945dca 100644 --- a/substrate/core/offchain/src/api.rs +++ b/substrate/core/offchain/src/api.rs @@ -14,7 +14,12 @@ // You should have received a copy of the GNU General Public License // along with Substrate. If not, see . -use std::{str::FromStr, sync::Arc, convert::TryFrom}; +use std::{ + str::FromStr, + sync::Arc, + convert::{TryFrom, TryInto}, + time::SystemTime +}; use client::backend::OffchainStorage; use crate::AuthorityKeyProvider; use futures::{Stream, Future, sync::mpsc}; @@ -308,7 +313,20 @@ where } fn timestamp(&mut self) -> Timestamp { - unavailable_yet("timestamp") + let now = SystemTime::now(); + let epoch_duration = now.duration_since(SystemTime::UNIX_EPOCH); + match epoch_duration { + Err(_) => { + // Current time is earlier than UNIX_EPOCH. + Timestamp::from_unix_millis(0) + }, + Ok(d) => { + let duration = d.as_millis(); + // Assuming overflow won't happen for a few hundred years. + Timestamp::from_unix_millis(duration.try_into() + .expect("epoch milliseconds won't overflow u64 for hundreds of years; qed")) + } + } } fn sleep_until(&mut self, _deadline: Timestamp) { @@ -574,6 +592,22 @@ mod tests { AsyncApi::new(pool, db, "pass".to_owned().into(), TestProvider::default(), BlockId::Number(Zero::zero()), mock) } + #[test] + fn should_get_timestamp() { + let mut api = offchain_api().0; + + // Get timestamp from std. + let now = SystemTime::now(); + let d: u64 = now.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_millis().try_into().unwrap(); + + // Get timestamp from offchain api. + let timestamp = api.timestamp(); + + // Compare. + assert!(timestamp.unix_millis() > 0); + assert_eq!(timestamp.unix_millis(), d); + } + #[test] fn should_set_and_get_local_storage() { // given