-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathbasic.py
197 lines (160 loc) · 6.16 KB
/
basic.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
from abc import abstractmethod
import io
import operator
from typing import IO, Any, Generator, Iterable, Sequence, Tuple
from eth_typing import Hash32
from eth_utils import to_tuple
from eth_utils.toolz import accumulate, concatv
from ssz import constants
from ssz.cache.utils import get_key
from ssz.constants import CHUNK_SIZE
from ssz.exceptions import DeserializationError
from ssz.sedes.base import (
BaseBitfieldCompositeSedes,
BaseProperCompositeSedes,
BaseSedes,
TSedes,
)
from ssz.typing import CacheObj, TDeserialized, TSerializable
from ssz.utils import encode_offset, merkleize, merkleize_with_cache, pack
class BasicSedes(BaseSedes[TSerializable, TDeserialized]):
def __init__(self, size: int):
if size <= 0:
raise ValueError("Length must be greater than 0")
self.size = size
#
# Size
#
is_fixed_sized = True
def get_fixed_size(self):
return self.size
#
# Tree hashing
#
def get_hash_tree_root(self, value: TSerializable) -> Hash32:
serialized_value = self.serialize(value)
return merkleize(pack((serialized_value,)))
def get_hash_tree_root_and_leaves(
self, value: TSerializable, cache: CacheObj
) -> Tuple[Hash32, CacheObj]:
serialized_value = self.serialize(value)
return merkleize_with_cache(pack((serialized_value,)), cache=cache)
def get_key(self, value: Any) -> str:
return get_key(self, value)
def _compute_fixed_size_section_length(element_sedes: Iterable[TSedes]) -> int:
return sum(
sedes.get_fixed_size() if sedes.is_fixed_sized else constants.OFFSET_SIZE
for sedes in element_sedes
)
class BitfieldCompositeSedes(BaseBitfieldCompositeSedes[TSerializable, TDeserialized]):
def get_key(self, value: Any) -> str:
return get_key(self, value)
class ProperCompositeSedes(BaseProperCompositeSedes[TSerializable, TDeserialized]):
@to_tuple
def _get_item_sedes_pairs(
self, value: Sequence[TSerializable]
) -> Generator[Tuple[TSerializable, TSedes], None, None]:
for index, element in enumerate(value):
yield element, self.get_element_sedes(index)
def _validate_serializable(self, value: Any) -> None:
...
def serialize(self, value: TSerializable) -> bytes:
self._validate_serializable(value)
if not len(value):
return b""
pairs = self._get_item_sedes_pairs(value) # slow
element_sedes = tuple(sedes for element, sedes in pairs)
has_fixed_size_section_length_cache = hasattr(
value, "_fixed_size_section_length_cache"
)
if has_fixed_size_section_length_cache:
if value._fixed_size_section_length_cache is None:
fixed_size_section_length = _compute_fixed_size_section_length(
element_sedes
)
value._fixed_size_section_length_cache = fixed_size_section_length
else:
fixed_size_section_length = value._fixed_size_section_length_cache
else:
fixed_size_section_length = _compute_fixed_size_section_length(
element_sedes
)
variable_size_section_parts = tuple(
sedes.serialize(item) # slow
for item, sedes in pairs
if not sedes.is_fixed_sized
)
if variable_size_section_parts:
offsets = tuple(
accumulate(
operator.add,
map(len, variable_size_section_parts[:-1]),
fixed_size_section_length,
)
)
else:
offsets = ()
offsets_iter = iter(offsets)
fixed_size_section_parts = tuple(
sedes.serialize(item) # slow
if sedes.is_fixed_sized
else encode_offset(next(offsets_iter))
for item, sedes in pairs
)
try:
next(offsets_iter)
except StopIteration:
pass
else:
raise DeserializationError(
"Did not consume all offsets while decoding value"
)
return b"".join(concatv(fixed_size_section_parts, variable_size_section_parts))
def serialize_element_for_tree(self, index: int, element: TSerializable) -> bytes:
sedes = self.get_element_sedes(index)
if self.is_packing:
return sedes.serialize(element)
else:
return sedes.get_hash_tree_root(element)
@property
def element_size_in_tree(self) -> int:
if self.is_packing:
# note that only homogenous composites with fixed sized elements are packed
return self.get_element_sedes(0).get_fixed_size()
else:
return CHUNK_SIZE
def deserialize(self, data: bytes) -> TDeserialized:
stream = io.BytesIO(data)
value = self._deserialize_stream(stream)
extra_data = stream.read()
if extra_data:
raise DeserializationError(f"Got {len(extra_data)} superfluous bytes")
return value
@abstractmethod
def _deserialize_stream(self, stream: IO[bytes]) -> TDeserialized:
...
def get_key(self, value: Any) -> str:
return get_key(self, value)
class HomogeneousProperCompositeSedes(
ProperCompositeSedes[TSerializable, TDeserialized]
):
def __init__(self, element_sedes: TSedes, max_length: int) -> None:
self.element_sedes = element_sedes
if max_length < 1:
raise ValueError(
f"(Maximum) length of homogenous composites must be at least 1, got {max_length}"
)
self.max_length = max_length
def get_sedes_id(self) -> str:
sedes_name = self.__class__.__name__
return f"{sedes_name}({self.element_sedes.get_sedes_id()},{self.max_length})"
@property
def is_packing(self) -> bool:
return isinstance(self.element_sedes, BasicSedes)
@property
def chunk_count(self) -> int:
if self.is_packing:
element_size = self.element_sedes.get_fixed_size()
return (element_size * self.max_length + CHUNK_SIZE - 1) // CHUNK_SIZE
else:
return self.max_length