Skip to content

Commit 6178f4c

Browse files
committed
use native inverse modulo when available
the builtin pow() can handle negative powers on python 3.8 and later, so do use it
1 parent 90bb8ae commit 6178f4c

File tree

2 files changed

+16
-8
lines changed

2 files changed

+16
-8
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ If `gmpy2` or `gmpy` is installed, they will be used for faster arithmetic.
4242
Either of them can be installed after this library is installed,
4343
`python-ecdsa` will detect their presence on start-up and use them
4444
automatically.
45+
You should prefer `gmpy2` on Python3 for optimal performance.
4546

4647
To run the OpenSSL compatibility tests, the 'openssl' tool must be in your
4748
`PATH`. This release has been tested successfully against OpenSSL 0.9.8o,

src/ecdsa/numbertheory.py

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
from __future__ import division
1313

14+
import sys
1415
from six import integer_types, PY2
1516
from six.moves import reduce
1617

@@ -219,23 +220,22 @@ def square_root_mod_prime(a, p):
219220
raise RuntimeError("No b found.")
220221

221222

222-
if GMPY2:
223+
if GMPY2: # pragma: no branch
223224

224225
def inverse_mod(a, m):
225226
"""Inverse of a mod m."""
226227
if a == 0:
227228
return 0
228229
return powmod(a, -1, m)
229230

230-
231-
elif GMPY:
231+
elif GMPY: # pragma: no branch
232232

233233
def inverse_mod(a, m):
234234
"""Inverse of a mod m."""
235-
# while libgmp likely does support inverses modulo, it is accessible
236-
# only using the native `pow()` function, and `pow()` sanity checks
237-
# the parameters before passing them on to underlying implementation
238-
# on Python2
235+
# while libgmp does support inverses modulo, it is accessible
236+
# only using the native `pow()` function, and `pow()` in gmpy sanity
237+
# checks the parameters before passing them on to underlying
238+
# implementation
239239
if a == 0:
240240
return 0
241241
a = mpz(a)
@@ -249,8 +249,15 @@ def inverse_mod(a, m):
249249

250250
return lm % m
251251

252+
elif sys.version_info >= (3, 8): # pragma: no branch
253+
254+
def inverse_mod(a, m):
255+
"""Inverse of a mod m."""
256+
if a == 0:
257+
return 0
258+
return pow(a, -1, m)
252259

253-
else:
260+
else: # pragma: no branch
254261

255262
def inverse_mod(a, m):
256263
"""Inverse of a mod m."""

0 commit comments

Comments
 (0)