-
Notifications
You must be signed in to change notification settings - Fork 60
Constant-time square root and division #376
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
The initial guess is 2^(ceil(bits/2)), which is always greater than sqrt(self), so initially `xn < guess`, which means the removed while loop never runs.
This makes `Uint::sqrt` constant-time as well.
Casts to `Word` are causing issues on 32-bit platforms
26b3547
to
60fb612
Compare
I am still uncertain about whether there's an off-by-1 error. First, I think I made a mistake in my previous comment saying that we can use Second, I wrote a Python implementation to test it, and it seems that while the paper claims that one needs to take assert_eq!(
U256::from_be_hex("4bb750738e25a8f82940737d94a48a91f8cd918a3679ff90c1a631f2bd6c3597").sqrt(),
U256::from_be_hex("000000000000000000000000000000008b3956339e8315cff66eb6107b610075")); Here the number is
and the square root is For reference, the Python implementation: import math
import random
def sqrt_test(x, x_bits):
log2_bits = int(math.log2(x_bits))
max_bits = (x.bit_length() + 1) // 2
xn = 1 << max_bits # x_0
i = 0
print(f"x = {x}")
print(f"log2(b)+1 =", log2_bits + 1)
print(f"x_{i} = {xn}")
while i < log2_bits - 1:
guess = xn
xn = (guess + x // guess) // 2
i += 1
print(f"x_{i} = {xn}")
return min(guess, xn)
if __name__ == '__main__':
for x in range(1, 2**16):
t = sqrt_test(x, 16)
assert t**2 <= x < (t+1)**2 |
If you want to finalize it, we can:
|
A test for
This also uses up the maximum number of iterations |
6e6899d
to
927ebaf
Compare
No, the Python code is just to document what I was using for cross-checking. I'm approving this, you can merge, and then I'll make a separate PR for the items from #376 (comment) |
This is the implementation from #277, rebased and with most of the review comments addressed.
This was already getting a bit hard to rebase, so if we can get it over the finish line before it becomes too stale that seems good.
cc @HastD