Skip to main content

One post tagged with "Ethereum"

View All Tags
· 15 min read

SSZ in lodestar-z: Schema, Values, Bytes

Author:
Protocol Engineer

Representing Ethereum's beacon state in Zig, Part 1

Table of Contents

  • Introduction
  • How Clients Generate SSZ Code
    • External Code Generation: fastssz
    • Derive Macros: ethereum_ssz
    • Compile-Time Metaprogramming: Nimbus and lodestar-z
    • Comparison
  • The Comptime Schema
    • One Definition, Four Representations
  • The Value Path
    • Where Values Are Used
    • Zero Allocation in the Core
    • Bulk memcpy in Both Directions
    • A Batch Hashing Interface
    • Benchmark
  • The Byte Path
  • Limitations
  • References

Introduction​

SSZ (Simple Serialize) is the serialization and Merkleization format of Ethereum's consensus layer. Consensus objects sent over the network, stored on disk, or signed are represented as SSZ values. The specification requires three operations for every type: serialize, deserialize, and hash_tree_root.

A Validator records a validator's public key, balance, and lifecycle in the beacon state:

FieldSSZ typePurpose
pubkeyBytes48BLS public key
withdrawal_credentialsBytes32Withdrawal credentials
effective_balanceuint64Balance used to weight consensus participation, in Gwei
slashedbooleanWhether the validator has been slashed
activation_eligibility_epochuint64When the validator became eligible for activation
activation_epochuint64When the validator becomes active
exit_epochuint64When the validator stops being active
withdrawable_epochuint64When the validator becomes eligible for full withdrawal

All eight fields have fixed sizes, so serialization concatenates their encodings in declaration order. The result is 121 bytes:

Validator serialization concatenates eight fixed-size fields into 121 bytes

For Merkleization, each field contributes a 32-byte root. The public key is the only field larger than one chunk: its 48 bytes are padded to 64 and hashed to produce its field root. The eight field roots are then hashed in pairs until one root remains:

Eight Validator field roots form a Merkle tree, with the public key expanded into two chunks

For the full serialization and Merkleization rules behind this example, see the SSZ spec, the EPF wiki's page on merkleization, and kourin's walkthrough of RLP and SSZ.

SSZ carries no type information in the wire format: no tags, no field names, no length prefix on fixed fields. Decoding therefore requires the schema to be known in advance.

The specification defines hundreds of nested types. A BeaconState, for example, contains a list of up to 2^40 Validator containers. Implementing serialization, deserialization, and Merkleization by hand for every type would be impractical. An SSZ library must therefore decide how to generate type-specific code and what runtime cost that code introduces. Runtime cost matters because some objects are large, while others arrive at high rates.

lodestar-z is ChainSafe's Zig implementation of Lodestar's performance-critical paths. It generates the per-type code with Zig's comptime: types are ordinary values at compile time, so the code generator is ordinary Zig code running inside the compiler.

This post compares how several consensus clients generate SSZ code, explains lodestar-z's comptime schema, and examines two of the four representations it provides: plain values and raw bytes. It also reports benchmark results for lodestar-z, libssz, and Lighthouse using libssz's fixture. Parts 2 and 3 cover the two tree-based representations used for the live beacon state.

How Clients Generate SSZ Code​

The production SSZ implementations considered here generate specialized code for each type at build time. They differ in where the generator runs and what information it can access.

External Code Generation: fastssz​

Prysm uses fastssz's sszgen: a standalone tool that parses Go structs and writes the methods into ordinary source files next to them:

// generated by sszgen
func (v *Validator) MarshalSSZTo(buf []byte) ([]byte, error) { ... }
func (v *Validator) UnmarshalSSZ(buf []byte) error { ... }
func (v *Validator) HashTreeRoot() ([32]byte, error) { ... }

