referrerpolicy=no-referrer-when-downgrade

polkadot_runtime_parachains/
shared.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// This file is part of Polkadot.
3
4// Polkadot is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// Polkadot is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with Polkadot.  If not, see <http://www.gnu.org/licenses/>.
16
17//! A pallet for any shared state that other pallets may want access to.
18//!
19//! To avoid cyclic dependencies, it is important that this pallet is not
20//! dependent on any of the other pallets.
21
22use alloc::{
23	collections::{btree_map::BTreeMap, btree_set::BTreeSet, vec_deque::VecDeque},
24	vec::Vec,
25};
26use frame_support::{pallet_prelude::*, traits::DisabledValidators};
27use frame_system::pallet_prelude::BlockNumberFor;
28use polkadot_primitives::{
29	transpose_claim_queue, CoreIndex, Id, SessionIndex, ValidatorId, ValidatorIndex,
30};
31use sp_runtime::traits::AtLeast32BitUnsigned;
32
33use rand::{seq::SliceRandom, SeedableRng};
34use rand_chacha::ChaCha20Rng;
35
36use crate::configuration::HostConfiguration;
37
38pub use pallet::*;
39
40// `SESSION_DELAY` is used to delay any changes to Paras registration or configurations.
41// Wait until the session index is 2 larger then the current index to apply any changes,
42// which guarantees that at least one full session has passed before any changes are applied.
43pub(crate) const SESSION_DELAY: SessionIndex = 2;
44
45#[cfg(test)]
46mod tests;
47
48pub mod migration;
49
50/// Information about a relay parent.
51#[derive(Encode, Decode, Default, TypeInfo, Debug)]
52pub struct RelayParentInfo<Hash> {
53	// Relay parent hash
54	pub relay_parent: Hash,
55	// The state root at this block
56	pub state_root: Hash,
57	// Claim queue snapshot, optimized for accessing the assignments by `ParaId`.
58	// For each para we store the cores assigned per depth.
59	pub claim_queue: BTreeMap<Id, BTreeMap<u8, BTreeSet<CoreIndex>>>,
60}
61
62/// Keeps tracks of information about all viable relay parents.
63#[derive(Encode, Decode, Default, TypeInfo)]
64pub struct AllowedRelayParentsTracker<Hash, BlockNumber> {
65	// Information about past relay parents that are viable to build upon.
66	//
67	// They are in ascending chronologic order, so the newest relay parents are at
68	// the back of the deque.
69	buffer: VecDeque<RelayParentInfo<Hash>>,
70
71	// The number of the most recent relay-parent, if any.
72	// If the buffer is empty, this value has no meaning and may
73	// be nonsensical.
74	latest_number: BlockNumber,
75}
76
77impl<Hash: PartialEq + Copy, BlockNumber: AtLeast32BitUnsigned + Copy>
78	AllowedRelayParentsTracker<Hash, BlockNumber>
79{
80	/// Add a new relay-parent to the allowed relay parents, along with info about the header.
81	/// Provide a maximum ancestry length for the buffer, which will cause old relay-parents to be
82	/// pruned.
83	/// If the relay parent hash is already present, do nothing.
84	pub(crate) fn update(
85		&mut self,
86		relay_parent: Hash,
87		state_root: Hash,
88		claim_queue: BTreeMap<CoreIndex, VecDeque<Id>>,
89		number: BlockNumber,
90		max_ancestry_len: u32,
91	) {
92		if self.buffer.iter().any(|info| info.relay_parent == relay_parent) {
93			// Already present.
94			return
95		}
96
97		let claim_queue = transpose_claim_queue(claim_queue);
98
99		self.buffer.push_back(RelayParentInfo { relay_parent, state_root, claim_queue });
100
101		self.latest_number = number;
102		while self.buffer.len() > (max_ancestry_len as usize) {
103			let _ = self.buffer.pop_front();
104		}
105
106		// We only allow relay parents within the same sessions, the buffer
107		// gets cleared on session changes.
108	}
109
110	/// Attempt to acquire the state root and block number to be used when building
111	/// upon the given relay-parent.
112	///
113	/// This only succeeds if the relay-parent is one of the allowed relay-parents.
114	/// If a previous relay-parent number is passed, then this only passes if the new relay-parent
115	/// is more recent than the previous.
116	pub(crate) fn acquire_info(
117		&self,
118		relay_parent: Hash,
119		prev: Option<BlockNumber>,
120	) -> Option<(&RelayParentInfo<Hash>, BlockNumber)> {
121		let pos = self.buffer.iter().position(|info| info.relay_parent == relay_parent)?;
122		let age = (self.buffer.len() - 1) - pos;
123		let number = self.latest_number - BlockNumber::from(age as u32);
124
125		if let Some(prev) = prev {
126			if prev > number {
127				return None
128			}
129		}
130
131		Some((&self.buffer[pos], number))
132	}
133
134	/// Returns block number of the earliest block the buffer would contain if
135	/// `now` is pushed into it.
136	pub(crate) fn hypothetical_earliest_block_number(
137		&self,
138		now: BlockNumber,
139		max_ancestry_len: u32,
140	) -> BlockNumber {
141		let allowed_ancestry_len = max_ancestry_len.min(self.buffer.len() as u32);
142
143		now - allowed_ancestry_len.into()
144	}
145}
146
147#[frame_support::pallet]
148pub mod pallet {
149	use super::*;
150
151	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);
152
153	#[pallet::pallet]
154	#[pallet::without_storage_info]
155	#[pallet::storage_version(STORAGE_VERSION)]
156	pub struct Pallet<T>(_);
157
158	#[pallet::config]
159	pub trait Config: frame_system::Config {
160		type DisabledValidators: frame_support::traits::DisabledValidators;
161	}
162
163	/// The current session index.
164	#[pallet::storage]
165	pub type CurrentSessionIndex<T: Config> = StorageValue<_, SessionIndex, ValueQuery>;
166
167	/// All the validators actively participating in parachain consensus.
168	/// Indices are into the broader validator set.
169	#[pallet::storage]
170	pub type ActiveValidatorIndices<T: Config> = StorageValue<_, Vec<ValidatorIndex>, ValueQuery>;
171
172	/// The parachain attestation keys of the validators actively participating in parachain
173	/// consensus. This should be the same length as `ActiveValidatorIndices`.
174	#[pallet::storage]
175	pub type ActiveValidatorKeys<T: Config> = StorageValue<_, Vec<ValidatorId>, ValueQuery>;
176
177	/// All allowed relay-parents.
178	#[pallet::storage]
179	pub(crate) type AllowedRelayParents<T: Config> =
180		StorageValue<_, AllowedRelayParentsTracker<T::Hash, BlockNumberFor<T>>, ValueQuery>;
181
182	#[pallet::call]
183	impl<T: Config> Pallet<T> {}
184}
185
186impl<T: Config> Pallet<T> {
187	/// Called by the initializer to initialize the configuration pallet.
188	pub(crate) fn initializer_initialize(_now: BlockNumberFor<T>) -> Weight {
189		Weight::zero()
190	}
191
192	/// Called by the initializer to finalize the configuration pallet.
193	pub(crate) fn initializer_finalize() {}
194
195	/// Called by the initializer to note that a new session has started.
196	///
197	/// Returns the list of outgoing paras from the actions queue.
198	pub(crate) fn initializer_on_new_session(
199		session_index: SessionIndex,
200		random_seed: [u8; 32],
201		new_config: &HostConfiguration<BlockNumberFor<T>>,
202		all_validators: Vec<ValidatorId>,
203	) -> Vec<ValidatorId> {
204		// Drop allowed relay parents buffer on a session change.
205		//
206		// During the initialization of the next block we always add its parent
207		// to the tracker.
208		//
209		// With asynchronous backing candidates built on top of relay
210		// parent `R` are still restricted by the runtime to be backed
211		// by the group assigned at `number(R) + 1`, which is guaranteed
212		// to be in the current session.
213		AllowedRelayParents::<T>::mutate(|tracker| tracker.buffer.clear());
214
215		CurrentSessionIndex::<T>::set(session_index);
216		let mut rng: ChaCha20Rng = SeedableRng::from_seed(random_seed);
217
218		let mut shuffled_indices: Vec<_> = (0..all_validators.len())
219			.enumerate()
220			.map(|(i, _)| ValidatorIndex(i as _))
221			.collect();
222
223		shuffled_indices.shuffle(&mut rng);
224
225		if let Some(max) = new_config.max_validators {
226			shuffled_indices.truncate(max as usize);
227		}
228
229		let active_validator_keys =
230			crate::util::take_active_subset(&shuffled_indices, &all_validators);
231
232		ActiveValidatorIndices::<T>::set(shuffled_indices);
233		ActiveValidatorKeys::<T>::set(active_validator_keys.clone());
234
235		active_validator_keys
236	}
237
238	/// Return the session index that should be used for any future scheduled changes.
239	pub fn scheduled_session() -> SessionIndex {
240		CurrentSessionIndex::<T>::get().saturating_add(SESSION_DELAY)
241	}
242
243	/// Fetches disabled validators list from session pallet.
244	/// CAVEAT: this might produce incorrect results on session boundaries
245	pub fn disabled_validators() -> Vec<ValidatorIndex> {
246		let shuffled_indices = ActiveValidatorIndices::<T>::get();
247		// mapping from raw validator index to `ValidatorIndex`
248		// this computation is the same within a session, but should be cheap
249		let reverse_index = shuffled_indices
250			.iter()
251			.enumerate()
252			.map(|(i, v)| (v.0, ValidatorIndex(i as u32)))
253			.collect::<BTreeMap<u32, ValidatorIndex>>();
254
255		// we might have disabled validators who are not parachain validators
256		T::DisabledValidators::disabled_validators()
257			.iter()
258			.filter_map(|v| reverse_index.get(v).cloned())
259			.collect()
260	}
261
262	/// Test function for setting the current session index.
263	#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
264	pub fn set_session_index(index: SessionIndex) {
265		CurrentSessionIndex::<T>::set(index);
266	}
267
268	#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
269	pub fn set_active_validators_ascending(active: Vec<ValidatorId>) {
270		ActiveValidatorIndices::<T>::set(
271			(0..active.len()).map(|i| ValidatorIndex(i as _)).collect(),
272		);
273		ActiveValidatorKeys::<T>::set(active);
274	}
275
276	#[cfg(test)]
277	pub(crate) fn set_active_validators_with_indices(
278		indices: Vec<ValidatorIndex>,
279		keys: Vec<ValidatorId>,
280	) {
281		assert_eq!(indices.len(), keys.len());
282		ActiveValidatorIndices::<T>::set(indices);
283		ActiveValidatorKeys::<T>::set(keys);
284	}
285
286	#[cfg(test)]
287	pub(crate) fn add_allowed_relay_parent(
288		relay_parent: T::Hash,
289		state_root: T::Hash,
290		claim_queue: BTreeMap<CoreIndex, VecDeque<Id>>,
291		number: BlockNumberFor<T>,
292		max_ancestry_len: u32,
293	) {
294		AllowedRelayParents::<T>::mutate(|tracker| {
295			tracker.update(relay_parent, state_root, claim_queue, number, max_ancestry_len + 1)
296		})
297	}
298}