1#![deny(missing_docs)]
42#![deny(unused_crate_dependencies)]
43#![deny(clippy::disallowed_methods)]
44#![cfg_attr(test, allow(clippy::disallowed_methods))]
47#![recursion_limit = "256"]
48
49#[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
102mod validator_side_metrics;
104
105const LOG_TARGET: &'static str = "parachain::collator-protocol";
106const LOG_TARGET_STATS: &'static str = "parachain::collator-protocol::stats";
107
108#[derive(Debug, Clone, Copy)]
110pub struct CollatorEvictionPolicy {
111 pub inactive_collator: Duration,
113 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
126pub enum ProtocolSide {
128 Validator {
130 keystore: KeystorePtr,
132 eviction_policy: CollatorEvictionPolicy,
134 metrics: validator_side::Metrics,
136 invulnerables: HashSet<PeerId>,
138 collator_protocol_hold_off: Option<Duration>,
140 clock: Arc<dyn Clock>,
143 },
144 ValidatorExperimental {
146 keystore: KeystorePtr,
148 metrics: validator_side_experimental::Metrics,
150 db: Arc<dyn Database>,
152 reputation_config: validator_side_experimental::ReputationConfig,
154 clock: Arc<dyn Clock>,
157 },
158 Collator {
160 peer_id: PeerId,
162 collator_pair: CollatorPair,
164 request_receiver_v2: IncomingRequestReceiver<protocol_v2::CollationFetchingRequest>,
166 request_receiver_v3: IncomingRequestReceiver<protocol_v3::CollationFetchingRequest>,
168 metrics: collator_side::Metrics,
170 clock: Arc<dyn Clock>,
173 },
174 None,
176}
177
178pub struct CollatorProtocolSubsystem {
180 protocol_side: ProtocolSide,
181}
182
183#[overseer::contextbounds(CollatorProtocol, prefix = self::overseer)]
184impl CollatorProtocolSubsystem {
185 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
262async 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
279async 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
291fn 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
300struct LeafSchedulingInfo {
304 parent_hash: Hash,
306 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 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 info.slot.checked_add(1).is_some_and(|next_slot| *current_slot == next_slot)
340 } else {
341 leaf_scheduling_info
344 .iter()
345 .any(|(_, info)| *current_slot == *info.slot && *scheduling_parent == info.parent_hash)
346 }
347}
348
349pub(crate) struct LeafClaimQueues {
357 claim_queues: BTreeMap<CoreIndex, VecDeque<ParaId>>,
358 scheduling_lookahead: usize,
359}
360
361impl LeafClaimQueues {
362 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 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 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 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 assert!(!is_scheduling_parent_valid(&clock_at_slot(6), &parent, &info));
442 }
443
444 #[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}