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