Skip to content

Commit a606b41

Browse files
committed
Fix tree hash calculation for extra data
1 parent 19f4250 commit a606b41

File tree

1 file changed

+21
-8
lines changed
  • contracts/near/eth-types/src

1 file changed

+21
-8
lines changed

contracts/near/eth-types/src/eth2.rs

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
2-
31
use super::*;
42
use borsh::{BorshDeserialize, BorshSerialize};
53
use std::io::{Error, Write};
@@ -48,14 +46,27 @@ impl tree_hash::TreeHash for ExtraData {
4846
}
4947

5048
fn tree_hash_root(&self) -> tree_hash::Hash256 {
51-
let mut hasher =
52-
tree_hash::MerkleHasher::with_leaves(self.0.len().div_ceil(tree_hash::BYTES_PER_CHUNK));
49+
// Replicate the logic from VariableList<u8, U32>
50+
// ExtraData has a maximum length of 32 bytes (U32)
51+
const MAX_LEN: usize = 32;
52+
53+
// For u8 (basic type), calculate number of leaves based on packing factor
54+
// u8 has a packing factor of 32 (32 bytes fit in one 32-byte chunk)
55+
let packing_factor = <u8 as tree_hash::TreeHash>::tree_hash_packing_factor();
56+
let num_leaves = (MAX_LEN + packing_factor - 1) / packing_factor;
57+
58+
let mut hasher = tree_hash::MerkleHasher::with_leaves(num_leaves);
5359

5460
for item in &self.0 {
55-
hasher.write(&item.tree_hash_packed_encoding()).unwrap();
61+
hasher
62+
.write(&item.tree_hash_packed_encoding())
63+
.expect("ExtraData should not contain more elements than max");
5664
}
5765

58-
let root = hasher.finish().unwrap();
66+
let root = hasher
67+
.finish()
68+
.expect("ExtraData should not have a remaining buffer");
69+
5970
tree_hash::mix_in_length(&root, self.0.len())
6071
}
6172
}
@@ -284,6 +295,8 @@ pub mod quoted_u256 {
284295
// Parse as decimal (base 10)
285296
ethereum_types::U256::from_dec_str(&s)
286297
.map(U256)
287-
.map_err(|e| serde::de::Error::custom(format!("failed to parse U256 from decimal: {}", e)))
298+
.map_err(|e| {
299+
serde::de::Error::custom(format!("failed to parse U256 from decimal: {}", e))
300+
})
288301
}
289-
}
302+
}

0 commit comments

Comments
 (0)