(Prysm's earlier runtime-reflection library was retired for performance.) The generated code is fast, but the approach adds operational complexity: a second toolchain in the build, generated files that must be kept in sync with their sources, and a generator that sees Go syntax but has no access to Go's type system.

Derive Macros: ethereum_ssz​

Lighthouse's ethereum_ssz runs the generator inside rustc, with no external tool and no files to sync:

#[derive(Encode, Decode)]
pub struct Validator {
pub pubkey: PublicKeyBytes,
// ...
}

But a proc macro receives token streams. It sees PublicKeyBytes as a name, not a type, so it cannot determine at expansion time whether the field is fixed-size. The generated code defers the question to the trait system:

// inside the generated impl: a question, asked per field, answered later:
fn is_ssz_fixed_len() -> bool {
<PublicKeyBytes as Encode>::is_ssz_fixed_len() && /* ...remaining fields... */ true
}

After monomorphization, the optimizer can fold these checks away. The relevant distinction is when the fixed-size property is resolved: the macro emits trait calls, and Rust's type system resolves them later.

Compile-Time Metaprogramming: Nimbus and lodestar-z​

Nim and Zig can run the generator inside the compiler with access to the actual types. Nimbus's nim-ssz-serialization branches on type properties while compiling:

when isFixedSize(T): # answered during compilation, not deferred
...

lodestar-z uses Zig's comptime for the same purpose. Zig exposes types as compile-time values, so the generator can be written as ordinary Zig code rather than as a separate macro.

Comparison​

sszgen (Prysm)derive macro (Lighthouse)comptime (Nimbus, lodestar-z)
generator runsseparate toolinside the compilerinside the compiler
generator seessource texttoken streamactual types
extra build machinerygenerated files to syncnonenone
"is this field fixed-size?"inferred from syntaxdeferred to trait systemanswered during generation

All three approaches eventually produce specialized code for each SSZ type. They differ mainly in how that code is generated and when type information becomes available.

The Comptime Schema​

Here is lodestar-z's Validator declaration from phase0.zig:

pub const Validator = ssz.StructContainerType(struct {
pubkey: p.BLSPubkey,
withdrawal_credentials: p.Root,
effective_balance: p.Gwei,
slashed: p.Boolean,
activation_eligibility_epoch: p.Epoch,
activation_epoch: p.Epoch,
exit_epoch: p.Epoch,
withdrawable_epoch: p.Epoch,
});

StructContainerType delegates the native value type, serialization, and hashing to FixedContainerType. It supplies its own tree representation and TreeView, covered in Parts 2 and 3.

FixedContainerType walks the fields at compile time and returns a fieldless struct containing the generated operations. Here is the relevant code, condensed from container.zig:

pub fn FixedContainerType(comptime ST: type) type {
const ssz_fields = @typeInfo(ST).@"struct".fields; // walks the fields at compile time

comptime var _offsets: [ssz_fields.len]usize = undefined;
comptime var _fixed_size: usize = 0;
inline for (ssz_fields, 0..) |field, i| {
_offsets[i] = _fixed_size;
_fixed_size += field.type.fixed_size; // 48 + 32 + 8 + 1 + 4 * 8 for Validator
}

return struct { // the schema namespace: no fields, only declarations
pub const Type: type = ...; // native fields: [48]u8, [32]u8, u64, bool, ...
pub const TreeView: type = ContainerTreeView(@This()); // live state over the tree (explained in Part 3)
pub const fixed_size: usize = _fixed_size; // 121 for Validator, a compile-time constant
pub const field_offsets = _offsets;

pub fn serializeIntoBytes(value: *const Type, out: []u8) usize {
var i: usize = 0;
inline for (ssz_fields) |field| { // unrolled: one write per field, no loop at runtime
i += field.type.serializeIntoBytes(&@field(value, field.name), out[i..]);
}
return i;
}
pub const serialized = struct { ... }; // operations on raw bytes
pub const tree = struct { ... }; // operations on Merkle tree nodes
};
}

For Validator, this computes fixed_size = 121 during compilation. The inline for in serializeIntoBytes expands into eight field writes, so there is no runtime loop over the fields.

Schema constructors can be composed because their parameters are compile-time values. Capacities are expressed as comptime usize values, while options are passed as struct literals. FixedListType(Gwei, VALIDATOR_REGISTRY_LIMIT, .{ .chunked_leaf = true }) is the actual balances declaration. Part 2 covers chunked_leaf. Compile-time type information also enables validation: declaring a fixed container with a variable-size field produces an error at the definition site.

One Definition, Four Representations​

The same Validator schema provides operations on values, bytes, and tree nodes:

// Start with zero-valued fields for this SSZ example.
var validator: Validator.Type = Validator.default_value;
validator.effective_balance = 32_000_000_000;
var buf: [Validator.fixed_size]u8 = undefined; // 121 bytes, known at compile time
var out: [32]u8 = undefined;

_ = Validator.serializeIntoBytes(&validator, &buf); // value → bytes
try Validator.serialized.hashTreeRoot(&buf, &out); // root from bytes, no decode
const node = try Validator.tree.fromValue(&pool, &validator); // value → tree (Part 2)

One Validator schema provides value operations, byte operations, tree operations, and TreeView access

Validator.Type is an ordinary struct. State-transition code reads validator.slashed through a normal field access, and lists use ArrayListUnmanaged. Values contain no wrapper, embedded type descriptor, or vtable. The schema defines operations separately for each representation.

The next two sections cover the value and byte representations. Parts 2 and 3 cover the two tree representations.

The Value Path​

Where Values Are Used​

The client uses plain values in several places. Most SSZ messages, including attestations, blocks, and aggregates, are deserialized, validated, used, and then discarded. Hashing also operates on values when computing signing roots, block roots, and attestation-data roots.

The beacon state has a different access pattern. It is long-lived, about 139 MB in the benchmark fixture, and each block modifies only a small fraction of it. The live state therefore uses the persistent tree representation described in Parts 2 and 3. Plain state values are still used at boundaries such as checkpoint import and persistence.

The following sections describe three optimizations used across these workloads.

Zero Allocation in the Core​

serializedSize computes the exact output size up front: for Validator it is the constant 121; for a state, the fixed portion is a constant and each fixed-element list contributes length * element_size. serializeIntoBytes writes into a caller-provided buffer. No internal growable buffer, no final copy. Decode is symmetric: the caller owns the output value, and lists reserve exact capacity once. During repeated decoding, an existing value can reuse its reserved list capacity.

For a type whose whole shape is comptime-fixed (Validator, a Bytes32, any UintType), there is no allocator call anywhere in the value path: Validator.Type is a plain stack struct, and hashTreeRoot's scratch chunk buffer is a comptime-sized stack array ([8][32]u8 for Validator's eight field roots), not a heap allocation. Runtime-length lists are different. Although FixedListType's elements are fixed-size, its chunk count depends on how many are stored, so hashTreeRoot allocates its scratch buffer from the heap.

