レッスン7 — 最小 ExEx を 1 行ずつ読む
問い
動く ExEx は Rust 約 40 行で書ける。Reth を fork せず、別プロセスを立てず、ノードビルダーに渡す関数 1 つ — その各行が前レッスンの組み立てステップにどう対応するか?
先に答え(reth eb4c15e で確認):
- head と datadir.
ctx.headは起動時のノード head(BlockNumHash)。datadir はctx.config.datadir()(例ctx.config.datadir().data_dir().join("my-exex"))、Reth 自身の ExEx WAL は<datadir>/exex/wal。 - 再同期なしで再開・再生. 処理済み最終ブロックを保存し、
exex_initでctx.set_notifications_with_head(ExExHead::new(saved))。Reth が自 DB からsaved+1..=ctx.headを再実行(savedが非 canonical なら先に revert)し、ライブ通知へ。 FinishedHeight.ctx.send_finished_height(tip.num_hash())は「この高さ以下(含む)は不要」。下がることもある: revert だけが来たとき(ChainReverted)は、取り消した区間の直前のブロック(old.fork_block())を報告する(下のコード例のとおり)。全 ExEx の最小値が pruning/WAL 削除を律速し、全 ExEx が一度送るまで prune されない。
use futures::{Future, TryStreamExt};
use reth_exex::{ExExContext, ExExHead};
use reth_node_api::FullNodeComponents;
async fn exex_init<Node: FullNodeComponents>(
mut ctx: ExExContext<Node>,
) -> eyre::Result<impl Future<Output = eyre::Result<()>>> {
// 自分の状態は Reth の隣に: 例 ~/.local/share/reth/mainnet/my-exex
let dir = ctx.config.datadir().data_dir().join("my-exex");
std::fs::create_dir_all(&dir)?;
// 処理済み最終ブロック。`dir` 内の自前ストアから読む(初回は None)。
let saved: Option<ExExHead> = None;
if let Some(head) = saved {
// Reth が自 DB から head+1..=ctx.head を再実行し、その後ライブ通知。
ctx.set_notifications_with_head(head);
}
Ok(async move {
while let Some(n) = ctx.notifications.try_next().await? {
if let Some(old) = n.reverted_chain() {
// old.blocks_iter() を自分の状態から undo
if n.committed_chain().is_none() {
// ChainReverted のみ: 最後に正しいブロックは `old` の直前。
// ExExHead::new(parent) を `dir` に保存し、下がった高さを報告
let parent = old.fork_block();
let _ = ExExHead::new(parent);
ctx.send_finished_height(parent)?;
}
}
if let Some(new) = n.committed_chain() {
// new.blocks_iter() / new.execution_outcome() を apply し、
// ExExHead::new(new.tip().num_hash()) を `dir` に保存
let _ = ExExHead::new(new.tip().num_hash());
ctx.send_finished_height(new.tip().num_hash())?;
}
}
Ok(())
})
}
原理(最小モデル)
- 40 行で完成する 5 要素. init/run 分割 + 永続 future + 3 アーム match +
committed_chain()+install_exex配線。 builder.install_exex("id", exex_init)で init 関数を登録.exex_init(ctx: ExExContext<Node>) -> eyre::Result<impl Future<Output = eyre::Result<()>>>内でセットアップ(DB を開く・保存済み head を読む)し、常駐 future を返す。- 3 バリアントはすべて
Arc<Chain>を持つ.ChainCommitted { new }/ChainReorged { old, new }/ChainReverted { old }。ブロックはnew.blocks_iter()、状態変更と receipt はnew.execution_outcome()。 committed_chain()は便利アクセサ.ChainCommittedとChainReorged(new)にはSome(Arc<Chain>)、ChainRevertedにはNone。FinishedHeightの送信. commit を伴う通知ごとにctx.send_finished_height(chain.tip().num_hash())。忘れると pruner が止まり(設定時)、<datadir>/exex/walが消えない(Reth が warning を出す)。- 本物の ExEx 4 系統. backfill(RPC で指定範囲を再実行)+ in-memory-state(plain state をメモリ保持)+ op-bridge(OP bridge イベントを SQLite へ)+ rollup(L1 から状態を導出する最小ロールアップ、SQLite)。
具体例
最小 ExEx 全コード(paradigmxyz/reth-exex-examples/minimal の main.rs):
use futures::{Future, TryStreamExt};
use reth_exex::{ExExContext, ExExEvent, ExExNotification};
use reth_node_api::FullNodeComponents;
use reth_node_ethereum::EthereumNode;
use reth_tracing::tracing::info;
async fn exex_init<Node: FullNodeComponents>(
ctx: ExExContext<Node>,
) -> eyre::Result<impl Future<Output = eyre::Result<()>>> {
Ok(exex(ctx))
}
async fn exex<Node: FullNodeComponents>(mut ctx: ExExContext<Node>) -> eyre::Result<()> {
while let Some(notification) = ctx.notifications.try_next().await? {
match ¬ification {
ExExNotification::ChainCommitted { new } => {
info!(committed_chain = ?new.range(), "Received commit");
}
ExExNotification::ChainReorged { old, new } => {
info!(from_chain = ?old.range(), to_chain = ?new.range(), "Received reorg");
}
ExExNotification::ChainReverted { old } => {
info!(reverted_chain = ?old.range(), "Received revert");
}
};
if let Some(committed_chain) = notification.committed_chain() {
ctx.events.send(ExExEvent::FinishedHeight(committed_chain.tip().num_hash()))?;
}
}
Ok(())
}
fn main() -> eyre::Result<()> {
reth::cli::Cli::parse_args().run(|builder, _| async move {
let handle = builder
.node(EthereumNode::default())
.install_exex("Minimal", exex_init)
.launch_with_debug_capabilities()
.await?;
handle.wait_for_node_exit().await
})
}
各部の対応:
exex_init(init/run 分割): ノード起動時に 1 度、Reth が ExExContext を渡す(head + config + notifications + events + ノードコンポーネントへのハンドル)、長時間動く future を返す。最小版は同期セットアップなし。
exex(長時間動く future): メインループ、ctx.notifications は eyre::Result<ExExNotification> の Stream、try_next() で next イベント await(スレッドブロックなし、未完なら他 ExEx + Reth 自体を走らせる)。ExEx は永久に動く前提: future が返ると(Ok でも Err でも)critical task のクラッシュ扱いでノード停止。通常のシャットダウンではタスクが cancel される。末尾の Ok(()) は型合わせ。
3 アーム match: ChainCommitted / ChainReorged / ChainReverted。最小版はログのみ、本物は派生状態更新。3 アーム正しく扱えるかが「動くインデクサ vs phantom-data バグ」を分ける。ChainReverted は通常の reorg ではなく、Reth がブロックを unwind した時(pipeline unwind、または再起動時に保存 head が非 canonical)に来る。
committed_chain() + FinishedHeight:
notification.committed_chain()— ChainCommitted と ChainReorged(new)にはSome(Arc<Chain>)、ChainReverted にはNone。逆側はreverted_chain()ctx.events.send(ExExEvent::FinishedHeight(...))(=ctx.send_finished_height(...))— ExEx manager に「このブロックまで(含む)処理した」。全 ExEx の最小値が pruner と ExEx WAL 削除を律速- commit を伴う通知ごとに送信、忘却 → pruning 停止 + WAL が消えない
main 配線: 通常 Reth ノード + 拡張 1 つ。install_exex("Minimal", exex_init) が ExEx 固有の唯一の行、複数 install で拡張コンポーズ可能。
本物の ExEx 4 系統:
| 例 | 内容 |
|---|---|
| backfill | RPC(backfill_start)で指定範囲を BackfillJobFactory で再実行 |
| in-memory-state | plain state をメモリに保持(各 chain の ExecutionOutcome を apply / revert) |
| op-bridge | L1 上の OP Stack bridge の deposit/withdrawal イベントを SQLite に記録 |
| rollup | L1 コントラクトのイベントから状態を導出する最小ロールアップ(SQLite) |
失敗例(誤解)
「ChainReorged の new だけで十分」— 間違い。new apply 前に old の状態変更を undo 必要、new だけだと古いチェーンの効果を派生状態から巻き戻せず → 静かに二重カウント or 取りこぼし。
「exex_init で同期セットアップを書かなくても良い」— 間違い。失敗し得るセットアップは exex_init に置く。init の Err はノード起動失敗として即座に分かる。常駐 future の Err は critical task クラッシュでノード停止。exex_init でセットアップ + future 返す。
「install_exex を 1 回で十分」— 不足。複数 ExEx を install できる。各 ExEx は独立した通知と FinishedHeight を持つが、1 つでも終了・クラッシュするとノード全体が停止し、最も遅い ExEx が pruning/WAL 削除を律速する。
ステップで組み立てる
Step 1: exex_init の役割
ノード起動時 1 度、同期セットアップ(DB を開く・保存済み head を読み set_notifications_with_head)+ future 返す。
Step 2: exex の永続ループ
while let Some(notification) = ctx.notifications.try_next().await? の構造。ループを抜けて future が返るとノード停止。
Step 3: 3 アーム match の load-bearing 性
本物の ExEx は派生状態更新、3 アーム正しく扱えるかが phantom-data バグ防止。
Step 4: committed_chain() の 3 バリアント挙動
ChainCommitted → Some(new) / ChainReorged → Some(new) / ChainReverted → None。
Step 5: FinishedHeight の送信タイミング
commit を伴う通知ごと。pruning と ExEx WAL 削除を止めないため。
Step 6: install_exex を main で配線
NodeBuilder にチェイン、複数 install で拡張コンポーズ。
答え合わせ
ChainReorgedで old/new 両方渡される理由: インデクサはnewを apply する前にoldの状態変更を undo 必要。newだけだと古いチェーンの効果を派生状態から巻き戻せず、静かに二重カウント or 取りこぼし。アトミック undo+apply のために両方必要。committed_chain()の 3 バリアント挙動: ChainCommitted と ChainReorged(new)にはSome(Arc<Chain>)、ChainReverted にはNone。「この通知後の canonical 状態は何か」を取り出すアクセサ、if let Some(...) = ...パターンでFinishedHeight送信判定に使う。- 「ExEx としてのロールアップ」が依存するもの: ホストチェーン(Reth ノードが追う L1。例では Holesky)の finality と DA に依存。Reth はその canonical チェーンの通知を届けるだけ。ロールアップは Reth fork ではなく ExEx フックだけで実装可能 = アーキテクチャ上のアンロック。
合格基準
- 40 行の最小 ExEx の 5 要素(init/run + 永続 future + 3 アーム + committed_chain + install_exex)を即答できる。
committed_chain()の 3 バリアント挙動を言える。FinishedHeight送信タイミング(commit を伴う通知ごと)と、忘れた時の影響(pruning 停止 + WAL 残留)を即答できる。- 本物の ExEx 4 系統(backfill / in-memory-state / op-bridge / rollup)を言える。
- 「ExEx としてのロールアップ」の依存(ホストチェーンの finality + DA)を 1 文で説明できる。
まとめ(3行)
- 40 行の最小 ExEx = init/run 分割 + 永続 future(
try_next().await、返ればノード停止)+ 3 アーム match +committed_chain()でFinishedHeight送信 +install_exex配線。 committed_chain()が ChainCommitted/Reorged(new)→Some、ChainReverted →None、これでFinishedHeight判定。再開はctx.set_notifications_with_head(ExExHead)。- 本物の ExEx 4 系統(backfill / in-memory-state / op-bridge / rollup)、ロールアップは ExEx フックだけで Reth fork なしに実装可能 = アーキテクチャ上のアンロック。