referrerpolicy=no-referrer-when-downgrade

polkadot_runtime_parachains/paras_inherent/
mod.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//! Provides glue code over the scheduler and inclusion modules, and accepting
18//! one inherent per block that can include new para candidates and bitfields.
19//!
20//! Unlike other modules in this crate, it does not need to be initialized by the initializer,
21//! as it has no initialization logic and its finalization logic depends only on the details of
22//! this module.
23
24use crate::{
25	configuration,
26	disputes::DisputesHandler,
27	inclusion::{self, CandidateCheckContext},
28	initializer,
29	metrics::METRICS,
30	paras, scheduler,
31	shared::{self, AllowedSchedulingParentsTracker},
32	ParaId,
33};
34use alloc::{
35	collections::{btree_map::BTreeMap, btree_set::BTreeSet},
36	vec,
37	vec::Vec,
38};
39use bitvec::prelude::BitVec;
40use core::result::Result;
41use frame_support::{
42	defensive,
43	dispatch::{DispatchErrorWithPostInfo, PostDispatchInfo},
44	inherent::{InherentData, InherentIdentifier, MakeFatalError, ProvideInherent},
45	pallet_prelude::*,
46	traits::Randomness,
47};
48
49use frame_system::pallet_prelude::*;
50use pallet_babe::{self, ParentBlockRandomness};
51use polkadot_primitives::{
52	effective_minimum_backing_votes, node_features::FeatureIndex, BackedCandidate,
53	CandidateDescriptorVersion, CandidateHash, CandidateReceiptV2 as CandidateReceipt,
54	CheckedDisputeStatementSet, CheckedMultiDisputeStatementSet, CoreIndex, DisputeStatementSet,
55	HeadData, InherentData as ParachainsInherentData, MultiDisputeStatementSet,
56	ScrapedOnChainVotes, SessionIndex, SignedAvailabilityBitfields, SigningContext,
57	UncheckedSignedAvailabilityBitfield, UncheckedSignedAvailabilityBitfields, ValidatorId,
58	ValidatorIndex, ValidityAttestation, PARACHAINS_INHERENT_IDENTIFIER,
59};
60use rand::{seq::SliceRandom, SeedableRng};
61use scale_info::TypeInfo;
62use sp_runtime::traits::{Header as HeaderT, One, Saturating};
63
64mod misc;
65mod weights;
66
67use self::weights::checked_multi_dispute_statement_sets_weight;
68pub use self::{
69	misc::{IndexedRetain, IsSortedBy},
70	weights::{
71		backed_candidate_weight, backed_candidates_weight, dispute_statement_set_weight,
72		multi_dispute_statement_sets_weight, paras_inherent_total_weight, signed_bitfield_weight,
73		signed_bitfields_weight, TestWeightInfo, WeightInfo,
74	},
75};
76
77#[cfg(feature = "runtime-benchmarks")]
78mod benchmarking;
79
80#[cfg(test)]
81mod tests;
82
83const LOG_TARGET: &str = "runtime::inclusion-inherent";
84
85/// A bitfield concerning concluded disputes for candidates
86/// associated to the core index equivalent to the bit position.
87#[derive(Default, PartialEq, Eq, Clone, Encode, Decode, Debug, TypeInfo)]
88pub(crate) struct DisputedBitfield(pub(crate) BitVec<u8, bitvec::order::Lsb0>);
89
90impl From<BitVec<u8, bitvec::order::Lsb0>> for DisputedBitfield {
91	fn from(inner: BitVec<u8, bitvec::order::Lsb0>) -> Self {
92		Self(inner)
93	}
94}
95
96#[cfg(test)]
97impl DisputedBitfield {
98	/// Create a new bitfield, where each bit is set to `false`.
99	pub fn zeros(n: usize) -> Self {
100		Self::from(BitVec::<u8, bitvec::order::Lsb0>::repeat(false, n))
101	}
102}
103
104pub use pallet::*;
105
106#[frame_support::pallet]
107pub mod pallet {
108	use super::*;
109
110	#[pallet::pallet]
111	#[pallet::without_storage_info]
112	pub struct Pallet<T>(_);
113
114	#[pallet::config]
115	#[pallet::disable_frame_system_supertrait_check]
116	pub trait Config:
117		inclusion::Config + scheduler::Config + initializer::Config + pallet_babe::Config
118	{
119		/// Weight information for extrinsics in this pallet.
120		type WeightInfo: WeightInfo;
121	}
122
123	#[pallet::error]
124	pub enum Error<T> {
125		/// Inclusion inherent called more than once per block.
126		TooManyInclusionInherents,
127		/// The hash of the submitted parent header doesn't correspond to the saved block hash of
128		/// the parent.
129		InvalidParentHeader,
130		/// Inherent data was filtered during execution. This should have only been done
131		/// during creation.
132		InherentDataFilteredDuringExecution,
133		/// Too many candidates supplied.
134		UnscheduledCandidate,
135	}
136
137	/// Whether the paras inherent was included within this block.
138	///
139	/// The `Option<()>` is effectively a `bool`, but it never hits storage in the `None` variant
140	/// due to the guarantees of FRAME's storage APIs.
141	///
142	/// If this is `None` at the end of the block, we panic and render the block invalid.
143	#[pallet::storage]
144	pub(crate) type Included<T> = StorageValue<_, ()>;
145
146	/// Scraped on chain data for extracting resolved disputes as well as backing votes.
147	#[pallet::storage]
148	pub type OnChainVotes<T: Config> = StorageValue<_, ScrapedOnChainVotes<T::Hash>>;
149
150	/// Update the disputes statements set part of the on-chain votes.
151	pub(crate) fn set_scrapable_on_chain_disputes<T: Config>(
152		session: SessionIndex,
153		checked_disputes: CheckedMultiDisputeStatementSet,
154	) {
155		crate::paras_inherent::OnChainVotes::<T>::mutate(move |value| {
156			let disputes =
157				checked_disputes.into_iter().map(DisputeStatementSet::from).collect::<Vec<_>>();
158			let backing_validators_per_candidate = match value.take() {
159				Some(v) => v.backing_validators_per_candidate,
160				None => Vec::new(),
161			};
162			*value = Some(ScrapedOnChainVotes::<T::Hash> {
163				backing_validators_per_candidate,
164				disputes,
165				session,
166			});
167		})
168	}
169
170	/// Update the backing votes including part of the on-chain votes.
171	pub(crate) fn set_scrapable_on_chain_backings<T: Config>(
172		session: SessionIndex,
173		backing_validators_per_candidate: Vec<(
174			CandidateReceipt<T::Hash>,
175			Vec<(ValidatorIndex, ValidityAttestation)>,
176		)>,
177	) {
178		crate::paras_inherent::OnChainVotes::<T>::mutate(move |value| {
179			let disputes = match value.take() {
180				Some(v) => v.disputes,
181				None => MultiDisputeStatementSet::default(),
182			};
183			*value = Some(ScrapedOnChainVotes::<T::Hash> {
184				backing_validators_per_candidate,
185				disputes,
186				session,
187			});
188		})
189	}
190
191	#[pallet::hooks]
192	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
193		fn on_initialize(_: BlockNumberFor<T>) -> Weight {
194			T::DbWeight::get().reads_writes(1, 1) // in `on_finalize`.
195		}
196
197		fn on_finalize(_: BlockNumberFor<T>) {
198			if Included::<T>::take().is_none() {
199				panic!("ParachainInherent was not executed in this block. This is a bug. Please report this at https://github.com/paritytech/polkadot-sdk/issues.");
200			}
201		}
202	}
203
204	#[pallet::inherent]
205	impl<T: Config> ProvideInherent for Pallet<T> {
206		type Call = Call<T>;
207		type Error = MakeFatalError<()>;
208		const INHERENT_IDENTIFIER: InherentIdentifier = PARACHAINS_INHERENT_IDENTIFIER;
209
210		fn create_inherent(data: &InherentData) -> Option<Self::Call> {
211			let inherent_data = Self::create_inherent_inner(data)?;
212
213			Some(Call::enter { data: inherent_data })
214		}
215
216		fn is_inherent(call: &Self::Call) -> bool {
217			matches!(call, Call::enter { .. })
218		}
219	}
220
221	#[pallet::call]
222	impl<T: Config> Pallet<T> {
223		/// Enter the paras inherent. This will process bitfields and backed candidates.
224		#[pallet::call_index(0)]
225		#[pallet::weight((
226			paras_inherent_total_weight::<T>(
227				data.backed_candidates.as_slice(),
228				&data.bitfields,
229				&data.disputes,
230			),
231			DispatchClass::Mandatory,
232		))]
233		pub fn enter(
234			origin: OriginFor<T>,
235			data: ParachainsInherentData<HeaderFor<T>>,
236		) -> DispatchResultWithPostInfo {
237			ensure_none(origin)?;
238
239			ensure!(!Included::<T>::exists(), Error::<T>::TooManyInclusionInherents);
240			Included::<T>::set(Some(()));
241			let initial_data = data.clone();
242
243			Self::process_inherent_data(data).and_then(|(processed, post_info)| {
244				ensure!(initial_data == processed, Error::<T>::InherentDataFilteredDuringExecution);
245				Ok(post_info)
246			})
247		}
248	}
249}
250
251impl<T: Config> Pallet<T> {
252	/// Create the `ParachainsInherentData` that gets passed to [`Self::enter`] in
253	/// [`Self::create_inherent`]. This code is pulled out of [`Self::create_inherent`] so it can be
254	/// unit tested.
255	fn create_inherent_inner(data: &InherentData) -> Option<ParachainsInherentData<HeaderFor<T>>> {
256		let parachains_inherent_data = match data.get_data(&Self::INHERENT_IDENTIFIER) {
257			Ok(Some(d)) => d,
258			Ok(None) => return None,
259			Err(_) => {
260				log::warn!(target: LOG_TARGET, "ParachainsInherentData failed to decode");
261				return None;
262			},
263		};
264		match Self::process_inherent_data(parachains_inherent_data) {
265			Ok((processed, _)) => Some(processed),
266			Err(err) => {
267				log::warn!(target: LOG_TARGET, "Processing inherent data failed: {:?}", err);
268				None
269			},
270		}
271	}
272
273	/// Process inherent data.
274	///
275	/// The given inherent data is processed and state is altered accordingly. If any data could
276	/// not be applied (inconsistencies, weight limit, ...) it is removed.
277	///
278	/// Returns: Result containing processed inherent data and weight, the processed inherent would
279	/// consume.
280	fn process_inherent_data(
281		data: ParachainsInherentData<HeaderFor<T>>,
282	) -> Result<(ParachainsInherentData<HeaderFor<T>>, PostDispatchInfo), DispatchErrorWithPostInfo>
283	{
284		#[cfg(feature = "runtime-metrics")]
285		sp_io::init_tracing();
286
287		let ParachainsInherentData {
288			mut bitfields,
289			mut backed_candidates,
290			parent_header,
291			mut disputes,
292		} = data;
293
294		log::debug!(
295			target: LOG_TARGET,
296			"[process_inherent_data] bitfields.len(): {}, backed_candidates.len(): {}, disputes.len() {}",
297			bitfields.len(),
298			backed_candidates.len(),
299			disputes.len()
300		);
301
302		let parent_hash = frame_system::Pallet::<T>::parent_hash();
303
304		ensure!(
305			parent_header.hash().as_ref() == parent_hash.as_ref(),
306			Error::<T>::InvalidParentHeader,
307		);
308
309		let now = frame_system::Pallet::<T>::block_number();
310		let config = configuration::ActiveConfig::<T>::get();
311
312		let current_session = shared::CurrentSessionIndex::<T>::get();
313
314		// Before anything else, update the allowed scheduling and relay parents.
315		{
316			let parent_number = now.saturating_sub(One::one());
317			let parent_storage_root = *parent_header.state_root();
318
319			shared::Pallet::<T>::new_block(
320				parent_hash,
321				scheduler::Pallet::<T>::claim_queue(),
322				parent_number,
323				config.scheduler_params.lookahead,
324				parent_storage_root,
325				current_session,
326			);
327		}
328
329		let candidates_weight = backed_candidates_weight::<T>(&backed_candidates);
330		let bitfields_weight = signed_bitfields_weight::<T>(&bitfields);
331		let disputes_weight = multi_dispute_statement_sets_weight::<T>(&disputes);
332
333		// Weight before filtering/sanitization except for enacting the candidates
334		let weight_before_filtering = candidates_weight + bitfields_weight + disputes_weight;
335
336		METRICS.on_before_filter(weight_before_filtering.ref_time());
337		log::debug!(target: LOG_TARGET, "Size before filter: {}, candidates + bitfields: {}, disputes: {}", weight_before_filtering.proof_size(), candidates_weight.proof_size() + bitfields_weight.proof_size(), disputes_weight.proof_size());
338		log::debug!(target: LOG_TARGET, "Time weight before filter: {}, candidates + bitfields: {}, disputes: {}", weight_before_filtering.ref_time(), candidates_weight.ref_time() + bitfields_weight.ref_time(), disputes_weight.ref_time());
339
340		let expected_bits = scheduler::Pallet::<T>::num_availability_cores();
341		let validator_public = shared::ActiveValidatorKeys::<T>::get();
342
343		// We are assuming (incorrectly) to have all the weight (for the mandatory class or even
344		// full block) available to us. This can lead to slightly overweight blocks, which still
345		// works as the dispatch class for `enter` is `Mandatory`. By using the `Mandatory`
346		// dispatch class, the upper layers impose no limit on the weight of this inherent, instead
347		// we limit ourselves and make sure to stay within reasonable bounds. It might make sense
348		// to subtract BlockWeights::base_block to reduce chances of becoming overweight.
349		let max_block_weight = {
350			let dispatch_class = DispatchClass::Mandatory;
351			let max_block_weight_full = <T as frame_system::Config>::BlockWeights::get();
352			log::debug!(target: LOG_TARGET, "Max block weight: {}", max_block_weight_full.max_block);
353			// Get max block weight for the mandatory class if defined, otherwise total max weight
354			// of the block.
355			let max_weight = max_block_weight_full
356				.per_class
357				.get(dispatch_class)
358				.max_total
359				.unwrap_or(max_block_weight_full.max_block);
360			log::debug!(target: LOG_TARGET, "Used max block time weight: {}", max_weight);
361
362			let max_block_size_full = <T as frame_system::Config>::BlockLength::get();
363			let max_block_size = max_block_size_full.max.get(dispatch_class);
364			log::debug!(target: LOG_TARGET, "Used max block size: {}", max_block_size);
365
366			// Adjust proof size to max block size as we are tracking tx size.
367			max_weight.set_proof_size(*max_block_size as u64)
368		};
369		log::debug!(target: LOG_TARGET, "Used max block weight: {}", max_block_weight);
370
371		let entropy = compute_entropy::<T>(parent_hash);
372		let mut rng = rand_chacha::ChaChaRng::from_seed(entropy.into());
373
374		// Filter out duplicates and continue.
375		if let Err(()) = T::DisputesHandler::deduplicate_and_sort_dispute_data(&mut disputes) {
376			log::debug!(target: LOG_TARGET, "Found duplicate statement sets, retaining the first");
377		}
378
379		let post_conclusion_acceptance_period = config.dispute_post_conclusion_acceptance_period;
380
381		let dispute_statement_set_valid = move |set: DisputeStatementSet| {
382			T::DisputesHandler::filter_dispute_data(set, post_conclusion_acceptance_period)
383		};
384
385		// Limit the disputes first, since the following statements depend on the votes included
386		// here.
387		let (checked_disputes_sets, checked_disputes_sets_consumed_weight) =
388			limit_and_sanitize_disputes::<T, _>(
389				disputes,
390				dispute_statement_set_valid,
391				max_block_weight,
392			);
393
394		let mut all_weight_after = {
395			// Assure the maximum block weight is adhered, by limiting bitfields and backed
396			// candidates. Dispute statement sets were already limited before.
397			let non_disputes_weight = apply_weight_limit::<T>(
398				&mut backed_candidates,
399				&mut bitfields,
400				max_block_weight.saturating_sub(checked_disputes_sets_consumed_weight),
401				&mut rng,
402			);
403
404			let all_weight_after =
405				non_disputes_weight.saturating_add(checked_disputes_sets_consumed_weight);
406
407			METRICS.on_after_filter(all_weight_after.ref_time());
408			log::debug!(
409				target: LOG_TARGET,
410				"[process_inherent_data] after filter: bitfields.len(): {}, backed_candidates.len(): {}, checked_disputes_sets.len() {}",
411				bitfields.len(),
412				backed_candidates.len(),
413				checked_disputes_sets.len()
414			);
415			log::debug!(target: LOG_TARGET, "Size after filter: {}, candidates + bitfields: {}, disputes: {}", all_weight_after.proof_size(), non_disputes_weight.proof_size(), checked_disputes_sets_consumed_weight.proof_size());
416			log::debug!(target: LOG_TARGET, "Time weight after filter: {}, candidates + bitfields: {}, disputes: {}", all_weight_after.ref_time(), non_disputes_weight.ref_time(), checked_disputes_sets_consumed_weight.ref_time());
417
418			if all_weight_after.any_gt(max_block_weight) {
419				log::warn!(target: LOG_TARGET, "Post weight limiting weight is still too large, time: {}, size: {}", all_weight_after.ref_time(), all_weight_after.proof_size());
420			}
421			all_weight_after
422		};
423
424		// Note that `process_checked_multi_dispute_data` will iterate and import each
425		// dispute; so the input here must be reasonably bounded,
426		// which is guaranteed by the checks and weight limitation above.
427		// We don't care about fresh or not disputes
428		// this writes them to storage, so let's query it via those means
429		// if this fails for whatever reason, that's ok.
430		if let Err(e) =
431			T::DisputesHandler::process_checked_multi_dispute_data(&checked_disputes_sets)
432		{
433			log::warn!(target: LOG_TARGET, "MultiDisputesData failed to update: {:?}", e);
434		};
435		METRICS.on_disputes_imported(checked_disputes_sets.len() as u64);
436
437		set_scrapable_on_chain_disputes::<T>(current_session, checked_disputes_sets.clone());
438
439		if T::DisputesHandler::is_frozen() {
440			// Relay chain freeze, at this point we will not include any parachain blocks.
441			METRICS.on_relay_chain_freeze();
442
443			let disputes = checked_disputes_sets
444				.into_iter()
445				.map(|checked| checked.into())
446				.collect::<Vec<_>>();
447			let processed = ParachainsInherentData {
448				bitfields: Vec::new(),
449				backed_candidates: Vec::new(),
450				disputes,
451				parent_header,
452			};
453
454			// The relay chain we are currently on is invalid. Proceed no further on parachains.
455			return Ok((processed, Some(checked_disputes_sets_consumed_weight).into()));
456		}
457
458		// Contains the disputes that are concluded in the current session only,
459		// since these are the only ones that are relevant for the occupied cores
460		// and lightens the load on `free_disputed` significantly.
461		// Cores can't be occupied with candidates of the previous sessions, and only
462		// things with new votes can have just concluded. We only need to collect
463		// cores with disputes that conclude just now, because disputes that
464		// concluded longer ago have already had any corresponding cores cleaned up.
465		let current_concluded_invalid_disputes = checked_disputes_sets
466			.iter()
467			.map(AsRef::as_ref)
468			.filter(|dss| dss.session == current_session)
469			.map(|dss| (dss.session, dss.candidate_hash))
470			.filter(|(session, candidate)| {
471				<T>::DisputesHandler::concluded_invalid(*session, *candidate)
472			})
473			.map(|(_session, candidate)| candidate)
474			.collect::<BTreeSet<CandidateHash>>();
475
476		// Get the cores freed as a result of concluded invalid candidates.
477		let (freed_disputed, concluded_invalid_hashes): (Vec<CoreIndex>, BTreeSet<CandidateHash>) =
478			inclusion::Pallet::<T>::free_disputed(&current_concluded_invalid_disputes)
479				.into_iter()
480				.unzip();
481
482		// Create a bit index from the set of core indices where each index corresponds to
483		// a core index that was freed due to a dispute.
484		//
485		// I.e. 010100 would indicate, the candidates on Core 1 and 3 would be disputed.
486		let disputed_bitfield = create_disputed_bitfield(expected_bits, freed_disputed.iter());
487
488		let bitfields = sanitize_bitfields::<T>(
489			bitfields,
490			disputed_bitfield,
491			expected_bits,
492			parent_hash,
493			current_session,
494			&validator_public[..],
495		);
496		METRICS.on_bitfields_processed(bitfields.len() as u64);
497
498		// Process new availability bitfields, yielding any availability cores whose
499		// work has now concluded.
500		let (enact_weight, freed_concluded) =
501			inclusion::Pallet::<T>::update_pending_availability_and_get_freed_cores(
502				&validator_public[..],
503				bitfields.clone(),
504			);
505		all_weight_after.saturating_accrue(enact_weight);
506		log::debug!(
507			target: LOG_TARGET,
508			"Enacting weight: {}, all weight: {}",
509			enact_weight.ref_time(),
510			all_weight_after.ref_time(),
511		);
512
513		// It's possible that that after the enacting the candidates, the total weight
514		// goes over the limit, however, we can't do anything about it at this point.
515		// By using the `Mandatory` weight, we ensure the block is still accepted,
516		// but no other (user) transactions can be included.
517		if all_weight_after.any_gt(max_block_weight) {
518			log::warn!(
519				target: LOG_TARGET,
520				"Overweight para inherent data after enacting the candidates {:?}: {} > {}",
521				parent_hash,
522				all_weight_after,
523				max_block_weight,
524			);
525		}
526
527		// Inform the disputes module of all included candidates.
528		for (_, candidate_hash) in &freed_concluded {
529			T::DisputesHandler::note_included(current_session, *candidate_hash, now);
530		}
531
532		METRICS.on_candidates_included(freed_concluded.len() as u64);
533
534		// Get the timed out candidates
535		let freed_timeout = if scheduler::Pallet::<T>::availability_timeout_check_required() {
536			inclusion::Pallet::<T>::free_timedout()
537		} else {
538			Vec::new()
539		};
540
541		if !freed_timeout.is_empty() {
542			log::debug!(target: LOG_TARGET, "Evicted timed out cores: {:?}", freed_timeout);
543		}
544
545		// Back candidates.
546		let (candidate_receipt_with_backing_validator_indices, backed_candidates_with_core) =
547			Self::back_candidates(concluded_invalid_hashes, backed_candidates)?;
548
549		set_scrapable_on_chain_backings::<T>(
550			current_session,
551			candidate_receipt_with_backing_validator_indices,
552		);
553
554		let disputes = checked_disputes_sets
555			.into_iter()
556			.map(|checked| checked.into())
557			.collect::<Vec<_>>();
558
559		let bitfields = bitfields.into_iter().map(|v| v.into_unchecked()).collect();
560
561		let count = backed_candidates_with_core.len();
562		let processed = ParachainsInherentData {
563			bitfields,
564			backed_candidates: backed_candidates_with_core.into_iter().fold(
565				Vec::with_capacity(count),
566				|mut acc, (_id, candidates)| {
567					acc.extend(candidates.into_iter().map(|(c, _)| c));
568					acc
569				},
570			),
571			disputes,
572			parent_header,
573		};
574		Ok((processed, Some(all_weight_after).into()))
575	}
576
577	fn back_candidates(
578		concluded_invalid_hashes: BTreeSet<CandidateHash>,
579		backed_candidates: Vec<BackedCandidate<T::Hash>>,
580	) -> Result<
581		(
582			Vec<(CandidateReceipt<T::Hash>, Vec<(ValidatorIndex, ValidityAttestation)>)>,
583			BTreeMap<ParaId, Vec<(BackedCandidate<T::Hash>, CoreIndex)>>,
584		),
585		DispatchErrorWithPostInfo,
586	> {
587		let allowed_scheduling_parents = shared::AllowedSchedulingParents::<T>::get();
588
589		let upcoming_new_session = initializer::Pallet::<T>::upcoming_session_change();
590
591		METRICS.on_candidates_processed_total(backed_candidates.len() as u64);
592
593		let occupied_cores: BTreeSet<_> =
594			inclusion::Pallet::<T>::get_occupied_cores().map(|(core, _)| core).collect();
595
596		let mut eligible: BTreeMap<ParaId, BTreeSet<CoreIndex>> = BTreeMap::new();
597
598		let is_blocked = |core_idx| occupied_cores.contains(&core_idx) || upcoming_new_session;
599		let scheduled = scheduler::Pallet::<T>::advance_claim_queue(is_blocked);
600		let total_eligible_cores = scheduled.len();
601
602		for (core_idx, para_id) in scheduled {
603			eligible.entry(para_id).or_default().insert(core_idx);
604		}
605
606		let node_features = configuration::ActiveConfig::<T>::get().node_features;
607		let v3_enabled = FeatureIndex::CandidateReceiptV3.is_set(&node_features);
608
609		let backed_candidates_with_core = sanitize_backed_candidates::<T>(
610			backed_candidates,
611			&allowed_scheduling_parents,
612			concluded_invalid_hashes,
613			eligible,
614			v3_enabled,
615		);
616		let count = count_backed_candidates(&backed_candidates_with_core);
617
618		ensure!(count <= total_eligible_cores, Error::<T>::UnscheduledCandidate);
619
620		METRICS.on_candidates_sanitized(count as u64);
621
622		// Process backed candidates according to scheduled cores.
623		let candidate_receipt_with_backing_validator_indices =
624			inclusion::Pallet::<T>::process_candidates(
625				&allowed_scheduling_parents,
626				&backed_candidates_with_core,
627				scheduler::Pallet::<T>::group_validators,
628			)?;
629
630		Ok((candidate_receipt_with_backing_validator_indices, backed_candidates_with_core))
631	}
632}
633
634/// Derive a bitfield from dispute
635pub(super) fn create_disputed_bitfield<'a, I>(
636	expected_bits: usize,
637	freed_cores: I,
638) -> DisputedBitfield
639where
640	I: 'a + IntoIterator<Item = &'a CoreIndex>,
641{
642	let mut bitvec = BitVec::repeat(false, expected_bits);
643	for core_idx in freed_cores {
644		let core_idx = core_idx.0 as usize;
645		if core_idx < expected_bits {
646			bitvec.set(core_idx, true);
647		}
648	}
649	DisputedBitfield::from(bitvec)
650}
651
652/// Select a random subset, with preference for certain indices.
653///
654/// Adds random items to the set until all candidates
655/// are tried or the remaining weight is depleted.
656///
657/// Returns the weight of all selected items from `selectables`
658/// as well as their indices in ascending order.
659fn random_sel<X, F: Fn(&X) -> Weight>(
660	rng: &mut rand_chacha::ChaChaRng,
661	selectables: &[X],
662	mut preferred_indices: Vec<usize>,
663	weight_fn: F,
664	weight_limit: Weight,
665) -> (Weight, Vec<usize>) {
666	if selectables.is_empty() {
667		return (Weight::zero(), Vec::new());
668	}
669	// all indices that are not part of the preferred set
670	let mut indices = (0..selectables.len())
671		.into_iter()
672		.filter(|idx| !preferred_indices.contains(idx))
673		.collect::<Vec<_>>();
674	let mut picked_indices = Vec::with_capacity(selectables.len().saturating_sub(1));
675
676	let mut weight_acc = Weight::zero();
677
678	preferred_indices.shuffle(rng);
679	for preferred_idx in preferred_indices {
680		// preferred indices originate from outside
681		if let Some(item) = selectables.get(preferred_idx) {
682			let updated = weight_acc.saturating_add(weight_fn(item));
683			if updated.any_gt(weight_limit) {
684				continue;
685			}
686			weight_acc = updated;
687			picked_indices.push(preferred_idx);
688		}
689	}
690
691	indices.shuffle(rng);
692	for idx in indices {
693		let item = &selectables[idx];
694		let updated = weight_acc.saturating_add(weight_fn(item));
695
696		if updated.any_gt(weight_limit) {
697			continue;
698		}
699		weight_acc = updated;
700
701		picked_indices.push(idx);
702	}
703
704	// sorting indices, so the ordering is retained
705	// unstable sorting is fine, since there are no duplicates in indices
706	// and even if there were, they don't have an identity
707	picked_indices.sort_unstable();
708	(weight_acc, picked_indices)
709}
710
711/// Considers an upper threshold that the inherent data must not exceed.
712///
713/// If there is sufficient space, all bitfields and all candidates
714/// will be included.
715///
716/// Otherwise tries to include all disputes, and then tries to fill the remaining space with
717/// bitfields and then candidates.
718///
719/// The selection process is random. For candidates, there is an exception for code upgrades as they
720/// are preferred. And for disputes, local and older disputes are preferred (see
721/// `limit_and_sanitize_disputes`). for backed candidates, since with a increasing number of
722/// parachains their chances of inclusion become slim. All backed candidates  are checked
723/// beforehand in `fn create_inherent_inner` which guarantees sanity.
724///
725/// Assumes disputes are already filtered by the time this is called.
726///
727/// Returns the total weight consumed by `bitfields` and `candidates`.
728pub(crate) fn apply_weight_limit<T: Config + inclusion::Config>(
729	candidates: &mut Vec<BackedCandidate<<T>::Hash>>,
730	bitfields: &mut UncheckedSignedAvailabilityBitfields,
731	max_consumable_weight: Weight,
732	rng: &mut rand_chacha::ChaChaRng,
733) -> Weight {
734	let total_candidates_weight = backed_candidates_weight::<T>(candidates.as_slice());
735
736	let total_bitfields_weight = signed_bitfields_weight::<T>(&bitfields);
737
738	let total = total_bitfields_weight.saturating_add(total_candidates_weight);
739
740	// candidates + bitfields fit into the block
741	if max_consumable_weight.all_gte(total) {
742		return total;
743	}
744
745	// Invariant: block author provides candidate in the order in which they form a chain
746	// wrt elastic scaling. If the invariant is broken, we'd fail later when filtering candidates
747	// which are unchained.
748
749	let mut chained_candidates: Vec<Vec<_>> = Vec::new();
750	let mut current_para_id = None;
751
752	for candidate in core::mem::take(candidates).into_iter() {
753		let candidate_para_id = candidate.descriptor().para_id();
754		if Some(candidate_para_id) == current_para_id {
755			let chain = chained_candidates
756				.last_mut()
757				.expect("if the current_para_id is Some, then vec is not empty; qed");
758			chain.push(candidate);
759		} else {
760			current_para_id = Some(candidate_para_id);
761			chained_candidates.push(vec![candidate]);
762		}
763	}
764
765	// Elastic scaling: we prefer chains that have a code upgrade among the candidates,
766	// as the candidates containing the upgrade tend to be large and hence stand no chance to
767	// be picked late while maintaining the weight bounds.
768	//
769	// Limitations: For simplicity if total weight of a chain of candidates is larger than
770	// the remaining weight, the chain will still not be included while it could still be possible
771	// to include part of that chain.
772	let preferred_chain_indices = chained_candidates
773		.iter()
774		.enumerate()
775		.filter_map(|(idx, candidates)| {
776			// Check if any of the candidate in chain contains a code upgrade.
777			if candidates
778				.iter()
779				.any(|candidate| candidate.candidate().commitments.new_validation_code.is_some())
780			{
781				Some(idx)
782			} else {
783				None
784			}
785		})
786		.collect::<Vec<usize>>();
787
788	// There is weight remaining to be consumed by a subset of chained candidates
789	// which are going to be picked now.
790	if let Some(max_consumable_by_candidates) =
791		max_consumable_weight.checked_sub(&total_bitfields_weight)
792	{
793		let (acc_candidate_weight, chained_indices) =
794			random_sel::<Vec<BackedCandidate<<T as frame_system::Config>::Hash>>, _>(
795				rng,
796				&chained_candidates,
797				preferred_chain_indices,
798				|candidates| backed_candidates_weight::<T>(&candidates),
799				max_consumable_by_candidates,
800			);
801		log::debug!(target: LOG_TARGET, "Indices Candidates: {:?}, size: {}", chained_indices, candidates.len());
802		chained_candidates
803			.indexed_retain(|idx, _backed_candidates| chained_indices.binary_search(&idx).is_ok());
804		// pick all bitfields, and
805		// fill the remaining space with candidates
806		let total_consumed = acc_candidate_weight.saturating_add(total_bitfields_weight);
807
808		*candidates = chained_candidates.into_iter().flatten().collect::<Vec<_>>();
809
810		return total_consumed;
811	}
812
813	candidates.clear();
814
815	// insufficient space for even the bitfields alone, so only try to fit as many of those
816	// into the block and skip the candidates entirely
817	let (total_consumed, indices) = random_sel::<UncheckedSignedAvailabilityBitfield, _>(
818		rng,
819		&bitfields,
820		vec![],
821		|bitfield| signed_bitfield_weight::<T>(&bitfield),
822		max_consumable_weight,
823	);
824	log::debug!(target: LOG_TARGET, "Indices Bitfields: {:?}, size: {}", indices, bitfields.len());
825
826	bitfields.indexed_retain(|idx, _bitfield| indices.binary_search(&idx).is_ok());
827
828	total_consumed
829}
830
831/// Filter bitfields based on freed core indices, validity, and other sanity checks.
832///
833/// Do sanity checks on the bitfields:
834///
835///  1. no more than one bitfield per validator
836///  2. bitfields are ascending by validator index.
837///  3. each bitfield has exactly `expected_bits`
838///  4. signature is valid
839///  5. remove any disputed core indices
840///
841/// If any of those is not passed, the bitfield is dropped.
842pub(crate) fn sanitize_bitfields<T: crate::inclusion::Config>(
843	unchecked_bitfields: UncheckedSignedAvailabilityBitfields,
844	disputed_bitfield: DisputedBitfield,
845	expected_bits: usize,
846	parent_hash: T::Hash,
847	session_index: SessionIndex,
848	validators: &[ValidatorId],
849) -> SignedAvailabilityBitfields {
850	let mut bitfields = Vec::with_capacity(unchecked_bitfields.len());
851
852	let mut last_index: Option<ValidatorIndex> = None;
853
854	if disputed_bitfield.0.len() != expected_bits {
855		// This is a system logic error that should never occur, but we want to handle it gracefully
856		// so we just drop all bitfields
857		log::error!(target: LOG_TARGET, "BUG: disputed_bitfield != expected_bits");
858		return vec![];
859	}
860
861	let all_zeros = BitVec::<u8, bitvec::order::Lsb0>::repeat(false, expected_bits);
862	let signing_context = SigningContext { parent_hash, session_index };
863	for unchecked_bitfield in unchecked_bitfields {
864		// Find and skip invalid bitfields.
865		if unchecked_bitfield.unchecked_payload().0.len() != expected_bits {
866			log::trace!(
867				target: LOG_TARGET,
868				"bad bitfield length: {} != {:?}",
869				unchecked_bitfield.unchecked_payload().0.len(),
870				expected_bits,
871			);
872			continue;
873		}
874
875		if unchecked_bitfield.unchecked_payload().0.clone() & disputed_bitfield.0.clone() !=
876			all_zeros
877		{
878			log::trace!(
879				target: LOG_TARGET,
880				"bitfield contains disputed cores: {:?}",
881				unchecked_bitfield.unchecked_payload().0.clone() & disputed_bitfield.0.clone()
882			);
883			continue;
884		}
885
886		let validator_index = unchecked_bitfield.unchecked_validator_index();
887
888		if !last_index.map_or(true, |last_index: ValidatorIndex| last_index < validator_index) {
889			log::trace!(
890				target: LOG_TARGET,
891				"bitfield validator index is not greater than last: !({:?} < {})",
892				last_index.as_ref().map(|x| x.0),
893				validator_index.0
894			);
895			continue;
896		}
897
898		if unchecked_bitfield.unchecked_validator_index().0 as usize >= validators.len() {
899			log::trace!(
900				target: LOG_TARGET,
901				"bitfield validator index is out of bounds: {} >= {}",
902				validator_index.0,
903				validators.len(),
904			);
905			continue;
906		}
907
908		let validator_public = &validators[validator_index.0 as usize];
909
910		// Validate bitfield signature.
911		if let Ok(signed_bitfield) =
912			unchecked_bitfield.try_into_checked(&signing_context, validator_public)
913		{
914			bitfields.push(signed_bitfield);
915			METRICS.on_valid_bitfield_signature();
916		} else {
917			log::warn!(target: LOG_TARGET, "Invalid bitfield signature");
918			METRICS.on_invalid_bitfield_signature();
919		};
920
921		last_index = Some(validator_index);
922	}
923	bitfields
924}
925
926/// Perform required checks for given candidate receipt.
927///
928/// Returns `true` if the candidate passes all version and signal checks.
929///
930/// Validate descriptor version, relay/scheduling parent, session, and UMP signals.
931///
932/// This is the first check in the sanitization pipeline. It establishes invariants that
933/// downstream checks (notably `verify_backed_candidate`) rely on.
934///
935/// Returns `false` if:
936/// - the descriptor version is unknown
937/// - version consistency check fails (old/new detection rules disagree unexpectedly)
938/// - version 3 descriptors are present but v3 is not enabled
939/// - the relay parent is not in the allowed relay parents for the relevant session:
940/// - the scheduling parent is not in the allowed scheduling parents
941/// - UMP signal parsing fails
942/// - for V2/V3: scheduling_session != current session
943/// - for V2/V3: the core index in descriptor doesn't match the one computed from the commitments,
944///   or the `SelectCore` signal does not refer to a core at the top of claim queue
945fn check_descriptor_version_and_signals<T: crate::inclusion::Config>(
946	candidate: &BackedCandidate<T::Hash>,
947	allowed_scheduling_parents: &AllowedSchedulingParentsTracker<T::Hash, BlockNumberFor<T>>,
948	v3_enabled: bool,
949) -> bool {
950	let current_session_index = shared::CurrentSessionIndex::<T>::get();
951	let descriptor_version = candidate.descriptor().version();
952
953	if descriptor_version == CandidateDescriptorVersion::Unknown {
954		log::debug!(
955			target: LOG_TARGET,
956			"Candidate with unknown descriptor version. Dropping candidate {:?} for paraid {:?}.",
957			candidate.candidate().hash(),
958			candidate.descriptor().para_id()
959		);
960		return false;
961	}
962
963	// Version consistency + V3 gating (shared logic from primitives).
964	if let Err(reason) = candidate.descriptor().check_version_acceptance(v3_enabled) {
965		log::debug!(
966			target: LOG_TARGET,
967			"{}. Dropping candidate {:?} for paraid {:?}.",
968			reason,
969			candidate.candidate().hash(),
970			candidate.descriptor().para_id()
971		);
972		return false;
973	}
974
975	// Check relay_parent exists in allowed relay parents (execution context).
976	// Needed for all versions to access relay chain state.
977	let relay_parent = candidate.descriptor().relay_parent();
978
979	let session_index = candidate.descriptor().session_index().unwrap_or(current_session_index);
980
981	if shared::Pallet::<T>::get_relay_parent_info(session_index, relay_parent).is_none() {
982		log::debug!(
983			target: LOG_TARGET,
984			"Relay parent {:?} for candidate {:?} is not in the allowed relay parents of session {}.",
985			relay_parent,
986			candidate.candidate().hash(),
987			session_index,
988		);
989		return false;
990	};
991
992	// Check scheduling_parent exists in allowed relay parents (scheduling context).
993	// For V1/V2: scheduling_parent() returns relay_parent (duplicate check, but cheap).
994	// For V3: scheduling_parent() returns the actual scheduling_parent field.
995	//
996	// Note: we do not check that scheduling_parents advance between candidates. Backwards
997	// movement of scheduling_parent is primarily a censorship resistance concern, handled
998	// by the collator protocol's active leaf check. The relay chain only requires validity
999	// (i.e., the scheduling_parent is in allowed relay parents).
1000	let scheduling_parent = candidate.descriptor().scheduling_parent();
1001	let Some((sp_info, _)) = allowed_scheduling_parents.acquire_info(scheduling_parent) else {
1002		log::debug!(
1003			target: LOG_TARGET,
1004			"Scheduling parent {:?} for candidate {:?} is not in the allowed scheduling parents.",
1005			scheduling_parent,
1006			candidate.candidate().hash(),
1007		);
1008		return false;
1009	};
1010
1011	// UMP signals check uses scheduling parent's claim queue.
1012	// For V1/V2: scheduling_parent == relay_parent, so uses same claim queue as before.
1013	// For V3: uses the claim queue from the scheduling_parent.
1014	if let Err(err) = candidate.candidate().parse_ump_signals(&sp_info.claim_queue) {
1015		log::debug!(
1016			target: LOG_TARGET,
1017			"UMP signal check failed: {:?}. Dropping candidate {:?} for paraid {:?}.",
1018			err,
1019			candidate.candidate().hash(),
1020			candidate.descriptor().para_id()
1021		);
1022		return false;
1023	}
1024
1025	if descriptor_version == CandidateDescriptorVersion::V1 {
1026		// Nothing more to check for v1 descriptors.
1027		return true;
1028	}
1029
1030	// For V2/V3: Check scheduling session matches current session.
1031	// For V2: scheduling_session() returns session_index (relay parent session).
1032	// For V3: scheduling_session() returns scheduling_session_index.
1033	let Some(scheduling_session) = candidate.descriptor().scheduling_session() else {
1034		log::debug!(
1035			target: LOG_TARGET,
1036			"Invalid V2/V3 candidate receipt {:?} for paraid {:?}, missing scheduling session.",
1037			candidate.candidate().hash(),
1038			candidate.descriptor().para_id(),
1039		);
1040		return false;
1041	};
1042
1043	// Check if scheduling session is equal to current session index.
1044	if scheduling_session != current_session_index {
1045		log::debug!(
1046			target: LOG_TARGET,
1047			"Dropping candidate receipt {:?} for paraid {:?}, invalid scheduling session {}, current session {}",
1048			candidate.candidate().hash(),
1049			candidate.descriptor().para_id(),
1050			scheduling_session,
1051			current_session_index
1052		);
1053		return false;
1054	}
1055
1056	true
1057}
1058
1059/// Performs various filtering on the backed candidates inherent data.
1060/// Must maintain the invariant that the returned candidate collection contains the candidates
1061/// sorted in dependency order for each para. When doing any filtering, we must therefore drop any
1062/// subsequent candidates after the filtered one.
1063///
1064/// Filter out:
1065/// 1. any candidates which don't form a chain with the other candidates of the paraid (even if they
1066///    do form a chain but are not in the right order).
1067/// 2. any candidates that have a concluded invalid dispute or who are descendants of a concluded
1068///    invalid candidate.
1069/// 3. any unscheduled candidates, as well as candidates whose paraid has multiple cores assigned
1070///    but have no core index (either injected or in the v2 descriptor).
1071/// 4. all backing votes from disabled validators
1072/// 5. any candidates that end up with less than `effective_minimum_backing_votes` backing votes
1073///
1074/// Returns the scheduled
1075/// backed candidates which passed filtering, mapped by para id and in the right dependency order.
1076///
1077/// ## Candidate validation pipeline
1078///
1079/// Candidate checks are split across two modules. The full pipeline is:
1080///
1081/// **Phase 1: Sanitization** (`paras_inherent`, this module)
1082/// - `check_descriptor_version_and_signals`: version gating, relay/scheduling parent validity,
1083///   session restrictions, UMP signals, core index from signals (V2/V3)
1084/// - `filter_unchained_candidates`: dependency ordering, relay parent bounds, PVD hash, validation
1085///   code hash, para head match (via `verify_backed_candidate`)
1086/// - `map_candidates_to_cores`: core assignment mapping, core index from descriptor/injection
1087/// - `filter_backed_statements_from_disabled_validators`: disabled validator filtering
1088///
1089/// **Phase 2: Processing** (`inclusion::process_candidates`)
1090/// - `verify_backed_candidate`: relay parent lookup (using session from descriptor), PVD hash,
1091///   validation code hash, para head match
1092/// - Scheduling parent lookup for group assignment
1093/// - Backing vote count and signature verification
1094/// - State updates (pending availability, head data, etc.)
1095///
1096/// Note: `verify_backed_candidate` is called in both phases. In phase 1 it's called by
1097/// `filter_unchained_candidates` to validate chaining. In phase 2 it's called by
1098/// `process_candidates` for final validation. The relay parent session check in
1099/// `verify_backed_candidate` relies on `check_descriptor_version_and_signals` having
1100/// already enforced that V1/V2 relay parents are in the current session.
1101fn sanitize_backed_candidates<T: crate::inclusion::Config>(
1102	backed_candidates: Vec<BackedCandidate<T::Hash>>,
1103	allowed_scheduling_parents: &AllowedSchedulingParentsTracker<T::Hash, BlockNumberFor<T>>,
1104	concluded_invalid_with_descendants: BTreeSet<CandidateHash>,
1105	scheduled: BTreeMap<ParaId, BTreeSet<CoreIndex>>,
1106	v3_enabled: bool,
1107) -> BTreeMap<ParaId, Vec<(BackedCandidate<T::Hash>, CoreIndex)>> {
1108	// Map the candidates to the right paraids, while making sure that the order between candidates
1109	// of the same para is preserved.
1110	let mut candidates_per_para: BTreeMap<ParaId, Vec<_>> = BTreeMap::new();
1111
1112	for candidate in backed_candidates {
1113		if !check_descriptor_version_and_signals::<T>(
1114			&candidate,
1115			allowed_scheduling_parents,
1116			v3_enabled,
1117		) {
1118			continue;
1119		}
1120
1121		candidates_per_para
1122			.entry(candidate.descriptor().para_id())
1123			.or_default()
1124			.push(candidate);
1125	}
1126
1127	// Check that candidates pertaining to the same para form a chain. Drop the ones that
1128	// don't, along with the rest of candidates which follow them in the input vector.
1129	filter_unchained_candidates::<T>(&mut candidates_per_para);
1130
1131	// Remove any candidates that were concluded invalid or who are descendants of concluded invalid
1132	// candidates (along with their descendants).
1133	retain_candidates::<T, _, _>(&mut candidates_per_para, |_, candidate| {
1134		let keep = !concluded_invalid_with_descendants.contains(&candidate.candidate().hash());
1135
1136		if !keep {
1137			log::debug!(
1138				target: LOG_TARGET,
1139				"Found backed candidate {:?} which was concluded invalid or is a descendant of a concluded invalid candidate, for paraid {:?}.",
1140				candidate.candidate().hash(),
1141				candidate.descriptor().para_id()
1142			);
1143		}
1144		keep
1145	});
1146
1147	// Map candidates to scheduled cores. Filter out any unscheduled candidates along with their
1148	// descendants.
1149	let mut backed_candidates_with_core =
1150		map_candidates_to_cores::<T>(&allowed_scheduling_parents, scheduled, candidates_per_para);
1151
1152	// Filter out backing statements from disabled validators. If by that we render a candidate with
1153	// less backing votes than required, filter that candidate also. As all the other filtering
1154	// operations above, we drop the descendants of the dropped candidates also.
1155	filter_backed_statements_from_disabled_validators::<T>(
1156		&mut backed_candidates_with_core,
1157		&allowed_scheduling_parents,
1158	);
1159
1160	backed_candidates_with_core
1161}
1162
1163fn count_backed_candidates<B>(backed_candidates: &BTreeMap<ParaId, Vec<B>>) -> usize {
1164	backed_candidates.values().map(|c| c.len()).sum()
1165}
1166
1167/// Derive entropy from babe provided per block randomness.
1168///
1169/// In the odd case none is available, uses the `parent_hash` and
1170/// a const value, while emitting a warning.
1171fn compute_entropy<T: Config>(parent_hash: T::Hash) -> [u8; 32] {
1172	const CANDIDATE_SEED_SUBJECT: [u8; 32] = *b"candidate-seed-selection-subject";
1173	// NOTE: this is slightly gameable since this randomness was already public
1174	// by the previous block, while for the block author this randomness was
1175	// known 2 epochs ago. it is marginally better than using the parent block
1176	// hash since it's harder to influence the VRF output than the block hash.
1177	let vrf_random = ParentBlockRandomness::<T>::random(&CANDIDATE_SEED_SUBJECT[..]).0;
1178	let mut entropy: [u8; 32] = CANDIDATE_SEED_SUBJECT;
1179	if let Some(vrf_random) = vrf_random {
1180		entropy.as_mut().copy_from_slice(vrf_random.as_ref());
1181	} else {
1182		// in case there is no VRF randomness present, we utilize the relay parent
1183		// as seed, it's better than a static value.
1184		log::warn!(target: LOG_TARGET, "ParentBlockRandomness did not provide entropy");
1185		entropy.as_mut().copy_from_slice(parent_hash.as_ref());
1186	}
1187	entropy
1188}
1189
1190/// Limit disputes in place.
1191///
1192/// Assumes ordering of disputes, retains sorting of the statement.
1193///
1194/// Prime source of overload safety for dispute votes:
1195/// 1. Check accumulated weight does not exceed the maximum block weight.
1196/// 2. If exceeded:
1197///   1. Check validity of all dispute statements sequentially
1198/// 2. If not exceeded:
1199///   1. If weight is exceeded by locals, pick the older ones (lower indices) until the weight limit
1200///      is reached.
1201///
1202/// Returns the consumed weight amount, that is guaranteed to be less than the provided
1203/// `max_consumable_weight`.
1204fn limit_and_sanitize_disputes<
1205	T: Config,
1206	CheckValidityFn: FnMut(DisputeStatementSet) -> Option<CheckedDisputeStatementSet>,
1207>(
1208	disputes: MultiDisputeStatementSet,
1209	mut dispute_statement_set_valid: CheckValidityFn,
1210	max_consumable_weight: Weight,
1211) -> (Vec<CheckedDisputeStatementSet>, Weight) {
1212	// The total weight if all disputes would be included
1213	let disputes_weight = multi_dispute_statement_sets_weight::<T>(&disputes);
1214
1215	if disputes_weight.any_gt(max_consumable_weight) {
1216		log::debug!(target: LOG_TARGET, "Above max consumable weight: {}/{}", disputes_weight, max_consumable_weight);
1217		let mut checked_acc = Vec::<CheckedDisputeStatementSet>::with_capacity(disputes.len());
1218
1219		// Accumulated weight of all disputes picked, that passed the checks.
1220		let mut weight_acc = Weight::zero();
1221
1222		// Select disputes in-order until the remaining weight is attained
1223		disputes.into_iter().for_each(|dss| {
1224			let dispute_weight = dispute_statement_set_weight::<T, &DisputeStatementSet>(&dss);
1225			let updated = weight_acc.saturating_add(dispute_weight);
1226			if max_consumable_weight.all_gte(updated) {
1227				// Always apply the weight. Invalid data cost processing time too:
1228				weight_acc = updated;
1229				if let Some(checked) = dispute_statement_set_valid(dss) {
1230					checked_acc.push(checked);
1231				}
1232			}
1233		});
1234
1235		(checked_acc, weight_acc)
1236	} else {
1237		// Go through all of them, and just apply the filter, they would all fit
1238		let checked = disputes
1239			.into_iter()
1240			.filter_map(|dss| dispute_statement_set_valid(dss))
1241			.collect::<Vec<CheckedDisputeStatementSet>>();
1242		// some might have been filtered out, so re-calc the weight
1243		let checked_disputes_weight = checked_multi_dispute_statement_sets_weight::<T>(&checked);
1244		(checked, checked_disputes_weight)
1245	}
1246}
1247
1248// Helper function for filtering candidates which don't pass the given predicate. When/if the first
1249// candidate which failed the predicate is found, all the other candidates that follow are dropped.
1250fn retain_candidates<
1251	T: inclusion::Config + paras::Config + inclusion::Config,
1252	F: FnMut(ParaId, &mut C) -> bool,
1253	C,
1254>(
1255	candidates_per_para: &mut BTreeMap<ParaId, Vec<C>>,
1256	mut pred: F,
1257) {
1258	for (para_id, candidates) in candidates_per_para.iter_mut() {
1259		let mut latest_valid_idx = None;
1260
1261		for (idx, candidate) in candidates.iter_mut().enumerate() {
1262			if pred(*para_id, candidate) {
1263				// Found a valid candidate.
1264				latest_valid_idx = Some(idx);
1265			} else {
1266				break;
1267			}
1268		}
1269
1270		if let Some(latest_valid_idx) = latest_valid_idx {
1271			candidates.truncate(latest_valid_idx + 1);
1272		} else {
1273			candidates.clear();
1274		}
1275	}
1276
1277	candidates_per_para.retain(|_, c| !c.is_empty());
1278}
1279
1280// Filters statements from disabled validators in `BackedCandidate` and does a few more sanity
1281// checks.
1282fn filter_backed_statements_from_disabled_validators<
1283	T: shared::Config + scheduler::Config + inclusion::Config,
1284>(
1285	backed_candidates_with_core: &mut BTreeMap<
1286		ParaId,
1287		Vec<(BackedCandidate<<T as frame_system::Config>::Hash>, CoreIndex)>,
1288	>,
1289	allowed_scheduling_parents: &AllowedSchedulingParentsTracker<T::Hash, BlockNumberFor<T>>,
1290) {
1291	let disabled_validators =
1292		BTreeSet::<_>::from_iter(shared::Pallet::<T>::disabled_validators().into_iter());
1293
1294	if disabled_validators.is_empty() {
1295		// No disabled validators - nothing to do
1296		return;
1297	}
1298
1299	let minimum_backing_votes = configuration::ActiveConfig::<T>::get().minimum_backing_votes;
1300
1301	// Process all backed candidates. `validator_indices` in `BackedCandidates` are indices within
1302	// the validator group assigned to the parachain. To obtain this group we need:
1303	// 1. Core index assigned to the parachain which has produced the candidate
1304	// 2. The scheduling parent block number of the candidate
1305	retain_candidates::<T, _, _>(backed_candidates_with_core, |para_id, (bc, core_idx)| {
1306		// `CoreIndex` not used, we just need a copy to write it back later.
1307		let (validator_indices, maybe_injected_core_index) = bc.validator_indices_and_core_index();
1308		let mut validator_indices = BitVec::<_>::from(validator_indices);
1309
1310		// Get scheduling parent block number of the candidate. We need this to get the group index
1311		// assigned to this core at this block number
1312		let scheduling_parent_block_number = match allowed_scheduling_parents
1313			.acquire_info(bc.descriptor().scheduling_parent())
1314		{
1315			Some((_, block_num)) => block_num,
1316			None => {
1317				log::debug!(
1318					target: LOG_TARGET,
1319					"Scheduling parent {:?} for candidate is not in the allowed scheduling parents. Dropping the candidate.",
1320					bc.descriptor().scheduling_parent()
1321				);
1322				return false;
1323			},
1324		};
1325
1326		// Get the group index for the core
1327		let group_idx = match scheduler::Pallet::<T>::group_assigned_to_core(
1328			*core_idx,
1329			scheduling_parent_block_number + One::one(),
1330		) {
1331			Some(group_idx) => group_idx,
1332			None => {
1333				log::debug!(target: LOG_TARGET, "Can't get the group index for core idx {:?}. Dropping the candidate.", core_idx);
1334				return false;
1335			},
1336		};
1337
1338		// And finally get the validator group for this group index
1339		let validator_group = match scheduler::Pallet::<T>::group_validators(group_idx) {
1340			Some(validator_group) => validator_group,
1341			None => {
1342				log::debug!(target: LOG_TARGET, "Can't get the validators from group {:?}. Dropping the candidate.", group_idx);
1343				return false;
1344			},
1345		};
1346
1347		// Bitmask with the disabled indices within the validator group
1348		let disabled_indices = BitVec::<u8, bitvec::order::Lsb0>::from_iter(
1349			validator_group.iter().map(|idx| disabled_validators.contains(idx)),
1350		);
1351		// The indices of statements from disabled validators in `BackedCandidate`. We have to drop
1352		// these.
1353		let indices_to_drop = disabled_indices.clone() & &validator_indices;
1354
1355		// Remove the corresponding votes from `validity_votes`
1356		for idx in indices_to_drop.iter_ones().rev() {
1357			// Map the index in `indices_to_drop` (which is an index into the validator group)
1358			// to the index in the validity votes vector, which might have less number of votes,
1359			// than validators assigned to the group.
1360			//
1361			// For each index `idx` in `indices_to_drop`, the corresponding index in the
1362			// validity votes vector is the number of `1` bits in `validator_indices` before `idx`.
1363			let mapped_idx = validator_indices[..idx].count_ones();
1364			bc.validity_votes_mut().remove(mapped_idx);
1365		}
1366
1367		// Apply the bitmask to drop the disabled validator from `validator_indices`
1368		validator_indices &= !disabled_indices;
1369		// Update the backed candidate
1370		bc.set_validator_indices_and_core_index(validator_indices, maybe_injected_core_index);
1371
1372		// By filtering votes we might render the candidate invalid and cause a failure in
1373		// [`process_candidates`]. To avoid this we have to perform a sanity check here. If there
1374		// are not enough backing votes after filtering we will remove the whole candidate.
1375		if bc.validity_votes().len() <
1376			effective_minimum_backing_votes(validator_group.len(), minimum_backing_votes)
1377		{
1378			log::debug!(
1379				target: LOG_TARGET,
1380				"Dropping candidate {:?} of paraid {:?} because it was left with too few backing votes after votes from disabled validators were filtered.",
1381				bc.candidate().hash(),
1382				para_id
1383			);
1384
1385			return false;
1386		}
1387
1388		true
1389	});
1390}
1391
1392// Check that candidates pertaining to the same para form a chain. Drop the ones that
1393// don't, along with the rest of candidates which follow them in the input vector.
1394// In the process, duplicated candidates will also be dropped (even if they form a valid cycle;
1395// cycles are not allowed if they entail backing duplicated candidates).
1396fn filter_unchained_candidates<T: inclusion::Config + paras::Config + inclusion::Config>(
1397	candidates: &mut BTreeMap<ParaId, Vec<BackedCandidate<T::Hash>>>,
1398) {
1399	let mut para_latest_context: BTreeMap<ParaId, (HeadData, BlockNumberFor<T>)> = BTreeMap::new();
1400	for para_id in candidates.keys() {
1401		let Some(latest_head_data) = inclusion::Pallet::<T>::para_latest_head_data(&para_id) else {
1402			defensive!("Latest included head data for paraid {:?} is None", para_id);
1403			continue;
1404		};
1405		let Some(latest_relay_parent) = inclusion::Pallet::<T>::para_most_recent_context(&para_id)
1406		else {
1407			defensive!("Latest relay parent for paraid {:?} is None", para_id);
1408			continue;
1409		};
1410		para_latest_context.insert(*para_id, (latest_head_data, latest_relay_parent));
1411	}
1412
1413	let mut para_visited_candidates: BTreeMap<ParaId, BTreeSet<CandidateHash>> = BTreeMap::new();
1414
1415	retain_candidates::<T, _, _>(candidates, |para_id, candidate| {
1416		let Some((latest_head_data, latest_relay_parent)) = para_latest_context.get(&para_id)
1417		else {
1418			return false;
1419		};
1420		let candidate_hash = candidate.candidate().hash();
1421
1422		let visited_candidates =
1423			para_visited_candidates.entry(para_id).or_insert_with(|| BTreeSet::new());
1424		if visited_candidates.contains(&candidate_hash) {
1425			log::debug!(
1426				target: LOG_TARGET,
1427				"Found duplicate candidates for paraid {:?}. Dropping the candidates with hash {:?}",
1428				para_id,
1429				candidate_hash
1430			);
1431
1432			// If we got a duplicate candidate, stop.
1433			return false;
1434		} else {
1435			visited_candidates.insert(candidate_hash);
1436		}
1437
1438		let check_ctx = CandidateCheckContext::<T>::new(Some(*latest_relay_parent));
1439
1440		match check_ctx.verify_backed_candidate(candidate.candidate(), latest_head_data.clone()) {
1441			Ok(relay_parent_block_number) => {
1442				para_latest_context.insert(
1443					para_id,
1444					(
1445						candidate.candidate().commitments.head_data.clone(),
1446						relay_parent_block_number,
1447					),
1448				);
1449				true
1450			},
1451			Err(err) => {
1452				log::debug!(
1453					target: LOG_TARGET,
1454					"Backed candidate verification for candidate {:?} of paraid {:?} failed with {:?}",
1455					candidate_hash,
1456					para_id,
1457					err
1458				);
1459				false
1460			},
1461		}
1462	});
1463}
1464
1465/// Map candidates to scheduled cores.
1466/// If the para only has one scheduled core and one candidate supplied, map the candidate to the
1467/// single core. If the para has multiple cores scheduled, only map the candidates with core index.
1468/// Filter out the rest.
1469/// Also returns whether or not we dropped any candidates.
1470/// When dropping a candidate of a para, we must drop all subsequent candidates from that para
1471/// (because they form a chain).
1472fn map_candidates_to_cores<T: configuration::Config + scheduler::Config + inclusion::Config>(
1473	allowed_scheduling_parents: &AllowedSchedulingParentsTracker<T::Hash, BlockNumberFor<T>>,
1474	mut scheduled: BTreeMap<ParaId, BTreeSet<CoreIndex>>,
1475	candidates: BTreeMap<ParaId, Vec<BackedCandidate<T::Hash>>>,
1476) -> BTreeMap<ParaId, Vec<(BackedCandidate<T::Hash>, CoreIndex)>> {
1477	let mut backed_candidates_with_core = BTreeMap::new();
1478
1479	for (para_id, backed_candidates) in candidates.into_iter() {
1480		if backed_candidates.len() == 0 {
1481			defensive!("Backed candidates for paraid {} is empty.", para_id);
1482			continue;
1483		}
1484
1485		let Some(scheduled_cores) = scheduled.get_mut(&para_id) else {
1486			log::debug!(
1487				target: LOG_TARGET,
1488				"Paraid: {:?} has no entry in scheduled cores but {} candidates were supplied.",
1489				para_id,
1490				backed_candidates.len()
1491			);
1492			continue;
1493		};
1494
1495		// ParaIds without scheduled cores are silently filtered out.
1496		if scheduled_cores.len() == 0 {
1497			log::debug!(
1498				target: LOG_TARGET,
1499				"Paraid: {:?} has no scheduled cores but {} candidates were supplied.",
1500				para_id,
1501				backed_candidates.len()
1502			);
1503			continue;
1504		}
1505
1506		// We must preserve the dependency order given in the input.
1507		let mut temp_backed_candidates = Vec::with_capacity(scheduled_cores.len());
1508
1509		for candidate in backed_candidates {
1510			if scheduled_cores.len() == 0 {
1511				// We've got candidates for all of this para's assigned cores. Move on to
1512				// the next para.
1513				log::debug!(
1514					target: LOG_TARGET,
1515					"Found enough candidates for paraid: {:?}.",
1516					candidate.descriptor().para_id()
1517				);
1518				break;
1519			}
1520
1521			if let Some(core_index) = get_core_index::<T>(allowed_scheduling_parents, &candidate) {
1522				if scheduled_cores.remove(&core_index) {
1523					temp_backed_candidates.push((candidate, core_index));
1524				} else {
1525					// if we got a candidate for a core index which is not scheduled, stop
1526					// the work for this para. the already processed candidate chain in
1527					// temp_backed_candidates is still fine though.
1528					log::debug!(
1529						target: LOG_TARGET,
1530						"Found a backed candidate {:?} with core index {}, which is not scheduled for paraid {:?}.",
1531						candidate.candidate().hash(),
1532						core_index.0,
1533						candidate.descriptor().para_id()
1534					);
1535
1536					break;
1537				}
1538			} else {
1539				// if we got a candidate which does not contain its core index, stop the
1540				// work for this para. the already processed candidate chain in
1541				// temp_backed_candidates is still fine though.
1542
1543				log::debug!(
1544					target: LOG_TARGET,
1545					"Found a backed candidate {:?} without core index information for para {:?}, dropping",
1546					candidate.candidate().hash(),
1547					candidate.descriptor().para_id()
1548				);
1549
1550				break;
1551			}
1552		}
1553
1554		if !temp_backed_candidates.is_empty() {
1555			backed_candidates_with_core
1556				.entry(para_id)
1557				.or_insert_with(|| vec![])
1558				.extend(temp_backed_candidates);
1559		}
1560	}
1561
1562	backed_candidates_with_core
1563}
1564
1565// Must be called only for candidates that have been sanitized already.
1566fn get_core_index<T: configuration::Config + scheduler::Config + inclusion::Config>(
1567	allowed_scheduling_parents: &AllowedSchedulingParentsTracker<T::Hash, BlockNumberFor<T>>,
1568	candidate: &BackedCandidate<T::Hash>,
1569) -> Option<CoreIndex> {
1570	candidate
1571		.candidate()
1572		.descriptor
1573		.core_index()
1574		.or_else(|| get_injected_core_index::<T>(allowed_scheduling_parents, &candidate))
1575}
1576
1577fn get_injected_core_index<T: configuration::Config + scheduler::Config + inclusion::Config>(
1578	allowed_scheduling_parents: &AllowedSchedulingParentsTracker<T::Hash, BlockNumberFor<T>>,
1579	candidate: &BackedCandidate<T::Hash>,
1580) -> Option<CoreIndex> {
1581	// After stripping the 8 bit extensions, the `validator_indices` field length is expected
1582	// to be equal to backing group size. If these don't match, the `CoreIndex` is badly encoded,
1583	// or not supported.
1584	let (validator_indices, Some(core_idx)) = candidate.validator_indices_and_core_index() else {
1585		return None;
1586	};
1587
1588	let scheduling_parent_block_number =
1589		match allowed_scheduling_parents.acquire_info(candidate.descriptor().scheduling_parent()) {
1590			Some((_, block_num)) => block_num,
1591			None => {
1592				log::debug!(
1593					target: LOG_TARGET,
1594					"Scheduling parent {:?} for candidate {:?} is not in the allowed scheduling parents.",
1595					candidate.descriptor().scheduling_parent(),
1596					candidate.candidate().hash(),
1597				);
1598				return None;
1599			},
1600		};
1601
1602	// Get the backing group of the candidate backed at `core_idx`.
1603	let group_idx = match scheduler::Pallet::<T>::group_assigned_to_core(
1604		core_idx,
1605		scheduling_parent_block_number + One::one(),
1606	) {
1607		Some(group_idx) => group_idx,
1608		None => {
1609			log::debug!(
1610				target: LOG_TARGET,
1611				"Can't get the group index for core idx {:?}.",
1612				core_idx,
1613			);
1614			return None;
1615		},
1616	};
1617
1618	let group_validators = match scheduler::Pallet::<T>::group_validators(group_idx) {
1619		Some(validators) => validators,
1620		None => return None,
1621	};
1622
1623	if group_validators.len() == validator_indices.len() {
1624		Some(core_idx)
1625	} else {
1626		log::debug!(
1627			target: LOG_TARGET,
1628			"Expected validator_indices count different than the real one: {}, {} for candidate {:?}",
1629			group_validators.len(),
1630			validator_indices.len(),
1631			candidate.candidate().hash()
1632		);
1633
1634		None
1635	}
1636}