Skip to content

Commit 8424fd1

Browse files
committed
Convert the encoding and decoding functions into python code
1 parent 4ec1397 commit 8424fd1

File tree

1 file changed

+24
-14
lines changed

1 file changed

+24
-14
lines changed

test/functional/test_framework/ellsq.py

Lines changed: 24 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
anything but tests."""
77

88
import random
9+
import secrets
910
import unittest
1011

1112
from .key import modsqrt, SECP256K1, SECP256K1_FIELD_SIZE, SECP256K1_G, SECP256K1_ORDER
@@ -103,35 +104,44 @@ def r(x,y,i):
103104

104105
def encode(P):
105106
while True:
106-
u = field_random()
107-
T = curve_negate(f(u))
108-
Q = curve_add(T, P)
109-
if is_infinity(Q): Q = T
107+
u = fe(random.randrange(1, SECP256K1_ORDER))
108+
fe1 = f(u)
109+
# convert fe1 to jacobian form for EC operations
110+
fe1 = (fe1[0].val, fe1[1].val, 1)
111+
T = SECP256K1.negate(fe1)
112+
Q = SECP256K1.add(T, P)
113+
if SECP256K1.on_curve(Q) is None: Q = T
110114
j = secrets.choice([1,2,3,4])
111-
v = r(Q, j)
112-
if v is not Nothing: return (u, v)
115+
Q = SECP256K1.affine(Q)
116+
v = r(fe(Q[0]), fe(Q[1]), j)
117+
if v is not None: return (u, v)
113118

114119
def decode(u, v):
115-
T = f(u)
116-
P = curve_add(T, f(v))
117-
if is_infinity(P): P = T
118-
return P
120+
fe1 = f(u)
121+
fe2 = f(v)
122+
# convert fe1 and fe2 to jacobian form for EC operations
123+
jac1 = (fe1[0].val, fe1[1].val, 1)
124+
jac2 = (fe2[0].val, fe2[1].val, 1)
125+
T = jac1
126+
S = jac2
127+
P = SECP256K1.affine(SECP256K1.add(T, S))
128+
if P is None: P = T # affine() returns None if at infinity.
129+
return (fe(P[0]), fe(P[1]))
119130

120131
P = SECP256K1_FIELD_SIZE
121132
FIELD_BITS = P.bit_length()
122133
FIELD_BYTES = (FIELD_BITS + 7) // 8
123-
PAD_BITS = FIELD_BYTES*8 - FIELD_BITS
124134

125135
def encode_bytes(P):
126136
u, v = encode(P)
127-
up = u + secrets.randbits(PAD_BITS) << FIELD_BITS
128-
vp = v + secrets.randbits(PAD_BITS) << FIELD_BITS
137+
up = u.val # since, PAD_BITS is 0, padding and masking can be left out
138+
vp = v.val
129139
return up.to_bytes(FIELD_BYTES, 'big') + vp.to_bytes(FIELD_BYTES, 'big')
130140

131141
def decode_bytes(enc):
132142
u = (int.from_bytes(enc[:FIELD_BYTES], 'big') & ((1 << FIELD_BITS) - 1)) % P
133143
v = (int.from_bytes(enc[FIELD_BYTES:], 'big') & ((1 << FIELD_BITS) - 1)) % P
134-
return decode(u, v)
144+
return decode(fe(u), fe(v))
135145

136146
def SECP256K1_FE_CONST(d7, d6, d5, d4, d3, d2, d1, d0):
137147
n = []

0 commit comments

Comments
 (0)