Skip to main content
· 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​

· 7 min read

Overview of Fork Choice in Gloas

Author:
Protocol Engineer

Fork choice in Gloas is modified to account for scenarios where a builder does not reveal the execution payload. In a beacon node, we must determine the effective payload status of each block. As a result, fork choice adopts voting over (root, payload_status) rather than over block roots alone.

At a high level, we collect attestation votes for block N. Based on the contents of block N, we can derive how many supporting votes apply to (parent_root, FULL) and (parent_root, EMPTY), where parent_root = block.parent_root. By combining supporting votes, local payload availability, and PTC votes, the fork choice weight calculation is modified, which in turn affects head selection.

Specification

Useful Resources​

Container​

In pre-Gloas fork choice, the block tree is conceptualized as a tree of blocks, where each node is represented solely by its block root. In post-Gloas fork choice, the tree consists of ForkChoiceNodes, each of which contains both a beacon block root and a PayloadStatus. As a result, function signatures such as get_head, get_ancestor, and get_weight are updated accordingly.

The fork choice store Store introduces two additional fields: • execution_payload_states: a dictionary mapping beacon block roots to post-states after process_execution_payload • ptc_vote: a dictionary mapping beacon block roots to a boolean vector of length PTC_SIZE, where true indicates payload present and false indicates payload absent

execution_payload_states serves several purposes. First, it provides the post-state of the previous slot when importing a new block in on_block, allowing state transition to proceed correctly. Second, it indicates local payload availability: if an execution payload state exists for a given root, the node has locally observed the execution payload. Otherwise it has not. A more subtle role is that it participates in payload status tie-breaking, which is discussed later.

ptc_vote represents votes from the Payload Timeliness Committee. It comes from block.body.payload_attestations of importing blocks. It influences the head block decision to see whether we should prefer extending payload or not through the tie-breaking logic.

Note that Store.block_states now stores the intermediate state after the beacon block state transition and before process_execution_payload. If the execution payload is missing, this intermediate state is used as the post-state when importing subsequent blocks.

Decision Making​

In the spec, we have a new type named PayloadStatus which can be FULL, EMPTY or PENDING. But notice that our fork choice store doesn't store any payload status or ForkChoiceNode. This is because the payload statuses (inside ForkChoiceNodes) are dynamically generated during node tree construction when determining head block. PENDING means the status of the payload is not yet determined which means the associated node is the leaf of the tree. One confusing part is PENDING is also used as a stub or dummy value when determining head block.

If we look at get_head(), we see we start with our justified checkpoint node and we assign PENDING to the node's status.

def get_head(store: Store) -> ForkChoiceNode:
# Get filtered block tree that only includes viable branches
blocks = get_filtered_block_tree(store)
# Execute the LMD-GHOST fork-choice
head = ForkChoiceNode(
root=store.justified_checkpoint.root,
payload_status=PAYLOAD_STATUS_PENDING,
)

while True:
children = get_node_children(store, blocks, head)
if len(children) == 0:
return head
# Sort by latest attesting balance with ties broken lexicographically
head = max(
children,
key=lambda child: (
get_weight(store, child),
child.root,
get_payload_status_tiebreaker(store, child),
),
)

In get_node_children, there are two branches. If node is PENDING, add a node with the same block root and EMPTY as node's child, and add a node with the same block root and FULL as node's child if we have observed the execution payload. If node is not PENDING, then we search for child blocks that build on this block root like the status quo, but we also add PENDING as the stub status. So this get_head() algorithm is modified to oscillate between PENDING -> EMPTY/FULL -> PENDING -> EMPTY/FULL until we reach the leaves of the tree.

def get_node_children(
store: Store, blocks: Dict[Root, BeaconBlock], node: ForkChoiceNode
) -> Sequence[ForkChoiceNode]:
if node.payload_status == PAYLOAD_STATUS_PENDING:
children = [ForkChoiceNode(root=node.root, payload_status=PAYLOAD_STATUS_EMPTY)]
if node.root in store.execution_payload_states:
children.append(ForkChoiceNode(root=node.root, payload_status=PAYLOAD_STATUS_FULL))
return children
else:
return [
ForkChoiceNode(root=root, payload_status=PAYLOAD_STATUS_PENDING)
for root in blocks.keys()
if (
blocks[root].parent_root == node.root
and node.payload_status == get_parent_payload_status(store, blocks[root])
)
]

Below is an illustration of the Gloas node tree, adapted in a style similar to eth2book:

gloas-fork-choice-tree

Here, ps denotes payload status and pps denotes parent payload status. The winning path in this example is A → C → E, and get_weight(store, (A, PENDING)) evaluates to 215.

Observations​

Observation 1: Each non-leaf PENDING node can only point to a parent node that is EMPTY or FULL. This is because each PENDING node's block has parent_root, to know which root it should point to, and get_parent_payload_status() determines which payload status it should point to.

Observation 2: Each non-leaf PENDING node inherits sum of the weights of its two (sometimes one) children ie. (root, EMPTY) and (root, FULL).

Observation 3: FULL node is constructed only if payload is locally available. In other words, all descendants of a FULL node will not be considered when it comes to beacon node's validator casting attestation or proposing a block if the payload is not locally available.

The get_weight() function is modified to count votes supporting a given (root, payload_status) via the helper is_supporting_vote().

Miscellaneous​

Skipped Slot​

The LatestMessage container has a new field named payload_present to indicate whether the message supports FULL or EMPTY node of the given root. Although this field is always present, it is not used when the message is voting for a PENDING node in the current slot. Rather, it is used when the message is voting for FULL/EMPTY node in previous slot. In beacon node's term, this field does not matter when an attestation is voting for a head block that is in the current slot, because we do not know whether the payload will be revealed yet. PTC will fulfilled the role of indicate the payload status. But if an attestation is voting for a head block in previous slot, it indicates there is a skipped slot. Since PTC votes reside in the beacon block, missed slot means we cannot retrieve these PTC votes, and we now rely on attestation.data.index which is converted into LatestMessage.payload_present to indicate the payload status.

