1 #!/usr/bin/env python3
2 # Copyright (c) 2022 The Limenka developers
3 # Distributed under the MIT software license, see the accompanying
4 # file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 """Test-only Elligator Swift implementation
6 7 WARNING: This code is slow and uses bad randomness.
8 Do not use for anything but tests."""
9 10 import csv
11 import os
12 import random
13 import unittest
14 15 from test_framework.crypto.secp256k1 import FE, G, GE
16 17 # Precomputed constant square root of -3 (mod p).
18 MINUS_3_SQRT = FE(-3).sqrt()
19 20 def xswiftec(u, t):
21 """Decode field elements (u, t) to an X coordinate on the curve."""
22 if u == 0:
23 u = FE(1)
24 if t == 0:
25 t = FE(1)
26 if u**3 + t**2 + 7 == 0:
27 t = 2 * t
28 X = (u**3 + 7 - t**2) / (2 * t)
29 Y = (X + t) / (MINUS_3_SQRT * u)
30 for x in (u + 4 * Y**2, (-X / Y - u) / 2, (X / Y - u) / 2):
31 if GE.is_valid_x(x):
32 return x
33 assert False
34 35 def xswiftec_inv(x, u, case):
36 """Given x and u, find t such that xswiftec(u, t) = x, or return None.
37 38 Case selects which of the up to 8 results to return."""
39 40 if case & 2 == 0:
41 if GE.is_valid_x(-x - u):
42 return None
43 v = x
44 s = -(u**3 + 7) / (u**2 + u*v + v**2)
45 else:
46 s = x - u
47 if s == 0:
48 return None
49 r = (-s * (4 * (u**3 + 7) + 3 * s * u**2)).sqrt()
50 if r is None:
51 return None
52 if case & 1 and r == 0:
53 return None
54 v = (-u + r / s) / 2
55 w = s.sqrt()
56 if w is None:
57 return None
58 if case & 5 == 0:
59 return -w * (u * (1 - MINUS_3_SQRT) / 2 + v)
60 if case & 5 == 1:
61 return w * (u * (1 + MINUS_3_SQRT) / 2 + v)
62 if case & 5 == 4:
63 return w * (u * (1 - MINUS_3_SQRT) / 2 + v)
64 if case & 5 == 5:
65 return -w * (u * (1 + MINUS_3_SQRT) / 2 + v)
66 67 def xelligatorswift(x):
68 """Given a field element X on the curve, find (u, t) that encode them."""
69 assert GE.is_valid_x(x)
70 while True:
71 u = FE(random.randrange(1, FE.SIZE))
72 case = random.randrange(0, 8)
73 t = xswiftec_inv(x, u, case)
74 if t is not None:
75 return u, t
76 77 def ellswift_create():
78 """Generate a (privkey, ellswift_pubkey) pair."""
79 priv = random.randrange(1, GE.ORDER)
80 u, t = xelligatorswift((priv * G).x)
81 return priv.to_bytes(32, 'big'), u.to_bytes() + t.to_bytes()
82 83 def ellswift_ecdh_xonly(pubkey_theirs, privkey):
84 """Compute X coordinate of shared ECDH point between ellswift pubkey and privkey."""
85 u = FE(int.from_bytes(pubkey_theirs[:32], 'big'))
86 t = FE(int.from_bytes(pubkey_theirs[32:], 'big'))
87 d = int.from_bytes(privkey, 'big')
88 return (d * GE.lift_x(xswiftec(u, t))).x.to_bytes()
89 90 91 class TestFrameworkEllSwift(unittest.TestCase):
92 def test_xswiftec(self):
93 """Verify that xswiftec maps all inputs to the curve."""
94 for _ in range(32):
95 u = FE(random.randrange(0, FE.SIZE))
96 t = FE(random.randrange(0, FE.SIZE))
97 x = xswiftec(u, t)
98 self.assertTrue(GE.is_valid_x(x))
99 100 # Check that inputs which are considered undefined in the original
101 # SwiftEC paper can also be decoded successfully (by remapping)
102 undefined_inputs = [
103 (FE(0), FE(23)), # u = 0
104 (FE(42), FE(0)), # t = 0
105 (FE(5), FE(-132).sqrt()), # u^3 + t^2 + 7 = 0
106 ]
107 assert undefined_inputs[-1][0]**3 + undefined_inputs[-1][1]**2 + 7 == 0
108 for u, t in undefined_inputs:
109 x = xswiftec(u, t)
110 self.assertTrue(GE.is_valid_x(x))
111 112 def test_elligator_roundtrip(self):
113 """Verify that encoding using xelligatorswift decodes back using xswiftec."""
114 for _ in range(32):
115 while True:
116 # Loop until we find a valid X coordinate on the curve.
117 x = FE(random.randrange(1, FE.SIZE))
118 if GE.is_valid_x(x):
119 break
120 # Encoding it to (u, t), decode it back, and compare.
121 u, t = xelligatorswift(x)
122 x2 = xswiftec(u, t)
123 self.assertEqual(x2, x)
124 125 def test_ellswift_ecdh_xonly(self):
126 """Verify that shared secret computed by ellswift_ecdh_xonly match."""
127 for _ in range(32):
128 privkey1, encoding1 = ellswift_create()
129 privkey2, encoding2 = ellswift_create()
130 shared_secret1 = ellswift_ecdh_xonly(encoding1, privkey2)
131 shared_secret2 = ellswift_ecdh_xonly(encoding2, privkey1)
132 self.assertEqual(shared_secret1, shared_secret2)
133 134 def test_elligator_encode_testvectors(self):
135 """Implement the BIP324 test vectors for ellswift encoding (read from xswiftec_inv_test_vectors.csv)."""
136 vectors_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'xswiftec_inv_test_vectors.csv')
137 with open(vectors_file, newline='', encoding='utf8') as csvfile:
138 reader = csv.DictReader(csvfile)
139 for row in reader:
140 u = FE.from_bytes(bytes.fromhex(row['u']))
141 x = FE.from_bytes(bytes.fromhex(row['x']))
142 for case in range(8):
143 ret = xswiftec_inv(x, u, case)
144 if ret is None:
145 self.assertEqual(row[f"case{case}_t"], "")
146 else:
147 self.assertEqual(row[f"case{case}_t"], ret.to_bytes().hex())
148 self.assertEqual(xswiftec(u, ret), x)
149 150 def test_elligator_decode_testvectors(self):
151 """Implement the BIP324 test vectors for ellswift decoding (read from ellswift_decode_test_vectors.csv)."""
152 vectors_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'ellswift_decode_test_vectors.csv')
153 with open(vectors_file, newline='', encoding='utf8') as csvfile:
154 reader = csv.DictReader(csvfile)
155 for row in reader:
156 encoding = bytes.fromhex(row['ellswift'])
157 assert len(encoding) == 64
158 expected_x = FE(int(row['x'], 16))
159 u = FE(int.from_bytes(encoding[:32], 'big'))
160 t = FE(int.from_bytes(encoding[32:], 'big'))
161 x = xswiftec(u, t)
162 self.assertEqual(x, expected_x)
163 self.assertTrue(GE.is_valid_x(x))
164