referrerpolicy=no-referrer-when-downgrade

cumulus_aura_authorizer_utils/
config.rs

1// This file is part of Cumulus.
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
18use alloc::vec::Vec;
19use codec::{Decode, Encode};
20use core::num::NonZero;
21use jam_types::{ServiceId, Slot, WorkItem};
22use polkadot_parachain_primitives::primitives::Id as ParaId;
23use primitive_types::H256;
24
25/// Invalid AURA configuration or work items that do not satisfy it.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum ConfigError {
28	/// A work item does not target the configured Parachain Service.
29	InvalidWorkItemService,
30	/// Number of work items does not match the number of configured para IDs.
31	InvalidWorkItemCount,
32	/// A candidate cannot be decoded or does not match its assignment.
33	Candidate(CandidateError),
34}
35
36/// Invalid candidate payload or parachain identity.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum CandidateError {
39	/// The payload does not start with a decodable para ID.
40	Undecodable,
41	/// The candidate's para ID does not match its assignment.
42	InvalidParaId,
43}
44
45/// The AURA authorizer config embedded in every work package.
46///
47/// Describes the collator set authorized to author work items, and the AURA slot-to-collator
48/// mapping used to check which collator is expected to author a given work package.
49///
50/// Encoding changes must stay compatible with Cumulus authorship.
51#[derive(Debug, Encode, Decode)]
52pub struct AuthConfig {
53	/// Authoritative `ParaId` for each work item, in item order.
54	pub para_ids: Vec<ParaId>,
55
56	/// The JAM service that every work item must target.
57	///
58	/// Prevents para-specific coretime being spent on other services.
59	pub parachain_service: ServiceId,
60
61	/// Root of a binary Merkle tree of the collator set.
62	pub collator_set_root: H256,
63
64	/// Number of collators in the set.
65	pub collator_set_size: NonZero<u32>,
66
67	/// Slot duration as a multiple of the JAM timeslot (6 s).
68	pub slot_duration: NonZero<u32>,
69}
70
71impl AuthConfig {
72	/// Check the count, service, and leading candidate para ID of every work item.
73	pub fn check_work_items(&self, items: &[WorkItem]) -> Result<(), ConfigError> {
74		if items.len() != self.para_ids.len() {
75			return Err(ConfigError::InvalidWorkItemCount);
76		}
77
78		if items.iter().any(|item| item.service != self.parachain_service) {
79			return Err(ConfigError::InvalidWorkItemService);
80		}
81
82		for (item, expected_para_id) in items.iter().zip(&self.para_ids) {
83			let para_id = ParaId::decode(&mut &item.payload.0[..])
84				.map_err(|_| ConfigError::Candidate(CandidateError::Undecodable))?;
85			if para_id != *expected_para_id {
86				return Err(ConfigError::Candidate(CandidateError::InvalidParaId));
87			}
88		}
89
90		Ok(())
91	}
92
93	/// The round-robin collator index expected for `slot`.
94	///
95	/// Computed as `(slot / slot_duration) mod collator_set_size`.
96	pub fn expected_collator_index(&self, slot: Slot) -> u32 {
97		// unchecked math is safe since both are NonZero types, QED
98		(slot / self.slot_duration) % self.collator_set_size
99	}
100}
101
102#[cfg(test)]
103mod tests {
104	use super::*;
105	use crate::ParachainCandidate;
106	use alloc::vec;
107	use polkadot_parachain_primitives::primitives::ValidationCodeHash;
108
109	#[test]
110	fn work_item_constraints_works() {
111		let config = AuthConfig {
112			para_ids: vec![ParaId::new(0)],
113			parachain_service: 1,
114			collator_set_root: H256::zero(),
115			collator_set_size: NonZero::new(1).expect("nonzero test size"),
116			slot_duration: NonZero::new(1).expect("nonzero test duration"),
117		};
118		let items = [WorkItem {
119			service: config.parachain_service,
120			code_hash: Default::default(),
121			refine_gas_limit: 1,
122			accumulate_gas_limit: 1,
123			export_count: 0,
124			payload: ParachainCandidate {
125				para_id: ParaId::new(0),
126				validation_code: ValidationCodeHash::from([0; 32]),
127			}
128			.encode()
129			.into(),
130			import_segments: Default::default(),
131			extrinsics: Default::default(),
132		}];
133
134		// A candidate matching its assignment and service is accepted.
135		assert_eq!(config.check_work_items(&items), Ok(()));
136
137		// Missing and surplus assignments fail.
138		{
139			let mut config = AuthConfig { para_ids: vec![], ..config };
140			for para_ids in [vec![], vec![ParaId::new(0), ParaId::new(1)]] {
141				config.para_ids = para_ids;
142				assert_eq!(config.check_work_items(&items), Err(ConfigError::InvalidWorkItemCount));
143			}
144		}
145
146		// A candidate addressed to another service is rejected.
147		{
148			let mut items = items.clone();
149			items[0].service += 1;
150			assert_eq!(config.check_work_items(&items), Err(ConfigError::InvalidWorkItemService));
151		}
152
153		// A valid candidate cannot claim a different parachain.
154		{
155			let mut items = items.clone();
156			items[0].payload = ParachainCandidate {
157				para_id: ParaId::new(1),
158				validation_code: ValidationCodeHash::from([0; 32]),
159			}
160			.encode()
161			.into();
162			assert_eq!(
163				config.check_work_items(&items),
164				Err(ConfigError::Candidate(CandidateError::InvalidParaId))
165			);
166		}
167
168		// A payload shorter than a para ID cannot be decoded.
169		for payload in [vec![], vec![0; 3]] {
170			let mut items = items.clone();
171			items[0].payload = payload.into();
172			assert_eq!(
173				config.check_work_items(&items),
174				Err(ConfigError::Candidate(CandidateError::Undecodable))
175			);
176		}
177
178		// Only the leading para ID is decoded, so trailing candidate bytes are ignored.
179		{
180			let mut items = items.clone();
181			items[0].payload.0.push(0);
182			assert_eq!(config.check_work_items(&items), Ok(()));
183		}
184
185		// Each item must match its own assignment, not merely any authorized para.
186		{
187			let config = AuthConfig { para_ids: vec![ParaId::new(0), ParaId::new(1)], ..config };
188			let mut items = [items[0].clone(), items[0].clone()];
189			let mut candidate = ParachainCandidate {
190				para_id: ParaId::new(1),
191				validation_code: ValidationCodeHash::from([1; 32]),
192			};
193			items[1].payload = candidate.encode().into();
194			assert_eq!(config.check_work_items(&items), Ok(()));
195
196			candidate.para_id = ParaId::new(0);
197			items[1].payload = candidate.encode().into();
198			assert_eq!(
199				config.check_work_items(&items),
200				Err(ConfigError::Candidate(CandidateError::InvalidParaId))
201			);
202		}
203
204		// Item-count errors take precedence over an invalid service.
205		{
206			let config = AuthConfig { para_ids: vec![], ..config };
207			let mut items = items.clone();
208			items[0].service += 1;
209			assert_eq!(config.check_work_items(&items), Err(ConfigError::InvalidWorkItemCount));
210		}
211	}
212
213	/// `check_work_items` decodes only the leading `ParaId` (a `u32`), so `ParachainCandidate`
214	/// must always start with its SCALE-encoded `ParaId`.
215	#[test]
216	fn candidate_prefix_is_para_id_works() {
217		for raw_id in [0u32, 1, 1000, 2000, u32::MAX] {
218			let para_id = ParaId::new(raw_id);
219			let candidate = ParachainCandidate {
220				para_id,
221				validation_code: ValidationCodeHash::from([0xab; 32]),
222			};
223			let encoded = candidate.encode();
224
225			assert_eq!(&encoded[..4], &raw_id.encode()[..]);
226			assert_eq!(u32::decode(&mut &encoded[..]), Ok(raw_id));
227			assert_eq!(ParaId::decode(&mut &encoded[..]), Ok(para_id));
228		}
229	}
230
231	#[test]
232	fn expected_collator_index_works() {
233		for (size, duration, slot, expected) in [
234			// good cases
235			(1, 1, Slot::MAX, 0),
236			(3, Slot::MAX, Slot::MAX - 1, 0),
237			(3, Slot::MAX, Slot::MAX, 1),
238			(u32::MAX, 1, Slot::MAX - 1, u32::MAX - 1),
239			(u32::MAX, 1, Slot::MAX, 0),
240		] {
241			let config = AuthConfig {
242				para_ids: Vec::new(),
243				parachain_service: 1,
244				collator_set_root: H256::zero(),
245				collator_set_size: NonZero::new(size).expect("nonzero test size"),
246				slot_duration: NonZero::new(duration).expect("nonzero test duration"),
247			};
248
249			assert_eq!(
250				config.expected_collator_index(slot),
251				expected,
252				"set size {size}, slot duration {duration}, slot {slot}"
253			);
254		}
255	}
256}