From 5bad6b6ea6eda7ef82840a98dc938459c944be53 Mon Sep 17 00:00:00 2001 From: Diego K <43053772+diegokingston@users.noreply.github.com> Date: Fri, 30 Aug 2024 18:27:39 -0300 Subject: [PATCH] fix overflow sum (#900) Co-authored-by: Mauro Toscano <12560266+MauroToscano@users.noreply.github.com> --- .../fields/montgomery_backed_prime_fields.rs | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/math/src/field/fields/montgomery_backed_prime_fields.rs b/math/src/field/fields/montgomery_backed_prime_fields.rs index d2c426330..763d77526 100644 --- a/math/src/field/fields/montgomery_backed_prime_fields.rs +++ b/math/src/field/fields/montgomery_backed_prime_fields.rs @@ -224,15 +224,17 @@ where if v <= u { u = u - v; if b < c { - b = b + modulus; + b = modulus - c + b; + } else { + b = b - c; } - b = b - c; } else { v = v - u; if c < b { - c = c + modulus; + c = modulus - b + c; + } else { + c = c - b; } - c = c - b; } } @@ -1243,6 +1245,14 @@ mod tests_u256_prime_fields { assert_eq!(minus_3_pow_2, nine); } + #[test] + fn secp256k1_inv_works() { + let a = SecpMontElement::from_hex_unchecked("0x456"); + let a_inv = a.inv().unwrap(); + + assert_eq!(a * a_inv, SecpMontElement::one()); + } + #[test] fn test_cios_overflow_case() { let a = GoldilocksElement::from(732582227915286439);