1use 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;
37const LOG_TARGET: &str = "cumulus-collator";
39
40pub trait ServiceInterface<Block: BlockT> {
42 fn check_block_status(&self, hash: Block::Hash, header: &Block::Header) -> bool;
46
47 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 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 fn announce_block(&self, block_hash: Block::Hash, data: Option<Vec<u8>>);
80}
81
82pub 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 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 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 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 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 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 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 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 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 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}