forked from zcash/zcash-test-vectors
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tv_output.py
220 lines (192 loc) · 5.96 KB
/
tv_output.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
#!/usr/bin/env python3
import sys; assert sys.version_info[0] >= 3, "Python 3 required."
import argparse
from binascii import hexlify
import json
def chunk(h):
hstr = str(h, 'utf-8')
hstr = ', 0x'.join([hstr[i:i+2] for i in range(0, len(hstr), 2)])
return '0x' + hstr if hstr else ''
class Some(object):
def __init__(self, thing):
self.thing = thing
def option(x):
return Some(x) if x else None
#
# JSON (with string comments)
# If bitcoin_flavoured == True, 32-byte values are reversed
#
def tv_value_json(value, bitcoin_flavoured):
if isinstance(value, Some):
value = value.thing
if type(value) == bytes:
if bitcoin_flavoured and len(value) == 32:
value = value[::-1]
value = hexlify(value).decode()
return value
def tv_json(filename, parts, vectors, bitcoin_flavoured):
if type(vectors) == type({}):
vectors = [vectors]
print('''[
["From https://github.com/zcash-hackworks/zcash-test-vectors/blob/master/%s.py"],
["%s"],''' % (
filename,
', '.join([p[0] for p in parts])
))
print(' ' + ',\n '.join([
json.dumps([tv_value_json(v[p[0]], p[1].get('bitcoin_flavoured', bitcoin_flavoured)) for p in parts]) for v in vectors
]))
print(']')
#
# Rust
#
def tv_bytes_rust(name, value, pad):
print('''%s%s: [
%s%s
%s],''' % (
pad,
name,
pad,
chunk(hexlify(value)),
pad,
))
def tv_vec_bytes_rust(name, value, pad):
print('''%s%s: vec![
%s%s
%s],''' % (
pad,
name,
pad,
chunk(hexlify(value)),
pad,
))
def tv_vec_bool_rust(name, value, pad):
print('''%s%s: vec![
%s%s
%s],''' % (
pad,
name,
pad,
', '.join(['true' if x else 'false' for x in value]),
pad,
))
def tv_option_bytes_rust(name, value, pad):
if value:
print('''%s%s: Some([
%s%s
%s]),''' % (
pad,
name,
pad,
chunk(hexlify(value.thing)),
pad,
))
else:
print('%s%s: None,' % (pad, name))
def tv_option_vec_bytes_rust(name, value, pad):
if value:
print('''%s%s: Some(vec![
%s%s
%s]),''' % (
pad,
name,
pad,
chunk(hexlify(value.thing)),
pad,
))
else:
print('%s%s: None,' % (pad, name))
def tv_int_rust(name, value, pad):
print('%s%s: %d,' % (pad, name, value))
def tv_option_int_rust(name, value, pad):
if value:
print('%s%s: Some(%d),' % (pad, name, value.thing))
else:
print('%s%s: None,' % (pad, name))
def tv_part_rust(name, value, config, indent=3):
if 'rust_fmt' in config:
value = config['rust_fmt'](value)
pad = ' ' * indent
if config['rust_type'] == 'Option<Vec<u8>>':
tv_option_vec_bytes_rust(name, value, pad)
elif config['rust_type'] == 'Vec<u8>':
tv_vec_bytes_rust(name, value, pad)
elif config['rust_type'] == 'Vec<bool>':
tv_vec_bool_rust(name, value, pad)
elif config['rust_type'].startswith('Option<['):
tv_option_bytes_rust(name, value, pad)
elif type(value) == bytes:
tv_bytes_rust(name, value, pad)
elif config['rust_type'].startswith('Option<'):
tv_option_int_rust(name, value, pad)
elif type(value) == int:
tv_int_rust(name, value, pad)
elif type(value) == list:
print('''%s%s: [''' % (
pad,
name,
))
for item in value:
if type(item) == bytes:
print('''%s[%s],''' % (
' ' * (indent + 1),
chunk(hexlify(item)),
))
elif type(item) == list:
print('''%s[''' % (
' ' * (indent + 1)
))
for subitem in item:
if type(subitem) == bytes:
print('''%s[%s],''' % (
' ' * (indent + 2),
chunk(hexlify(subitem)),
))
else:
raise ValueError('Invalid sublist type(%s): %s' % (name, type(subitem)))
print('''%s],''' % (
' ' * (indent + 1)
))
else:
raise ValueError('Invalid list type(%s): %s' % (name, type(item)))
print('''%s],''' % (
pad,
))
else:
raise ValueError('Invalid type(%s): %s' % (name, type(value)))
def tv_rust(filename, parts, vectors):
print(' struct TestVector {')
for p in parts: print(' %s: %s,' % (p[0], p[1]['rust_type']))
print(''' };
// From https://github.com/zcash-hackworks/zcash-test-vectors/blob/master/%s.py''' % (
filename,
))
if type(vectors) == type({}):
print(' let test_vector = TestVector {')
for p in parts: tv_part_rust(p[0], vectors[p[0]], p[1])
print(' };')
elif type(vectors) == type([]):
print(' let test_vectors = vec![')
for vector in vectors:
print(' TestVector {')
for p in parts: tv_part_rust(p[0], vector[p[0]], p[1], 4)
print(' },')
print(' ];')
else:
raise ValueError('Invalid type(vectors)')
#
# Rendering functions
#
def render_args():
parser = argparse.ArgumentParser()
parser.add_argument('-t', '--target', choices=['zcash', 'json', 'rust'], default='rust')
return parser.parse_args()
def render_tv(args, filename, parts, vectors):
# Convert older format
parts = [(p[0], p[1] if type(p[1]) == type({}) else {'rust_type': p[1]}) for p in parts]
if args.target == 'rust':
tv_rust(filename, parts, vectors)
elif args.target == 'zcash':
tv_json(filename, parts, vectors, True)
elif args.target == 'json':
tv_json(filename, parts, vectors, False)