cumulus-primitives-core 0.26.0

Cumulus related core primitive types and traits
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Cumulus.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 	http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Provides [`ParachainBlockData`] and its historical versions.

use crate::SchedulingProof;
use alloc::vec::Vec;
use codec::{Decode, Encode};
use sp_runtime::traits::Block as BlockT;
use sp_trie::CompactProof;

/// Special prefix used by [`ParachainBlockData`] from version 1 and upwards to distinguish from the
/// unversioned legacy/v0 version.
const VERSIONED_PARACHAIN_BLOCK_DATA_PREFIX: &[u8] = b"VERSIONEDPBD";

// Struct which allows prepending bytes after reading from an input.
pub(crate) struct PrependBytesInput<'a, I> {
	prepend: &'a [u8],
	read: usize,
	inner: &'a mut I,
}

impl<'a, I: codec::Input> codec::Input for PrependBytesInput<'a, I> {
	fn remaining_len(&mut self) -> Result<Option<usize>, codec::Error> {
		let remaining_compact = self.prepend.len().saturating_sub(self.read);
		Ok(self.inner.remaining_len()?.map(|len| len.saturating_add(remaining_compact)))
	}

	fn read(&mut self, into: &mut [u8]) -> Result<(), codec::Error> {
		if into.is_empty() {
			return Ok(());
		}

		let remaining_compact = self.prepend.len().saturating_sub(self.read);
		if remaining_compact > 0 {
			let to_read = into.len().min(remaining_compact);
			into[..to_read].copy_from_slice(&self.prepend[self.read..][..to_read]);
			self.read += to_read;

			if to_read < into.len() {
				// Buffer not full, keep reading the inner.
				self.inner.read(&mut into[to_read..])
			} else {
				// Buffer was filled by the bytes.
				Ok(())
			}
		} else {
			// Prepended bytes has been read, just read from inner.
			self.inner.read(into)
		}
	}
}

/// The parachain block that is created by a collator.
///
/// This is send as PoV (proof of validity block) to the relay-chain validators. There it will be
/// passed to the parachain validation Wasm blob to be validated.
#[derive(Clone)]
pub enum ParachainBlockData<Block> {
	V0 {
		block: [Block; 1],
		proof: CompactProof,
	},
	V1 {
		blocks: Vec<Block>,
		proof: CompactProof,
	},
	/// V2 adds scheduling proof for V3 candidates.
	V2 {
		blocks: Vec<Block>,
		proof: CompactProof,
		scheduling_proof: SchedulingProof,
	},
}

impl<Block: Encode> Encode for ParachainBlockData<Block> {
	fn encode(&self) -> Vec<u8> {
		match self {
			Self::V0 { block, proof } => (&block[0], &proof).encode(),
			Self::V1 { blocks, proof } => {
				let mut res = VERSIONED_PARACHAIN_BLOCK_DATA_PREFIX.to_vec();
				1u8.encode_to(&mut res);
				blocks.encode_to(&mut res);
				proof.encode_to(&mut res);
				res
			},
			Self::V2 { blocks, proof, scheduling_proof } => {
				let mut res = VERSIONED_PARACHAIN_BLOCK_DATA_PREFIX.to_vec();
				2u8.encode_to(&mut res);
				blocks.encode_to(&mut res);
				proof.encode_to(&mut res);
				scheduling_proof.encode_to(&mut res);
				res
			},
		}
	}
}

impl<Block: Decode> Decode for ParachainBlockData<Block> {
	fn decode<I: codec::Input>(input: &mut I) -> Result<Self, codec::Error> {
		let mut prefix = [0u8; VERSIONED_PARACHAIN_BLOCK_DATA_PREFIX.len()];
		input.read(&mut prefix)?;

		if prefix == VERSIONED_PARACHAIN_BLOCK_DATA_PREFIX {
			match input.read_byte()? {
				1 => {
					let blocks = Vec::<Block>::decode(input)?;
					let proof = CompactProof::decode(input)?;

					Ok(Self::V1 { blocks, proof })
				},
				2 => {
					let blocks = Vec::<Block>::decode(input)?;
					let proof = CompactProof::decode(input)?;
					let scheduling_proof = crate::SchedulingProof::decode(input)?;

					Ok(Self::V2 { blocks, proof, scheduling_proof })
				},
				_ => Err("Unknown `ParachainBlockData` version".into()),
			}
		} else {
			let mut input = PrependBytesInput { prepend: &prefix, read: 0, inner: input };
			let block = Block::decode(&mut input)?;
			let proof = CompactProof::decode(&mut input)?;

			Ok(Self::V0 { block: [block], proof })
		}
	}
}

impl<Block> ParachainBlockData<Block> {
	/// Creates a new instance of `Self`.
	pub fn new(
		blocks: Vec<Block>,
		proof: CompactProof,
		scheduling_proof: Option<SchedulingProof>,
	) -> Self {
		match scheduling_proof {
			Some(sp) => Self::V2 { blocks, proof, scheduling_proof: sp },
			None => Self::V1 { blocks, proof },
		}
	}

