referrerpolicy=no-referrer-when-downgrade

cumulus_primitives_core/
scheduling.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// This file is part of Cumulus.
3// SPDX-License-Identifier: Apache-2.0
4
5//! V3 scheduling types for low-latency parachain block production.
6//!
7//! V3 candidates separate the relay parent (execution context) from the scheduling parent (a recent
8//! relay tip used for core assignment), so blocks can build on older relay parents while still
9//! being scheduled off recent relay state.
10//!
11//! # Resubmission
12//!
13//! If a candidate isn't backed in time, another collator can resubmit it with a fresh
14//! `scheduling_parent` — same `relay_parent`, no re-execution — by providing a
15//! `signed_scheduling_info` proving it is the eligible author for the slot at
16//! `internal_scheduling_parent`.
17
18use alloc::vec::Vec;
19use codec::{Decode, Encode};
20use polkadot_primitives::{
21	ApprovedPeerId, ClaimQueueOffset, CoreSelector, Header as RelayChainHeader, Slot, UMPSignal,
22	UMP_SEPARATOR,
23};
24use sp_runtime::traits::{BlakeTwo256, Hash as HashT};
25
26/// Payload a collator signs to resubmit a candidate.
27///
28/// Binds the core selection and credited peer to an internal scheduling parent, preventing replay
29/// across scheduling contexts.
30#[derive(Clone, Encode, Decode, Debug, PartialEq, Eq)]
31pub struct SchedulingInfoPayload {
32	/// Which core to use (indexes into the parachain's assigned cores).
33	pub core_selector: CoreSelector,
34	/// The claim queue offset.
35	pub claim_queue_offset: u8,
36	/// Peer ID credited for successful collation delivery.
37	pub peer_id: ApprovedPeerId,
38	/// The internal scheduling parent whose slot decides the eligible author that must sign this
39	/// payload.
40	pub internal_scheduling_parent: polkadot_primitives::Hash,
41}
42
43/// Signed scheduling info for candidate resubmission: a [`SchedulingInfoPayload`] plus the
44/// collator's signature over it, proving eligibility for the slot at `internal_scheduling_parent`.
45///
46/// `claim_queue_offset` comes from the runtime's `relay_parent_offset`, not this struct, so the
47/// collator cannot override it.
48#[derive(Clone, Encode, Decode, Debug, PartialEq, Eq)]
49pub struct SignedSchedulingInfo {
50	/// The scheduling information.
51	pub payload: SchedulingInfoPayload,
52	/// The eligible collator's signature over the SCALE-encoded [`SchedulingInfoPayload`].
53	///
54	/// A fixed 64-byte blob, decodable as either sr25519 or ed25519 (both are 64 bytes).
55	pub signature: [u8; 64],
56}
57
58impl SchedulingInfoPayload {
59	/// Create a new scheduling info payload.
60	pub fn new(
61		core_selector: CoreSelector,
62		claim_queue_offset: u8,
63		peer_id: ApprovedPeerId,
64		internal_scheduling_parent: polkadot_primitives::Hash,
65	) -> Self {
66		Self { core_selector, claim_queue_offset, peer_id, internal_scheduling_parent }
67	}
68}
69
70/// The scheduling-signal tail (`SelectCore`/`ApprovedPeer`) a candidate emits after the first
71/// `UMP_SEPARATOR`.
72///
73/// Single source of truth shared by the collator and the PVF (`validate_block`) so their tails
74/// can't drift. The relay decoder (`CandidateCommitments::ump_signals`) rejects a repeated variant
75/// or more than `MAX_UMP_SIGNALS` signals, and parses only the run after the first
76/// `UMP_SEPARATOR`.
77#[derive(Debug, Default, PartialEq, Eq)]
78pub struct SchedulingSignals {
79	select_core: Option<(CoreSelector, ClaimQueueOffset)>,
80	approved_peer: Option<ApprovedPeerId>,
81}
82
83impl SchedulingSignals {
84	/// Parse the encoded `UMPSignal`s a PoV's blocks emitted after the in-block `UMP_SEPARATOR`.
85	///
86	/// Panics on a repeated variant even when the values match: the relay decoder counts
87	/// occurrences, not distinct values, so a duplicate is a bug regardless.
88	pub fn from_block_signals(raw: &[Vec<u8>]) -> Self {
89		let mut signals = Self::default();
90		for bytes in raw {
91			// Exhaustive on purpose (no `_`): a new `UMPSignal` variant must fail to compile
92			// here, forcing a deliberate decision rather than being silently dropped.
93			match UMPSignal::decode(&mut &bytes[..]).expect("Failed to decode `UMPSignal`") {
94				UMPSignal::SelectCore(selector, offset) => {
95					if signals.select_core.replace((selector, offset)).is_some() {
96						panic!("Parachain emitted more than one `SelectCore` UMP signal");
97					}
98				},
99				UMPSignal::ApprovedPeer(peer_id) => {
100					if signals.approved_peer.replace(peer_id).is_some() {
101						panic!("Parachain emitted more than one `ApprovedPeer` UMP signal");
102					}
103				},
104				UMPSignal::Provides(_) | UMPSignal::Requires(_) => panic!(
105					"Parachain emitted a speculative-messaging UMP signal, which `validate_block` does not yet forward"
106				),
107			}
108		}
109		signals
110	}
111
112	/// Build the tail from a verified `SignedSchedulingInfo`, replacing the block's own signals
113	/// wholesale. Assumes every `UMPSignal` is a scheduling signal; guarded by
114	/// `every_ump_signal_is_classified`.
115	pub fn from_scheduling_info(signed_info: &SignedSchedulingInfo) -> Self {
116		let payload = &signed_info.payload;
117		Self {
118			select_core: Some((
119				payload.core_selector,
120				ClaimQueueOffset(payload.claim_queue_offset),
121			)),
122			approved_peer: Some(payload.peer_id.clone()),
123		}
124	}
125
126	fn is_empty(&self) -> bool {
127		self.select_core.is_none() && self.approved_peer.is_none()
128	}
129
130	/// The encoded UMP messages for this tail: empty when there are no signals, otherwise
131	/// `[UMP_SEPARATOR, SelectCore?, ApprovedPeer?]`. Order is `SelectCore` then `ApprovedPeer`,
132	/// matching `pallet_parachain_system::send_ump_signals`. Nothing — not even the separator — is
133	/// emitted when empty, since the relay decoder keys off the first `UMP_SEPARATOR`.
134	pub fn into_ump_messages(self) -> Vec<Vec<u8>> {
135		if self.is_empty() {
136			return Vec::new();
137		}
138		let mut messages = Vec::with_capacity(3);
139		messages.push(UMP_SEPARATOR);
140		if let Some((selector, offset)) = self.select_core {
141			messages.push(UMPSignal::SelectCore(selector, offset).encode());
142		}
143		if let Some(peer_id) = self.approved_peer {
144			messages.push(UMPSignal::ApprovedPeer(peer_id).encode());
145		}
146		messages
147	}
148}
149
150/// V3 scheduling proof included in the PoV.
151///
152/// Proves ancestry from `scheduling_parent` back to the internal scheduling parent; the PVF
153/// validates it against the `relay_parent`/`scheduling_parent` in the candidate descriptor.
154#[derive(Clone, Encode, Decode, Debug, PartialEq, Eq)]
155pub struct SchedulingProof {
156	/// Relay chain headers chaining `scheduling_parent` backward: each header's `parent_hash` is
157	/// the next header's hash. The first header hashes to the candidate's `scheduling_parent`, the
158	/// last header's `parent_hash` is the internal scheduling parent. Length is the runtime's
159	/// `RelayParentOffset`.
160	pub header_chain: Vec<RelayChainHeader>,
161	/// The header at `internal_scheduling_parent`; its hash must equal the internal scheduling
162	/// parent derived from `header_chain` (the last header's `parent_hash`, or `scheduling_parent`
163	/// if the chain is empty).
164	pub internal_scheduling_parent_header: RelayChainHeader,
165	/// Optional signed core-selection override:
166	///
167	/// - `None`, `relay_parent == internal_scheduling_parent`: initial submission; core selection
168	///   comes from the block's UMP signals.
169	/// - `Some`, `relay_parent == internal_scheduling_parent`: initial submission with an explicit
170	///   (optional) core selection.
171	/// - `Some`, `relay_parent != internal_scheduling_parent`: resubmission (required); the
172	///   signature overrides the block's UMP signals and is verified against the eligible author
173	///   for the slot at `internal_scheduling_parent`.
174	pub signed_scheduling_info: Option<SignedSchedulingInfo>,
175}
176
177impl SchedulingProof {
178	/// Create a new scheduling proof.
179	pub fn new(
180		header_chain: Vec<RelayChainHeader>,
181		internal_scheduling_parent_header: RelayChainHeader,
182		signed_scheduling_info: Option<SignedSchedulingInfo>,
183	) -> Self {
184		Self { header_chain, internal_scheduling_parent_header, signed_scheduling_info }
185	}
186
187	/// The scheduling parent hash: the first/newest header in `header_chain`, or
188	/// `internal_scheduling_parent_header.hash()` when the chain is empty (they coincide at
189	/// `relay_parent_offset = 0`).
190	pub fn scheduling_parent(&self) -> polkadot_primitives::Hash {
191		self.header_chain
192			.first()
193			.map(BlakeTwo256::hash_of)
194			.unwrap_or_else(|| self.internal_scheduling_parent_header.hash())
195	}
196}
197
198/// Verifier for V3 scheduling: reports whether V3 is enabled and verifies a candidate's
199/// [`SignedSchedulingInfo`].
200pub trait VerifySchedulingSignature {
201	/// Whether V3 scheduling validation is enabled.
202	const V3_SCHEDULING_ENABLED: bool;
203
204	/// Verify `signed_info` against the author eligible at `relay_slot` (the internal scheduling
205	/// parent's slot).
206	fn verify(signed_info: &SignedSchedulingInfo, relay_slot: Slot) -> bool;
207}
208
209/// Default no-op wiring: V3 disabled, scheduling info accepted unconditionally. A real verifier
210/// should also turn V3 on.
211impl VerifySchedulingSignature for () {
212	const V3_SCHEDULING_ENABLED: bool = false;
213
214	fn verify(_signed_info: &SignedSchedulingInfo, _relay_slot: Slot) -> bool {
215		true
216	}
217}
218
219#[cfg(test)]
220mod tests {
221	use super::{SchedulingInfoPayload, SchedulingSignals, SignedSchedulingInfo};
222	use alloc::vec;
223	use codec::Encode;
224	use polkadot_primitives::{
225		ApprovedPeerId, ClaimQueueOffset, CoreSelector, UMPSignal, UMP_SEPARATOR,
226	};
227
228	fn peer(byte: u8) -> ApprovedPeerId {
229		ApprovedPeerId::try_from(vec![byte; 4]).expect("4 bytes fits the bound; qed")
230	}
231
232	fn signed_with(
233		core_selector: CoreSelector,
234		claim_queue_offset: u8,
235		peer_id: ApprovedPeerId,
236	) -> SignedSchedulingInfo {
237		SignedSchedulingInfo {
238			payload: SchedulingInfoPayload::new(
239				core_selector,
240				claim_queue_offset,
241				peer_id,
242				Default::default(),
243			),
244			signature: [0u8; 64],
245		}
246	}
247
248	#[test]
249	fn from_block_signals_roundtrips_select_core_and_approved_peer() {
250		// Both signals present: parsed, then emitted as [SEPARATOR, SelectCore, ApprovedPeer] in
251		// that exact order.
252		let raw = vec![
253			UMPSignal::SelectCore(CoreSelector(7), ClaimQueueOffset(1)).encode(),
254			UMPSignal::ApprovedPeer(peer(0xAA)).encode(),
255		];
256		assert_eq!(
257			SchedulingSignals::from_block_signals(&raw).into_ump_messages(),
258			vec![
259				UMP_SEPARATOR,
260				UMPSignal::SelectCore(CoreSelector(7), ClaimQueueOffset(1)).encode(),
261				UMPSignal::ApprovedPeer(peer(0xAA)).encode(),
262			]
263		);
264	}
265
266	#[test]
267	fn from_block_signals_select_core_only() {
268		// Block emitted only a `SelectCore`: no `ApprovedPeer`, one signal emitted.
269		let raw = vec![UMPSignal::SelectCore(CoreSelector(3), ClaimQueueOffset(0)).encode()];
270		assert_eq!(
271			SchedulingSignals::from_block_signals(&raw).into_ump_messages(),
272			vec![
273				UMP_SEPARATOR,
274				UMPSignal::SelectCore(CoreSelector(3), ClaimQueueOffset(0)).encode()
275			]
276		);
277	}
278
279	#[test]
280	#[should_panic(expected = "more than one `SelectCore`")]
281	fn from_block_signals_panics_on_duplicate_select_core_same_value() {
282		// Two identical `SelectCore` signals: still an error. The relay decoder counts
283		// occurrences, not distinct values, so matching duplicates would be rejected too.
284		let raw = vec![
285			UMPSignal::SelectCore(CoreSelector(1), ClaimQueueOffset(0)).encode(),
286			UMPSignal::SelectCore(CoreSelector(1), ClaimQueueOffset(0)).encode(),
287		];
288		let _ = SchedulingSignals::from_block_signals(&raw);
289	}
290
291	#[test]
292	#[should_panic(expected = "more than one `SelectCore`")]
293	fn from_block_signals_panics_on_duplicate_select_core_different_value() {
294		let raw = vec![
295			UMPSignal::SelectCore(CoreSelector(1), ClaimQueueOffset(0)).encode(),
296			UMPSignal::SelectCore(CoreSelector(2), ClaimQueueOffset(0)).encode(),
297		];
298		let _ = SchedulingSignals::from_block_signals(&raw);
299	}
300
301	#[test]
302	#[should_panic(expected = "more than one `ApprovedPeer`")]
303	fn from_block_signals_panics_on_duplicate_approved_peer() {
304		let raw = vec![
305			UMPSignal::ApprovedPeer(peer(0xAA)).encode(),
306			UMPSignal::ApprovedPeer(peer(0xBB)).encode(),
307		];
308		let _ = SchedulingSignals::from_block_signals(&raw);
309	}
310
311	#[test]
312	fn from_block_signals_empty_emits_nothing() {
313		// No signals in, nothing out — not even a separator.
314		assert!(SchedulingSignals::from_block_signals(&[]).into_ump_messages().is_empty());
315	}
316
317	#[test]
318	fn from_scheduling_info_sources_all_fields() {
319		// All three values — `core_selector`, `claim_queue_offset`, `peer_id` — are signed by the
320		// resubmitting collator, so the override sources every field from the signed payload.
321		// Distinct values ensure no field is sourced from the wrong place.
322		let signed = signed_with(CoreSelector(7), 3, peer(0xAA));
323		assert_eq!(
324			SchedulingSignals::from_scheduling_info(&signed).into_ump_messages(),
325			vec![
326				UMP_SEPARATOR,
327				UMPSignal::SelectCore(CoreSelector(7), ClaimQueueOffset(3)).encode(),
328				UMPSignal::ApprovedPeer(peer(0xAA)).encode(),
329			]
330		);
331	}
332
333	#[test]
334	fn from_scheduling_info_emits_peer_verbatim_even_if_empty() {
335		// The payload `peer_id` is a plain (non-`Option`) type → always emitted. An empty peer is
336		// emitted verbatim as `ApprovedPeer([])`, NOT omitted and NOT replaced by the block's peer.
337		let signed = signed_with(CoreSelector(5), 1, ApprovedPeerId::default());
338		assert_eq!(
339			SchedulingSignals::from_scheduling_info(&signed).into_ump_messages(),
340			vec![
341				UMP_SEPARATOR,
342				UMPSignal::SelectCore(CoreSelector(5), ClaimQueueOffset(1)).encode(),
343				UMPSignal::ApprovedPeer(ApprovedPeerId::default()).encode(),
344			]
345		);
346	}
347
348	#[test]
349	fn override_matches_block_signals_when_values_agree() {
350		// Given the same core info and peer id, the override emits the block's own tail byte for
351		// byte. Resubmissions rely on this: the collator rebuilds the commitments from the signed
352		// payload, and the PVF's override must land on identical bytes to pass the commitments
353		// check at backing.
354		let selector = CoreSelector(7);
355		let offset = ClaimQueueOffset(3);
356		let peer_id = peer(0xAA);
357
358		let from_block = SchedulingSignals::from_block_signals(&[
359			UMPSignal::SelectCore(selector, offset).encode(),
360			UMPSignal::ApprovedPeer(peer_id.clone()).encode(),
361		])
362		.into_ump_messages();
363
364		let from_signed =
365			SchedulingSignals::from_scheduling_info(&signed_with(selector, offset.0, peer_id))
366				.into_ump_messages();
367
368		assert_eq!(from_block, from_signed);
369	}
370
371	#[test]
372	fn from_scheduling_info_emits_even_when_block_emitted_nothing() {
373		// The override is authoritative and independent of what the block emitted: a resubmission
374		// always produces its tail.
375		let signed = signed_with(CoreSelector(0), 0, peer(0xCC));
376		assert!(!SchedulingSignals::from_scheduling_info(&signed).into_ump_messages().is_empty());
377	}
378
379	/// Stops compiling when a `UMPSignal` variant is added. Then decide whether it must survive
380	/// [`SchedulingSignals::from_scheduling_info`], which keeps only scheduling signals.
381	#[test]
382	fn every_ump_signal_is_classified() {
383		fn classify(signal: UMPSignal) {
384			match signal {
385				UMPSignal::SelectCore(..) | UMPSignal::ApprovedPeer(..) => {},
386				UMPSignal::Provides(..) | UMPSignal::Requires(..) => {},
387			}
388		}
389		let _ = classify;
390	}
391}