Serving BlocksByRange from a Canonical Index in ethlambda
Reading time: 9 minutesethlambda is a minimalist Ethereum consensus client from LambdaClass, written in Rust. Over a few months I contributed a series of changes to it, and the thread that ran through most of them was one question: how does a node that is behind catch up, and how does a node that is ahead serve it cheaply?
This post follows that thread through three pull requests. First I added the BlocksByRange protocol. Then I wired it into long-range sync. Finally I replaced the naive way of serving it with a canonical slot-to-block-root index in storage. The last step is the most interesting, because an index over “the canonical chain” is only correct if it moves every time the canonical chain moves, including during reorgs.
What BlocksByRange is for
Consensus clients talk to each other in two ways. Gossip pushes new blocks and attestations to everyone as they happen. Request/response (req/resp) lets one peer ask another for specific data.
Gossip is fine when you are at the head. It is useless when you are a thousand slots behind, because nobody is gossiping blocks from an hour ago. For that, the consensus p2p spec defines BlocksByRange: “give me the blocks for slots start_slot through start_slot + count - 1.” The responder streams back blocks from its canonical chain, in slot order, skipping empty slots. There is also BlocksByRoot, which asks for specific block hashes, and is the right tool when you already know which block you are missing.
Two properties matter for the rest of this post:
- The answer is defined in terms of the canonical chain. Blocks on side forks must not appear, even if the responder has them stored.
- The request is cheap to send and the responder pays for it. Any work the responder does per request is work a peer can make it do on demand.
The Lean Consensus spec added the protocol in leanSpec#691, and ethlambda needed to support it.
Step one: a working protocol
My first PR, #348, added inbound support. It registered /leanconsensus/req/blocks_by_range/1/ssz_snappy with libp2p, added SSZ codec paths, and validated requests: a zero count, a zero step, or a count above MAX_REQUEST_BLOCKS (1024) gets an INVALID_REQUEST response. During review we also unified the response type, since BlocksByRoot and BlocksByRange both return a list of signed blocks, so there is now a single ResponsePayload::Blocks variant.
The interesting part is how it found the blocks. Storage at that point was keyed by block root, with no way to ask “which canonical block is at slot N?” So the handler walked backwards from the fork-choice head, following parent_root, until it passed start_slot:
let mut roots_by_slot = HashMap::new();
let mut current_root = store.head().expect("head block exists");
while !current_root.is_zero() {
let Ok(Some(header)) = store.get_block_header(¤t_root) else {
break;
};
if header.slot < start_slot {
break;
}
if header.slot <= end_slot {
roots_by_slot.insert(header.slot, current_root);
}
current_root = header.parent_root;
}
This is correct, and correctness comes for free: walking parent links from the head only ever visits canonical blocks, so side forks are excluded by construction. But the cost is proportional to head_slot - start_slot, not to count. A request for 1024 blocks near genesis on a long-running node reads every header between the head and genesis. The automated reviewer flagged it as a cheap DoS surface, and the maintainer, MegaRedHand, suggested the real fix: an index from block number to block root. He opened issue #355 for it and assigned it to me. We merged the walk first so the protocol existed, and came back to performance separately.
Step two: using it to sync
#351 made ethlambda use the protocol as a client. When a peer’s Status shows a head ahead of ours, the node requests the gap in batches.
My first version was too eager. It fired off every batch at once, to every peer that reported being ahead, with no deduplication and no retry. Review pushed it towards a much better shape: a single RangeSyncState with one batch in flight at a time.
pub(crate) struct RangeSyncState {
/// Remaining slots to request, with an exclusive end.
pub(crate) current_range: Range<u64>,
/// Latest advertised head slot for each peer.
pub(crate) peer_set: HashMap<PeerId, u64>,
pub(crate) in_flight: bool,
}
New Status responses only extend current_range.end. Each completed batch advances current_range.start. Peers whose advertised head falls behind the start are dropped, and a failed peer is removed from the set. Two other details came out of review and are worth calling out because they are about distrust:
- The total range is capped (
MAX_SYNC_RANGE = MAX_REQUEST_BLOCKS * 64), because the gap comes from a peer’s unauthenticatedStatusmessage. - Blocks in a response whose slot falls outside the requested range are dropped with a warning instead of being forwarded to the blockchain layer.
Shortly after, #407 fixed a bug this exposed: the req/resp decoder read the whole remaining stream for the first chunk, so multi-block responses failed at the snappy layer. It now decodes one varint-prefixed snappy payload at a time.
Step three: the canonical index
With sync working, the per-request walk was the obvious weak point. #495 closed issue #355 by adding a new storage table:
/// Canonical block index: slot -> block root
BlockRoots,
The key is the slot as big-endian bytes, and the value is the SSZ-encoded root. Big-endian matters: it makes byte order equal numeric order, so a backend like RocksDB could later serve a range as a single ordered scan instead of point lookups.
The read side becomes simple. Following another review suggestion, the lookup lives in storage as Store::get_signed_blocks_by_slot_range, which opens one read view and reuses it for the whole range:
pub fn get_signed_blocks_by_slot_range(
&self,
start_slot: u64,
end_slot: u64,
) -> Result<Vec<SignedBlock>, Error> {
let view = self.backend.begin_read().expect("read view");
let mut blocks = Vec::new();
for slot in start_slot..=end_slot {
let Some(root_bytes) = view
.get(Table::BlockRoots, &encode_block_root_key(slot))
.expect("get block root")
else {
continue; // empty slot, or not canonical
};
let root = H256::from_ssz_bytes(&root_bytes).expect("valid block root");
if let Some(block) = Self::signed_block_from_view(view.as_ref(), &root) {
blocks.push(block);
}
}
Ok(blocks)
}
Putting this behind a storage method, rather than in the p2p handler, was the right boundary. The p2p layer now asks a question in protocol terms (“blocks in this slot range”) and storage decides how to answer it. The handler just logs on error and returns an empty response.
| Before (#348) | After (#495) | |
|---|---|---|
| Work per request | Header reads from head back to start_slot |
One index read per slot in the range, plus block reads |
| Depends on | Distance from head | count only |
| Side-fork exclusion | Implicit in the parent walk | Index must only hold canonical roots |
| Extra storage | None | One small entry per canonical block |
That third row is the whole problem. The walk got canonicality for free. The index has to earn it.
Keeping the index canonical under reorgs
“Canonical” is not a fixed property of a block. It is a property of the block relative to the current head, and fork choice can move the head to a different branch at any time. So the index has to be updated whenever the head changes, and the update has to be a correct diff between the old canonical chain and the new one.
The update lives in update_checkpoints, the method fork choice already calls to move the head. Before writing, it computes the diff by walking the old head and the new head back to their common ancestor:
// Walk both branches back until they meet at the common ancestor.
while old_root != new_root {
if old_header.slot < new_header.slot {
entries.push((encode_block_root_key(new_header.slot), new_root.to_ssz()));
new_root = new_header.parent_root;
new_header = self
.get_block_header(&new_root)?
.ok_or(Error::UnexpectedMissingBlockHeader(new_root))?;
} else {
deletes.push(encode_block_root_key(old_header.slot));
old_root = old_header.parent_root;
old_header = self
.get_block_header(&old_root)?
.ok_or(Error::UnexpectedMissingBlockHeader(old_root))?;
}
}
At each step it moves whichever side has the higher slot. Slots that were canonical on the old branch get deleted; slots on the new branch get written. If both sides have a block at the same slot, the delete and the put target the same key, but deletes are queued before puts and the batch applies operations in order, so the new root wins.
graph RL
B3["slot 3 (old head)"] --> B1["slot 1"]
B1 --> G["slot 0 (anchor)"]
B4["slot 4 (new head)"] --> B2["slot 2"]
B2 --> G
In that picture, moving the head from slot 3 to slot 4 deletes keys 3 and 1 and writes keys 4 and 2. Slot 0 is the common ancestor and is untouched. In the common case, where the new head is just a child of the old one, the loop runs once and writes one entry. The cost of maintaining the index is proportional to the depth of the reorg, which is the right thing to pay for.
Three decisions made this hold up:
- Same batch as the head. The index deletes and puts go into the same write batch as the new
KEY_HEADmetadata, so the head pointer and the index commit together. There is no window where a reader sees the new head with the old index. - Fail loudly on a broken invariant. My first version had defensive branches for reaching a zero parent root. The reviewer asked when that could actually happen. The honest answer was that it should never happen in normal fork-choice updates, because both heads always share an ancestor above genesis. So the final version returns
UnexpectedMissingBlockHeaderinstead of quietly producing a partial diff, which would have corrupted the index silently. - Seed it at the anchor.
init_storewrites the anchor (genesis or checkpoint) block root intoBlockRoots, so the walk always has a base to converge on.
Trade-offs I accepted
Storage. One key per canonical block. Headers and bodies are kept for the whole history in ethlambda, so the index is tiny by comparison. Old signatures are pruned, but the pruning test now asserts that headers, bodies and index entries all stay queryable.
Migration. The first draft rebuilt the index on startup if it was missing, by walking from the head back to the anchor. The reviewer pointed out that this is the same unbounded walk we were trying to get rid of, just moved to startup. We agreed to assume any existing database already has BlockRoots populated, and only initialize it for fresh stores. The consequence is that a database created before this change will not serve history from before the upgrade. That is a real cost, and it was a deliberate one: a hidden full-chain scan at startup is worse than an explicit “resync if your DB predates this.”
Consistency model. The index is derived data, and it is only as correct as the code path that moves the head. Routing every head change through update_checkpoints keeps that to one place, but it also means any future code that writes KEY_HEAD some other way would have to update the index too.
Testing
The core test builds a small fork by hand: anchor at slot 0, blocks at slots 1 and 3 on one branch, and a skipped slot 2. It moves the head to slot 3 and asserts the index holds 0, 1 and 3, with 2 empty. Then it adds a side branch at slots 2 and 4, moves the head there, and asserts the index flipped completely: 1 and 3 are gone, 2 and 4 point at the side branch, and 0 is unchanged. That one test covers extension, skipped slots, side forks and a reorg.
A second test writes through a store, reopens it with from_db_state, and checks that get_signed_blocks_by_slot_range still returns the right block, which guards the “existing DBs already have it” assumption. The existing BlocksByRange handler test now exercises the indexed path too.
Other ethlambda contributions
The rest of my ethlambda commits cluster around sync and correctness:
- #417 aligned the sync-status heuristic with leanSpec#708 (lag threshold, network-stall detection, hysteresis), and #418 used it to skip proposals and attestations while syncing, so validators do not sign on a chain the network has left. #436 moved the tracker into its own module.
- #552 stored fork-choice votes independently, because deriving them from bounded proof buffers meant a FIFO eviction could silently drop a validator’s latest vote.
- #426 added the
MultiMessageAggregateSSZ container for Devnet 5, and #319 made the node’s actors and HTTP servers shut down gracefully. - Smaller ones: a status-ahead warning (#432), slot intervals as an enum (#496), a unified Hive and spec-test fork-choice runner (#524), and CI using released leanSpec fixtures (#385).
- Still open: #618, which fixes the duty gate reporting “synced” during backfill on a stale head.
Takeaways
- Make protocol cost track request size. A handler whose work depends on chain depth rather than
counthands peers a lever. Indexing turned an O(history) request into an O(count) one. - Derived indexes need one owner. “Canonical” changes with the head, so the index is updated in the same method, and the same write batch, that moves the head.
- Diff by walking to the common ancestor. It handles extensions, skipped slots and reorgs with one loop, and costs the depth of the reorg.
- Prefer a loud invariant to a quiet fallback. A partial index diff is worse than an error.
- Shipping in stages worked. A correct-but-slow protocol, then a client, then the index. Each PR was reviewable on its own, and review made every one of them better.