Writing

Local Trust vs Protocol Finality: Starting Grandine From a Non-Finalized Checkpoint

Reading time: 10 minutes

Work in progress. This project is still under active development and PR #851 is in review. This post is a snapshot of where things stand, not a finished result, and I will update it as the work moves forward.

For my Ethereum Protocol Fellowship (cohort 7) project I have been teaching Grandine, a Rust consensus client, to start from a trusted checkpoint that is not yet finalized. The motivation and the original design are in two earlier posts: the project proposal and the draft design document. This post is about what has happened so far as I build it.

The short version: the hard part was not downloading a newer block. It was that Grandine used one value to mean two different things, and most of the work came from pulling those meanings apart without breaking the path everyone already depends on.

The implementation lives in grandinetech/grandine#851. It is still in progress and under review, and I will be explicit below about what is verified so far and what is not.

Two kinds of “finalized”

When a beacon node checkpoint-syncs, it downloads a block and its post-state from a provider and starts from there instead of from genesis. In Grandine that startup block is the anchor. Before this work, the anchor was always the network’s finalized checkpoint, so the code could safely treat it as both:

  • the trusted local anchor: the boundary the node accepts on trust and will never roll back past; and
  • the protocol-finalized checkpoint: the on-chain finality the node reports to peers, to the Beacon API and to its own sync logic.

Those two coincide when you start from finalized. They stop coinciding the moment you start from something newer. A non-finalized anchor is something I trust as an operator. It is not something the network has agreed is irreversible, and the node must not claim otherwise.

So the invariant I wrote down for a non-finalized start is:

protocol-finalized checkpoint <= trusted startup anchor <= current remote head

The downloaded BeaconState already carries the real finalized_checkpoint. Nothing about protocol finality is lost in transit. The question is only whether the client keeps using it, or quietly overwrites it with the anchor.

The spike: make it work, then see what breaks

The Grandine team’s feedback on my proposal was to go implementation-first instead of landing a large new abstraction up front. In hindsight that was the right call: my design proposed several new types (AnchorCheckpoint, ForkChoiceInit, a “local irreversible” checkpoint), and the spike showed the code needed fewer than I had planned.

The first commit, 1b0f3dac, added one CLI option:

grandine \
  --network hoodi \
  --checkpoint-sync-url https://FULL_HOODI_BEACON_API \
  --checkpoint-sync-block-id head \
  --force-checkpoint-sync

It accepts anything Grandine’s BlockId already parses: finalized, head, a slot or a block root. Omitting it still means finalized, so the existing path is untouched by default. The loader then:

  1. fetches the selected block from /eth/v2/beacon/blocks/{block_id};
  2. walks back to the most recent available epoch-start block, because Store::new requires an epoch-start anchor;
  3. fetches the matching state by slot;
  4. checks the block and state against each other in both directions before anything reaches the store.
if block.message().state_root() != state.hash_tree_root() {
    bail!(Error::BlockStateRootMismatch { /* ... */ });
}

if accessors::latest_block_root(state) != block.message().hash_tree_root() {
    bail!(Error::BlockStateMismatch { /* ... */ });
}

I added that validation deliberately. A non-finalized selection means trusting the provider for more than before, so the cheapest defence is to make inconsistent responses fail loudly at the loader rather than trip assertions deep inside fork choice.

My first test pointed head at the usual Hoodi checkpoint-sync endpoint, and it returned HTTP 500 for /eth/v2/beacon/blocks/head. That was my first lesson: a checkpoint-sync endpoint is built to serve finalized checkpoints, not arbitrary block IDs. I switched to the full Hoodi Beacon API, and with Reth as the execution client Grandine fetched the head, normalized it to epoch-start slot 3686048, loaded the state, started P2P and the HTTP API, and advanced to slot 3686144.

Then I compared what the state said with what the node said:

Source Finalized
BeaconState finality checkpoints epoch 115190 (current justified 115191)
Grandine /eth/v1/beacon/headers/finalized slot 3686144, the same block as /headers/head

The state was right and the node was wrong. Grandine was reporting its own head as finalized. That single table justified the whole second milestone.

Separating the two, with the smallest change I could defend

Store::new built one checkpoint from the anchor and assigned it to justified, finalized and both unrealized checkpoints. Large parts of fork choice, including the initial finalized chain, assume finalized_checkpoint is the local boundary. Re-deriving all of that at once would have meant a huge, hard-to-review diff in consensus-critical code.

So in f8e09615 I made a narrower cut. The store keeps its internal finalized_checkpoint at the anchor, and gains a second field for the externally meaningful value:

