evm-fork-cache 0.4.0

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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
//! Acceptance tests for cache-owned execution read-set warming and hydration.

use std::sync::{
    Arc,
    atomic::{AtomicUsize, Ordering},
};

use alloy_primitives::{Address, B256, Bytes, U256};
use alloy_provider::{RootProvider, network::AnyNetwork};
use alloy_rpc_client::RpcClient;
use alloy_rpc_types_eth::TransactionRequest;
use alloy_transport::mock::Asserter;
use evm_fork_cache::cache::EvmCache;
use evm_fork_cache::{
    AccountProof, ReadSetHydrationFailure, ReadSetWarmupBatch, ReadSetWarmupCall,
    ReadSetWarmupConfig, ReadSetWarmupError, ReadSetWarmupStrategy, StorageAccessList,
    StorageFetchError,
};
use revm::primitives::hardfork::SpecId;
use revm::state::{AccountInfo, Bytecode};

async fn cache() -> EvmCache {
    let provider = RootProvider::<AnyNetwork>::new(RpcClient::mocked(Asserter::new()));
    EvmCache::new(Arc::new(provider)).await
}

async fn cache_without_fetchers() -> EvmCache {
    let base = cache().await;
    EvmCache::from_backend(
        base.unchecked_backend().clone(),
        base.unchecked_blockchain_db().clone(),
        base.block(),
        base.chain_id(),
        None,
        None,
        SpecId::CANCUN,
    )
}

#[tokio::test(flavor = "multi_thread")]
async fn required_access_list_discovery_fails_when_no_fetcher_is_installed() {
    let mut cache = cache_without_fetchers().await;
    let error = cache
        .prewarm_read_sets(
            ReadSetWarmupBatch {
                known_slots: Vec::new(),
                calls: vec![ReadSetWarmupCall {
                    tx: TransactionRequest::default().to(Address::repeat_byte(0x41)),
                    expected_slots: Some(1),
                    restrict_to: None,
                }],
            },
            ReadSetWarmupConfig {
                strategy: ReadSetWarmupStrategy::AccessList,
                ..Default::default()
            },
        )
        .expect_err("required access-list discovery must not silently skip");

    assert!(matches!(
        error,
        ReadSetWarmupError::AccessListFetcherUnavailable { calls: 1 }
    ));
}

