Skip to content

Commit

Permalink
chore(engine): Migrate To Alloy (#241)
Browse files Browse the repository at this point in the history
* chore(l1): alloy type port

* chore(engine): alloy type port

* chore(engine): alloy type port

* chore(engine): fix wrong log type in deposit decoding
  • Loading branch information
refcell authored May 1, 2024
1 parent 89e8e2c commit eb829a9
Show file tree
Hide file tree
Showing 9 changed files with 178 additions and 215 deletions.
8 changes: 2 additions & 6 deletions bin/network.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
use std::str::FromStr;

use ethers::types::Address;
use alloy_primitives::address;
use eyre::Result;

use magi::{
Expand All @@ -15,9 +13,7 @@ async fn main() -> Result<()> {

let addr = "0.0.0.0:9876".parse()?;
let chain_id = 420;
let (_, recv) = watch::channel(Address::from_str(
"0x715b7219d986641df9efd9c7ef01218d528e19ec",
)?);
let (_, recv) = watch::channel(address!("715b7219d986641df9efd9c7ef01218d528e19ec"));
let (block_handler, block_recv) = BlockHandler::new(chain_id, recv);

Service::new(addr, chain_id)
Expand Down
8 changes: 4 additions & 4 deletions src/common/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,10 +92,10 @@ impl From<&ExecutionPayload> for BlockInfo {
/// Converts an [ExecutionPayload] to [BlockInfo]
fn from(value: &ExecutionPayload) -> Self {
Self {
number: value.block_number.as_u64(),
hash: B256::from_slice(value.block_hash.as_bytes()),
parent_hash: B256::from_slice(value.parent_hash.as_bytes()),
timestamp: value.timestamp.as_u64(),
number: value.block_number.try_into().unwrap_or_default(),
hash: value.block_hash,
parent_hash: value.parent_hash,
timestamp: value.timestamp.try_into().unwrap_or_default(),
}
}
}
Expand Down
36 changes: 16 additions & 20 deletions src/derive/stages/attributes.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::sync::{Arc, RwLock};

use ethers::abi::{decode, encode, ParamType, Token};
use ethers::types::{Address, Log, H256, U256, U64};
use ethers::types::{Address, H256, U256};
use ethers::utils::{keccak256, rlp::Encodable, rlp::RlpStream};

use eyre::Result;
Expand Down Expand Up @@ -89,21 +89,20 @@ impl Attributes {
None
};

let timestamp = U64([input.timestamp]);
let l1_inclusion_block = Some(input.l1_inclusion_block);
let seq_number = Some(self.sequence_number);
let prev_randao = l1_info.block_info.mix_hash;
let epoch = Some(input.epoch);
let transactions = Some(self.derive_transactions(input, l1_info));
let transactions = Some(self.derive_transactions(&input, l1_info));
let suggested_fee_recipient = SystemAccounts::default().fee_vault;

PayloadAttributes {
timestamp,
prev_randao: H256::from_slice(prev_randao.as_slice()),
suggested_fee_recipient: Address::from_slice(suggested_fee_recipient.as_slice()),
timestamp: alloy_primitives::U64::from(input.timestamp),
prev_randao,
suggested_fee_recipient,
transactions,
no_tx_pool: true,
gas_limit: U64([l1_info.system_config.gas_limit.try_into().unwrap()]),
gas_limit: alloy_primitives::U64::from(l1_info.system_config.gas_limit),
withdrawals,
epoch,
l1_inclusion_block,
Expand All @@ -118,7 +117,7 @@ impl Attributes {
/// Returns a [RawTransaction] vector containing all of the transactions for the L2 block.
fn derive_transactions(
&self,
input: BlockInput<Epoch>,
input: &BlockInput<Epoch>,
l1_info: &L1Info,
) -> Vec<RawTransaction> {
let mut transactions = Vec::new();
Expand All @@ -145,7 +144,7 @@ impl Attributes {
}

// Remaining transactions
let mut rest = input.transactions;
let mut rest = input.transactions.clone();
transactions.append(&mut rest);

transactions
Expand Down Expand Up @@ -428,28 +427,25 @@ impl UserDeposited {
}
}

impl TryFrom<Log> for UserDeposited {
impl TryFrom<alloy_rpc_types::Log> for UserDeposited {
type Error = eyre::Report;

/// Converts the emitted L1 deposit event log into [UserDeposited]
fn try_from(log: Log) -> Result<Self, Self::Error> {
let opaque_data = decode(&[ParamType::Bytes], &log.data)?[0]
fn try_from(log: alloy_rpc_types::Log) -> Result<Self, Self::Error> {
let opaque_data = decode(&[ParamType::Bytes], &log.data().data)?[0]
.clone()
.into_bytes()
.unwrap();

let from = Address::from(log.topics[1]);
let to = Address::from(log.topics[2]);
let from = Address::from_slice(log.topics()[1].as_slice());
let to = Address::from_slice(log.topics()[2].as_slice());
let mint = U256::from_big_endian(&opaque_data[0..32]);
let value = U256::from_big_endian(&opaque_data[32..64]);
let gas = u64::from_be_bytes(opaque_data[64..72].try_into()?);
let is_creation = opaque_data[72] != 0;
let data = opaque_data[73..].to_vec();

let l1_block_num = log
.block_number
.ok_or(eyre::eyre!("block num not found"))?
.as_u64();
let l1_block_num = log.block_number.ok_or(eyre::eyre!("block num not found"))?;

let l1_block_hash = log.block_hash.ok_or(eyre::eyre!("block hash not found"))?;
let log_index = log.log_index.unwrap();
Expand All @@ -463,8 +459,8 @@ impl TryFrom<Log> for UserDeposited {
is_creation,
data,
l1_block_num,
l1_block_hash,
log_index,
l1_block_hash: H256::from_slice(l1_block_hash.as_slice()),
log_index: log_index.into(),
})
}
}
28 changes: 15 additions & 13 deletions src/driver/engine_driver.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use std::sync::Arc;

use alloy_primitives::B256;
use ethers::providers::{Http, Middleware, Provider};
use ethers::types::Transaction;
use ethers::{
Expand Down Expand Up @@ -38,7 +37,8 @@ pub struct EngineDriver<E: Engine> {
impl<E: Engine> EngineDriver<E> {
/// Initiates validation & production of a new L2 block from the given [PayloadAttributes] and updates the forkchoice
pub async fn handle_attributes(&mut self, attributes: PayloadAttributes) -> Result<()> {
let block: Option<Block<Transaction>> = self.block_at(attributes.timestamp.as_u64()).await;
let timestamp: u64 = attributes.timestamp.try_into()?;
let block: Option<Block<Transaction>> = self.block_at(timestamp).await;

if let Some(block) = block {
if should_skip(&block, &attributes)? {
Expand Down Expand Up @@ -100,10 +100,10 @@ impl<E: Engine> EngineDriver<E> {
let payload = self.build_payload(attributes).await?;

let new_head = BlockInfo {
number: payload.block_number.as_u64(),
hash: B256::from_slice(payload.block_hash.as_bytes()),
parent_hash: B256::from_slice(payload.parent_hash.as_bytes()),
timestamp: payload.timestamp.as_u64(),
number: payload.block_number.try_into().unwrap_or_default(),
hash: payload.block_hash,
parent_hash: payload.parent_hash,
timestamp: payload.timestamp.try_into().unwrap_or_default(),
};

self.push_payload(payload).await?;
Expand Down Expand Up @@ -199,9 +199,9 @@ impl<E: Engine> EngineDriver<E> {
/// - `finalized_block` = `finalized_head`
fn create_forkchoice_state(&self) -> ForkchoiceState {
ForkchoiceState {
head_block_hash: H256::from_slice(self.unsafe_head.hash.as_slice()),
safe_block_hash: H256::from_slice(self.safe_head.hash.as_slice()),
finalized_block_hash: H256::from_slice(self.finalized_head.hash.as_slice()),
head_block_hash: self.unsafe_head.hash,
safe_block_hash: self.safe_head.hash,
finalized_block_hash: self.finalized_head.hash,
}
}

Expand Down Expand Up @@ -243,10 +243,12 @@ fn should_skip(block: &Block<Transaction>, attributes: &PayloadAttributes) -> Re
tracing::debug!("block hashes: {:?}", block_hashes);

let is_same = attributes_hashes == block_hashes
&& attributes.timestamp.as_u64() == block.timestamp.as_u64()
&& attributes.prev_randao == block.mix_hash.unwrap()
&& attributes.suggested_fee_recipient == block.author.unwrap()
&& attributes.gas_limit.as_u64() == block.gas_limit.as_u64();
&& attributes.timestamp == alloy_primitives::U64::from(block.timestamp.as_u64())
&& attributes.prev_randao
== alloy_primitives::B256::from_slice(block.mix_hash.unwrap().as_bytes())
&& attributes.suggested_fee_recipient
== alloy_primitives::Address::from_slice(block.author.unwrap().as_bytes())
&& attributes.gas_limit == alloy_primitives::U64::from(block.gas_limit.as_u64());

Ok(is_same)
}
Expand Down
17 changes: 10 additions & 7 deletions src/driver/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ use std::{
time::Duration,
};

use alloy_primitives::Address;
use ethers::providers::{Http, Provider};
use ethers::types::Address;
use eyre::Result;
use reqwest::Url;
use tokio::{
Expand Down Expand Up @@ -100,7 +100,7 @@ impl Driver<EngineApi> {

let _addr = rpc::run_server(config.clone()).await?;

let signer = Address::from_slice(config.chain.system_config.unsafe_block_signer.as_slice());
let signer = config.chain.system_config.unsafe_block_signer;
let (unsafe_block_signer_sender, unsafe_block_signer_recv) = watch::channel(signer);

let (block_handler, unsafe_block_recv) =
Expand Down Expand Up @@ -230,16 +230,19 @@ impl<E: Engine> Driver<E> {
}

self.future_unsafe_blocks.retain(|payload| {
let unsafe_block_num = payload.block_number.as_u64();
let unsafe_block_num: u64 = match payload.block_number.try_into() {
Ok(num) => num,
Err(_) => return false,
};
let synced_block_num = self.engine_driver.unsafe_head.number;

unsafe_block_num > synced_block_num && unsafe_block_num - synced_block_num < 1024
});

let next_unsafe_payload = self.future_unsafe_blocks.iter().find(|p| {
alloy_primitives::B256::from_slice(p.parent_hash.as_bytes())
== self.engine_driver.unsafe_head.hash
});
let next_unsafe_payload = self
.future_unsafe_blocks
.iter()
.find(|p| p.parent_hash == self.engine_driver.unsafe_head.hash);

if let Some(payload) = next_unsafe_payload {
_ = self.engine_driver.handle_unsafe_payload(payload).await;
Expand Down
14 changes: 6 additions & 8 deletions src/engine/fork.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use alloy_primitives::B256;
use ethers::types::H256;
use serde::{Deserialize, Serialize};

use super::{PayloadId, PayloadStatus};
Expand All @@ -23,23 +22,22 @@ pub struct ForkChoiceUpdate {
#[serde(rename_all = "camelCase")]
pub struct ForkchoiceState {
/// 32 byte block hash of the head of the canonical chain
pub head_block_hash: H256,
pub head_block_hash: B256,
/// 32 byte "safe" block hash of the canonical chain under certain synchrony and honesty assumptions
/// This value MUST be either equal to or an ancestor of headBlockHash
pub safe_block_hash: H256,
pub safe_block_hash: B256,
/// 32 byte block hash of the most recent finalized block
pub finalized_block_hash: H256,
pub finalized_block_hash: B256,
}

impl ForkchoiceState {
/// Creates a new fork choice state with the given head block hash.
/// The safe and finalized block hashes are set to the head block hash.
pub fn from_single_head(head_block_hash: B256) -> Self {
let hash = H256::from_slice(head_block_hash.as_slice());
Self {
head_block_hash: hash,
safe_block_hash: hash,
finalized_block_hash: hash,
head_block_hash,
safe_block_hash: head_block_hash,
finalized_block_hash: head_block_hash,
}
}
}
Loading

0 comments on commit eb829a9

Please sign in to comment.