Skip to content

Commit ca08973

Browse files
authored
Merge pull request #296 from willcl-ark/update-test-framework
2 parents 492b8a2 + 49342d5 commit ca08973

20 files changed

+1070
-511
lines changed

src/test_framework/authproxy.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
import http.client
4040
import json
4141
import logging
42+
import pathlib
4243
import socket
4344
import time
4445
import urllib.parse
@@ -59,9 +60,11 @@ def __init__(self, rpc_error, http_status=None):
5960
self.http_status = http_status
6061

6162

62-
def EncodeDecimal(o):
63+
def serialization_fallback(o):
6364
if isinstance(o, decimal.Decimal):
6465
return str(o)
66+
if isinstance(o, pathlib.Path):
67+
return str(o)
6568
raise TypeError(repr(o) + " is not JSON serializable")
6669

6770
class AuthServiceProxy():
@@ -108,7 +111,7 @@ def get_request(self, *args, **argsn):
108111
log.debug("-{}-> {} {}".format(
109112
AuthServiceProxy.__id_count,
110113
self._service_name,
111-
json.dumps(args or argsn, default=EncodeDecimal, ensure_ascii=self.ensure_ascii),
114+
json.dumps(args or argsn, default=serialization_fallback, ensure_ascii=self.ensure_ascii),
112115
))
113116
if args and argsn:
114117
params = dict(args=args, **argsn)
@@ -120,7 +123,7 @@ def get_request(self, *args, **argsn):
120123
'id': AuthServiceProxy.__id_count}
121124

122125
def __call__(self, *args, **argsn):
123-
postdata = json.dumps(self.get_request(*args, **argsn), default=EncodeDecimal, ensure_ascii=self.ensure_ascii)
126+
postdata = json.dumps(self.get_request(*args, **argsn), default=serialization_fallback, ensure_ascii=self.ensure_ascii)
124127
response, status = self._request('POST', self.__url.path, postdata.encode('utf-8'))
125128
if response['error'] is not None:
126129
raise JSONRPCException(response['error'], status)
@@ -134,7 +137,7 @@ def __call__(self, *args, **argsn):
134137
return response['result']
135138

136139
def batch(self, rpc_call_list):
137-
postdata = json.dumps(list(rpc_call_list), default=EncodeDecimal, ensure_ascii=self.ensure_ascii)
140+
postdata = json.dumps(list(rpc_call_list), default=serialization_fallback, ensure_ascii=self.ensure_ascii)
138141
log.debug("--> " + postdata)
139142
response, status = self._request('POST', self.__url.path, postdata.encode('utf-8'))
140143
if status != HTTPStatus.OK:
@@ -167,7 +170,7 @@ def _get_response(self):
167170
response = json.loads(responsedata, parse_float=decimal.Decimal)
168171
elapsed = time.time() - req_start_time
169172
if "error" in response and response["error"] is None:
170-
log.debug("<-%s- [%.6f] %s" % (response["id"], elapsed, json.dumps(response["result"], default=EncodeDecimal, ensure_ascii=self.ensure_ascii)))
173+
log.debug("<-%s- [%.6f] %s" % (response["id"], elapsed, json.dumps(response["result"], default=serialization_fallback, ensure_ascii=self.ensure_ascii)))
171174
else:
172175
log.debug("<-- [%.6f] %s" % (elapsed, responsedata))
173176
return response, http_response.status

src/test_framework/coverage.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import os
1212

1313
from .authproxy import AuthServiceProxy
14+
from typing import Optional
1415

1516
REFERENCE_FILENAME = 'rpc_interface.txt'
1617

@@ -20,7 +21,7 @@ class AuthServiceProxyWrapper():
2021
An object that wraps AuthServiceProxy to record specific RPC calls.
2122
2223
"""
23-
def __init__(self, auth_service_proxy_instance: AuthServiceProxy, rpc_url: str, coverage_logfile: str=None):
24+
def __init__(self, auth_service_proxy_instance: AuthServiceProxy, rpc_url: str, coverage_logfile: Optional[str]=None):
2425
"""
2526
Kwargs:
2627
auth_service_proxy_instance: the instance being wrapped.

src/test_framework/ellswift.py

Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
1+
#!/usr/bin/env python3
2+
# Copyright (c) 2022 The Bitcoin Core 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.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))

0 commit comments

Comments
 (0)