Skip to content

Commit b702461

Browse files
committed
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 bitcoin-core#1471 by real-or-random. The existing loop for generating the x values is kept as-is.
1 parent 0653a25 commit b702461

File tree

1 file changed

+23
-10
lines changed

1 file changed

+23
-10
lines changed

src/tests.c

Lines changed: 23 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3285,18 +3285,31 @@ static void run_fe_mul(void) {
32853285
}
32863286

32873287
static void run_sqr(void) {
3288-
secp256k1_fe x, s;
3288+
int i;
3289+
secp256k1_fe x, y, lhs, rhs, tmp;
32893290

3290-
{
3291-
int i;
3292-
secp256k1_fe_set_int(&x, 1);
3293-
secp256k1_fe_negate(&x, &x, 1);
3291+
secp256k1_fe_set_int(&x, 1);
3292+
secp256k1_fe_negate(&x, &x, 1);
32943293

3295-
for (i = 1; i <= 512; ++i) {
3296-
secp256k1_fe_mul_int(&x, 2);
3297-
secp256k1_fe_normalize(&x);
3298-
secp256k1_fe_sqr(&s, &x);
3299-
}
3294+
for (i = 1; i <= 512; ++i) {
3295+
secp256k1_fe_mul_int(&x, 2);
3296+
secp256k1_fe_normalize(&x);
3297+
3298+
/* Check that (x+y)*(x-y) = x^2 - y*2 for some random values y */
3299+
random_fe_test(&y);
3300+
3301+
lhs = x;
3302+
secp256k1_fe_add(&lhs, &y); /* lhs = x+y */
3303+
secp256k1_fe_negate(&tmp, &y, 1); /* tmp = -y */
3304+
secp256k1_fe_add(&tmp, &x); /* tmp = x-y */
3305+
secp256k1_fe_mul(&lhs, &lhs, &tmp); /* lhs = (x+y)*(x-y) */
3306+
3307+
secp256k1_fe_sqr(&rhs, &x); /* rhs = x^2 */
3308+
secp256k1_fe_sqr(&tmp, &y); /* tmp = y^2 */
3309+
secp256k1_fe_negate(&tmp, &tmp, 1); /* tmp = -y^2 */
3310+
secp256k1_fe_add(&rhs, &tmp); /* rhs = x^2 - y^2 */
3311+
3312+
CHECK(check_fe_equal(&lhs, &rhs));
33003313
}
33013314
}
33023315

0 commit comments

Comments
 (0)