2019-04-15 18:02:23 +00:00
# SimpleSerialize (SSZ)
2019-02-27 10:54:23 +00:00
## Table of contents
2019-05-06 15:30:32 +00:00
<!-- TOC -->
2019-12-10 14:17:06 +00:00
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE - RUN doctoc TO UPDATE -->
- [Constants ](#constants )
- [Typing ](#typing )
- [Basic types ](#basic-types )
- [Composite types ](#composite-types )
- [Variable-size and fixed-size ](#variable-size-and-fixed-size )
2023-09-19 12:23:08 +00:00
- [Byte ](#byte )
2019-12-10 14:17:06 +00:00
- [Aliases ](#aliases )
- [Default values ](#default-values )
- [`is_zero` ](#is_zero )
- [Illegal types ](#illegal-types )
- [Serialization ](#serialization )
- [`uintN` ](#uintn )
- [`boolean` ](#boolean )
- [`Bitvector[N]`](#bitvectorn)
- [`Bitlist[N]`](#bitlistn)
2021-05-25 17:46:23 +00:00
- [Vectors, containers, lists ](#vectors-containers-lists )
- [Union ](#union )
2019-12-10 14:17:06 +00:00
- [Deserialization ](#deserialization )
- [Merkleization ](#merkleization )
- [Summaries and expansions ](#summaries-and-expansions )
- [Implementations ](#implementations )
2023-09-19 12:23:08 +00:00
- [JSON mapping ](#json-mapping )
2019-12-10 14:17:06 +00:00
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
2019-05-06 15:30:32 +00:00
<!-- /TOC -->
2018-09-23 23:52:38 +00:00
2019-02-27 21:33:36 +00:00
## Constants
| Name | Value | Description |
|-|-|-|
2019-04-13 13:44:14 +00:00
| `BYTES_PER_CHUNK` | `32` | Number of bytes per chunk. |
2019-04-13 13:56:06 +00:00
| `BYTES_PER_LENGTH_OFFSET` | `4` | Number of bytes per serialized length offset. |
2019-04-13 13:44:14 +00:00
| `BITS_PER_BYTE` | `8` | Number of bits per byte. |
2018-09-23 23:52:38 +00:00
2019-02-27 21:33:36 +00:00
## Typing
2019-02-27 16:54:19 +00:00
### Basic types
2018-09-23 23:52:38 +00:00
2019-06-27 08:51:06 +00:00
* `uintN` : `N` -bit unsigned integer (where `N in [8, 16, 32, 64, 128, 256]` )
2023-09-19 12:23:08 +00:00
* `byte` : 8-bit opaque data container, equivalent in serialization and hashing to `uint8`
2019-06-27 08:51:06 +00:00
* `boolean` : `True` or `False`
2018-11-27 07:45:04 +00:00
2019-02-27 16:54:19 +00:00
### Composite types
2018-09-23 23:52:38 +00:00
2019-04-20 05:18:14 +00:00
* **container**: ordered heterogeneous collection of values
2019-06-27 10:30:23 +00:00
* python dataclass notation with key-type pairs, e.g.
2019-07-04 13:26:07 +00:00
```python
class ContainerExample(Container):
foo: uint64
bar: boolean
```
2019-06-28 15:07:36 +00:00
* **vector**: ordered fixed-length homogeneous collection, with `N` values
2019-06-27 08:51:06 +00:00
* notation `Vector[type, N]` , e.g. `Vector[uint64, N]`
2019-06-28 15:07:36 +00:00
* **list**: ordered variable-length homogeneous collection, limited to `N` values
2019-06-27 08:51:06 +00:00
* notation `List[type, N]` , e.g. `List[uint64, N]`
2019-06-28 15:07:36 +00:00
* **bitvector**: ordered fixed-length collection of `boolean` values, with `N` bits
2019-06-27 08:51:06 +00:00
* notation `Bitvector[N]`
2019-06-28 15:07:36 +00:00
* **bitlist**: ordered variable-length collection of `boolean` values, limited to `N` bits
2019-06-27 08:51:06 +00:00
* notation `Bitlist[N]`
2019-06-27 10:30:23 +00:00
* **union**: union type containing one of the given subtypes
2021-05-25 17:46:23 +00:00
* notation `Union[type_0, type_1, ...]` , e.g. `union[None, uint64, uint32]`
2018-09-23 23:52:38 +00:00
2020-06-18 04:47:10 +00:00
*Note*: Both `Vector[boolean, N]` and `Bitvector[N]` are valid, yet distinct due to their different serialization requirements. Similarly, both `List[boolean, N]` and `Bitlist[N]` are valid, yet distinct. Generally `Bitvector[N]` /`Bitlist[N]` are preferred because of their serialization efficiencies.
2019-05-01 12:52:37 +00:00
### Variable-size and fixed-size
2019-05-01 10:39:44 +00:00
2019-06-27 08:51:06 +00:00
We recursively define "variable-size" types to be lists, unions, `Bitlist` and all types that contain a variable-size type. All other types are said to be "fixed-size".
2019-03-17 11:33:29 +00:00
2022-08-25 08:08:04 +00:00
### Byte
2023-09-19 12:23:08 +00:00
Although the SSZ serialization of `byte` is equivalent to that of `uint8` , the former is used for opaque data while the latter is intended as a number.
2022-08-25 08:08:04 +00:00
2019-02-27 17:00:49 +00:00
### Aliases
2018-10-02 13:33:11 +00:00
2019-02-27 10:54:23 +00:00
For convenience we alias:
2018-10-02 13:33:11 +00:00
2019-06-27 08:51:06 +00:00
* `bit` to `boolean`
2021-04-20 12:18:00 +00:00
* `BytesN` and `ByteVector[N]` to `Vector[byte, N]` (this is *not* a basic type)
* `ByteList[N]` to `List[byte, N]`
2018-10-02 22:17:29 +00:00
2022-08-25 08:08:04 +00:00
Aliases are semantically equivalent to their underlying type and therefore share canonical representations both in SSZ and in related formats.
2019-04-19 08:26:54 +00:00
### Default values
2019-08-08 13:59:06 +00:00
Assuming a helper function `default(type)` which returns the default value for `type` , we can recursively define the default value for all types.
| Type | Default Value |
| ---- | ------------- |
| `uintN` | `0` |
| `boolean` | `False` |
| `Container` | `[default(type) for type in container]` |
| `Vector[type, N]` | `[default(type)] * N` |
2020-06-18 04:47:10 +00:00
| `Bitvector[N]` | `[False] * N` |
2019-08-08 13:59:06 +00:00
| `List[type, N]` | `[]` |
2020-06-18 04:47:10 +00:00
| `Bitlist[N]` | `[]` |
2019-08-08 13:59:06 +00:00
| `Union[type_0, type_1, ...]` | `default(type_0)` |
2019-04-19 08:26:54 +00:00
2019-07-25 09:32:27 +00:00
#### `is_zero`
2019-06-05 13:29:26 +00:00
2019-07-25 09:32:27 +00:00
An SSZ object is called zeroed (and thus, `is_zero(object)` returns true) if it is equal to the default value for that type.
2019-06-05 13:29:26 +00:00
2019-05-01 12:52:37 +00:00
### Illegal types
2019-07-25 09:26:27 +00:00
- Empty vector types (`Vector[type, 0]`, `Bitvector[0]` ) are illegal.
- Containers with no fields are illegal.
2021-05-25 17:46:23 +00:00
- The `None` type option in a `Union` type is only legal as the first option (i.e. with index zero).
2019-04-19 08:26:54 +00:00
2019-02-27 10:54:23 +00:00
## Serialization
2018-10-02 13:42:25 +00:00
2019-06-27 08:51:06 +00:00
We recursively define the `serialize` function which consumes an object `value` (of the type specified) and returns a bytestring of type `bytes` .
2019-02-28 10:32:54 +00:00
2019-11-21 22:13:45 +00:00
*Note*: In the function definitions below (`serialize`, `hash_tree_root` , `is_variable_size` , etc.) objects implicitly carry their type.
2019-03-18 14:57:02 +00:00
2019-06-27 08:51:06 +00:00
### `uintN`
2019-03-18 22:28:33 +00:00
2018-09-23 23:52:38 +00:00
```python
2019-02-27 10:54:23 +00:00
assert N in [8, 16, 32, 64, 128, 256]
2019-07-04 13:38:08 +00:00
return value.to_bytes(N // BITS_PER_BYTE, "little")
2018-09-23 23:52:38 +00:00
```
2019-06-27 08:51:06 +00:00
### `boolean`
2019-03-18 22:28:33 +00:00
2018-10-26 13:22:28 +00:00
```python
2019-02-27 16:35:26 +00:00
assert value in (True, False)
2019-03-17 11:33:29 +00:00
return b"\x01" if value is True else b"\x00"
2018-09-23 23:52:38 +00:00
```
2019-06-27 08:51:06 +00:00
### `Bitvector[N]`
```python
2019-07-12 20:20:07 +00:00
array = [0] * ((N + 7) // 8)
for i in range(N):
array[i // 8] |= value[i] < < (i % 8)
return bytes(array)
2019-06-27 08:51:06 +00:00
```
### `Bitlist[N]`
2019-10-25 10:02:12 +00:00
Note that from the offset coding, the length (in bytes) of the bitlist is known. An additional `1` bit is added to the end, at index `e` where `e` is the length of the bitlist (not the limit), so that the length in bits will also be known.
2019-06-27 08:51:06 +00:00
```python
2019-07-12 20:20:07 +00:00
array = [0] * ((len(value) // 8) + 1)
for i in range(len(value)):
array[i // 8] |= value[i] < < (i % 8)
array[len(value) // 8] |= 1 < < (len(value) % 8)
return bytes(array)
2019-06-27 08:51:06 +00:00
```
2021-05-25 17:46:23 +00:00
### Vectors, containers, lists
2019-03-18 14:57:02 +00:00
2019-04-13 13:44:14 +00:00
```python
2019-05-07 00:36:55 +00:00
# Recursively serialize
2019-04-24 05:53:28 +00:00
fixed_parts = [serialize(element) if not is_variable_size(element) else None for element in value]
variable_parts = [serialize(element) if is_variable_size(element) else b"" for element in value]
2019-03-18 14:57:02 +00:00
2019-04-13 13:50:23 +00:00
# Compute and check lengths
2019-04-13 13:55:08 +00:00
fixed_lengths = [len(part) if part != None else BYTES_PER_LENGTH_OFFSET for part in fixed_parts]
2019-04-13 14:10:02 +00:00
variable_lengths = [len(part) for part in variable_parts]
2019-04-13 13:55:08 +00:00
assert sum(fixed_lengths + variable_lengths) < 2 * * ( BYTES_PER_LENGTH_OFFSET * BITS_PER_BYTE )
2019-03-18 14:57:02 +00:00
2019-04-13 14:22:41 +00:00
# Interleave offsets of variable-size parts with fixed-size parts
2020-09-09 11:04:53 +00:00
variable_offsets = [serialize(uint32(sum(fixed_lengths + variable_lengths[:i]))) for i in range(len(value))]
2019-04-13 14:26:44 +00:00
fixed_parts = [part if part != None else variable_offsets[i] for i, part in enumerate(fixed_parts)]
2019-03-18 14:57:02 +00:00
2019-04-13 14:22:41 +00:00
# Return the concatenation of the fixed-size parts (offsets interleaved) with the variable-size parts
2019-04-24 05:53:28 +00:00
return b"".join(fixed_parts + variable_parts)
2018-10-03 05:08:20 +00:00
```
2021-05-25 17:46:23 +00:00
### Union
2019-04-10 14:09:53 +00:00
2021-05-25 17:46:23 +00:00
A `value` as `Union[T...]` type has properties `value.value` with the contained value, and `value.selector` which indexes the selected `Union` type option `T` .
A `Union` :
2021-05-28 19:27:19 +00:00
- May have multiple selectors with the same type.
2021-05-25 17:46:23 +00:00
- Should not use selectors above 127 (i.e. highest bit is set), these are reserved for backwards compatible extensions.
- Must have at least 1 type option.
- May have `None` as first type option, i.e. `selector == 0`
- Must have at least 2 type options if the first is `None`
- Is always considered a variable-length type, even if all type options have an equal fixed-length.
2019-04-10 14:09:53 +00:00
```python
2021-05-25 17:46:23 +00:00
if value.value is None:
assert value.selector == 0
return b"\x00"
else:
serialized_bytes = serialize(value.value)
serialized_selector_index = value.selector.to_bytes(1, "little")
return serialized_selector_index + serialized_bytes
2019-04-10 14:09:53 +00:00
```
2019-02-27 10:54:23 +00:00
## Deserialization
2018-11-15 13:12:34 +00:00
2021-05-28 19:27:19 +00:00
Because serialization is an injective function (i.e. two distinct objects of the same type will serialize to different values) any bytestring has at most one object it could deserialize to.
2019-08-27 10:45:17 +00:00
Deserialization can be implemented using a recursive algorithm. The deserialization of basic objects is easy, and from there we can find a simple recursive algorithm for all fixed-size objects. For variable-size objects we have to do one of the following depending on what kind of object it is:
* Vector/list of a variable-size object: The serialized data will start with offsets of all the serialized objects (`BYTES_PER_LENGTH_OFFSET` bytes each).
* Using the first offset, we can compute the length of the list (divide by `BYTES_PER_LENGTH_OFFSET` ), as it gives us the total number of bytes in the offset data.
* The size of each object in the vector/list can be inferred from the difference of two offsets. To get the size of the last object, the total number of bytes has to be known (it is not generally possible to deserialize an SSZ object of unknown length)
* Containers follow the same principles as vectors, with the difference that there may be fixed-size objects in a container as well. This means the `fixed_parts` data will contain offsets as well as fixed-size objects.
2019-10-25 10:02:12 +00:00
* In the case of bitlists, the length in bits cannot be uniquely inferred from the number of bytes in the object. Because of this, they have a bit at the end that is always set. This bit has to be used to infer the size of the bitlist in bits.
2021-05-29 01:13:22 +00:00
* In the case of unions, the first byte of the deserialization scope is deserialized as type selector, the remainder of the scope is deserialized as the selected type.
2018-11-15 13:12:34 +00:00
2019-06-28 15:07:36 +00:00
Note that deserialization requires hardening against invalid inputs. A non-exhaustive list:
2019-07-04 13:26:07 +00:00
- Offsets: out of order, out of range, mismatching minimum element size.
2019-06-28 15:07:36 +00:00
- Scope: Extra unused bytes, not aligned with element size.
- More elements than a list limit allows. Part of enforcing consensus.
2021-05-25 17:46:23 +00:00
- An out-of-bounds selected index in an `Union`
2019-06-28 15:07:36 +00:00
2019-08-27 10:45:17 +00:00
Efficient algorithms for computing this object can be found in [the implementations ](#implementations ).
2019-02-27 10:54:23 +00:00
## Merkleization
2018-11-15 13:12:34 +00:00
2019-02-27 10:54:23 +00:00
We first define helper functions:
2018-11-15 13:12:34 +00:00
2019-07-14 22:12:12 +00:00
* `size_of(B)` , where `B` is a basic type: the length, in bytes, of the serialized form of the basic type.
2019-07-12 19:15:28 +00:00
* `chunk_count(type)` : calculate the amount of leafs for merkleization of the type.
* all basic types: `1`
2019-07-14 22:12:12 +00:00
* `Bitlist[N]` and `Bitvector[N]` : `(N + 255) // 256` (dividing by chunk size, rounding up)
* `List[B, N]` and `Vector[B, N]` , where `B` is a basic type: `(N * size_of(B) + 31) // 32` (dividing by chunk size, rounding up)
* `List[C, N]` and `Vector[C, N]` , where `C` is a composite type: `N`
2019-07-12 19:15:28 +00:00
* containers: `len(fields)`
2020-06-25 03:20:57 +00:00
* `pack(values)` : Given ordered objects of the same basic type:
2020-06-26 03:33:23 +00:00
1. Serialize `values` into bytes.
2020-06-26 03:32:56 +00:00
2. If not aligned to a multiple of `BYTES_PER_CHUNK` bytes, right-pad with zeroes to the next multiple.
3. Partition the bytes into `BYTES_PER_CHUNK` -byte chunks.
4. Return the chunks.
2020-06-25 03:20:57 +00:00
* `pack_bits(bits)` : Given the bits of bitlist or bitvector, get `bitfield_bytes` by packing them in bytes and aligning to the start. The length-delimiting bit for bitlists is excluded. Then return `pack(bitfield_bytes)` .
2019-06-28 20:45:20 +00:00
* `next_pow_of_two(i)` : get the next power of 2 of `i` , if not already a power of 2, with 0 mapping to 1. Examples: `0->1, 1->1, 2->2, 3->4, 4->4, 6->8, 9->16`
2019-07-12 19:15:28 +00:00
* `merkleize(chunks, limit=None)` : Given ordered `BYTES_PER_CHUNK` -byte chunks, merkleize the chunks, and return the root:
2020-06-25 03:20:57 +00:00
* The merkleization depends on the effective input, which must be padded/limited:
2019-07-12 19:15:28 +00:00
- if no limit: pad the `chunks` with zeroed chunks to `next_pow_of_two(len(chunks))` (virtually for memory efficiency).
2020-06-25 03:20:57 +00:00
- if `limit >= len(chunks)` , pad the `chunks` with zeroed chunks to `next_pow_of_two(limit)` (virtually for memory efficiency).
2019-07-12 19:15:28 +00:00
- if `limit < len(chunks)` : do not merkleize, input exceeds limit. Raise an error instead.
2019-07-04 13:26:07 +00:00
* Then, merkleize the chunks (empty input is padded to 1 zero chunk):
2019-07-12 19:15:28 +00:00
- If `1` chunk: the root is the chunk itself.
- If `> 1` chunks: merkleize as binary tree.
2019-03-06 16:46:40 +00:00
* `mix_in_length` : Given a Merkle root `root` and a length `length` (`"uint256"` little-endian serialization) return `hash(root + length)` .
2021-05-25 17:46:23 +00:00
* `mix_in_selector` : Given a Merkle root `root` and a type selector `selector` (`"uint256"` little-endian serialization) return `hash(root + selector)` .
2018-11-15 13:12:34 +00:00
2019-02-27 16:56:51 +00:00
We now define Merkleization `hash_tree_root(value)` of an object `value` recursively:
2019-02-16 21:44:27 +00:00
2019-07-04 13:38:08 +00:00
* `merkleize(pack(value))` if `value` is a basic object or a vector of basic objects.
2020-05-13 08:26:20 +00:00
* `merkleize(pack_bits(value), limit=chunk_count(type))` if `value` is a bitvector.
2019-07-12 19:15:28 +00:00
* `mix_in_length(merkleize(pack(value), limit=chunk_count(type)), len(value))` if `value` is a list of basic objects.
2020-05-13 08:26:20 +00:00
* `mix_in_length(merkleize(pack_bits(value), limit=chunk_count(type)), len(value))` if `value` is a bitlist.
2019-07-04 13:38:08 +00:00
* `merkleize([hash_tree_root(element) for element in value])` if `value` is a vector of composite objects or a container.
2019-07-12 19:15:28 +00:00
* `mix_in_length(merkleize([hash_tree_root(element) for element in value], limit=chunk_count(type)), len(value))` if `value` is a list of composite objects.
2021-05-25 17:46:23 +00:00
* `mix_in_selector(hash_tree_root(value.value), value.selector)` if `value` is of union type, and `value.value` is not `None`
* `mix_in_selector(Bytes32(), 0)` if `value` is of union type, and `value.value` is `None`
2019-02-16 21:44:27 +00:00
2019-08-14 13:48:30 +00:00
## Summaries and expansions
Let `A` be an object derived from another object `B` by replacing some of the (possibly nested) values of `B` by their `hash_tree_root` . We say `A` is a "summary" of `B` , and that `B` is an "expansion" of `A` . Notice `hash_tree_root(A) == hash_tree_root(B)` .
2020-01-10 18:42:55 +00:00
We similarly define "summary types" and "expansion types". For example, [`BeaconBlock` ](../specs/phase0/beacon-chain.md#beaconblock ) is an expansion type of [`BeaconBlockHeader` ](../specs/phase0/beacon-chain.md#beaconblockheader ). Notice that objects expand to at most one object of a given expansion type. For example, `BeaconBlockHeader` objects uniquely expand to `BeaconBlock` objects.
2019-08-14 13:48:30 +00:00
2018-09-23 23:52:38 +00:00
## Implementations
2020-11-22 06:12:32 +00:00
See https://github.com/ethereum/eth2.0-specs/issues/2138 for a list of current known implementations.
2022-08-25 08:08:04 +00:00
## JSON mapping
The canonical JSON mapping assigns to each SSZ type a corresponding JSON encoding, enabling an SSZ schema to also define the JSON encoding.
When decoding JSON data, all fields in the SSZ schema must be present with a value. Parsers may ignore additional JSON fields.
| SSZ | JSON | Example |
| --- | --- | --- |
| `uintN` | string | `"0"` |
| `byte` | hex-byte-string | `"0x00"` |
| `boolean` | bool | `false` |
| `Container` | object | `{ "field": ... }` |
| `Vector[type, N]` | array | `[element, ...]` |
| `Vector[byte, N]` | hex-byte-string | `"0x1122"` |
| `Bitvector[N]` | hex-byte-string | `"0x1122"` |
| `List[type, N]` | array | `[element, ...]` |
| `List[byte, N]` | hex-byte-string | `"0x1122"` |
| `Bitlist[N]` | hex-byte-string | `"0x1122"` |
| `Union[type_0, type_1, ...]` | selector-object | `{ "selector": number, "data": type_N }` |
Integers are encoded as strings to avoid loss of precision in 64-bit values.
Aliases are encoded as their underlying type.
`hex-byte-string` is a `0x` -prefixed hex encoding of byte data, as it would appear in an SSZ stream.
`List` and `Vector` of `byte` (and aliases thereof) are encoded as `hex-byte-string` . `Bitlist` and `Bitvector` similarly map their SSZ-byte encodings to a `hex-byte-string` .
`Union` is encoded as an object with a `selector` and `data` field, where the contents of `data` change according to the selector.