Skip to content

Commit

Permalink
Merge pull request #151 from ralexstokes/remove-mut-hash-tree-root
Browse files Browse the repository at this point in the history
refactor: drop `mut` on `HashTreeRoot::hash_tree_root`
  • Loading branch information
ralexstokes committed Apr 2, 2024
2 parents 2989bd2 + 50f3d40 commit 8b2eb8e
Show file tree
Hide file tree
Showing 28 changed files with 1,885 additions and 1,912 deletions.
10 changes: 6 additions & 4 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,15 @@ jobs:
cache-on-failure: true

- name: Build
run: cargo build --all-targets --all-features --verbose
run: cargo build --all-targets --all-features --workspace --verbose

- name: Build `no-std`
run: cargo build --no-default-features --all-targets --verbose
run: cargo build --no-default-features --all-targets --workspace --verbose

- name: Run tests
run: cargo test --all-features --all-targets --verbose
run: |
cargo test --all-features --all-targets --workspace --verbose
cargo test --doc
lint:
runs-on: ubuntu-latest
Expand All @@ -59,7 +61,7 @@ jobs:
run: cargo +nightly fmt --all --check

- name: Check clippy
run: cargo +nightly clippy --all-targets --all-features --verbose -- -D warnings
run: cargo +nightly clippy --all-targets --all-features --workspace --verbose -- -D warnings

