Skip to content

Commit 6d6102f

Browse files
committed
A few improvements to the sqrt tests
1 parent 5355746 commit 6d6102f

File tree

1 file changed

+38
-10
lines changed

1 file changed

+38
-10
lines changed

src/tests.c

Lines changed: 38 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -217,18 +217,26 @@ void random_fe(secp256k1_fe_t *x) {
217217
secp256k1_fe_set_b32(x, bin);
218218
}
219219

220-
void random_fe_non_square(secp256k1_fe_t *ns) {
221-
secp256k1_fe_t r;
222-
int tries = 100;
220+
void random_fe_non_zero(secp256k1_fe_t *nz) {
221+
int tries = 10;
223222
while (--tries >= 0) {
224-
random_fe(ns);
225-
if (!secp256k1_fe_sqrt(&r, ns))
223+
random_fe(nz);
224+
secp256k1_fe_normalize(nz);
225+
if (!secp256k1_fe_is_zero(nz))
226226
break;
227227
}
228-
// 2^-100 probability of spurious failure here
228+
// Infinitesimal probability of spurious failure here
229229
assert(tries >= 0);
230230
}
231231

232+
void random_fe_non_square(secp256k1_fe_t *ns) {
233+
random_fe_non_zero(ns);
234+
secp256k1_fe_t r;
235+
if (secp256k1_fe_sqrt(&r, ns)) {
236+
secp256k1_fe_negate(ns, ns, 1);
237+
}
238+
}
239+
232240
void test_sqrt(const secp256k1_fe_t *a, const secp256k1_fe_t *k) {
233241
secp256k1_fe_t r1, r2;
234242
int v = secp256k1_fe_sqrt(&r1, a);
@@ -245,14 +253,34 @@ void test_sqrt(const secp256k1_fe_t *a, const secp256k1_fe_t *k) {
245253

246254
void run_sqrt() {
247255
secp256k1_fe_t ns, x, s, t;
248-
random_fe_non_square(&ns);
249-
for (int i=0; i<10*count; i++) {
250-
random_fe(&x);
256+
257+
// Check sqrt(0) is 0
258+
secp256k1_fe_set_int(&x, 0);
259+
secp256k1_fe_sqr(&s, &x);
260+
test_sqrt(&s, &x);
261+
262+
// Check sqrt of small squares (and their negatives)
263+
for (int i=1; i<=100; i++) {
264+
secp256k1_fe_set_int(&x, i);
251265
secp256k1_fe_sqr(&s, &x);
252266
test_sqrt(&s, &x);
253-
secp256k1_fe_mul(&t, &s, &ns);
267+
secp256k1_fe_negate(&t, &s, 1);
254268
test_sqrt(&t, NULL);
255269
}
270+
271+
// Consistency checks for large random values
272+
for (int i=0; i<10; i++) {
273+
random_fe_non_square(&ns);
274+
for (int j=0; j<count; j++) {
275+
random_fe(&x);
276+
secp256k1_fe_sqr(&s, &x);
277+
test_sqrt(&s, &x);
278+
secp256k1_fe_negate(&t, &s, 1);
279+
test_sqrt(&t, NULL);
280+
secp256k1_fe_mul(&t, &s, &ns);
281+
test_sqrt(&t, NULL);
282+
}
283+
}
256284
}
257285

258286
/***** ECMULT TESTS *****/

0 commit comments

Comments
 (0)