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