referrerpolicy=no-referrer-when-downgrade

cumulus_client_collator/
service.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
18//! The Cumulus [`CollatorService`] is a utility struct for performing common
19//! operations used in parachain consensus/authoring.
20
21use cumulus_primitives_core::{
22	bundle_provides,
23	signals::{split_at_separator, ump_signal_tail},
24	CollationInfo, CollectCollationInfo, ParachainBlockData, SchedulingProof,
25};
26
27use sc_client_api::BlockBackend;
28use sp_api::{ApiExt, ProvideRuntimeApi, StorageProof};
29use sp_consensus::BlockStatus;
30use sp_runtime::traits::{Block as BlockT, HashingFor, Header as HeaderT, Zero};
31
32use cumulus_client_consensus_common::ParachainCandidate;
33use polkadot_node_primitives::{BlockData, Collation, MaybeCompressedPoV, PoV};
34
35use codec::Encode;
36use std::sync::Arc;
37/// The logging target.
38const LOG_TARGET: &str = "cumulus-collator";
39
40/// Utility functions generally applicable to writing collators for Cumulus.
41pub trait ServiceInterface<Block: BlockT> {
42	/// Checks the status of the given block hash in the Parachain.
43	///
44	/// Returns `true` if the block could be found and is good to be build on.
45	fn check_block_status(&self, hash: Block::Hash, header: &Block::Header) -> bool;
46
47	/// Build a full [`Collation`] from a given [`ParachainCandidate`]. This requires
48	/// that the underlying block has been fully imported into the underlying client,
49	/// as implementations will fetch underlying runtime API data.
50	///
51	/// `scheduling_proof` is `Some` for V3 candidates (produces [`ParachainBlockData::V2`])
52	/// and `None` for legacy candidates (produces [`ParachainBlockData::V1`]).
53	///
54	/// This also returns the unencoded parachain block data, in case that is desired.
55	fn build_collation(
56		&self,
57		parent_header: &Block::Header,
58		block_hash: Block::Hash,
59		candidate: ParachainCandidate<Block>,
60		scheduling_proof: Option<SchedulingProof>,
61	) -> Option<(Collation, ParachainBlockData<Block>)>;
62
63	/// Build a multi-block collation.
64	///
65	/// Does the same as [`Self::build_collation`], but includes multiple blocks into one collation.
66	/// The given `parent_header` should be the header from the parent of the first block.
67	///
68	/// `scheduling_proof` is `Some` for V3 candidates (produces [`ParachainBlockData::V2`])
69	/// and `None` for legacy candidates (produces [`ParachainBlockData::V1`]).
70	fn build_multi_block_collation(
71		&self,
72		parent_header: &Block::Header,
73		blocks: Vec<Block>,
74		proof: StorageProof,
75		scheduling_proof: Option<SchedulingProof>,
76	) -> Option<(Collation, ParachainBlockData<Block>)>;
77
78	/// Directly announce a block on the network.
79	fn announce_block(&self, block_hash: Block::Hash, data: Option<Vec<u8>>);
80}
81
82/// The [`CollatorService`] provides common utilities for parachain consensus and authoring.
83///
84/// This includes logic for checking the block status of arbitrary parachain headers
85/// gathered from the relay chain state, creating full [`Collation`]s to be shared with validators,
86/// and distributing new parachain blocks along the network.
87pub struct CollatorService<Block: BlockT, BS, RA> {
88	block_status: Arc<BS>,
89	announce_block: Arc<dyn Fn(Block::Hash, Option<Vec<u8>>) + Send + Sync>,
90	runtime_api: Arc<RA>,
91}
92
93impl<Block: BlockT, BS, RA> Clone for CollatorService<Block, BS, RA> {
94	fn clone(&self) -> Self {
95		Self {
96			block_status: self.block_status.clone(),
97			announce_block: self.announce_block.clone(),
98			runtime_api: self.runtime_api.clone(),
99		}
100	}
101}
102
103impl<Block, BS, RA> CollatorService<Block, BS, RA>
104where
105	Block: BlockT,
106	BS: BlockBackend<Block>,
107	RA: ProvideRuntimeApi<Block>,
108	RA::Api: CollectCollationInfo<Block>,
109{
110	/// Create a new instance.
111	pub fn new(
112		block_status: Arc<BS>,
113		announce_block: Arc<dyn Fn(Block::Hash, Option<Vec<u8>>) + Send + Sync>,
114		runtime_api: Arc<RA>,
115	) -> Self {
116		Self { block_status, announce_block, runtime_api }
117	}
118
119	/// Checks the status of the given block hash in the Parachain.
120	///
121	/// Returns `true` if the block could be found and is good to be build on.
122	pub fn check_block_status(&self, hash: Block::Hash, header: &Block::Header) -> bool {
123		match self.block_status.block_status(hash) {
124			Ok(BlockStatus::Queued) => {
125				tracing::debug!(
126					target: LOG_TARGET,
127					block_hash = ?hash,
128					"Skipping candidate production, because block is still queued for import.",
129				);
130				false
131			},
132			Ok(BlockStatus::InChainWithState) => true,
133			Ok(BlockStatus::InChainPruned) => {
134				tracing::error!(
135					target: LOG_TARGET,
136					"Skipping candidate production, because block `{:?}` is already pruned!",
137					hash,
138				);
139				false
140			},
141			Ok(BlockStatus::KnownBad) => {
142				tracing::error!(
143					target: LOG_TARGET,
144					block_hash = ?hash,
145					"Block is tagged as known bad and is included in the relay chain! Skipping candidate production!",
146				);
147				false
148			},
149			Ok(BlockStatus::Unknown) => {
150				if header.number().is_zero() {
151					tracing::error!(
152						target: LOG_TARGET,
153						block_hash = ?hash,
154						"Could not find the header of the genesis block in the database!",
155					);
156				} else {
157					tracing::debug!(
158						target: LOG_TARGET,
159						block_hash = ?hash,
160						"Skipping candidate production, because block is unknown.",
161					);
162				}
163				false
164			},
165			Err(e) => {
166				tracing::error!(
167					target: LOG_TARGET,
168					block_hash = ?hash,
169					error = ?e,
170					"Failed to get block status.",
171				);
172				false
173			},
174		}
175	}
176
177	/// Fetch the collation info from the runtime.
178	///
179	/// Returns `Ok(Some((CollationInfo, ApiVersion)))` on success, `Err(_)` on error or `Ok(None)`
180	/// if the runtime api isn't implemented by the runtime. `ApiVersion` being the version of the
181	/// [`CollectCollationInfo`] runtime api.
182	pub fn fetch_collation_info(
183		&self,
184		block_hash: Block::Hash,
185		header: &Block::Header,
186	) -> Result<Option<(CollationInfo, u32)>, sp_api::ApiError> {
187		let runtime_api = self.runtime_api.runtime_api();
188
189		let api_version =
190			match runtime_api.api_version::<dyn CollectCollationInfo<Block>>(block_hash)? {
191				Some(version) => version,
192				None => {
193					tracing::error!(
194						target: LOG_TARGET,
195						"Could not fetch `CollectCollationInfo` runtime api version."
196					);
197					return Ok(None);
198				},
199			};
200
201		let collation_info = if api_version < 2 {
202			#[allow(deprecated)]
203			runtime_api
204				.collect_collation_info_before_version_2(block_hash)?
205				.into_latest(header.encode().into())
206		} else {
207			runtime_api.collect_collation_info(block_hash, header)?
208		};
209
210		Ok(Some((collation_info, api_version)))
211	}
212
213	/// Build a full [`Collation`] from a given [`ParachainCandidate`]. This requires
214	/// that the underlying block has been fully imported into the underlying client,
215	/// as it fetches underlying runtime API data.
216	///
217	/// This also returns the unencoded parachain block data, in case that is desired.
218	fn build_multi_block_collation(
219		&self,
220		parent_header: &Block::Header,
221		blocks: Vec<Block>,
222		proof: StorageProof,
223		scheduling_proof: Option<SchedulingProof>,
224	) -> Option<(Collation, ParachainBlockData<Block>)> {
225		let compact_proof =
226			match proof.into_compact_proof::<HashingFor<Block>>(*parent_header.state_root()) {
227				Ok(proof) => proof,
228				Err(e) => {
229					tracing::error!(target: "cumulus-collator", "Failed to compact proof: {:?}", e);
230					return None;
231				},
232			};
233
234		// We are always using the `api_version` of the parent block. The `api_version` can only
235		// change with a runtime upgrade and this is when we want to observe the old
236		// `api_version`. Because this old `api_version` is the one used to validate this
237		// block. Otherwise, we already assume the `api_version` is higher than what the relay
238		// chain will use and this will lead to validation errors.
239		let api_version = self
240			.runtime_api
241			.runtime_api()
242			.api_version::<dyn CollectCollationInfo<Block>>(parent_header.hash())
243			.ok()
244			.flatten()?;
245		let mut upward_messages = Vec::new();
246		let mut upward_message_signals = Vec::<Vec<u8>>::with_capacity(4);
247		let mut horizontal_messages = Vec::new();
248		let mut new_validation_code = None;
249		let mut processed_downward_messages = 0;
250		let mut hrmp_watermark = None;
251		let mut head_data = None;
252
253		for block in &blocks {
254			// Create the parachain block data for the validators.
255			let (collation_info, _api_version) = self
256				.fetch_collation_info(block.hash(), block.header())
257				.map_err(|e| {
258					tracing::error!(
259						target: LOG_TARGET,
260						error = ?e,
261						"Failed to collect collation info.",
262					)
263				})
264				.ok()
265				.flatten()?;
266
267			let (messages, signals) = split_at_separator(collation_info.upward_messages);
268
269			upward_messages.extend(messages);
270			upward_message_signals.extend(signals);
271			horizontal_messages.extend(collation_info.horizontal_messages);
272
273			if let Some(new_code) = collation_info.new_validation_code {
274				if new_validation_code.replace(new_code).is_some() {
275					tracing::warn!(
276						target: LOG_TARGET,
277						block = ?block.hash(),
278						"Overwriting validation code from an earlier block in the bundle.",
279					);
280				}
281			}
282			processed_downward_messages += collation_info.processed_downward_messages;
283			hrmp_watermark = Some(collation_info.hrmp_watermark);
284			head_data = Some(collation_info.head_data);
285		}
286
287		// Sort by recipient as required by the relay chain rules.
288		horizontal_messages.sort_by(|a, b| a.recipient.cmp(&b.recipient));
289
290		let signed = scheduling_proof
291			.as_ref()
292			.and_then(|proof| proof.signed_scheduling_info.as_ref());
293		let tail = bundle_provides(blocks.iter().map(|block| block.header().digest()))
294			.and_then(|provides| {
295				// TODO(https://github.com/paritytech/polkadot-sdk/issues/12707): Pass the bundle's
296				// records and lifts. Until then, the PVF rejects candidates that consume messages.
297				ump_signal_tail(&upward_message_signals, signed, provides, &[], None)
298			})
299			.map_err(
300				|error| tracing::error!(target: LOG_TARGET, %error, "Invalid candidate signals."),
301			)
302			.ok()?;
303		upward_messages.extend(tail);
304
305		let block_data = ParachainBlockData::<Block>::new(blocks, compact_proof, scheduling_proof);
306
307		let pov = polkadot_node_primitives::maybe_compress_pov(PoV {
308			block_data: BlockData(if api_version >= 3 {
309				block_data.encode()
310			} else {
311				let block_data = block_data.as_v0();
312
313				if block_data.is_none() {
314					tracing::error!(
315						target: LOG_TARGET,
316						"Trying to submit a collation with multiple blocks is not supported by the current runtime."
317					);
318				}
319
320				block_data?.encode()
321			}),
322		});
323
324		let upward_messages = upward_messages
325			.try_into()
326			.map_err(|e| {
327				tracing::error!(
328					target: LOG_TARGET,
329					error = ?e,
330					"Number of upward messages should not be greater than `MAX_UPWARD_MESSAGE_NUM`",
331				)
332			})
333			.ok()?;
334		let horizontal_messages = horizontal_messages
335			.try_into()
336			.map_err(|e| {
337				tracing::error!(
338					target: LOG_TARGET,
339					error = ?e,
340					"Number of horizontal messages should not be greater than `MAX_HORIZONTAL_MESSAGE_NUM`",
341				)
342			})
343			.ok()?;
344
345		let collation = Collation {
346			upward_messages,
347			new_validation_code,
348			processed_downward_messages,
349			horizontal_messages,
350			// If these are `None`, there was no block.
351			hrmp_watermark: hrmp_watermark?,
352			head_data: head_data?,
353			proof_of_validity: MaybeCompressedPoV::Compressed(pov),
354		};
355
356		Some((collation, block_data))
357	}
358}
359
360impl<Block, BS, RA> ServiceInterface<Block> for CollatorService<Block, BS, RA>
361where
362	Block: BlockT,
363	BS: BlockBackend<Block>,
364	RA: ProvideRuntimeApi<Block>,
365	RA::Api: CollectCollationInfo<Block>,
366{
367	fn check_block_status(&self, hash: Block::Hash, header: &Block::Header) -> bool {
368		CollatorService::check_block_status(self, hash, header)
369	}
370
371	fn build_collation(
372		&self,
373		parent_header: &Block::Header,
374		_: Block::Hash,
375		candidate: ParachainCandidate<Block>,
376		scheduling_proof: Option<SchedulingProof>,
377	) -> Option<(Collation, ParachainBlockData<Block>)> {
378		CollatorService::build_multi_block_collation(
379			self,
380			parent_header,
381			vec![candidate.block],
382			candidate.proof,
383			scheduling_proof,
384		)
385	}
386
387	fn announce_block(&self, block_hash: Block::Hash, data: Option<Vec<u8>>) {
388		(self.announce_block)(block_hash, data)
389	}
390
391	fn build_multi_block_collation(
392		&self,
393		parent_header: &<Block as BlockT>::Header,
394		blocks: Vec<Block>,
395		proof: StorageProof,
396		scheduling_proof: Option<SchedulingProof>,
397	) -> Option<(Collation, ParachainBlockData<Block>)> {
398		CollatorService::build_multi_block_collation(
399			self,
400			parent_header,
401			blocks,
402			proof,
403			scheduling_proof,
404		)
405	}
406}