referrerpolicy=no-referrer-when-downgrade

cumulus_primitives_spec_messaging/
channel.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// This file is part of Cumulus.
3// SPDX-License-Identifier: Apache-2.0
4
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// 	http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17//! The channel layer: the formats both ends exchange, and each side's local channel state. The
18//! pallet owns the lifecycle and flow-control logic.
19//!
20//! # Formats (consensus surface)
21//!
22//! - [`ChannelMessage`] is the SCALE payload of every channel-stream MMR leaf, inside
23//! [`crate::mmr::leaf_hash`]'s framing.
24//! - [`Register`] is the SCALE payload of every ack-stream leaf: the receiver's complete voice in
25//! the channel, lossy and latest-wins, read out-of-band by the sender.
26//!
27//! [`ChannelMessage::Hello`] (index 0), [`ChannelMessage::CloseChannel`] (index 1) and the
28//! [`Register`] / [`RegisterStatus`] layout are the frozen core: they parse at every channel
29//! version. Variants beyond it (such as [`ChannelMessage::Data`] at index 2) are interpreted under
30//! the session's negotiated channel version. The tests pin their byte layouts.
31//!
32//! # Local state
33//!
34//! Distinct ID types per direction and kind ([`OutChannelId`], [`InChannelId`], [`BroadcastId`])
35//! prevent an outbound channel ID from indexing inbound state, and let the runtime API and
36//! inherent maps fix each entry's discipline by type.
37//!
38//! Helper convention: a bare [`StreamId`] is one of this chain's own streams (a key in its own
39//! commitment tree and sender-side storage). A foreign stream is returned with its owner,
40//! `(ParaId, StreamId)`.
41
42use alloc::vec::Vec;
43
44use codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
45use polkadot_parachain_primitives::primitives::Id as ParaId;
46use scale_info::TypeInfo;
47
48use crate::{
49	mmr::{MessagePosition, MmrFrontier},
50	stream::StreamId,
51};
52
53/// The payload of every channel-stream MMR leaf: session signalling or userspace data.
54#[derive(Clone, Encode, Decode, DecodeWithMemTracking, PartialEq, Eq, Debug, TypeInfo)]
55pub enum ChannelMessage {
56	/// Frozen core (index 0). Opens session `session` at `version`, chosen from the range the
57	/// receiver advertised in [`RegisterStatus::Accepting`].
58	#[codec(index = 0)]
59	Hello { session: u32, version: u8 },
60	/// Frozen core (index 1). Last leaf of a session the sender took part in; nothing further
61	/// until a new session opens.
62	#[codec(index = 1)]
63	CloseChannel { session: u32 },
64	/// Channel version 1 (index 2). Userspace payload bytes, delivered in order. Size bounds apply
65	/// to the whole encoded leaf payload, envelope included.
66	#[codec(index = 2)]
67	Data(Vec<u8>),
68}
69
70/// The receiver's complete voice in a channel, published as a leaf on its `Ack` stream.
71/// Latest-wins: every register is self-contained.
72#[derive(
73	Clone,
74	Copy,
75	Encode,
76	Decode,
77	DecodeWithMemTracking,
78	MaxEncodedLen,
79	PartialEq,
80	Eq,
81	Debug,
82	TypeInfo,
83)]
84pub struct Register {
85	/// Cumulative watermark: all positions `< up_to` of the channel's data stream (data and
86	/// signals alike) have been consumed.
87	pub up_to: MessagePosition,
88	/// Current session status.
89	pub status: RegisterStatus,
90}
91
92/// Receiver-side session status carried in a [`Register`].
93#[derive(
94	Clone,
95	Copy,
96	Encode,
97	Decode,
98	DecodeWithMemTracking,
99	MaxEncodedLen,
100	PartialEq,
101	Eq,
102	Debug,
103	TypeInfo,
104)]
105pub enum RegisterStatus {
106	/// Session `session` accepted; the sender may open it with a [`ChannelMessage::Hello`] at a
107	/// version in `min..=max` and encoded leaf size at most `max_message_size`.
108	#[codec(index = 0)]
109	Accepting { session: u32, min: u8, max: u8, max_message_size: u32 },
110	/// The receiver consumed the session's `Hello`; data may flow.
111	#[codec(index = 1)]
112	Opened,
113	/// Session `session` is closing or closed; `up_to` reports the drain's progress.
114	#[codec(index = 2)]
115	Closed { session: u32 },
116}
117
118/// A channel this chain sends on, named by its recipient.
119#[derive(
120	Clone,
121	Copy,
122	Encode,
123	Decode,
124	DecodeWithMemTracking,
125	MaxEncodedLen,
126	PartialEq,
127	Eq,
128	PartialOrd,
129	Ord,
130	Hash,
131	Debug,
132	TypeInfo,
133)]
134pub struct OutChannelId {
135	pub recipient: ParaId,
136	pub domain: u8,
137	pub num: u16,
138}
139
140impl OutChannelId {
141	/// Our data stream: `Channel { recipient, domain, num }`.
142	pub fn data_stream(&self) -> StreamId {
143		StreamId::Channel { recipient: self.recipient, domain: self.domain, num: self.num }
144	}
145
146	/// The recipient's `Ack { us, domain, num }`, read for its register.
147	pub fn peer_ack_stream(&self, us: ParaId) -> (ParaId, StreamId) {
148		(self.recipient, StreamId::Ack { recipient: us, domain: self.domain, num: self.num })
149	}
150}
151
152/// A channel this chain receives on, named by its sender.
153#[derive(
154	Clone,
155	Copy,
156	Encode,
157	Decode,
158	DecodeWithMemTracking,
159	MaxEncodedLen,
160	PartialEq,
161	Eq,
162	PartialOrd,
163	Ord,
164	Hash,
165	Debug,
166	TypeInfo,
167)]
168pub struct InChannelId {
169	pub sender: ParaId,
170	pub domain: u8,
171	pub num: u16,
172}
173
174impl InChannelId {
175	/// Our `Ack { sender, domain, num }`, where we publish the register.
176	pub fn ack_stream(&self) -> StreamId {
177		StreamId::Ack { recipient: self.sender, domain: self.domain, num: self.num }
178	}
179
180	/// The sender's `Channel { us, domain, num }`, consumed in order.
181	pub fn sender_data_stream(&self, us: ParaId) -> (ParaId, StreamId) {
182		(self.sender, StreamId::Channel { recipient: us, domain: self.domain, num: self.num })
183	}
184}
185
186/// A broadcast stream: its sender plus the discriminator. Broadcast has no recipient, so this is
187/// the stream's global identity.
188#[derive(
189	Clone,
190	Copy,
191	Encode,
192	Decode,
193	DecodeWithMemTracking,
194	MaxEncodedLen,
195	PartialEq,
196	Eq,
197	PartialOrd,
198	Ord,
199	Hash,
200	Debug,
201	TypeInfo,
202)]
203pub struct BroadcastId {
204	pub sender: ParaId,
205	pub domain: u16,
206	pub subdomain: u8,
207	pub num: u32,
208}
209
210impl BroadcastId {
211	/// The sender's `Broadcast { domain, subdomain, num }`, with its owner.
212	pub fn stream(&self) -> (ParaId, StreamId) {
213		(
214			self.sender,
215			StreamId::Broadcast { domain: self.domain, subdomain: self.subdomain, num: self.num },
216		)
217	}
218}
219
220/// A session's negotiated parameters, fixed from `Accepting` to `Closed`.
221#[derive(
222	Clone,
223	Copy,
224	Encode,
225	Decode,
226	DecodeWithMemTracking,
227	MaxEncodedLen,
228	PartialEq,
229	Eq,
230	Debug,
231	TypeInfo,
232)]
233pub struct SessionParams {
234	pub version: u8,
235	pub max_message_size: u32,
236}
237
238/// A register applied by the sender, with its position on the recipient's `Ack` stream (the ack
239/// highwater).
240#[derive(
241	Clone,
242	Copy,
243	Encode,
244	Decode,
245	DecodeWithMemTracking,
246	MaxEncodedLen,
247	PartialEq,
248	Eq,
249	Debug,
250	TypeInfo,
251)]
252pub struct AppliedRegister {
253	pub position: MessagePosition,
254	pub register: Register,
255}
256
257/// The session the sender took part in (sent `Hello` for), its parameters, and whether the sender
258/// has applied its `Opened` register.
259#[derive(
260	Clone,
261	Copy,
262	Encode,
263	Decode,
264	DecodeWithMemTracking,
265	MaxEncodedLen,
266	PartialEq,
267	Eq,
268	Debug,
269	TypeInfo,
270)]
271pub struct OpenSession {
272	pub session: u32,
273	pub params: SessionParams,
274	pub opened: bool,
275}
276
277/// Sender side, per outbound channel.
278#[derive(
279	Clone,
280	Copy,
281	Encode,
282	Decode,
283	DecodeWithMemTracking,
284	MaxEncodedLen,
285	PartialEq,
286	Eq,
287	Debug,
288	Default,
289	TypeInfo,
290)]
291pub struct OutChannelState {
292	/// Own intent: set by `open()`, cleared by `close()`. Survives receiver-initiated closes so
293	/// the sender reopens on the next `Accepting`.
294	pub want_open: bool,
295	/// Latest session number seen in `Accepting` or `Closed` (register validation).
296	pub session: u32,
297	/// Latest register applied, with its position on the recipient's `Ack` stream.
298	pub register: Option<AppliedRegister>,
299	/// The session we took part in (sent `Hello` for), its parameters, and whether we applied its
300	/// `Opened`.
301	pub open: Option<OpenSession>,
302	/// The session we sent `CloseChannel` for: no `Data` in it any more, and no second
303	/// `CloseChannel`.
304	pub closed_session: Option<u32>,
305}
306
307/// Receiver side, per inbound channel.
308#[derive(
309	Clone, Encode, Decode, DecodeWithMemTracking, MaxEncodedLen, PartialEq, Eq, Debug, TypeInfo,
310)]
311pub struct InChannelState {
312	/// Our copy of the sender's channel stream: incoming messages are appended to it; its leaf
313	/// count is the position of the next message to consume.
314	pub frontier: MmrFrontier,
315	/// Current session.
316	pub session: u32,
317	/// Current status.
318	pub status: RegisterStatus,
319	/// The register last published, verbatim (`None` before the first).
320	pub published: Option<Register>,
321	/// The session's parameters, set by the session's `Hello` and cleared when it closes (`Some`
322	/// while `Opened` or `Draining`).
323	pub open: Option<SessionParams>,
324	/// Draining: `Closed` but still consuming toward `CloseChannel { session }`.
325	pub draining: bool,
326}
327
328#[cfg(test)]
329mod tests {
330	use super::*;
331
332	#[test]
333	fn typed_ids_map_to_own_and_foreign_streams() {
334		let us = ParaId::from(1000);
335		let peer = ParaId::from(2000);
336
337		let out_id = OutChannelId { recipient: peer, domain: 1, num: 2 };
338		assert_eq!(out_id.data_stream(), StreamId::Channel { recipient: peer, domain: 1, num: 2 });
339		assert_eq!(
340			out_id.peer_ack_stream(us),
341			(peer, StreamId::Ack { recipient: us, domain: 1, num: 2 }),
342		);
343
344		let in_id = InChannelId { sender: peer, domain: 1, num: 2 };
345		assert_eq!(in_id.ack_stream(), StreamId::Ack { recipient: peer, domain: 1, num: 2 });
346		assert_eq!(
347			in_id.sender_data_stream(us),
348			(peer, StreamId::Channel { recipient: us, domain: 1, num: 2 }),
349		);
350
351		let bcast_id = BroadcastId { sender: peer, domain: 3, subdomain: 4, num: 5 };
352		assert_eq!(
353			bcast_id.stream(),
354			(peer, StreamId::Broadcast { domain: 3, subdomain: 4, num: 5 }),
355		);
356	}
357
358	#[test]
359	fn id_ordering_is_by_peer_then_discriminator() {
360		let a = OutChannelId { recipient: ParaId::from(1), domain: 1, num: 9 };
361		let b = OutChannelId { recipient: ParaId::from(2), domain: 0, num: 0 };
362		let c = OutChannelId { recipient: ParaId::from(2), domain: 0, num: 1 };
363		assert!(a < b && b < c);
364	}
365
366	#[test]
367	fn channel_message_frozen_core_variant_indices() {
368		assert_eq!(
369			ChannelMessage::Hello { session: 3, version: 7 }.encode(),
370			vec![0x00, 0x03, 0, 0, 0, 0x07],
371		);
372		assert_eq!(ChannelMessage::CloseChannel { session: 5 }.encode(), vec![0x01, 0x05, 0, 0, 0]);
373		assert_eq!(ChannelMessage::Data(vec![0xAA]).encode(), vec![0x02, 0x04, 0xAA]);
374	}
375
376	#[test]
377	fn data_at_the_protocol_bound_takes_five_bytes_of_framing() {
378		// The bound is on the encoded leaf. At this size the compact length takes 4 bytes, so 5
379		// bytes less data fill it exactly and one more overflows it.
380		let max = crate::fetch::MAX_SPECULATIVE_MESSAGE_LEN as usize;
381		assert_eq!(ChannelMessage::Data(vec![0; max - 5]).encoded_size(), max);
382		assert_eq!(ChannelMessage::Data(vec![0; max - 4]).encoded_size(), max + 1);
383	}
384
385	#[test]
386	fn register_frozen_layout() {
387		let accepting = Register {
388			up_to: MessagePosition(5),
389			status: RegisterStatus::Accepting {
390				session: 1,
391				min: 1,
392				max: 3,
393				max_message_size: 1024,
394			},
395		};
396		assert_eq!(
397			accepting.encode(),
398			vec![
399				0x05, 0, 0, 0, 0, 0, 0, 0,    // up_to: u64 LE = 5
400				0x00, // status: Accepting (index 0)
401				0x01, 0, 0, 0,    // session: u32 LE = 1
402				0x01, // min: u8 = 1
403				0x03, // max: u8 = 3
404				0x00, 0x04, 0, 0, // max_message_size: u32 LE = 1024
405			],
406		);
407		assert_eq!(Register::decode(&mut &accepting.encode()[..]).unwrap(), accepting);
408
409		let opened = Register { up_to: MessagePosition(9), status: RegisterStatus::Opened };
410		assert_eq!(opened.encode(), vec![0x09, 0, 0, 0, 0, 0, 0, 0, 0x01]);
411		assert_eq!(Register::decode(&mut &opened.encode()[..]).unwrap(), opened);
412
413		let closed =
414			Register { up_to: MessagePosition(12), status: RegisterStatus::Closed { session: 2 } };
415		assert_eq!(closed.encode(), vec![0x0c, 0, 0, 0, 0, 0, 0, 0, 0x02, 0x02, 0, 0, 0]);
416		assert_eq!(Register::decode(&mut &closed.encode()[..]).unwrap(), closed);
417	}
418}