evm-fork-cache 0.4.0-alpha.3

Forked EVM state cache, snapshots, overlays, and simulation utilities for EVM search
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
//! Red-green acceptance tests for WS-2 / Phase-8 step 2:
//! strict block-context requirements and engine-driven `advance_block` env
//! refresh.
//!
//! Contract:
//! - `BlockContextRequirements::strict()` rejects a header missing a required
//!   block-env field (e.g. EIP-1559 base fee); `lenient()` (the default) accepts
//!   it; requirements are per-field so a pre-EIP-1559 chain can opt out of the
//!   base-fee requirement.
//! - `EvmCache::advance_block(header)` refreshes the full block env
//!   (number / base fee / coinbase / prevrandao / gas limit / timestamp) from a
//!   canonical header, and under strict requirements returns an error rather than
//!   silently defaulting a missing field.
//!
//! Fully offline: block headers are constructed in memory; no network access.
#![cfg(feature = "reactive")]

mod common;

use alloy_consensus::{BlockHeader as _, Header};
use alloy_eips::BlockId;
use alloy_primitives::{Address, B256, Bytes, Log as PrimitiveLog};
use alloy_rpc_types_eth::Log;
use anyhow::Result;

use common::setup_cache;
use evm_fork_cache::cache::BlockContextRequirements;

/// A synthetic canonical header. `basefee = None` models a pre-EIP-1559 block.
fn header(number: u64, basefee: Option<u64>) -> Header {
    Header {
        number,
        timestamp: 1_700_000_000 + number,
        base_fee_per_gas: basefee,
        beneficiary: Address::repeat_byte(0xcb),
        gas_limit: 30_000_000,
        mix_hash: B256::repeat_byte(0xab),
        ..Default::default()
    }
}

/// WS-2: strict requirements reject a header missing the EIP-1559 base fee, and
/// accept a complete one.
#[test]
fn strict_requirements_reject_header_missing_basefee() {
    let reqs = BlockContextRequirements::strict();

    assert!(
        reqs.validate_header(&header(100, Some(7))).is_ok(),
        "a complete header must satisfy strict requirements"
    );

    let err = reqs
        .validate_header(&header(100, None))
        .expect_err("strict must reject a header with no base fee");
    assert!(
        err.to_string().to_lowercase().contains("basefee")
            || err.to_string().to_lowercase().contains("base fee"),
        "the error must name the missing base-fee field, got: {err}"
    );
}

/// WS-2: the lenient default accepts an incomplete header (today's behavior).
#[test]
fn lenient_requirements_accept_incomplete_header() {
    let reqs = BlockContextRequirements::lenient();
    assert!(reqs.validate_header(&header(100, None)).is_ok());
    assert!(reqs.validate_header(&header(100, Some(7))).is_ok());
}

/// WS-2: requirements are per-field — a chain without EIP-1559 can turn off the
/// base-fee requirement while still requiring the rest.
#[test]
fn per_field_requirements_allow_opting_out_of_basefee() {
    let mut reqs = BlockContextRequirements::strict();
    reqs.require_basefee = false;
    assert!(
        reqs.validate_header(&header(100, None)).is_ok(),
        "opting out of the base-fee requirement must accept a header without one"
    );
}

/// Phase-8 s2: `advance_block` refreshes every block-env field from the header.
#[tokio::test]
async fn advance_block_refreshes_all_block_env_fields() -> Result<()> {
    let mut cache = setup_cache().await?;
    let h = header(12_345, Some(42));

    cache
        .advance_block(&h)
        .expect("lenient advance_block over a complete header succeeds");

    assert_eq!(cache.block_number(), Some(12_345));
    assert_eq!(cache.basefee(), Some(42));
    assert_eq!(cache.coinbase(), Some(Address::repeat_byte(0xcb)));
    assert_eq!(cache.prevrandao(), Some(B256::repeat_byte(0xab)));
    assert_eq!(cache.block_gas_limit(), Some(30_000_000));
    assert_eq!(cache.timestamp(), Some(1_700_000_000 + 12_345));
    // The RPC pin must advance with the env: a lazy miss after the advance must
    // fetch state at the NEW block, not the previously pinned one (review
    // finding: env said N+1 while the SharedBackend still fetched at N).
    assert_eq!(
        cache.block(),
        alloy_eips::BlockId::number(12_345),
        "advance_block must re-pin RPC fetches to the advanced block"
    );
    Ok(())
}

