referrerpolicy=no-referrer-when-downgrade

sc_consensus_manual_seal/consensus/
timestamp.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
5
6// This program is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10
11// This program is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// You should have received a copy of the GNU General Public License
17// along with this program. If not, see <https://www.gnu.org/licenses/>.
18
19//! Mocked timestamp inherent, allows for manual seal to create blocks for runtimes
20//! that expect this inherent.
21
22use crate::Error;
23use sc_client_api::{AuxStore, UsageProvider};
24use sp_api::ProvideRuntimeApi;
25use sp_blockchain::HeaderBackend;
26use sp_consensus_aura::{sr25519::AuthorityId, AuraApi};
27use sp_consensus_babe::BabeApi;
28use sp_consensus_slots::{Slot, SlotDuration};
29use sp_inherents::{InherentData, InherentDataProvider, InherentIdentifier};
30use sp_runtime::traits::{Block as BlockT, Zero};
31use sp_timestamp::{InherentType, INHERENT_IDENTIFIER};
32use std::{
33	sync::{atomic, Arc},
34	time::SystemTime,
35};
36
37/// Provide duration since unix epoch in millisecond for timestamp inherent.
38/// Mocks the timestamp inherent to always produce a valid timestamp for the next slot.
39///
40/// This works by either fetching the `slot_number` from the most recent header and dividing
41/// that value by `slot_duration` in order to fork chains that expect this inherent.
42///
43/// It produces timestamp inherents that are increased by `slot_duration` whenever
44/// `provide_inherent_data` is called.
45pub struct SlotTimestampProvider {
46	// holds the unix millisecond timestamp for the most recent block
47	unix_millis: atomic::AtomicU64,
48	// configured slot_duration in the runtime
49	slot_duration: SlotDuration,
50}
51
52impl SlotTimestampProvider {
53	/// Create a new mocked time stamp provider, for babe.
54	pub fn new_babe<B, C>(client: Arc<C>) -> Result<Self, Error>
55	where
56		B: BlockT,
57		C: AuxStore + HeaderBackend<B> + ProvideRuntimeApi<B> + UsageProvider<B>,
58		C::Api: BabeApi<B>,
59	{
60		let slot_duration = sc_consensus_babe::configuration(&*client)?.slot_duration();
61
62		let time = Self::with_header(&client, slot_duration, |header| {
63			let slot_number = *sc_consensus_babe::find_pre_digest::<B>(&header)
64				.map_err(|err| format!("{}", err))?
65				.slot();
66			Ok(slot_number)
67		})?;
68
69		Ok(Self { unix_millis: atomic::AtomicU64::new(time), slot_duration })
70	}
71
72	/// Create a new mocked time stamp provider, for aura
73	pub fn new_aura<B, C>(client: Arc<C>) -> Result<Self, Error>
74	where
75		B: BlockT,
76		C: AuxStore + HeaderBackend<B> + ProvideRuntimeApi<B> + UsageProvider<B>,
77		C::Api: AuraApi<B, AuthorityId>,
78	{
79		let slot_duration = sc_consensus_aura::slot_duration(&*client)?;
80
81		let time = Self::with_header(&client, slot_duration, |header| {
82			let slot_number = *sc_consensus_aura::find_pre_digest::<B>(&header)
83				.map_err(|err| format!("{}", err))?;
84			Ok(slot_number)
85		})?;
86
87		Ok(Self { unix_millis: atomic::AtomicU64::new(time), slot_duration })
88	}
89
90	fn with_header<F, C, B>(
91		client: &Arc<C>,
92		slot_duration: SlotDuration,
93		func: F,
94	) -> Result<u64, Error>
95	where
96		B: BlockT,
97		C: AuxStore + HeaderBackend<B> + UsageProvider<B>,
98		F: Fn(B::Header) -> Result<u64, Error>,
99	{
100		let info = client.info();
101
102		// looks like this isn't the first block, rehydrate the fake time.
103		// otherwise we'd be producing blocks for older slots.
104		let time = if info.best_number != Zero::zero() {
105			let header = client
106				.header(info.best_hash)?
107				.ok_or_else(|| "best header not found in the db!".to_string())?;
108			let slot = func(header)?;
109			// add the slot duration so there's no collision of slots
110			(slot * slot_duration.as_millis() as u64) + slot_duration.as_millis() as u64
111		} else {
112			// this is the first block, use the correct time.
113			let now = SystemTime::now();
114			now.duration_since(SystemTime::UNIX_EPOCH)
115				.map_err(|err| Error::StringError(format!("{}", err)))?
116				.as_millis() as u64
117		};
118
119		Ok(time)
120	}
121
122	/// Get the current slot number
123	pub fn slot(&self) -> Slot {
124		Slot::from_timestamp(
125			self.unix_millis.load(atomic::Ordering::SeqCst).into(),
126			self.slot_duration,
127		)
128	}
129
130	/// Gets the current time stamp.
131	pub fn timestamp(&self) -> sp_timestamp::Timestamp {
132		sp_timestamp::Timestamp::new(self.unix_millis.load(atomic::Ordering::SeqCst))
133	}
134}
135
136#[async_trait::async_trait]
137impl InherentDataProvider for SlotTimestampProvider {
138	async fn provide_inherent_data(
139		&self,
140		inherent_data: &mut InherentData,
141	) -> Result<(), sp_inherents::Error> {
142		// we update the time here.
143		let new_time: InherentType = self
144			.unix_millis
145			.fetch_add(self.slot_duration.as_millis() as u64, atomic::Ordering::SeqCst)
146			.into();
147		inherent_data.put_data(INHERENT_IDENTIFIER, &new_time)?;
148		Ok(())
149	}
150
151	async fn try_handle_error(
152		&self,
153		_: &InherentIdentifier,
154		_: &[u8],
155	) -> Option<Result<(), sp_inherents::Error>> {
156		None
157	}
158}