Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions crates/blockchain/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# ethrex-blockchain

Core blockchain logic for the ethrex Ethereum client.

For detailed API documentation, see the rustdocs:
```bash
cargo doc --package ethrex-blockchain --open
```

## Quick Start

```rust
use ethrex_blockchain::Blockchain;

let blockchain = Blockchain::new(store, BlockchainOptions::default());

// Add a block
blockchain.add_block(&block)?;

// Add transaction to mempool
blockchain.add_transaction_to_mempool(tx).await?;
```

## Features

- `metrics`: Enable Prometheus metrics collection

## Notes

ethrex is a post-merge client and does not support pre-merge (PoW) forks.
99 changes: 92 additions & 7 deletions crates/blockchain/blockchain.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,47 @@
//! # ethrex Blockchain
//!
//! Core blockchain logic for the ethrex Ethereum client.
//!
//! ## Overview
//!
//! This module implements the blockchain layer, which is responsible for:
//! - Block validation and execution
//! - State management and transitions
//! - Fork choice rule implementation
//! - Transaction mempool management
//! - Payload building for block production
//!
//! ## Key Components
//!
//! - [`Blockchain`]: Main interface for blockchain operations
//! - [`Mempool`]: Transaction pool for pending transactions
//! - [`fork_choice`]: Fork choice rule implementation
//! - [`payload`]: Block payload building for consensus
//!
//! ## Block Execution Flow
//!
//! ```text
//! 1. Receive block from consensus/P2P
//! 2. Validate block header (parent, timestamp, gas limit, etc.)
//! 3. Execute transactions in EVM
//! 4. Verify state root matches header
//! 5. Store block and update canonical chain
//! ```
//!
//! ## Usage
//!
//! ```ignore
//! use ethrex_blockchain::Blockchain;
//!
//! let blockchain = Blockchain::new(store, BlockchainOptions::default());
//!
//! // Add a block
//! blockchain.add_block(&block)?;
//!
//! // Add transaction to mempool
//! blockchain.add_transaction_to_mempool(tx).await?;
//! ```

