Skip to content

Commit 58ea273

Browse files
authored
Merge pull request #220 from tomato42/fast-native-inverse
use native inverse modulo when available
2 parents 90bb8ae + 0d5dffa commit 58ea273

File tree

2 files changed

+18
-7
lines changed

2 files changed

+18
-7
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: 17 additions & 7 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,7 +220,7 @@ 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."""
@@ -228,14 +229,14 @@ def inverse_mod(a, m):
228229
return powmod(a, -1, m)
229230

230231

231-
elif GMPY:
232+
elif GMPY: # pragma: no branch
232233

233234
def inverse_mod(a, m):
234235
"""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
236+
# while libgmp does support inverses modulo, it is accessible
237+
# only using the native `pow()` function, and `pow()` in gmpy sanity
238+
# checks the parameters before passing them on to underlying
239+
# implementation
239240
if a == 0:
240241
return 0
241242
a = mpz(a)
@@ -250,7 +251,16 @@ def inverse_mod(a, m):
250251
return lm % m
251252

252253

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

255265
def inverse_mod(a, m):
256266
"""Inverse of a mod m."""

0 commit comments

Comments
 (0)