Bulk memcpy in Both Directions​

A comptime predicate checks two facts: the element is an integer type, and the target is little-endian. When both hold, the in-memory array is byte-identical to its SSZ encoding:

A little-endian u64 list has the same byte layout in Zig memory and SSZ, so encoding and decoding use one memcpy

The per-element alternative performs a million 8-byte stores whose vectorization is up to the optimizer. One large memcpy instead runs at memory bandwidth with the widest stores available and, at this size, uses non-temporal stores that skip the read-for-ownership traffic. balances (8 MB of u64s), slashings, and inactivity_scores take this path. libssz implements the same optimization.

A Batch Hashing Interface​

The SIMD kernel is hashtree, Prysm's standalone library. Its API takes arrays, hash(out: [][32]u8, in: [][32]u8), and interleaves four to sixteen independent SHA-256 compressions across SIMD lanes. One message is a serial 64-round dependency chain, but separate messages hide each other's latency. The kernel only helps when it receives many pairs per call.

lodestar-z batches hashes to match this interface. The hasher packs chunks into contiguous buffers (sized per type at compile time, allocated once, and reused across roots), and merkleization consumes one level per call, halving the buffer in place:

for (0..chunk_depth) |_| {
const parents = chunks[0 .. chunks.len / 2];
try hash(parents, chunks); // one call hashes the whole level
chunks = parents;
}

Merkleization hashes eight chunks in three batched calls, one tree level per call

