ethrex-rpc 17.0.0

JSON-RPC and Engine API server for the ethrex Ethereum execution client
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
//! Utility types and error handling for JSON-RPC.
//!
//! This module provides common types used across all RPC handlers:
//! - [`RpcErr`]: Error type for RPC failures with proper JSON-RPC error codes
//! - [`RpcRequest`]: Parsed JSON-RPC request
//! - [`RpcNamespace`]: RPC method namespace (eth, engine, debug, etc.)
//! - Response types for success and error cases

use ethrex_common::U256;
use ethrex_storage::error::StoreError;
use ethrex_vm::EvmError;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::{authentication::AuthenticationError, clients::EthClientError};
use ethrex_blockchain::error::MempoolError;

/// Error type for JSON-RPC method failures.
///
/// Each variant maps to a specific JSON-RPC error code when serialized:
/// - `-32601`: Method not found
/// - `-32602`: Invalid params
/// - `-32603`: Internal error
/// - `-32000`: Generic server error
/// - `-38001` to `-38006`: Engine API specific errors
/// - `3`: Execution reverted/halted
#[derive(Debug, thiserror::Error)]
pub enum RpcErr {
    #[error("Method not found: {0}")]
    MethodNotFound(String),
    #[error("Wrong parameter: {0}")]
    WrongParam(String),
    #[error("Invalid params: {0}")]
    BadParams(String),
    #[error("Missing parameter: {0}")]
    MissingParam(String),
    #[error("Too large request")]
    TooLargeRequest,
    #[error("Bad hex format: {0}")]
    BadHexFormat(u64),
    #[error("Unsupported fork: {0}")]
    UnsupportedFork(String),
    #[error("Internal Error: {0}")]
    Internal(String),
    #[error("Vm execution error: {0}")]
    Vm(String),
    #[error("execution reverted: data={data}")]
    Revert { data: String },
    #[error("execution halted: reason={reason}, gas_used={gas_used}")]
    Halt { reason: String, gas_used: u64 },
    #[error("Authentication error: {0:?}")]
    AuthenticationError(AuthenticationError),
    /// JSON-RPC 2.0 ยง5.1: the JSON sent is not a valid Request object. Used
    /// for malformed bodies on the auth port (e.g. empty batches) where we
    /// also drop the request id (per spec, id MUST be null when it cannot
    /// be detected).
    #[error("Invalid Request: {0}")]
    InvalidRequest(String),
    #[error("Invalid forkchoice state: {0}")]
    InvalidForkChoiceState(String),
    #[error("Invalid payload attributes: {0}")]
    InvalidPayloadAttributes(String),
    #[error("Too deep reorg: {0}")]
    TooDeepReorg(String),
    #[error("Unknown payload: {0}")]
    UnknownPayload(String),
    // EIP-8025 proof errors (-39001 .. -39004)
    #[error("Invalid proof format: {0}")]
    InvalidProofFormat(String),
    #[error("Invalid header format: {0}")]
    InvalidHeaderFormat(String),
    #[error("Invalid payload: {0}")]
    InvalidPayload(String),
    #[error("Proof generation unavailable: {0}")]
    ProofGenerationUnavailable(String),
}

