Skip to content

Commit

Permalink
wip L2 full node
Browse files Browse the repository at this point in the history
  • Loading branch information
Brechtpd committed Aug 4, 2024
1 parent 69ff57c commit 058f59e
Show file tree
Hide file tree
Showing 17 changed files with 1,017 additions and 63 deletions.
11 changes: 11 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

38 changes: 37 additions & 1 deletion bin/reth/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,44 @@ foundry-blob-explorers = "0.5"
discv5.workspace = true

# alloy
alloy-consensus = { version = "0.2", features = ["kzg"] }
#alloy-consensus = { version = "0.2", features = ["kzg"] }
alloy-sol-types = { workspace = true, features = ["json"] }
alloy-signer.workspace = true
alloy-signer-local = { workspace = true, features = ["mnemonic"] }
alloy-rpc-types.workspace = true
alloy-network.workspace = true
alloy-consensus = { workspace = true, features = ["kzg"] }



#reth.workspace = true
#reth-chainspec.workspace = true
#reth-primitives.workspace = true
#reth-tracing.workspace = true
#reth-db = { workspace = true, features = ["test-utils"] }
#reth-rpc.workspace = true
reth-rpc-layer.workspace = true
#reth-payload-builder = { workspace = true, features = ["test-utils"] }
#reth-provider.workspace = true
#reth-node-builder = { workspace = true, features = ["test-utils"] }
reth-tokio-util.workspace = true
reth-stages-types.workspace = true
reth-network-peers.workspace = true
#reth-node-ethereum.workspace = true

jsonrpsee.workspace = true

futures-util.workspace = true
#eyre.workspace = true
#tokio.workspace = true
tokio-stream.workspace = true
#serde_json.workspace = true
#alloy-signer.workspace = true
#alloy-signer-local = { workspace = true, features = ["mnemonic"] }
#alloy-rpc-types.workspace = true
#alloy-network.workspace = true
#alloy-consensus = { workspace = true, features = ["kzg"] }
#tracing.workspace = true

