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 all 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", default-features = false }

# macros
proc-macro2 = "1.0"
quote = "1.0"
Expand Down
9 changes: 7 additions & 2 deletions crates/primitives/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ 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,14 +71,16 @@ 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", "std"]
arbitrary = [
"std",
"ruint/arbitrary",
"ruint/proptest",
"dep:arbitrary",
"dep:derive_arbitrary",
"dep:proptest",
"dep:proptest-derive",
"ruint/arbitrary",
"ruint/proptest",
"ethereum_ssz?/arbitrary",
]

# `const-hex` compatibility feature for `hex`.
Expand Down
60 changes: 60 additions & 0 deletions crates/primitives/src/bits/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ macro_rules! wrap_fixed_bytes {
$crate::impl_rlp!($name, $n);
$crate::impl_serde!($name);
$crate::impl_arbitrary!($name, $n);
$crate::impl_ssz_fixed_len!($name, $n);
$crate::impl_rand!($name);

impl $name {
Expand Down Expand Up @@ -608,6 +609,65 @@ macro_rules! impl_arbitrary {
($t:ty, $n:literal) => {};
}

#[doc(hidden)]
#[macro_export]
#[cfg(feature = "ssz")]
macro_rules! impl_ssz_fixed_len {
($type:ty, $fixed_len:expr) => {
impl $crate::private::ssz::Encode for $type {
#[inline]
fn is_ssz_fixed_len() -> bool {
true
}

#[inline]
fn ssz_fixed_len() -> usize {
$fixed_len
}

#[inline]
fn ssz_bytes_len(&self) -> usize {
<$type as $crate::private::ssz::Encode>::ssz_fixed_len()
}

#[inline]
fn ssz_append(&self, buf: &mut $crate::private::Vec<u8>) {
buf.extend_from_slice(self.as_slice());
}
}

impl $crate::private::ssz::Decode for $type {
#[inline]
fn is_ssz_fixed_len() -> bool {
true
}

#[inline]
fn ssz_fixed_len() -> usize {
$fixed_len
}

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

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

#[doc(hidden)]
#[macro_export]
#[cfg(not(feature = "ssz"))]
macro_rules! impl_ssz_fixed_len {
($t:ty, $n:literal) => {};
}

macro_rules! fixed_bytes_macros {
($d:tt $($(#[$attr:meta])* macro $name:ident($ty:ident $($rest:tt)*);)*) => {$(
/// Converts a sequence of string literals containing hex-encoded data
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;
110 changes: 110 additions & 0 deletions crates/primitives/src/bits/ssz.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
use crate::FixedBytes;
use alloc::vec::Vec;
use ssz::{Decode, DecodeError, Encode};

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

#[inline]
fn ssz_bytes_len(&self) -> usize {
N
}

#[inline]
fn ssz_append(&self, buf: &mut Vec<u8>) {
buf.extend_from_slice(&self.0);
}

#[inline]
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))
}
}

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

macro_rules! test_encode_decode_ssz {
($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);
)*
}
};
}

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
62 changes: 62 additions & 0 deletions crates/primitives/src/bytes/ssz.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
use crate::Bytes;
use alloc::vec::Vec;
use ssz::{Decode, DecodeError, Encode};

impl Encode for Bytes {
#[inline]
fn is_ssz_fixed_len() -> bool {
false
}

#[inline]
fn ssz_bytes_len(&self) -> usize {
self.0.len()
}

#[inline]
fn ssz_append(&self, buf: &mut Vec<u8>) {
buf.extend_from_slice(&self.0);
}

#[inline]
fn as_ssz_bytes(&self) -> Vec<u8> {
self.0.to_vec()
}
}

impl Decode for Bytes {
#[inline]
fn is_ssz_fixed_len() -> bool {
false
}

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

#[cfg(test)]
mod tests {
use super::*;

macro_rules! test_encode_decode_ssz {
($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);
)*
}
};
}

test_encode_decode_ssz!(
test_encode_decode_bytes,
Bytes,
[bytes!("01234567"), bytes!("6394198df16000526103ff60206004601c335afa6040516060f3")]
);
}
4 changes: 4 additions & 0 deletions crates/primitives/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ pub type B160 = FixedBytes<20>;
// Not public API.
#[doc(hidden)]
pub mod private {
pub use alloc::vec::Vec;
pub use core::{
self,
borrow::{Borrow, BorrowMut},
Expand All @@ -106,6 +107,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
1 change: 1 addition & 0 deletions rustfmt.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@ imports_granularity = "Crate"
wrap_comments = true
format_code_in_doc_comments = true
doc_comment_code_block_width = 100
format_macro_matchers = true
Loading