From 6c50a43a19e9764e881e1959fe0a2c3f08419793 Mon Sep 17 00:00:00 2001 From: Justin Traglia <95511699+jtraglia@users.noreply.github.com> Date: Sun, 28 May 2023 10:47:59 -0500 Subject: [PATCH] Make from_hex() safer in rust bindings (#307) * Make from_hex() safer in rust bindings * Add hex_to_bytes function --- bindings/rust/src/bindings/mod.rs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/bindings/rust/src/bindings/mod.rs b/bindings/rust/src/bindings/mod.rs index 5355787..d19a961 100644 --- a/bindings/rust/src/bindings/mod.rs +++ b/bindings/rust/src/bindings/mod.rs @@ -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. @@ -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, 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 @@ -175,7 +184,7 @@ impl Blob { } pub fn from_hex(hex_str: &str) -> Result { - Self::from_bytes(&hex::decode(&hex_str[2..]).unwrap()) + Self::from_bytes(&hex_to_bytes(hex_str)?) } } @@ -194,7 +203,7 @@ impl Bytes32 { } pub fn from_hex(hex_str: &str) -> Result { - Self::from_bytes(&hex::decode(&hex_str[2..]).unwrap()) + Self::from_bytes(&hex_to_bytes(hex_str)?) } } @@ -213,7 +222,7 @@ impl Bytes48 { } pub fn from_hex(hex_str: &str) -> Result { - Self::from_bytes(&hex::decode(&hex_str[2..]).unwrap()) + Self::from_bytes(&hex_to_bytes(hex_str)?) } pub fn into_inner(self) -> [u8; 48] {