referrerpolicy=no-referrer-when-downgrade

pallet_aura/
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//! # Aura Module
19//!
20//! - [`Config`]
21//! - [`Pallet`]
22//!
23//! ## Overview
24//!
25//! The Aura module extends Aura consensus by managing offline reporting.
26//!
27//! ## Interface
28//!
29//! ### Public Functions
30//!
31//! - `slot_duration` - Determine the Aura slot-duration based on the Timestamp module
32//!   configuration.
33//!
34//! ## Related Modules
35//!
36//! - [Timestamp](../pallet_timestamp/index.html): The Timestamp module is used in Aura to track
37//! consensus rounds (via `slots`).
38
39#![cfg_attr(not(feature = "std"), no_std)]
40
41extern crate alloc;
42
43use alloc::vec::Vec;
44use codec::{Decode, Encode, MaxEncodedLen};
45use frame_support::{
46	traits::{DisabledValidators, FindAuthor, Get, OnTimestampSet, OneSessionHandler},
47	BoundedSlice, BoundedVec, ConsensusEngineId, Parameter,
48};
49use log;
50use sp_consensus_aura::{AuthorityIndex, ConsensusLog, Slot, AURA_ENGINE_ID};
51use sp_runtime::{
52	generic::DigestItem,
53	traits::{IsMember, Member, SaturatedConversion, Saturating, Zero},
54	RuntimeAppPublic,
55};
56
57pub mod migrations;
58mod mock;
59mod tests;
60
61pub use pallet::*;
62
63const LOG_TARGET: &str = "runtime::aura";
64
65/// A slot duration provider which infers the slot duration from the
66/// [`pallet_timestamp::Config::MinimumPeriod`] by multiplying it by two, to ensure
67/// that authors have the majority of their slot to author within.
68///
69/// This was the default behavior of the Aura pallet and may be used for
70/// backwards compatibility.
71pub struct MinimumPeriodTimesTwo<T>(core::marker::PhantomData<T>);
72
73impl<T: pallet_timestamp::Config> Get<T::Moment> for MinimumPeriodTimesTwo<T> {
74	fn get() -> T::Moment {
75		<T as pallet_timestamp::Config>::MinimumPeriod::get().saturating_mul(2u32.into())
76	}
77}
78
79#[frame_support::pallet]
80pub mod pallet {
81	use super::*;
82	use frame_support::pallet_prelude::*;
83	use frame_system::pallet_prelude::*;
84
85	#[pallet::config]
86	pub trait Config: pallet_timestamp::Config + frame_system::Config {
87		/// The identifier type for an authority.
88		type AuthorityId: Member
89			+ Parameter
90			+ RuntimeAppPublic
91			+ MaybeSerializeDeserialize
92			+ MaxEncodedLen;
93		/// The maximum number of authorities that the pallet can hold.
94		type MaxAuthorities: Get<u32>;
95
96		/// A way to check whether a given validator is disabled and should not be authoring blocks.
97		/// Blocks authored by a disabled validator will lead to a panic as part of this module's
98		/// initialization.
99		type DisabledValidators: DisabledValidators;
100
101		/// Whether to allow block authors to create multiple blocks per slot.
102		///
103		/// If this is `true`, the pallet will allow slots to stay the same across sequential
104		/// blocks. If this is `false`, the pallet will require that subsequent blocks always have
105		/// higher slots than previous ones.
106		///
107		/// Regardless of the setting of this storage value, the pallet will always enforce the
108		/// invariant that slots don't move backwards as the chain progresses.
109		///
110		/// The typical value for this should be 'false' unless this pallet is being augmented by
111		/// another pallet which enforces some limitation on the number of blocks authors can create
112		/// using the same slot.
113		type AllowMultipleBlocksPerSlot: Get<bool>;
114
115		/// The slot duration Aura should run with, expressed in milliseconds.
116		/// The effective value of this type should not change while the chain is running.
117		///
118		/// For backwards compatibility either use [`MinimumPeriodTimesTwo`] or a const.
119		#[pallet::constant]
120		type SlotDuration: Get<<Self as pallet_timestamp::Config>::Moment>;
121	}
122
123	#[pallet::pallet]
124	pub struct Pallet<T>(core::marker::PhantomData<T>);
125
126	#[pallet::hooks]
127	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
128		fn on_initialize(_: BlockNumberFor<T>) -> Weight {
129			if let Some(new_slot) = Self::current_slot_from_digests() {
130				let current_slot = CurrentSlot::<T>::get();
131
132				if T::AllowMultipleBlocksPerSlot::get() {
133					assert!(current_slot <= new_slot, "Slot must not decrease");
134				} else {
135					assert!(current_slot < new_slot, "Slot must increase");
136				}
137
138				CurrentSlot::<T>::put(new_slot);
139
140				if let Some(n_authorities) = <Authorities<T>>::decode_len() {
141					let authority_index = *new_slot % n_authorities as u64;
142					if T::DisabledValidators::is_disabled(authority_index as u32) {
143						panic!(
144							"Validator with index {:?} is disabled and should not be attempting to author blocks.",
145							authority_index,
146						);
147					}
148				}
149
150				// TODO [#3398] Generate offence report for all authorities that skipped their
151				// slots.
152
153				T::DbWeight::get().reads_writes(2, 1)
154			} else {
155				T::DbWeight::get().reads(1)
156			}
157		}
158
159		#[cfg(feature = "try-runtime")]
160		fn try_state(_: BlockNumberFor<T>) -> Result<(), sp_runtime::TryRuntimeError> {
161			Self::do_try_state()
162		}
163	}
164
165	/// The current authority set.
166	#[pallet::storage]
167	pub type Authorities<T: Config> =
168		StorageValue<_, BoundedVec<T::AuthorityId, T::MaxAuthorities>, ValueQuery>;
169
170	/// The current slot of this block.
171	///
172	/// This will be set in `on_initialize`.
173	#[pallet::storage]
174	pub type CurrentSlot<T: Config> = StorageValue<_, Slot, ValueQuery>;
175
176	#[pallet::genesis_config]
177	#[derive(frame_support::DefaultNoBound)]
178	pub struct GenesisConfig<T: Config> {
179		pub authorities: Vec<T::AuthorityId>,
180	}
181
182	#[pallet::genesis_build]
183	impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
184		fn build(&self) {
185			Pallet::<T>::initialize_authorities(&self.authorities);
186		}
187	}
188}
189
190impl<T: Config> Pallet<T> {
191	/// Change authorities.
192	///
193	/// The storage will be applied immediately.
194	/// And aura consensus log will be appended to block's log.
195	///
196	/// This is a no-op if `new` is empty.
197	pub fn change_authorities(new: BoundedVec<T::AuthorityId, T::MaxAuthorities>) {
198		if new.is_empty() {
199			log::warn!(target: LOG_TARGET, "Ignoring empty authority change.");
200
201			return
202		}
203
204		<Authorities<T>>::put(&new);
205
206		let log = DigestItem::Consensus(
207			AURA_ENGINE_ID,
208			ConsensusLog::AuthoritiesChange(new.into_inner()).encode(),
209		);
210		<frame_system::Pallet<T>>::deposit_log(log);
211	}
212
213	/// Initial authorities.
214	///
215	/// The storage will be applied immediately.
216	///
217	/// The authorities length must be equal or less than T::MaxAuthorities.
218	pub fn initialize_authorities(authorities: &[T::AuthorityId]) {
219		if !authorities.is_empty() {
220			assert!(<Authorities<T>>::get().is_empty(), "Authorities are already initialized!");
221			let bounded = <BoundedSlice<'_, _, T::MaxAuthorities>>::try_from(authorities)
222				.expect("Initial authority set must be less than T::MaxAuthorities");
223			<Authorities<T>>::put(bounded);
224		}
225	}
226
227	/// Return current authorities length.
228	pub fn authorities_len() -> usize {
229		Authorities::<T>::decode_len().unwrap_or(0)
230	}
231
232	/// Get the current slot from the pre-runtime digests.
233	fn current_slot_from_digests() -> Option<Slot> {
234		let digest = frame_system::Pallet::<T>::digest();
235		let pre_runtime_digests = digest.logs.iter().filter_map(|d| d.as_pre_runtime());
236		for (id, mut data) in pre_runtime_digests {
237			if id == AURA_ENGINE_ID {
238				return Slot::decode(&mut data).ok()
239			}
240		}
241
242		None
243	}
244
245	/// Determine the Aura slot-duration based on the Timestamp module configuration.
246	pub fn slot_duration() -> T::Moment {
247		T::SlotDuration::get()
248	}
249
250	/// Ensure the correctness of the state of this pallet.
251	///
252	/// This should be valid before or after each state transition of this pallet.
253	///
254	/// # Invariants
255	///
256	/// ## `CurrentSlot`
257	///
258	/// If we don't allow for multiple blocks per slot, then the current slot must be less than the
259	/// maximal slot number. Otherwise, it can be arbitrary.
260	///
261	/// ## `Authorities`
262	///
263	/// * The authorities must be non-empty.
264	/// * The current authority cannot be disabled.
265	/// * The number of authorities must be less than or equal to `T::MaxAuthorities`. This however,
266	///   is guarded by the type system.
267	#[cfg(any(test, feature = "try-runtime"))]
268	pub fn do_try_state() -> Result<(), sp_runtime::TryRuntimeError> {
269		// We don't have any guarantee that we are already after `on_initialize` and thus we have to
270		// check the current slot from the digest or take the last known slot.
271		let current_slot =
272			Self::current_slot_from_digests().unwrap_or_else(|| CurrentSlot::<T>::get());
273
274		// Check that the current slot is less than the maximal slot number, unless we allow for
275		// multiple blocks per slot.
276		if !T::AllowMultipleBlocksPerSlot::get() {
277			frame_support::ensure!(
278				current_slot < u64::MAX,
279				"Current slot has reached maximum value and cannot be incremented further.",
280			);
281		}
282
283		let authorities_len =
284			<Authorities<T>>::decode_len().ok_or("Failed to decode authorities length")?;
285
286		// Check that the authorities are non-empty.
287		frame_support::ensure!(!authorities_len.is_zero(), "Authorities must be non-empty.");
288
289		// Check that the current authority is not disabled.
290		let authority_index = *current_slot % authorities_len as u64;
291		frame_support::ensure!(
292			!T::DisabledValidators::is_disabled(authority_index as u32),
293			"Current validator is disabled and should not be attempting to author blocks.",
294		);
295
296		Ok(())
297	}
298}
299
300impl<T: Config> sp_runtime::BoundToRuntimeAppPublic for Pallet<T> {
301	type Public = T::AuthorityId;
302}
303
304impl<T: Config> OneSessionHandler<T::AccountId> for Pallet<T> {
305	type Key = T::AuthorityId;
306
307	fn on_genesis_session<'a, I: 'a>(validators: I)
308	where
309		I: Iterator<Item = (&'a T::AccountId, T::AuthorityId)>,
310	{
311		let authorities = validators.map(|(_, k)| k).collect::<Vec<_>>();
312		Self::initialize_authorities(&authorities);
313	}
314
315	fn on_new_session<'a, I: 'a>(changed: bool, validators: I, _queued_validators: I)
316	where
317		I: Iterator<Item = (&'a T::AccountId, T::AuthorityId)>,
318	{
319		// instant changes
320		if changed {
321			let next_authorities = validators.map(|(_, k)| k).collect::<Vec<_>>();
322			let last_authorities = Authorities::<T>::get();
323			if last_authorities != next_authorities {
324				if next_authorities.len() as u32 > T::MaxAuthorities::get() {
325					log::warn!(
326						target: LOG_TARGET,
327						"next authorities list larger than {}, truncating",
328						T::MaxAuthorities::get(),
329					);
330				}
331				let bounded = <BoundedVec<_, T::MaxAuthorities>>::truncate_from(next_authorities);
332				Self::change_authorities(bounded);
333			}
334		}
335	}
336
337	fn on_disabled(i: u32) {
338		let log = DigestItem::Consensus(
339			AURA_ENGINE_ID,
340			ConsensusLog::<T::AuthorityId>::OnDisabled(i as AuthorityIndex).encode(),
341		);
342
343		<frame_system::Pallet<T>>::deposit_log(log);
344	}
345}
346
347impl<T: Config> FindAuthor<u32> for Pallet<T> {
348	fn find_author<'a, I>(digests: I) -> Option<u32>
349	where
350		I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,
351	{
352		for (id, mut data) in digests.into_iter() {
353			if id == AURA_ENGINE_ID {
354				let slot = Slot::decode(&mut data).ok()?;
355				let author_index = *slot % Self::authorities_len() as u64;
356				return Some(author_index as u32)
357			}
358		}
359
360		None
361	}
362}
363
364/// We can not implement `FindAuthor` twice, because the compiler does not know if
365/// `u32 == T::AuthorityId` and thus, prevents us to implement the trait twice.
366#[doc(hidden)]
367pub struct FindAccountFromAuthorIndex<T, Inner>(core::marker::PhantomData<(T, Inner)>);
368
369impl<T: Config, Inner: FindAuthor<u32>> FindAuthor<T::AuthorityId>
370	for FindAccountFromAuthorIndex<T, Inner>
371{
372	fn find_author<'a, I>(digests: I) -> Option<T::AuthorityId>
373	where
374		I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,
375	{
376		let i = Inner::find_author(digests)?;
377
378		let validators = Authorities::<T>::get();
379		validators.get(i as usize).cloned()
380	}
381}
382
383/// Find the authority ID of the Aura authority who authored the current block.
384pub type AuraAuthorId<T> = FindAccountFromAuthorIndex<T, Pallet<T>>;
385
386impl<T: Config> IsMember<T::AuthorityId> for Pallet<T> {
387	fn is_member(authority_id: &T::AuthorityId) -> bool {
388		Authorities::<T>::get().iter().any(|id| id == authority_id)
389	}
390}
391
392impl<T: Config> OnTimestampSet<T::Moment> for Pallet<T> {
393	fn on_timestamp_set(moment: T::Moment) {
394		let slot_duration = Self::slot_duration();
395		assert!(!slot_duration.is_zero(), "Aura slot duration cannot be zero.");
396
397		let timestamp_slot = moment / slot_duration;
398		let timestamp_slot = Slot::from(timestamp_slot.saturated_into::<u64>());
399
400		assert_eq!(
401			CurrentSlot::<T>::get(),
402			timestamp_slot,
403			"Timestamp slot must match `CurrentSlot`. This likely means that the configured block \
404			time in the node and/or rest of the runtime is not compatible with Aura's \
405			`SlotDuration`",
406		);
407	}
408}