From 69301f8f8c30fd3d26cfb2ce1b042ce30a0cc652 Mon Sep 17 00:00:00 2001 From: Ranadeep Biswas Date: Fri, 3 Nov 2023 18:05:19 -0400 Subject: [PATCH] optimize validate_prefix_length --- .../core/ics24_host/identifier/validate.rs | 27 ++++++++++--------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/crates/ibc/src/core/ics24_host/identifier/validate.rs b/crates/ibc/src/core/ics24_host/identifier/validate.rs index 769206e5b..d0b0c01c6 100644 --- a/crates/ibc/src/core/ics24_host/identifier/validate.rs +++ b/crates/ibc/src/core/ics24_host/identifier/validate.rs @@ -61,25 +61,26 @@ pub fn validate_prefix_length( min_id_length: u64, max_id_length: u64, ) -> Result<(), Error> { + assert!(max_id_length >= min_id_length); + if prefix.is_empty() { return Err(Error::InvalidPrefix { prefix: prefix.into(), }); } - // Checks if the prefix forms a valid identifier length when constructed with `u64::MIN` - validate_identifier_length( - &format!("{prefix}-{}", u64::MIN), - min_id_length, - max_id_length, - )?; - - // Checks if the prefix forms a valid identifier length when constructed with `u64::MAX` - validate_identifier_length( - &format!("{prefix}-{}", u64::MAX), - min_id_length, - max_id_length, - )?; + // Checks if the prefix forms a valid identifier length when constructed with `u64::MIN` and `u64::MAX` + // Checks `prefix` directly adding the 2 and 21 chars for the separator and the `u64::MIN` and `u64::MAX` value. + // Valid condition: (min <= len + 2 <= max) && (min <= len + 21 <= max) which can be simplified to: + // (min <= len + 2) && (len + 21 <= max) + if (prefix.len() as u64 + 2) < min_id_length || (prefix.len() as u64 + 21) > max_id_length { + return Err(Error::InvalidLength { + id: prefix.into(), + length: prefix.len() as u64, + min: min_id_length, + max: max_id_length, + }); + } Ok(()) }