#[tokio::test(flavor = "multi_thread")]
async fn access_list_discovery_rejects_result_count_mismatches() {
    for actual in [0, 2] {
        let mut cache = cache().await;
        cache.set_access_list_fetcher(Arc::new(move |_requests, _block| {
            (0..actual)
                .map(|_| Ok(StorageAccessList::default()))
                .collect()
        }));

        let error = cache
            .prewarm_read_sets(
                ReadSetWarmupBatch {
                    known_slots: Vec::new(),
                    calls: vec![ReadSetWarmupCall {
                        tx: TransactionRequest::default().to(Address::repeat_byte(0x42)),
                        expected_slots: Some(1),
                        restrict_to: None,
                    }],
                },
                ReadSetWarmupConfig {
                    strategy: ReadSetWarmupStrategy::AccessList,
                    ..Default::default()
                },
            )
            .expect_err("fetcher result cardinality is part of the public contract");

        assert!(matches!(
            error,
            ReadSetWarmupError::AccessListResultCountMismatch {
                expected: 1,
                actual: observed,
            } if observed == actual
        ));
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn discovery_contract_errors_do_not_partially_warm_known_slots() {
    let mut cache = cache().await;
    let target = Address::repeat_byte(0x54);
    let slot = U256::from(9);
    let fetches = Arc::new(AtomicUsize::new(0));
    let observed_fetches = Arc::clone(&fetches);
    cache.set_storage_batch_fetcher(Arc::new(move |requests, _block| {
        observed_fetches.fetch_add(1, Ordering::SeqCst);
        requests
            .into_iter()
            .map(|(address, slot)| (address, slot, Ok(U256::from(77))))
            .collect()
    }));
    cache.set_access_list_fetcher(Arc::new(|_requests, _block| Vec::new()));

    let error = cache
        .prewarm_read_sets(
            ReadSetWarmupBatch {
                known_slots: vec![(target, slot)],
                calls: vec![ReadSetWarmupCall {
                    tx: TransactionRequest::default().to(target),
                    expected_slots: Some(1),
                    restrict_to: None,
                }],
            },
            ReadSetWarmupConfig {
                strategy: ReadSetWarmupStrategy::AccessList,
                ..Default::default()
            },
        )
        .expect_err("a malformed discovery batch must fail before cache mutation");

    assert!(matches!(
        error,
        ReadSetWarmupError::AccessListResultCountMismatch {
            expected: 1,
            actual: 0
        }
    ));
    assert_eq!(fetches.load(Ordering::SeqCst), 0);
    assert_eq!(cache.cached_storage_value(target, slot), None);
}

#[tokio::test(flavor = "multi_thread")]
async fn automatic_discovery_saturates_extreme_slot_hints() {
    let mut cache = cache().await;
    cache.set_access_list_fetcher(Arc::new(|requests, _block| {
        requests
            .into_iter()
            .map(|_| Ok(StorageAccessList::default()))
            .collect()
    }));

    let report = cache
        .prewarm_read_sets(
            ReadSetWarmupBatch {
                known_slots: Vec::new(),
                calls: vec![
                    ReadSetWarmupCall {
                        tx: TransactionRequest::default().to(Address::repeat_byte(0x43)),
                        expected_slots: Some(usize::MAX),
                        restrict_to: None,
                    },
                    ReadSetWarmupCall {
                        tx: TransactionRequest::default().to(Address::repeat_byte(0x44)),
                        expected_slots: Some(1),
                        restrict_to: None,
                    },
                ],
            },
            ReadSetWarmupConfig::default(),
        )
        .expect("automatic access-list discovery");

    assert!(report.used_access_lists);
    assert_eq!(report.access_list_successes, 2);
}

#[tokio::test(flavor = "multi_thread")]
async fn exact_hydration_reports_a_typed_missing_proof_fetcher() {
    let mut cache = cache_without_fetchers().await;
    let target = Address::repeat_byte(0x45);
    let required = StorageAccessList {
        accounts: [target].into_iter().collect(),
        ..Default::default()
    };

    let report = cache.hydrate_read_set(&required);

    assert!(!report.is_complete());
    assert!(matches!(
        report.failures.as_slice(),
        [ReadSetHydrationFailure::ProofFetcherUnavailable { address }] if *address == target
    ));
}

#[tokio::test(flavor = "multi_thread")]
async fn exact_hydration_rejects_duplicate_and_unexpected_proof_results() {
    let mut cache = cache().await;
    let target = Address::repeat_byte(0x46);
    let unexpected = Address::repeat_byte(0x47);
    cache.set_account_proof_fetcher(Arc::new(move |_requests, _block| {
        let proof = AccountProof {
            storage_hash: B256::ZERO,
            balance: U256::ZERO,
            nonce: 0,
            code_hash: B256::ZERO,
            slots: Vec::new(),
        };
        vec![
            (target, Ok(proof.clone())),
            (target, Ok(proof.clone())),
            (unexpected, Ok(proof)),
        ]
    }));
    let required = StorageAccessList {
        accounts: [target].into_iter().collect(),
        ..Default::default()
    };

    let report = cache.hydrate_read_set(&required);

    assert!(!report.is_complete());
    assert!(report.failures.iter().any(|failure| matches!(
        failure,
        ReadSetHydrationFailure::ProofResultDuplicate { address } if *address == target
    )));
    assert!(report.failures.iter().any(|failure| matches!(
        failure,
        ReadSetHydrationFailure::ProofResultUnexpected { address } if *address == unexpected
    )));
    assert_eq!(report.accounts_refreshed, 0);
    assert!(report.missing_after.accounts.contains(&target));
}

#[tokio::test(flavor = "multi_thread")]
async fn exact_hydration_rejects_duplicate_and_unexpected_proof_slots() {
    let mut cache = cache().await;
    let target = Address::repeat_byte(0x55);
    let requested = U256::from(1);
    let unexpected = U256::from(2);
    cache.set_account_proof_fetcher(Arc::new(move |_requests, _block| {
        vec![(
            target,
            Ok(AccountProof {
                storage_hash: B256::ZERO,
                balance: U256::ZERO,
                nonce: 0,
                code_hash: B256::ZERO,
                slots: vec![
                    (requested, U256::from(10)),
                    (requested, U256::from(11)),
                    (unexpected, U256::from(12)),
                ],
            }),
        )]
    }));
    let required = StorageAccessList {
        accounts: [target].into_iter().collect(),
        slots: [(target, requested)].into_iter().collect(),
        ..Default::default()
    };

    let report = cache.hydrate_read_set(&required);

    assert!(!report.is_complete());
    assert!(report.failures.iter().any(|failure| matches!(
        failure,
        ReadSetHydrationFailure::StorageSlotDuplicate { address, slot }
            if *address == target && *slot == requested
    )));
    assert!(report.failures.iter().any(|failure| matches!(
        failure,
        ReadSetHydrationFailure::StorageSlotUnexpected { address, slot }
            if *address == target && *slot == unexpected
    )));
    assert_eq!(cache.cached_storage_value(target, requested), None);
    assert!(report.missing_after.slots.contains(&(target, requested)));
}

#[tokio::test(flavor = "multi_thread")]
async fn policy_skips_calls_only_when_remote_discovery_is_not_selected() {
    let target = Address::repeat_byte(0x48);
    for config in [
        ReadSetWarmupConfig {
            strategy: ReadSetWarmupStrategy::LocalOnly,
            ..Default::default()
        },
        ReadSetWarmupConfig {
            strategy: ReadSetWarmupStrategy::Auto,
            ..Default::default()
        },
    ] {
        let mut cache = cache_without_fetchers().await;
        let report = cache
            .prewarm_read_sets(
                ReadSetWarmupBatch {
                    known_slots: Vec::new(),
                    calls: vec![ReadSetWarmupCall {
                        tx: TransactionRequest::default().to(target),
                        expected_slots: Some(1),
                        restrict_to: None,
                    }],
                },
                config,
            )
            .expect("policy did not select remote discovery");

        assert!(!report.used_access_lists);
        assert_eq!(report.skipped_calls, 1);
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn access_list_discovery_preserves_per_call_failures() {
    let mut cache = cache().await;
    cache.set_access_list_fetcher(Arc::new(|_requests, _block| {
        vec![Err(evm_fork_cache::AccessListError::query(
            "eth_createAccessList",
            "provider rejected the call",
        ))]
    }));

    let report = cache
        .prewarm_read_sets(
            ReadSetWarmupBatch {
                known_slots: Vec::new(),
                calls: vec![ReadSetWarmupCall {
                    tx: TransactionRequest::default().to(Address::repeat_byte(0x49)),
                    expected_slots: None,
                    restrict_to: None,
                }],
            },
            ReadSetWarmupConfig {
                strategy: ReadSetWarmupStrategy::AccessList,
                ..Default::default()
            },
        )
        .expect("the batch contract was valid");

    assert!(report.used_access_lists);
    assert_eq!(report.access_list_successes, 0);
    assert_eq!(report.access_list_failures.len(), 1);
    assert_eq!(report.access_list_failures[0].0, 0);
}

#[tokio::test(flavor = "multi_thread")]
async fn exact_hydration_preserves_typed_partial_failure_causes() {
    let mut cache = cache().await;
    let omitted = Address::repeat_byte(0x4a);
    let provider_failed = Address::repeat_byte(0x4b);
    let runtime_missing = Address::repeat_byte(0x4c);
    let slot_missing = Address::repeat_byte(0x4d);
    let slot = U256::from(9);
    let deployed_hash = B256::repeat_byte(0x4e);
    cache.set_account_proof_fetcher(Arc::new(move |_requests, _block| {
        vec![
            (
                provider_failed,
                Err(StorageFetchError::custom("archive unavailable")),
            ),
            (
                runtime_missing,
                Ok(AccountProof {
                    storage_hash: B256::ZERO,
                    balance: U256::ZERO,
                    nonce: 1,
                    code_hash: deployed_hash,
                    slots: Vec::new(),
                }),
            ),
            (
                slot_missing,
                Ok(AccountProof {
                    storage_hash: B256::ZERO,
                    balance: U256::ZERO,
                    nonce: 0,
                    code_hash: B256::ZERO,
                    slots: Vec::new(),
                }),
            ),
        ]
    }));
    let required = StorageAccessList {
        accounts: [omitted, provider_failed, runtime_missing, slot_missing]
            .into_iter()
            .collect(),
        slots: [(slot_missing, slot)].into_iter().collect(),
        ..Default::default()
    };

    let report = cache.hydrate_read_set(&required);

    assert!(report.failures.iter().any(|failure| matches!(
        failure,
        ReadSetHydrationFailure::ProofResultMissing { address } if *address == omitted
    )));
    assert!(report.failures.iter().any(|failure| matches!(
        failure,
        ReadSetHydrationFailure::ProofFetch { address, source }
            if *address == provider_failed && source.to_string().contains("archive unavailable")
    )));
    assert!(report.failures.iter().any(|failure| matches!(
        failure,
        ReadSetHydrationFailure::RuntimeCodeUnavailable { address, code_hash }
            if *address == runtime_missing && *code_hash == deployed_hash
    )));
    assert!(report.failures.iter().any(|failure| matches!(
        failure,
        ReadSetHydrationFailure::StorageSlotMissing { address, slot: missing }
            if *address == slot_missing && *missing == slot
    )));
    assert!(!report.is_complete());
}

#[tokio::test(flavor = "multi_thread")]
async fn block_hash_dependencies_are_validated_from_canonical_cache_residency() {
    let mut cache = cache().await;
    let resident_number = 100_u64;
    let missing_number = 101_u64;
    cache
        .db_mut()
        .cache
        .block_hashes
        .insert(U256::from(resident_number), B256::repeat_byte(0x4f));

    let resident = cache.hydrate_read_set(&StorageAccessList {
        block_numbers: [resident_number].into_iter().collect(),
        ..Default::default()
    });
    let missing = cache.hydrate_read_set(&StorageAccessList {
        block_numbers: [missing_number].into_iter().collect(),
        ..Default::default()
    });

    assert!(resident.is_complete(), "{resident:?}");
    assert!(missing.failures.is_empty());
    assert_eq!(
        missing.missing_after.block_numbers,
        [missing_number].into_iter().collect()
    );
    assert!(!missing.is_complete());
}

#[tokio::test(flavor = "multi_thread")]
async fn cache_owned_warmup_discovers_filters_and_loads_slots() {
    let mut cache = cache().await;
    let target = Address::repeat_byte(0x51);
    let unrelated = Address::repeat_byte(0x52);
    let slot = U256::from(7);
    cache.set_access_list_fetcher(Arc::new(move |requests, _block| {
        assert_eq!(requests.len(), 1);
        let mut access = StorageAccessList::default();
        access.accounts.extend([target, unrelated]);
        access.slots.extend([(target, slot), (unrelated, slot)]);
        vec![Ok(access)]
    }));
    cache.set_storage_batch_fetcher(Arc::new(move |requests, _block| {
        assert_eq!(requests, vec![(target, slot)]);
        vec![(target, slot, Ok(U256::from(99)))]
    }));

    let report = cache
        .prewarm_read_sets(
            ReadSetWarmupBatch {
                known_slots: Vec::new(),
                calls: vec![ReadSetWarmupCall {
                    tx: TransactionRequest::default().to(target),
                    expected_slots: Some(32),
                    restrict_to: Some(vec![target]),
                }],
            },
            ReadSetWarmupConfig {
                strategy: ReadSetWarmupStrategy::AccessList,
                ..Default::default()
            },
        )
        .expect("access-list warmup");

    assert!(report.used_access_lists);
    assert_eq!(report.access_list_successes, 1);
    assert_eq!(
        report.discovered_access.accounts,
        [target].into_iter().collect()
    );
    assert_eq!(
        report.discovered_access.slots,
        [(target, slot)].into_iter().collect()
    );
    assert_eq!(report.discovered.loaded, 1);
    assert_eq!(
        cache.cached_storage_value(target, slot),
        Some(U256::from(99))
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn provider_backed_cache_installs_access_list_discovery() {
    assert!(cache().await.access_list_fetcher().is_some());
}

#[tokio::test(flavor = "multi_thread")]
async fn exact_read_set_hydration_refreshes_accounts_code_and_storage_together() {
    let mut cache = cache().await;
    let target = Address::repeat_byte(0x61);
    let slot = U256::from(8);
    let code = Bytecode::new_raw(Bytes::from_static(&[0x00]));
    let code_hash = code.hash_slow();
    cache.db_mut().insert_account_info(
        target,
        AccountInfo {
            balance: U256::from(1),
            nonce: 2,
            code_hash,
            code: Some(code),
            account_id: None,
        },
    );
    cache
        .insert_storage_slot(target, slot, U256::from(3))
        .expect("seed storage");
    cache.set_account_proof_fetcher(Arc::new(move |requests, _block| {
        assert_eq!(requests, vec![(target, vec![slot])]);
        vec![(
            target,
            Ok(AccountProof {
                storage_hash: B256::repeat_byte(0x62),
                balance: U256::from(10),
                nonce: 11,
                code_hash,
                slots: vec![(slot, U256::from(12))],
            }),
        )]
    }));
    let required = StorageAccessList {
        accounts: [target].into_iter().collect(),
        code_hashes: [code_hash].into_iter().collect(),
        slots: [(target, slot)].into_iter().collect(),
        ..Default::default()
    };

    let report = cache.hydrate_read_set(&required);

    assert!(report.is_complete(), "{report:?}");
    assert_eq!(report.accounts_refreshed, 1);
    assert_eq!(report.slots_refreshed, 1);
    assert_eq!(
        cache.cached_storage_value(target, slot),
        Some(U256::from(12))
    );
    assert!(cache.snapshot().missing_read_set(&required).is_empty());
}

#[tokio::test(flavor = "multi_thread")]
async fn exact_read_set_hydration_rejects_code_layout_changes() {
    let mut cache = cache().await;
    let target = Address::repeat_byte(0x71);
    let code = Bytecode::new_raw(Bytes::from_static(&[0x00]));
    let code_hash = code.hash_slow();
    cache.db_mut().insert_account_info(
        target,
        AccountInfo {
            code_hash,
            code: Some(code),
            ..Default::default()
        },
    );
    let changed = B256::repeat_byte(0x72);
    cache.set_account_proof_fetcher(Arc::new(move |_, _| {
        vec![(
            target,
            Ok(AccountProof {
                storage_hash: B256::ZERO,
                balance: U256::ZERO,
                nonce: 1,
                code_hash: changed,
                slots: Vec::new(),
            }),
        )]
    }));
    let required = StorageAccessList {
        accounts: [target].into_iter().collect(),
        code_hashes: [code_hash].into_iter().collect(),
        ..Default::default()
    };

    let report = cache.hydrate_read_set(&required);

    assert!(!report.is_complete());
    assert_eq!(report.code_changes, vec![(target, code_hash, changed)]);
}