|
8 | 8 | Do not use for anything but tests."""
|
9 | 9 |
|
10 | 10 | import random
|
| 11 | +import unittest |
11 | 12 |
|
12 | 13 | from test_framework.secp256k1 import FE, G, GE
|
13 | 14 |
|
@@ -81,3 +82,46 @@ def ellswift_ecdh_xonly(pubkey_theirs, privkey):
|
81 | 82 | t = FE(int.from_bytes(pubkey_theirs[32:], 'big'))
|
82 | 83 | d = int.from_bytes(privkey, 'big')
|
83 | 84 | return (d * GE.lift_x(xswiftec(u, t))).x.to_bytes()
|
| 85 | + |
| 86 | + |
| 87 | +class TestFrameworkEllSwift(unittest.TestCase): |
| 88 | + def test_elligator_forward(self): |
| 89 | + """Verify that xswiftec maps all inputs to the curve.""" |
| 90 | + for _ in range(32): |
| 91 | + u = FE(random.randrange(0, FE.SIZE)) |
| 92 | + t = FE(random.randrange(0, FE.SIZE)) |
| 93 | + x = xswiftec(u, t) |
| 94 | + self.assertTrue(GE.is_valid_x(x)) |
| 95 | + |
| 96 | + # Check that inputs which are considered undefined in the original |
| 97 | + # SwiftEC paper can also be decoded successfully (by remapping) |
| 98 | + undefined_inputs = [ |
| 99 | + (FE(0), FE(23)), # u = 0 |
| 100 | + (FE(42), FE(0)), # t = 0 |
| 101 | + (FE(5), FE(-132).sqrt()), # u^3 + t^2 + 7 = 0 |
| 102 | + ] |
| 103 | + assert undefined_inputs[-1][0]**3 + undefined_inputs[-1][1]**2 + 7 == 0 |
| 104 | + for u, t in undefined_inputs: |
| 105 | + x = xswiftec(u, t) |
| 106 | + self.assertTrue(GE.is_valid_x(x)) |
| 107 | + |
| 108 | + def test_elligator_roundtrip(self): |
| 109 | + """Verify that encoding using xelligatorswift decodes back using xswiftec.""" |
| 110 | + for _ in range(32): |
| 111 | + while True: |
| 112 | + # Loop until we find a valid X coordinate on the curve. |
| 113 | + x = FE(random.randrange(1, FE.SIZE)) |
| 114 | + if GE.is_valid_x(x): |
| 115 | + break |
| 116 | + # Encoding it to (u, t), decode it back, and compare. |
| 117 | + u, t = xelligatorswift(x) |
| 118 | + x2 = xswiftec(u, t) |
| 119 | + self.assertEqual(x2, x) |
| 120 | + |
| 121 | + def test_ellswift_ecdh_xonly(self): |
| 122 | + for _ in range(32): |
| 123 | + privkey1, encoding1 = ellswift_create() |
| 124 | + privkey2, encoding2 = ellswift_create() |
| 125 | + shared_secret1 = ellswift_ecdh_xonly(encoding1, privkey2) |
| 126 | + shared_secret2 = ellswift_ecdh_xonly(encoding2, privkey1) |
| 127 | + assert shared_secret1 == shared_secret2 |
0 commit comments