Skip to content

Commit b02940f

Browse files
constwzMatusKyselcbh876claude
authored
feat: Mendel HF (#105)
* feat(txpool): add EIP-7594 blob sidecar toggle * feat: align eth_getFinalizedHeader/block with BSC validator-based finalization --------- Co-authored-by: Matus Kysel <matus.kysel@bnbchain.org> Co-authored-by: cbh876 <3930922419@qq.com> Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
1 parent 301b7f6 commit b02940f

11 files changed

Lines changed: 625 additions & 64 deletions

File tree

CLAUDE.md

Lines changed: 83 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,79 @@
1-
# Reth Development Guide for AI Agents
1+
# BNB Chain Reth (bnb-chain/reth) — Development Guide
22

3-
This guide provides comprehensive instructions for AI agents working on the Reth codebase. It covers the architecture, development workflows, and critical guidelines for effective contributions.
3+
This guide provides comprehensive instructions for AI agents working on the **BNB Chain fork** of the Reth codebase. This is a production-grade execution layer client specifically adapted for **BNB Smart Chain (BSC)**.
4+
5+
**Repository**: `bnb-chain/reth` (https://github.com/bnb-chain/reth)
6+
**Upstream**: Fork of `paradigmxyz/reth` (v1.7.0 baseline)
7+
**Main branch**: `main`
8+
9+
---
10+
11+
## Relationship: reth-bsc and reth
12+
13+
`bnb-chain/reth` (this repo) is the **core library layer** — a fork of upstream `paradigmxyz/reth` with BSC-specific modifications (Parlia consensus, TrieDB, system transactions, custom RPC, etc.).
14+
15+
`bnb-chain/reth-bsc` is the **application layer** that depends on this repo. It is the actual BSC node binary that imports crates from `bnb-chain/reth` as git dependencies. Issues reported in `reth-bsc` (e.g., RPC returning wrong data during staged sync) often have root causes in this repo's provider/storage layer.
16+
17+
When fixing issues from `reth-bsc`:
18+
1. Trace the call path from RPC through the provider layer in this repo
19+
2. Apply fixes here in `bnb-chain/reth`
20+
3. The `reth-bsc` project will pick up fixes via git dependency updates
21+
22+
---
23+
24+
## BSC Fork Summary
25+
26+
This fork adapts the Ethereum-focused Reth client for BNB Smart Chain. Key differences from upstream:
27+
28+
| Aspect | Upstream Reth | BSC Fork |
29+
|--------|--------------|----------|
30+
| Consensus | PoS (Beacon Chain) | **Parlia** (Validator-based PoSA) |
31+
| Finalized Block | Beacon Chain determined | Validator snapshot based |
32+
| State Backend | MDBX only | **MDBX + TrieDB** (dual backend) |
33+
| System Txs | Not supported | Supported (`gas_limit == u64::MAX/2`) |
34+
| P2P Peers | Standard | **Proxied peer** support |
35+
| Custom RPC | Standard Ethereum | `eth_getFinalizedBlock`, `eth_getFinalizedHeader` |
36+
| Hardforks | Ethereum only | Ethereum + BSC-specific (Ramanujan → Pascal) |
37+
38+
### BSC-Specific Features
39+
40+
1. **Parlia Consensus Engine**: BSC's Proof-of-Staked-Authority (PoSA) consensus replacing Ethereum's PoS. Implementation in `examples/bsc-p2p/src/block_import/parlia.rs`. Canonical head: highest block number wins; for equal heights, lower hash wins.
41+
42+
2. **TrieDB State Storage Backend**: Alternative state database alongside MDBX. Configured via `StateDbConfig` in `crates/config/src/config.rs`. Supports genesis init, staged sync, live sync, and io-uring. Dependencies from `bnb-chain/reth-bsc-triedb`.
43+
44+
3. **BSC System Transactions**: Special transactions identified by `gas_limit == u64::MAX/2 && caller == beneficiary`. Exempted from block gas limit validation. Handled across all RPC tracers via `handle_bsc_system_transaction()` in `crates/rpc/rpc/src/debug.rs`.
45+
46+
4. **Custom RPC Methods**: `eth_getFinalizedBlock(verified_validator_num)` and `eth_getFinalizedHeader(verified_validator_num)` in `crates/rpc/rpc-eth-api/src/core.rs` and `helpers/block.rs`.
47+
48+
5. **Proxied Peer Support**: Enhanced P2P networking with proxy peer definitions in `crates/net/network/` and `crates/net/eth-wire-types/`.
49+
50+
6. **Validator Block Snapshot Table**: BSC validator support integrated into the engine with a dedicated database table.
51+
52+
7. **Blob Fee Validation**: Enhanced blob storage with extended time support and fee checks for EIP-4844 compatibility on BSC.
53+
54+
8. **BSC Hardforks**: Ramanujan, Niels, MirrorSync, Bruno, Euler, Nano, Moran, Gibbs, Planck, Luban, Plato, Hertz, HertzFix, Kepler, Feynman, FeynmanFix, Haber, HaberFix, Bohr, Pascal, Prague — defined in `examples/bsc-p2p/src/chainspec.rs`.
55+
56+
### Key BSC Code Locations
57+
58+
- `examples/bsc-p2p/` — Complete BSC P2P node example (Parlia consensus, chainspec, genesis)
59+
- `crates/config/src/config.rs``StateDbConfig` for TrieDB/MDBX selection
60+
- `crates/rpc/rpc/src/debug.rs` — BSC system transaction handling in tracers
61+
- `crates/rpc/rpc-eth-api/src/core.rs` — Custom `eth_getFinalizedBlock` / `eth_getFinalizedHeader`
62+
- `crates/rpc/rpc-eth-api/src/helpers/block.rs` — Finalized block logic with validator count
63+
- `crates/transaction-pool/src/validate/eth.rs` — Blob fee and EIP-1559 validation for BSC
64+
- `crates/net/network/` — Proxied peer support
65+
- `crates/storage/provider/` — TrieDB integration in state provider
66+
67+
### Custom Dependencies
68+
69+
```toml
70+
# In Cargo.toml — BSC TrieDB support
71+
rust-eth-triedb = { git = "https://github.com/bnb-chain/reth-bsc-triedb.git", tag = "v0.0.1" }
72+
rust-eth-triedb-common = { ... }
73+
rust-eth-triedb-state-trie = { ... }
74+
```
75+
76+
---
477

578
## Project Overview
679

@@ -10,21 +83,22 @@ Reth is a high-performance Ethereum execution client written in Rust, focusing o
1083

1184
### Core Components
1285

13-
1. **Consensus (`crates/consensus/`)**: Validates blocks according to Ethereum consensus rules
14-
2. **Storage (`crates/storage/`)**: Hybrid database using MDBX + static files for optimal performance
15-
3. **Networking (`crates/net/`)**: P2P networking stack with discovery, sync, and transaction propagation
16-
4. **RPC (`crates/rpc/`)**: JSON-RPC server supporting all standard Ethereum APIs
86+
1. **Consensus (`crates/consensus/`)**: Validates blocks according to consensus rules (Parlia for BSC)
87+
2. **Storage (`crates/storage/`)**: Hybrid database using MDBX + static files + TrieDB (BSC) for optimal performance
88+
3. **Networking (`crates/net/`)**: P2P networking stack with discovery, sync, transaction propagation, and proxied peer support
89+
4. **RPC (`crates/rpc/`)**: JSON-RPC server supporting standard Ethereum APIs + BSC custom methods
1790
5. **Execution (`crates/evm/`, `crates/ethereum/`)**: Transaction execution and state transitions
1891
6. **Pipeline (`crates/stages/`)**: Staged sync architecture for blockchain synchronization
1992
7. **Trie (`crates/trie/`)**: Merkle Patricia Trie implementation with parallel state root computation
2093
8. **Node Builder (`crates/node/`)**: High-level node orchestration and configuration
2194
9. **The Consensus Engine (`crates/engine/`)**: Handles processing blocks received from the consensus layer with the Engine API (newPayload, forkchoiceUpdated)
95+
10. **Configuration (`crates/config/`)**: Node configuration including StateDbConfig for TrieDB/MDBX backend selection
2296

2397
### Key Design Principles
2498

2599
- **Modularity**: Each crate can be used as a standalone library
26100
- **Performance**: Extensive use of parallelism, memory-mapped I/O, and optimized data structures
27-
- **Extensibility**: Traits and generic types allow for different implementations (Ethereum, Optimism, etc.)
101+
- **Extensibility**: Traits and generic types allow for different implementations (Ethereum, BSC, Optimism, etc.)
28102
- **Type Safety**: Strong typing throughout with minimal use of dynamic dispatch
29103

30104
## Development Workflow
@@ -175,7 +249,7 @@ Before submitting changes, ensure:
175249
5. **Commit Messages**: Follow conventional format (feat:, fix:, chore:, etc.)
176250

177251

178-
### Opening PRs against <https://github.com/paradigmxyz/reth>
252+
### Opening PRs against <https://github.com/bnb-chain/reth>
179253

180254
Label PRs appropriately, first check the available labels and then apply the relevant ones:
181255
* when changes are RPC related, add A-rpc label
@@ -258,7 +332,7 @@ const TRACER_TIMEOUT: Duration = Duration::from_secs(5);
258332
**Document constraints and assumptions:**
259333
```rust
260334
/// Returns heap size estimate.
261-
///
335+
///
262336
/// Note: May undercount shared references (Rc/Arc). For precise
263337
/// accounting, combine with an allocator-based approach.
264338
fn deep_size_of(&self) -> usize
@@ -314,7 +388,6 @@ GLOBAL_COUNTER.fetch_add(1, Ordering::SeqCst);
314388

315389
Before adding a comment, ask: Would someone reading just the current code (no PR, no history) find this helpful?
316390

317-
318391
### Example Contribution Workflow
319392

320393
Let's say you want to fix a bug where external IP resolution fails on startup:

crates/engine/tree/src/persistence.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,6 @@ where
100100
.send(MetricEvent::SyncHeight { height: block_number });
101101

102102
if self.pruner.is_pruning_needed(block_number) {
103-
// We log `PrunerOutput` inside the `Pruner`
104103
let _ = self.prune_before(block_number)?;
105104
}
106105
}

crates/node/builder/src/launch/common.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -557,6 +557,8 @@ impl<R, ChainSpec: EthChainSpec> LaunchContextWith<Attached<WithConfigs<ChainSpe
557557
ChainSpec: reth_chainspec::EthereumHardforks,
558558
{
559559
PrunerBuilder::new(self.prune_config())
560+
.delete_limit(self.chain_spec().prune_delete_limit())
561+
.timeout(PrunerBuilder::DEFAULT_TIMEOUT)
560562
}
561563

562564
/// Loads the JWT secret for the engine API

crates/prune/prune/src/builder.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,9 @@ pub struct PrunerBuilder {
2929
}
3030

3131
impl PrunerBuilder {
32+
/// Default timeout for a prune run.
33+
pub const DEFAULT_TIMEOUT: Duration = Duration::from_millis(100);
34+
3235
/// Creates a new [`PrunerBuilder`] from the given [`PruneConfig`].
3336
pub fn new(pruner_config: PruneConfig) -> Self {
3437
Self::default()

crates/rpc/rpc-eth-api/src/core.rs

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -245,22 +245,26 @@ pub trait EthApi<
245245

246246
/// Returns the finalized block header.
247247
///
248-
/// The `verified_validator_num` parameter is provided for BSC compatibility but is not used
249-
/// in standard Ethereum. The finalized block is determined by the Beacon Chain consensus
250-
/// (Casper FFG) and requires 2/3+ validator attestations.
248+
/// BSC compatibility:
249+
/// - `-1` uses ceil(validators/2)
250+
/// - `-2` uses ceil(validators*2/3)
251+
/// - `-3` uses all validators
252+
/// - positive values override the threshold directly.
251253
#[method(name = "getFinalizedHeader")]
252-
async fn finalized_header(&self, verified_validator_num: u64) -> RpcResult<Option<H>>;
254+
async fn finalized_header(&self, verified_validator_num: i64) -> RpcResult<Option<H>>;
253255

254256
/// Returns the finalized block.
255257
///
256-
/// The `verified_validator_num` parameter is provided for BSC compatibility but is not used
257-
/// in standard Ethereum. The finalized block is determined by the Beacon Chain consensus
258-
/// (Casper FFG) and requires 2/3+ validator attestations.
258+
/// BSC compatibility:
259+
/// - `-1` uses ceil(validators/2)
260+
/// - `-2` uses ceil(validators*2/3)
261+
/// - `-3` uses all validators
262+
/// - positive values override the threshold directly.
259263
///
260264
/// If `full` is true, the block object will contain all transaction objects,
261265
/// otherwise it will only contain the transaction hashes.
262266
#[method(name = "getFinalizedBlock")]
263-
async fn finalized_block(&self, verified_validator_num: u64, full: bool) -> RpcResult<Option<B>>;
267+
async fn finalized_block(&self, verified_validator_num: i64, full: bool) -> RpcResult<Option<B>>;
264268

265269
/// `eth_simulateV1` executes an arbitrary number of transactions on top of the requested state.
266270
/// The transactions are packed into individual blocks. Overrides can be provided.
@@ -752,13 +756,13 @@ where
752756
}
753757

754758
/// Handler for: `eth_getFinalizedHeader`
755-
async fn finalized_header(&self, verified_validator_num: u64) -> RpcResult<Option<RpcHeader<T::NetworkTypes>>> {
759+
async fn finalized_header(&self, verified_validator_num: i64) -> RpcResult<Option<RpcHeader<T::NetworkTypes>>> {
756760
trace!(target: "rpc::eth", verified_validator_num, "Serving eth_getFinalizedHeader");
757761
Ok(EthBlocks::rpc_finalized_header(self, verified_validator_num).await?)
758762
}
759763

760764
/// Handler for: `eth_getFinalizedBlock`
761-
async fn finalized_block(&self, verified_validator_num: u64, full: bool) -> RpcResult<Option<RpcBlock<T::NetworkTypes>>> {
765+
async fn finalized_block(&self, verified_validator_num: i64, full: bool) -> RpcResult<Option<RpcBlock<T::NetworkTypes>>> {
762766
trace!(target: "rpc::eth", verified_validator_num, ?full, "Serving eth_getFinalizedBlock");
763767
Ok(EthBlocks::rpc_finalized_block(self, verified_validator_num, full).await?)
764768
}
@@ -974,4 +978,3 @@ where
974978
Ok(EthState::get_account_info(self, address, block).await?)
975979
}
976980
}
977-

0 commit comments

Comments
 (0)