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#[derive(Clone, Debug)]
29pub struct CreateFork {
30 pub enable_caching: bool,
32 pub url: String,
34 pub evm_opts: EvmOpts,
36}
37
38#[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 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 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 pub fn number(&self) -> BlockNumber {
98 self.block.header.number()
99 }
100
101 pub fn hash(&self) -> B256 {
103 self.block.header.hash
104 }
105
106 pub const fn context(&self) -> ForkContext {
108 self.context
109 }
110
111 pub fn exact_block_id(&self) -> BlockId {
113 BlockId::from((self.hash(), Some(false)))
114 }
115
116 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 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 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 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}