From f9de91f25c44d98c982289f5585dda5ba471f719 Mon Sep 17 00:00:00 2001 From: VolodymyrBg Date: Sat, 1 Feb 2025 10:09:02 +0200 Subject: [PATCH] feat(acir_field): Add little-endian byte serialization for FieldElement --- acvm-repo/acir_field/src/field_element.rs | 28 ++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/acvm-repo/acir_field/src/field_element.rs b/acvm-repo/acir_field/src/field_element.rs index 0249b410aa7..cea0e4537ed 100644 --- a/acvm-repo/acir_field/src/field_element.rs +++ b/acvm-repo/acir_field/src/field_element.rs @@ -274,15 +274,19 @@ impl AcirField for FieldElement { } fn to_be_bytes(self) -> Vec { - // to_be_bytes! uses little endian which is why we reverse the output - // TODO: Add a little endian equivalent, so the caller can use whichever one - // TODO they desire let mut bytes = Vec::new(); self.0.serialize_uncompressed(&mut bytes).unwrap(); bytes.reverse(); bytes } + /// Converts the field element to a vector of bytes in little-endian order + fn to_le_bytes(self) -> Vec { + let mut bytes = Vec::new(); + self.0.serialize_uncompressed(&mut bytes).unwrap(); + bytes + } + /// Converts bytes into a FieldElement and applies a /// reduction if needed. fn from_be_bytes_reduce(bytes: &[u8]) -> FieldElement { @@ -405,6 +409,24 @@ mod tests { assert_eq!(max_num_bits_bn254, 254); } + #[test] + fn test_endianness() { + let field = FieldElement::::from(0x1234_5678_u32); + let le_bytes = field.to_le_bytes(); + let be_bytes = field.to_be_bytes(); + + // Check that the bytes are reversed between BE and LE + let mut reversed_le = le_bytes.clone(); + reversed_le.reverse(); + assert_eq!(be_bytes, reversed_le); + + // Verify we can reconstruct the same field element from either byte order + let from_le = FieldElement::from_be_bytes_reduce(&reversed_le); + let from_be = FieldElement::from_be_bytes_reduce(&be_bytes); + assert_eq!(from_le, from_be); + assert_eq!(from_le, field); + } + proptest! { // This currently panics due to the fact that we allow inputs which are greater than the field modulus, // automatically reducing them to fit within the canonical range.