Skip to content

Commit

Permalink
chore(engine): alloy type port
Browse files Browse the repository at this point in the history
  • Loading branch information
refcell committed May 1, 2024
1 parent ea600a2 commit 783b18f
Show file tree
Hide file tree
Showing 6 changed files with 80 additions and 63 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
6 changes: 3 additions & 3 deletions src/derive/stages/attributes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ impl Attributes {
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 {
Expand All @@ -117,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 @@ -144,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
6 changes: 4 additions & 2 deletions src/driver/engine_driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -244,8 +244,10 @@ fn should_skip(block: &Block<Transaction>, attributes: &PayloadAttributes) -> Re

let is_same = attributes_hashes == block_hashes
&& 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.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
12 changes: 6 additions & 6 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 @@ -239,10 +239,10 @@ impl<E: Engine> Driver<E> {
unsafe_block_num > synced_block_num && unsafe_block_num - synced_block_num < 1024
});

let next_unsafe_payload = self.future_unsafe_blocks.iter().find(|p| {
p.parent_hash
== 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
39 changes: 29 additions & 10 deletions src/engine/payload.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use alloy_consensus::TxEnvelope;
use alloy_eips::eip2718::Encodable2718;
use alloy_primitives::{Address, Bytes, B256, U64};
use alloy_rpc_types::Block;
use alloy_rpc_types::BlockTransactions;
use alloy_primitives::{Bytes, Address, B256, U64};
use eyre::Result;
use serde::{Deserialize, Serialize};

Expand Down Expand Up @@ -80,19 +80,37 @@ impl TryFrom<Block> for ExecutionPayload {
state_root: value.header.state_root,
receipts_root: value.header.receipts_root,
logs_bloom: value.header.logs_bloom.0.to_vec().into(),
prev_randao: value.header.mix_hash.ok_or_else(|| eyre::eyre!("Missing mix hash"))?,
block_number: value.header.number.ok_or_else(|| eyre::eyre!("Missing block number"))?.try_into()?,
prev_randao: value
.header
.mix_hash
.ok_or_else(|| eyre::eyre!("Missing mix hash"))?,
block_number: value
.header
.number
.ok_or_else(|| eyre::eyre!("Missing block number"))?
.try_into()?,
gas_limit: (value.header.gas_limit as u64).try_into()?,
gas_used: (value.header.gas_used as u64).try_into()?,
timestamp: value.header.timestamp.try_into()?,
extra_data: Bytes::from(value.header.extra_data.0),
base_fee_per_gas: (value.header.base_fee_per_gas.unwrap_or_else(|| 0u64.into()) as u64)
.try_into()?,
block_hash: value.header.hash.ok_or_else(|| eyre::eyre!("Missing block hash"))?,
block_hash: value
.header
.hash
.ok_or_else(|| eyre::eyre!("Missing block hash"))?,
transactions: encoded_txs,
withdrawals: Some(Vec::new()),
blob_gas_used: value.header.blob_gas_used.map(|v| (v as u64).try_into()).transpose()?,
excess_blob_gas: value.header.excess_blob_gas.map(|v| (v as u64).try_into()).transpose()?,
blob_gas_used: value
.header
.blob_gas_used
.map(|v| (v as u64).try_into())
.transpose()?,
excess_blob_gas: value
.header
.excess_blob_gas
.map(|v| (v as u64).try_into())
.transpose()?,
})
}
}
Expand Down Expand Up @@ -175,17 +193,18 @@ pub enum Status {

#[cfg(test)]
mod tests {
use eyre::Result;
use alloy_provider::{Provider, ProviderBuilder};
use alloy_primitives::{b256, uint};
use crate::engine::ExecutionPayload;
use alloy_primitives::{b256, uint};
use alloy_provider::{Provider, ProviderBuilder};
use eyre::Result;

#[tokio::test]
async fn test_from_block_hash_to_execution_paylaod() -> Result<()> {
let Ok(l2_rpc_url) = std::env::var("L2_TEST_RPC_URL") else {
return Ok(());
};
let checkpoint_hash = b256!("c2794a16acacd9f7670379ffd12b6968ff98e2a602f57d7d1f880220aa5a4973");
let checkpoint_hash =
b256!("c2794a16acacd9f7670379ffd12b6968ff98e2a602f57d7d1f880220aa5a4973");
let url = reqwest::Url::parse(&l2_rpc_url)?;
let l2_provider = ProviderBuilder::new().on_http(url);

Expand Down
72 changes: 36 additions & 36 deletions src/network/handlers/block_handler.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use std::sync::mpsc::{channel, Receiver, Sender};
use std::time::SystemTime;

use ethers::types::{Address, Bytes, Signature, H256};
use ethers::utils::keccak256;
use alloy_primitives::{keccak256, Address, Bytes, Signature, B256, U64};
use eyre::Result;
use libp2p::gossipsub::{IdentTopic, Message, MessageAcceptance, TopicHash};
use ssz_rs::{prelude::*, List, Vector, U256};
Expand Down Expand Up @@ -32,7 +31,7 @@ struct ExecutionPayloadEnvelope {
signature: Signature,
hash: PayloadHash,
#[allow(unused)]
parent_beacon_block_root: Option<H256>,
parent_beacon_block_root: Option<B256>,
}

impl Handler for BlockHandler {
Expand Down Expand Up @@ -109,7 +108,10 @@ impl BlockHandler {

let msg = envelope.hash.signature_message(self.chain_id);
let block_signer = *self.unsafe_signer_recv.borrow();
let sig_valid = envelope.signature.verify(msg, block_signer).is_ok();
let sig_valid = envelope
.signature
.recover_address_from_prehash(&msg)
.map_or(false, |addr| addr == block_signer);

time_valid && sig_valid
}
Expand Down Expand Up @@ -154,7 +156,7 @@ fn decode_post_ecotone_block_msg(data: Vec<u8>) -> Result<ExecutionPayloadEnvelo

let signature = Signature::try_from(sig_data)?;

let parent_beacon_block_root = Some(H256::from_slice(parent_beacon_block_root));
let parent_beacon_block_root = Some(B256::from_slice(parent_beacon_block_root));

let payload: ExecutionPayloadV3SSZ = deserialize(block_data)?;
let payload = ExecutionPayload::from(payload);
Expand All @@ -170,30 +172,30 @@ fn decode_post_ecotone_block_msg(data: Vec<u8>) -> Result<ExecutionPayloadEnvelo
}

/// Represents the Keccak256 hash of the block
struct PayloadHash(H256);
struct PayloadHash(B256);

impl From<&[u8]> for PayloadHash {
/// Returns the Keccak256 hash of a sequence of bytes
fn from(value: &[u8]) -> Self {
Self(keccak256(value).into())
Self(keccak256(value))
}
}

impl PayloadHash {
/// The expected message that should be signed by the unsafe block signer.
fn signature_message(&self, chain_id: u64) -> H256 {
let domain = H256::zero();
let chain_id = H256::from_low_u64_be(chain_id);
fn signature_message(&self, chain_id: u64) -> B256 {
let domain = B256::ZERO;
let chain_id = B256::from_slice(&chain_id.to_be_bytes());
let payload_hash = self.0;

let data: Vec<u8> = [
domain.as_bytes(),
chain_id.as_bytes(),
payload_hash.as_bytes(),
domain.as_slice(),
chain_id.as_slice(),
payload_hash.as_slice(),
]
.concat();

keccak256(data).into()
keccak256(data)
}
}

Expand Down Expand Up @@ -246,10 +248,10 @@ impl From<ExecutionPayloadV1SSZ> for ExecutionPayload {
receipts_root: convert_hash(value.receipts_root),
logs_bloom: convert_byte_vector(value.logs_bloom),
prev_randao: convert_hash(value.prev_randao),
block_number: value.block_number.into(),
gas_limit: value.gas_limit.into(),
gas_used: value.gas_used.into(),
timestamp: value.timestamp.into(),
block_number: value.block_number.try_into().unwrap_or_default(),
gas_limit: value.gas_limit.try_into().unwrap_or_default(),
gas_used: value.gas_used.try_into().unwrap_or_default(),
timestamp: value.timestamp.try_into().unwrap_or_default(),
extra_data: convert_byte_list(value.extra_data),
base_fee_per_gas: convert_uint(value.base_fee_per_gas),
block_hash: convert_hash(value.block_hash),
Expand Down Expand Up @@ -320,10 +322,10 @@ impl From<ExecutionPayloadV2SSZ> for ExecutionPayload {
receipts_root: convert_hash(value.receipts_root),
logs_bloom: convert_byte_vector(value.logs_bloom),
prev_randao: convert_hash(value.prev_randao),
block_number: value.block_number.into(),
gas_limit: value.gas_limit.into(),
gas_used: value.gas_used.into(),
timestamp: value.timestamp.into(),
block_number: value.block_number.try_into().unwrap_or_default(),
gas_limit: value.gas_limit.try_into().unwrap_or_default(),
gas_used: value.gas_used.try_into().unwrap_or_default(),
timestamp: value.timestamp.try_into().unwrap_or_default(),
extra_data: convert_byte_list(value.extra_data),
base_fee_per_gas: convert_uint(value.base_fee_per_gas),
block_hash: convert_hash(value.block_hash),
Expand Down Expand Up @@ -365,24 +367,24 @@ impl From<ExecutionPayloadV3SSZ> for ExecutionPayload {
receipts_root: convert_hash(value.receipts_root),
logs_bloom: convert_byte_vector(value.logs_bloom),
prev_randao: convert_hash(value.prev_randao),
block_number: value.block_number.into(),
gas_limit: value.gas_limit.into(),
gas_used: value.gas_used.into(),
timestamp: value.timestamp.into(),
block_number: value.block_number.try_into().unwrap_or_default(),
gas_limit: value.gas_limit.try_into().unwrap_or_default(),
gas_used: value.gas_used.try_into().unwrap_or_default(),
timestamp: value.timestamp.try_into().unwrap_or_default(),
extra_data: convert_byte_list(value.extra_data),
base_fee_per_gas: convert_uint(value.base_fee_per_gas),
block_hash: convert_hash(value.block_hash),
transactions: convert_tx_list(value.transactions),
withdrawals: Some(Vec::new()),
blob_gas_used: Some(value.blob_gas_used.into()),
excess_blob_gas: Some(value.excess_blob_gas.into()),
blob_gas_used: Some(value.blob_gas_used.try_into().unwrap_or_default()),
excess_blob_gas: Some(value.excess_blob_gas.try_into().unwrap_or_default()),
}
}
}

/// Converts [Bytes32] into [H256]
fn convert_hash(bytes: Bytes32) -> H256 {
H256::from_slice(bytes.as_slice())
/// Converts [Bytes32] into [B256]
fn convert_hash(bytes: Bytes32) -> B256 {
B256::from_slice(bytes.as_slice())
}

/// Converts [VecAddress] into [Address]
Expand All @@ -400,12 +402,10 @@ fn convert_byte_list<const N: usize>(list: List<u8, N>) -> Bytes {
Bytes::from(list.to_vec())
}

/// Converts a [U256] into [ethers::types::U64]
fn convert_uint(value: U256) -> ethers::types::U64 {
/// Converts a [U256] into [U64]
fn convert_uint(value: U256) -> U64 {
let bytes = value.to_bytes_le();
ethers::types::U256::from_little_endian(&bytes)
.as_u64()
.into()
U64::from_le_slice(&bytes)
}

/// Converts [ssz_rs::List] of [Transaction] into a vector of [RawTransaction]
Expand Down

0 comments on commit 783b18f

Please sign in to comment.