Skip to content

Commit b0f348f

Browse files
authored
fix(l1): catch potential panic when decoding NodeHash (#2683)
**Motivation** The method `NodeHash::from_slice` can panic if the slice is over 32 bytes. This could cause panics when decoding nodes as it is used without checking the length beforehand. This PR adds a check and returns an invalid length error before calling `from_slice`. It also mentions the potential panic on the method's documentation & removes a misleading `From<Vec<u8>>` implementation that would also panic under the same condition. <!-- Why does this pull request exist? What are its goals? --> **Description** * Remove `From<Vec<u8>> for NodeHash` impl as it could cause panics * Mention potential panic on `NodeHash::from_slice` doc * Check rlp decoded data len to avoid panics when decoding `NodeHash` <!-- A clear and concise general description of the changes this PR introduces --> <!-- Link to issues: Resolves #111, Resolves #222 --> Closes #2649
1 parent 352e5b6 commit b0f348f

File tree

1 file changed

+6
-9
lines changed

1 file changed

+6
-9
lines changed

crates/common/trie/node_hash.rs

+6-9
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use ethereum_types::H256;
2-
use ethrex_rlp::{decode::RLPDecode, encode::RLPEncode, structs::Encoder};
2+
use ethrex_rlp::{decode::RLPDecode, encode::RLPEncode, error::RLPDecodeError, structs::Encoder};
33
#[cfg(feature = "libmdbx")]
44
use libmdbx::orm::{Decodable, Encodable};
55
use sha3::{Digest, Keccak256};
@@ -36,7 +36,7 @@ impl NodeHash {
3636
}
3737

3838
/// Converts a slice of an already hashed data (in case it's not inlineable) to a NodeHash.
39-
///
39+
/// Panics if the slice is over 32 bytes
4040
/// If you need to hash it in case its len >= 32 see `from_encoded_raw`
4141
pub(crate) fn from_slice(slice: &[u8]) -> NodeHash {
4242
match slice.len() {
@@ -103,12 +103,6 @@ impl NodeHash {
103103
}
104104
}
105105

106-
impl From<Vec<u8>> for NodeHash {
107-
fn from(value: Vec<u8>) -> Self {
108-
NodeHash::from_slice(&value)
109-
}
110-
}
111-
112106
impl From<H256> for NodeHash {
113107
fn from(value: H256) -> Self {
114108
NodeHash::Hashed(value)
@@ -160,7 +154,10 @@ impl RLPDecode for NodeHash {
160154
fn decode_unfinished(rlp: &[u8]) -> Result<(Self, &[u8]), ethrex_rlp::error::RLPDecodeError> {
161155
let (hash, rest): (Vec<u8>, &[u8]);
162156
(hash, rest) = RLPDecode::decode_unfinished(rlp)?;
163-
let hash = NodeHash::from(hash);
157+
if hash.len() > 32 {
158+
return Err(RLPDecodeError::InvalidLength);
159+
}
160+
let hash = NodeHash::from_slice(&hash);
164161
Ok((hash, rest))
165162
}
166163
}

0 commit comments

Comments
 (0)