impl From<RpcErr> for RpcErrorMetadata {
    fn from(value: RpcErr) -> Self {
        match value {
            RpcErr::MethodNotFound(bad_method) => RpcErrorMetadata {
                code: -32601,
                data: None,
                message: format!("Method not found: {bad_method}"),
            },
            RpcErr::WrongParam(field) => RpcErrorMetadata {
                code: -32602,
                data: None,
                message: format!("Field '{field}' is incorrect or has an unknown format"),
            },
            RpcErr::BadParams(context) => RpcErrorMetadata {
                code: -32000,
                data: None,
                message: format!("Invalid params: {context}"),
            },
            RpcErr::InvalidRequest(context) => RpcErrorMetadata {
                code: -32600,
                data: None,
                message: format!("Invalid Request: {context}"),
            },
            RpcErr::MissingParam(parameter_name) => RpcErrorMetadata {
                code: -32000,
                data: None,
                message: format!("Expected parameter: {parameter_name} is missing"),
            },
            RpcErr::TooLargeRequest => RpcErrorMetadata {
                code: -38004,
                data: None,
                message: "Too large request".to_string(),
            },
            RpcErr::UnsupportedFork(context) => RpcErrorMetadata {
                code: -38005,
                data: None,
                message: format!("Unsupported fork: {context}"),
            },
            RpcErr::BadHexFormat(arg_number) => RpcErrorMetadata {
                code: -32602,
                data: None,
                message: format!("invalid argument {arg_number} : hex string without 0x prefix"),
            },
            RpcErr::Internal(context) => RpcErrorMetadata {
                code: -32603,
                data: None,
                message: format!("Internal Error: {context}"),
            },
            RpcErr::Vm(context) => RpcErrorMetadata {
                code: -32015,
                data: None,
                message: format!("Vm execution error: {context}"),
            },
            RpcErr::Revert { data } => RpcErrorMetadata {
                // This code (3) was hand-picked to match hive tests.
                // Could not find proper documentation about it.
                code: 3,
                data: Some(data.clone()),
                message: format!(
                    "execution reverted: {}",
                    get_message_from_revert_data(&data).unwrap_or_else(|err| format!(
                        "tried to decode error from abi but failed: {err}"
                    ))
                ),
            },
            RpcErr::Halt { reason, gas_used } => RpcErrorMetadata {
                // Just copy the `Revert` error code.
                // Haven't found an example of this one yet.
                code: 3,
                data: None,
                message: format!("execution halted: reason={reason}, gas_used={gas_used}"),
            },
            RpcErr::AuthenticationError(auth_error) => match auth_error {
                AuthenticationError::InvalidIssuedAtClaim => RpcErrorMetadata {
                    code: -32000,
                    data: None,
                    message: "Auth failed: Invalid iat claim".to_string(),
                },
                AuthenticationError::TokenDecodingError => RpcErrorMetadata {
                    code: -32000,
                    data: None,
                    message: "Auth failed: Invalid or missing token".to_string(),
                },
                AuthenticationError::MissingAuthentication => RpcErrorMetadata {
                    code: -32000,
                    data: None,
                    message: "Auth failed: Missing authentication header".to_string(),
                },
            },
            RpcErr::InvalidForkChoiceState(data) => RpcErrorMetadata {
                code: -38002,
                data: Some(data),
                message: "Invalid forkchoice state".to_string(),
            },
            RpcErr::InvalidPayloadAttributes(data) => RpcErrorMetadata {
                code: -38003,
                data: Some(data),
                message: "Invalid payload attributes".to_string(),
            },
            RpcErr::TooDeepReorg(data) => RpcErrorMetadata {
                code: -38006,
                data: Some(data),
                message: "Too deep reorg".to_string(),
            },
            RpcErr::UnknownPayload(context) => RpcErrorMetadata {
                code: -38001,
                data: None,
                message: format!("Unknown payload: {context}"),
            },
            // EIP-8025 proof error codes
            RpcErr::InvalidProofFormat(context) => RpcErrorMetadata {
                code: -39001,
                data: None,
                message: format!("Invalid proof format: {context}"),
            },
            RpcErr::InvalidHeaderFormat(context) => RpcErrorMetadata {
                code: -39002,
                data: None,
                message: format!("Invalid header format: {context}"),
            },
            RpcErr::InvalidPayload(context) => RpcErrorMetadata {
                code: -39003,
                data: None,
                message: format!("Invalid payload: {context}"),
            },
            RpcErr::ProofGenerationUnavailable(context) => RpcErrorMetadata {
                code: -39004,
                data: None,
                message: format!("Proof generation unavailable: {context}"),
            },
        }
    }
}

impl From<serde_json::Error> for RpcErr {
    fn from(error: serde_json::Error) -> Self {
        Self::BadParams(error.to_string())
    }
}

// TODO: Actually return different errors for each case
// here we are returning a BadParams error
impl From<MempoolError> for RpcErr {
    fn from(err: MempoolError) -> Self {
        match err {
            MempoolError::StoreError(err) => Self::Internal(err.to_string()),
            other_err => Self::BadParams(other_err.to_string()),
        }
    }
}

impl From<ethrex_crypto::CryptoError> for RpcErr {
    fn from(err: ethrex_crypto::CryptoError) -> Self {
        Self::Internal(format!("Cryptography error: {err}"))
    }
}

/// JSON-RPC method namespace.
///
/// Methods are namespaced by prefix (e.g., `eth_getBalance` is in the `Eth` namespace).
/// Different namespaces may have different authentication requirements.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RpcNamespace {
    /// Engine API methods for consensus client communication (requires JWT auth).
    Engine,
    /// Standard Ethereum methods for querying state and sending transactions.
    Eth,
    /// Node administration methods.
    Admin,
    /// Debugging and tracing methods.
    Debug,
    /// Web3 utility methods.
    Web3,
    /// Network information methods.
    Net,
    /// Transaction pool inspection methods (exposed as `txpool_*`).
    Mempool,
}

impl RpcNamespace {
    /// Parses a namespace name from its CLI/method-prefix form.
    pub fn from_prefix(s: &str) -> Option<Self> {
        match s {
            "engine" => Some(RpcNamespace::Engine),
            "eth" => Some(RpcNamespace::Eth),
            "admin" => Some(RpcNamespace::Admin),
            "debug" => Some(RpcNamespace::Debug),
            "web3" => Some(RpcNamespace::Web3),
            "net" => Some(RpcNamespace::Net),
            "txpool" => Some(RpcNamespace::Mempool),
            _ => None,
        }
    }
}

/// JSON-RPC request identifier.
///
/// Per the JSON-RPC 2.0 spec, request IDs can be either numbers or strings.
/// The same ID must be returned in the response.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum RpcRequestId {
    /// Numeric request ID.
    Number(u64),
    /// String request ID.
    String(String),
}

