-
Notifications
You must be signed in to change notification settings - Fork 60
/
types.py
427 lines (303 loc) · 9.49 KB
/
types.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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
# -*- coding: utf-8 -*-
import json
import struct
import time
from calendar import timegm
from binascii import hexlify, unhexlify
from .objecttypes import object_type
from .utils import unicodify
timeformat = "%Y-%m-%dT%H:%M:%S%Z"
def varint(n):
"""Varint encoding"""
data = b""
while n >= 0x80:
data += bytes([(n & 0x7F) | 0x80])
n >>= 7
data += bytes([n])
return data
def varintdecode(data): # pragma: no cover
"""Varint decoding"""
shift = 0
result = 0
for b in bytes(data):
result |= (b & 0x7F) << shift
if not (b & 0x80):
break
shift += 7
return result
def variable_buffer(s):
"""Encode variable length buffer"""
return varint(len(s)) + s
def JsonObj(data):
"""Return json object from data
If data has a __json__() method, use that, else assume it follows the
convention that its string representation is interprettable as valid json.
(The latter can be problematic if str(data) returns, e.g., "1234". Was
this supposed to be the string "1234" or the number 1234? If this
ambiguity exists, the data type must implement __json__().)
"""
try:
return data.__json__()
except Exception:
return json.loads(str(data))
class Uint8:
def __init__(self, d):
self.data = int(d)
def __bytes__(self):
return struct.pack("<B", self.data)
def __str__(self):
return "%d" % self.data
class Int16:
def __init__(self, d):
self.data = int(d)
def __bytes__(self):
return struct.pack("<h", int(self.data))
def __str__(self):
return "%d" % self.data
class Uint16:
def __init__(self, d):
self.data = int(d)
def __bytes__(self):
return struct.pack("<H", self.data)
def __str__(self):
return "%d" % self.data
class Uint32:
def __init__(self, d):
self.data = int(d)
def __bytes__(self):
return struct.pack("<I", self.data)
def __str__(self):
return "%d" % self.data
class Uint64:
def __init__(self, d):
self.data = int(d)
def __bytes__(self):
return struct.pack("<Q", self.data)
def __str__(self):
return "%d" % self.data
class Varint32:
def __init__(self, d):
self.data = int(d)
def __bytes__(self):
return varint(self.data)
def __str__(self):
return "%d" % self.data
class Int64:
def __init__(self, d):
self.data = int(d)
def __bytes__(self):
return struct.pack("<q", self.data)
def __str__(self):
return "%d" % self.data
class String:
def __init__(self, d):
self.data = d
def __bytes__(self):
if self.data:
d = unicodify(self.data)
else:
d = b""
return varint(len(d)) + d
def __str__(self):
return "%s" % str(self.data)
class Bytes:
"""Bytes
Initializes from and stores internally as a string of hex digits.
Byte-serializes as a length-prefixed series of bytes represented
by those hex digits.
Ex: len(str(Bytes("deadbeef")) == 8 # Eight hex chars
len(bytes(Bytes("deadbeef")) == 5 # Four data bytes plus varint length
Implements __json__() method to disambiguate between string and numeric in
event where hex digits include only numeric digits and no alpha digits.
"""
def __init__(self, d):
self.data = d
def __bytes__(self):
d = unhexlify(bytes(self.data, "utf-8"))
return varint(len(d)) + d
def __json__(self):
return str(self.data)
def __str__(self):
return str(self.data)
class Hash(Bytes):
def json(self):
return str(self.data)
def __bytes__(self):
return unhexlify(bytes(self.data, "utf-8"))
class Ripemd160(Hash):
def __init__(self, a):
assert len(a) == 40, "Require 40 char long hex"
super().__init__(a)
class Sha1(Hash):
def __init__(self, a):
assert len(a) == 40, "Require 40 char long hex"
super().__init__(a)
class Sha256(Hash):
def __init__(self, a):
assert len(a) == 64, "Require 64 char long hex"
super().__init__(a)
class Hash160(Hash):
def __init__(self, a):
assert len(a) == 40, "Require 40 char long hex"
super().__init__(a)
class Void:
def __init__(self):
pass
def __bytes__(self):
return b""
def __str__(self):
return ""
class Array:
def __init__(self, d):
self.data = d or []
self.length = Varint32(len(self.data))
def __bytes__(self):
return bytes(self.length) + b"".join([bytes(a) for a in self.data])
def __str__(self):
r = []
for a in self.data:
try:
r.append(JsonObj(a))
except Exception:
r.append(str(a))
return json.dumps(r)
class PointInTime:
def __init__(self, d):
self.data = d
def __bytes__(self):
return struct.pack("<I", timegm(time.strptime((self.data + "UTC"), timeformat)))
def __str__(self):
return self.data
class Signature:
def __init__(self, d):
self.data = d
def __bytes__(self):
return self.data
def __str__(self):
return json.dumps(hexlify(self.data).decode("ascii"))
class Bool(Uint8): # Bool = Uint8
def __init__(self, d):
super().__init__(d)
def __str__(self):
return json.dumps(True) if self.data else json.dumps(False)
class Set(Array): # Set = Array
def __init__(self, d):
super().__init__(d)
class Fixed_array:
pass
class Optional:
def __init__(self, d):
self.data = d
def __bytes__(self):
if not bool(self.data):
return bytes(Bool(0))
else:
return (
bytes(Bool(1)) + bytes(self.data)
if bytes(self.data)
else bytes(Bool(0))
)
def __str__(self):
return str(self.data)
def isempty(self):
if self.data is None:
return True
if not bool(str(self.data)): # pragma: no cover
return True
return not bool(bytes(self.data))
class Static_variant:
def __init__(self, d, type_id):
self.data = d
self.type_id = type_id
def __bytes__(self):
return varint(self.type_id) + bytes(self.data)
def __str__(self):
return json.dumps([self.type_id, self.data.json()])
class Map:
def __init__(self, data):
self.data = data
def __bytes__(self):
b = b""
b += varint(len(self.data))
for e in self.data:
b += bytes(e[0]) + bytes(e[1])
return b
def __str__(self):
r = []
for e in self.data:
r.append([str(e[0]), JsonObj(str(e[1]))])
return json.dumps(r)
class Id:
def __init__(self, d):
self.data = Varint32(d)
def __bytes__(self):
return bytes(self.data)
def __str__(self):
return str(self.data)
class VoteId:
def __init__(self, vote):
parts = vote.split(":")
assert len(parts) == 2
self.type = int(parts[0])
self.instance = int(parts[1])
def __bytes__(self):
binary = (self.type & 0xFF) | (self.instance << 8)
return struct.pack("<I", binary)
def __str__(self):
return "%d:%d" % (self.type, self.instance)
class ObjectId:
"""Encodes protocol ids - serializes to the *instance* only!"""
object_types = object_type
def __init__(self, object_str, type_verify=None):
if len(object_str.split(".")) == 3:
space, type, id = object_str.split(".")
self.space = int(space)
self.type = int(type)
self.instance = Id(int(id))
self.Id = object_str
if type_verify:
assert (
type_verify in self.object_types
), "Type {} is not defined!".format(type_verify)
assert self.object_types[type_verify] == int(type), (
"Object id does not match object type! "
+ "Excpected %d, got %d"
% (self.object_types[type_verify], int(type))
)
else:
raise Exception("Object id is invalid")
def __bytes__(self):
return bytes(self.instance) # only yield instance
def __str__(self):
return self.Id
class FullObjectId:
"""Encodes object ids - serializes to a full object id"""
def __init__(self, object_str):
if len(object_str.split(".")) == 3:
space, type, id = object_str.split(".")
self.space = int(space)
self.type = int(type)
self.id = int(id)
self.instance = Id(int(id))
self.Id = object_str
else:
raise ValueError("Object id is invalid")
def __bytes__(self):
return (self.space << 56 | self.type << 48 | self.id).to_bytes(
8, byteorder="little", signed=False
)
def __str__(self):
return self.Id
class Enum8(Uint8):
# List needs to be provided by super class
options = []
def __init__(self, selection):
if selection not in self.options or (
isinstance(selection, int) and len(self.options) < selection
):
raise ValueError(
"Options are {}. Given '{}'".format(str(self.options), selection)
)
super(Enum8, self).__init__(self.options.index(selection))
def __str__(self):
return str(self.options[self.data])