Skip to content

Commit

Permalink
node-data: add protocol version to Message
Browse files Browse the repository at this point in the history
See also #2197
  • Loading branch information
herr-seppia committed Sep 5, 2024
1 parent 1f9e1f2 commit a47ca60
Showing 1 changed file with 47 additions and 2 deletions.
49 changes: 47 additions & 2 deletions node-data/src/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,39 @@ use async_channel::TrySendError;
use self::payload::{Candidate, Ratification, Validation};

/// Topic field position in the message binary representation
pub const TOPIC_FIELD_POS: usize = 8 + 8 + 4;
pub const TOPIC_FIELD_POS: usize = 1 + 2 + 2;
pub const PROTOCOL_VERSION: Version = Version(1, 0, 0);

#[derive(Debug, Clone)]
/// Represent version (major, minor, patch)
pub struct Version(pub u8, pub u16, pub u16);

impl Default for Version {
fn default() -> Self {
PROTOCOL_VERSION
}
}

impl crate::Serializable for Version {
fn write<W: Write>(&self, w: &mut W) -> io::Result<()> {
let Version(maj, min, patch) = self;
w.write_all(&[maj])?;
w.write_all(&min.to_le_bytes())?;
w.write_all(&patch.to_le_bytes())?;

Ok(())
}

fn read<R: Read>(r: &mut R) -> io::Result<Self>
where
Self: Sized,
{
let maj = Self::read_u8(r)?;
let min = Self::read_u16_le(r)?;
let patch = Self::read_u16_le(r)?;
Ok(Self(maj, min, patch))
}
}

pub enum Status {
Past,
Expand All @@ -46,6 +78,7 @@ impl From<Ordering> for Status {
/// Message definition
#[derive(Debug, Default, Clone)]
pub struct Message {
pub version: Version,
topic: Topics,
pub header: ConsensusHeader,
pub payload: Payload,
Expand Down Expand Up @@ -95,6 +128,15 @@ impl Message {
_ => StepName::Proposal.to_step(self.header.iteration),
}
}

pub fn version(&self) -> &Version {
&self.version
}

pub fn with_version(mut self, v: Version) -> Self {
self.version = v;
self
}
}

/// Defines a transport-related properties that determines how the message
Expand All @@ -107,6 +149,7 @@ pub struct Metadata {

impl Serializable for Message {
fn write<W: Write>(&self, w: &mut W) -> io::Result<()> {
self.version.write(w)?;
w.write_all(&[self.topic as u8])?;

match &self.payload {
Expand All @@ -128,6 +171,8 @@ impl Serializable for Message {
where
Self: Sized,
{
let version = Version::read(r)?;

// Read topic
let topic = Topics::from(Self::read_u8(r)?);
let message: Message = match topic {
Expand All @@ -149,7 +194,7 @@ impl Serializable for Message {
}
};

Ok(message)
Ok(message.with_version(version))
}
}

Expand Down

0 comments on commit a47ca60

Please sign in to comment.