Skip to content

Commit

Permalink
Add functions to compute ellswift encoding, x-only ECDH
Browse files Browse the repository at this point in the history
Co-authored-by: Pieter Wuille <pieter.wuille@gmail.com>
  • Loading branch information
stratospher and sipa committed Dec 12, 2022
1 parent f676008 commit a9c2165
Showing 1 changed file with 25 additions and 1 deletion.
26 changes: 25 additions & 1 deletion test/functional/test_framework/ellswift.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
WARNING: This code is slow and uses bad randomness.
Do not use for anything but tests."""

from .key import FE, GE
import random

from .key import FE, GE, SECP256K1_G

MINUS_3_SQRT = FE(-3).sqrt()

Expand Down Expand Up @@ -52,3 +54,25 @@ def xswiftec_inv(x, u, case):
if case & 4:
w = -w
return w * (u * (MINUS_3_SQRT + 1) / 2 + v)

def xelligatorswift(x):
"""Given a field element X on the curve, find (u, t) that encode them."""
while True:
u = FE(random.randrange(1, GE.ORDER))
case = random.randrange(0, 8)
t = xswiftec_inv(x, u, case)
if t is not None:
return u, t

def ellswift_create():
"""Generate a (privkey, ellswift_pubkey) pair."""
priv = random.randrange(1, GE.ORDER)
u, t = xelligatorswift((priv * SECP256K1_G).x)
return priv.to_bytes(32, 'big'), u.to_bytes() + t.to_bytes()

def ellswift_ecdh_xonly(pubkey_theirs, privkey):
"""Compute X coordinate of shared ECDH point between ellswift pubkey and privkey."""
u = FE(int.from_bytes(pubkey_theirs[:32], 'big'))
t = FE(int.from_bytes(pubkey_theirs[32:], 'big'))
d = int.from_bytes(privkey, 'big')
return (d * GE.lift_x(xswiftec(u, t))).x.to_bytes()

0 comments on commit a9c2165

Please sign in to comment.