From 11420a7a2836114393b70f4d10bb81921403a360 Mon Sep 17 00:00:00 2001 From: Sebastian Falbesoner Date: Thu, 1 Feb 2024 00:28:45 +0100 Subject: [PATCH 1/2] tests: improve fe_sqr test Currently the `run_sqr` test doesn't do anything with the result of the `fe_sqr` call. Improve that by checking that the equation `(x+y)*(x-y) = x^2 - y^2` holds for some random values y, as suggested in issue #1471 by real-or-random. The existing loop for generating the x values is kept as-is. --- src/tests.c | 33 +++++++++++++++++++++++---------- 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/src/tests.c b/src/tests.c index 1caee85e15..85b4881295 100644 --- a/src/tests.c +++ b/src/tests.c @@ -3285,18 +3285,31 @@ static void run_fe_mul(void) { } static void run_sqr(void) { - secp256k1_fe x, s; + int i; + secp256k1_fe x, y, lhs, rhs, tmp; - { - int i; - secp256k1_fe_set_int(&x, 1); - secp256k1_fe_negate(&x, &x, 1); + secp256k1_fe_set_int(&x, 1); + secp256k1_fe_negate(&x, &x, 1); - for (i = 1; i <= 512; ++i) { - secp256k1_fe_mul_int(&x, 2); - secp256k1_fe_normalize(&x); - secp256k1_fe_sqr(&s, &x); - } + for (i = 1; i <= 512; ++i) { + secp256k1_fe_mul_int(&x, 2); + secp256k1_fe_normalize(&x); + + /* Check that (x+y)*(x-y) = x^2 - y*2 for some random values y */ + random_fe_test(&y); + + lhs = x; + secp256k1_fe_add(&lhs, &y); /* lhs = x+y */ + secp256k1_fe_negate(&tmp, &y, 1); /* tmp = -y */ + secp256k1_fe_add(&tmp, &x); /* tmp = x-y */ + secp256k1_fe_mul(&lhs, &lhs, &tmp); /* lhs = (x+y)*(x-y) */ + + secp256k1_fe_sqr(&rhs, &x); /* rhs = x^2 */ + secp256k1_fe_sqr(&tmp, &y); /* tmp = y^2 */ + secp256k1_fe_negate(&tmp, &tmp, 1); /* tmp = -y^2 */ + secp256k1_fe_add(&rhs, &tmp); /* rhs = x^2 - y^2 */ + + CHECK(fe_equal(&lhs, &rhs)); } } From 2028069df2e16a05b332ae24c7ae63791f461063 Mon Sep 17 00:00:00 2001 From: Sebastian Falbesoner Date: Thu, 1 Feb 2024 14:46:31 +0100 Subject: [PATCH 2/2] doc: clarify input requirements for secp256k1_fe_mul "... neither can be equal to b." could suggest that the values are not allowed to be identical, but what is meant here is that the mentioned inputs shouldn't point to the same object. --- src/field.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/field.h b/src/field.h index bd589bf8a8..8c65a3aff6 100644 --- a/src/field.h +++ b/src/field.h @@ -255,8 +255,8 @@ static void secp256k1_fe_add(secp256k1_fe *r, const secp256k1_fe *a); /** Multiply two field elements. * * On input, a and b must be valid field elements; r does not need to be initialized. - * r and a may point to the same object, but neither can be equal to b. The magnitudes - * of a and b must not exceed 8. + * r and a may point to the same object, but neither may point to the object pointed + * to by b. The magnitudes of a and b must not exceed 8. * Performs {r = a * b} * On output, r will have magnitude 1, but won't be normalized. */