mirror of
https://github.com/bitcoin/bips.git
synced 2025-02-26 00:14:27 +01:00
Add x() and y() functions for points to bip-schnorr
This commit is contained in:
parent
8d893f9c06
commit
7e273fbda6
1 changed files with 15 additions and 9 deletions
|
@ -11,19 +11,25 @@ def tagged_hash(tag, msg):
|
|||
tag_hash = hashlib.sha256(tag.encode()).digest()
|
||||
return hashlib.sha256(tag_hash + tag_hash + msg).digest()
|
||||
|
||||
def x(P):
|
||||
return P[0]
|
||||
|
||||
def y(P):
|
||||
return P[1]
|
||||
|
||||
def point_add(P1, P2):
|
||||
if (P1 is None):
|
||||
return P2
|
||||
if (P2 is None):
|
||||
return P1
|
||||
if (P1[0] == P2[0] and P1[1] != P2[1]):
|
||||
if (x(P1) == x(P2) and y(P1) != y(P2)):
|
||||
return None
|
||||
if (P1 == P2):
|
||||
lam = (3 * P1[0] * P1[0] * pow(2 * P1[1], p - 2, p)) % p
|
||||
lam = (3 * x(P1) * x(P1) * pow(2 * y(P1), p - 2, p)) % p
|
||||
else:
|
||||
lam = ((P2[1] - P1[1]) * pow(P2[0] - P1[0], p - 2, p)) % p
|
||||
x3 = (lam * lam - P1[0] - P2[0]) % p
|
||||
return (x3, (lam * (P1[0] - x3) - P1[1]) % p)
|
||||
lam = ((y(P2) - y(P1)) * pow(x(P2) - x(P1), p - 2, p)) % p
|
||||
x3 = (lam * lam - x(P1) - x(P2)) % p
|
||||
return (x3, (lam * (x(P1) - x3) - y(P1)) % p)
|
||||
|
||||
def point_mul(P, n):
|
||||
R = None
|
||||
|
@ -37,7 +43,7 @@ def bytes_from_int(x):
|
|||
return x.to_bytes(32, byteorder="big")
|
||||
|
||||
def bytes_from_point(P):
|
||||
return bytes_from_int(P[0])
|
||||
return bytes_from_int(x(P))
|
||||
|
||||
def point_from_bytes(b):
|
||||
x = int_from_bytes(b)
|
||||
|
@ -66,12 +72,12 @@ def schnorr_sign(msg, seckey0):
|
|||
if not (1 <= seckey0 <= n - 1):
|
||||
raise ValueError('The secret key must be an integer in the range 1..n-1.')
|
||||
P = point_mul(G, seckey0)
|
||||
seckey = seckey0 if (jacobi(P[1]) == 1) else n - seckey0
|
||||
seckey = seckey0 if (jacobi(y(P)) == 1) else n - seckey0
|
||||
k0 = int_from_bytes(tagged_hash("BIPSchnorrDerive", bytes_from_int(seckey) + msg)) % n
|
||||
if k0 == 0:
|
||||
raise RuntimeError('Failure. This happens only with negligible probability.')
|
||||
R = point_mul(G, k0)
|
||||
k = n - k0 if (jacobi(R[1]) != 1) else k0
|
||||
k = n - k0 if (jacobi(y(R)) != 1) else k0
|
||||
e = int_from_bytes(tagged_hash("BIPSchnorr", bytes_from_point(R) + bytes_from_point(P) + msg)) % n
|
||||
return bytes_from_point(R) + bytes_from_int((k + e * seckey) % n)
|
||||
|
||||
|
@ -91,7 +97,7 @@ def schnorr_verify(msg, pubkey, sig):
|
|||
return False
|
||||
e = int_from_bytes(tagged_hash("BIPSchnorr", sig[0:32] + pubkey + msg)) % n
|
||||
R = point_add(point_mul(G, s), point_mul(P, n - e))
|
||||
if R is None or jacobi(R[1]) != 1 or R[0] != r:
|
||||
if R is None or jacobi(y(R)) != 1 or x(R) != r:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
|
Loading…
Add table
Reference in a new issue