referrerpolicy=no-referrer-when-downgrade

polkadot_collator_protocol/
lib.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//! The Collator Protocol allows collators and validators talk to each other.
18//! This subsystem implements both sides of the collator protocol.
19//!
20//! # Public API discipline
21//!
22//! The deterministic test-sim framework
23//! (`polkadot-collator-protocol-test-sim`) is a **separate crate** and uses only this crate's
24//! public API. This is intentional. **Do not** add `pub` items to expose internals just to
25//! make a scenario compile.
26//!
27//! When a scenario needs a private type the answer is one of:
28//!
29//! - Add a variant to the contract enums in `test-sim/src/contract/{effect,query}.rs`. The scenario
30//!   then asserts/queries the new observable rather than reaching into state.
31//! - Add a public builder method on the test-sim builders (`World`, `Peer`, `Candidate`).
32//! - Refactor the scenario to drive the property via a stimulus that makes it observable.
33//!
34//! Why: tests that depend on internals calcify implementation choices, mask production bugs
35//! when private state diverges from observable behaviour, and break on refactors that did not
36//! actually change behaviour. The whole point of the framework is that tests survive internal
37//! refactors. Convenience exports erode that asset; the doc rule + reviewer attention on new
38//! `pub` items at the lib.rs boundary is the enforcement mechanism. PR reviewers: any new
39//! `pub` item in this file gets a justification or a "no".
40
41#![deny(missing_docs)]
42#![deny(unused_crate_dependencies)]
43#![deny(clippy::disallowed_methods)]
44// Tests still call `Instant::now`, `Delay::new`, etc directly. The deterministic-clock plumbing
45// is enforced for production code; legacy tests retain their original behavior.
46#![cfg_attr(test, allow(clippy::disallowed_methods))]
47#![recursion_limit = "256"]
48
49// Acknowledge dev-deps used only by integration tests under `tests/`. The
50// `unused_crate_dependencies` lint checks each Cargo target against the whole dependency set,
51// so the lib target flags deps that only the `tests/` target uses.
52// See https://github.com/rust-lang/rust/issues/95513.
53#[cfg(test)]
54use {
55	polkadot_collator_protocol_test_sim_macros as _, polkadot_node_core_backing as _,
56	polkadot_node_core_prospective_parachains as _, polkadot_overseer as _,
57	polkadot_subsystem_test_sim as _, sp_consensus_slots as _,
58};
59
60use std::{
61	collections::{BTreeMap, HashMap, HashSet, VecDeque},
62	sync::Arc,
63	time::{Duration, Instant},
64};
65
66use futures::{
67	channel::oneshot,
68	stream::{FusedStream, StreamExt},
69	FutureExt, TryFutureExt,
70};
71
72use polkadot_node_subsystem::CollatorProtocolSenderTrait;
73use polkadot_node_subsystem_util::{
74	database::Database,
75	reputation::ReputationAggregator,
76	request_claim_queue,
77	runtime::{self, fetch_scheduling_lookahead, recv_runtime},
78};
79use sp_consensus_babe::digests::CompatibleDigestItem;
80use sp_core::H256;
81use sp_keystore::KeystorePtr;
82
83use polkadot_node_network_protocol::{
84	request_response::{v2 as protocol_v2, v3 as protocol_v3, IncomingRequestReceiver},
85	PeerId, UnifiedReputationChange as Rep,
86};
87use polkadot_node_subsystem::{
88	errors::SubsystemError, messages::ChainApiMessage, overseer, DummySubsystem, SpawnedSubsystem,
89};
90use polkadot_primitives::{
91	CollatorPair, CoreIndex, Hash, Id as ParaId, SessionIndex, RELAY_CHAIN_SLOT_DURATION_MILLIS,
92};
93use sp_consensus_slots::SlotDuration;
94pub use validator_side_experimental::ReputationConfig;
95
96use polkadot_node_clock::Clock;
97
98mod collator_side;
99mod validator_side;
100mod validator_side_experimental;
101
102// TODO: move into validator_side_experimental once `validator_side` is retired
103mod validator_side_metrics;
104
105const LOG_TARGET: &'static str = "parachain::collator-protocol";
106const LOG_TARGET_STATS: &'static str = "parachain::collator-protocol::stats";
107
108/// A collator eviction policy - how fast to evict collators which are inactive.
109#[derive(Debug, Clone, Copy)]
110pub struct CollatorEvictionPolicy {
111	/// How fast to evict collators who are inactive.
112	pub inactive_collator: Duration,
113	/// How fast to evict peers which don't declare their para.
114	pub undeclared: Duration,
115}
116
117impl Default for CollatorEvictionPolicy {
118	fn default() -> Self {
119		CollatorEvictionPolicy {
120			inactive_collator: Duration::from_secs(24),
121			undeclared: Duration::from_secs(1),
122		}
123	}
124}
125
126/// What side of the collator protocol is being engaged
127pub enum ProtocolSide {
128	/// Validators operate on the relay chain.
129	Validator {
130		/// The keystore holding validator keys.
131		keystore: KeystorePtr,
132		/// An eviction policy for inactive peers or validators.
133		eviction_policy: CollatorEvictionPolicy,
134		/// Prometheus metrics for validators.
135		metrics: validator_side::Metrics,
136		/// List of invulnerable collators which is handled with a priority.
137		invulnerables: HashSet<PeerId>,
138		/// Override for `HOLD_OFF_DURATION` constant .
139		collator_protocol_hold_off: Option<Duration>,
140		/// Clock used for all time reads. Production passes [`polkadot_node_clock::SystemClock`];
141		/// tests inject a mock.
142		clock: Arc<dyn Clock>,
143	},
144	/// Experimental variant of the validator side. Do not use in production.
145	ValidatorExperimental {
146		/// The keystore holding validator keys.
147		keystore: KeystorePtr,
148		/// Prometheus metrics for validators.
149		metrics: validator_side_experimental::Metrics,
150		/// Database used for reputation house keeping.
151		db: Arc<dyn Database>,
152		/// Reputation configuration (column number).
153		reputation_config: validator_side_experimental::ReputationConfig,
154		/// Clock used for all time reads. Production passes [`polkadot_node_clock::SystemClock`];
155		/// tests inject a mock.
156		clock: Arc<dyn Clock>,
157	},
158	/// Collators operate on a parachain.
159	Collator {
160		/// Local peer id.
161		peer_id: PeerId,
162		/// Parachain collator pair.
163		collator_pair: CollatorPair,
164		/// Receiver for v2 collation fetching requests.
165		request_receiver_v2: IncomingRequestReceiver<protocol_v2::CollationFetchingRequest>,
166		/// Receiver for v3 collation fetching requests.
167		request_receiver_v3: IncomingRequestReceiver<protocol_v3::CollationFetchingRequest>,
168		/// Metrics.
169		metrics: collator_side::Metrics,
170		/// Clock used for all time reads. Production passes [`polkadot_node_clock::SystemClock`];
171		/// tests inject a mock.
172		clock: Arc<dyn Clock>,
173	},
174	/// No protocol side, just disable it.
175	None,
176}
177
178/// The collator protocol subsystem.
179pub struct CollatorProtocolSubsystem {
180	protocol_side: ProtocolSide,
181}
182
183#[overseer::contextbounds(CollatorProtocol, prefix = self::overseer)]
184impl CollatorProtocolSubsystem {
185	/// Start the collator protocol.
186	pub fn new(protocol_side: ProtocolSide) -> Self {
187		Self { protocol_side }
188	}
189}
190
191#[overseer::subsystem(CollatorProtocol, error=SubsystemError, prefix=self::overseer)]
192impl<Context> CollatorProtocolSubsystem {
193	fn start(self, ctx: Context) -> SpawnedSubsystem {
194		let future = match self.protocol_side {
195			ProtocolSide::Validator {
196				keystore,
197				eviction_policy,
198				metrics,
199				invulnerables,
200				collator_protocol_hold_off,
201				clock,
202			} => {
203				gum::trace!(
204					target: LOG_TARGET,
205					?invulnerables,
206					?collator_protocol_hold_off,
207					"AH collator protocol params",
208				);
209				validator_side::run(
210					ctx,
211					keystore,
212					eviction_policy,
213					metrics,
214					invulnerables,
215					collator_protocol_hold_off,
216					clock,
217				)
218				.map_err(|e| SubsystemError::with_origin("collator-protocol", e))
219				.boxed()
220			},
221			ProtocolSide::ValidatorExperimental {
222				keystore,
223				metrics,
224				db,
225				reputation_config,
226				clock,
227			} => validator_side_experimental::run(
228				ctx,
229				keystore,
230				metrics,
231				db,
232				reputation_config,
233				clock,
234			)
235			.map_err(|e| SubsystemError::with_origin("collator-protocol", e))
236			.boxed(),
237			ProtocolSide::Collator {
238				peer_id,
239				collator_pair,
240				request_receiver_v2,
241				request_receiver_v3,
242				metrics,
243				clock,
244			} => collator_side::run(
245				ctx,
246				peer_id,
247				collator_pair,
248				request_receiver_v2,
249				request_receiver_v3,
250				metrics,
251				clock,
252			)
253			.map_err(|e| SubsystemError::with_origin("collator-protocol", e))
254			.boxed(),
255			ProtocolSide::None => return DummySubsystem.start(ctx),
256		};
257
258		SpawnedSubsystem { name: "collator-protocol-subsystem", future }
259	}
260}
261
262/// Modify the reputation of a peer based on its behavior.
263async fn modify_reputation(
264	reputation: &mut ReputationAggregator,
265	sender: &mut impl overseer::CollatorProtocolSenderTrait,
266	peer: PeerId,
267	rep: Rep,
268) {
269	gum::trace!(
270		target: LOG_TARGET,
271		rep = ?rep,
272		peer_id = %peer,
273		"reputation change for peer",
274	);
275
276	reputation.modify(sender, peer, rep).await;
277}
278
279/// Wait until tick and return the timestamp for the following one.
280async fn wait_until_next_tick(clock: &dyn Clock, last_poll: Instant, period: Duration) -> Instant {
281	let now = clock.now();
282	let next_poll = last_poll + period;
283
284	if next_poll > now {
285		clock.delay(next_poll - now).await
286	}
287
288	clock.now()
289}
290
291/// Returns an infinite stream that yields with an interval of `period`.
292fn tick_stream(clock: Arc<dyn Clock>, period: Duration) -> impl FusedStream<Item = ()> {
293	futures::stream::unfold(clock.now(), move |next_check| {
294		let clock = clock.clone();
295		async move { Some(((), wait_until_next_tick(&*clock, next_check, period).await)) }
296	})
297	.fuse()
298}
299
300/// Scheduling info tracked per active leaf, used for V3 scheduling parent validation.
301/// Stores the leaf's BABE slot and parent hash so the validator can determine whether
302/// the scheduling parent corresponds to the last finished relay chain slot.
303struct LeafSchedulingInfo {
304	/// The parent hash of the leaf block.
305	parent_hash: Hash,
306	/// The BABE slot of the leaf block.
307	slot: sp_consensus_slots::Slot,
308}
309
310pub(crate) async fn extract_leaf_scheduling_info<Sender: CollatorProtocolSenderTrait>(
311	sender: &mut Sender,
312	leaf: H256,
313) -> Option<LeafSchedulingInfo> {
314	// Fetch leaf header to extract BABE slot for V3 scheduling parent validation.
315	// Without this info, V3 advertisements referencing this leaf will be rejected.
316	let (tx, rx) = oneshot::channel();
317	sender.send_message(ChainApiMessage::BlockHeader(leaf, tx)).await;
318	let header = rx.await.ok().and_then(|r| r.ok().flatten());
319	header.and_then(|header| {
320		let slot = header.digest.logs().iter().find_map(|log| log.as_babe_pre_digest())?.slot();
321		Some(LeafSchedulingInfo { parent_hash: header.parent_hash, slot })
322	})
323}
324
325pub(crate) fn is_scheduling_parent_valid(
326	clock: &dyn Clock,
327	scheduling_parent: &Hash,
328	leaf_scheduling_info: &HashMap<Hash, LeafSchedulingInfo>,
329) -> bool {
330	let slot_duration = SlotDuration::from_millis(RELAY_CHAIN_SLOT_DURATION_MILLIS);
331	let current_slot = sp_consensus_slots::Slot::from_timestamp(
332		sp_timestamp::Timestamp::new(clock.duration_since_epoch().as_millis() as u64),
333		slot_duration,
334	);
335	if let Some(info) = leaf_scheduling_info.get(scheduling_parent) {
336		// scheduling_parent is a leaf. This is allowed only when the leaf's slot is
337		// the previous slot. The slot comes from an untrusted header, so use checked
338		// addition to avoid overflowing at `u64::MAX`.
339		info.slot.checked_add(1).is_some_and(|next_slot| *current_slot == next_slot)
340	} else {
341		// scheduling_parent is not a leaf. This is allowed only if the sp is the parent of
342		// any leaf whose slot is still in progress.
343		leaf_scheduling_info
344			.iter()
345			.any(|(_, info)| *current_slot == *info.slot && *scheduling_parent == info.parent_hash)
346	}
347}
348
349/// The per-core claim queues for one active leaf, together with the runtime scheduling lookahead
350/// that bounds them.
351///
352/// Experimental (`validator_side_experimental`) goes through the [`Self::slots`] / [`Self::window`]
353/// helpers, which own the lookahead arithmetic. Legacy (`validator_side`) has its own
354/// bitfield-based allocation and reads the fields directly — a properly factored legacy would go
355/// through the helpers too, but legacy is on its way out so we don't invest in that.
356pub(crate) struct LeafClaimQueues {
357	claim_queues: BTreeMap<CoreIndex, VecDeque<ParaId>>,
358	scheduling_lookahead: usize,
359}
360
361impl LeafClaimQueues {
362	/// Fetch the per-core claim queues and the scheduling lookahead for `leaf` from the runtime.
363	pub(crate) async fn fetch<Sender: CollatorProtocolSenderTrait>(
364		leaf: Hash,
365		session_index: SessionIndex,
366		sender: &mut Sender,
367	) -> std::result::Result<Self, runtime::Error> {
368		let scheduling_lookahead =
369			fetch_scheduling_lookahead(leaf, session_index, sender).await? as usize;
370		let claim_queues = recv_runtime(request_claim_queue(leaf, sender).await).await?;
371		Ok(Self { claim_queues, scheduling_lookahead })
372	}
373
374	/// The core's claim queue padded to the scheduling lookahead: slot `i` is `Some(para)` where
375	/// scheduled, `None` for positions within the lookahead the runtime left unscheduled. Length
376	/// is always the lookahead. `None` if the core has no claim queue at this leaf.
377	pub(crate) fn slots(&self, core: CoreIndex) -> Option<Vec<Option<ParaId>>> {
378		let cq = self.claim_queues.get(&core)?;
379		Some(
380			cq.iter()
381				.copied()
382				.map(Some)
383				.chain(std::iter::repeat(None))
384				.take(self.scheduling_lookahead)
385				.collect(),
386		)
387	}
388
389	/// Claim-queue positions on `core` reachable from a scheduling parent at `depth` from this
390	/// leaf (leaf = depth 0). A depth-`d` SP can host advertisements landing at leaf-CQ positions
391	/// `i` with `i + d < lookahead`, so the window is `cq[0 .. lookahead - d]` capped to the
392	/// scheduled entries.
393	pub(crate) fn window(&self, core: CoreIndex, depth: usize) -> Vec<ParaId> {
394		let Some(cq) = self.claim_queues.get(&core) else { return Vec::new() };
395		let valid_len = self.scheduling_lookahead.saturating_sub(depth).min(cq.len());
396		cq.iter().take(valid_len).copied().collect()
397	}
398}
399
400#[cfg(test)]
401mod tests {
402	use super::*;
403	use polkadot_node_clock::MockClock;
404	use sp_consensus_slots::Slot;
405
406	/// Creates a mock clock positioned at the given relay-chain slot.
407	fn clock_at_slot(slot: u64) -> MockClock {
408		let clock = MockClock::default();
409		clock.advance(Duration::from_millis(slot * RELAY_CHAIN_SLOT_DURATION_MILLIS));
410		clock
411	}
412
413	fn leaf_info(parent_hash: Hash, slot: u64) -> LeafSchedulingInfo {
414		LeafSchedulingInfo { parent_hash, slot: Slot::from(slot) }
415	}
416
417	#[test]
418	fn leaf_at_previous_slot_is_valid() {
419		let leaf = Hash::repeat_byte(0xAB);
420		let info = HashMap::from([(leaf, leaf_info(Hash::repeat_byte(0x42), 4))]);
421
422		assert!(is_scheduling_parent_valid(&clock_at_slot(5), &leaf, &info));
423	}
424
425	#[test]
426	fn leaf_at_current_slot_is_invalid() {
427		let leaf = Hash::repeat_byte(0xAB);
428		let info = HashMap::from([(leaf, leaf_info(Hash::repeat_byte(0x42), 5))]);
429
430		assert!(!is_scheduling_parent_valid(&clock_at_slot(5), &leaf, &info));
431	}
432
433	#[test]
434	fn parent_of_leaf_in_current_slot_is_valid() {
435		let leaf = Hash::repeat_byte(0xAB);
436		let parent = Hash::repeat_byte(0x42);
437		let info = HashMap::from([(leaf, leaf_info(parent, 5))]);
438
439		assert!(is_scheduling_parent_valid(&clock_at_slot(5), &parent, &info));
440		// The parent is no longer valid once the leaf's slot ends.
441		assert!(!is_scheduling_parent_valid(&clock_at_slot(6), &parent, &info));
442	}
443
444	// Verify that a leaf slot at `u64::MAX` is safely rejected without overflowing.
445	#[test]
446	fn max_leaf_slot_is_rejected_without_overflowing() {
447		let leaf = Hash::repeat_byte(0xAB);
448		let info = HashMap::from([(leaf, leaf_info(Hash::repeat_byte(0x42), u64::MAX))]);
449
450		assert!(!is_scheduling_parent_valid(&clock_at_slot(0), &leaf, &info));
451	}
452}