Skip to content

Commit

Permalink
node-data: add protocol version to Message
Browse files Browse the repository at this point in the history
Resolves #2197
  • Loading branch information
herr-seppia committed Sep 3, 2024
1 parent d71293c commit 1686f55
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
1 change: 1 addition & 0 deletions node-data/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ bs58 = { version = "0.4" }
tracing = "0.1"
anyhow = "1"
thiserror = "1"
varint-rs = "2.2"


[dev-dependencies]
Expand Down
51 changes: 50 additions & 1 deletion node-data/src/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,42 @@ use async_channel::TrySendError;

use self::payload::{Candidate, Ratification, Validation};

use varint_rs::VarintReader;
use varint_rs::VarintWriter;

pub const PROTOCOL_VERSION: Version = Version(1, 0, 0);

#[derive(Debug, Clone)]
/// Represent version (major, minor, patch)
pub struct Version(pub u16, 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_u16_varint(*maj)?;
w.write_u16_varint(*min)?;
w.write_u16_varint(*patch)?;

Ok(())
}

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

/// Topic field position in the message binary representation
pub const TOPIC_FIELD_POS: usize = 8 + 8 + 4;

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

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

pub(crate) 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 +153,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 +175,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 +198,7 @@ impl Serializable for Message {
}
};

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

Expand Down

0 comments on commit 1686f55

Please sign in to comment.