Skip to content

Commit

Permalink
complete rust fmt on internal ssz-rs
Browse files Browse the repository at this point in the history
  • Loading branch information
willemolding committed Jul 19, 2023
1 parent 08b499b commit 2e3518e
Show file tree
Hide file tree
Showing 14 changed files with 58 additions and 54 deletions.
5 changes: 1 addition & 4 deletions finality-client/libs/ssz-rs/ssz-rs-derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ fn derive_deserialize_impl(data: &Data) -> TokenStream {

Ok(container)
}
};
}
}
_ => unimplemented!(
"this type of struct is currently not supported by this derive macro"
Expand Down Expand Up @@ -469,12 +469,9 @@ fn derive_treeify_impl(data: &Data) -> TokenStream {
quote_spanned! { variant.span() =>
Self::#variant_name(value) => {
let mut tree = value.to_merkle_tree()?;

let selector = #i;
let data_root = value.hash_tree_root()?;
tree.push(ssz_rs::__internal::mix_in_selector_tree(&data_root, selector));


Ok(tree)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,15 +50,15 @@ fn main() {
Ok(encoding) => encoding,
Err(err) => {
eprintln!("some error encoding: {err}");
return;
return
}
};

let mut restored_example = match Foo::<4>::deserialize(&encoding) {
Ok(value) => value,
Err(err) => {
eprintln!("some error decoding: {err}");
return;
return
}
};

Expand Down
8 changes: 4 additions & 4 deletions finality-client/libs/ssz-rs/ssz-rs/src/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ macro_rules! define_ssz_for_array_of_size {
{
fn serialize(&self, buffer: &mut Vec<u8>) -> Result<usize, SerializeError> {
if $n == 0 {
return Err(TypeError::InvalidBound($n).into());
return Err(TypeError::InvalidBound($n).into())
}
serialize_composite(self, buffer)
}
Expand All @@ -47,7 +47,7 @@ macro_rules! define_ssz_for_array_of_size {
{
fn deserialize(encoding: &[u8]) -> Result<Self, DeserializeError> {
if $n == 0 {
return Err(TypeError::InvalidBound($n).into());
return Err(TypeError::InvalidBound($n).into())
}

if !T::is_variable_size() {
Expand All @@ -56,13 +56,13 @@ macro_rules! define_ssz_for_array_of_size {
return Err(DeserializeError::ExpectedFurtherInput {
provided: encoding.len(),
expected: expected_length,
});
})
}
if encoding.len() > expected_length {
return Err(DeserializeError::AdditionalInput {
provided: encoding.len(),
expected: expected_length,
});
})
}
}
let elements = deserialize_homogeneous_composite(encoding)?;
Expand Down
10 changes: 5 additions & 5 deletions finality-client/libs/ssz-rs/ssz-rs/src/bitlist.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ impl<const N: usize> Bitlist<N> {
with_length_bit: bool,
) -> Result<usize, SerializeError> {
if self.len() > N {
return Err(InstanceError::Bounded { bound: N, provided: self.len() }.into());
return Err(InstanceError::Bounded { bound: N, provided: self.len() }.into())
}
let start_len = buffer.len();
buffer.extend_from_slice(self.as_raw_slice());
Expand Down Expand Up @@ -151,14 +151,14 @@ impl<const N: usize> Deserialize for Bitlist<N> {
fn deserialize(encoding: &[u8]) -> Result<Self, DeserializeError> {
let max_len = byte_length(N);
if encoding.is_empty() {
return Err(DeserializeError::ExpectedFurtherInput { provided: 0, expected: max_len });
return Err(DeserializeError::ExpectedFurtherInput { provided: 0, expected: max_len })
}

if encoding.len() > max_len {
return Err(DeserializeError::AdditionalInput {
provided: encoding.len(),
expected: max_len,
});
})
}

let (last_byte, prefix) = encoding.split_last().unwrap();
Expand All @@ -167,15 +167,15 @@ impl<const N: usize> Deserialize for Bitlist<N> {
let high_bit_index = 8 - last.trailing_zeros();

if !last[high_bit_index - 1] {
return Err(DeserializeError::InvalidByte(*last_byte));
return Err(DeserializeError::InvalidByte(*last_byte))
}

for bit in last.iter().take(high_bit_index - 1) {
result.push(*bit);
}
// TODO: this seems redundant...
if result.len() > N {
return Err(InstanceError::Bounded { bound: N, provided: result.len() }.into());
return Err(InstanceError::Bounded { bound: N, provided: result.len() }.into())
}
Ok(Self(result))
}
Expand Down
10 changes: 5 additions & 5 deletions finality-client/libs/ssz-rs/ssz-rs/src/bitvector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ impl<const N: usize> Sized for Bitvector<N> {
impl<const N: usize> Serialize for Bitvector<N> {
fn serialize(&self, buffer: &mut Vec<u8>) -> Result<usize, SerializeError> {
if N == 0 {
return Err(TypeError::InvalidBound(N).into());
return Err(TypeError::InvalidBound(N).into())
}
let bytes_to_write = Self::size_hint();
buffer.reserve(bytes_to_write);
Expand All @@ -141,21 +141,21 @@ impl<const N: usize> Serialize for Bitvector<N> {
impl<const N: usize> Deserialize for Bitvector<N> {
fn deserialize(encoding: &[u8]) -> Result<Self, DeserializeError> {
if N == 0 {
return Err(TypeError::InvalidBound(N).into());
return Err(TypeError::InvalidBound(N).into())
}

let expected_length = byte_length(N);
if encoding.len() < expected_length {
return Err(DeserializeError::ExpectedFurtherInput {
provided: encoding.len(),
expected: expected_length,
});
})
}
if encoding.len() > expected_length {
return Err(DeserializeError::AdditionalInput {
provided: encoding.len(),
expected: expected_length,
});
})
}

let mut result = Self::default();
Expand All @@ -167,7 +167,7 @@ impl<const N: usize> Deserialize for Bitvector<N> {
let last_byte = encoding.last().unwrap();
let remainder_bits = last_byte >> remainder_count;
if remainder_bits != 0 {
return Err(DeserializeError::InvalidByte(*last_byte));
return Err(DeserializeError::InvalidByte(*last_byte))
}
}
Ok(result)
Expand Down
6 changes: 3 additions & 3 deletions finality-client/libs/ssz-rs/ssz-rs/src/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ where
return Err(DeserializeError::AdditionalInput {
provided: encoding.len(),
expected: encoding.len() - remainder,
});
})
}

let mut elements = vec![];
Expand All @@ -77,7 +77,7 @@ where
T: SimpleSerialize,
{
if encoding.is_empty() {
return Ok(vec![]);
return Ok(vec![])
}

let data_pointer = u32::deserialize(&encoding[..BYTES_PER_LENGTH_OFFSET])?;
Expand All @@ -86,7 +86,7 @@ where
return Err(DeserializeError::ExpectedFurtherInput {
provided: encoding.len(),
expected: data_pointer,
});
})
}

let offsets = &mut encoding[..data_pointer]
Expand Down
2 changes: 1 addition & 1 deletion finality-client/libs/ssz-rs/ssz-rs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ pub use crate::{
de::{Deserialize, DeserializeError},
error::{Error as SimpleSerializeError, InstanceError, TypeError},
list::List,
merkleization::{is_valid_merkle_branch, compute_proof, MerkleizationError, Merkleized, Node},
merkleization::{compute_proof, is_valid_merkle_branch, MerkleizationError, Merkleized, Node},
ser::{Serialize, SerializeError},
uint::U256,
utils::{deserialize, serialize},
Expand Down
4 changes: 2 additions & 2 deletions finality-client/libs/ssz-rs/ssz-rs/src/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ where
{
fn serialize(&self, buffer: &mut Vec<u8>) -> Result<usize, SerializeError> {
if self.len() > N {
return Err(InstanceError::Bounded { bound: N, provided: self.len() }.into());
return Err(InstanceError::Bounded { bound: N, provided: self.len() }.into())
}
serialize_composite(&self.data, buffer)
}
Expand All @@ -201,7 +201,7 @@ where
fn deserialize(encoding: &[u8]) -> Result<Self, DeserializeError> {
let result = deserialize_homogeneous_composite(encoding)?;
if result.len() > N {
return Err(InstanceError::Bounded { bound: N, provided: result.len() }.into());
return Err(InstanceError::Bounded { bound: N, provided: result.len() }.into())
}
let result = result.try_into().map_err(|(_, err)| match err {
Error::Instance(err) => DeserializeError::InvalidInstance(err),
Expand Down
10 changes: 5 additions & 5 deletions finality-client/libs/ssz-rs/ssz-rs/src/merkleization/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use sha2::{Digest, Sha256};

pub use cache::Cache as MerkleCache;
pub use node::Node;
pub use proofs::{is_valid_merkle_branch, compute_proof};
pub use proofs::{compute_proof, is_valid_merkle_branch};

pub(crate) const BYTES_PER_CHUNK: usize = 32;

Expand Down Expand Up @@ -118,7 +118,7 @@ fn merkleize_chunks_with_virtual_padding(

if chunk_count == 0 {
let depth = height - 1;
return Ok(CONTEXT[depth as usize].try_into().expect("can produce a single root chunk"));
return Ok(CONTEXT[depth as usize].try_into().expect("can produce a single root chunk"))
}

let mut layer = chunks.to_vec();
Expand Down Expand Up @@ -193,7 +193,7 @@ fn treeify_chunks_with_virtual_padding(
let mut ret = vec![];

if chunk_count == 0 {
return Ok(ret);
return Ok(ret)
}

let mut layer = chunks.to_vec();
Expand Down Expand Up @@ -281,7 +281,7 @@ pub fn merkleize(chunks: &[u8], limit: Option<usize>) -> Result<Node, Merkleizat
let mut leaf_count = chunk_count.next_power_of_two();
if let Some(limit) = limit {
if limit < chunk_count {
return Err(MerkleizationError::InputExceedsLimit(limit));
return Err(MerkleizationError::InputExceedsLimit(limit))
}
leaf_count = limit.next_power_of_two();
}
Expand All @@ -297,7 +297,7 @@ pub fn treeify(
let mut leaf_count = chunk_count.next_power_of_two();
if let Some(limit) = limit {
if limit < chunk_count {
return Err(MerkleizationError::InputExceedsLimit(limit));
return Err(MerkleizationError::InputExceedsLimit(limit))
}
leaf_count = limit.next_power_of_two();
}
Expand Down
31 changes: 19 additions & 12 deletions finality-client/libs/ssz-rs/ssz-rs/src/merkleization/proofs.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::merkleization::{Node, MerkleizationError};
use std::collections::HashMap;
use sha2::{Digest, Sha256};
use crate::merkleization::{MerkleizationError, Node};
use bitvec::prelude::*;
use sha2::{Digest, Sha256};
use std::collections::HashMap;

/// `is_valid_merkle_branch` verifies the Merkle proof
/// against the `root` given the other metadata.
Expand Down Expand Up @@ -32,27 +32,34 @@ pub fn is_valid_merkle_branch<'a>(
value == *root
}

// only use this method for very small trees. It is extremely inefficient and holds the whole tree in memory (and clones it :())
pub fn compute_proof(root: &Node, gindex: usize, tree: &[([u8; 32], [u8; 64])]) -> Result<Vec<[u8; 32]>, MerkleizationError> {
let tree_map: HashMap<[u8; 32], [u8; 64]> = tree.iter().cloned().collect();
let root: [u8;32] = root.as_ref().try_into().unwrap();
let (_, proof): (_, Vec<[u8;32]>) = gindex
// only use this method for very small trees. It is extremely inefficient and holds the whole tree
// in memory (and clones it :())
pub fn compute_proof(
root: &Node,
gindex: usize,
tree: &[([u8; 32], [u8; 64])],
) -> Result<Vec<[u8; 32]>, MerkleizationError> {
let tree_map: HashMap<[u8; 32], [u8; 64]> = tree.iter().cloned().collect();
let root: [u8; 32] = root.as_ref().try_into().unwrap();
let (_, proof): (_, Vec<[u8; 32]>) = gindex
.view_bits::<Msb0>()
.iter()
.skip_while(|b| b.as_ref() == &false) // skip the leading zeros
.skip(1) // skip the first 1, this just indicates the root
.try_fold((root, vec![]), |(hash, mut proof), direction| {
let leaves = tree_map.get(hash.as_ref()).ok_or(MerkleizationError::MissingNode)?;
let mut left = [0_u8;32];
let mut right = [0_u8;32];
let mut left = [0_u8; 32];
let mut right = [0_u8; 32];
left.copy_from_slice(&leaves[0..32]);
right.copy_from_slice(&leaves[32..64]);
match direction.as_ref() {
false => { // left
false => {
// left
proof.insert(0, right.try_into().unwrap());
Ok::<_, MerkleizationError>((left, proof))
}
true => { //right
true => {
//right
proof.insert(0, left.try_into().unwrap());
Ok((right, proof))
}
Expand Down
2 changes: 1 addition & 1 deletion finality-client/libs/ssz-rs/ssz-rs/src/ser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ pub fn serialize_composite_from_components(
) -> Result<usize, SerializeError> {
let total_size = fixed_lengths_sum + variable_lengths.iter().sum::<usize>();
if total_size as u64 >= MAXIMUM_LENGTH {
return Err(SerializeError::MaximumEncodedLengthExceeded(total_size));
return Err(SerializeError::MaximumEncodedLengthExceeded(total_size))
}

let mut total_bytes_written = 0;
Expand Down
8 changes: 4 additions & 4 deletions finality-client/libs/ssz-rs/ssz-rs/src/uint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,13 @@ macro_rules! define_uint {
return Err(DeserializeError::ExpectedFurtherInput {
provided: encoding.len(),
expected: byte_size,
});
})
}
if encoding.len() > byte_size {
return Err(DeserializeError::AdditionalInput {
provided: encoding.len(),
expected: byte_size,
});
})
}

let bytes = encoding[..byte_size].try_into().expect("slice has right length");
Expand Down Expand Up @@ -155,13 +155,13 @@ impl Deserialize for U256 {
return Err(DeserializeError::ExpectedFurtherInput {
provided: encoding.len(),
expected: byte_size,
});
})
}
if encoding.len() > byte_size {
return Err(DeserializeError::AdditionalInput {
provided: encoding.len(),
expected: byte_size,
});
})
}

let value = BigUint::from_bytes_le(&encoding[..byte_size]);
Expand Down
2 changes: 1 addition & 1 deletion finality-client/libs/ssz-rs/ssz-rs/src/union.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ where
{
fn deserialize(encoding: &[u8]) -> Result<Self, DeserializeError> {
if encoding.is_empty() {
return Err(DeserializeError::ExpectedFurtherInput { provided: 0, expected: 1 });
return Err(DeserializeError::ExpectedFurtherInput { provided: 0, expected: 1 })
}

match encoding[0] {
Expand Down
Loading

0 comments on commit 2e3518e

Please sign in to comment.