This is a rebased and squashed version of #767, adding safegcd-based implementations of constant-time and variable-time modular inverses for scalars and field elements, by Peter Dettman. The PR is organized as follows:
- Add secp256k1_ctz{32,64}_var functions Introduction of ctz functions to util.h (which use
__builtin_ctz
on recent GCC and Clang, but fall back to using a software emulation using de Bruijn on other platforms). This isn’t used anywhere in this commit, but does include tests. - Add safegcd based modular inverse modules Add Peter Dettman’s safegcd code from #767 (without some of his optimizations, which are moved to later commits), turned into separate modules by me.
- Add extensive comments on the safegcd algorithm and implementation Add a long description of the algorithm and optimizations to
doc/safegcd_implementation.md
, as well as additional comments to the code itself. It is probably best to review this together with the previous commit (they’re separated to keep authorship). - Add tests for modinv modules Adds tests on the modinv interface directly, for arbitrary moduli.
- Improve bounds checks in modinv modules Adds a lot of sanity checking to the modinv modules.
- Move secp256k1_scalar_{inverse{_var},is_even} to per-impl files A pure refactor to prepare for switching the field and scalar code to modinv.
- Make field/scalar code use the new modinv modules for inverses Actually switch over.
- Add extra modular inverse tests This adds modular inverse tests through the field/scalar interface, now that those use modinv.
- Remove unused Jacobi symbol support No longer needed.
- Remove num/gmp support Bye-bye.
- 3 commits with further optimizations.