Skip to main content

foundry_evm_core/fork/
mod.rs

1use super::opts::{EvmOpts, ForkContext};
2use alloy_consensus::BlockHeader;
3use alloy_eips::{BlockId, BlockNumHash};
4use alloy_network::{AnyNetwork, AnyRpcBlock, Network};
5use alloy_primitives::{B256, BlockNumber, keccak256};
6use alloy_provider::{Provider, RootProvider};
7use alloy_rpc_client::RpcClient;
8use eyre::OptionExt;
9use foundry_fork_db::StateBlockId;
10use std::{
11    fmt,
12    hash::{Hash, Hasher},
13    sync::Arc,
14};
15
16mod block_env;
17pub use block_env::{BlobExcessGasAndPrice, BlockEnv};
18
19mod multi;
20pub use multi::{ForkId, ForkResult, MultiFork, MultiForkHandler};
21
22mod bal;
23pub use bal::{cache_bal, validate_bal};
24
25pub(crate) mod prefetch;
26
27/// Represents a _fork_ of a remote chain whose data is available only via the `url` endpoint.
28#[derive(Clone, Debug)]
29pub struct CreateFork {
30    /// Whether to enable rpc storage caching for this fork
31    pub enable_caching: bool,
32    /// The URL to a node for fetching remote state
33    pub url: String,
34    /// All env settings as configured by the user
35    pub evm_opts: EvmOpts,
36}
37
38/// A prepared remote fork. The RPC client and block are shared by preflight and execution.
39///
40/// The configured selector remains separate from the observed block. Clones share the provider
41/// and header; changing the requested source or rolling a fork prepares a new snapshot. The
42/// optional number-based state mode retains this anchor, but state reads may follow a replacement
43/// block after a reorganization.
44#[derive(Clone)]
45pub struct Fork {
46    source_id: B256,
47    client: RpcClient,
48    selector: Option<BlockNumber>,
49    pub(crate) block: Arc<AnyRpcBlock>,
50    context: ForkContext,
51    /// Whether state reads use the RPC block number instead of the exact hash.
52    pub(crate) state_by_number: bool,
53}
54
55impl Fork {
56    pub(crate) fn new(
57        opts: &EvmOpts,
58        client: RpcClient,
59        block: AnyRpcBlock,
60        mut context: ForkContext,
61    ) -> Self {
62        debug_assert_eq!(block.header.number(), context.block_number);
63        context.network_profile = context.network_profile.canonical_execution_profile();
64        Self {
65            source_id: source_id(
66                opts.fork_url.as_deref().unwrap_or_default(),
67                opts.fork_source_headers(),
68                opts.rpc_jwt.as_deref(),
69            ),
70            client,
71            selector: opts.fork_block_number,
72            block: Arc::new(block),
73            context,
74            state_by_number: opts.fork_state_by_number,
75        }
76    }
77
78    /// Whether this backend's fork was created from the requested source, selector, and state mode.
79    pub fn matches_request(&self, opts: &EvmOpts) -> bool {
80        opts.fork_url.as_deref().is_some_and(|url| {
81            self.selector == opts.fork_block_number
82                && self.state_by_number == opts.fork_state_by_number
83                && self.matches_source(url, opts.fork_source_headers(), opts.rpc_jwt.as_deref())
84        })
85    }
86
87    pub(crate) fn matches_source(
88        &self,
89        url: &str,
90        headers: Option<&[String]>,
91        jwt: Option<&str>,
92    ) -> bool {
93        self.source_id == source_id(url, headers, jwt)
94    }
95
96    /// Returns the RPC block number, which may differ from the EVM-visible number on L2s.
97    pub fn number(&self) -> BlockNumber {
98        self.block.header.number()
99    }
100
101    /// Returns the fork block hash.
102    pub fn hash(&self) -> B256 {
103        self.block.header.hash
104    }
105
106    /// Returns the endpoint and execution context observed when the fork was prepared.
107    pub const fn context(&self) -> ForkContext {
108        self.context
109    }
110
111    /// Returns an exact state selector that remains valid for a retained noncanonical block.
112    pub fn exact_block_id(&self) -> BlockId {
113        BlockId::from((self.hash(), Some(false)))
114    }
115
116    /// Returns the state selector for preflight RPC reads, honoring the RPC compatibility opt-in.
117    ///
118    /// The hash selector leaves `requireCanonical` unset, which EIP-1898 defines as `false`, so it
119    /// pins the same block as [`Self::exact_block_id`] and serializes as `{"blockHash": "0x…"}`.
120    pub(crate) fn state_block_id(&self) -> StateBlockId {
121        StateBlockId(if self.state_by_number {
122            BlockId::number(self.number())
123        } else {
124            BlockId::hash(self.hash())
125        })
126    }
127
128    pub(crate) fn block(&self) -> BlockNumHash {
129        BlockNumHash::new(self.number(), self.hash())
130    }
131
132    /// Reuses the configured RPC client with the response types required by the caller.
133    pub(crate) fn provider<N: Network>(&self) -> RootProvider<N> {
134        RootProvider::new(self.client.clone())
135    }
136
137    pub(crate) async fn at_block(&self, block: BlockNumHash) -> eyre::Result<Self> {
138        let provider = self.provider::<AnyNetwork>();
139        let response = provider
140            .get_block_by_hash(block.hash)
141            .await?
142            .ok_or_eyre("exact fork block is unavailable")?;
143        eyre::ensure!(
144            response.header.number() == block.number && response.header.hash == block.hash,
145            "exact fork block does not match the requested number and hash"
146        );
147        let mut fork = self.clone();
148        fork.selector = Some(block.number);
149        fork.block = Arc::new(response);
150        fork.state_by_number = false;
151        fork.context.block_number = block.number;
152        Ok(fork)
153    }
154
155    pub(crate) const fn source_id(&self) -> B256 {
156        self.source_id
157    }
158
159    /// Returns the stable, redacted identity used by persisted execution caches.
160    pub fn fingerprint(&self) -> B256 {
161        let mut encoded = serde_json::to_vec(&(
162            "foundry-resolved-fork-v1",
163            self.source_id,
164            self.block(),
165            self.context,
166        ))
167        .expect("fork identity is serializable");
168        // Distinguish execution policies without invalidating existing hash-based disk caches.
169        if self.state_by_number {
170            encoded.extend_from_slice(b"state-by-number");
171        }
172        keccak256(encoded)
173    }
174}
175
176impl PartialEq for Fork {
177    fn eq(&self, other: &Self) -> bool {
178        (self.source_id, self.selector, self.block(), self.context, self.state_by_number)
179            == (
180                other.source_id,
181                other.selector,
182                other.block(),
183                other.context,
184                other.state_by_number,
185            )
186    }
187}
188
189impl Eq for Fork {}
190
191impl Hash for Fork {
192    fn hash<H: Hasher>(&self, state: &mut H) {
193        (self.source_id, self.selector, self.block(), self.context, self.state_by_number)
194            .hash(state);
195    }
196}
197
198impl fmt::Debug for Fork {
199    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
200        let mut debug = f.debug_struct("Fork");
201        debug.field("source", &"<redacted>");
202        if let Some(number) = self.selector {
203            debug.field("selector", &number);
204        } else {
205            debug.field("selector", &"latest");
206        }
207        debug.field("block", &self.block()).finish()
208    }
209}
210
211fn source_id(url: &str, headers: Option<&[String]>, jwt: Option<&str>) -> B256 {
212    let mut encoded = Vec::from(b"foundry-resolved-fork-source-v1".as_slice());
213    encode_source_part(&mut encoded, url.as_bytes());
214    let headers = headers.unwrap_or_default();
215    encoded.extend_from_slice(
216        &u64::try_from(headers.len()).expect("fork header count exceeds u64").to_be_bytes(),
217    );
218    for header in headers {
219        encode_source_part(&mut encoded, header.as_bytes());
220    }
221    if let Some(jwt) = jwt {
222        encoded.push(1);
223        encode_source_part(&mut encoded, jwt.as_bytes());
224    } else {
225        encoded.push(0);
226    }
227    keccak256(encoded)
228}
229
230fn encode_source_part(encoded: &mut Vec<u8>, part: &[u8]) {
231    encoded.extend_from_slice(
232        &u64::try_from(part.len()).expect("source identity part length exceeds u64").to_be_bytes(),
233    );
234    encoded.extend_from_slice(part);
235}
236
237#[cfg(test)]
238mod tests {
239    use super::*;
240    use alloy_network::{AnyHeader, AnyRpcHeader};
241    use alloy_rpc_types::Block;
242    use foundry_evm_networks::{NetworkConfigs, NetworkVariant};
243    use serde_json::json;
244    use std::collections::HashSet;
245
246    impl Fork {
247        pub(crate) fn test(
248            url: &str,
249            headers: Option<&[String]>,
250            jwt: Option<&str>,
251            selector: Option<BlockNumber>,
252            block: BlockNumHash,
253            context: ForkContext,
254        ) -> Self {
255            let opts = EvmOpts {
256                fork_url: Some(url.to_string()),
257                fork_headers: headers.map(<[String]>::to_vec),
258                rpc_jwt: jwt.map(str::to_string),
259                fork_block_number: selector,
260                ..Default::default()
261            };
262            let header = AnyHeader { number: block.number, ..Default::default() };
263            let block = AnyRpcBlock::new(
264                Block::new(AnyRpcHeader::from_sealed(header.seal(block.hash)), Default::default())
265                    .into(),
266            );
267            Self::new(&opts, opts.fork_rpc_client(url).unwrap(), block, context)
268        }
269    }
270
271    fn context(block_number: BlockNumber) -> ForkContext {
272        ForkContext {
273            execution_chain_id: 1,
274            source_chain_id: 1,
275            network: NetworkVariant::Ethereum,
276            network_profile: NetworkConfigs::default(),
277            block_number,
278            hardfork: None,
279            instance_id: None,
280            source_fork_block_number: None,
281            source_fork_block_hash: None,
282        }
283    }
284
285    #[test]
286    fn exact_block_id_serializes_as_eip_1898_object() {
287        let hash = B256::with_last_byte(1);
288        let fork = Fork::test(
289            "http://localhost:8545",
290            None,
291            None,
292            None,
293            BlockNumHash::new(1, hash),
294            context(1),
295        );
296
297        assert_eq!(
298            serde_json::to_value(fork.exact_block_id()).unwrap(),
299            json!({
300                "blockHash": hash,
301                "requireCanonical": false,
302            })
303        );
304    }
305
306    #[test]
307    fn state_block_id_serializes_as_hash_object_without_canonical_flag() {
308        let hash = B256::with_last_byte(1);
309        let fork = Fork::test(
310            "http://localhost:8545",
311            None,
312            None,
313            None,
314            BlockNumHash::new(1, hash),
315            context(1),
316        );
317
318        assert_eq!(
319            serde_json::to_value(fork.state_block_id()).unwrap(),
320            json!({ "blockHash": hash })
321        );
322    }
323
324    #[test]
325    fn fork_state_by_number_preserves_anchor_and_separates_identity() {
326        let block = BlockNumHash::new(42, B256::with_last_byte(1));
327        let exact = Fork::test("http://localhost:8545", None, None, None, block, context(42));
328        let mut numbered = exact.clone();
329        numbered.state_by_number = true;
330        assert_eq!(serde_json::to_value(numbered.state_block_id()).unwrap(), json!("0x2a"));
331        assert_eq!(exact.state_block_id().0, BlockId::hash(block.hash));
332        assert_eq!(numbered.exact_block_id(), exact.exact_block_id());
333        assert_ne!(numbered, exact);
334        assert_eq!(numbered.source_id(), exact.source_id());
335        assert_ne!(numbered.fingerprint(), exact.fingerprint());
336    }
337
338    #[test]
339    fn endpoint_identity_participates_in_equality_and_hashing() {
340        let block = BlockNumHash::new(1, B256::with_last_byte(1));
341        let first = Fork::test("http://localhost:8545", None, None, None, block, context(1));
342        for changed_context in [
343            ForkContext { instance_id: Some(B256::with_last_byte(2)), ..context(1) },
344            ForkContext { network_profile: NetworkConfigs::with_celo(), ..context(1) },
345            ForkContext {
346                network: NetworkVariant::Tempo,
347                network_profile: NetworkConfigs::with_tempo(),
348                ..context(1)
349            },
350        ] {
351            let second =
352                Fork::test("http://localhost:8545", None, None, None, block, changed_context);
353
354            assert_ne!(first, second);
355            assert_ne!(first.fingerprint(), second.fingerprint());
356            assert_eq!(HashSet::from([first.clone(), second]).len(), 2);
357        }
358    }
359
360    #[test]
361    fn configured_source_identity_is_unambiguous() {
362        let block = BlockNumHash::new(1, B256::with_last_byte(1));
363        let context = context(1);
364        let plain = Fork::test("http://localhost:8545", None, None, None, block, context);
365        let header = Fork::test(
366            "http://localhost:8545",
367            Some(&["secret".to_string()]),
368            None,
369            None,
370            block,
371            context,
372        );
373        let jwt = Fork::test("http://localhost:8545", None, Some("secret"), None, block, context);
374
375        assert_ne!(plain.source_id, header.source_id);
376        assert_ne!(plain.source_id, jwt.source_id);
377        assert_ne!(header.source_id, jwt.source_id);
378        assert_ne!(plain.fingerprint(), header.fingerprint());
379        assert_ne!(plain.fingerprint(), jwt.fingerprint());
380    }
381
382    #[test]
383    fn resolved_fork_canonicalizes_equivalent_ethereum_profiles() {
384        let url = "http://localhost:8545";
385        let block = BlockNumHash::new(1, B256::with_last_byte(1));
386        let implicit = Fork::test(url, None, None, Some(1), block, context(1));
387        let explicit = Fork::test(
388            url,
389            None,
390            None,
391            Some(1),
392            block,
393            ForkContext { network_profile: NetworkConfigs::with_ethereum(), ..context(1) },
394        );
395
396        assert_eq!(implicit.context(), explicit.context());
397        assert_eq!(implicit.fingerprint(), explicit.fingerprint());
398        assert_eq!(HashSet::from([implicit, explicit]).len(), 1);
399    }
400}