// A non-finalized startup anchor is a trusted local boundary, not a claim of protocol
// finality. Keep the checkpoint reported to peers and APIs separate until on-chain finality
// advances beyond the anchor.
protocol_finalized_checkpoint: Checkpoint,

It starts from the state’s real finalized checkpoint and only moves forward:

if finalized_checkpoint.epoch > self.protocol_finalized_checkpoint.epoch {
    self.protocol_finalized_checkpoint = finalized_checkpoint;
}

Then I rerouted the consumers that face outward, and only those:

  • controller and snapshot finalized_epoch() / finalized_root(), which feed P2P status and forward sync;
  • BlockId::Finalized and StateId::Finalized in the Beacon API;
  • Store::is_slot_finalized, which decides the finalized flag on responses;
  • finalized event notifications.

Because the API now has to resolve a block older than the anchor, the loader also downloads, validates and persists the protocol-finalized block and state. When the selection is finalized, that branch does not run and protocol_finalized_checkpoint simply equals the anchor, which keeps the old behaviour by construction.

flowchart TD
    A["--checkpoint-sync-block-id"] --> B["fetch selected block"]
    B --> C["normalize to epoch-start anchor"]
    C --> D["fetch + validate anchor state"]
    D --> E{"selection == finalized?"}
    E -- yes --> F["anchor is also protocol finality (old path)"]
    E -- no --> G["read state.finalized_checkpoint()"]
    G --> H["fetch + validate finalized block and state"]
    H --> I["persist both, record protocol_finalized_checkpoint"]
    F --> J["Store: internal boundary = anchor"]
    I --> J
    J --> K["API, P2P status, sync, events use protocol finality"]

This is an incremental compromise, not the final architecture: two “finalized” fields on one struct can confuse the next reader. The trade-off I chose was: a small, reviewable diff that makes every external claim correct now, plus a written list of the internal places that still treat the anchor as finalized (FinalizedCheckpoint as the anchor type, AnchorCheckpointProvider, the FinalizedBlockByRoot write, back-sync bookkeeping). Whether those deserve a proper anchor abstraction is a decision I would rather make with evidence and with the maintainers than guess at alone.

I backed this with a focused test, non_finalized_startup_reports_protocol_finality_separately_from_anchor. It builds a controller from an epoch-3 anchor with an epoch-1 protocol-finalized checkpoint and asserts that the internal checkpoint is the anchor, the reported finality is epoch 1, and the head is not flagged finalized. It also builds a normal controller from the same anchor and checks that finality there still equals the anchor.

Testing against infrastructure that lies

Code complete is not the same as verified, and the next few weeks were mostly about getting a clean live run.

The first live attempt of the milestone got further than ever: Grandine loaded a non-finalized anchor at slot 3931136, then failed with:

remote beacon node does not have protocol-finalized state for block
0x909ccd747ac35cba31f80285baa554bd9896ec591436818a2c5d30213ec05424

That was a real bug (more on it below). But after fixing it locally, every retry failed earlier, inside SSZ decoding of the anchor state:

offsets 226285627 and 125615949 are not valid subslice bounds
for slice of length 125615949

The important detail is what stayed constant and what did not. The required offset was the same every time (226285627), but the body length changed between attempts: 126103373, 94756685, 114605901, 125615949 bytes. A decoder bug would fail the same way on the same input. A varying length under a fixed expected size points at the transport, not at Grandine.

I did not want to “fix” that by guessing, so I measured it directly. I downloaded the same state (slot 4197536) from the full Hoodi Beacon API four times. Every request returned HTTP 200, and every transfer stopped after roughly 90 to 116 seconds at a different size: 67.4, 69.5, 59.4 and 89.0 MB, with no Content-Length header. Grandine’s fetch only learns something is wrong when the SSZ offsets do not fit.

That diagnosis kept me from blaming my own change, and kept provider-specific retry hacks out of a consensus-correctness PR.

Next, following Saulius’s suggestion, I probed every Hoodi provider on the checkpoint-sync endpoints list:

Endpoint type finalized head State size returned
Full Beacon API (beacon.hoodi.ethpandaops.io) yes yes truncated, varied per request
Checkpointz (EthStaker, Attestant, Stakely, ethPandaOps, ChainSafe, Sigma Prime) yes 500 / 404 complete

So I had one provider that supported the routes I needed but could not deliver a whole state, and six that delivered whole states but would not serve head.

Exercising the non-finalized path through Checkpointz

