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 all commits
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
15 changes: 12 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 All @@ -51,6 +53,13 @@ pub enum Error {
CError(C_KZG_RET),
}

/// Converts a hex string (with or without the 0x prefix) to bytes.
pub fn hex_to_bytes(hex_str: &str) -> Result<Vec<u8>, Error> {
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)))
}

/// Holds the parameters of a kzg trusted setup ceremony.
impl KZGSettings {
/// Initializes a trusted setup from `FIELD_ELEMENTS_PER_BLOB` g1 points
Expand Down Expand Up @@ -175,7 +184,7 @@ impl Blob {
}

pub fn from_hex(hex_str: &str) -> Result<Self, Error> {
Self::from_bytes(&hex::decode(&hex_str[2..]).unwrap())
Self::from_bytes(&hex_to_bytes(hex_str)?)
}
}

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

pub fn from_hex(hex_str: &str) -> Result<Self, Error> {
Self::from_bytes(&hex::decode(&hex_str[2..]).unwrap())
Self::from_bytes(&hex_to_bytes(hex_str)?)
}
}

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

pub fn from_hex(hex_str: &str) -> Result<Self, Error> {
Self::from_bytes(&hex::decode(&hex_str[2..]).unwrap())
Self::from_bytes(&hex_to_bytes(hex_str)?)
}

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