Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make from_hex() safer in rust bindings #307

Merged
merged 2 commits into from
May 28, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 14 additions & 3 deletions bindings/rust/src/bindings/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ pub struct KZGProof {
pub enum Error {
/// Wrong number of bytes.
InvalidBytesLength(String),
/// The hex string is invalid.
InvalidHexFormat(String),
/// The KZG proof is invalid.
InvalidKzgProof(String),
/// The KZG commitment is invalid.
Expand Down Expand Up @@ -175,7 +177,10 @@ impl Blob {
}

pub fn from_hex(hex_str: &str) -> Result<Self, Error> {
Self::from_bytes(&hex::decode(&hex_str[2..]).unwrap())
let trimmed_str = hex_str.strip_prefix("0x").unwrap_or(hex_str);
jtraglia marked this conversation as resolved.
Show resolved Hide resolved
hex::decode(trimmed_str)
.map_err(|e| Error::InvalidHexFormat(format!("Failed to decode hex: {}", e)))
.and_then(|bytes| Self::from_bytes(&bytes))
}
}

Expand All @@ -194,7 +199,10 @@ impl Bytes32 {
}

pub fn from_hex(hex_str: &str) -> Result<Self, Error> {
Self::from_bytes(&hex::decode(&hex_str[2..]).unwrap())
let trimmed_str = hex_str.strip_prefix("0x").unwrap_or(hex_str);
hex::decode(trimmed_str)
.map_err(|e| Error::InvalidHexFormat(format!("Failed to decode hex: {}", e)))
.and_then(|bytes| Self::from_bytes(&bytes))
}
}

Expand All @@ -213,7 +221,10 @@ impl Bytes48 {
}

pub fn from_hex(hex_str: &str) -> Result<Self, Error> {
Self::from_bytes(&hex::decode(&hex_str[2..]).unwrap())
let trimmed_str = hex_str.strip_prefix("0x").unwrap_or(hex_str);
hex::decode(trimmed_str)
.map_err(|e| Error::InvalidHexFormat(format!("Failed to decode hex: {}", e)))
.and_then(|bytes| Self::from_bytes(&bytes))
}

pub fn into_inner(self) -> [u8; 48] {
Expand Down
Loading