From f91c0ec37e5e495c7303dcbf1ba24066ec60e914 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Gr=C3=BCner?= <47506558+MegaRedHand@users.noreply.github.com> Date: Wed, 29 Nov 2023 08:02:15 -0300 Subject: [PATCH] fix: was mixing max size instead of length in hash calculation (#469) --- native/ssz_nif/src/utils/helpers.rs | 14 +++++++------- test/unit/ssz_test.exs | 9 ++++++++- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/native/ssz_nif/src/utils/helpers.rs b/native/ssz_nif/src/utils/helpers.rs index 481c4b801..24fd300ae 100644 --- a/native/ssz_nif/src/utils/helpers.rs +++ b/native/ssz_nif/src/utils/helpers.rs @@ -78,8 +78,9 @@ where Elx: Decoder<'a>, Ssz: TreeHash + FromElx, { + let list_size = list.len(); let root = hash_vector_tree_root::<'a, Elx, Ssz>((list, max_size))?; - let bytes = tree_hash::mix_in_length(&Hash256::from(root), max_size).0; + let bytes = tree_hash::mix_in_length(&Hash256::from(root), list_size).0; Ok(bytes) } @@ -95,16 +96,15 @@ where Ok(vec_tree_hash_root(&x, max_size)) } -/// A helper function providing common functionality between the `TreeHash` implementations for -/// `FixedVector` and `VariableList`. -pub fn vec_tree_hash_root(vec: &[T], size: usize) -> [u8; 32] +/// Taken from `ssz_types` and modified to take `max_size` as dynamic parameter. +pub fn vec_tree_hash_root(vec: &[T], max_size: usize) -> [u8; 32] where T: TreeHash, { let root = match T::tree_hash_type() { TreeHashType::Basic => { - let mut hasher: MerkleHasher = MerkleHasher::with_leaves( - (size + T::tree_hash_packing_factor() - 1) / T::tree_hash_packing_factor(), + let mut hasher = MerkleHasher::with_leaves( + (max_size + T::tree_hash_packing_factor() - 1) / T::tree_hash_packing_factor(), ); for item in vec { @@ -118,7 +118,7 @@ where .expect("ssz_types variable vec should not have a remaining buffer") } TreeHashType::Container | TreeHashType::List | TreeHashType::Vector => { - let mut hasher = MerkleHasher::with_leaves(size); + let mut hasher = MerkleHasher::with_leaves(max_size); for item in vec { hasher diff --git a/test/unit/ssz_test.exs b/test/unit/ssz_test.exs index 846ddd09c..3ae214b2d 100644 --- a/test/unit/ssz_test.exs +++ b/test/unit/ssz_test.exs @@ -171,10 +171,17 @@ defmodule Unit.SSZTests do Enum.join(deserialized) ]) + assert serialized == + Base.decode16!( + "0C000000140000001F000000617366617366617331383431383238303139327A6439673861733066373061307366" + ) + assert {:ok, ^serialized} = Ssz.to_ssz_typed(deserialized, SszTypes.Transaction) assert {:ok, ^deserialized} = Ssz.list_from_ssz(serialized, SszTypes.Transaction) - assert {:ok, _hash} = + hash = Base.decode16!("D5ACD42F851C9AE241B55AB79B23D7EC613E01BB6404B4A49D8CF214DBA26CF2") + + assert {:ok, ^hash} = Ssz.hash_list_tree_root_typed(deserialized, 1_048_576, SszTypes.Transaction) end