1// This file is part of Substrate.
23// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
56// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
1718//! Substrate core types and inherents for timestamps.
1920#![cfg_attr(not(feature = "std"), no_std)]
2122use codec::{Decode, Encode};
23use core::time::Duration;
24use sp_inherents::{InherentData, InherentIdentifier, IsFatalError};
2526/// The identifier for the `timestamp` inherent.
27pub const INHERENT_IDENTIFIER: InherentIdentifier = *b"timstap0";
2829/// The type of the inherent.
30pub type InherentType = Timestamp;
3132/// Unit type wrapper that represents a timestamp.
33///
34/// Such a timestamp is the time since the UNIX_EPOCH in milliseconds at a given point in time.
35#[derive(Debug, Encode, Decode, Eq, Clone, Copy, Default, Ord)]
36pub struct Timestamp(u64);
3738impl Timestamp {
39/// Create new `Self`.
40pub const fn new(inner: u64) -> Self {
41Self(inner)
42 }
4344/// Returns `self` as [`Duration`].
45pub const fn as_duration(self) -> Duration {
46 Duration::from_millis(self.0)
47 }
4849/// Returns `self` as a `u64` representing the elapsed time since the UNIX_EPOCH in
50 /// milliseconds.
51pub const fn as_millis(&self) -> u64 {
52self.0
53}
5455/// Checked subtraction that returns `None` on an underflow.
56pub fn checked_sub(self, other: Self) -> Option<Self> {
57self.0.checked_sub(other.0).map(Self)
58 }
5960/// The current timestamp using the system time.
61#[cfg(feature = "std")]
62pub fn current() -> Self {
63use std::time::SystemTime;
6465let now = SystemTime::now();
66 now.duration_since(SystemTime::UNIX_EPOCH)
67 .expect("Current time is always after unix epoch; qed")
68 .into()
69 }
70}
7172impl core::ops::Deref for Timestamp {
73type Target = u64;
7475fn deref(&self) -> &Self::Target {
76&self.0
77}
78}
7980impl core::ops::Add for Timestamp {
81type Output = Self;
8283fn add(self, other: Self) -> Self {
84Self(self.0 + other.0)
85 }
86}
8788impl core::ops::Add<u64> for Timestamp {
89type Output = Self;
9091fn add(self, other: u64) -> Self {
92Self(self.0 + other)
93 }
94}
9596impl<T: Into<u64> + Copy> core::cmp::PartialEq<T> for Timestamp {
97fn eq(&self, eq: &T) -> bool {
98self.0 == (*eq).into()
99 }
100}
101102impl<T: Into<u64> + Copy> core::cmp::PartialOrd<T> for Timestamp {
103fn partial_cmp(&self, other: &T) -> Option<core::cmp::Ordering> {
104self.0.partial_cmp(&(*other).into())
105 }
106}
107108#[cfg(feature = "std")]
109impl std::fmt::Display for Timestamp {
110fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111write!(f, "{}", self.0)
112 }
113}
114115impl From<u64> for Timestamp {
116fn from(timestamp: u64) -> Self {
117 Timestamp(timestamp)
118 }
119}
120121impl From<Timestamp> for u64 {
122fn from(timestamp: Timestamp) -> u64 {
123 timestamp.0
124}
125}
126127impl From<Duration> for Timestamp {
128fn from(duration: Duration) -> Self {
129 Timestamp(duration.as_millis() as u64)
130 }
131}
132133/// Errors that can occur while checking the timestamp inherent.
134#[derive(Encode, sp_runtime::RuntimeDebug)]
135#[cfg_attr(feature = "std", derive(Decode, thiserror::Error))]
136pub enum InherentError {
137/// The time between the blocks is too short.
138#[cfg_attr(
139 feature = "std",
140 error("The time since the last timestamp is lower than the minimum period.")
141 )]
142TooEarly,
143/// The block timestamp is too far in the future.
144#[cfg_attr(feature = "std", error("The timestamp of the block is too far in the future."))]
145TooFarInFuture,
146}
147148impl IsFatalError for InherentError {
149fn is_fatal_error(&self) -> bool {
150match self {
151 InherentError::TooEarly => true,
152 InherentError::TooFarInFuture => true,
153 }
154 }
155}
156157impl InherentError {
158/// Try to create an instance ouf of the given identifier and data.
159#[cfg(feature = "std")]
160pub fn try_from(id: &InherentIdentifier, mut data: &[u8]) -> Option<Self> {
161if id == &INHERENT_IDENTIFIER {
162 <InherentError as codec::Decode>::decode(&mut data).ok()
163 } else {
164None
165}
166 }
167}
168169/// Auxiliary trait to extract timestamp inherent data.
170pub trait TimestampInherentData {
171/// Get timestamp inherent data.
172fn timestamp_inherent_data(&self) -> Result<Option<InherentType>, sp_inherents::Error>;
173}
174175impl TimestampInherentData for InherentData {
176fn timestamp_inherent_data(&self) -> Result<Option<InherentType>, sp_inherents::Error> {
177self.get_data(&INHERENT_IDENTIFIER)
178 }
179}
180181/// Provide duration since unix epoch in millisecond for timestamp inherent.
182#[cfg(feature = "std")]
183pub struct InherentDataProvider {
184 max_drift: InherentType,
185 timestamp: InherentType,
186}
187188#[cfg(feature = "std")]
189impl InherentDataProvider {
190/// Create `Self` while using the system time to get the timestamp.
191pub fn from_system_time() -> Self {
192Self {
193 max_drift: std::time::Duration::from_secs(60).into(),
194 timestamp: Timestamp::current(),
195 }
196 }
197198/// Create `Self` using the given `timestamp`.
199pub fn new(timestamp: InherentType) -> Self {
200Self { max_drift: std::time::Duration::from_secs(60).into(), timestamp }
201 }
202203/// With the given maximum drift.
204 ///
205 /// By default the maximum drift is 60 seconds.
206 ///
207 /// The maximum drift is used when checking the inherents of a runtime. If the current timestamp
208 /// plus the maximum drift is smaller than the timestamp in the block, the block will be
209 /// rejected as being too far in the future.
210pub fn with_max_drift(mut self, max_drift: std::time::Duration) -> Self {
211self.max_drift = max_drift.into();
212self
213}
214215/// Returns the timestamp of this inherent data provider.
216pub fn timestamp(&self) -> InherentType {
217self.timestamp
218 }
219}
220221#[cfg(feature = "std")]
222impl core::ops::Deref for InherentDataProvider {
223type Target = InherentType;
224225fn deref(&self) -> &Self::Target {
226&self.timestamp
227 }
228}
229230#[cfg(feature = "std")]
231#[async_trait::async_trait]
232impl sp_inherents::InherentDataProvider for InherentDataProvider {
233async fn provide_inherent_data(
234&self,
235 inherent_data: &mut InherentData,
236 ) -> Result<(), sp_inherents::Error> {
237 inherent_data.put_data(INHERENT_IDENTIFIER, &self.timestamp)
238 }
239240async fn try_handle_error(
241&self,
242 identifier: &InherentIdentifier,
243 error: &[u8],
244 ) -> Option<Result<(), sp_inherents::Error>> {
245Some(Err(sp_inherents::Error::Application(Box::from(InherentError::try_from(
246 identifier, error,
247 )?))))
248 }
249}