Skip to content

Commit

Permalink
fix: add blob gas & parent beacon root to local blockchain constructor
Browse files Browse the repository at this point in the history
  • Loading branch information
Wodann committed Nov 10, 2023
1 parent fa34342 commit 1204f19
Show file tree
Hide file tree
Showing 9 changed files with 90 additions and 32 deletions.
25 changes: 24 additions & 1 deletion crates/edr_evm/src/blockchain/local.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@ use std::{
};

use async_trait::async_trait;
use edr_eth::{block::PartialHeader, trie::KECCAK_NULL_RLP, Bytes, B256, B64, U256};
use edr_eth::{
block::{BlobGas, PartialHeader},
trie::KECCAK_NULL_RLP,
Bytes, B256, B64, U256,
};
use revm::{db::BlockHashRef, primitives::SpecId, DatabaseCommit};

use super::{
Expand All @@ -25,6 +29,12 @@ pub enum CreationError {
/// Missing base fee per gas for post-London blockchain
#[error("Missing base fee per gas for post-London blockchain")]
MissingBaseFee,
/// Missing blob gas information for post-Cancun blockchain
#[error("Missing blob gas information for post-Cancun blockchain")]
MissingBlobGas,
/// Missing parent beacon block root for post-Cancun blockchain
#[error("Missing parent beacon block root for post-Cancun blockchain")]
MissingParentBeaconBlockRoot,
/// Missing prevrandao for post-merge blockchain
#[error("Missing prevrandao for post-merge blockchain")]
MissingPrevrandao,
Expand All @@ -51,6 +61,7 @@ impl LocalBlockchain {
/// Constructs a new instance using the provided arguments to build a
/// genesis block.
#[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
#[allow(clippy::too_many_arguments)]
pub fn new(
genesis_diff: StateDiff,
chain_id: u64,
Expand All @@ -59,6 +70,8 @@ impl LocalBlockchain {
timestamp: Option<u64>,
prevrandao: Option<B256>,
base_fee: Option<U256>,
blob_gas: Option<BlobGas>,
parent_beacon_block_root: Option<B256>,
) -> Result<Self, CreationError> {
const EXTRA_DATA: &[u8] = b"\x12\x34";

Expand Down Expand Up @@ -105,6 +118,16 @@ impl LocalBlockchain {
} else {
None
},
blob_gas: if spec_id >= SpecId::CANCUN {
Some(blob_gas.ok_or(CreationError::MissingBlobGas)?)
} else {
None
},
parent_beacon_block_root: if spec_id >= SpecId::CANCUN {
Some(parent_beacon_block_root.ok_or(CreationError::MissingParentBeaconBlockRoot)?)
} else {
None
},
..PartialHeader::default()
};

Expand Down
7 changes: 6 additions & 1 deletion crates/edr_evm/tests/blockchain.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::str::FromStr;

use edr_eth::{
block::PartialHeader,
block::{BlobGas, PartialHeader},
transaction::{EIP155TransactionRequest, SignedTransaction, TransactionKind},
trie::KECCAK_NULL_RLP,
Address, Bytes, B256, U256,
Expand Down Expand Up @@ -60,6 +60,11 @@ async fn create_dummy_blockchains() -> Vec<Box<dyn SyncBlockchain<BlockchainErro
None,
Some(B256::zero()),
Some(U256::from(DEFAULT_INITIAL_BASE_FEE)),
Some(BlobGas {
gas_used: 0,
excess_gas: 0,
}),
Some(KECCAK_NULL_RLP),
)
.expect("Should construct without issues");

Expand Down
2 changes: 1 addition & 1 deletion crates/edr_evm_napi/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -509,7 +509,7 @@ export class Block {
/** The EDR blockchain */
export class Blockchain {
/** Constructs a new blockchain from a genesis block. */
constructor(chainId: bigint, specId: SpecId, gasLimit: bigint, accounts: Array<GenesisAccount>, timestamp?: bigint | undefined | null, prevRandao?: Buffer | undefined | null, baseFee?: bigint | undefined | null)
constructor(chainId: bigint, specId: SpecId, gasLimit: bigint, accounts: Array<GenesisAccount>, timestamp?: bigint | undefined | null, prevRandao?: Buffer | undefined | null, baseFee?: bigint | undefined | null, blobGas?: BlobGas | undefined | null, parentBeaconBlockRoot?: Buffer | undefined | null)
static fork(context: EdrContext, specId: SpecId, hardforkActivationOverrides: Array<[bigint, Array<[bigint, SpecId]>]>, remoteUrl: string, forkBlockNumber?: bigint | undefined | null, cacheDir?: string | undefined | null): Promise<Blockchain>
/**Retrieves the block with the provided hash, if it exists. */
blockByHash(hash: Buffer): Promise<Block | null>
Expand Down
12 changes: 6 additions & 6 deletions crates/edr_evm_napi/src/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,13 +186,13 @@ pub struct BlobGas {
pub excess_gas: BigInt,
}

impl TryCast<edr_eth::block::BlobGas> for BlobGas {
impl TryFrom<BlobGas> for edr_eth::block::BlobGas {
type Error = napi::Error;

fn try_cast(self) -> Result<edr_eth::block::BlobGas, Self::Error> {
Ok(edr_eth::block::BlobGas {
gas_used: BigInt::try_cast(self.gas_used)?,
excess_gas: BigInt::try_cast(self.excess_gas)?,
fn try_from(value: BlobGas) -> Result<Self, Self::Error> {
Ok(Self {
gas_used: BigInt::try_cast(value.gas_used)?,
excess_gas: BigInt::try_cast(value.excess_gas)?,
})
}
}
Expand Down Expand Up @@ -306,7 +306,7 @@ impl TryFrom<BlockHeader> for edr_eth::block::Header {
.withdrawals_root
.map(TryCast::<B256>::try_cast)
.transpose()?,
blob_gas: value.blob_gas.map(BlobGas::try_cast).transpose()?,
blob_gas: value.blob_gas.map(BlobGas::try_into).transpose()?,
parent_beacon_block_root: value
.parent_beacon_block_root
.map(TryCast::<B256>::try_cast)
Expand Down
11 changes: 10 additions & 1 deletion crates/edr_evm_napi/src/blockchain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use napi_derive::napi;

use crate::{
account::{add_precompiles, genesis_accounts, GenesisAccount},
block::Block,
block::{BlobGas, Block},
cast::TryCast,
config::SpecId,
context::EdrContext,
Expand Down Expand Up @@ -71,13 +71,20 @@ impl Blockchain {
timestamp: Option<BigInt>,
prev_randao: Option<Buffer>,
base_fee: Option<BigInt>,
blob_gas: Option<BlobGas>,
parent_beacon_block_root: Option<Buffer>,
) -> napi::Result<Self> {
let chain_id: u64 = chain_id.try_cast()?;
let spec_id = edr_evm::SpecId::from(spec_id);
let gas_limit: u64 = BigInt::try_cast(gas_limit)?;
let timestamp: Option<u64> = timestamp.map(TryCast::<u64>::try_cast).transpose()?;
let prev_randao: Option<B256> = prev_randao.map(TryCast::<B256>::try_cast).transpose()?;
let base_fee: Option<U256> = base_fee.map(TryCast::<U256>::try_cast).transpose()?;
let blob_gas: Option<edr_eth::block::BlobGas> =
blob_gas.map(TryInto::try_into).transpose()?;
let parent_beacon_block_root: Option<B256> = parent_beacon_block_root
.map(TryCast::<B256>::try_cast)
.transpose()?;

let mut accounts = genesis_accounts(accounts)?;
add_precompiles(&mut accounts);
Expand Down Expand Up @@ -105,6 +112,8 @@ impl Blockchain {
timestamp,
prev_randao,
base_fee,
blob_gas,
parent_beacon_block_root,
)
.map_err(|e| napi::Error::new(Status::InvalidArg, e.to_string()))?;

Expand Down
4 changes: 3 additions & 1 deletion crates/edr_provider/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::{path::PathBuf, time::SystemTime};

use edr_eth::{AccountInfo, Address, HashMap, SpecId, U256};
use edr_eth::{block::BlobGas, AccountInfo, Address, HashMap, SpecId, B256, U256};
use rpc_hardhat::config::ForkConfig;

/// Configuration for the provider
Expand All @@ -18,7 +18,9 @@ pub struct ProviderConfig {
pub gas: u64,
pub hardfork: SpecId,
pub initial_base_fee_per_gas: Option<U256>,
pub initial_blob_gas: Option<BlobGas>,
pub initial_date: Option<SystemTime>,
pub initial_parent_beacon_block_root: Option<B256>,
pub network_id: u64,
}

Expand Down
2 changes: 2 additions & 0 deletions crates/edr_provider/src/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -763,6 +763,8 @@ async fn create_blockchain_and_state(
}),
Some(RandomHashGenerator::with_seed("seed").next_value()),
config.initial_base_fee_per_gas,
config.initial_blob_gas.clone(),
config.initial_parent_beacon_block_root,
)?;

let state = blockchain
Expand Down
10 changes: 9 additions & 1 deletion crates/edr_provider/src/test_utils.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
use std::{path::PathBuf, time::SystemTime};

use edr_eth::{signature::secret_key_from_str, AccountInfo, Address, SpecId, U256};
use edr_eth::{
block::BlobGas, signature::secret_key_from_str, trie::KECCAK_NULL_RLP, AccountInfo, Address,
SpecId, U256,
};
use edr_evm::KECCAK_EMPTY;

use super::*;
Expand Down Expand Up @@ -50,7 +53,12 @@ pub fn create_test_config_with_impersonated_accounts(
gas: 30_000_000,
hardfork: SpecId::LATEST,
initial_base_fee_per_gas: Some(U256::from(1000000000)),
initial_blob_gas: Some(BlobGas {
gas_used: 0,
excess_gas: 0,
}),
initial_date: Some(SystemTime::now()),
initial_parent_beacon_block_root: Some(KECCAK_NULL_RLP),
network_id: 123,
cache_dir,
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { privateToAddress, toBuffer } from "@nomicfoundation/ethereumjs-util";
import {
KECCAK256_RLP,
privateToAddress,
toBuffer,
} from "@nomicfoundation/ethereumjs-util";
import { Account, Blockchain, EdrContext, SpecId } from "@ignored/edr";
import { BlockchainAdapter } from "../blockchain";
import { EdrBlockchain } from "../blockchain/edr";
Expand All @@ -13,11 +17,7 @@ import {
ethereumjsMempoolOrderToEdrMineOrdering,
ethereumsjsHardforkToEdrSpecId,
} from "../utils/convertToEdr";
import {
HardforkName,
getHardforkName,
hardforkGte,
} from "../../../util/hardforks";
import { getHardforkName } from "../../../util/hardforks";
import { EdrStateManager } from "../EdrState";
import { EdrMemPool } from "../mem-pool/edr";
import { makeCommon } from "../utils/makeCommon";
Expand Down Expand Up @@ -50,7 +50,6 @@ export class EdrEthContext implements EthContextAdapter {

public static async create(config: NodeConfig): Promise<EdrEthContext> {
const common = makeCommon(config);
const hardforkName = getHardforkName(config.hardfork);

const prevRandaoGenerator =
RandomBufferGenerator.create("randomMixHashSeed");
Expand Down Expand Up @@ -134,28 +133,36 @@ export class EdrEthContext implements EthContextAdapter {

config.forkConfig.blockNumber = Number(latestBlockNumber);
} else {
const isPostLondon = hardforkGte(hardforkName, HardforkName.LONDON);

const initialBaseFeePerGas = isPostLondon
? config.initialBaseFeePerGas !== undefined
? BigInt(config.initialBaseFeePerGas)
: BigInt(HARDHAT_NETWORK_DEFAULT_INITIAL_BASE_FEE_PER_GAS)
: undefined;
const initialBaseFeePerGas =
specId >= SpecId.London
? config.initialBaseFeePerGas !== undefined
? BigInt(config.initialBaseFeePerGas)
: BigInt(HARDHAT_NETWORK_DEFAULT_INITIAL_BASE_FEE_PER_GAS)
: undefined;

const initialBlockTimestamp =
config.initialDate !== undefined
? BigInt(dateToTimestampSeconds(config.initialDate))
: undefined;

const isPostMerge = hardforkGte(hardforkName, HardforkName.MERGE);
const initialMixHash = isPostMerge
? prevRandaoGenerator.next()
: undefined;
const initialMixHash =
specId >= SpecId.Merge ? prevRandaoGenerator.next() : undefined;

const initialBlobGas =
specId >= SpecId.Cancun
? {
gasUsed: 0n,
excessGas: 0n,
}
: undefined;

const initialParentBeaconRoot =
specId >= SpecId.Cancun ? KECCAK256_RLP : undefined;

blockchain = new EdrBlockchain(
new Blockchain(
common.chainId(),
ethereumsjsHardforkToEdrSpecId(hardforkName),
specId,
BigInt(config.blockGasLimit),
config.genesisAccounts.map((account) => {
return {
Expand All @@ -165,7 +172,9 @@ export class EdrEthContext implements EthContextAdapter {
}),
initialBlockTimestamp,
initialMixHash,
initialBaseFeePerGas
initialBaseFeePerGas,
initialBlobGas,
initialParentBeaconRoot
),
irregularState,
common
Expand Down

0 comments on commit 1204f19

Please sign in to comment.