|
1 | | -"""Base classes and interfaces for all SSZ types.""" |
| 1 | +"""Abstract bases for the SSZ type system.""" |
2 | 2 |
|
3 | 3 | import io |
4 | 4 | from abc import ABC, abstractmethod |
5 | | -from collections.abc import Sequence |
6 | | -from typing import IO, Any, Self |
| 5 | +from typing import IO, Self |
7 | 6 |
|
8 | 7 | from .base import StrictBaseModel |
| 8 | +from .exceptions import SSZSerializationError |
9 | 9 |
|
10 | 10 |
|
11 | 11 | class SSZType(ABC): |
12 | | - """ |
13 | | - Abstract base class for all SSZ types. |
14 | | -
|
15 | | - This is the minimal interface that all SSZ types must implement. |
16 | | - Use SSZModel for Pydantic-based SSZ types. |
17 | | - """ |
| 12 | + """Abstract base for every SSZ-encodable type.""" |
18 | 13 |
|
19 | 14 | @classmethod |
20 | 15 | @abstractmethod |
21 | 16 | def is_fixed_size(cls) -> bool: |
22 | | - """ |
23 | | - Check if the type has a fixed size in bytes. |
| 17 | + """Whether every instance encodes to the same number of bytes. |
24 | 18 |
|
25 | 19 | Returns: |
26 | | - bool: True if the size is fixed, False otherwise. |
| 20 | + True for fixed-size types, False for variable-size. |
27 | 21 | """ |
28 | 22 | ... |
29 | 23 |
|
30 | 24 | @classmethod |
31 | 25 | @abstractmethod |
32 | 26 | def get_byte_length(cls) -> int: |
33 | | - """ |
34 | | - Get the byte length of the type if it is fixed-size. |
35 | | -
|
36 | | - Raises: |
37 | | - TypeError: If the type is not fixed-size. |
| 27 | + """Fixed encoded byte length of this type. |
38 | 28 |
|
39 | 29 | Returns: |
40 | | - int: The number of bytes. |
| 30 | + The constant byte width every instance encodes to. |
| 31 | +
|
| 32 | + Raises: |
| 33 | + SSZTypeError: If the type is variable-size. |
41 | 34 | """ |
42 | 35 | ... |
43 | 36 |
|
44 | 37 | @abstractmethod |
45 | 38 | def serialize(self, stream: IO[bytes]) -> int: |
46 | | - """ |
47 | | - Serializes the object and writes it to a binary stream. |
| 39 | + """Write the SSZ encoding to a binary stream. |
48 | 40 |
|
49 | 41 | Args: |
50 | | - stream (IO[bytes]): The stream to write the serialized data to. |
| 42 | + stream: Output binary stream. |
51 | 43 |
|
52 | 44 | Returns: |
53 | | - int: The number of bytes written. |
| 45 | + Number of bytes written. |
54 | 46 | """ |
55 | 47 | ... |
56 | 48 |
|
57 | 49 | @classmethod |
58 | 50 | @abstractmethod |
59 | 51 | def deserialize(cls, stream: IO[bytes], scope: int) -> Self: |
60 | | - """ |
61 | | - Deserializes an object from a binary stream within a given scope. |
| 52 | + """Read one value from a binary stream within a bounded byte budget. |
62 | 53 |
|
63 | 54 | Args: |
64 | | - stream (IO[bytes]): The stream to read from. |
65 | | - scope (int): The number of bytes available to read for this object. |
| 55 | + stream: Source binary stream. |
| 56 | + scope: Number of bytes belonging to this value. |
66 | 57 |
|
67 | 58 | Returns: |
68 | | - Self: An instance of the class. |
| 59 | + A new instance reconstructed from the stream. |
69 | 60 | """ |
70 | 61 | ... |
71 | 62 |
|
72 | 63 | def encode_bytes(self) -> bytes: |
73 | | - """ |
74 | | - Serializes the SSZ object to a byte string. |
| 64 | + """Encode this value to its SSZ byte representation. |
75 | 65 |
|
76 | 66 | Returns: |
77 | | - bytes: The serialized byte string. |
| 67 | + Serialized bytes. |
78 | 68 | """ |
79 | | - with io.BytesIO() as stream: |
80 | | - self.serialize(stream) |
81 | | - return stream.getvalue() |
| 69 | + stream = io.BytesIO() |
| 70 | + self.serialize(stream) |
| 71 | + return stream.getvalue() |
82 | 72 |
|
83 | 73 | @classmethod |
84 | 74 | def decode_bytes(cls, data: bytes) -> Self: |
85 | | - """ |
86 | | - Deserializes a byte string into an SSZ object. |
| 75 | + """Decode SSZ bytes into a new instance. |
| 76 | +
|
| 77 | + Rejects trailing bytes left over after the stream-based decoder finishes. |
| 78 | + A spec decoder must accept exactly one canonical encoding per value. |
87 | 79 |
|
88 | 80 | Args: |
89 | | - data (bytes): The byte string to deserialize. |
| 81 | + data: SSZ-encoded bytes containing exactly one value. |
90 | 82 |
|
91 | 83 | Returns: |
92 | | - Self: An instance of the class. |
| 84 | + A new instance reconstructed from the input. |
| 85 | +
|
| 86 | + Raises: |
| 87 | + SSZSerializationError: If the input carries bytes past the decoded value. |
93 | 88 | """ |
94 | | - with io.BytesIO(data) as stream: |
95 | | - return cls.deserialize(stream, len(data)) |
| 89 | + stream = io.BytesIO(data) |
| 90 | + instance = cls.deserialize(stream, len(data)) |
| 91 | + |
| 92 | + # Spec contract: each canonical encoding maps to exactly one value. |
| 93 | + # |
| 94 | + # Any unread bytes mean the input either over-allocated or carries noise. |
| 95 | + leftover = len(data) - stream.tell() |
| 96 | + if leftover: |
| 97 | + raise SSZSerializationError(f"{cls.__name__}: {leftover} trailing byte(s) after decode") |
| 98 | + return instance |
96 | 99 |
|
97 | 100 |
|
98 | 101 | class SSZModel(StrictBaseModel, SSZType): |
99 | | - """ |
100 | | - Base class for SSZ types that use Pydantic validation. |
| 102 | + """Pydantic-backed SSZ base used by containers, lists, vectors, and bitfields. |
| 103 | +
|
| 104 | + Two shapes share this base: |
101 | 105 |
|
102 | | - This combines StrictBaseModel (Pydantic validation + immutability) with SSZ serialization. |
103 | | - Use this for containers and complex types that can benefit from Pydantic. |
| 106 | + - Collections wrap an inner sequence in one Pydantic field called data. |
| 107 | + - Containers expose multiple named Pydantic fields that map to a struct on the wire. |
104 | 108 |
|
105 | | - For simple types that need special inheritance (like int), use SSZType directly. |
| 109 | + The default length and string forms switch on which shape the subclass uses. |
106 | 110 | """ |
107 | 111 |
|
108 | 112 | def __len__(self) -> int: |
109 | | - """Return the length of the collection's data or number of container fields.""" |
110 | | - data: Sequence[Any] | None = getattr(self, "data", None) |
| 113 | + """Element count for collections, field count for containers.""" |
| 114 | + data = getattr(self, "data", None) |
111 | 115 | if data is not None: |
112 | 116 | return len(data) |
113 | 117 | return len(type(self).model_fields) |
114 | 118 |
|
115 | 119 | def __repr__(self) -> str: |
116 | | - """String representation showing the class name and data.""" |
117 | | - data: Sequence[Any] | None = getattr(self, "data", None) |
| 120 | + """Show collection contents as data=[...] or container fields as name=value pairs.""" |
| 121 | + cls_name = type(self).__name__ |
| 122 | + data = getattr(self, "data", None) |
118 | 123 | if data is not None: |
119 | | - return f"{self.__class__.__name__}(data={list(data)!r})" |
| 124 | + return f"{cls_name}(data={list(data)!r})" |
120 | 125 | field_strs = [f"{name}={getattr(self, name)!r}" for name in type(self).model_fields] |
121 | | - return f"{self.__class__.__name__}({' '.join(field_strs)})" |
| 126 | + return f"{cls_name}({' '.join(field_strs)})" |
0 commit comments