The way out came from re-reading my own invariant. Every checkpoint state records a finalized checkpoint older than itself. Grandine decides which path to take from the selection, not from the network’s opinion of the block:

let protocol_finalized = if block_id == BlockId::Finalized {
    None
} else {
    let checkpoint = state.finalized_checkpoint();
    // fetch, validate and return the older protocol-finalized block and state
};

So if I select a Checkpointz checkpoint by slot with --checkpoint-sync-block-id <slot> instead of finalized, Grandine treats it as a trusted anchor and goes on to fetch the older protocol-finalized block and state separately. That is exactly the code path I needed to test, and Checkpointz supports every request in it: block by slot, block by root, state by slot and state by state root. I confirmed the states are complete: the state at slot 4197600 came back as exactly 237,589,421 bytes, both by slot and by state root.

The limitation is real and I want to be clear about it. Hoodi is finalizing normally, so a “non-finalized” anchor chosen this way is already finalized on the network. This exercises the anchor/finality separation and the lookup logic, but it does not simulate a long period of non-finality, which is the scenario the feature exists for.

The state-root vs block-root bug

Back to the error from the first live run. The pushed code fetched the protocol-finalized block correctly by the checkpoint’s block root, then passed that same block root to the state endpoint as StateId::Root. The Beacon API’s state-by-root lookup expects a state root. The hash in the error message was the finalized checkpoint’s block root, being used where a state root belonged. Both are H256, so the type system had no way to catch it.

The fix is to take the state root from the block I have already fetched and validated:

let finalized_state_root = finalized_block.message().state_root();
let finalized_state =
    fetch_state(config, client, url, StateId::Root(finalized_state_root))
        .await?
        .ok_or(Error::ProtocolFinalizedStateNotFound {
            state_root: finalized_state_root,
        })?;

I also renamed the error field from block_root to state_root, because the old message described the wrong thing and made the failure harder to read.

A fix found in a live test that cannot be reproduced reliably needs a test that does not depend on the network. The regression test builds a small Minimal-preset chain in which every block fully attests the previous epoch, so the last state finalizes an older block. It serves that chain from an httpmock server and registers two mocks for the finalized state: one at the correct state-root path that returns the state, and one at the block-root path that returns 404. Then it asserts the important part:

state_by_state_root.assert();
state_by_block_root.assert_calls(0);

It also checks the preconditions that make the test meaningful: the finalized epoch is older than the anchor’s epoch, and the block root differs from the state root. Without those, the test could pass for the wrong reason.

Where the work stands now

  • End-to-end validation. The latest code, with the state-root fix, has not yet completed a clean live Hoodi run. The next run goes through Checkpointz by slot and compares /headers/head, /headers/finalized and finality_checkpoints, cross-checking the finalized slot and state root against a second Checkpointz instance.
  • Forward-sync lower boundary. My design doc proposed that forward sync should start from the trusted anchor. The current implementation starts it from protocol finality, which is older than the anchor after a non-finalized start. I do not yet know which is right in practice, so I plan to check the sync logs during the live test and raise it on the PR rather than change it on intuition.
  • Restart and persistence. I have not proven that a restart reconstructs both the trusted boundary and protocol finality from storage.
  • Remaining internal assumptions. The anchor is still typed and stored as a FinalizedCheckpoint, and back-sync still describes it as finalized. Each needs a review before the design can be called complete.
  • Failure modes. Explicit block-root selection, missing epoch-boundary blocks, provider capability errors and a finalized checkpoint-sync regression run are all still on the list.

What I learned

  • Name the trust assumption before you write code. “Finalized” was carrying two meanings in Grandine. Once I wrote down protocol-finalized <= anchor <= head, it was obvious which consumers needed which value.
  • Fix the external contract first, and document the rest. Peers, APIs and sync logic now see the network’s real finality. The internal compromise is written down instead of hidden, which makes it a review question instead of a latent bug.
  • Keep the default path correct by construction. With finalized selected, the new field equals the anchor and the new loader branch never runs. That is easier to trust than a set of if statements spread across the codebase.
  • HTTP 200 is not proof of a complete response. When the error changes but the expected size does not, look at the transport before you blame the decoder.
  • Use your own invariants to build test fixtures. Selecting by slot turned six “unsuitable” Checkpointz endpoints into a reliable way to test the non-finalized path.
  • A bug found live needs a test that runs offline. The block-root and state-root mix-up is now pinned by a mock-server test that fails if the wrong path is ever requested again.

Week-by-week progress is in my EPF cohort 7 weekly updates.