/// A low-level repin has no header from which to refresh the EVM environment.
/// It must fail closed instead of pairing the new state pin with old header
/// fields, including values that could have been manually overridden.
#[tokio::test]
async fn set_block_clears_every_stale_header_field_on_repin() -> Result<()> {
    let mut cache = setup_cache().await?;
    cache
        .advance_block(&header(100, Some(42)))
        .expect("install complete old header");

    cache.set_block(BlockId::number(101));

    assert_eq!(cache.block(), BlockId::number(101));
    assert_eq!(cache.block_number(), Some(101));
    assert_eq!(cache.basefee(), None);
    assert_eq!(cache.coinbase(), None);
    assert_eq!(cache.prevrandao(), None);
    assert_eq!(cache.block_gas_limit(), None);
    assert_eq!(cache.timestamp(), None);
    Ok(())
}

/// WS-2 / Phase-8 s2: under strict requirements, `advance_block` fails loudly on
/// a header missing a required field instead of silently defaulting it.
#[tokio::test]
async fn advance_block_strict_rejects_incomplete_header() -> Result<()> {
    let mut cache = setup_cache().await?;
    cache.set_block_context_requirements(BlockContextRequirements::strict());

    let err = cache
        .advance_block(&header(200, None))
        .expect_err("strict advance_block must reject a header with no base fee");
    assert!(
        err.to_string().to_lowercase().contains("basefee")
            || err.to_string().to_lowercase().contains("base fee"),
        "the error must name the missing base-fee field, got: {err}"
    );

    // A complete header still refreshes under strict mode.
    cache
        .advance_block(&header(200, Some(9)))
        .expect("strict advance_block over a complete header succeeds");
    assert_eq!(cache.basefee(), Some(9));
    Ok(())
}

// --- Additional Wave 4 coverage --------------------------------------------

use std::sync::Arc;

use alloy_network::{Ethereum, primitives::HeaderResponse as _};
use alloy_provider::RootProvider;
use alloy_provider::network::AnyNetwork;
use alloy_rpc_client::RpcClient;
use alloy_transport::mock::Asserter;
use evm_fork_cache::EvmCacheBuilder;
use evm_fork_cache::reactive::{
    BlockRef, ChainControl, ChainStatus, InputSource, ReactiveConfig, ReactiveContext,
    ReactiveInput, ReactiveInputBatch, ReactiveInputRecord, ReactiveReport, ReactiveRuntime,
};

/// Build a mocked provider (no network access) modelled on `common::setup_cache`.
fn mock_provider() -> Arc<RootProvider<AnyNetwork>> {
    let client = RpcClient::mocked(Asserter::new());
    Arc::new(RootProvider::<AnyNetwork>::new(client))
}

/// A cache built at a concrete block must retain the complete header context
/// fetched for that pin. Otherwise a downstream consumer can pair state from
/// the pinned block with a wall-clock timestamp during simulation.
#[tokio::test]
async fn pinned_builder_captures_timestamp_from_fetched_header() -> Result<()> {
    let asserter = Asserter::new();
    let expected = header(12_345, Some(42));
    let block: alloy_rpc_types_eth::Block =
        alloy_rpc_types_eth::Block::empty(alloy_rpc_types_eth::Header::new(expected.clone()));
    asserter.push_success(&Some(block));
    let provider = Arc::new(RootProvider::<AnyNetwork>::new(RpcClient::mocked(asserter)));

    let cache = EvmCacheBuilder::new(provider)
        .block(BlockId::number(expected.number))
        .chain_id(1)
        .build()
        .await;

    assert_eq!(cache.block_number(), Some(expected.number));
    assert_eq!(cache.timestamp(), Some(expected.timestamp));
    Ok(())
}

/// WS-2: a strict `try_build` over a provider that yields no header must fail
/// loudly at construction rather than silently defaulting the block env.
#[tokio::test]
async fn try_build_strict_fails_when_header_unavailable() {
    let result = EvmCacheBuilder::new(mock_provider())
        .strict_block_context(true)
        .try_build()
        .await;
    // `EvmCache` is not `Debug`, so branch manually rather than `expect_err`.
    let err = match result {
        Ok(_) => panic!("strict try_build over a header-less mock provider must error"),
        Err(err) => err,
    };
    // The mock provider returns no block, so the header fetch fails.
    assert!(
        err.to_string().to_lowercase().contains("fetch failed"),
        "expected a fetch-failure error, got: {err}"
    );
}

