-
Notifications
You must be signed in to change notification settings - Fork 648
Expand file tree
/
Copy pathserialize.py
More file actions
434 lines (348 loc) · 12.5 KB
/
serialize.py
File metadata and controls
434 lines (348 loc) · 12.5 KB
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
428
429
430
431
432
433
434
# Copyright (C) 2012-2018 The python-bitcoinlib developers
#
# This file is part of python-bitcoinlib.
#
# It is subject to the license terms in the LICENSE file found in the top-level
# directory of this distribution.
#
# No part of python-bitcoinlib, including this file, may be copied, modified,
# propagated, or distributed except according to the terms contained in the
# LICENSE file.
"""Serialization routines
You probabably don't need to use these directly.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import hashlib
import struct
# Py3 compatibility
import sys
if sys.version > '3':
_bchr = lambda x: bytes([x])
_bord = lambda x: x[0]
from io import BytesIO as _BytesIO
else:
_bchr = chr
_bord = ord
from cStringIO import StringIO as _BytesIO
MAX_SIZE = 0x02000000
def Hash(msg):
"""SHA256^2)(msg) -> bytes"""
return hashlib.sha256(hashlib.sha256(msg).digest()).digest()
def Hash160(msg):
"""RIPEME160(SHA256(msg)) -> bytes"""
h = hashlib.new('ripemd160')
h.update(hashlib.sha256(msg).digest())
return h.digest()
class SerializationError(Exception):
"""Base class for serialization errors"""
class SerializationTruncationError(SerializationError):
"""Serialized data was truncated
Thrown by deserialize() and stream_deserialize()
"""
class DeserializationExtraDataError(SerializationError):
"""Deserialized data had extra data at the end
Thrown by deserialize() when not all data is consumed during
deserialization. The deserialized object and extra padding not consumed are
saved.
"""
def __init__(self, msg, obj, padding):
super(DeserializationExtraDataError, self).__init__(msg)
self.obj = obj
self.padding = padding
class DeserializationValueBoundsError(SerializationError):
"""Deserialized value out of bounds
Thrown by deserialize() when a deserialized value turns out to be out
of allowed bounds
"""
def __init__(self, msg, klass=None, value=None,
upper_bound=None, lower_bound=None):
super().__init__(msg)
self.klass = klass
self.value = value
self.upper_bound = upper_bound
self.lower_bound = lower_bound
def ser_read(f, n):
"""Read from a stream safely
Raises SerializationError and SerializationTruncationError appropriately.
Use this instead of f.read() in your classes stream_(de)serialization()
functions.
"""
if n > MAX_SIZE:
raise SerializationError('Asked to read 0x%x bytes; MAX_SIZE exceeded' % n)
r = f.read(n)
if len(r) < n:
raise SerializationTruncationError('Asked to read %i bytes, but only got %i' % (n, len(r)))
return r
class Serializable(object):
"""Base class for serializable objects"""
__slots__ = []
def stream_serialize(self, f, **kwargs):
"""Serialize to a stream"""
raise NotImplementedError
@classmethod
def stream_deserialize(cls, f, **kwargs):
"""Deserialize from a stream"""
raise NotImplementedError
def serialize(self, params={}):
"""Serialize, returning bytes"""
f = _BytesIO()
self.stream_serialize(f, **params)
return f.getvalue()
@classmethod
def deserialize(cls, buf, allow_padding=False, params={}):
"""Deserialize bytes, returning an instance
allow_padding - Allow buf to include extra padding. (default False)
If allow_padding is False and not all bytes are consumed during
deserialization DeserializationExtraDataError will be raised.
"""
fd = _BytesIO(buf)
r = cls.stream_deserialize(fd, **params)
if not allow_padding:
padding = fd.read()
if len(padding) != 0:
raise DeserializationExtraDataError('Not all bytes consumed during deserialization',
r, padding)
return r
def GetHash(self):
"""Return the hash of the serialized object"""
return Hash(self.serialize())
def __eq__(self, other):
if (not isinstance(other, self.__class__) and
not isinstance(self, other.__class__)):
return NotImplemented
return self.serialize() == other.serialize()
def __ne__(self, other):
return not (self == other)
def __hash__(self):
return hash(self.serialize())
class ImmutableSerializable(Serializable):
"""Immutable serializable object"""
__slots__ = ['_cached_GetHash', '_cached__hash__']
def __setattr__(self, name, value):
raise AttributeError('Object is immutable')
def __delattr__(self, name):
raise AttributeError('Object is immutable')
def GetHash(self):
"""Return the hash of the serialized object"""
try:
return self._cached_GetHash
except AttributeError:
_cached_GetHash = super(ImmutableSerializable, self).GetHash()
object.__setattr__(self, '_cached_GetHash', _cached_GetHash)
return _cached_GetHash
def __hash__(self):
try:
return self._cached__hash__
except AttributeError:
_cached__hash__ = hash(self.serialize())
object.__setattr__(self, '_cached__hash__', _cached__hash__)
return _cached__hash__
class Serializer(object):
"""Base class for object serializers"""
def __new__(cls):
raise NotImplementedError
@classmethod
def stream_serialize(cls, obj, f):
raise NotImplementedError
@classmethod
def stream_deserialize(cls, f):
raise NotImplementedError
@classmethod
def serialize(cls, obj):
f = _BytesIO()
cls.stream_serialize(obj, f)
return f.getvalue()
@classmethod
def deserialize(cls, buf):
if isinstance(buf, str) or isinstance(buf, bytes):
buf = _BytesIO(buf)
return cls.stream_deserialize(buf)
class VarIntSerializer(Serializer):
"""Serialization of variable length ints"""
@classmethod
def stream_serialize(cls, i, f):
if i < 0:
raise ValueError('varint must be non-negative integer')
elif i < 0xfd:
f.write(_bchr(i))
elif i <= 0xffff:
f.write(_bchr(0xfd))
f.write(struct.pack(b'<H', i))
elif i <= 0xffffffff:
f.write(_bchr(0xfe))
f.write(struct.pack(b'<I', i))
else:
f.write(_bchr(0xff))
f.write(struct.pack(b'<Q', i))
@classmethod
def stream_deserialize(cls, f):
r = _bord(ser_read(f, 1))
if r < 0xfd:
return r
if r == 0xfd:
v = int(struct.unpack(b'<H', ser_read(f, 2))[0])
lower_bound = 0xfd
if v < lower_bound:
raise DeserializationValueBoundsError(
"non-canonical 3-byte compact size for variable integer",
klass=cls, value=v, lower_bound=lower_bound,
upper_bound=0xFFFF)
elif r == 0xfe:
v = int(struct.unpack(b'<I', ser_read(f, 4))[0])
lower_bound = 0x10000
if v < lower_bound:
raise DeserializationValueBoundsError(
"non-canonical 5-byte compact size for variable integer",
klass=cls, value=v, lower_bound=lower_bound,
upper_bound=0xFFFFFFFF)
else:
v = int(struct.unpack(b'<Q', ser_read(f, 8))[0])
lower_bound = 0x100000000
if v < lower_bound:
raise DeserializationValueBoundsError(
"non-canonical 9-byte compact size for variable integer",
klass=cls, value=v, lower_bound=lower_bound,
upper_bound=MAX_SIZE)
# With MAX_SIZE being defined as less than 32-bit max value,
# this means that any canonically encoded 64-bit value will be
# more than MAX_SIZE. This also means that upper_bound supplied
# to the exception may happen to be less than lower bound.
if v > MAX_SIZE:
raise DeserializationValueBoundsError(
"non-canonical compact size for variable integer: "
"value too large",
klass=cls, value=v, lower_bound=lower_bound,
upper_bound=MAX_SIZE)
return v
class BytesSerializer(Serializer):
"""Serialization of bytes instances"""
@classmethod
def stream_serialize(cls, b, f):
VarIntSerializer.stream_serialize(len(b), f)
f.write(b)
@classmethod
def stream_deserialize(cls, f):
l = VarIntSerializer.stream_deserialize(f)
return ser_read(f, l)
class VectorSerializer(Serializer):
"""Base class for serializers of object vectors"""
# FIXME: stream_(de)serialize don't match the signatures of the base class
# due to the inner_cls parameter. This probably isn't optimal API design
# and should be rethought at some point.
@classmethod
def stream_serialize(cls, inner_cls, objs, f, inner_params={}):
VarIntSerializer.stream_serialize(len(objs), f)
for obj in objs:
inner_cls.stream_serialize(obj, f, **inner_params)
@classmethod
def stream_deserialize(cls, inner_cls, f, inner_params={}):
n = VarIntSerializer.stream_deserialize(f)
r = []
for i in range(n):
r.append(inner_cls.stream_deserialize(f, **inner_params))
return r
class uint256VectorSerializer(Serializer):
"""Serialize vectors of uint256"""
@classmethod
def stream_serialize(cls, uints, f):
VarIntSerializer.stream_serialize(len(uints), f)
for uint in uints:
assert len(uint) == 32
f.write(uint)
@classmethod
def stream_deserialize(cls, f):
n = VarIntSerializer.stream_deserialize(f)
r = []
for i in range(n):
r.append(ser_read(f, 32))
return r
class intVectorSerializer(Serializer):
@classmethod
def stream_serialize(cls, ints, f):
l = len(ints)
VarIntSerializer.stream_serialize(l, f)
for i in ints:
f.write(struct.pack(b"<i", i))
@classmethod
def stream_deserialize(cls, f):
l = VarIntSerializer.stream_deserialize(f)
ints = []
for i in range(l):
ints.append(struct.unpack(b"<i", ser_read(f, 4))[0])
return ints
class VarStringSerializer(Serializer):
"""Serialize variable length byte strings"""
@classmethod
def stream_serialize(cls, s, f):
l = len(s)
VarIntSerializer.stream_serialize(l, f)
f.write(s)
@classmethod
def stream_deserialize(cls, f):
l = VarIntSerializer.stream_deserialize(f)
return ser_read(f, l)
def uint256_from_str(s):
"""Convert bytes to uint256"""
r = 0
t = struct.unpack(b"<IIIIIIII", s[:32])
for i in range(8):
r += t[i] << (i * 32)
return r
def uint256_from_compact(c):
"""Convert compact encoding to uint256
Used for the nBits compact encoding of the target in the block header.
"""
nbytes = (c >> 24) & 0xFF
if nbytes <= 3:
v = (c & 0xFFFFFF) >> 8 * (3 - nbytes)
else:
v = (c & 0xFFFFFF) << (8 * (nbytes - 3))
return v
def compact_from_uint256(v):
"""Convert uint256 to compact encoding
"""
nbytes = (v.bit_length() + 7) >> 3
compact = 0
if nbytes <= 3:
compact = (v & 0xFFFFFF) << 8 * (3 - nbytes)
else:
compact = v >> 8 * (nbytes - 3)
compact = compact & 0xFFFFFF
# If the sign bit (0x00800000) is set, divide the mantissa by 256 and
# increase the exponent to get an encoding without it set.
if compact & 0x00800000:
compact >>= 8
nbytes += 1
return compact | nbytes << 24
def uint256_to_str(u):
r = b""
for i in range(8):
r += struct.pack('<I', u >> (i * 32) & 0xffffffff)
return r
def uint256_to_shortstr(u):
s = "%064x" % (u,)
return s[:16]
__all__ = (
'MAX_SIZE',
'Hash',
'Hash160',
'SerializationError',
'SerializationTruncationError',
'DeserializationExtraDataError',
'DeserializationValueBoundsError',
'ser_read',
'Serializable',
'ImmutableSerializable',
'Serializer',
'VarIntSerializer',
'BytesSerializer',
'VectorSerializer',
'uint256VectorSerializer',
'intVectorSerializer',
'VarStringSerializer',
'uint256_from_str',
'uint256_from_compact',
'compact_from_uint256',
'uint256_to_str',
'uint256_to_shortstr',
)