Skip to main content

reth_rpc_e2e_tests/
rpc_compat.rs

1//! RPC compatibility test actions for testing RPC methods against execution-apis test data.
2
3use alloy_rpc_types_engine::ForkchoiceUpdated;
4use eyre::{eyre, Result};
5use futures_util::future::BoxFuture;
6use reth_e2e_test_utils::testsuite::{
7    actions::{expect_fcu_valid, Action},
8    BlockInfo, Environment,
9};
10use reth_node_api::EngineTypes;
11use serde_json::Value;
12use std::path::Path;
13use tracing::{debug, info};
14
15/// Test case from execution-apis .io file format
16#[derive(Debug, Clone)]
17pub struct RpcTestCase {
18    /// The test name (filename without .io extension)
19    pub name: String,
20    /// Request to send (as JSON value)
21    pub request: Value,
22    /// Expected response (as JSON value)
23    pub expected_response: Value,
24    /// Whether this test is spec-only
25    pub spec_only: bool,
26}
27
28/// Action that runs RPC compatibility tests from execution-apis test data
29#[derive(Debug)]
30pub struct RunRpcCompatTests {
31    /// RPC methods to test (e.g. `eth_getLogs`)
32    pub methods: Vec<String>,
33    /// Path to the execution-apis tests directory
34    pub test_data_path: String,
35    /// Whether to stop on first failure
36    pub fail_fast: bool,
37}
38
39impl RunRpcCompatTests {
40    /// Create a new RPC compatibility test runner
41    pub fn new(methods: Vec<String>, test_data_path: impl Into<String>) -> Self {
42        Self { methods, test_data_path: test_data_path.into(), fail_fast: false }
43    }
44
45    /// Set whether to stop on first failure
46    pub const fn with_fail_fast(mut self, fail_fast: bool) -> Self {
47        self.fail_fast = fail_fast;
48        self
49    }
50
51    /// Parse a .io test file
52    fn parse_io_file(content: &str) -> Result<RpcTestCase> {
53        let mut lines = content.lines();
54        let mut spec_only = false;
55        let mut request_line = None;
56        let mut response_line = None;
57
58        // Skip comments and look for spec_only marker
59        for line in lines.by_ref() {
60            let line = line.trim();
61            if line.starts_with("//") {
62                if line.contains("speconly:") {
63                    spec_only = true;
64                }
65            } else if let Some(stripped) = line.strip_prefix(">>") {
66                request_line = Some(stripped.trim());
67                break;
68            }
69        }
70
71        // Look for response
72        for line in lines {
73            let line = line.trim();
74            if let Some(stripped) = line.strip_prefix("<<") {
75                response_line = Some(stripped.trim());
76                break;
77            }
78        }
79
80        let request_str =
81            request_line.ok_or_else(|| eyre!("No request found in test file (>> marker)"))?;
82        let response_str =
83            response_line.ok_or_else(|| eyre!("No response found in test file (<< marker)"))?;
84
85        // Parse request
86        let request: Value = serde_json::from_str(request_str)
87            .map_err(|e| eyre!("Failed to parse request: {}", e))?;
88
89        // Parse response
90        let expected_response: Value = serde_json::from_str(response_str)
91            .map_err(|e| eyre!("Failed to parse response: {}", e))?;
92
93        Ok(RpcTestCase { name: String::new(), request, expected_response, spec_only })
94    }
95
96    /// Compare JSON values with special handling for numbers and errors
97    /// Uses iterative approach to avoid stack overflow with deeply nested structures
98    fn compare_json_values(actual: &Value, expected: &Value, path: &str) -> Result<()> {
99        // Stack to hold work items: (actual, expected, path)
100        let mut work_stack = vec![(actual, expected, path.to_string())];
101
102        while let Some((actual, expected, current_path)) = work_stack.pop() {
103            match (actual, expected) {
104                // Number comparison: handle different representations
105                (Value::Number(a), Value::Number(b)) => {
106                    let a_f64 = a.as_f64().ok_or_else(|| eyre!("Invalid number"))?;
107                    let b_f64 = b.as_f64().ok_or_else(|| eyre!("Invalid number"))?;
108                    // Use a reasonable epsilon for floating point comparison
109                    const EPSILON: f64 = 1e-10;
110                    if (a_f64 - b_f64).abs() > EPSILON {
111                        return Err(eyre!("Number mismatch at {}: {} != {}", current_path, a, b));
112                    }
113                }
114                // Array comparison
115                (Value::Array(a), Value::Array(b)) => {
116                    if a.len() != b.len() {
117                        return Err(eyre!(
118                            "Array length mismatch at {}: {} != {}",
119                            current_path,
120                            a.len(),
121                            b.len()
122                        ));
123                    }
124                    // Add array elements to work stack in reverse order
125                    // so they are processed in correct order
126                    for (i, (av, bv)) in a.iter().zip(b.iter()).enumerate().rev() {
127                        work_stack.push((av, bv, format!("{current_path}[{i}]")));
128                    }
129                }
130                // Object comparison
131                (Value::Object(a), Value::Object(b)) => {
132                    // Check all keys in expected are present in actual
133                    for (key, expected_val) in b {
134                        if let Some(actual_val) = a.get(key) {
135                            work_stack.push((
136                                actual_val,
137                                expected_val,
138                                format!("{current_path}.{key}"),
139                            ));
140                        } else {
141                            return Err(eyre!("Missing key at {}.{}", current_path, key));
142                        }
143                    }
144                }
145                // Direct value comparison
146                (a, b) => {
147                    if a != b {
148                        return Err(eyre!("Value mismatch at {}: {:?} != {:?}", current_path, a, b));
149                    }
150                }
151            }
152        }
153        Ok(())
154    }
155
156    /// Execute a single test case
157    async fn execute_test_case<Engine: EngineTypes>(
158        &self,
159        test_case: &RpcTestCase,
160        env: &Environment<Engine>,
161    ) -> Result<()> {
162        let node_client = &env.node_clients[env.active_node_idx];
163
164        // Extract method and params from request
165        let method = test_case
166            .request
167            .get("method")
168            .and_then(|v| v.as_str())
169            .ok_or_else(|| eyre!("Request missing method field"))?;
170
171        let params = test_case.request.get("params").cloned().unwrap_or(Value::Array(vec![]));
172
173        // Non-array params are wrapped in an array, and RPC errors become error responses below.
174        let params = match params {
175            Value::Array(_) => params,
176            _ => Value::Array(vec![params]),
177        };
178        let response_result = node_client.rpc.request::<_, Value>(method.to_owned(), params).await;
179
180        // Build actual response object to match execution-apis format
181        let actual_response = match response_result {
182            Ok(response) => {
183                serde_json::json!({
184                    "jsonrpc": "2.0",
185                    "id": test_case.request.get("id").cloned().unwrap_or(Value::Null),
186                    "result": response
187                })
188            }
189            Err(err) => {
190                let error =
191                    err.as_error_resp().ok_or_else(|| eyre!("RPC request failed: {err}"))?;
192                serde_json::json!({
193                    "jsonrpc": "2.0",
194                    "id": test_case.request.get("id").cloned().unwrap_or(Value::Null),
195                    "error": error
196                })
197            }
198        };
199
200        // Compare responses
201        let expected_result = test_case.expected_response.get("result");
202        let expected_error = test_case.expected_response.get("error");
203        let actual_result = actual_response.get("result");
204        let actual_error = actual_response.get("error");
205
206        match (expected_result, expected_error) {
207            (Some(expected), None) => {
208                // Expected success response
209                if let Some(actual) = actual_result {
210                    Self::compare_json_values(actual, expected, "result")?;
211                } else if let Some(error) = actual_error {
212                    return Err(eyre!("Expected success response but got error: {}", error));
213                } else {
214                    return Err(eyre!("Expected success response but got neither result nor error"));
215                }
216            }
217            (None, Some(expected)) => {
218                let actual =
219                    actual_error.ok_or_else(|| eyre!("Expected error response but got success"))?;
220                // Hive ignores error message wording, but the error code must match.
221                Self::compare_json_values(&actual["code"], &expected["code"], "error.code")?;
222                debug!("Both responses are errors (expected behavior)");
223            }
224            _ => {
225                return Err(eyre!("Invalid expected response format"));
226            }
227        }
228
229        Ok(())
230    }
231}
232
233impl<Engine> Action<Engine> for RunRpcCompatTests
234where
235    Engine: EngineTypes,
236{
237    fn execute<'a>(&'a mut self, env: &'a mut Environment<Engine>) -> BoxFuture<'a, Result<()>> {
238        Box::pin(async move {
239            let mut total_tests = 0;
240            let mut passed_tests = 0;
241
242            for method in &self.methods {
243                info!("Running RPC compatibility tests for {}", method);
244
245                let method_dir = Path::new(&self.test_data_path).join(method);
246                if !method_dir.exists() {
247                    return Err(eyre!("Test directory does not exist: {}", method_dir.display()));
248                }
249
250                // Read all .io files in the method directory
251                let entries = std::fs::read_dir(&method_dir)
252                    .map_err(|e| eyre!("Failed to read directory: {}", e))?;
253
254                for entry in entries {
255                    let entry = entry?;
256                    let path = entry.path();
257
258                    if path.extension().and_then(|s| s.to_str()) == Some("io") {
259                        let test_name = path
260                            .file_stem()
261                            .and_then(|s| s.to_str())
262                            .unwrap_or("unknown")
263                            .to_string();
264
265                        let content = std::fs::read_to_string(&path)
266                            .map_err(|e| eyre!("Failed to read test file: {}", e))?;
267
268                        match Self::parse_io_file(&content) {
269                            Ok(mut test_case) => {
270                                test_case.name = test_name.clone();
271                                total_tests += 1;
272
273                                match self.execute_test_case(&test_case, env).await {
274                                    Ok(_) => {
275                                        info!("✓ {}/{}: PASS", method, test_name);
276                                        passed_tests += 1;
277                                    }
278                                    Err(e) => {
279                                        info!("✗ {}/{}: FAIL - {}", method, test_name, e);
280
281                                        if self.fail_fast {
282                                            return Err(eyre!("Test failed (fail-fast enabled)"));
283                                        }
284                                    }
285                                }
286                            }
287                            Err(e) => {
288                                info!("✗ {}/{}: PARSE ERROR - {}", method, test_name, e);
289                                if self.fail_fast {
290                                    return Err(e);
291                                }
292                            }
293                        }
294                    }
295                }
296            }
297
298            info!("RPC compatibility test results: {}/{} passed", passed_tests, total_tests);
299
300            if passed_tests < total_tests {
301                return Err(eyre!("Some tests failed: {}/{} passed", passed_tests, total_tests));
302            }
303
304            Ok(())
305        })
306    }
307}
308
309/// Action to initialize the chain from execution-apis test data
310#[derive(Debug)]
311pub struct InitializeFromExecutionApis {
312    /// Path to the base.rlp file (if different from default)
313    pub chain_rlp_path: Option<String>,
314    /// Path to the headfcu.json file (if different from default)
315    pub fcu_json_path: Option<String>,
316}
317
318impl Default for InitializeFromExecutionApis {
319    fn default() -> Self {
320        Self::new()
321    }
322}
323
324impl InitializeFromExecutionApis {
325    /// Create with default paths (assumes execution-apis/tests structure)
326    pub const fn new() -> Self {
327        Self { chain_rlp_path: None, fcu_json_path: None }
328    }
329
330    /// Set custom chain RLP path
331    pub fn with_chain_rlp(mut self, path: impl Into<String>) -> Self {
332        self.chain_rlp_path = Some(path.into());
333        self
334    }
335
336    /// Set custom FCU JSON path
337    pub fn with_fcu_json(mut self, path: impl Into<String>) -> Self {
338        self.fcu_json_path = Some(path.into());
339        self
340    }
341}
342
343impl<Engine> Action<Engine> for InitializeFromExecutionApis
344where
345    Engine: EngineTypes,
346{
347    fn execute<'a>(&'a mut self, env: &'a mut Environment<Engine>) -> BoxFuture<'a, Result<()>> {
348        Box::pin(async move {
349            // Load forkchoice state
350            let fcu_path = self
351                .fcu_json_path
352                .as_ref()
353                .map(Path::new)
354                .ok_or_else(|| eyre!("FCU JSON path is required"))?;
355
356            let fcu_state = reth_e2e_test_utils::setup_import::load_forkchoice_state(fcu_path)?;
357
358            info!(
359                "Applying forkchoice state - head: {}, safe: {}, finalized: {}",
360                fcu_state.head_block_hash,
361                fcu_state.safe_block_hash,
362                fcu_state.finalized_block_hash
363            );
364
365            // Apply forkchoice update to each node. The import setup only returns once the nodes
366            // accepted the imported head, so the update does not need to wait for syncing.
367            for (idx, client) in env.node_clients.iter().enumerate() {
368                debug!("Applying forkchoice update to node {}", idx);
369
370                let response: ForkchoiceUpdated = client
371                    .engine
372                    .http_client()
373                    .request("engine_forkchoiceUpdatedV3", (fcu_state, None::<()>))
374                    .await
375                    .map_err(|e| eyre!("Failed to update forkchoice on node {}: {}", idx, e))?;
376                expect_fcu_valid(&response, &format!("Forkchoice update on node {idx}"))?;
377            }
378
379            // Update environment state
380            env.active_node_state_mut()?.current_block_info = Some(BlockInfo {
381                hash: fcu_state.head_block_hash,
382                number: 0, // Will be updated when we fetch the actual block
383                timestamp: 0,
384            });
385
386            info!("Successfully initialized chain from execution-apis test data");
387            Ok(())
388        })
389    }
390}
391
392#[cfg(test)]
393mod tests {
394    use super::*;
395    use serde_json::json;
396
397    #[test]
398    fn test_compare_json_values_deeply_nested() {
399        // Test that the iterative comparison handles deeply nested structures
400        // without stack overflow
401        let mut nested = json!({"value": 0});
402        let mut expected = json!({"value": 0});
403
404        // Create a deeply nested structure
405        for i in 1..1000 {
406            nested = json!({"level": i, "nested": nested});
407            expected = json!({"level": i, "nested": expected});
408        }
409
410        // Should not panic with stack overflow
411        RunRpcCompatTests::compare_json_values(&nested, &expected, "root").unwrap();
412    }
413
414    #[test]
415    fn test_compare_json_values_arrays() {
416        // Test array comparison
417        let actual = json!([1, 2, 3, 4, 5]);
418        let expected = json!([1, 2, 3, 4, 5]);
419
420        RunRpcCompatTests::compare_json_values(&actual, &expected, "root").unwrap();
421
422        // Test array length mismatch
423        let actual = json!([1, 2, 3]);
424        let expected = json!([1, 2, 3, 4, 5]);
425
426        let result = RunRpcCompatTests::compare_json_values(&actual, &expected, "root");
427        assert!(result.is_err());
428        assert!(result.unwrap_err().to_string().contains("Array length mismatch"));
429    }
430
431    #[test]
432    fn test_compare_json_values_objects() {
433        // Test object comparison
434        let actual = json!({"a": 1, "b": 2, "c": 3});
435        let expected = json!({"a": 1, "b": 2, "c": 3});
436
437        RunRpcCompatTests::compare_json_values(&actual, &expected, "root").unwrap();
438
439        // Test missing key
440        let actual = json!({"a": 1, "b": 2});
441        let expected = json!({"a": 1, "b": 2, "c": 3});
442
443        let result = RunRpcCompatTests::compare_json_values(&actual, &expected, "root");
444        assert!(result.is_err());
445        assert!(result.unwrap_err().to_string().contains("Missing key"));
446    }
447
448    #[test]
449    fn test_compare_json_values_numbers() {
450        // Test number comparison with floating point
451        let actual = json!({"value": 1.00000000001});
452        let expected = json!({"value": 1.0});
453
454        // Should be equal within epsilon (1e-10)
455        RunRpcCompatTests::compare_json_values(&actual, &expected, "root").unwrap();
456
457        // Test significant difference
458        let actual = json!({"value": 1.1});
459        let expected = json!({"value": 1.0});
460
461        let result = RunRpcCompatTests::compare_json_values(&actual, &expected, "root");
462        assert!(result.is_err());
463        assert!(result.unwrap_err().to_string().contains("Number mismatch"));
464    }
465}