Skip to content

Instantly share code, notes, and snippets.

@sanket1729
Created December 14, 2020 18:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sanket1729/1b85a233452b0fc83ff3a7781ae48543 to your computer and use it in GitHub Desktop.
Save sanket1729/1b85a233452b0fc83ff3a7781ae48543 to your computer and use it in GitHub Desktop.
def normalize(sign, v, modulus):
"""Compute sign*v mod modulus, where v in (-2*modulus,modulus); output in [0,modulus)."""
ans = (sign*v) % modulus
v += modulus & (v >> 256) # I think this line is wrong when v has 257th bit set and 256 unset
c = (sign - 1) >> 1
v = (v ^ c) - c
v += modulus & (v >> 256)
assert ans == (v % modulus), print(ans, v)
return v
def normalize_var(sign, v, modulus):
"""Compute sign*v mod modulus, where v in (-2*modulus,modulus); output in [0,modulus)."""
assert sign == 1 or sign == -1
# v in (-2*modulus,modulus)
if v < 0:
v += modulus
# v in (-modulus,modulus)
if sign == -1:
v =-v
if v < 0:
v += modulus
# v in [0,modulus)
# assert v >=0 and v < modulas
return v
sign = 1
v = -136834439519537824422704808331812250261221278517316523901929417126851299120761
secp_mod = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
assert -2* secp_mod < v < secp_mod, "Initial condition not satisfied"
assert normalize(sign, v, secp_mod) == normalize_var(sign, v, secp_mod), "Normalizations must be equal"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment