Skip to content

Commit 030fbb6

Browse files
committed
Add error to UnsInt from_hex when hex too big
1 parent dfe4f0e commit 030fbb6

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

math/src/errors.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ pub enum ByteConversionError {
1111
pub enum CreationError {
1212
InvalidHexString,
1313
InvalidDecString,
14+
HexStringIsTooBig,
1415
EmptyString,
1516
}
1617

math/src/unsigned_integer/element.rs

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -440,6 +440,14 @@ impl<const NUM_LIMBS: usize> UnsignedInteger<NUM_LIMBS> {
440440
if !Self::is_hex_string(string) {
441441
return Err(CreationError::InvalidHexString);
442442
}
443+
444+
// Limbs are of 64 bits - 8 bytes
445+
// We have 16 nibbles per bytes
446+
let max_amount_of_hex_chars = NUM_LIMBS * 16;
447+
if string.len() > max_amount_of_hex_chars {
448+
return Err(CreationError::HexStringIsTooBig);
449+
}
450+
443451
Ok(Self::from_hex_unchecked(string))
444452
}
445453

@@ -1001,7 +1009,7 @@ impl<const NUM_LIMBS: usize> Arbitrary for UnsignedInteger<NUM_LIMBS> {
10011009
#[cfg(test)]
10021010
mod tests_u384 {
10031011
use crate::traits::ByteConversion;
1004-
use crate::unsigned_integer::element::{UnsignedInteger, U384};
1012+
use crate::unsigned_integer::element::{UnsignedInteger, U256, U384};
10051013
#[cfg(feature = "proptest")]
10061014
use proptest::prelude::*;
10071015
#[cfg(feature = "proptest")]
@@ -1246,6 +1254,18 @@ mod tests_u384 {
12461254
);
12471255
}
12481256

1257+
#[test]
1258+
fn from_hex_with_overflowing_hexstring_should_error() {
1259+
let u256_from_big_string = U256::from_hex(&"f".repeat(65));
1260+
assert!(u256_from_big_string.is_err());
1261+
assert!(u256_from_big_string == Err(crate::unsigned_integer::element::CreationError::HexStringIsTooBig));
1262+
}
1263+
1264+
#[test]
1265+
fn from_hex_with_non_overflowing_hexstring_should_work() {
1266+
assert_eq!(U256::from_hex(&"0".repeat(64)).unwrap().limbs, [0,0,0,0])
1267+
}
1268+
12491269
#[test]
12501270
fn construct_new_integer_from_dec_1() {
12511271
let a = U384::from_dec_str("1").unwrap();

0 commit comments

Comments
 (0)