Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SSZ implementation for alloy primitives #407

Merged
merged 10 commits into from
Nov 8, 2023
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ syn-solidity = { version = "0.4.2", path = "crates/syn-solidity", default-featur
serde = { version = "1.0", default-features = false, features = ["alloc"] }
serde_json = { version = "1.0", default-features = false, features = ["alloc"] }

# ssz
ethereum_ssz = { version = "0.5.3" }

# macros
proc-macro2 = "1.0"
quote = "1.0"
Expand Down
5 changes: 5 additions & 0 deletions crates/primitives/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ alloy-rlp = { workspace = true, optional = true }
# serde
serde = { workspace = true, optional = true, features = ["derive"] }

# ssz
ethereum_ssz = { workspace = true, optional = true}


# getrandom
getrandom = { workspace = true, optional = true }

Expand Down Expand Up @@ -68,6 +72,7 @@ getrandom = ["dep:getrandom"]
rand = ["dep:rand", "getrandom", "ruint/rand"]
rlp = ["dep:alloy-rlp", "ruint/alloy-rlp"]
serde = ["dep:serde", "bytes/serde", "hex/serde", "ruint/serde"]
ssz = ["dep:ethereum_ssz"]
loocapro marked this conversation as resolved.
Show resolved Hide resolved
arbitrary = [
"std",
"ruint/arbitrary",
Expand Down
75 changes: 75 additions & 0 deletions crates/primitives/src/bits/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -684,6 +684,81 @@ macro_rules! bytes {
}};
}

/// Implements the `ssz::Decode` and `ssz::Encode` traits for a given type
/// with a specified fixed length.
///
/// This macro is designed to be used with types that have a known, fixed size
/// when encoded or decoded using the Simple Serialize (SSZ) encoding scheme.
/// It generates implementations of the `ssz::Decode` and `ssz::Encode` traits
/// which enforce that the SSZ-encoded byte representation of the type has a
/// length exactly equal to the specified `fixed_len`.
///
/// The `ssz::Decode::from_ssz_bytes` function provided by this implementation
/// will produce an error if the length of the byte slice provided does not
/// match `fixed_len`. Conversely, the `ssz::Encode::ssz_append` function will
/// append exactly `fixed_len` bytes to the provided buffer.
#[macro_export]
#[cfg(feature = "ssz")]
macro_rules! impl_ssz_fixed_len {
loocapro marked this conversation as resolved.
Show resolved Hide resolved
($type:ty, $fixed_len:expr) => {
impl ssz::Decode for $type {
loocapro marked this conversation as resolved.
Show resolved Hide resolved
fn is_ssz_fixed_len() -> bool {
true
}

fn ssz_fixed_len() -> usize {
$fixed_len
}

fn from_ssz_bytes(bytes: &[u8]) -> Result<Self, ssz::DecodeError> {
let len = bytes.len();
let expected: usize = <$type as Decode>::ssz_fixed_len();

if len != expected {
Err(ssz::DecodeError::InvalidByteLength { len, expected })
} else {
Ok(<$type>::from_slice(bytes))
}
}
}

impl ssz::Encode for $type {
fn is_ssz_fixed_len() -> bool {
true
}

fn ssz_fixed_len() -> usize {
$fixed_len
}

fn ssz_bytes_len(&self) -> usize {
<$type as Encode>::ssz_fixed_len()
}

fn ssz_append(&self, buf: &mut alloc::vec::Vec<u8>) {
buf.extend_from_slice(self.as_slice());
}
}
};
}

#[cfg(test)]
#[macro_export]
#[cfg(feature = "ssz")]
macro_rules! test_encode_decode_ssz {
loocapro marked this conversation as resolved.
Show resolved Hide resolved
loocapro marked this conversation as resolved.
Show resolved Hide resolved
($test_name:ident, $type:ty, [$( $value:expr ),*]) => {
#[test]
fn $test_name() {
$(
let expected: $type = $value;
let encoded = ssz::Encode::as_ssz_bytes(&expected);
let actual: $type = ssz::Decode::from_ssz_bytes(&encoded).unwrap();
assert_eq!(expected, actual, "Failed for value: {:?}", $value);
)*
}
};
}