pub mod constants;
pub mod error;
pub mod fork_choice;
Expand Down Expand Up @@ -67,38 +111,79 @@ type StoreUpdatesMap = FxHashMap<H256, (Result<Trie, StoreError>, FxHashMap<Nibb
//TODO: Implement a struct Chain or BlockChain to encapsulate
//functionality and canonical chain state and config

/// Specifies whether the blockchain operates as L1 (mainnet/testnet) or L2 (rollup).
#[derive(Debug, Clone, Default)]
pub enum BlockchainType {
/// Standard Ethereum L1 blockchain.
#[default]
L1,
/// Layer 2 rollup with additional fee configuration.
L2(L2Config),
}

/// Configuration for L2 rollup operation.
#[derive(Debug, Clone, Default)]
pub struct L2Config {
/// We use a RwLock because the Watcher updates the L1 fee config periodically
/// Fee configuration for L2 transactions.
///
/// Uses `RwLock` because the Watcher updates L1 fee config periodically.
pub fee_config: Arc<RwLock<FeeConfig>>,
}

/// Core blockchain implementation for block validation and execution.
///
/// The `Blockchain` struct is the main entry point for all blockchain operations:
/// - Adding and validating blocks
/// - Managing the transaction mempool
/// - Building payloads for block production
/// - Handling fork choice updates
///
/// # Thread Safety
///
/// `Blockchain` uses interior mutability for thread-safe access to shared state.
/// The mempool and payload storage are protected by appropriate synchronization primitives.
///
/// # Example
///
/// ```ignore
/// let blockchain = Blockchain::new(store, BlockchainOptions::default());
///
/// // Validate and add a block
/// blockchain.add_block(&block)?;
///
/// // Check sync status
/// if blockchain.is_synced() {
/// // Process transactions from mempool
/// }
/// ```
#[derive(Debug)]
pub struct Blockchain {
/// Underlying storage for blocks and state.
storage: Store,
/// Transaction mempool for pending transactions.
pub mempool: Mempool,
/// Whether the node's chain is in or out of sync with the current chain
/// This will be set to true once the initial sync has taken place and wont be set to false after
/// This does not reflect whether there is an ongoing sync process
/// Whether the node has completed initial sync.
///
/// Set to true after initial sync completes, never reset to false.
/// Does not reflect whether an ongoing sync is in progress.
is_synced: AtomicBool,
/// Configuration options for blockchain behavior.
pub options: BlockchainOptions,
/// Mapping from a payload id to either a complete payload or a payload build task
/// We need to keep completed payloads around in case consensus requests them twice
/// Cache of recently built payloads.
///
/// Maps payload IDs to either completed payloads or in-progress build tasks.
/// Kept around in case consensus requests the same payload twice.
pub payloads: Arc<TokioMutex<Vec<(u64, PayloadOrTask)>>>,
}

/// Configuration options for the blockchain.
#[derive(Debug, Clone)]
pub struct BlockchainOptions {
/// Maximum number of transactions in the mempool.
pub max_mempool_size: usize,
/// Whether performance logs should be emitted
/// Whether to emit performance logging.
pub perf_logs_enabled: bool,
/// Blockchain type (L1 or L2).
pub r#type: BlockchainType,
}

Expand Down
20 changes: 20 additions & 0 deletions crates/networking/p2p/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# ethrex-p2p

Peer-to-peer networking layer for the ethrex Ethereum client.

For detailed API documentation, see the rustdocs:
```bash
cargo doc --package ethrex-p2p --open
```

## Protocols

- **DiscV4**: Node discovery
- **RLPx**: Encrypted transport
- **eth/68**: Block and transaction propagation
- **snap/1**: Snap sync for state synchronization

## Features

- `experimental-discv5`: Enable discv5 node discovery (experimental)
- `sync-test`: Testing utilities for sync
68 changes: 68 additions & 0 deletions crates/networking/p2p/p2p.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,71 @@
//! # ethrex P2P Networking
//!
//! Peer-to-peer networking layer for the ethrex Ethereum client.
//!
//! ## Overview
//!
//! This crate implements the Ethereum P2P networking stack:
//! - **Discovery**: Node discovery using discv4 (and experimental discv5)
//! - **RLPx**: Encrypted transport protocol for peer communication
//! - **eth Protocol**: Block and transaction propagation
//! - **snap Protocol**: Fast state synchronization
Comment on lines +10 to +11
Copy link

Copilot AI Jan 7, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The documentation refers to "eth Protocol" and "snap Protocol" without the / version specifier. For consistency with the rest of the documentation (e.g., "eth/68", "snap/1"), consider using "eth/68 Protocol" and "snap/1 Protocol".

Suggested change
//! - **eth Protocol**: Block and transaction propagation
//! - **snap Protocol**: Fast state synchronization
//! - **eth/68 Protocol**: Block and transaction propagation
//! - **snap/1 Protocol**: Fast state synchronization

Copilot uses AI. Check for mistakes.
//!
//! ## Architecture
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────┐
//! │ Network Layer │
//! │ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │
//! │ │ discv4 │ │ RLPx │ │ Peer Handler │ │
//! │ │ (Discovery) │ │ (Transport) │ │ (Messages) │ │
//! │ └─────────────┘ └─────────────┘ └─────────────────────┘ │
//! └─────────────────────────────────────────────────────────────┘
//! │
//! ┌──────────────────┼──────────────────┐
//! ▼ ▼ ▼
//! ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
//! │ Sync Manager │ │ TX Broadcaster │ │ Snap Sync │
//! └─────────────────┘ └─────────────────┘ └─────────────────┘
//! ```
//!
//! ## Key Components
//!
//! - [`network`]: Network initialization and peer management
//! - [`peer_handler`]: Message handling for connected peers
//! - [`sync_manager`]: Block synchronization coordination
//! - [`sync`]: Full and snap sync implementations
//! - [`tx_broadcaster`]: Transaction pool broadcasting
//! - [`discv4`]: Node discovery protocol v4
//! - [`rlpx`]: RLPx encrypted transport
//!
//! ## Usage
//!
//! ```ignore
//! use ethrex_p2p::{start_network, SyncManager};
//!
//! // Start the P2P network
//! let (sync_manager, peer_handler) = start_network(
//! udp_addr,
//! tcp_addr,
//! bootnodes,
//! signer,
//! storage,
//! blockchain,
//! ).await?;
//!
//! // Start synchronization
//! sync_manager.start_sync().await?;
//! ```
//!
//! ## Protocols
//!
//! - **eth/68**: Block and transaction exchange
//! - **snap/1**: State snapshot synchronization
//!
//! ## Features
//!
//! - `experimental-discv5`: Enable discv5 node discovery (experimental)

pub mod discv4;
#[cfg(feature = "experimental-discv5")]
pub mod discv5;
Expand Down
18 changes: 18 additions & 0 deletions crates/networking/rpc/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# ethrex-rpc

JSON-RPC API implementation for the ethrex Ethereum client.

For detailed API documentation, see the rustdocs:
```bash
cargo doc --package ethrex-rpc --open
```

## Supported Namespaces

- `eth_*`: Standard Ethereum methods
- `engine_*`: Consensus client communication
- `debug_*`: Debugging and tracing
- `net_*`: Network information
- `admin_*`: Node administration
- `web3_*`: Web3 utilities
- `txpool_*`: Transaction pool inspection
26 changes: 21 additions & 5 deletions crates/networking/rpc/eth/gas_price.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,29 @@
//! Gas price estimation for `eth_gasPrice` RPC method.
//!
//! This module implements the gas price oracle that estimates a reasonable
//! gas price based on recent block history and network conditions.

use crate::rpc::{RpcApiContext, RpcHandler};
use crate::utils::RpcErr;
use ethrex_blockchain::BlockchainType;
use serde_json::Value;

// TODO: This does not need a struct,
// but I'm leaving it like this for consistency
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why remove the explanation?

// with the other RPC endpoints.
// The handle function could simply be
// a function called 'estimate'.
/// Handler for the `eth_gasPrice` RPC method.
///
/// Returns the current gas price in wei as a hexadecimal string.
/// The price is calculated as: `base_fee + estimated_priority_fee + operator_fee (L2 only)`.
///
/// # Algorithm
///
/// 1. Gets the base fee from the latest block header
/// 2. Estimates a reasonable priority fee (gas tip) by analyzing recent transactions
/// 3. For L2 nodes, adds the operator fee if configured
///
/// # Example Response
///
/// ```json
/// "0x3b9aca00" // 1 Gwei in hexadecimal
/// ```
Comment on lines +22 to +26
Copy link

Copilot AI Jan 7, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The comment states "TODO: This does not need a struct, but I'm leaving it like this for consistency". This TODO comment should be removed from the documentation as it's not relevant to users and suggests incomplete implementation decisions.

Suggested change
/// # Example Response
///
/// ```json
/// "0x3b9aca00" // 1 Gwei in hexadecimal
/// ```

Copilot uses AI. Check for mistakes.
#[derive(Debug, Clone)]
pub struct GasPrice;

Expand Down
58 changes: 58 additions & 0 deletions crates/networking/rpc/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,61 @@
//! # ethrex RPC
//!
//! This crate implements the Ethereum JSON-RPC API for the ethrex node.
//!
//! ## Overview
//!
//! The RPC server provides three interfaces:
//! - **HTTP API**: Public JSON-RPC endpoint for client requests (`eth_*`, `debug_*`, `net_*`, etc.)
//! - **WebSocket API**: Optional WebSocket endpoint for subscriptions and real-time updates
//! - **Auth RPC API**: Authenticated endpoint for consensus client communication (`engine_*` methods)
//!
//! ## Supported Namespaces
//!
//! - `eth`: Standard Ethereum methods (blocks, transactions, accounts, gas estimation)
//! - `engine`: Consensus layer methods for block building and fork choice
//! - `debug`: Debugging methods (raw blocks, execution witnesses, tracing)
//! - `net`: Network information methods
//! - `admin`: Node administration methods
//! - `web3`: Web3 utility methods
//! - `txpool`: Transaction pool inspection methods
//!
//! ## Usage
//!
//! ```ignore
//! use ethrex_rpc::{start_api, RpcApiContext};
//!
//! // Start the RPC server
//! start_api(
//! http_addr,
//! ws_addr,
//! authrpc_addr,
//! storage,
//! blockchain,
//! jwt_secret,
//! // ... other parameters
//! ).await?;
//! ```
//!
//! ## Implementing Custom RPC Handlers
//!
//! Implement the [`RpcHandler`] trait to create custom RPC endpoints:
//!
//! ```ignore
//! use ethrex_rpc::{RpcHandler, RpcApiContext, RpcErr};
//!
//! struct MyHandler { /* fields */ }
//!
//! impl RpcHandler for MyHandler {
//! fn parse(params: &Option<Vec<Value>>) -> Result<Self, RpcErr> {
//! // Parse JSON-RPC parameters
//! }
//!
//! async fn handle(&self, context: RpcApiContext) -> Result<Value, RpcErr> {
//! // Handle the request
//! }
//! }
//! ```

// This is added because otherwise some tests would fail due to reaching the recursion limit
#![recursion_limit = "400"]

Expand Down
Loading
Loading