	/// Returns references to the stored blocks.
	pub fn blocks(&self) -> &[Block] {
		match self {
			Self::V0 { block, .. } => &block[..],
			Self::V1 { blocks, .. } => &blocks,
			Self::V2 { blocks, .. } => &blocks,
		}
	}

	/// Returns mutable references to the stored blocks.
	pub fn blocks_mut(&mut self) -> &mut [Block] {
		match self {
			Self::V0 { ref mut block, .. } => block,
			Self::V1 { ref mut blocks, .. } => blocks,
			Self::V2 { ref mut blocks, .. } => blocks,
		}
	}

	/// Returns the stored blocks.
	pub fn into_blocks(self) -> Vec<Block> {
		match self {
			Self::V0 { block, .. } => block.into_iter().collect(),
			Self::V1 { blocks, .. } => blocks,
			Self::V2 { blocks, .. } => blocks,
		}
	}

	/// Returns a reference to the stored proof.
	pub fn proof(&self) -> &CompactProof {
		match self {
			Self::V0 { proof, .. } => &proof,
			Self::V1 { proof, .. } => proof,
			Self::V2 { proof, .. } => proof,
		}
	}

	/// Deconstruct into the inner parts.
	pub fn into_inner(self) -> (Vec<Block>, CompactProof) {
		match self {
			Self::V0 { block, proof } => (block.into_iter().collect(), proof),
			Self::V1 { blocks, proof } => (blocks, proof),
			Self::V2 { blocks, proof, .. } => (blocks, proof),
		}
	}

	/// Returns the scheduling proof if this is a V2 POV.
	pub fn scheduling_proof(&self) -> Option<&crate::SchedulingProof> {
		match self {
			Self::V2 { scheduling_proof, .. } => Some(scheduling_proof),
			_ => None,
		}
	}
}

impl<Block: BlockT> ParachainBlockData<Block> {
	/// Log the size of the individual components (header, extrinsics, storage proof) as info.
	pub fn log_size_info(&self) {
		tracing::info!(
			target: "cumulus",
			header_kb = %self.blocks().iter().map(|b| b.header().encoded_size()).sum::<usize>() as f64 / 1024f64,
			extrinsics_kb = %self.blocks().iter().map(|b| b.extrinsics().encoded_size()).sum::<usize>() as f64 / 1024f64,
			storage_proof_kb = %self.proof().encoded_size() as f64 / 1024f64,
			"PoV size",
		);
	}

