@@ -217,18 +217,26 @@ void random_fe(secp256k1_fe_t *x) {
217
217
secp256k1_fe_set_b32 (x , bin );
218
218
}
219
219
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 ;
223
222
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 ))
226
226
break ;
227
227
}
228
- // 2^-100 probability of spurious failure here
228
+ // Infinitesimal probability of spurious failure here
229
229
assert (tries >= 0 );
230
230
}
231
231
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
+
232
240
void test_sqrt (const secp256k1_fe_t * a , const secp256k1_fe_t * k ) {
233
241
secp256k1_fe_t r1 , r2 ;
234
242
int v = secp256k1_fe_sqrt (& r1 , a );
@@ -245,14 +253,34 @@ void test_sqrt(const secp256k1_fe_t *a, const secp256k1_fe_t *k) {
245
253
246
254
void run_sqrt () {
247
255
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 );
251
265
secp256k1_fe_sqr (& s , & x );
252
266
test_sqrt (& s , & x );
253
- secp256k1_fe_mul (& t , & s , & ns );
267
+ secp256k1_fe_negate (& t , & s , 1 );
254
268
test_sqrt (& t , NULL );
255
269
}
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
+ }
256
284
}
257
285
258
286
/***** ECMULT TESTS *****/
0 commit comments