#[cfg(test)]
mod tests {
use crate::{hex, Address, Bytes, FixedBytes};
Expand Down
3 changes: 3 additions & 0 deletions crates/primitives/src/bits/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,6 @@ mod rlp;

#[cfg(feature = "serde")]
mod serde;

#[cfg(feature = "ssz")]
mod ssz;
93 changes: 93 additions & 0 deletions crates/primitives/src/bits/ssz.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
use crate::{Address, Bloom, FixedBytes};
use alloc::vec::Vec;
use ssz::{Decode, DecodeError, Encode};

impl<const N: usize> Encode for FixedBytes<N> {
fn is_ssz_fixed_len() -> bool {
true
}

fn ssz_bytes_len(&self) -> usize {
N
}

fn ssz_append(&self, buf: &mut Vec<u8>) {
buf.extend_from_slice(&self.0);
}
fn as_ssz_bytes(&self) -> Vec<u8> {
self.0.to_vec()
}
}

impl<const N: usize> Decode for FixedBytes<N> {
fn is_ssz_fixed_len() -> bool {
true
}

fn ssz_fixed_len() -> usize {
N
}

fn from_ssz_bytes(bytes: &[u8]) -> Result<Self, DecodeError> {
if bytes.len() != N {
return Err(DecodeError::InvalidByteLength { len: bytes.len(), expected: N });
}

let mut fixed_array = [0u8; N];
fixed_array.copy_from_slice(bytes);

Ok(FixedBytes::<N>(fixed_array))
}
}

impl_ssz_fixed_len!(Address, 20);
impl_ssz_fixed_len!(Bloom, 256);

#[cfg(test)]
mod tests {
use crate::{Address, Bloom, FixedBytes};

test_encode_decode_ssz!(
test_encode_decode_fixed_bytes32,
FixedBytes<32>,
[fixed_bytes!("a1de988600a42c4b4ab089b619297c17d53cffae5d5120d82d8a92d0bb3b78f2")]
);

test_encode_decode_ssz!(
test_encode_decode_fixed_bytes4,
FixedBytes<4>,
[fixed_bytes!("01234567")]
);

test_encode_decode_ssz!(
test_encode_decode_bloom,
Bloom,
[bloom!(
"00000000000000000000000000000000
00000000100000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
00000002020000000000000000000000
00000000000000000000000800000000
10000000000000000000000000000000
00000000000000000000001000000000
00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000"
)]
);
test_encode_decode_ssz!(
test_encode_decode_address,
Address,
[
address!("2222222222222222222222222222222222222222"),
address!("0000000000000000000000000000000000012321"),
address!("0000000000000000000000000000000000000000")
]
);
}
3 changes: 3 additions & 0 deletions crates/primitives/src/bytes/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ mod rlp;
#[cfg(feature = "serde")]
mod serde;

#[cfg(feature = "ssz")]
mod ssz;

/// Wrapper type around [`bytes::Bytes`] to support "0x" prefixed hex strings.
#[derive(Clone, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
#[repr(transparent)]
Expand Down
43 changes: 43 additions & 0 deletions crates/primitives/src/bytes/ssz.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
use crate::Bytes;
use alloc::vec::Vec;
use ssz::{Decode, DecodeError, Encode};

impl Encode for Bytes {
fn is_ssz_fixed_len() -> bool {
false
}

fn ssz_bytes_len(&self) -> usize {
self.0.len()
}

fn ssz_append(&self, buf: &mut Vec<u8>) {
buf.extend_from_slice(&self.0);
}
fn as_ssz_bytes(&self) -> Vec<u8> {
self.0.to_vec()
}
}

impl Decode for Bytes {
fn is_ssz_fixed_len() -> bool {
false
}

fn from_ssz_bytes(bytes: &[u8]) -> Result<Self, DecodeError> {
Ok(bytes.to_vec().into())
}
}

#[cfg(test)]
mod tests {
use crate::test_encode_decode_ssz;

use super::*;

test_encode_decode_ssz!(
test_encode_decode_bytes,
Bytes,
[bytes!("01234567"), bytes!("6394198df16000526103ff60206004601c335afa6040516060f3")]
);
}
3 changes: 3 additions & 0 deletions crates/primitives/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,9 @@ pub mod private {
#[cfg(feature = "rlp")]
pub use alloy_rlp;

#[cfg(feature = "ssz")]
pub use ssz;

#[cfg(feature = "serde")]
pub use serde;

Expand Down