本文へ移動
← Inside Reth — シンク・拡張・SDK
Reth スタック — シンク・拡張・SDK

Rust Ethereum のスタックを学ぶ · スタックの内部 — 順不同

トピック:Reth の Execution Extensions(ExEx) →
このコースの 15 / 1724 分

レッスン14 — Stage と ExEx のテスト — fixture chain・インプロセスノード・golden state

問い

Stage トレイト・ExEx API・NodeBuilder SDK を歩いてきた。Reth と Reth を拡張するアプリは、これらの動作をどう検証しているか? dev で「動いて見える」コンポーネントは本番で何千人ものユーザの状態を静かに壊する。Reth 自身の CI がそれを防ぐパターンは?

原理(最小モデル)

  • 2 テスト層が必要. Stage/ExEx ユニットテスト(Stage を直接呼ぶ / ExEx を直接駆動、ノード起動なし)+ NodeBuilder 統合テスト(NodeBuilder::testing_node でノード全体をインプロセス起動)。ヘルパーはすべて test-utils feature の裏。
  • TestStageDB(reth_stages::test_utils). テストごとに一時 MDBX + static file / RocksDB ディレクトリ。db.factory.provider_rw() が Stage::execute / unwind に渡す provider。
  • Stage のメソッドは同期. fn execute(&mut self, provider: &Provider, input: ExecInput) -> Result<ExecOutput, StageError>。非同期の準備は poll_execute_ready 側。Reth 自身の stage テストは reth_testing_utils::generators のランダムブロック + crate 内部の stage_test_suite_ext! マクロ。
  • ExEx ハーネス. reth_exex_test_utils::test_exex_context() が (ExExContext, TestExExHandle) を返す(一時 DB + mainnet genesis 挿入済み + 一時 WAL)。handle に send_notification_chain_committed / _reorged / _reverted、assert_event_finished_height(BlockNumHash)、assert_events_empty()。PollOnce::poll_once() で ExEx を Pending まで駆動。
  • インプロセスノード. NodeBuilder::new(NodeConfig::test()).testing_node(runtime).node(EthereumNode::default()).launch() が使い捨て datadir でフルノード起動。crates/ethereum/node/tests/e2e/ の e2e テストがこの形。
  • Reth CI の実チェーン検証は golden ファイルではない. ef-tests が ethereum/tests + execution-spec-tests の fixture を再生し毎ブロック state root を照合。stage.yml が merge queue で mainnet 0–50,000 の各 stage を reth stage run(job は merge_group イベントでのみ実行、main に入る前に検査)。sync.yml が 6 時間ごとに mainnet をブロック 100,000 まで sync → unwind。
  • Building tier との接続. Building tier の test gate のレッスンが ExEx インデクサ lab に課す「fixture chain replay」= この §2 ExEx ユニットテストパターンのアプリ層適用。

具体例

2 テスト層:

層何をテストするか何を起動するか
Stage / ExEx ユニットテストtrait 実装単体に、用意したチェーンイベントを与える一時 DB(ExEx は + 一時 WAL・ネットワークハンドル)— ノードは起動しない
NodeBuilder 統合テスト自前コンポーネントを差したノード全体Reth ノードを一時 datadir でインプロセス起動

Stage ユニットテスト(Reth eb4c15e でコンパイル・合格確認済み、依存: reth-stages(test-utils)+ reth-stages-api):

use reth_stages::test_utils::TestStageDB;
use reth_stages_api::{
    ExecInput, ExecOutput, Stage, StageCheckpoint, StageError, StageId, UnwindInput, UnwindOutput,
};

/// A trivial stage: "processes" every block up to the target and records the checkpoint.
struct CountStage;

impl<Provider> Stage<Provider> for CountStage {
    fn id(&self) -> StageId {
        StageId::Other("Count")
    }

    fn execute(&mut self, _provider: &Provider, input: ExecInput) -> Result<ExecOutput, StageError> {
        Ok(ExecOutput::done(StageCheckpoint::new(input.target())))
    }