def is_supporting_vote(store: Store, node: ForkChoiceNode, message: LatestMessage) -> bool:
"""
Returns whether a vote for ``message.root`` supports the chain containing the beacon block ``node.root`` with the
payload contents indicated by ``node.payload_status`` as head during slot ``node.slot``.
"""
block = store.blocks[node.root]
if node.root == message.root:
if node.payload_status == PAYLOAD_STATUS_PENDING:
return True
if message.slot <= block.slot:
return False
if message.payload_present:
return node.payload_status == PAYLOAD_STATUS_FULL
else:
return node.payload_status == PAYLOAD_STATUS_EMPTY
else:
ancestor = get_ancestor(store, message.root, block.slot)
return node.root == ancestor.root and (
node.payload_status == PAYLOAD_STATUS_PENDING
or node.payload_status == ancestor.payload_status
)

Notice that if message.slot > block.slot, the message is a supporting vote for FULL or EMPTY. If message.slot == block.slot then it will only support PENDING.

Usually votes for FULL or EMPTY are not as significant as PENDING votes because we can rely on the following PENDING node's block hash to see if it is building on FULL or EMPTY to derive that information.

Tiebreaker​

In the event there are two nodes in node tree that have the same amount of weight and same root, think of two nodes (root, EMPTY) and (root, FULL) having the same weight and root, a new tiebreaker is introduced.

def get_payload_status_tiebreaker(store: Store, node: ForkChoiceNode) -> uint8:
if node.payload_status == PAYLOAD_STATUS_PENDING or store.blocks[
node.root
].slot + 1 != get_current_slot(store):
return node.payload_status
else:
# To decide on a payload from the previous slot, choose
# between FULL and EMPTY based on `should_extend_payload`
if node.payload_status == PAYLOAD_STATUS_EMPTY:
return 1
else:
return 2 if should_extend_payload(store, node.root) else 0
def should_extend_payload(store: Store, root: Root) -> bool:
proposer_root = store.proposer_boost_root
return (
is_payload_timely(store, root)
or proposer_root == Root()
or store.blocks[proposer_root].parent_root != root
or is_parent_node_full(store, store.blocks[proposer_root])
)

The high level concept is we prefer the node that is FULL with sufficiently evidence (see should_extend_payload, involves ptc_vote and execution_payload_states) > EMPTY node > Others

· 3 min read

Mitigating Supply Chain Attacks

Author:
Protocol Engineer, Technical Lead

I've heard people say that they would never trust software written in JavaScript because of the growing number of npm supply chain attacks. Kinda based, but also overly absolutist in an unproductive way.

Since we have a JS product, we take these concerns seriously and have steps in place to mitigate the risks (detailed below). With proper handling, JS products can be just as safe as those in other ecosystems.

What are Supply Chain Attacks​

Basically, an attacker gains access to the publishing credentials for a highly-used package, and publishes a maliciously crafted version of the package. Any packages or products that transitively depend on this package may then unwittingly install the malware when they install their product or upgrade their dependencies. So it may be a dependency of a dependency of a dependency of a package which can poison the product.

These malware packages are often quickly noticed within a few days, but anyone caught installing these packages during that time will be affected.

These malware packages cause extreme damage, often targeting exfiltration of additional credentials, like cryptocurrency wallets or AWS access tokens. No bueno.

The vast majority of supply chain attacks occur via the npm package registry. Why? Probably because JavaScript remains one of the largest, most popular language ecosystems and package reuse is highly encouraged. There's billions of downloads from npm per week. So it's a juicy target.

What We Do​

Use a Lockfile​

So if npm supply chain attacks occur when a user upgrades a project dependencies, we have to make sure that all upgrades are audited and intentional. This starts with a project lockfile.

A lockfile is a snapshot of exact versions of all dependencies and transitive dependencies for a project. It ensures that only those exact versions specified in the lockfile will be installed.

Our code includes a lockfile, so checking out the code and installing dependencies will always install the pre-selected dependencies, and can never expose us to a new supply chain attack.

Audit Lockfile Changes​

It's very important that every update to the lockfile is treated carefully, since updating the lockfile to a malicious version of a dependency can open up our developers or users to these supply chain attacks. We conservatively update the lockfile and don't update dependencies to newly-published versions proactively. We review diffs manually and use automated tooling to flag suspicious changes.

Enforce a Lockfile in Production​

The problem with lockfiles is that they are limited to only apply within a local project. There's no way to fully enforce a lockfile from a published package. For this reason we emphatically warn against installing Lodestar via npm.

We only support and promote deployments which respect the lockfile.

  1. Build from source
  2. Prebuilt binary
  3. Prebuilt docker image

Switch to PNPM​

We're switching to the pnpm package manager, which has been championing features to mitigate supply chain attacks. This should help us more robustly mitigate these attacks.

Minimize External Dependency Attack Surface​

We intentionally are very selective about which dependencies we rely on, choosing to copy or vendor simple code rather than fully embracing the entire npm package ecosystem. Additionally, implementing our zig roadmap will further reduce the external dependencies we rely on.

· One min read

hello world

Author:
Protocol Engineer, Technical Lead

We're Lodestar, we've built an Ethereum Consensus client entirely in Typescript, and we've begun reinventing ourselves by rewriting the beacon node in Zig, for higher performance and broader usefulness.

This blog is an experiment in sharing our informal notes as we navigate the high seas of the Ethereum R&D process and share our engineering progress.

Enjoy.