1use polkadot_node_primitives::MAX_FINALITY_LAG;
20use schnellru::{ByLength, LruMap};
21
22use codec::Encode;
23use sp_application_crypto::AppCrypto;
24use sp_core::crypto::ByteArray;
25use sp_keystore::{Keystore, KeystorePtr};
26
27use polkadot_node_subsystem::{
28 errors::RuntimeApiError,
29 messages::{RuntimeApiMessage, RuntimeApiRequest},
30 overseer, SubsystemSender,
31};
32use polkadot_node_subsystem_types::UnpinHandle;
33use polkadot_primitives::{
34 node_features::FeatureIndex, slashing, ApprovalVotingParams, CandidateEvent, CandidateHash,
35 CoreIndex, CoreState, EncodeAs, GroupIndex, GroupRotationInfo, Hash, Id as ParaId, IndexedVec,
36 NodeFeatures, OccupiedCore, ScrapedOnChainVotes, SessionIndex, SessionInfo, Signed,
37 SigningContext, UncheckedSigned, ValidationCode, ValidationCodeHash, ValidatorId,
38 ValidatorIndex, DEFAULT_SCHEDULING_LOOKAHEAD,
39};
40
41use std::collections::{BTreeMap, VecDeque};
42
43use crate::{
44 request_approval_voting_params, request_availability_cores, request_candidate_events,
45 request_claim_queue, request_disabled_validators, request_from_runtime,
46 request_key_ownership_proof, request_node_features, request_on_chain_votes,
47 request_session_index_for_child, request_session_info, request_submit_report_dispute_lost,
48 request_unapplied_slashes, request_unapplied_slashes_v2, request_validation_code_by_hash,
49 request_validator_groups,
50};
51
52mod error;
54
55use error::Result;
56pub use error::{recv_runtime, Error, FatalError, JfyiError};
57
58const LOG_TARGET: &'static str = "parachain::runtime-info";
59
60pub struct Config {
62 pub keystore: Option<KeystorePtr>,
66
67 pub session_cache_lru_size: u32,
69}
70
71pub struct RuntimeInfo {
75 session_index_cache: LruMap<Hash, SessionIndex>,
80
81 disabled_validators_cache: LruMap<Hash, Vec<ValidatorIndex>>,
85
86 session_info_cache: LruMap<SessionIndex, ExtendedSessionInfo>,
88
89 pinned_blocks: LruMap<SessionIndex, UnpinHandle>,
92
93 keystore: Option<KeystorePtr>,
95}
96
97pub struct ExtendedSessionInfo {
99 pub session_info: SessionInfo,
101 pub validator_info: ValidatorInfo,
103 pub node_features: NodeFeatures,
105 pub approval_voting_params: ApprovalVotingParams,
107}
108
109pub struct ValidatorInfo {
113 pub our_index: Option<ValidatorIndex>,
115 pub our_group: Option<GroupIndex>,
117}
118
119impl Default for Config {
120 fn default() -> Self {
121 Self {
122 keystore: None,
123 session_cache_lru_size: 2,
125 }
126 }
127}
128
129impl RuntimeInfo {
130 pub fn new(keystore: Option<KeystorePtr>) -> Self {
132 Self::new_with_config(Config { keystore, ..Default::default() })
133 }
134
135 pub fn new_with_config(cfg: Config) -> Self {
137 Self {
138 session_index_cache: LruMap::new(ByLength::new(
142 cfg.session_cache_lru_size.max(2 * MAX_FINALITY_LAG),
143 )),
144 session_info_cache: LruMap::new(ByLength::new(cfg.session_cache_lru_size)),
145 disabled_validators_cache: LruMap::new(ByLength::new(100)),
146 pinned_blocks: LruMap::new(ByLength::new(cfg.session_cache_lru_size)),
147 keystore: cfg.keystore,
148 }
149 }
150
151 pub async fn get_session_index_for_child<Sender>(
154 &mut self,
155 sender: &mut Sender,
156 parent: Hash,
157 ) -> Result<SessionIndex>
158 where
159 Sender: SubsystemSender<RuntimeApiMessage>,
160 {
161 match self.session_index_cache.get(&parent) {
162 Some(index) => Ok(*index),
163 None => {
164 let index =
165 recv_runtime(request_session_index_for_child(parent, sender).await).await?;
166 self.session_index_cache.insert(parent, index);
167 Ok(index)
168 },
169 }
170 }
171
172 pub fn pin_block(&mut self, session_index: SessionIndex, unpin_handle: UnpinHandle) {
175 self.pinned_blocks.get_or_insert(session_index, || unpin_handle);
176 }
177
178 pub fn get_block_in_session(&self, session_index: SessionIndex) -> Option<Hash> {
180 self.pinned_blocks.peek(&session_index).map(|h| h.hash())
181 }
182
183 pub async fn get_session_info<'a, Sender>(
185 &'a mut self,
186 sender: &mut Sender,
187 relay_parent: Hash,
188 ) -> Result<&'a ExtendedSessionInfo>
189 where
190 Sender: SubsystemSender<RuntimeApiMessage>,
191 {
192 let session_index = self.get_session_index_for_child(sender, relay_parent).await?;
193
194 self.get_session_info_by_index(sender, relay_parent, session_index).await
195 }
196
197 pub async fn get_disabled_validators<Sender>(
199 &mut self,
200 sender: &mut Sender,
201 relay_parent: Hash,
202 ) -> Result<Vec<ValidatorIndex>>
203 where
204 Sender: SubsystemSender<RuntimeApiMessage>,
205 {
206 match self.disabled_validators_cache.get(&relay_parent).cloned() {
207 Some(result) => Ok(result),
208 None => {
209 let disabled_validators =
210 request_disabled_validators(relay_parent, sender).await.await??;
211 self.disabled_validators_cache.insert(relay_parent, disabled_validators.clone());
212 Ok(disabled_validators)
213 },
214 }
215 }
216
217 pub async fn get_session_info_by_index<'a, Sender>(
222 &'a mut self,
223 sender: &mut Sender,
224 parent: Hash,
225 session_index: SessionIndex,
226 ) -> Result<&'a ExtendedSessionInfo>
227 where
228 Sender: SubsystemSender<RuntimeApiMessage>,
229 {
230 if self.session_info_cache.get(&session_index).is_none() {
231 let session_info =
232 recv_runtime(request_session_info(parent, session_index, sender).await)
233 .await?
234 .ok_or(JfyiError::NoSuchSession(session_index))?;
235
236 let validator_info = self.get_validator_info(&session_info)?;
237
238 let node_features =
239 request_node_features(parent, session_index, sender).await.await??;
240 let last_set_index = node_features.iter_ones().last().unwrap_or_default();
241 if last_set_index >= FeatureIndex::FirstUnassigned as usize {
242 gum::warn!(target: LOG_TARGET, "Runtime requires feature bit {} that node doesn't support, please upgrade node version", last_set_index);
243 }
244
245 let approval_voting_params =
246 request_approval_voting_params(parent, session_index, sender).await.await??;
247
248 let full_info = ExtendedSessionInfo {
249 session_info,
250 validator_info,
251 node_features,
252 approval_voting_params,
253 };
254
255 self.session_info_cache.insert(session_index, full_info);
256 }
257 Ok(self
258 .session_info_cache
259 .get(&session_index)
260 .expect("We just put the value there. qed."))
261 }
262
263 pub async fn check_signature<Sender, Payload, RealPayload>(
265 &mut self,
266 sender: &mut Sender,
267 relay_parent: Hash,
268 signed: UncheckedSigned<Payload, RealPayload>,
269 ) -> Result<
270 std::result::Result<Signed<Payload, RealPayload>, UncheckedSigned<Payload, RealPayload>>,
271 >
272 where
273 Sender: SubsystemSender<RuntimeApiMessage>,
274 Payload: EncodeAs<RealPayload> + Clone,
275 RealPayload: Encode + Clone,
276 {
277 let session_index = self.get_session_index_for_child(sender, relay_parent).await?;
278 let info = self.get_session_info_by_index(sender, relay_parent, session_index).await?;
279 Ok(check_signature(session_index, &info.session_info, relay_parent, signed))
280 }
281
282 fn get_validator_info(&self, session_info: &SessionInfo) -> Result<ValidatorInfo> {
287 if let Some(our_index) = self.get_our_index(&session_info.validators) {
288 let our_group =
290 session_info.validator_groups.iter().enumerate().find_map(|(i, g)| {
291 g.iter().find_map(|v| {
292 if *v == our_index {
293 Some(GroupIndex(i as u32))
294 } else {
295 None
296 }
297 })
298 });
299 let info = ValidatorInfo { our_index: Some(our_index), our_group };
300 return Ok(info);
301 }
302 return Ok(ValidatorInfo { our_index: None, our_group: None });
303 }
304
305 fn get_our_index(
309 &self,
310 validators: &IndexedVec<ValidatorIndex, ValidatorId>,
311 ) -> Option<ValidatorIndex> {
312 let keystore = self.keystore.as_ref()?;
313 for (i, v) in validators.iter().enumerate() {
314 if Keystore::has_keys(&**keystore, &[(v.to_raw_vec(), ValidatorId::ID)]) {
315 return Some(ValidatorIndex(i as u32));
316 }
317 }
318 None
319 }
320}
321
322pub fn check_signature<Payload, RealPayload>(
324 session_index: SessionIndex,
325 session_info: &SessionInfo,
326 relay_parent: Hash,
327 signed: UncheckedSigned<Payload, RealPayload>,
328) -> std::result::Result<Signed<Payload, RealPayload>, UncheckedSigned<Payload, RealPayload>>
329where
330 Payload: EncodeAs<RealPayload> + Clone,
331 RealPayload: Encode + Clone,
332{
333 let signing_context = SigningContext { session_index, parent_hash: relay_parent };
334
335 session_info
336 .validators
337 .get(signed.unchecked_validator_index())
338 .ok_or_else(|| signed.clone())
339 .and_then(|v| signed.try_into_checked(&signing_context, v))
340}
341
342pub async fn get_availability_cores<Sender>(
344 sender: &mut Sender,
345 relay_parent: Hash,
346) -> Result<Vec<CoreState>>
347where
348 Sender: overseer::SubsystemSender<RuntimeApiMessage>,
349{
350 recv_runtime(request_availability_cores(relay_parent, sender).await).await
351}
352
353pub async fn get_occupied_cores<Sender>(
355 sender: &mut Sender,
356 relay_parent: Hash,
357) -> Result<Vec<(CoreIndex, OccupiedCore)>>
358where
359 Sender: overseer::SubsystemSender<RuntimeApiMessage>,
360{
361 let cores = get_availability_cores(sender, relay_parent).await?;
362
363 Ok(cores
364 .into_iter()
365 .enumerate()
366 .filter_map(|(core_index, core_state)| {
367 if let CoreState::Occupied(occupied) = core_state {
368 Some((CoreIndex(core_index as u32), occupied))
369 } else {
370 None
371 }
372 })
373 .collect())
374}
375
376pub async fn get_group_rotation_info<Sender>(
378 sender: &mut Sender,
379 relay_parent: Hash,
380) -> Result<GroupRotationInfo>
381where
382 Sender: overseer::SubsystemSender<RuntimeApiMessage>,
383{
384 let (_, info) = recv_runtime(request_validator_groups(relay_parent, sender).await).await?;
387 Ok(info)
388}
389
390pub async fn get_candidate_events<Sender>(
392 sender: &mut Sender,
393 relay_parent: Hash,
394) -> Result<Vec<CandidateEvent>>
395where
396 Sender: SubsystemSender<RuntimeApiMessage>,
397{
398 recv_runtime(request_candidate_events(relay_parent, sender).await).await
399}
400
401pub async fn get_on_chain_votes<Sender>(
403 sender: &mut Sender,
404 relay_parent: Hash,
405) -> Result<Option<ScrapedOnChainVotes>>
406where
407 Sender: SubsystemSender<RuntimeApiMessage>,
408{
409 recv_runtime(request_on_chain_votes(relay_parent, sender).await).await
410}
411
412pub async fn get_validation_code_by_hash<Sender>(
414 sender: &mut Sender,
415 relay_parent: Hash,
416 validation_code_hash: ValidationCodeHash,
417) -> Result<Option<ValidationCode>>
418where
419 Sender: SubsystemSender<RuntimeApiMessage>,
420{
421 recv_runtime(request_validation_code_by_hash(relay_parent, validation_code_hash, sender).await)
422 .await
423}
424
425pub async fn get_unapplied_slashes<Sender>(
429 sender: &mut Sender,
430 relay_parent: Hash,
431) -> Result<Vec<(SessionIndex, CandidateHash, slashing::PendingSlashes)>>
432where
433 Sender: SubsystemSender<RuntimeApiMessage>,
434{
435 match recv_runtime(request_unapplied_slashes_v2(relay_parent, sender).await).await {
436 Ok(v2) => Ok(v2),
437 Err(Error::RuntimeRequest(RuntimeApiError::NotSupported { .. })) => {
438 let legacy =
440 recv_runtime(request_unapplied_slashes(relay_parent, sender).await).await?;
441 Ok(legacy
443 .into_iter()
444 .map(|(session, candidate_hash, legacy_slash)| {
445 (
446 session,
447 candidate_hash,
448 slashing::PendingSlashes {
449 keys: legacy_slash.keys,
450 kind: legacy_slash.kind.into(),
451 },
452 )
453 })
454 .collect())
455 },
456 Err(e) => Err(e),
457 }
458}
459
460pub async fn key_ownership_proof<Sender>(
465 sender: &mut Sender,
466 relay_parent: Hash,
467 validator_id: ValidatorId,
468) -> Result<Option<slashing::OpaqueKeyOwnershipProof>>
469where
470 Sender: SubsystemSender<RuntimeApiMessage>,
471{
472 recv_runtime(request_key_ownership_proof(relay_parent, validator_id, sender).await).await
473}
474
475pub async fn submit_report_dispute_lost<Sender>(
477 sender: &mut Sender,
478 relay_parent: Hash,
479 dispute_proof: slashing::DisputeProof,
480 key_ownership_proof: slashing::OpaqueKeyOwnershipProof,
481) -> Result<Option<()>>
482where
483 Sender: SubsystemSender<RuntimeApiMessage>,
484{
485 recv_runtime(
486 request_submit_report_dispute_lost(
487 relay_parent,
488 dispute_proof,
489 key_ownership_proof,
490 sender,
491 )
492 .await,
493 )
494 .await
495}
496
497#[derive(Default, Clone, Debug)]
499pub struct ClaimQueueSnapshot(pub BTreeMap<CoreIndex, VecDeque<ParaId>>);
500
501impl From<BTreeMap<CoreIndex, VecDeque<ParaId>>> for ClaimQueueSnapshot {
502 fn from(claim_queue_snapshot: BTreeMap<CoreIndex, VecDeque<ParaId>>) -> Self {
503 ClaimQueueSnapshot(claim_queue_snapshot)
504 }
505}
506
507impl ClaimQueueSnapshot {
508 pub fn get_claim_for(&self, core_index: CoreIndex, depth: usize) -> Option<ParaId> {
511 self.0.get(&core_index)?.get(depth).copied()
512 }
513
514 pub fn iter_claims_at_depth(
517 &self,
518 depth: usize,
519 ) -> impl Iterator<Item = (CoreIndex, ParaId)> + '_ {
520 self.0
521 .iter()
522 .filter_map(move |(core_index, paras)| Some((*core_index, *paras.get(depth)?)))
523 }
524
525 pub fn iter_claims_for_core(
527 &self,
528 core_index: &CoreIndex,
529 ) -> impl Iterator<Item = &ParaId> + '_ {
530 self.0.get(core_index).map(|c| c.iter()).into_iter().flatten()
531 }
532
533 pub fn iter_all_claims(&self) -> impl Iterator<Item = (&CoreIndex, &VecDeque<ParaId>)> + '_ {
535 self.0.iter()
536 }
537
538 pub fn iter_claims_at_depth_for_para(
540 &self,
541 depth: usize,
542 para_id: ParaId,
543 ) -> impl Iterator<Item = CoreIndex> + '_ {
544 self.0.iter().filter_map(move |(core_index, ids)| {
545 ids.get(depth).filter(|id| **id == para_id).map(|_| *core_index)
546 })
547 }
548}
549
550pub async fn fetch_claim_queue(
552 sender: &mut impl SubsystemSender<RuntimeApiMessage>,
553 relay_parent: Hash,
554) -> Result<ClaimQueueSnapshot> {
555 let cq = request_claim_queue(relay_parent, sender)
556 .await
557 .await
558 .map_err(Error::RuntimeRequestCanceled)??;
559
560 Ok(cq.into())
561}
562
563pub async fn fetch_scheduling_lookahead(
566 parent: Hash,
567 session_index: SessionIndex,
568 sender: &mut impl overseer::SubsystemSender<RuntimeApiMessage>,
569) -> Result<u32> {
570 let res = recv_runtime(
571 request_from_runtime(parent, sender, |tx| {
572 RuntimeApiRequest::SchedulingLookahead(session_index, tx)
573 })
574 .await,
575 )
576 .await;
577
578 if let Err(Error::RuntimeRequest(RuntimeApiError::NotSupported { .. })) = res {
579 gum::trace!(
580 target: LOG_TARGET,
581 ?parent,
582 "Querying the scheduling lookahead from the runtime is not supported by the current Runtime API, falling back to default value of {}",
583 DEFAULT_SCHEDULING_LOOKAHEAD
584 );
585
586 Ok(DEFAULT_SCHEDULING_LOOKAHEAD)
587 } else {
588 res
589 }
590}
591
592pub async fn fetch_validation_code_bomb_limit(
594 parent: Hash,
595 session_index: SessionIndex,
596 sender: &mut impl overseer::SubsystemSender<RuntimeApiMessage>,
597) -> Result<u32> {
598 let res = recv_runtime(
599 request_from_runtime(parent, sender, |tx| {
600 RuntimeApiRequest::ValidationCodeBombLimit(session_index, tx)
601 })
602 .await,
603 )
604 .await;
605
606 if let Err(Error::RuntimeRequest(RuntimeApiError::NotSupported { .. })) = res {
607 gum::trace!(
608 target: LOG_TARGET,
609 ?parent,
610 "Querying the validation code bomb limit from the runtime is not supported by the current Runtime API",
611 );
612
613 #[allow(deprecated)]
615 Ok(polkadot_node_primitives::VALIDATION_CODE_BOMB_LIMIT as u32)
616 } else {
617 res
618 }
619}