    fn unwind(
        &mut self,
        _provider: &Provider,
        input: UnwindInput,
    ) -> Result<UnwindOutput, StageError> {
        Ok(UnwindOutput { checkpoint: StageCheckpoint::new(input.unwind_to) })
    }
}

#[test]
fn execute_then_unwind() {
    let db = TestStageDB::default(); // fresh temp MDBX + static files per test
    let provider = db.factory.provider_rw().unwrap();
    let mut stage = CountStage;

    let out = stage.execute(&provider, ExecInput { target: Some(10), checkpoint: None }).unwrap();
    assert_eq!(out, ExecOutput::done(StageCheckpoint::new(10)));

    let out = stage
        .unwind(&provider, UnwindInput { checkpoint: out.checkpoint, unwind_to: 5, bad_block: None })
        .unwrap();
    assert_eq!(out.checkpoint.block_number, 5);

    provider.commit().unwrap();
}

実際の stage は provider 経由でテーブルを読み書きするので、本物のテストは先に TestStageDB::insert_blocks(...)(ブロックは reth_testing_utils::generators::random_block_range)で seed し、execute 後・unwind 後のテーブルを検証する。create_test_provider_factory()(reth_provider::test_utils)は stage ヘルパー抜きの同種の使い捨て factory。どちらもテストごとに ephemeral DB = 共有状態なし + cleanup 定型コードなし + stale fixture なし。

🔍 リポジトリで確認. crates/stages/stages/src/stages/sender_recovery.rs の mod tests → execute_single_transaction。ランダムブロックを seed → テストランナーで実行 → ExecOutput を厳密 assert。ランナー(crates/stages/stages/src/test_utils/runner.rs)の中身は provider_rw() → stage.execute(&provider, input) → commit() で、上のテストが手でやっていることと同じ。

ExEx ユニットテスト(ハーネス、Reth eb4c15e でコンパイル・合格確認済み)。commit で +1・revert で −1 する ExEx に 3 commit + 1 revert:

use futures::TryStreamExt;
use reth_execution_types::{Chain, ExecutionOutcome};
use reth_exex::{ExExContext, ExExEvent, ExExNotification};
use reth_exex_test_utils::{test_exex_context, PollOnce};
use reth_node_api::FullNodeComponents;
use reth_trie::{updates::TrieUpdatesSorted, HashedPostStateSorted};
use reth_trie_common::LazyTrieData;
use std::{
    pin::pin,
    sync::{
        atomic::{AtomicI64, Ordering},
        Arc,
    },
};

/// +1 per committed chain, -1 per reverted chain.
async fn counter_exex<Node: FullNodeComponents>(
    mut ctx: ExExContext<Node>,
    count: Arc<AtomicI64>,
) -> eyre::Result<()> {
    while let Some(notification) = ctx.notifications.try_next().await? {
        match &notification {
            ExExNotification::ChainCommitted { .. } => {
                count.fetch_add(1, Ordering::SeqCst);
            }
            ExExNotification::ChainReverted { .. } => {
                count.fetch_sub(1, Ordering::SeqCst);
            }
            ExExNotification::ChainReorged { .. } => {}
        }
        if let Some(committed) = notification.committed_chain() {
            ctx.events.send(ExExEvent::FinishedHeight(committed.tip().num_hash()))?;
        }
    }
    Ok(())
}

#[tokio::test]
async fn three_commits_one_revert() -> eyre::Result<()> {
    let (ctx, mut handle) = test_exex_context().await?;
    let head = ctx.head;
    let genesis = handle.genesis.clone();
    let chain = || {
        Chain::from_block(
            genesis.clone(),
            ExecutionOutcome::default(),
            LazyTrieData::ready(
                Arc::new(HashedPostStateSorted::default()),
                Arc::new(TrieUpdatesSorted::default()),
            ),
        )
    };

    let count = Arc::new(AtomicI64::new(0));
    let mut exex = pin!(counter_exex(ctx, count.clone()));

    for _ in 0..3 {
        handle.send_notification_chain_committed(chain()).await?;
        exex.poll_once().await?; // drive the ExEx until it is Pending again
        handle.assert_event_finished_height((head.number, head.hash).into())?;
    }
    handle.send_notification_chain_reverted(chain()).await?;
    exex.poll_once().await?;
    handle.assert_events_empty(); // a pure revert has no committed chain -> no FinishedHeight

    assert_eq!(count.load(Ordering::SeqCst), 2);
    Ok(())
}