With one million validators, balances alone occupies about 250,000 chunks. The first iteration hashes 125,000 pairs in one call, and about 38 calls replace roughly 250,000 per-pair digest() calls. The hash_tree_root rows below measure this full-state hash.

In production, the live state root is computed from the tree described in Part 2. Full-state hashing through the value API occurs only at boundaries. The benchmark still provides a direct comparison between the libraries because both the value and tree paths pass chunks to the same hashing kernel in the same batch layout. Small objects such as signing roots and block roots contain only a few chunks, so batching has less effect on them.

Benchmark​

We replicated the fixture from libssz's differential benchmark (a phase0 BeaconState with deterministic contents), field-for-field, in bench/ssz/libssz_compare.zig. All benchmarks were run serially in one session on a 16-vCPU AMD EPYC 7763 Linux machine. libssz and Lighthouse were measured with libssz's Criterion harness in release mode. lodestar-z was measured with zbench using Zig 0.16. All implementations used the system allocator.

1M validators (~139 MB state)lodestar-z (fast)lodestar-z (safe)libsszLighthouse
encode17.5 ms45.7 ms30.5 ms69.2 ms
decode17.6 ms59.4 ms20.7 ms40.0 ms
hash_tree_root (full state)466 ms474 ms1.01 s1.53 s
100K validatorslodestar-z (fast)lodestar-z (safe)libsszLighthouse
encode0.67 ms3.81 ms1.70 ms6.70 ms
decode0.88 ms4.61 ms0.84 ms3.03 ms
hash_tree_root49.9 ms50.8 ms111 ms165 ms

ReleaseFast disables safety checks; ReleaseSafe keeps bounds and overflow checks (Rust's release profile keeps only bounds checks). Safety checks mainly affect the per-element field loops. They add only 2% to hash_tree_root, where most of the time is spent inside the hashing kernel.

The Byte Path​

Two patterns in the client skip decoding entirely. The gossip pipeline triages on raw bytes: Lodestar reads the slot, block root, and attestation data directly from a serialized attestation, then deduplicates or drops messages before deserializing them. State persistence also operates directly on bytes. Checkpoint states are stored in serialized form and later loaded by comparing them with a similar state already in memory. The schema supports both patterns without constructing a value.

The serialized.* namespace provides validate, which checks structure (offset monotonicity and length bounds) by reading the buffer in place, and serialized.hashTreeRoot, which computes a root by feeding chunks to the hasher directly from the encoded buffer. For a variable-size container, serialized.hashTreeRoot does not require a separate validation pass. The same traversal of the offset table both locates each field and verifies that the offsets are monotonic and within bounds. Bounds checking and root computation can therefore happen in one pass. The container schema adds readFieldRanges, which locates each field inside an encoded container with one pass over the offset table:

One traversal of a variable-size container&#39;s offset table locates each field and produces its byte range

The state loader is the current consumer. Lodestar calls it through the NAPI bindings when a state arrives as bytes and a near-identical state is already in memory. The loader reads the fork version and the field ranges from the encoded state, locates validators (~121 MB of the 139), and compares those bytes against the seed state's serialization in 121-byte strides:

Comparing validator entries in fixed-size strides identifies one modified and one appended entry, so only those two are deserialized

Only the entries that differ are deserialized; the comparison also yields the list of modified validator indices, which downstream caches consume. The loader never decodes 139 MB to apply a few kilobytes of changes.

Limitations​

Monomorphization generates a separate copy of each operation for every schema type, increasing compile time and binary size. In a consensus client, the set of SSZ types is known at compile time, so this cost remains bounded. Zig also has no trait system, so schemas cannot explicitly declare support for operations such as serializeIntoBytes. If an operation is missing, the compiler reports the error where generic code tries to call it, and errors from deeply generated comptime code can be difficult to trace.

The value representation has a more significant limitation. A beacon state is about 150 MB, but each block changes only a few hundred bytes. Using this representation for the live state would require recomputing the full root every 12 seconds, at a measured cost of 466 ms. Because the value API cannot identify which parts changed, it cannot reuse the unaffected work. Part 2 addresses this problem by making a persistent Merkle tree the canonical representation of the live state. A plain value is then materialized only when needed.

References​