	/// Converts into [`ParachainBlockData::V0`].
	///
	/// Returns `None` if there is not exactly one block.
	pub fn as_v0(&self) -> Option<Self> {
		match self {
			Self::V0 { .. } => Some(self.clone()),
			Self::V1 { blocks, proof } => {
				if blocks.len() != 1 {
					return None;
				}

				blocks
					.first()
					.map(|block| Self::V0 { block: [block.clone()], proof: proof.clone() })
			},
			Self::V2 { blocks, proof, .. } => {
				if blocks.len() != 1 {
					return None;
				}

				blocks
					.first()
					.map(|block| Self::V0 { block: [block.clone()], proof: proof.clone() })
			},
		}
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use sp_runtime::testing::*;

	#[derive(codec::Encode, codec::Decode, Clone, PartialEq, Debug)]
	struct ParachainBlockDataV0<B: BlockT> {
		/// The header of the parachain block.
		pub header: B::Header,
		/// The extrinsics of the parachain block.
		pub extrinsics: alloc::vec::Vec<B::Extrinsic>,
		/// The data that is required to emulate the storage accesses executed by all extrinsics.
		pub storage_proof: sp_trie::CompactProof,
	}

	type TestExtrinsic = TestXt<MockCallU64, ()>;
	type TestBlock = Block<TestExtrinsic>;

	#[test]
	fn decoding_encoding_v0_works() {
		let v0 = ParachainBlockDataV0::<TestBlock> {
			header: Header::new_from_number(10),
			extrinsics: vec![
				TestExtrinsic::new_bare(MockCallU64(10)),
				TestExtrinsic::new_bare(MockCallU64(100)),
			],
			storage_proof: CompactProof { encoded_nodes: vec![vec![10u8; 200], vec![20u8; 30]] },
		};

		let encoded = v0.encode();
		let decoded = ParachainBlockData::<TestBlock>::decode(&mut &encoded[..]).unwrap();

		match &decoded {
			ParachainBlockData::V0 { block, proof } => {
				assert_eq!(v0.header, block[0].header);
				assert_eq!(v0.extrinsics, block[0].extrinsics);
				assert_eq!(&v0.storage_proof, proof);
			},
			_ => panic!("Invalid decoding"),
		}

		let encoded = decoded.as_v0().unwrap().encode();

		let decoded = ParachainBlockDataV0::<TestBlock>::decode(&mut &encoded[..]).unwrap();
		assert_eq!(decoded, v0);
	}

	#[test]
	fn decoding_encoding_v1_works() {
		let v1 = ParachainBlockData::<TestBlock>::V1 {
			blocks: vec![TestBlock::new(
				Header::new_from_number(10),
				vec![
					TestExtrinsic::new_bare(MockCallU64(10)),
					TestExtrinsic::new_bare(MockCallU64(100)),
				],
			)],
			proof: CompactProof { encoded_nodes: vec![vec![10u8; 200], vec![20u8; 30]] },
		};

		let encoded = v1.encode();
		let decoded = ParachainBlockData::<TestBlock>::decode(&mut &encoded[..]).unwrap();

		assert_eq!(v1.blocks(), decoded.blocks());
		assert_eq!(v1.proof(), decoded.proof());
	}

	// Helper to create a relay chain header for tests
	fn make_relay_header(number: u32) -> polkadot_primitives::Header {
		use sp_runtime::traits::Header as _;
		polkadot_primitives::Header::new(
			number,
			polkadot_core_primitives::Hash::repeat_byte(1),
			polkadot_core_primitives::Hash::repeat_byte(2),
			polkadot_core_primitives::Hash::repeat_byte(3),
			Default::default(),
		)
	}

	#[test]
	fn decoding_encoding_v2_works() {
		let scheduling_proof = crate::SchedulingProof {
			header_chain: vec![make_relay_header(5)],
			internal_scheduling_parent_header: make_relay_header(4),
			signed_scheduling_info: None,
		};

		let v2 = ParachainBlockData::<TestBlock>::V2 {
			blocks: vec![TestBlock::new(
				Header::new_from_number(10),
				vec![
					TestExtrinsic::new_bare(MockCallU64(10)),
					TestExtrinsic::new_bare(MockCallU64(100)),
				],
			)],
			proof: CompactProof { encoded_nodes: vec![vec![10u8; 200], vec![20u8; 30]] },
			scheduling_proof: scheduling_proof.clone(),
		};

		let encoded = v2.encode();
		let decoded = ParachainBlockData::<TestBlock>::decode(&mut &encoded[..]).unwrap();

		assert_eq!(v2.blocks(), decoded.blocks());
		assert_eq!(v2.proof(), decoded.proof());
		assert_eq!(v2.scheduling_proof(), decoded.scheduling_proof());

		// Verify scheduling_proof accessor works
		assert!(decoded.scheduling_proof().is_some());
		assert_eq!(decoded.scheduling_proof().unwrap().header_chain.len(), 1);
	}

	#[test]
	fn v2_scheduling_proof_accessor_returns_none_for_v0_v1() {
		// V0 should return None for scheduling_proof
		let v0 = ParachainBlockData::<TestBlock>::V0 {
			block: [TestBlock::new(Header::new_from_number(1), vec![])],
			proof: CompactProof { encoded_nodes: vec![] },
		};
		assert!(v0.scheduling_proof().is_none());

		// V1 should return None for scheduling_proof
		let v1 = ParachainBlockData::<TestBlock>::V1 {
			blocks: vec![TestBlock::new(Header::new_from_number(1), vec![])],
			proof: CompactProof { encoded_nodes: vec![] },
		};
		assert!(v1.scheduling_proof().is_none());
	}

	#[test]
	fn v2_into_inner_drops_scheduling_proof() {
		let scheduling_proof = crate::SchedulingProof {
			header_chain: vec![make_relay_header(5)],
			internal_scheduling_parent_header: make_relay_header(4),
			signed_scheduling_info: None,
		};

		let v2 = ParachainBlockData::<TestBlock>::V2 {
			blocks: vec![TestBlock::new(Header::new_from_number(10), vec![])],
			proof: CompactProof { encoded_nodes: vec![vec![1u8; 10]] },
			scheduling_proof,
		};

		let (blocks, proof) = v2.into_inner();
		assert_eq!(blocks.len(), 1);
		assert_eq!(proof.encoded_nodes.len(), 1);
	}

	#[test]
	fn v2_as_v0_works_with_single_block() {
		let scheduling_proof = crate::SchedulingProof {
			header_chain: vec![make_relay_header(5)],
			internal_scheduling_parent_header: make_relay_header(4),
			signed_scheduling_info: None,
		};

		// V2 with single block can be converted to V0
		let v2_single = ParachainBlockData::<TestBlock>::V2 {
			blocks: vec![TestBlock::new(Header::new_from_number(10), vec![])],
			proof: CompactProof { encoded_nodes: vec![] },
			scheduling_proof: scheduling_proof.clone(),
		};
		assert!(v2_single.as_v0().is_some());

		// V2 with multiple blocks cannot be converted to V0
		let v2_multi = ParachainBlockData::<TestBlock>::V2 {
			blocks: vec![
				TestBlock::new(Header::new_from_number(10), vec![]),
				TestBlock::new(Header::new_from_number(11), vec![]),
			],
			proof: CompactProof { encoded_nodes: vec![] },
			scheduling_proof,
		};
		assert!(v2_multi.as_v0().is_none());
	}
}