referrerpolicy=no-referrer-when-downgrade

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//!
124//! 3. If a timestamp is set before the [`Config::MinimumPeriod`] is elapsed:
125#![doc = docify::embed!("src/tests.rs", block_period_minimum_enforced)]
126#![deny(missing_docs)]
127#![cfg_attr(not(feature = "std"), no_std)]
128
129mod benchmarking;
130#[cfg(test)]
131mod mock;
132#[cfg(test)]
133mod tests;
134pub mod weights;
135
136use core::{cmp, result};
137use frame_support::traits::{OnTimestampSet, Time, UnixTime};
138use sp_runtime::traits::{AtLeast32Bit, SaturatedConversion, Scale, Zero};
139use sp_timestamp::{InherentError, InherentType, INHERENT_IDENTIFIER};
140pub use weights::WeightInfo;
141
142pub use pallet::*;
143
144#[frame_support::pallet]
145pub mod pallet {
146	use super::*;
147	use frame_support::{derive_impl, pallet_prelude::*};
148	use frame_system::pallet_prelude::*;
149
150	/// Default preludes for [`Config`].
151	pub mod config_preludes {
152		use super::*;
153
154		/// Default prelude sensible to be used in a testing environment.
155		pub struct TestDefaultConfig;
156
157		#[derive_impl(frame_system::config_preludes::TestDefaultConfig, no_aggregated_types)]
158		impl frame_system::DefaultConfig for TestDefaultConfig {}
159
160		#[frame_support::register_default_impl(TestDefaultConfig)]
161		impl DefaultConfig for TestDefaultConfig {
162			type Moment = u64;
163			type OnTimestampSet = ();
164			type MinimumPeriod = ConstUint<1>;
165			type WeightInfo = ();
166		}
167	}
168
169	/// The pallet configuration trait
170	#[pallet::config(with_default)]
171	pub trait Config: frame_system::Config {
172		/// Type used for expressing a timestamp.
173		#[pallet::no_default_bounds]
174		type Moment: Parameter
175			+ Default
176			+ AtLeast32Bit
177			+ Scale<BlockNumberFor<Self>, Output = Self::Moment>
178			+ Copy
179			+ MaxEncodedLen
180			+ scale_info::StaticTypeInfo;
181
182		/// Something which can be notified (e.g. another pallet) when the timestamp is set.
183		///
184		/// This can be set to `()` if it is not needed.
185		type OnTimestampSet: OnTimestampSet<Self::Moment>;
186
187		/// The minimum period between blocks.
188		///
189		/// Be aware that this is different to the *expected* period that the block production
190		/// apparatus provides. Your chosen consensus system will generally work with this to
191		/// determine a sensible block time. For example, in the Aura pallet it will be double this
192		/// period on default settings.
193		#[pallet::constant]
194		type MinimumPeriod: Get<Self::Moment>;
195
196		/// Weight information for extrinsics in this pallet.
197		type WeightInfo: WeightInfo;
198	}
199
200	#[pallet::pallet]
201	pub struct Pallet<T>(_);
202
203	/// The current time for the current block.
204	#[pallet::storage]
205	pub type Now<T: Config> = StorageValue<_, T::Moment, ValueQuery>;
206
207	/// Whether the timestamp has been updated in this block.
208	///
209	/// This value is updated to `true` upon successful submission of a timestamp by a node.
210	/// It is then checked at the end of each block execution in the `on_finalize` hook.
211	#[pallet::storage]
212	pub(super) type DidUpdate<T: Config> = StorageValue<_, bool, ValueQuery>;
213
214	#[pallet::hooks]
215	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
216		/// A dummy `on_initialize` to return the amount of weight that `on_finalize` requires to
217		/// execute.
218		fn on_initialize(_n: BlockNumberFor<T>) -> Weight {
219			// weight of `on_finalize`
220			T::WeightInfo::on_finalize()
221		}
222
223		/// At the end of block execution, the `on_finalize` hook checks that the timestamp was
224		/// updated. Upon success, it removes the boolean value from storage. If the value resolves
225		/// to `false`, the pallet will panic.
226		///
227		/// ## Complexity
228		/// - `O(1)`
229		fn on_finalize(_n: BlockNumberFor<T>) {
230			assert!(DidUpdate::<T>::take(), "Timestamp must be updated once in the block");
231		}
232	}
233
234	#[pallet::call]
235	impl<T: Config> Pallet<T> {
236		/// Set the current time.
237		///
238		/// This call should be invoked exactly once per block. It will panic at the finalization
239		/// phase, if this call hasn't been invoked by that time.
240		///
241		/// The timestamp should be greater than the previous one by the amount specified by
242		/// [`Config::MinimumPeriod`].
243		///
244		/// The dispatch origin for this call must be _None_.
245		///
246		/// This dispatch class is _Mandatory_ to ensure it gets executed in the block. Be aware
247		/// that changing the complexity of this call could result exhausting the resources in a
248		/// block to execute any other calls.
249		///
250		/// ## Complexity
251		/// - `O(1)` (Note that implementations of `OnTimestampSet` must also be `O(1)`)
252		/// - 1 storage read and 1 storage mutation (codec `O(1)` because of `DidUpdate::take` in
253		///   `on_finalize`)
254		/// - 1 event handler `on_timestamp_set`. Must be `O(1)`.
255		#[pallet::call_index(0)]
256		#[pallet::weight((
257			T::WeightInfo::set(),
258			DispatchClass::Mandatory
259		))]
260		pub fn set(origin: OriginFor<T>, #[pallet::compact] now: T::Moment) -> DispatchResult {
261			ensure_none(origin)?;
262			assert!(!DidUpdate::<T>::exists(), "Timestamp must be updated only once in the block");
263			let prev = Now::<T>::get();
264			assert!(
265				prev.is_zero() || now >= prev + T::MinimumPeriod::get(),
266				"Timestamp must increment by at least <MinimumPeriod> between sequential blocks"
267			);
268			Now::<T>::put(now);
269			DidUpdate::<T>::put(true);
270
271			<T::OnTimestampSet as OnTimestampSet<_>>::on_timestamp_set(now);
272
273			Ok(())
274		}
275	}
276
277	/// To check the inherent is valid, we simply take the max value between the current timestamp
278	/// and the current timestamp plus the [`Config::MinimumPeriod`].
279	/// We also check that the timestamp has not already been set in this block.
280	///
281	/// ## Errors:
282	/// - [`InherentError::TooFarInFuture`]: If the timestamp is larger than the current timestamp +
283	///   minimum drift period.
284	/// - [`InherentError::TooEarly`]: If the timestamp is less than the current + minimum period.
285	#[pallet::inherent]
286	impl<T: Config> ProvideInherent for Pallet<T> {
287		type Call = Call<T>;
288		type Error = InherentError;
289		const INHERENT_IDENTIFIER: InherentIdentifier = INHERENT_IDENTIFIER;
290
291		fn create_inherent(data: &InherentData) -> Option<Self::Call> {
292			let inherent_data = data
293				.get_data::<InherentType>(&INHERENT_IDENTIFIER)
294				.expect("Timestamp inherent data not correctly encoded")
295				.expect("Timestamp inherent data must be provided");
296			let data = (*inherent_data).saturated_into::<T::Moment>();
297
298			let next_time = cmp::max(data, Now::<T>::get() + T::MinimumPeriod::get());
299			Some(Call::set { now: next_time })
300		}
301
302		fn check_inherent(
303			call: &Self::Call,
304			data: &InherentData,
305		) -> result::Result<(), Self::Error> {
306			const MAX_TIMESTAMP_DRIFT_MILLIS: sp_timestamp::Timestamp =
307				sp_timestamp::Timestamp::new(30 * 1000);
308
309			let t: u64 = match call {
310				Call::set { ref now } => (*now).saturated_into::<u64>(),
311				_ => return Ok(()),
312			};
313
314			let data = data
315				.get_data::<InherentType>(&INHERENT_IDENTIFIER)
316				.expect("Timestamp inherent data not correctly encoded")
317				.expect("Timestamp inherent data must be provided");
318
319			let minimum = (Now::<T>::get() + T::MinimumPeriod::get()).saturated_into::<u64>();
320			if t > *(data + MAX_TIMESTAMP_DRIFT_MILLIS) {
321				Err(InherentError::TooFarInFuture)
322			} else if t < minimum {
323				Err(InherentError::TooEarly)
324			} else {
325				Ok(())
326			}
327		}
328
329		fn is_inherent(call: &Self::Call) -> bool {
330			matches!(call, Call::set { .. })
331		}
332	}
333}
334
335impl<T: Config> Pallet<T> {
336	/// Get the current time for the current block.
337	///
338	/// NOTE: if this function is called prior to setting the timestamp,
339	/// it will return the timestamp of the previous block.
340	pub fn get() -> T::Moment {
341		Now::<T>::get()
342	}
343
344	/// Set the timestamp to something in particular. Only used for tests.
345	#[cfg(any(feature = "runtime-benchmarks", feature = "std"))]
346	pub fn set_timestamp(now: T::Moment) {
347		Now::<T>::put(now);
348		DidUpdate::<T>::put(true);
349		<T::OnTimestampSet as OnTimestampSet<_>>::on_timestamp_set(now);
350	}
351}
352
353impl<T: Config> Time for Pallet<T> {
354	/// A type that represents a unit of time.
355	type Moment = T::Moment;
356
357	fn now() -> Self::Moment {
358		Now::<T>::get()
359	}
360}
361
362/// Before the timestamp inherent is applied, it returns the time of previous block.
363///
364/// On genesis the time returned is not valid.
365impl<T: Config> UnixTime for Pallet<T> {
366	fn now() -> core::time::Duration {
367		// now is duration since unix epoch in millisecond as documented in
368		// `sp_timestamp::InherentDataProvider`.
369		let now = Now::<T>::get();
370
371		if now == T::Moment::zero() {
372			log::error!(
373				target: "runtime::timestamp",
374				"`pallet_timestamp::UnixTime::now` is called at genesis, invalid value returned: 0",
375			);
376		}
377
378		core::time::Duration::from_millis(now.saturated_into::<u64>())
379	}
380}