referrerpolicy=no-referrer-when-downgrade

polkadot_node_subsystem_util/runtime/
mod.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//! Convenient interface to runtime information.
18
19use 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
52/// Errors that can happen on runtime fetches.
53mod error;
54
55use error::Result;
56pub use error::{recv_runtime, Error, FatalError, JfyiError};
57
58const LOG_TARGET: &'static str = "parachain::runtime-info";
59
60/// Configuration for construction a `RuntimeInfo`.
61pub struct Config {
62	/// Needed for retrieval of `ValidatorInfo`
63	///
64	/// Pass `None` if you are not interested.
65	pub keystore: Option<KeystorePtr>,
66
67	/// How many sessions should we keep in the cache?
68	pub session_cache_lru_size: u32,
69}
70
71/// Caching of session info.
72///
73/// It should be ensured that a cached session stays live in the cache as long as we might need it.
74pub struct RuntimeInfo {
75	/// Get the session index for a given relay parent.
76	///
77	/// We query this up to a 100 times per block, so caching it here without roundtrips over the
78	/// overseer seems sensible.
79	session_index_cache: LruMap<Hash, SessionIndex>,
80
81	/// In the happy case, we do not query disabled validators at all. In the worst case, we can
82	/// query it order of `n_cores` times `n_validators` per block, so caching it here seems
83	/// sensible.
84	disabled_validators_cache: LruMap<Hash, Vec<ValidatorIndex>>,
85
86	/// Look up cached sessions by `SessionIndex`.
87	session_info_cache: LruMap<SessionIndex, ExtendedSessionInfo>,
88
89	/// Unpin handle of *some* block in the session.
90	/// Only blocks pinned explicitly by `pin_block` are stored here.
91	pinned_blocks: LruMap<SessionIndex, UnpinHandle>,
92
93	/// Key store for determining whether we are a validator and what `ValidatorIndex` we have.
94	keystore: Option<KeystorePtr>,
95}
96
97/// `SessionInfo` with additional useful data for validator nodes.
98pub struct ExtendedSessionInfo {
99	/// Actual session info as fetched from the runtime.
100	pub session_info: SessionInfo,
101	/// Contains useful information about ourselves, in case this node is a validator.
102	pub validator_info: ValidatorInfo,
103	/// Node features
104	pub node_features: NodeFeatures,
105	/// Approval-voting parameters.
106	pub approval_voting_params: ApprovalVotingParams,
107}
108
109/// Information about ourselves, in case we are an `Authority`.
110///
111/// This data is derived from the `SessionInfo` and our key as found in the keystore.
112pub struct ValidatorInfo {
113	/// The index this very validator has in `SessionInfo` vectors, if any.
114	pub our_index: Option<ValidatorIndex>,
115	/// The group we belong to, if any.
116	pub our_group: Option<GroupIndex>,
117}
118
119impl Default for Config {
120	fn default() -> Self {
121		Self {
122			keystore: None,
123			// Usually we need to cache the current and the last session.
124			session_cache_lru_size: 2,
125		}
126	}
127}
128
129impl RuntimeInfo {
130	/// Create a new `RuntimeInfo` for convenient runtime fetches.
131	pub fn new(keystore: Option<KeystorePtr>) -> Self {
132		Self::new_with_config(Config { keystore, ..Default::default() })
133	}
134
135	/// Create with more elaborate configuration options.
136	pub fn new_with_config(cfg: Config) -> Self {
137		Self {
138			// Usually messages are processed for blocks pointing to hashes from last finalized
139			// block to to best, so make this cache large enough to hold at least this amount of
140			// hashes, so that we get the benefit of caching even when finality lag is large.
141			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	/// Returns the session index expected at any child of the `parent` block.
152	/// This does not return the session index for the `parent` block.
153	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	/// Pin a given block in the given session if none are pinned in that session.
173	/// Unpinning will happen automatically when LRU cache grows over the limit.
174	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	/// Get the hash of a pinned block for the given session index, if any.
179	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	/// Get `ExtendedSessionInfo` by relay parent hash.
184	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	/// Get the list of disabled validators at the relay parent.
198	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	/// Get `ExtendedSessionInfo` by session index.
218	///
219	/// `request_session_info` still requires the parent to be passed in, so we take the parent
220	/// in addition to the `SessionIndex`.
221	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	/// Convenience function for checking the signature of something signed.
264	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	/// Build `ValidatorInfo` for the current session.
283	///
284	///
285	/// Returns: `None` if not a parachain validator.
286	fn get_validator_info(&self, session_info: &SessionInfo) -> Result<ValidatorInfo> {
287		if let Some(our_index) = self.get_our_index(&session_info.validators) {
288			// Get our group index:
289			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	/// Get our `ValidatorIndex`.
306	///
307	/// Returns: None if we are not a validator.
308	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
322/// Convenience function for quickly checking the signature on signed data.
323pub 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
342/// Request availability cores from the runtime.
343pub 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
353/// Variant of `request_availability_cores` that only returns occupied ones.
354pub 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
376/// Get group rotation info based on the given `relay_parent`.
377pub 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	// We drop `groups` here as we don't need them, because of `RuntimeInfo`. Ideally we would not
385	// fetch them in the first place.
386	let (_, info) = recv_runtime(request_validator_groups(relay_parent, sender).await).await?;
387	Ok(info)
388}
389
390/// Get `CandidateEvent`s for the given `relay_parent`.
391pub 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
401/// Get on chain votes.
402pub 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
412/// Fetch `ValidationCode` by hash from the runtime.
413pub 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
425/// Fetch a list of `PendingSlashes` from the runtime.
426/// Will fallback to `unapplied_slashes` if the runtime does not
427/// support `unapplied_slashes_v2`.
428pub 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			// Fallback to legacy unapplied_slashes
439			let legacy =
440				recv_runtime(request_unapplied_slashes(relay_parent, sender).await).await?;
441			// Convert legacy slashes to PendingSlashes
442			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
460/// Generate validator key ownership proof.
461///
462/// Note: The choice of `relay_parent` is important here, it needs to match
463/// the desired session index of the validator set in question.
464pub 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
475/// Submit a past-session dispute slashing report.
476pub 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/// A snapshot of the runtime claim queue at an arbitrary relay chain block.
498#[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	/// Returns the `ParaId` that has a claim for `core_index` at the specified `depth` in the
509	/// claim queue. A depth of `0` means the very next block.
510	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	/// Returns an iterator over all claimed cores and the claiming `ParaId` at the specified
515	/// `depth` in the claim queue.
516	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	/// Returns an iterator over all claims on the given core.
526	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	/// Returns an iterator over the whole claim queue.
534	pub fn iter_all_claims(&self) -> impl Iterator<Item = (&CoreIndex, &VecDeque<ParaId>)> + '_ {
535		self.0.iter()
536	}
537
538	/// Get all claimed cores for the given `para_id` at the specified depth.
539	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
550/// Fetch the claim queue and wrap it into a helpful `ClaimQueueSnapshot`
551pub 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
563/// Returns the lookahead from the scheduler params if the runtime supports it,
564/// or default value if scheduling lookahead API is not supported by runtime.
565pub 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
592/// Fetch the validation code bomb limit from the runtime.
593pub 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		// TODO: Remove this once runtime API version 12 is released.
614		#[allow(deprecated)]
615		Ok(polkadot_node_primitives::VALIDATION_CODE_BOMB_LIMIT as u32)
616	} else {
617		res
618	}
619}