Skip to content

Commit

Permalink
serde: for MerklePath, ValuePath, and RootPath
Browse files Browse the repository at this point in the history
  • Loading branch information
hackaugusto authored and bobbinth committed Dec 21, 2023
1 parent 8bb080a commit 4758e06
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions src/merkle/path.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use super::{vec, InnerNodeInfo, MerkleError, NodeIndex, Rpo256, RpoDigest, Vec};
use core::ops::{Deref, DerefMut};
use winter_utils::{ByteReader, Deserializable, DeserializationError, Serializable};

// MERKLE PATH
// ================================================================================================
Expand All @@ -17,6 +18,7 @@ impl MerklePath {

/// Creates a new Merkle path from a list of nodes.
pub fn new(nodes: Vec<RpoDigest>) -> Self {
assert!(nodes.len() <= u8::MAX.into(), "MerklePath may have at most 256 items");
Self { nodes }
}

Expand Down Expand Up @@ -189,6 +191,54 @@ pub struct RootPath {
pub path: MerklePath,
}

// SERILIZATION
// ================================================================================================
impl Serializable for MerklePath {
fn write_into<W: winter_utils::ByteWriter>(&self, target: &mut W) {
assert!(self.nodes.len() <= u8::MAX.into(), "Length enforced in the construtor");
target.write_u8(self.nodes.len() as u8);
self.nodes.write_into(target);
}
}

impl Deserializable for MerklePath {
fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
let count = source.read_u8()?.into();
let nodes = RpoDigest::read_batch_from(source, count)?;
Ok(Self { nodes })
}
}

impl Serializable for ValuePath {
fn write_into<W: winter_utils::ByteWriter>(&self, target: &mut W) {
self.value.write_into(target);
self.path.write_into(target);
}
}

impl Deserializable for ValuePath {
fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
let value = RpoDigest::read_from(source)?;
let path = MerklePath::read_from(source)?;
Ok(Self { value, path })
}
}

impl Serializable for RootPath {
fn write_into<W: winter_utils::ByteWriter>(&self, target: &mut W) {
self.root.write_into(target);
self.path.write_into(target);
}
}

impl Deserializable for RootPath {
fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
let root = RpoDigest::read_from(source)?;
let path = MerklePath::read_from(source)?;
Ok(Self { root, path })
}
}

// TESTS
// ================================================================================================

Expand Down

0 comments on commit 4758e06

Please sign in to comment.