1use alloc::{collections::BTreeMap, vec::Vec};
30use codec::{Compact, Decode, DecodeWithMemTracking, Encode, Error as CodecError, Input};
31use scale_info::TypeInfo;
32
33use crate::{
34 channel::{BroadcastId, InChannelId, OutChannelId},
35 mmr::{MessagePosition, MmrFrontier},
36};
37
38pub const INHERENT_IDENTIFIER: sp_inherents::InherentIdentifier = *b"specmsg0";
40
41pub type Payload = Vec<u8>;
42
43#[derive(Clone, Encode, Decode, DecodeWithMemTracking, PartialEq, Eq, Debug, TypeInfo, Default)]
46pub struct ConsumedStreams {
47 pub channels: BTreeMap<InChannelId, MmrFrontier>,
51 pub registers: BTreeMap<OutChannelId, MessagePosition>,
54 pub events: BTreeMap<BroadcastId, MessagePosition>,
57}
58
59impl ConsumedStreams {
60 pub fn is_empty(&self) -> bool {
61 self.channels.is_empty() && self.registers.is_empty() && self.events.is_empty()
62 }
63
64 pub fn len(&self) -> usize {
65 self.channels.len() + self.registers.len() + self.events.len()
66 }
67}
68
69#[derive(Clone, Encode, Decode, DecodeWithMemTracking, PartialEq, Eq, Debug, TypeInfo, Default)]
74pub struct LossyRead {
75 pub frontier: MmrFrontier,
76 pub payloads: Vec<Payload>,
77}
78
79#[derive(Clone, Encode, PartialEq, Eq, Debug, TypeInfo, Default)]
85pub struct MessagingInherentData {
86 pub channels: BTreeMap<InChannelId, Vec<Payload>>,
89 pub registers: BTreeMap<OutChannelId, LossyRead>,
91 pub events: BTreeMap<BroadcastId, LossyRead>,
93}
94
95impl MessagingInherentData {
96 pub fn is_empty(&self) -> bool {
98 self.channels.is_empty() && self.registers.is_empty() && self.events.is_empty()
99 }
100
101 pub fn len(&self) -> usize {
103 self.channels.len() + self.registers.len() + self.events.len()
104 }
105}
106
107fn mem_size_of_btree<T>(len: u32) -> usize {
109 use core::mem::size_of;
110
111 const B: usize = 6;
112 const CAPACITY: usize = 2 * B - 1;
113 const MIN_LEN_AFTER_SPLIT: usize = B - 1;
114
115 if len == 0 {
116 return 0;
117 }
118 let leaf_node_size = size_of::<(usize, u16, u16, [T; CAPACITY])>();
119 let internal_node_size = leaf_node_size + size_of::<[usize; 2 * B]>();
120 let num_nodes = (len as usize).saturating_div((CAPACITY + MIN_LEN_AFTER_SPLIT) * 2 / 3);
121 if num_nodes == 0 {
122 return leaf_node_size;
123 }
124 num_nodes.saturating_mul(internal_node_size)
125}
126
127fn decode_strict_map<K: Decode + Ord, V: Decode, I: Input>(
128 input: &mut I,
129) -> Result<BTreeMap<K, V>, CodecError> {
130 let Compact(len) = Compact::<u32>::decode(input)?;
131 input.descend_ref()?;
132 let result = (|| {
133 input.on_before_alloc_mem(mem_size_of_btree::<(K, V)>(len))?;
134 let mut map = BTreeMap::new();
135 for _ in 0..len {
136 let (key, value) = <(K, V)>::decode(input)?;
137 if map.last_key_value().is_some_and(|(previous, _)| previous >= &key) {
138 return Err("MessagingInherentData: map keys must be strictly increasing".into());
139 }
140 map.insert(key, value);
141 }
142 Ok(map)
143 })();
144 input.ascend_ref();
145 result
146}
147
148impl Decode for MessagingInherentData {
149 fn decode<I: Input>(input: &mut I) -> Result<Self, CodecError> {
150 Ok(Self {
151 channels: decode_strict_map(input)?,
152 registers: decode_strict_map(input)?,
153 events: decode_strict_map(input)?,
154 })
155 }
156}
157
158impl DecodeWithMemTracking for MessagingInherentData {}
159
160#[cfg(feature = "std")]
163#[async_trait::async_trait]
164impl sp_inherents::InherentDataProvider for MessagingInherentData {
165 async fn provide_inherent_data(
166 &self,
167 inherent_data: &mut sp_inherents::InherentData,
168 ) -> Result<(), sp_inherents::Error> {
169 if self.is_empty() {
170 return Ok(());
171 }
172 inherent_data.put_data(INHERENT_IDENTIFIER, self)
173 }
174
175 async fn try_handle_error(
176 &self,
177 _: &sp_inherents::InherentIdentifier,
178 _: &[u8],
179 ) -> Option<Result<(), sp_inherents::Error>> {
180 None
182 }
183}
184
185#[cfg(test)]
186mod tests {
187 use super::*;
188 use polkadot_parachain_primitives::primitives::Id as ParaId;
189
190 fn sample_inherent() -> MessagingInherentData {
191 let in_id = InChannelId { sender: ParaId::from(1000), domain: 0, num: 1 };
192 let out_id = OutChannelId { recipient: ParaId::from(2000), domain: 0, num: 0 };
193 let bcast_id = BroadcastId { sender: ParaId::from(3000), domain: 1, subdomain: 0, num: 7 };
194 MessagingInherentData {
195 channels: BTreeMap::from([(in_id, alloc::vec![alloc::vec![1, 2, 3]])]),
196 registers: BTreeMap::from([(
197 out_id,
198 LossyRead { frontier: MmrFrontier::new(), payloads: alloc::vec![alloc::vec![4]] },
199 )]),
200 events: BTreeMap::from([(
201 bcast_id,
202 LossyRead { frontier: MmrFrontier::new(), payloads: alloc::vec![alloc::vec![5]] },
203 )]),
204 }
205 }
206
207 #[test]
208 fn empty_data_places_no_inherent_and_non_empty_round_trips() {
209 use sp_inherents::InherentDataProvider;
210 let mut inherent_data = sp_inherents::InherentData::new();
211 futures::executor::block_on(
212 MessagingInherentData::default().provide_inherent_data(&mut inherent_data),
213 )
214 .expect("providing empty data succeeds");
215 assert_eq!(
216 inherent_data.get_data::<MessagingInherentData>(&INHERENT_IDENTIFIER).unwrap(),
217 None,
218 "absent = consumed nothing"
219 );
220
221 let data = sample_inherent();
222 let mut inherent_data = sp_inherents::InherentData::new();
223 futures::executor::block_on(data.provide_inherent_data(&mut inherent_data))
224 .expect("providing data succeeds");
225 assert_eq!(
226 inherent_data.get_data::<MessagingInherentData>(&INHERENT_IDENTIFIER).unwrap(),
227 Some(data)
228 );
229 }
230
231 #[test]
232 fn inherent_round_trips_and_rejects_unsorted_or_duplicate_keys() {
233 let data = sample_inherent();
234 assert_eq!(MessagingInherentData::decode(&mut &data.encode()[..]).unwrap(), data);
235 assert_eq!(data.len(), 3);
236
237 let a = InChannelId { sender: ParaId::from(1000), domain: 0, num: 0 };
238 let b = InChannelId { sender: ParaId::from(2000), domain: 0, num: 0 };
239
240 let unsorted = (
242 alloc::vec![(b, alloc::vec![alloc::vec![1u8]]), (a, alloc::vec![alloc::vec![2u8]])],
243 Vec::<(OutChannelId, LossyRead)>::new(),
244 Vec::<(BroadcastId, LossyRead)>::new(),
245 )
246 .encode();
247 assert!(MessagingInherentData::decode(&mut &unsorted[..]).is_err());
248
249 let duplicate = (
251 alloc::vec![(a, alloc::vec![alloc::vec![1u8]]), (a, alloc::vec![alloc::vec![2u8]])],
252 Vec::<(OutChannelId, LossyRead)>::new(),
253 Vec::<(BroadcastId, LossyRead)>::new(),
254 )
255 .encode();
256 assert!(MessagingInherentData::decode(&mut &duplicate[..]).is_err());
257 }
258
259 #[test]
260 fn register_and_event_keys_must_strictly_increase() {
261 let o1 = OutChannelId { recipient: ParaId::from(1000), domain: 0, num: 0 };
262 let o2 = OutChannelId { recipient: ParaId::from(2000), domain: 0, num: 0 };
263 let b1 = BroadcastId { sender: ParaId::from(1000), domain: 0, subdomain: 0, num: 0 };
264 let b2 = BroadcastId { sender: ParaId::from(2000), domain: 0, subdomain: 0, num: 0 };
265 let read = LossyRead::default();
266 let no_channels = Vec::<(InChannelId, Vec<Payload>)>::new;
267
268 for registers in [vec![(o2, read.clone()), (o1, read.clone())], vec![(o1, read.clone()); 2]]
269 {
270 let bytes = (no_channels(), registers, Vec::<(BroadcastId, LossyRead)>::new()).encode();
271 assert!(MessagingInherentData::decode(&mut &bytes[..]).is_err());
272 }
273 for events in [vec![(b2, read.clone()), (b1, read.clone())], vec![(b1, read.clone()); 2]] {
274 let bytes = (no_channels(), Vec::<(OutChannelId, LossyRead)>::new(), events).encode();
275 assert!(MessagingInherentData::decode(&mut &bytes[..]).is_err());
276 }
277 }
278
279 #[test]
280 fn inherent_memory_limit_accounts_for_map_nodes() {
281 use codec::DecodeWithMemLimit;
282
283 let key = InChannelId { sender: ParaId::from(1000), domain: 0, num: 0 };
284 let data = MessagingInherentData {
285 channels: BTreeMap::from([(key, Vec::new())]),
286 ..Default::default()
287 };
288 let encoded = data.encode();
289 let vec_bytes = data.channels.len() * core::mem::size_of::<(InChannelId, Vec<Payload>)>();
290 let map_bytes =
291 mem_size_of_btree::<(InChannelId, Vec<Payload>)>(data.channels.len() as u32);
292 let small_limit = vec_bytes + 1;
293 assert!(small_limit < map_bytes);
294 assert!(Vec::<(InChannelId, Vec<Payload>)>::decode_with_mem_limit(
295 &mut &encoded[..],
296 small_limit,
297 )
298 .is_ok());
299 assert!(
300 MessagingInherentData::decode_with_mem_limit(&mut &encoded[..], small_limit).is_err()
301 );
302 assert!(MessagingInherentData::decode_with_mem_limit(&mut &encoded[..], map_bytes).is_err());
303 assert_eq!(
304 MessagingInherentData::decode_with_mem_limit(&mut &encoded[..], map_bytes + 1)
305 .expect("the limit exceeds the map estimate; qed"),
306 data,
307 );
308 }
309
310 #[test]
311 fn strict_map_balances_depth_on_success_and_errors() {
312 struct TrackedInput<'a> {
313 bytes: &'a [u8],
314 depth: usize,
315 fail_allocation: bool,
316 }
317
318 impl Input for TrackedInput<'_> {
319 fn remaining_len(&mut self) -> Result<Option<usize>, CodecError> {
320 self.bytes.remaining_len()
321 }
322
323 fn read(&mut self, into: &mut [u8]) -> Result<(), CodecError> {
324 self.bytes.read(into)
325 }
326
327 fn descend_ref(&mut self) -> Result<(), CodecError> {
328 self.depth += 1;
329 Ok(())
330 }
331
332 fn ascend_ref(&mut self) {
333 self.depth -= 1;
334 }
335
336 fn on_before_alloc_mem(&mut self, _: usize) -> Result<(), CodecError> {
337 if self.fail_allocation {
338 return Err("allocation rejected".into());
339 }
340 Ok(())
341 }
342 }
343
344 let valid = vec![(1u8, 0u8)].encode();
345 let mut input = TrackedInput { bytes: &valid, depth: 0, fail_allocation: false };
346 assert_eq!(
347 decode_strict_map::<u8, u8, _>(&mut input)
348 .expect("the encoded map is ordered and complete; qed"),
349 BTreeMap::from([(1, 0)])
350 );
351 assert_eq!(input.depth, 0);
352
353 for (bytes, fail_allocation) in [
354 (valid, true),
355 (Compact(1u32).encode(), false),
356 (vec![(2u8, 0u8), (1, 0)].encode(), false),
357 (vec![(1u8, 0u8), (1, 0)].encode(), false),
358 ] {
359 let mut input = TrackedInput { bytes: &bytes, depth: 0, fail_allocation };
360 assert!(decode_strict_map::<u8, u8, _>(&mut input).is_err());
361 assert_eq!(input.depth, 0);
362 }
363 }
364
365 #[test]
366 fn inherent_frozen_layout() {
367 let empty_frontier = [0u8, 0, 0, 0, 0, 0, 0, 0, 0x00]; let read =
369 LossyRead { frontier: MmrFrontier::new(), payloads: alloc::vec![alloc::vec![4]] };
370 let read_bytes = [&empty_frontier[..], &[0x04, 0x04, 0x04]].concat();
371 assert_eq!(read.encode(), read_bytes);
372
373 let data = sample_inherent();
374 let expected = [
375 &[0x04, 0xE8, 0x03, 0, 0, 0x00, 0x01, 0x00, 0x04, 0x0C, 1, 2, 3][..],
377 &[0x04, 0xD0, 0x07, 0, 0, 0x00, 0x00, 0x00],
379 &empty_frontier,
380 &[0x04, 0x04, 0x04],
381 &[0x04, 0xB8, 0x0B, 0, 0, 0x01, 0x00, 0x00, 0x07, 0, 0, 0],
383 &empty_frontier,
384 &[0x04, 0x04, 0x05],
385 ]
386 .concat();
387 assert_eq!(data.encode(), expected);
388 assert_eq!(MessagingInherentData::decode(&mut &expected[..]).unwrap(), data);
389 }
390}