/// WS-2: a lenient `try_build` never errors, even when no header is available —
/// preserving the infallible/lenient default construction behavior.
#[tokio::test]
async fn try_build_lenient_succeeds_without_header() -> Result<()> {
    // Explicit lenient.
    let cache = EvmCacheBuilder::new(mock_provider())
        .strict_block_context(false)
        .try_build()
        .await?;
    // A header-less mock provider leaves the block env unset under lenient mode.
    assert_eq!(cache.block_number(), None);

    // Default (no requirements configured) is lenient and also succeeds.
    let _cache = EvmCacheBuilder::new(mock_provider()).try_build().await?;
    Ok(())
}

/// Build the RPC-flavored `HeaderResponse` (`alloy_rpc_types_eth::Header`) that
/// the `Ethereum` reactive runtime ingests, from the in-memory consensus header.
fn rpc_header(number: u64, basefee: Option<u64>) -> alloy_rpc_types_eth::Header {
    alloy_rpc_types_eth::Header::new(header(number, basefee))
}

/// A canonical (`Included`) context for a block header at `number`.
fn included_header_context(header: &alloy_rpc_types_eth::Header) -> ReactiveContext {
    let block = evm_fork_cache::reactive::BlockRef {
        number: header.number(),
        hash: header.hash(),
        parent_hash: Some(header.parent_hash()),
        timestamp: Some(header.timestamp()),
    };
    ReactiveContext {
        chain_id: Some(1),
        source: InputSource::Batch,
        chain_status: ChainStatus::Included {
            block,
            confirmations: 0,
        },
        block: Some(block),
        transaction_index: None,
        log_index: None,
    }
}

/// Phase-8 s2: ingesting a canonical `BlockHeader` drives `advance_block`, so
/// the cache's block env is refreshed from the header without any handler.
#[tokio::test]
async fn reactive_ingest_of_canonical_header_refreshes_block_env() -> Result<()> {
    let mut cache = setup_cache().await?;
    let mut runtime = ReactiveRuntime::<Ethereum>::new(ReactiveConfig::default());

    let header = rpc_header(7_777, Some(123));
    let context = included_header_context(&header);
    let input = ReactiveInput::BlockHeader(header);
    let batch = ReactiveInputBatch::new(vec![ReactiveInputRecord::new(input, context)]);

    let report = runtime.ingest_batch(&mut cache, batch)?;

    // The env was refreshed from the ingested header.
    assert_eq!(cache.block_number(), Some(7_777));
    assert_eq!(cache.basefee(), Some(123));
    assert_eq!(cache.timestamp(), Some(1_700_000_000 + 7_777));
    // Lenient default: no error report surfaced.
    assert!(
        !report
            .reports
            .iter()
            .any(|r| matches!(r.as_ref(), ReactiveReport::Error(_))),
        "a lenient canonical drive must not surface an error report"
    );
    Ok(())
}

#[tokio::test]
async fn post_record_compact_barrier_preserves_full_header_environment() -> Result<()> {
    let mut cache = setup_cache().await?;
    let mut runtime = ReactiveRuntime::<Ethereum>::new(ReactiveConfig::default());
    let header = rpc_header(7_778, Some(124));
    let context = included_header_context(&header);
    let exact_hash = header.hash();
    let compact = BlockRef {
        number: header.number(),
        hash: exact_hash,
        parent_hash: None,
        timestamp: None,
    };

    runtime.ingest_batch(
        &mut cache,
        ReactiveInputBatch::new(vec![ReactiveInputRecord::new(
            ReactiveInput::BlockHeader(header),
            context,
        )])
        .with_chain_controls([ChainControl::Barrier {
            id: b"header-complete".to_vec(),
            block: Some(compact),
        }]),
    )?;

    assert_eq!(cache.block(), BlockId::from((exact_hash, Some(true))));
    assert_eq!(cache.block_number(), Some(7_778));
    assert_eq!(cache.basefee(), Some(124));
    assert_eq!(cache.coinbase(), Some(Address::repeat_byte(0xcb)));
    assert_eq!(cache.prevrandao(), Some(B256::repeat_byte(0xab)));
    assert_eq!(cache.block_gas_limit(), Some(30_000_000));
    assert_eq!(cache.timestamp(), Some(1_700_000_000 + 7_778));
    Ok(())
}