/// A parsed JSON-RPC 2.0 request.
///
/// # Example
///
/// ```json
/// {
///     "jsonrpc": "2.0",
///     "id": 1,
///     "method": "eth_getBalance",
///     "params": ["0x...", "latest"]
/// }
/// ```
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct RpcRequest {
    /// Request identifier, echoed back in the response.
    pub id: RpcRequestId,
    /// JSON-RPC version, must be "2.0".
    pub jsonrpc: String,
    /// Method name (e.g., "eth_getBalance").
    pub method: String,
    /// Optional array of method parameters.
    pub params: Option<Vec<Value>>,
}

impl RpcRequest {
    pub fn namespace(&self) -> Result<RpcNamespace, RpcErr> {
        let mut parts = self.method.split('_');
        let Some(namespace) = parts.next() else {
            return Err(RpcErr::MethodNotFound(self.method.clone()));
        };
        resolve_namespace(namespace, self.method.clone())
    }

    pub fn new(method: &str, params: Option<Vec<Value>>) -> Self {
        RpcRequest {
            id: RpcRequestId::Number(1),
            jsonrpc: "2.0".to_string(),
            method: method.to_string(),
            params,
        }
    }
}

pub fn resolve_namespace(maybe_namespace: &str, method: String) -> Result<RpcNamespace, RpcErr> {
    RpcNamespace::from_prefix(maybe_namespace).ok_or(RpcErr::MethodNotFound(method))
}

impl Default for RpcRequest {
    fn default() -> Self {
        RpcRequest {
            id: RpcRequestId::Number(1),
            jsonrpc: "2.0".to_string(),
            method: "".to_string(),
            params: None,
        }
    }
}

/// Error metadata for JSON-RPC error responses.
///
/// Contains the error code, message, and optional additional data.
/// Error codes follow the JSON-RPC 2.0 and Ethereum conventions.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct RpcErrorMetadata {
    /// Numeric error code (negative for standard errors).
    pub code: i32,
    /// Optional additional error data (e.g., revert reason).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<String>,
    /// Human-readable error message.
    pub message: String,
}

/// A successful JSON-RPC 2.0 response.
#[derive(Serialize, Deserialize, Debug)]
pub struct RpcSuccessResponse {
    /// Request identifier from the original request.
    pub id: RpcRequestId,
    /// JSON-RPC version, always "2.0".
    pub jsonrpc: String,
    /// The result value returned by the method.
    pub result: Value,
}

/// An error JSON-RPC 2.0 response.
#[derive(Serialize, Deserialize, Debug)]
pub struct RpcErrorResponse {
    /// Request identifier from the original request.
    pub id: RpcRequestId,
    /// JSON-RPC version, always "2.0".
    pub jsonrpc: String,
    /// Error details including code and message.
    pub error: RpcErrorMetadata,
}

/// A JSON-RPC 2.0 response, either success or error.
#[derive(Deserialize, Debug)]
#[serde(untagged)]
pub enum RpcResponse {
    Success(RpcSuccessResponse),
    Error(RpcErrorResponse),
}

/// Failure to read from DB will always constitute an internal error
impl From<StoreError> for RpcErr {
    fn from(value: StoreError) -> Self {
        RpcErr::Internal(value.to_string())
    }
}

impl From<EvmError> for RpcErr {
    fn from(value: EvmError) -> Self {
        RpcErr::Vm(value.to_string())
    }
}

pub fn get_message_from_revert_data(data: &str) -> Result<String, EthClientError> {
    if data == "0x" {
        Ok("Execution reverted without a reason string.".to_owned())
    // 4 byte function signature 0xXXXXXXXX
    } else if data.len() == 10 {
        Ok(data.to_owned())
    } else {
        let abi_decoded_error_data =
            hex::decode(data.strip_prefix("0x").ok_or(EthClientError::Custom(
                "Failed to strip_prefix when getting message from revert data".to_owned(),
            ))?)
            .map_err(|_| {
                EthClientError::Custom(
                    "Failed to hex::decode when getting message from revert data".to_owned(),
                )
            })?;
        let string_length = U256::from_big_endian(abi_decoded_error_data.get(36..68).ok_or(
            EthClientError::Custom(
                "Failed to slice index abi_decoded_error_data when getting message from revert data".to_owned(),
            ),
        )?);
        let string_len = usize::try_from(string_length).map_err(|_| {
            EthClientError::Custom(
                "Failed to convert string_length to usize when getting message from revert data"
                    .to_owned(),
            )
        })?;
        let string_data = abi_decoded_error_data
            .get(68..68 + string_len)
            .ok_or(EthClientError::Custom(
            "Failed to slice index abi_decoded_error_data when getting message from revert data"
                .to_owned(),
        ))?;
        String::from_utf8(string_data.to_vec()).map_err(|_| {
            EthClientError::Custom(
                "Failed to String::from_utf8 when getting message from revert data".to_owned(),
            )
        })
    }
}

pub fn parse_json_hex(hex: &serde_json::Value) -> Result<u64, String> {
    if let Value::String(maybe_hex) = hex {
        let trimmed = maybe_hex.trim_start_matches("0x");
        let maybe_parsed = u64::from_str_radix(trimmed, 16);
        maybe_parsed.map_err(|_| format!("Could not parse given hex {maybe_hex}"))
    } else {
        Err(format!("Could not parse given hex {hex}"))
    }
}