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.network)
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

            
129
mod benchmarking;
130
#[cfg(test)]
131
mod mock;
132
#[cfg(test)]
133
mod tests;
134
pub mod weights;
135

            
136
use core::{cmp, result};
137
use frame_support::traits::{OnTimestampSet, Time, UnixTime};
138
use sp_runtime::traits::{AtLeast32Bit, SaturatedConversion, Scale, Zero};
139
use sp_timestamp::{InherentError, InherentType, INHERENT_IDENTIFIER};
140
pub use weights::WeightInfo;
141

            
142
pub use pallet::*;
143

            
144
198297
#[frame_support::pallet]
145
pub 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 = frame_support::traits::ConstU64<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
1698
	#[pallet::pallet]
201
	pub struct Pallet<T>(_);
202

            
203
	/// The current time for the current block.
204
917148
	#[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
1168578
	#[pallet::storage]
212
	pub(super) type DidUpdate<T: Config> = StorageValue<_, bool, ValueQuery>;
213

            
214
554367
	#[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
194763
		fn on_initialize(_n: BlockNumberFor<T>) -> Weight {
219
194763
			// weight of `on_finalize`
220
194763
			T::WeightInfo::on_finalize()
221
194763
		}
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
194763
		fn on_finalize(_n: BlockNumberFor<T>) {
230
194763
			assert!(DidUpdate::<T>::take(), "Timestamp must be updated once in the block");
231
194763
		}
232
	}
233

            
234
22929
	#[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
198297
		pub fn set(origin: OriginFor<T>, #[pallet::compact] now: T::Moment) -> DispatchResult {
261
198297
			ensure_none(origin)?;
262
194763
			assert!(!DidUpdate::<T>::exists(), "Timestamp must be updated only once in the block");
263
194763
			let prev = Now::<T>::get();
264
194763
			assert!(
265
194763
				prev.is_zero() || now >= prev + T::MinimumPeriod::get(),
266
				"Timestamp must increment by at least <MinimumPeriod> between sequential blocks"
267
			);
268
194763
			Now::<T>::put(now);
269
194763
			DidUpdate::<T>::put(true);
270
194763

            
271
194763
			<T::OnTimestampSet as OnTimestampSet<_>>::on_timestamp_set(now);
272
194763

            
273
194763
			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

            
335
impl<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

            
353
impl<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.
365
impl<T: Config> UnixTime for Pallet<T> {
366
69048
	fn now() -> core::time::Duration {
367
69048
		// now is duration since unix epoch in millisecond as documented in
368
69048
		// `sp_timestamp::InherentDataProvider`.
369
69048
		let now = Now::<T>::get();
370
69048

            
371
69048
		log::error!(
372
			target: "runtime::timestamp",
373
69048
			"`pallet_timestamp::UnixTime::now` is called at genesis, invalid value returned: 0",
374
		);
375

            
376
69048
		core::time::Duration::from_millis(now.saturated_into::<u64>())
377
69048
	}
378
}