Skip to content

Commit

Permalink
Optimize addmod() for elliptic curve context
Browse files Browse the repository at this point in the history
In elliptic curve context the x and y arguments are already reduced
modulo mod. Here we can pick up similar condition and provide optimized
implementation for such case. This case is 2x faster with little
overhead for other cases.

Based on holiman/uint256#86.
  • Loading branch information
chfast committed Dec 17, 2021
1 parent e05e571 commit 2670a82
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions include/intx/intx.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -1943,6 +1943,24 @@ inline constexpr uint<N>& operator>>=(uint<N>& x, const T& y) noexcept

inline uint256 addmod(const uint256& x, const uint256& y, const uint256& mod) noexcept
{
// Fast path for mod >= 2^192, with x and y at most slightly bigger than mod.
// This is always the case when x and y are already reduced modulo mod.
// Based on https://github.com/holiman/uint256/pull/86.
if ((mod[3] != 0) && (x[3] <= mod[3]) && (y[3] <= mod[3]))
{
auto s = sub_with_carry(x, mod);
if (s.carry)
s.value = x;

auto t = sub_with_carry(y, mod);
if (t.carry)
t.value = y;

s = add_with_carry(s.value, t.value);
t = sub_with_carry(s.value, mod);
return (s.carry || !t.carry) ? t.value : s.value;
}

const auto s = add_with_carry(x, y);
uint<256 + 64> n = s.value;
n[4] = s.carry;
Expand Down

0 comments on commit 2670a82

Please sign in to comment.