ハマりどころ 3 つ:

  • 自分で poll する. バックグラウンドでは何も動かない。future が Pending でなく終了すると poll_once は PollOnceError::FutureIsReady — 本番でも返った ExEx はノードを落とす。
  • 通知チャネルの容量は 1. send → poll → send の順。poll なしで 2 回 send するとブロック。
  • handle の assert は同期. assert_event_finished_height は BlockNumHash を取り eyre::Result を返す。ハーネスが用意するブロックは handle.genesis だけ、追加の fixture ブロックは自作。

形は reth-exex-examples/minimal/src/main.rs 末尾のテストと同じ。Arc<AtomicI64> は ExEx が所有する状態をテストから読むため(Reth Book の Tracking State が ExEx を struct にするのも同じ理由)。ハーネスなし = ノード起動 + 実ブロック再生 + イベント待ち。ハーネスあり = 各通知が単一関数呼び出し。

NodeBuilder 統合テスト(Reth eb4c15e で合格確認済み、reth-node-builder の test-utils):

use reth_node_builder::{NodeBuilder, NodeConfig, NodeHandle};
use reth_node_ethereum::EthereumNode;
use reth_provider::BlockNumReader;
use reth_tasks::Runtime;

#[tokio::test]
async fn boots_in_process() -> eyre::Result<()> {
    let runtime = Runtime::test();
    let config = NodeConfig::test().with_unused_ports();
    let NodeHandle { node, node_exit_future: _ } = NodeBuilder::new(config)
        .testing_node(runtime.clone()) // ephemeral temp datadir
        .node(EthereumNode::default())
        .launch()
        .await?;

    assert_eq!(node.provider.best_block_number()?, 0);
    Ok(())
}

testing_node(...) が datadir を一時ディレクトリに向けてテスト DB を開く。launch() が返す FullNode の公開フィールド(node.pool、node.provider、node.network、node.payload_builder_handle)を直接駆動。自前コンポーネントを差すなら .node(EthereumNode::default()) を .with_types::<EthereumNode>().with_components(EthereumNode::components().pool(MyPoolBuilder)).with_add_ons(EthereumAddOns::default()) に(crates/ethereum/node/tests/it/builder.rs の形)。Reth の e2e テスト(crates/ethereum/node/tests/e2e/pool.rs、dev.rs 等)は起動したノードを reth_e2e_test_utils::NodeTestContext で包んで tx 投入・ブロック進行。手元で上のテストは約 3.6 秒(stage テストは 0.3 秒)= テストごとにフル起動。それでもコンポーネント間バグを捕まえられるのはこの層だけ。

Fixture-chain テスト — Reth は自家製の「golden DB」ファイルを持たない。CI の実際の 3 つ(eb4c15e のパス):

チェック場所何を assert するか
コンセンサス fixturetesting/ef-tests(.github/workflows/unit.yml が実行)ethereum/tests + execution-spec-tests(v4.5.0)の blockchain test を再生、毎ブロック state root を再計算して不一致なら state root mismatch(testing/ef-tests/src/cases/blockchain_test.rs)、最後に期待 post-state をアカウント単位で比較
Stage 実行.github/workflows/stage.yml(merge queue。job は merge_group イベントでのみ実行)mainnet で headers・bodies・senders・execution・merkle・tx-lookup・history 各 stage を reth stage run <stage> --from 0 --to 50000 --commit --checkpoints
固定 tip sync.github/workflows/sync.yml(6 時間ごと)reth node --chain mainnet --debug.tip <hash> --debug.max-block 100000 --debug.terminate → ブロック 100000 のヘッダハッシュ確認 → reth stage unwind

