referrerpolicy=no-referrer-when-downgrade

cumulus_primitives_timestamp/
lib.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// This file is part of Cumulus.
3// SPDX-License-Identifier: Apache-2.0
4
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// 	http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17//! Cumulus timestamp related primitives.
18//!
19//! Provides a [`InherentDataProvider`] that should be used in the validation phase of the
20//! parachain. It will be used to create the inherent data and that will be used to check the
21//! inherents inside the parachain block (in this case the timestamp inherent). As we don't have
22//! access to any clock from the runtime the timestamp is always passed as an inherent into the
23//! runtime. To check this inherent when validating the block, we will use the relay chain slot. As
24//! the relay chain slot is derived from a timestamp, we can easily convert it back to a timestamp
25//! by multiplying it with the slot duration. By comparing the relay chain slot derived timestamp
26//! with the timestamp we can ensure that the parachain timestamp is reasonable.
27
28#![cfg_attr(not(feature = "std"), no_std)]
29
30use core::time::Duration;
31use cumulus_primitives_core::relay_chain::Slot;
32use sp_inherents::{Error, InherentData};
33
34pub use sp_timestamp::{InherentType, INHERENT_IDENTIFIER};
35
36/// The inherent data provider for the timestamp.
37///
38/// This should be used in the runtime when checking the inherents in the validation phase of the
39/// parachain.
40pub struct InherentDataProvider {
41	relay_chain_slot: Slot,
42	relay_chain_slot_duration: Duration,
43}
44
45impl InherentDataProvider {
46	/// Create `Self` from the given relay chain slot and slot duration.
47	pub fn from_relay_chain_slot_and_duration(
48		relay_chain_slot: Slot,
49		relay_chain_slot_duration: Duration,
50	) -> Self {
51		Self { relay_chain_slot, relay_chain_slot_duration }
52	}
53
54	/// Create the inherent data.
55	pub fn create_inherent_data(&self) -> Result<InherentData, Error> {
56		let mut inherent_data = InherentData::new();
57		self.provide_inherent_data(&mut inherent_data).map(|_| inherent_data)
58	}
59
60	/// Provide the inherent data into the given `inherent_data`.
61	pub fn provide_inherent_data(&self, inherent_data: &mut InherentData) -> Result<(), Error> {
62		// As the parachain starts building at around `relay_chain_slot + 1` we use that slot to
63		// calculate the timestamp.
64		//
65		// Use saturating arithmetic to avoid overflow if inputs are out of range.
66		let slot_duration_millis =
67			u64::try_from(self.relay_chain_slot_duration.as_millis()).unwrap_or(u64::MAX);
68		let next_slot = self.relay_chain_slot.saturating_add(1u64);
69		let data: InherentType = (*next_slot).saturating_mul(slot_duration_millis).into();
70
71		inherent_data.put_data(INHERENT_IDENTIFIER, &data)
72	}
73}
74
75#[cfg(test)]
76mod tests {
77	use super::*;
78
79	fn timestamp_for(relay_chain_slot: u64, slot_duration: Duration) -> InherentType {
80		let inherent_data = InherentDataProvider::from_relay_chain_slot_and_duration(
81			Slot::from(relay_chain_slot),
82			slot_duration,
83		)
84		.create_inherent_data()
85		.expect("inherent data is created");
86
87		inherent_data
88			.get_data(&INHERENT_IDENTIFIER)
89			.expect("inherent data decodes")
90			.expect("inherent data is present")
91	}
92
93	#[test]
94	fn zero_slot_duration_is_a_zero_timestamp() {
95		assert_eq!(timestamp_for(100, Duration::ZERO), 0u64);
96	}
97
98	#[test]
99	fn timestamp_is_the_start_of_the_next_relay_chain_slot() {
100		assert_eq!(timestamp_for(100, Duration::from_millis(6_000)), 606_000u64);
101	}
102
103	#[test]
104	fn max_relay_chain_slot_does_not_overflow() {
105		assert_eq!(timestamp_for(u64::MAX, Duration::from_millis(6_000)), u64::MAX);
106	}
107
108	#[test]
109	fn huge_slot_duration_does_not_overflow() {
110		assert_eq!(timestamp_for(1, Duration::MAX), u64::MAX);
111	}
112
113	#[test]
114	fn slot_duration_above_u64_millis_does_not_truncate() {
115		// Verify that a duration larger than `u64::MAX` milliseconds saturates instead of wrapping.
116		let duration = Duration::new(18_446_744_073_709_551, 616_000_000);
117		assert_eq!(duration.as_millis(), u128::from(u64::MAX) + 1);
118		assert_eq!(timestamp_for(1, duration), u64::MAX);
119	}
120}