[target.'cfg(unix)'.dependencies]
tikv-jemallocator = { version = "0.5.0", optional = true }
Expand Down
1 change: 1 addition & 0 deletions bin/reth/src/commands/debug_cmd/build_block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use reth_evm::execute::{BlockExecutionOutput, BlockExecutorProvider, Executor};
use reth_execution_types::ExecutionOutcome;
use reth_fs_util as fs;
use reth_node_api::PayloadBuilderAttributes;
//use reth_node_api::PayloadBuilderAttributes;
use reth_payload_builder::database::CachedReads;
use reth_primitives::{
constants::eip4844::LoadKzgSettingsError, revm_primitives::KzgSettings, Address,
Expand Down
101 changes: 101 additions & 0 deletions bin/reth/src/engine_api.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
use crate::traits::PayloadEnvelopeExt;
use jsonrpsee::{
core::client::ClientT,
http_client::{transport::HttpBackend, HttpClient},
};
use reth::{
api::{EngineTypes, PayloadBuilderAttributes},
providers::CanonStateNotificationStream,
rpc::{
api::EngineApiClient,
types::engine::{ForkchoiceState, PayloadStatusEnum},
},
};
use reth_payload_builder::PayloadId;
use reth_primitives::B256;
use reth_rpc_layer::AuthClientService;
use std::marker::PhantomData;

/// Helper for engine api operations
pub struct EngineApiTestContext<E> {
pub canonical_stream: CanonStateNotificationStream,
pub engine_api_client: HttpClient<AuthClientService<HttpBackend>>,
pub _marker: PhantomData<E>,
}

impl<E: EngineTypes> EngineApiTestContext<E> {
/// Retrieves a v3 payload from the engine api
pub async fn get_payload_v3(
&self,
payload_id: PayloadId,
) -> eyre::Result<E::ExecutionPayloadV3> {
Ok(EngineApiClient::<E>::get_payload_v3(&self.engine_api_client, payload_id).await?)
}

/// Retrieves a v3 payload from the engine api as serde value
pub async fn get_payload_v3_value(
&self,
payload_id: PayloadId,
) -> eyre::Result<serde_json::Value> {
Ok(self.engine_api_client.request("engine_getPayloadV3", (payload_id,)).await?)
}

/// Submits a payload to the engine api
pub async fn submit_payload(
&self,
payload: E::BuiltPayload,
payload_builder_attributes: E::PayloadBuilderAttributes,
expected_status: PayloadStatusEnum,
versioned_hashes: Vec<B256>,
) -> eyre::Result<B256>
where
E::ExecutionPayloadV3: From<E::BuiltPayload> + PayloadEnvelopeExt,
{
// setup payload for submission
let envelope_v3: <E as EngineTypes>::ExecutionPayloadV3 = payload.into();

// submit payload to engine api
let submission = EngineApiClient::<E>::new_payload_v3(
&self.engine_api_client,
envelope_v3.execution_payload(),
versioned_hashes,
payload_builder_attributes.parent_beacon_block_root().unwrap(),
)
.await?;

assert_eq!(submission.status, expected_status);

Ok(submission.latest_valid_hash.unwrap_or_default())
}

/// Sends forkchoice update to the engine api
pub async fn update_forkchoice(&self, current_head: B256, new_head: B256) -> eyre::Result<()> {
EngineApiClient::<E>::fork_choice_updated_v2(
&self.engine_api_client,
ForkchoiceState {
head_block_hash: new_head,
safe_block_hash: current_head,
finalized_block_hash: current_head,
},
None,
)
.await?;
Ok(())
}

/// Sends forkchoice update to the engine api with a zero finalized hash
pub async fn update_optimistic_forkchoice(&self, hash: B256) -> eyre::Result<()> {
EngineApiClient::<E>::fork_choice_updated_v2(
&self.engine_api_client,
ForkchoiceState {
head_block_hash: hash,
safe_block_hash: B256::ZERO,
finalized_block_hash: B256::ZERO,
},
None,
)
.await?;

Ok(())
}
}
40 changes: 23 additions & 17 deletions bin/reth/src/execution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,52 +14,57 @@ use reth_primitives::{
TxType, B256, U256,
};
use reth_revm::{
db::{states::bundle_state::BundleRetention, BundleState},
DBBox, DatabaseCommit, Evm, StateBuilder, StateDBBox,
db::{states::bundle_state::BundleRetention, BundleState}, primitives::FixedBytes, DBBox, DatabaseCommit, Evm, StateBuilder, StateDBBox
};
use reth_tracing::tracing::debug;

/// Execute a rollup block and return (block with recovered senders)[BlockWithSenders], (bundle
/// state)[BundleState] and list of (receipts)[Receipt].
pub(crate) async fn execute_block<Pool: TransactionPool>(
db: &mut Database,
//db: &mut Database,
pool: &Pool,
tx: &TransactionSigned,
block_metadata: &RollupContract::BlockMetadata,
block_data: Bytes,
//block_data_hash: B256,
) -> eyre::Result<(BlockWithSenders, BundleState, Vec<Receipt>, Vec<ExecutionResult>)> {
) -> eyre::Result<(BlockWithSenders/*, BundleState*/, Vec<Receipt>, Vec<ExecutionResult>)> {
//if header.rollupChainId != U256::from(CHAIN_ID) {
// eyre::bail!("Invalid rollup chain ID")
//}

// Construct header
let header = construct_header(db, block_metadata)?;
let header = construct_header(block_metadata)?;

// Decode transactions
let transactions = decode_transactions(pool, tx, block_data).await?;
println!("transactions: {:?}", transactions);

// Configure EVM
let evm_config = EthEvmConfig::default();
let mut evm = configure_evm(&evm_config, db, &header);
//let mut evm = configure_evm(&evm_config, db, &header);

// Execute transactions
let (executed_txs, receipts, results) = execute_transactions(&mut evm, &header, transactions)?;
// let (executed_txs, receipts, results) = execute_transactions(&mut evm, &header, transactions)?;
// println!("executed_txs: {:?}", executed_txs);

// Construct block and recover senders
let block = Block { header, body: executed_txs, ..Default::default() }
.with_recovered_senders()
.ok_or_eyre("failed to recover senders")?;
// // Construct block and recover senders
// let block = Block { header, body: executed_txs, ..Default::default() }
// .with_recovered_senders()
// .ok_or_eyre("failed to recover senders")?;

let bundle = evm.db_mut().take_bundle();

Ok((block, bundle, receipts, results))
let block = BlockWithSenders::default();
let receipts = Vec::new();
let results = Vec::new();

//let bundle = evm.db_mut().take_bundle();

Ok((block/* , bundle*/, receipts, results))
}

/// Construct header from the given rollup header.
fn construct_header(db: &Database, meta_data: &RollupContract::BlockMetadata) -> eyre::Result<Header> {
let parent_block = db.get_block((meta_data.l2BlockNumber - 1).try_into().unwrap())?;
fn construct_header(meta_data: &RollupContract::BlockMetadata) -> eyre::Result<Header> {
//let parent_block = db.get_block((meta_data.l2BlockNumber - 1).try_into().unwrap())?;

let block_number = u64::try_from(meta_data.l2BlockNumber)?;

Expand All @@ -78,7 +83,8 @@ fn construct_header(db: &Database, meta_data: &RollupContract::BlockMetadata) ->

// Construct header
Ok(Header {
parent_hash: parent_block.map(|block| block.header.hash()).unwrap_or_default(),
//parent_hash: parent_block.map(|block| block.header.hash()).unwrap_or_default(),
parent_hash: B256::default(),
number: block_number,
gas_limit: u64::try_from(meta_data.gasLimit)?,
timestamp: u64::try_from(meta_data.timestamp)?,
Expand Down Expand Up @@ -171,7 +177,7 @@ async fn decode_transactions<Pool: TransactionPool>(
// Decode block data, filter only transactions with the correct chain ID and recover senders
let transactions = Vec::<TransactionSigned>::decode(&mut raw_transactions.as_ref())?
.into_iter()
.filter(|tx| tx.chain_id() == Some(CHAIN_ID))
.filter(|tx| {println!("chain_id: {:?}", tx.chain_id()); tx.chain_id() == Some(CHAIN_ID) })
.map(|tx| {
let sender = tx.recover_signer().ok_or(eyre::eyre!("failed to recover signer"))?;
Ok((tx, sender))
Expand Down
Loading

0 comments on commit 058f59e

Please sign in to comment.