sc_consensus_manual_seal/consensus/
timestamp.rs1use 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
37pub struct SlotTimestampProvider {
46 unix_millis: atomic::AtomicU64,
48 slot_duration: SlotDuration,
50}
51
52impl SlotTimestampProvider {
53 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 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 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 (slot * slot_duration.as_millis() as u64) + slot_duration.as_millis() as u64
111 } else {
112 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 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 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 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}