@@ -201,6 +201,7 @@ static void secp256k1_modinv64_update_de_62(secp256k1_modinv64_signed62 *d, secp
201
201
md -= (modinfo -> modulus_inv62 * (uint64_t )cd + md ) & M62 ;
202
202
me -= (modinfo -> modulus_inv62 * (uint64_t )ce + me ) & M62 ;
203
203
204
+ /* The modulus has to be odd, so we can assume it is nonzero. */
204
205
cd += (int128_t )modinfo -> modulus .v [0 ] * md ;
205
206
ce += (int128_t )modinfo -> modulus .v [0 ] * me ;
206
207
@@ -210,33 +211,43 @@ static void secp256k1_modinv64_update_de_62(secp256k1_modinv64_signed62 *d, secp
210
211
cd += (int128_t )u * d1 + (int128_t )v * e1 ;
211
212
ce += (int128_t )q * d1 + (int128_t )r * e1 ;
212
213
213
- cd += (int128_t )modinfo -> modulus .v [1 ] * md ;
214
- ce += (int128_t )modinfo -> modulus .v [1 ] * me ;
214
+ /* Limb 1 of the modulus may be zero (optimization). */
215
+ if (modinfo -> modulus .v [1 ]) {
216
+ cd += (int128_t )modinfo -> modulus .v [1 ] * md ;
217
+ ce += (int128_t )modinfo -> modulus .v [1 ] * me ;
218
+ }
215
219
216
220
d -> v [0 ] = (int64_t )cd & M62 ; cd >>= 62 ;
217
221
e -> v [0 ] = (int64_t )ce & M62 ; ce >>= 62 ;
218
222
219
223
cd += (int128_t )u * d2 + (int128_t )v * e2 ;
220
224
ce += (int128_t )q * d2 + (int128_t )r * e2 ;
221
225
222
- cd += (int128_t )modinfo -> modulus .v [2 ] * md ;
223
- ce += (int128_t )modinfo -> modulus .v [2 ] * me ;
226
+ /* Limb 2 of the modulus may be zero (optimization). */
227
+ if (modinfo -> modulus .v [2 ]) {
228
+ cd += (int128_t )modinfo -> modulus .v [2 ] * md ;
229
+ ce += (int128_t )modinfo -> modulus .v [2 ] * me ;
230
+ }
224
231
225
232
d -> v [1 ] = (int64_t )cd & M62 ; cd >>= 62 ;
226
233
e -> v [1 ] = (int64_t )ce & M62 ; ce >>= 62 ;
227
234
228
235
cd += (int128_t )u * d3 + (int128_t )v * e3 ;
229
236
ce += (int128_t )q * d3 + (int128_t )r * e3 ;
230
237
231
- cd += (int128_t )modinfo -> modulus .v [3 ] * md ;
232
- ce += (int128_t )modinfo -> modulus .v [3 ] * me ;
238
+ /* Limb 3 of the modulus may be zero (optimization). */
239
+ if (modinfo -> modulus .v [3 ]) {
240
+ cd += (int128_t )modinfo -> modulus .v [3 ] * md ;
241
+ ce += (int128_t )modinfo -> modulus .v [3 ] * me ;
242
+ }
233
243
234
244
d -> v [2 ] = (int64_t )cd & M62 ; cd >>= 62 ;
235
245
e -> v [2 ] = (int64_t )ce & M62 ; ce >>= 62 ;
236
246
237
247
cd += (int128_t )u * d4 + (int128_t )v * e4 ;
238
248
ce += (int128_t )q * d4 + (int128_t )r * e4 ;
239
249
250
+ /* As this is for 256-bit operations, assume the top limb is nonzero. */
240
251
cd += (int128_t )modinfo -> modulus .v [4 ] * md ;
241
252
ce += (int128_t )modinfo -> modulus .v [4 ] * me ;
242
253
0 commit comments