coverage:
runs-on: ubuntu-latest
Expand Down
9 changes: 5 additions & 4 deletions justfile
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
test:
cargo test --all-features --all-targets
cargo test --all-features --workspace --all-targets
cargo test --doc
fmt:
cargo +nightly fmt --all
lint: fmt
cargo +nightly clippy --all-targets --all-features
cargo +nightly clippy --all-features --workspace --all-targets
build:
cargo build --all-targets --all-features
cargo build --all-features --workspace --all-targets
build-no-std:
cargo build --no-default-features --all-targets
cargo build --no-default-features --workspace --all-targets
run-ci: lint build build-no-std test
14 changes: 7 additions & 7 deletions ssz-rs-derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -404,13 +404,13 @@ fn derive_merkleization_impl(
let (impl_generics, ty_generics, _) = generics.split_for_impl();
quote! {
impl #impl_generics #name #ty_generics {
fn assemble_chunks(&mut self) -> Result<Vec<u8>, ssz_rs::MerkleizationError> {
fn assemble_chunks(&self) -> Result<Vec<u8>, ssz_rs::MerkleizationError> {
#chunks_impl
}
}

impl #impl_generics ssz_rs::HashTreeRoot for #name #ty_generics {
fn hash_tree_root(&mut self) -> Result<ssz_rs::Node, ssz_rs::MerkleizationError> {
fn hash_tree_root(&self) -> Result<ssz_rs::Node, ssz_rs::MerkleizationError> {
#hash_tree_root_impl
}
}
Expand Down Expand Up @@ -600,7 +600,7 @@ fn derive_prove_impl(data: &Data, name: &Ident, generics: &Generics) -> TokenStr
let field_name = field.ident.as_ref().expect("only named fields");
quote! {
#i => {
let child = &mut self.#field_name;
let child = &self.#field_name;
prover.compute_proof(child)
}
}
Expand Down Expand Up @@ -665,8 +665,8 @@ fn derive_prove_impl(data: &Data, name: &Ident, generics: &Generics) -> TokenStr
(
quote! {
Self::None => {
let mut leaf = 0usize;
prover.compute_proof(&mut leaf)
let leaf = 0usize;
prover.compute_proof(&leaf)
}
},
quote! {
Expand Down Expand Up @@ -706,12 +706,12 @@ fn derive_prove_impl(data: &Data, name: &Ident, generics: &Generics) -> TokenStr

quote! {
impl #impl_generics ssz_rs::Prove for #name #ty_generics {
fn chunks(&mut self) -> Result<Vec<u8>, ssz_rs::MerkleizationError> {
fn chunks(&self) -> Result<Vec<u8>, ssz_rs::MerkleizationError> {
#chunks_impl
}

fn prove_element(
&mut self,
&self,
index: usize,
prover: &mut ssz_rs::proofs::Prover,
) -> Result<(), ssz_rs::MerkleizationError> {
Expand Down
42 changes: 21 additions & 21 deletions ssz-rs-derive/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ enum Bar {
}

fn generalized_index_for_bar(
object: &mut Bar,
object: &Bar,
path: Path,
) -> Result<GeneralizedIndex, MerkleizationError> {
match object {
Expand All @@ -27,7 +27,7 @@ fn generalized_index_for_bar(
}
}

fn prove_for_bar(object: &mut Bar, path: Path) -> Result<ProofAndWitness, MerkleizationError> {
fn prove_for_bar(object: &Bar, path: Path) -> Result<ProofAndWitness, MerkleizationError> {
match object {
Bar::A(value) => value.prove(path),
Bar::B(value) => value.prove(path),
Expand All @@ -40,7 +40,7 @@ struct Wrapper(Foo);
#[derive(Debug, PartialEq, Eq, SimpleSerialize)]
struct WrappedList(List<u8, 23>);

fn can_serde<T: Serializable + Eq + fmt::Debug>(data: &mut T) {
fn can_serde<T: Serializable + Eq + fmt::Debug>(data: &T) {
let mut buf = vec![];
let _ = data.serialize(&mut buf).unwrap();
let recovered = T::deserialize(&buf).unwrap();
Expand All @@ -50,13 +50,13 @@ fn can_serde<T: Serializable + Eq + fmt::Debug>(data: &mut T) {
#[test]
fn test_transparent_helper() {
// derive traits for "regular" types
let mut container = Foo {
let container = Foo {
a: 23,
b: 445,
c: List::<usize, 45>::try_from(vec![9, 8, 7, 6, 5, 4]).unwrap(),
d: U256::from(234234),
};
can_serde(&mut container);
can_serde(&container);

let container_root = container.hash_tree_root().unwrap();

Expand Down Expand Up @@ -85,43 +85,43 @@ fn test_transparent_helper() {
}

// derive traits in "transparent" mode
let mut inner = 22;
let mut bar = Bar::A(inner);
can_serde(&mut bar);
let inner = 22;
let bar = Bar::A(inner);
can_serde(&bar);

let inner_root = inner.hash_tree_root().unwrap();
let bar_root = bar.hash_tree_root().unwrap();
assert_eq!(inner_root, bar_root);

// `bar` just wraps a primitive type, so `path` is empty.
let index = generalized_index_for_bar(&mut bar, &[]).unwrap();
let index = generalized_index_for_bar(&bar, &[]).unwrap();
assert_eq!(index, 1);
let result = generalized_index_for_bar(&mut bar, &["a".into()]);
let result = generalized_index_for_bar(&bar, &["a".into()]);
assert!(result.is_err());

let path = &[];
let (proof, witness) = prove_for_bar(&mut bar, path).unwrap();
let (proof, witness) = prove_for_bar(&bar, path).unwrap();
assert_eq!(witness, inner_root);
assert_eq!(witness, bar_root);
assert!(proof.verify(witness).is_ok());

// repeat transparent with other variant
let mut inner = container.clone();
let inner = container.clone();
let inner_root = inner.hash_tree_root().unwrap();
let mut bar = Bar::B(inner);
can_serde(&mut bar);
let bar = Bar::B(inner);
can_serde(&bar);

let bar_root = bar.hash_tree_root().unwrap();
assert_eq!(inner_root, bar_root);

for (i, (path, _)) in container_paths.iter().enumerate() {
let index = generalized_index_for_bar(&mut bar, path).unwrap();
let index = generalized_index_for_bar(&bar, path).unwrap();
assert_eq!(index, container_indices[i]);
}

for (i, pair) in container_paths.iter().enumerate() {
let path = &pair.0;
let (proof, witness) = prove_for_bar(&mut bar, path).unwrap();
let (proof, witness) = prove_for_bar(&bar, path).unwrap();
assert_eq!(witness, container_root);
assert!(proof.verify(witness).is_ok());
assert_eq!((proof, witness), container_proofs[i]);
Expand All @@ -131,8 +131,8 @@ fn test_transparent_helper() {
// for a wrapped type without "decoration"
let mut buf = vec![];
let container_serialization = container.serialize(&mut buf).unwrap();
let mut wrapped = Wrapper(container);
can_serde(&mut wrapped);
let wrapped = Wrapper(container);
can_serde(&wrapped);
buf.clear();
let wrapped_serialization = wrapped.serialize(&mut buf).unwrap();
assert_eq!(container_serialization, wrapped_serialization);
Expand Down Expand Up @@ -164,7 +164,7 @@ fn test_transparent_helper() {

// for a wrapped type with "decoration"
let mut buf = vec![];
let mut inner = List::<u8, 23>::try_from(vec![10, 11, 12]).unwrap();
let inner = List::<u8, 23>::try_from(vec![10, 11, 12]).unwrap();
let inner_serialization = inner.serialize(&mut buf).unwrap();
let inner_root = inner.hash_tree_root().unwrap();
let inner_paths =
Expand All @@ -183,8 +183,8 @@ fn test_transparent_helper() {
inner_proofs.push((proof, witness));
}

let mut wrapped = WrappedList(inner);
can_serde(&mut wrapped);
let wrapped = WrappedList(inner);
can_serde(&wrapped);
buf.clear();
let wrapped_serialization = wrapped.serialize(&mut buf).unwrap();
assert_eq!(inner_serialization, wrapped_serialization);
Expand Down
4 changes: 2 additions & 2 deletions ssz-rs-test-gen/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -442,15 +442,15 @@ impl Generator {
r#"
#[test]
fn test_{ssz_type}_{name}() {{
let mut value = {value};
let value = {value};
let encoding = serialize(&value);
let expected_encoding = read_ssz_snappy_from_test_data("{target_data_path}");
assert_eq!(encoding, expected_encoding);
let recovered_value: {rust_type} = deserialize(&expected_encoding);
assert_eq!(recovered_value, value);
let root = hash_tree_root(&mut value);
let root = hash_tree_root(&value);
let expected_root = root_from_hex("{root}");
assert_eq!(root, expected_root);
}}
Expand Down
2 changes: 1 addition & 1 deletion ssz-rs/examples/another_container.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ struct SerializableStruct {
}

fn main() {
let mut value = ComplexTestStruct {
let value = ComplexTestStruct {
a: 51972,
b: List::<u16, 128>::try_from(vec![48645]).unwrap(),
c: 46,
Expand Down
2 changes: 1 addition & 1 deletion ssz-rs/examples/container_with_some_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ fn main() {
}
};

let mut restored_example = match Foo::<4>::deserialize(&encoding) {
let restored_example = match Foo::<4>::deserialize(&encoding) {
Ok(value) => value,
Err(err) => {
eprintln!("some error decoding: {err}");
Expand Down
20 changes: 10 additions & 10 deletions ssz-rs/examples/proofs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ struct ComplexTestStruct {
g: Vector<VarTestStruct, 2>,
}

fn compute_and_verify_proof<T: SimpleSerialize>(data: &mut T, path: Path) {
fn compute_and_verify_proof<T: SimpleSerialize>(data: &T, path: Path) {
let (proof, witness) = data.prove(path).unwrap();
assert_eq!(witness, data.hash_tree_root().unwrap());
dbg!(&proof);
Expand All @@ -36,11 +36,11 @@ fn compute_and_verify_proof<T: SimpleSerialize>(data: &mut T, path: Path) {
}

fn main() {
let mut data = 8u8;
let data = 8u8;
let path = &[];
compute_and_verify_proof(&mut data, path);
compute_and_verify_proof(&data, path);

let mut data = ComplexTestStruct {
let data = ComplexTestStruct {
a: 51972,
b: List::<u16, 128>::try_from(vec![48645]).unwrap(),
c: 46,
Expand Down Expand Up @@ -69,20 +69,20 @@ fn main() {
};

let path = &["a".into()];
compute_and_verify_proof(&mut data, path);
compute_and_verify_proof(&data, path);

let path = &["b".into(), 0.into()];
compute_and_verify_proof(&mut data, path);
compute_and_verify_proof(&data, path);

let path = &["e".into(), "a".into()];
compute_and_verify_proof(&mut data, path);
compute_and_verify_proof(&data, path);

let path = &["e".into(), "b".into(), 0.into()];
compute_and_verify_proof(&mut data, path);
compute_and_verify_proof(&data, path);

let path = &["e".into(), "b".into(), 33.into()];
compute_and_verify_proof(&mut data, path);
compute_and_verify_proof(&data, path);

let path = &["g".into(), 1.into(), "b".into(), 0.into()];
compute_and_verify_proof(&mut data, path);
compute_and_verify_proof(&data, path);
}
14 changes: 5 additions & 9 deletions ssz-rs/src/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ impl<T, const N: usize> HashTreeRoot for [T; N]
where
T: SimpleSerialize,
{
fn hash_tree_root(&mut self) -> Result<Node, MerkleizationError> {
fn hash_tree_root(&self) -> Result<Node, MerkleizationError> {
let chunks = self.chunks()?;
merkleize(&chunks, None)
}
Expand Down Expand Up @@ -121,24 +121,20 @@ impl<T, const N: usize> Prove for [T; N]
where
T: SimpleSerialize,
{
fn chunks(&mut self) -> Result<Vec<u8>, MerkleizationError> {
fn chunks(&self) -> Result<Vec<u8>, MerkleizationError> {
if T::is_composite_type() {
let count = self.len();
elements_to_chunks(self.iter_mut().enumerate(), count)
elements_to_chunks(self.iter().enumerate(), count)
} else {
pack(self)
}
}

fn prove_element(
&mut self,
index: usize,
prover: &mut Prover,
) -> Result<(), MerkleizationError> {
fn prove_element(&self, index: usize, prover: &mut Prover) -> Result<(), MerkleizationError> {
if index >= N {
Err(MerkleizationError::InvalidInnerIndex)
} else {
let child = &mut self[index];
let child = &self[index];
prover.compute_proof(child)
}
}
Expand Down
6 changes: 3 additions & 3 deletions ssz-rs/src/bitlist.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ impl<const N: usize> Default for Bitlist<N> {

impl<const N: usize> Bitlist<N> {
/// Return the bit at `index`. `None` if index is out-of-bounds.
pub fn get(&mut self, index: usize) -> Option<bool> {
pub fn get(&self, index: usize) -> Option<bool> {
self.0.get(index).map(|value| *value)
}

Expand Down Expand Up @@ -179,7 +179,7 @@ impl<const N: usize> Deserialize for Bitlist<N> {
}

impl<const N: usize> HashTreeRoot for Bitlist<N> {
fn hash_tree_root(&mut self) -> Result<Node, MerkleizationError> {
fn hash_tree_root(&self) -> Result<Node, MerkleizationError> {
let chunks = self.pack_bits()?;
let data_root = merkleize(&chunks, Some(Self::chunk_count()))?;
Ok(mix_in_length(data_root, self.len()))
Expand Down Expand Up @@ -218,7 +218,7 @@ impl<const N: usize> GeneralizedIndexable for Bitlist<N> {
}

impl<const N: usize> Prove for Bitlist<N> {
fn chunks(&mut self) -> Result<Vec<u8>, MerkleizationError> {
fn chunks(&self) -> Result<Vec<u8>, MerkleizationError> {
self.pack_bits()
}

Expand Down
Loading

0 comments on commit 8b2eb8e

Please sign in to comment.