Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(op): use RollupCostData instead of full encoding #1491

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions crates/interpreter/src/gas/calc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,15 @@ pub const fn memory_gas(num_words: u64) -> u64 {
.saturating_add(num_words.saturating_mul(num_words) / 512)
}

/// This counts the number of zero, and non-zero bytes in the input data.
///
/// Returns a tuple of (zero_bytes, non_zero_bytes).
pub fn count_zero_bytes(data: &[u8]) -> (u64, u64) {
let zero_data_len = data.iter().filter(|v| **v == 0).count() as u64;
let non_zero_data_len = data.len() as u64 - zero_data_len;
(zero_data_len, non_zero_data_len)
}

/// Initial gas that is deducted for transaction to be included.
/// Initial gas contains initial stipend gas, gas for access list and input data.
pub fn validate_initial_tx_gas(
Expand All @@ -360,8 +369,7 @@ pub fn validate_initial_tx_gas(
access_list: &[(Address, Vec<U256>)],
) -> u64 {
let mut initial_gas = 0;
let zero_data_len = input.iter().filter(|v| **v == 0).count() as u64;
let non_zero_data_len = input.len() as u64 - zero_data_len;
let (zero_data_len, non_zero_data_len) = count_zero_bytes(input);

// initdate stipend
initial_gas += zero_data_len * TRANSACTION_ZERO_DATA;
Expand Down
4 changes: 3 additions & 1 deletion crates/revm/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,9 @@ alloy-provider = { git = "https://github.com/alloy-rs/alloy.git", rev = "44b8a6d
alloy-transport-http = { git = "https://github.com/alloy-rs/alloy.git", rev = "44b8a6d" }

[features]
default = ["std", "c-kzg", "secp256k1", "portable", "blst"]
# default = ["std", "c-kzg", "secp256k1", "portable", "blst"]
# for developing in editor w op
default = ["std", "c-kzg", "secp256k1", "portable", "blst", "optimism"]
std = [
"serde?/std",
"serde_json?/std",
Expand Down
2 changes: 2 additions & 0 deletions crates/revm/src/optimism.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
mod fast_lz;
mod handler_register;
mod l1block;
mod rollup_cost;

pub use handler_register::{
deduct_caller, end, last_frame_return, load_accounts, load_precompiles,
optimism_handle_register, output, reward_beneficiary, validate_env, validate_tx_against_state,
};
pub use l1block::{L1BlockInfo, BASE_FEE_RECIPIENT, L1_BLOCK_CONTRACT, L1_FEE_RECIPIENT};
pub use rollup_cost::RollupCostData;
96 changes: 48 additions & 48 deletions crates/revm/src/optimism/l1block.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use crate::optimism::fast_lz::flz_compress_len;
use crate::optimism::rollup_cost::RollupCostData;
use crate::primitives::{address, db::Database, Address, SpecId, U256};
use core::ops::Mul;

const ZERO_BYTE_COST: u64 = 4;
const NON_ZERO_BYTE_COST: u64 = 16;
Expand Down Expand Up @@ -124,26 +123,23 @@ impl L1BlockInfo {
///
/// Prior to regolith, an extra 68 non-zero bytes were included in the rollup data costs to
/// account for the empty signature.
pub fn data_gas(&self, input: &[u8], spec_id: SpecId) -> U256 {
pub fn data_gas(&self, cost_data: RollupCostData, spec_id: SpecId) -> u64 {
if spec_id.is_enabled_in(SpecId::FJORD) {
let estimated_size = self.tx_estimated_size_fjord(input);
let estimated_size = self.tx_estimated_size_fjord(cost_data);

return estimated_size
.saturating_mul(U256::from(NON_ZERO_BYTE_COST))
.wrapping_div(U256::from(1_000_000));
return (estimated_size as u64)
.saturating_mul(NON_ZERO_BYTE_COST)
.wrapping_div(1_000_000);
};

let mut rollup_data_gas_cost = U256::from(input.iter().fold(0, |acc, byte| {
acc + if *byte == 0x00 {
ZERO_BYTE_COST
} else {
NON_ZERO_BYTE_COST
}
}));
let mut rollup_data_gas_cost = cost_data
.ones
.saturating_mul(NON_ZERO_BYTE_COST)
.saturating_add(cost_data.zeroes.saturating_mul(ZERO_BYTE_COST));

// Prior to regolith, an extra 68 non zero bytes were included in the rollup data costs.
if !spec_id.is_enabled_in(SpecId::REGOLITH) {
rollup_data_gas_cost += U256::from(NON_ZERO_BYTE_COST).mul(U256::from(68));
rollup_data_gas_cost += NON_ZERO_BYTE_COST * 68;
}

rollup_data_gas_cost
Expand All @@ -152,13 +148,12 @@ impl L1BlockInfo {
// Calculate the estimated compressed transaction size in bytes, scaled by 1e6.
// This value is computed based on the following formula:
// max(minTransactionSize, intercept + fastlzCoef*fastlzSize)
fn tx_estimated_size_fjord(&self, input: &[u8]) -> U256 {
let fastlz_size = U256::from(flz_compress_len(input));

fastlz_size
.saturating_mul(U256::from(836_500))
.saturating_sub(U256::from(42_585_600))
.max(U256::from(100_000_000))
fn tx_estimated_size_fjord(&self, cost_data: RollupCostData) -> u32 {
cost_data
.fastlz_size
.saturating_mul(836_500)
.saturating_sub(42_585_600)
.max(100_000_000)
}

/// Calculate the gas cost of a transaction based on L1 block data posted on L2, depending on the [SpecId] passed.
Expand All @@ -168,19 +163,22 @@ impl L1BlockInfo {
return U256::ZERO;
}

// let's create a `RollupCostData` to make the computation easier
let cost_data = RollupCostData::from_bytes(input);

if spec_id.is_enabled_in(SpecId::FJORD) {
self.calculate_tx_l1_cost_fjord(input)
self.calculate_tx_l1_cost_fjord(cost_data)
} else if spec_id.is_enabled_in(SpecId::ECOTONE) {
self.calculate_tx_l1_cost_ecotone(input, spec_id)
self.calculate_tx_l1_cost_ecotone(cost_data, spec_id)
} else {
self.calculate_tx_l1_cost_bedrock(input, spec_id)
self.calculate_tx_l1_cost_bedrock(cost_data, spec_id)
}
}

/// Calculate the gas cost of a transaction based on L1 block data posted on L2, pre-Ecotone.
fn calculate_tx_l1_cost_bedrock(&self, input: &[u8], spec_id: SpecId) -> U256 {
let rollup_data_gas_cost = self.data_gas(input, spec_id);
rollup_data_gas_cost
fn calculate_tx_l1_cost_bedrock(&self, cost_data: RollupCostData, spec_id: SpecId) -> U256 {
let rollup_data_gas_cost = self.data_gas(cost_data, spec_id);
U256::from(rollup_data_gas_cost)
.saturating_add(self.l1_fee_overhead.unwrap_or_default())
.saturating_mul(self.l1_base_fee)
.saturating_mul(self.l1_base_fee_scalar)
Expand All @@ -197,31 +195,31 @@ impl L1BlockInfo {
///
/// Function is actually computed as follows for better precision under integer arithmetic:
/// `calldataGas*(l1BaseFee*16*l1BaseFeeScalar + l1BlobBaseFee*l1BlobBaseFeeScalar)/16e6`
fn calculate_tx_l1_cost_ecotone(&self, input: &[u8], spec_id: SpecId) -> U256 {
fn calculate_tx_l1_cost_ecotone(&self, cost_data: RollupCostData, spec_id: SpecId) -> U256 {
// There is an edgecase where, for the very first Ecotone block (unless it is activated at Genesis), we must
// use the Bedrock cost function. To determine if this is the case, we can check if the Ecotone parameters are
// unset.
if self.empty_scalars {
return self.calculate_tx_l1_cost_bedrock(input, spec_id);
return self.calculate_tx_l1_cost_bedrock(cost_data, spec_id);
}

let rollup_data_gas_cost = self.data_gas(input, spec_id);
let rollup_data_gas_cost = self.data_gas(cost_data, spec_id);
let l1_fee_scaled = self.calculate_l1_fee_scaled_ecotone();

l1_fee_scaled
.saturating_mul(rollup_data_gas_cost)
U256::from(l1_fee_scaled)
.saturating_mul(U256::from(rollup_data_gas_cost))
.wrapping_div(U256::from(1_000_000 * NON_ZERO_BYTE_COST))
}

/// Calculate the gas cost of a transaction based on L1 block data posted on L2, post-Fjord.
///
/// [SpecId::FJORD] L1 cost function:
/// `estimatedSize*(baseFeeScalar*l1BaseFee*16 + blobFeeScalar*l1BlobBaseFee)/1e12`
fn calculate_tx_l1_cost_fjord(&self, input: &[u8]) -> U256 {
fn calculate_tx_l1_cost_fjord(&self, cost_data: RollupCostData) -> U256 {
let l1_fee_scaled = self.calculate_l1_fee_scaled_ecotone();
let estimated_size = self.tx_estimated_size_fjord(input);
let estimated_size = self.tx_estimated_size_fjord(cost_data);

estimated_size
U256::from(estimated_size)
.saturating_mul(l1_fee_scaled)
.wrapping_div(U256::from(1e12))
}
Expand Down Expand Up @@ -262,18 +260,19 @@ mod tests {
// gas cost = 3 non-zero bytes * NON_ZERO_BYTE_COST + NON_ZERO_BYTE_COST * 68
// gas cost = 3 * 16 + 68 * 16 = 1136
let input = bytes!("FACADE");
let bedrock_data_gas = l1_block_info.data_gas(&input, SpecId::BEDROCK);
assert_eq!(bedrock_data_gas, U256::from(1136));
let cost_data = RollupCostData::from_bytes(&input);
let bedrock_data_gas = l1_block_info.data_gas(cost_data, SpecId::BEDROCK);
assert_eq!(bedrock_data_gas, 1136);

// Regolith has no added 68 non zero bytes
// gas cost = 3 * 16 = 48
let regolith_data_gas = l1_block_info.data_gas(&input, SpecId::REGOLITH);
assert_eq!(regolith_data_gas, U256::from(48));
let regolith_data_gas = l1_block_info.data_gas(cost_data, SpecId::REGOLITH);
assert_eq!(regolith_data_gas, 48);

// Fjord has a minimum compressed size of 100 bytes
// gas cost = 100 * 16 = 1600
let fjord_data_gas = l1_block_info.data_gas(&input, SpecId::FJORD);
assert_eq!(fjord_data_gas, U256::from(1600));
let fjord_data_gas = l1_block_info.data_gas(cost_data, SpecId::FJORD);
assert_eq!(fjord_data_gas, 1600);
}

#[test]
Expand All @@ -292,18 +291,19 @@ mod tests {
// gas cost = 3 non-zero * NON_ZERO_BYTE_COST + 2 * ZERO_BYTE_COST + NON_ZERO_BYTE_COST * 68
// gas cost = 3 * 16 + 2 * 4 + 68 * 16 = 1144
let input = bytes!("FA00CA00DE");
let bedrock_data_gas = l1_block_info.data_gas(&input, SpecId::BEDROCK);
assert_eq!(bedrock_data_gas, U256::from(1144));
let cost_data = RollupCostData::from_bytes(&input);
let bedrock_data_gas = l1_block_info.data_gas(cost_data, SpecId::BEDROCK);
assert_eq!(bedrock_data_gas, 1144);

// Regolith has no added 68 non zero bytes
// gas cost = 3 * 16 + 2 * 4 = 56
let regolith_data_gas = l1_block_info.data_gas(&input, SpecId::REGOLITH);
assert_eq!(regolith_data_gas, U256::from(56));
let regolith_data_gas = l1_block_info.data_gas(cost_data, SpecId::REGOLITH);
assert_eq!(regolith_data_gas, 56);

// Fjord has a minimum compressed size of 100 bytes
// gas cost = 100 * 16 = 1600
let fjord_data_gas = l1_block_info.data_gas(&input, SpecId::FJORD);
assert_eq!(fjord_data_gas, U256::from(1600));
let fjord_data_gas = l1_block_info.data_gas(cost_data, SpecId::FJORD);
assert_eq!(fjord_data_gas, 1600);
}

#[test]
Expand Down
34 changes: 34 additions & 0 deletions crates/revm/src/optimism/rollup_cost.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
//! This contains a struct, [`RollupCostData`], that is used to compute the data availability costs
//! for a transaction.

use crate::optimism::fast_lz::flz_compress_len;
use revm_interpreter::gas::count_zero_bytes;

/// RollupCostData contains three fields, which are used depending on the current optimism fork.
///
/// The `zeroes` and `ones` fields are used to compute the data availability costs for a
/// transaction pre-fjord.
///
/// The `fastlz_size` field is used to compute the data availability costs for a transaction
/// post-fjord.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RollupCostData {
/// The number of zeroes in the transaction.
pub(crate) zeroes: u64,
/// The number of ones in the transaction.
pub(crate) ones: u64,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

non-zero

/// The size of the transaction after fastLZ compression.
pub(crate) fastlz_size: u32,
}

impl RollupCostData {
/// This takes bytes as input, creating a [`RollupCostData`] struct based on the encoded data.
pub fn from_bytes(bytes: &[u8]) -> Self {
let (zeroes, ones) = count_zero_bytes(bytes);
Self {
zeroes,
ones,
fastlz_size: flz_compress_len(bytes),
}
}
}
Loading