#[tokio::test]
async fn zero_depth_runtime_preserves_full_header_env_for_same_block_compact_records() -> Result<()>
{
    let mut cache = setup_cache().await?;
    let mut runtime = ReactiveRuntime::<Ethereum>::new(ReactiveConfig {
        journal_depth: 0,
        ..ReactiveConfig::default()
    });
    let header = rpc_header(7_779, Some(125));
    let context = included_header_context(&header);
    let block = context.block.expect("canonical block");
    let log = Log {
        inner: PrimitiveLog::new_unchecked(
            Address::repeat_byte(0xdd),
            vec![B256::repeat_byte(0xee)],
            Bytes::new(),
        ),
        block_hash: Some(block.hash),
        block_number: Some(block.number),
        block_timestamp: block.timestamp,
        transaction_hash: Some(B256::repeat_byte(0xef)),
        transaction_index: Some(0),
        log_index: Some(0),
        removed: false,
    };
    let log_context = ReactiveContext {
        transaction_index: Some(0),
        log_index: Some(0),
        ..context.clone()
    };

    runtime.ingest_batch(
        &mut cache,
        ReactiveInputBatch::new(vec![
            ReactiveInputRecord::new(ReactiveInput::BlockHeader(header), context),
            ReactiveInputRecord::new(ReactiveInput::Log(log), log_context),
        ]),
    )?;

    assert_eq!(runtime.last_canonical_block(), Some(block));
    assert_eq!(cache.basefee(), Some(125));
    assert_eq!(cache.coinbase(), Some(Address::repeat_byte(0xcb)));
    assert_eq!(cache.prevrandao(), Some(B256::repeat_byte(0xab)));
    assert_eq!(cache.block_gas_limit(), Some(30_000_000));
    assert_eq!(cache.timestamp(), Some(1_700_000_000 + 7_779));
    Ok(())
}

/// Phase-8 s2: a pending (non-canonical) header must NOT drive `advance_block`.
#[tokio::test]
async fn reactive_ingest_of_pending_header_does_not_refresh_block_env() -> Result<()> {
    let mut cache = setup_cache().await?;
    let mut runtime = ReactiveRuntime::<Ethereum>::new(ReactiveConfig::default());

    let ctx = ReactiveContext {
        chain_id: Some(1),
        source: InputSource::Subscription,
        chain_status: ChainStatus::Pending,
        block: None,
        transaction_index: None,
        log_index: None,
    };
    let input = ReactiveInput::BlockHeader(rpc_header(9_999, Some(55)));
    let batch = ReactiveInputBatch::new(vec![ReactiveInputRecord::new(input, ctx)]);

    runtime.ingest_batch(&mut cache, batch)?;

    // Pending inputs never drive a canonical env refresh.
    assert_eq!(cache.block_number(), None);
    assert_eq!(cache.basefee(), None);
    Ok(())
}

/// WS-2 / Phase-8 s2: under strict requirements, a canonical header missing a
/// required field surfaces a non-fatal `ReactiveReport::Error` (the batch is not
/// aborted).
#[tokio::test]
async fn reactive_strict_drive_surfaces_error_report_for_incomplete_header() -> Result<()> {
    let mut cache = setup_cache().await?;
    cache.set_block_context_requirements(BlockContextRequirements::strict());
    let mut runtime = ReactiveRuntime::<Ethereum>::new(ReactiveConfig::default());

    // No base fee -> strict validation fails during the drive.
    let header = rpc_header(4_242, None);
    let context = included_header_context(&header);
    let input = ReactiveInput::BlockHeader(header);
    let batch = ReactiveInputBatch::new(vec![ReactiveInputRecord::new(input, context)]);

    let report = runtime.ingest_batch(&mut cache, batch)?;

    let error_message = report
        .reports
        .iter()
        .find_map(|r| match r.as_ref() {
            ReactiveReport::Error(e) => Some(e.message.clone()),
            _ => None,
        })
        .expect("strict drive over an incomplete header must surface an error report");
    assert!(
        error_message.to_lowercase().contains("basefee"),
        "the error report must name the missing base-fee field, got: {error_message}"
    );
    Ok(())
}

#[tokio::test]
async fn canonical_block_records_are_sorted_before_advancing_runtime_and_cache_heads() -> Result<()>
{
    let mut cache = setup_cache().await?;
    let mut runtime = ReactiveRuntime::<Ethereum>::new(ReactiveConfig::default());
    let older = rpc_header(50, Some(5));
    let newer = rpc_header(51, Some(6));
    let older_context = included_header_context(&older);
    let newer_context = included_header_context(&newer);

    runtime.ingest_batch(
        &mut cache,
        ReactiveInputBatch::new(vec![
            ReactiveInputRecord::new(ReactiveInput::BlockHeader(newer), newer_context),
            ReactiveInputRecord::new(ReactiveInput::BlockHeader(older), older_context),
        ]),
    )?;

    assert_eq!(
        runtime.last_canonical_block().map(|block| block.number),
        Some(51)
    );
    assert_eq!(cache.block_number(), Some(51));
    assert_eq!(cache.basefee(), Some(6));
    Ok(())
}