「golden」値は 外部: fixture の期待 post-state、または実チェーンのブロックハッシュ・state root。任意 stage の回帰が state-root / ハッシュ不一致として現れる = コンセンサスバグを出荷前に捕獲。自前拡張で流用できるのは ef-tests ランナーの形(実行 → 公開 post-state と比較)と、ノード起動前に chain RLP を import できる reth_e2e_test_utils(crates/e2e-test-utils/src/setup_import.rs)。

失敗例(誤解)

「ユニットテストだけで十分」— 間違い。コンポーネント間相互作用(カスタム pool ビルダーが payload builder の挙動に依存する等)はユニットテストでは見えない。統合テスト必須。

「ExEx テストは tokio::spawn(exex) して待てば良い」— 間違い。ハーネスの流儀は future を pin してテスト側で poll_once()。spawn するとテストが ExEx の進行を制御できず、イベント assert がタイミング依存になる。

「Reth は自前の golden state ファイルを CI で比較している」— 間違い。比較対象は外部の正解(ef-tests の期待 post-state、mainnet の実ハッシュ)。stage.yml は merge queue ごと、sync.yml は 6 時間ごと。

ステップで組み立てる

Step 1: 2 テスト層を即答

ユニット(trait 実装単体)+ 統合(ノード全体)。

Step 2: Stage ユニットテストパターン

TestStageDB::default() + provider_rw() + 同期 execute + assert + unwind + assert(seed は insert_blocks)。

Step 3: ExEx ユニットテストハーネス

test_exex_context() + send_notification_* + poll_once() + assert_event_finished_height。

Step 4: NodeBuilder 統合テスト

testing_node() でインプロセス起動 + FullNode のフィールド(pool / provider / network)を直接駆動。

Step 5: Fixture-chain テスト

ef-tests(毎ブロック state root)+ reth stage run(mainnet 0–50k)+ 固定 tip sync(mainnet 100k)。

Step 6: Building tier との接続

Building tier test gate の fixture chain replay = §2 のアプリ層適用。

答え合わせ

  • reth-exex-test-utils を別 crate で同梱する理由: ExExContext を作るには provider・EVM 設定・ネットワーク・WAL・イベント/通知チャネルが要る。ハーネスがそれを一時リソースで組み立て、イベント受信・通知送信の チャネル両端を handle に持たせる。テストは send → poll_once → assert を決定的に回せる。
  • Fixture-chain 検証が Reth の CI に必須な理由: 任意 stage の回帰が state-root / ハッシュ不一致 として現れる = コンセンサスクリティカルバグを出荷前に捕獲。正解は外部(ef-tests の期待値、mainnet の実チェーン)なので自己参照にならない。
  • 2 層テストの補完関係: ユニット = trait 実装単体の正しさ(速い、ノード不要)+ 統合 = コンポーネント間相互作用(数秒、ノード組み立て)。どちらかを省くと特定クラスのバグが通り抜ける。

Expert への接続

Reth コンポーネント層のテスト規律。Systems 層では Expert tier の 2 レッスンがこれを発展させる:

合格基準

  • 2 テスト層と各々が何をテストするかを言える。
  • TestStageDB + 同期 execute / unwind のテストを書ける。
  • test_exex_context() + poll_once() のハーネスパターンを書ける。
  • testing_node() での統合テスト構造を即答できる。
  • Reth CI の実チェーン検証 3 つ(ef-tests / stage run / pinned sync)を言える。

まとめ(3行)

  • Stage: TestStageDB + provider_rw() 上の同期 execute / unwind。ノード全体: NodeBuilder::testing_node(...) でインプロセス。
  • ExEx: test_exex_context() + send_notification_chain_* + poll_once() + assert_event_finished_height。reorg は _reorged / _reverted で注入。
  • Reth CI の実チェーン検証 = ef-tests の state root + mainnet 0–50k の reth stage run + 100k ブロックの固定 tip sync。Building tier の test gate が §2 をアプリ層で適用。