pallet_timestamp/lib.rs
1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// 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.
17
18//! > Made with *Substrate*, for *Polkadot*.
19//!
20//! [![github]](https://github.com/paritytech/polkadot-sdk/substrate/frame/timestamp)
21//! [![polkadot]](https://polkadot.com)
22//!
23//! [polkadot]: https://img.shields.io/badge/polkadot-E6007A?style=for-the-badge&logo=polkadot&logoColor=white
24//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
25//!
26//! # Timestamp Pallet
27//!
28//! A pallet that provides a way for consensus systems to set and check the onchain time.
29//!
30//! ## Pallet API
31//!
32//! See the [`pallet`] module for more information about the interfaces this pallet exposes,
33//! including its configuration trait, dispatchables, storage items, events and errors.
34//!
35//! ## Overview
36//!
37//! The Timestamp pallet is designed to create a consensus-based time source. This helps ensure that
38//! nodes maintain a synchronized view of time that all network participants can agree on.
39//!
40//! It defines an _acceptable range_ using a configurable constant to specify how much time must
41//! pass before setting the new timestamp. Validator nodes in the network must verify that the
42//! timestamp falls within this acceptable range and reject blocks that do not.
43//!
44//! > **Note:** The timestamp set by this pallet is the recommended way to query the onchain time
45//! > instead of using block numbers alone. Measuring time with block numbers can cause cumulative
46//! > calculation errors if depended upon in time critical operations and hence should generally be
47//! > avoided.
48//!
49//! ## Example
50//!
51//! To get the current time for the current block in another pallet:
52//!
53//! ```
54//! use pallet_timestamp::{self as timestamp};
55//!
56//! #[frame_support::pallet]
57//! pub mod pallet {
58//! use super::*;
59//! use frame_support::pallet_prelude::*;
60//! use frame_system::pallet_prelude::*;
61//!
62//! #[pallet::pallet]
63//! pub struct Pallet<T>(_);
64//!
65//! #[pallet::config]
66//! pub trait Config: frame_system::Config + timestamp::Config {}
67//!
68//! #[pallet::call]
69//! impl<T: Config> Pallet<T> {
70//! #[pallet::weight(0)]
71//! pub fn get_time(origin: OriginFor<T>) -> DispatchResult {
72//! let _sender = ensure_signed(origin)?;
73//! let _now = timestamp::Pallet::<T>::get();
74//! Ok(())
75//! }
76//! }
77//! }
78//! # fn main() {}
79//! ```
80//!
81//! If [`Pallet::get`] is called prior to setting the timestamp, it will return the timestamp of
82//! the previous block.
83//!
84//! ## Low Level / Implementation Details
85//!
86//! A timestamp is added to the chain using an _inherent extrinsic_ that only a block author can
87//! submit. Inherents are a special type of extrinsic in Substrate chains that will always be
88//! included in a block.
89//!
90//! To provide inherent data to the runtime, this pallet implements
91//! [`ProvideInherent`](frame_support::inherent::ProvideInherent). It will only create an inherent
92//! if the [`Call::set`] dispatchable is called, using the
93//! [`inherent`](frame_support::pallet_macros::inherent) macro which enables validator nodes to call
94//! into the runtime to check that the timestamp provided is valid.
95//! The implementation of [`ProvideInherent`](frame_support::inherent::ProvideInherent) specifies a
96//! constant called `MAX_TIMESTAMP_DRIFT_MILLIS` which is used to determine the acceptable range for
97//! a valid timestamp. If a block author sets a timestamp to anything that is more than this
98//! constant, a validator node will reject the block.
99//!
100//! The pallet also ensures that a timestamp is set at the start of each block by running an
101//! assertion in the `on_finalize` runtime hook. See [`frame_support::traits::Hooks`] for more
102//! information about how hooks work.
103//!
104//! Because inherents are applied to a block in the order they appear in the runtime
105//! construction, the index of this pallet in
106//! [`construct_runtime`](frame_support::construct_runtime) must always be less than any other
107//! pallet that depends on it.
108//!
109//! The [`Config::OnTimestampSet`] configuration trait can be set to another pallet we want to
110//! notify that the timestamp has been updated, as long as it implements [`OnTimestampSet`].
111//! Examples are the Babe and Aura pallets.
112//! This pallet also implements [`Time`] and [`UnixTime`] so it can be used to configure other
113//! pallets that require these types (e.g. in Staking pallet).
114//!
115//! ## Panics
116//!
117//! There are 3 cases where this pallet could cause the runtime to panic.
118//!
119//! 1. If no timestamp is set at the end of a block.
120//!
121//! 2. If a timestamp is set more than once per block:
122#![doc = docify::embed!("src/tests.rs", double_timestamp_should_fail)]
123//! 3. If a timestamp is set before the [`Config::MinimumPeriod`] is elapsed:
124#![doc = docify::embed!("src/tests.rs", block_period_minimum_enforced)]
125#![deny(missing_docs)]
126#![cfg_attr(not(feature = "std"), no_std)]
127
128mod benchmarking;
129#[cfg(test)]
130mod mock;
131#[cfg(test)]
132mod tests;
133pub mod weights;
134
135use core::{cmp, result};
136use frame_support::traits::{OnTimestampSet, Time, UnixTime};
137use sp_runtime::traits::{AtLeast32Bit, SaturatedConversion, Scale, Zero};
138use sp_timestamp::{InherentError, InherentType, INHERENT_IDENTIFIER};
139pub use weights::WeightInfo;
140
141pub use pallet::*;
142
143#[frame_support::pallet]
144pub mod pallet {
145 use super::*;
146 use frame_support::{derive_impl, pallet_prelude::*};
147 use frame_system::pallet_prelude::*;
148
149 /// Default preludes for [`Config`].
150 pub mod config_preludes {
151 use super::*;
152
153 /// Default prelude sensible to be used in a testing environment.
154 pub struct TestDefaultConfig;
155
156 #[derive_impl(frame_system::config_preludes::TestDefaultConfig, no_aggregated_types)]
157 impl frame_system::DefaultConfig for TestDefaultConfig {}
158
159 #[frame_support::register_default_impl(TestDefaultConfig)]
160 impl DefaultConfig for TestDefaultConfig {
161 type Moment = u64;
162 type OnTimestampSet = ();
163 type MinimumPeriod = ConstUint<1>;
164 type WeightInfo = ();
165 }
166 }
167
168 /// The pallet configuration trait
169 #[pallet::config(with_default)]
170 pub trait Config: frame_system::Config {
171 /// Type used for expressing a timestamp.
172 #[pallet::no_default_bounds]
173 type Moment: Parameter
174 + Default
175 + AtLeast32Bit
176 + Scale<BlockNumberFor<Self>, Output = Self::Moment>
177 + Copy
178 + MaxEncodedLen
179 + scale_info::StaticTypeInfo;
180
181 /// Something which can be notified (e.g. another pallet) when the timestamp is set.
182 ///
183 /// This can be set to `()` if it is not needed.
184 type OnTimestampSet: OnTimestampSet<Self::Moment>;
185
186 /// The minimum period between blocks.
187 ///
188 /// Be aware that this is different to the *expected* period that the block production
189 /// apparatus provides. Your chosen consensus system will generally work with this to
190 /// determine a sensible block time. For example, in the Aura pallet it will be double this
191 /// period on default settings.
192 #[pallet::constant]
193 type MinimumPeriod: Get<Self::Moment>;
194
195 /// Weight information for extrinsics in this pallet.
196 type WeightInfo: WeightInfo;
197 }
198
199 #[pallet::pallet]
200 pub struct Pallet<T>(_);
201
202 /// The current time for the current block.
203 #[pallet::storage]
204 pub type Now<T: Config> = StorageValue<_, T::Moment, ValueQuery>;
205
206 /// Whether the timestamp has been updated in this block.
207 ///
208 /// This value is updated to `true` upon successful submission of a timestamp by a node.
209 /// It is then checked at the end of each block execution in the `on_finalize` hook.
210 #[pallet::storage]
211 pub(super) type DidUpdate<T: Config> = StorageValue<_, bool, ValueQuery>;
212
213 #[pallet::hooks]
214 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
215 /// A dummy `on_initialize` to return the amount of weight that `on_finalize` requires to
216 /// execute.
217 fn on_initialize(_n: BlockNumberFor<T>) -> Weight {
218 // weight of `on_finalize`
219 T::WeightInfo::on_finalize()
220 }
221
222 /// At the end of block execution, the `on_finalize` hook checks that the timestamp was
223 /// updated. Upon success, it removes the boolean value from storage. If the value resolves
224 /// to `false`, the pallet will panic.
225 ///
226 /// ## Complexity
227 /// - `O(1)`
228 fn on_finalize(_n: BlockNumberFor<T>) {
229 assert!(DidUpdate::<T>::take(), "Timestamp must be updated once in the block");
230 }
231 }
232
233 #[pallet::call]
234 impl<T: Config> Pallet<T> {
235 /// Set the current time.
236 ///
237 /// This call should be invoked exactly once per block. It will panic at the finalization
238 /// phase, if this call hasn't been invoked by that time.
239 ///
240 /// The timestamp should be greater than the previous one by the amount specified by
241 /// [`Config::MinimumPeriod`].
242 ///
243 /// The dispatch origin for this call must be _None_.
244 ///
245 /// This dispatch class is _Mandatory_ to ensure it gets executed in the block. Be aware
246 /// that changing the complexity of this call could result exhausting the resources in a
247 /// block to execute any other calls.
248 ///
249 /// ## Complexity
250 /// - `O(1)` (Note that implementations of `OnTimestampSet` must also be `O(1)`)
251 /// - 1 storage read and 1 storage mutation (codec `O(1)` because of `DidUpdate::take` in
252 /// `on_finalize`)
253 /// - 1 event handler `on_timestamp_set`. Must be `O(1)`.
254 #[pallet::call_index(0)]
255 #[pallet::weight((
256 T::WeightInfo::set(),
257 DispatchClass::Mandatory
258 ))]
259 pub fn set(origin: OriginFor<T>, #[pallet::compact] now: T::Moment) -> DispatchResult {
260 ensure_none(origin)?;
261 assert!(!DidUpdate::<T>::exists(), "Timestamp must be updated only once in the block");
262 let prev = Now::<T>::get();
263 assert!(
264 prev.is_zero() || now >= prev + T::MinimumPeriod::get(),
265 "Timestamp must increment by at least <MinimumPeriod> between sequential blocks"
266 );
267 Now::<T>::put(now);
268 DidUpdate::<T>::put(true);
269
270 <T::OnTimestampSet as OnTimestampSet<_>>::on_timestamp_set(now);
271
272 Ok(())
273 }
274 }
275
276 /// To check the inherent is valid, we simply take the max value between the current timestamp
277 /// and the current timestamp plus the [`Config::MinimumPeriod`].
278 /// We also check that the timestamp has not already been set in this block.
279 ///
280 /// ## Errors:
281 /// - [`InherentError::TooFarInFuture`]: If the timestamp is larger than the current timestamp +
282 /// minimum drift period.
283 /// - [`InherentError::TooEarly`]: If the timestamp is less than the current + minimum period.
284 #[pallet::inherent]
285 impl<T: Config> ProvideInherent for Pallet<T> {
286 type Call = Call<T>;
287 type Error = InherentError;
288 const INHERENT_IDENTIFIER: InherentIdentifier = INHERENT_IDENTIFIER;
289
290 fn create_inherent(data: &InherentData) -> Option<Self::Call> {
291 let inherent_data = data
292 .get_data::<InherentType>(&INHERENT_IDENTIFIER)
293 .expect("Timestamp inherent data not correctly encoded")
294 .expect("Timestamp inherent data must be provided");
295 let data = (*inherent_data).saturated_into::<T::Moment>();
296
297 let next_time = cmp::max(data, Now::<T>::get() + T::MinimumPeriod::get());
298 Some(Call::set { now: next_time })
299 }
300
301 fn check_inherent(
302 call: &Self::Call,
303 data: &InherentData,
304 ) -> result::Result<(), Self::Error> {
305 const MAX_TIMESTAMP_DRIFT_MILLIS: sp_timestamp::Timestamp =
306 sp_timestamp::Timestamp::new(30 * 1000);
307
308 let t: u64 = match call {
309 Call::set { ref now } => (*now).saturated_into::<u64>(),
310 _ => return Ok(()),
311 };
312
313 let data = data
314 .get_data::<InherentType>(&INHERENT_IDENTIFIER)
315 .expect("Timestamp inherent data not correctly encoded")
316 .expect("Timestamp inherent data must be provided");
317
318 let minimum = (Now::<T>::get() + T::MinimumPeriod::get()).saturated_into::<u64>();
319 if t > *(data + MAX_TIMESTAMP_DRIFT_MILLIS) {
320 Err(InherentError::TooFarInFuture)
321 } else if t < minimum {
322 Err(InherentError::TooEarly)
323 } else {
324 Ok(())
325 }
326 }
327
328 fn is_inherent(call: &Self::Call) -> bool {
329 matches!(call, Call::set { .. })
330 }
331 }
332}
333
334impl<T: Config> Pallet<T> {
335 /// Get the current time for the current block.
336 ///
337 /// NOTE: if this function is called prior to setting the timestamp,
338 /// it will return the timestamp of the previous block.
339 pub fn get() -> T::Moment {
340 Now::<T>::get()
341 }
342
343 /// Set the timestamp to something in particular. Only used for tests.
344 #[cfg(any(feature = "runtime-benchmarks", feature = "std"))]
345 pub fn set_timestamp(now: T::Moment) {
346 Now::<T>::put(now);
347 DidUpdate::<T>::put(true);
348 <T::OnTimestampSet as OnTimestampSet<_>>::on_timestamp_set(now);
349 }
350}
351
352impl<T: Config> Time for Pallet<T> {
353 /// A type that represents a unit of time.
354 type Moment = T::Moment;
355
356 fn now() -> Self::Moment {
357 Now::<T>::get()
358 }
359}
360
361/// Before the timestamp inherent is applied, it returns the time of previous block.
362///
363/// On genesis the time returned is not valid.
364impl<T: Config> UnixTime for Pallet<T> {
365 fn now() -> core::time::Duration {
366 // now is duration since unix epoch in millisecond as documented in
367 // `sp_timestamp::InherentDataProvider`.
368 let now = Now::<T>::get();
369
370 if now == T::Moment::zero() {
371 log::error!(
372 target: "runtime::timestamp",
373 "`pallet_timestamp::UnixTime::now` is called at genesis, invalid value returned: 0",
374 );
375 }
376
377 core::time::Duration::from_millis(now.saturated_into::<u64>())
378 }
379}