Skip to content

Commit

Permalink
feat: add deserde check for JsonStorageKey
Browse files Browse the repository at this point in the history
  • Loading branch information
stevencartavia committed Jan 14, 2025
1 parent 249e6d8 commit 78a8170
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion crates/serde/src/storage.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
use alloc::collections::BTreeMap;
use alloy_primitives::{ruint::ParseError, Bytes, B256, U256};
use alloy_primitives::{
ruint::{BaseConvertError, ParseError},
Bytes, B256, U256,
};
use core::{fmt, str::FromStr};
use serde::{Deserialize, Deserializer, Serialize};

Expand Down Expand Up @@ -70,6 +73,13 @@ impl FromStr for JsonStorageKey {
type Err = ParseError;

fn from_str(s: &str) -> Result<Self, Self::Err> {
let hex_str = s.strip_prefix("0x").unwrap_or(s);
let is_prefixed = s.starts_with("0x");

if (is_prefixed && hex_str.len() > 64) || (!is_prefixed && hex_str.len() > 66) {
return Err(ParseError::BaseConvertError(BaseConvertError::Overflow));
}

if let Ok(hash) = B256::from_str(s) {
return Ok(Self::Hash(hash));
}
Expand Down Expand Up @@ -242,6 +252,14 @@ mod tests {
assert_eq!(key, JsonStorageKey::Number(U256::from(42)));
}

#[test]
fn test_from_str_with_too_long_hex_string() {
let long_hex_str = "0x".to_string() + &"1".repeat(65);
let result = JsonStorageKey::from_str(&long_hex_str);

assert!(matches!(result, Err(ParseError::BaseConvertError(BaseConvertError::Overflow))));
}

#[test]
fn test_deserialize_storage_map_with_valid_data() {
let json_data = json!({
Expand Down

0 comments on commit 78a8170

Please sign in to comment.