cumulus_client_consensus_common/
lib.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// This file is part of Cumulus.
3// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
4
5// Cumulus is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9
10// Cumulus is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14
15// You should have received a copy of the GNU General Public License
16// along with Cumulus. If not, see <https://www.gnu.org/licenses/>.
17
18use codec::Decode;
19use polkadot_primitives::{Block as PBlock, Hash as PHash, Header as PHeader, ValidationCodeHash};
20
21use cumulus_primitives_core::{relay_chain, AbridgedHostConfiguration};
22use cumulus_relay_chain_interface::{RelayChainError, RelayChainInterface};
23
24use sc_client_api::Backend;
25use sc_consensus::{shared_data::SharedData, BlockImport, ImportResult};
26use sp_consensus_slots::Slot;
27
28use sp_runtime::traits::{Block as BlockT, Header as HeaderT};
29use sp_timestamp::Timestamp;
30
31use std::{sync::Arc, time::Duration};
32
33mod level_monitor;
34mod parachain_consensus;
35mod parent_search;
36#[cfg(test)]
37mod tests;
38
39pub use parent_search::*;
40
41pub use cumulus_relay_chain_streams::finalized_heads;
42pub use parachain_consensus::spawn_parachain_consensus_tasks;
43
44use level_monitor::LevelMonitor;
45pub use level_monitor::{LevelLimit, MAX_LEAVES_PER_LEVEL_SENSIBLE_DEFAULT};
46
47pub mod import_queue;
48
49/// Provides the hash of validation code used for authoring/execution of blocks at a given
50/// hash.
51pub trait ValidationCodeHashProvider<Hash> {
52	fn code_hash_at(&self, at: Hash) -> Option<ValidationCodeHash>;
53}
54
55impl<F, Hash> ValidationCodeHashProvider<Hash> for F
56where
57	F: Fn(Hash) -> Option<ValidationCodeHash>,
58{
59	fn code_hash_at(&self, at: Hash) -> Option<ValidationCodeHash> {
60		(self)(at)
61	}
62}
63
64/// The result from building a collation.
65pub struct ParachainCandidate<B> {
66	/// The block that was built for this candidate.
67	pub block: B,
68	/// The proof that was recorded while building the block.
69	pub proof: sp_trie::StorageProof,
70}
71
72/// Parachain specific block import.
73///
74/// Specialized block import for parachains. It supports to delay setting the best block until the
75/// relay chain has included a candidate in its best block. By default the delayed best block
76/// setting is disabled. The block import also monitors the imported blocks and prunes by default if
77/// there are too many blocks at the same height. Too many blocks at the same height can for example
78/// happen if the relay chain is rejecting the parachain blocks in the validation.
79pub struct ParachainBlockImport<Block: BlockT, BI, BE> {
80	inner: BI,
81	monitor: Option<SharedData<LevelMonitor<Block, BE>>>,
82	delayed_best_block: bool,
83}
84
85impl<Block: BlockT, BI, BE: Backend<Block>> ParachainBlockImport<Block, BI, BE> {
86	/// Create a new instance.
87	///
88	/// The number of leaves per level limit is set to `LevelLimit::Default`.
89	pub fn new(inner: BI, backend: Arc<BE>) -> Self {
90		Self::new_with_limit(inner, backend, LevelLimit::Default)
91	}
92
93	/// Create a new instance with an explicit limit to the number of leaves per level.
94	///
95	/// This function alone doesn't enforce the limit on levels for old imported blocks,
96	/// the limit is eventually enforced only when new blocks are imported.
97	pub fn new_with_limit(inner: BI, backend: Arc<BE>, level_leaves_max: LevelLimit) -> Self {
98		let level_limit = match level_leaves_max {
99			LevelLimit::None => None,
100			LevelLimit::Some(limit) => Some(limit),
101			LevelLimit::Default => Some(MAX_LEAVES_PER_LEVEL_SENSIBLE_DEFAULT),
102		};
103
104		let monitor =
105			level_limit.map(|level_limit| SharedData::new(LevelMonitor::new(level_limit, backend)));
106
107		Self { inner, monitor, delayed_best_block: false }
108	}
109
110	/// Create a new instance which delays setting the best block.
111	///
112	/// The number of leaves per level limit is set to `LevelLimit::Default`.
113	pub fn new_with_delayed_best_block(inner: BI, backend: Arc<BE>) -> Self {
114		Self {
115			delayed_best_block: true,
116			..Self::new_with_limit(inner, backend, LevelLimit::Default)
117		}
118	}
119}
120
121impl<Block: BlockT, I: Clone, BE> Clone for ParachainBlockImport<Block, I, BE> {
122	fn clone(&self) -> Self {
123		ParachainBlockImport {
124			inner: self.inner.clone(),
125			monitor: self.monitor.clone(),
126			delayed_best_block: self.delayed_best_block,
127		}
128	}
129}
130
131#[async_trait::async_trait]
132impl<Block, BI, BE> BlockImport<Block> for ParachainBlockImport<Block, BI, BE>
133where
134	Block: BlockT,
135	BI: BlockImport<Block> + Send + Sync,
136	BE: Backend<Block>,
137{
138	type Error = BI::Error;
139
140	async fn check_block(
141		&self,
142		block: sc_consensus::BlockCheckParams<Block>,
143	) -> Result<sc_consensus::ImportResult, Self::Error> {
144		self.inner.check_block(block).await
145	}
146
147	async fn import_block(
148		&self,
149		mut params: sc_consensus::BlockImportParams<Block>,
150	) -> Result<sc_consensus::ImportResult, Self::Error> {
151		// Blocks are stored within the backend by using POST hash.
152		let hash = params.post_hash();
153		let number = *params.header.number();
154
155		if params.with_state() {
156			// Force imported state finality.
157			// Required for warp sync. We assume that preconditions have been
158			// checked properly and we are importing a finalized block with state.
159			params.finalized = true;
160		}
161
162		if self.delayed_best_block {
163			// Best block is determined by the relay chain, or if we are doing the initial sync
164			// we import all blocks as new best.
165			params.fork_choice = Some(sc_consensus::ForkChoiceStrategy::Custom(
166				params.origin == sp_consensus::BlockOrigin::NetworkInitialSync,
167			));
168		}
169
170		let maybe_lock = self.monitor.as_ref().map(|monitor_lock| {
171			let mut monitor = monitor_lock.shared_data_locked();
172			monitor.enforce_limit(number);
173			monitor.release_mutex()
174		});
175
176		let res = self.inner.import_block(params).await?;
177
178		if let (Some(mut monitor_lock), ImportResult::Imported(_)) = (maybe_lock, &res) {
179			let mut monitor = monitor_lock.upgrade();
180			monitor.block_imported(number, hash);
181		}
182
183		Ok(res)
184	}
185}
186
187/// Marker trait denoting a block import type that fits the parachain requirements.
188pub trait ParachainBlockImportMarker {}
189
190impl<B: BlockT, BI, BE> ParachainBlockImportMarker for ParachainBlockImport<B, BI, BE> {}
191
192/// Get the relay-parent slot and timestamp from a header.
193pub fn relay_slot_and_timestamp(
194	relay_parent_header: &PHeader,
195	relay_chain_slot_duration: Duration,
196) -> Option<(Slot, Timestamp)> {
197	sc_consensus_babe::find_pre_digest::<PBlock>(relay_parent_header)
198		.map(|babe_pre_digest| {
199			let slot = babe_pre_digest.slot();
200			let t = Timestamp::new(relay_chain_slot_duration.as_millis() as u64 * *slot);
201
202			(slot, t)
203		})
204		.ok()
205}
206
207/// Reads abridged host configuration from the relay chain storage at the given relay parent.
208pub async fn load_abridged_host_configuration(
209	relay_parent: PHash,
210	relay_client: &impl RelayChainInterface,
211) -> Result<Option<AbridgedHostConfiguration>, RelayChainError> {
212	relay_client
213		.get_storage_by_key(relay_parent, relay_chain::well_known_keys::ACTIVE_CONFIG)
214		.await?
215		.map(|bytes| {
216			AbridgedHostConfiguration::decode(&mut &bytes[..])
217				.map_err(RelayChainError::DeserializationError)
218		})
219		.transpose()
220}