Skip to content

Commit

Permalink
num-audit: extension (#474)
Browse files Browse the repository at this point in the history
* num-audit: extension
* gas related field to `u128`
* `nonce` and `number` to `u64` in `Header` from `B64` and `U256` respectively

* num-audit: gas fields to `u128` in Genesis

* num-audit: use primitive types in rpc-types: common, optimism, receipt, request

* fix(rpc-types): request tests

* fix(rpc-types): optimism tests

* add serde attr and fix rpc-types tests

* timestamp -> `u64` in rpc-types `block`

* nit

* serde attr nits

* skip_serializing nits

* rpc-types: make `gas_used` required in receipt

* fix: gas filler tests
  • Loading branch information
yash-atreya authored Apr 8, 2024
1 parent da41ddb commit cd5a2c7
Show file tree
Hide file tree
Showing 17 changed files with 200 additions and 148 deletions.
36 changes: 18 additions & 18 deletions crates/consensus/src/header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,9 @@ pub struct Header {
/// zero; formally Hi.
pub number: BlockNumber,
/// A scalar value equal to the current limit of gas expenditure per block; formally Hl.
pub gas_limit: u64,
pub gas_limit: u128,
/// A scalar value equal to the total gas used in transactions in this block; formally Hg.
pub gas_used: u64,
pub gas_used: u128,
/// A scalar value equal to the reasonable output of Unix’s time() at this block’s inception;
/// formally Hs.
pub timestamp: u64,
Expand All @@ -73,14 +73,14 @@ pub struct Header {
/// The algorithm results in the base fee per gas increasing when blocks are
/// above the gas target, and decreasing when blocks are below the gas target. The base fee per
/// gas is burned.
pub base_fee_per_gas: Option<u64>,
pub base_fee_per_gas: Option<u128>,
/// The total amount of blob gas consumed by the transactions within the block, added in
/// EIP-4844.
pub blob_gas_used: Option<u64>,
pub blob_gas_used: Option<u128>,
/// A running total of blob gas consumed in excess of the target, prior to the block. Blocks
/// with above-target blob gas consumption increase this value, blocks with below-target blob
/// gas consumption decrease it (bounded at 0). This was added in EIP-4844.
pub excess_blob_gas: Option<u64>,
pub excess_blob_gas: Option<u128>,
/// The hash of the parent beacon block's root is included in execution blocks, as proposed by
/// EIP-4788.
///
Expand Down Expand Up @@ -194,7 +194,7 @@ impl Header {
/// Calculate base fee for next block according to the EIP-1559 spec.
///
/// Returns a `None` if no base fee is set, no EIP-1559 support
pub fn next_block_base_fee(&self, base_fee_params: BaseFeeParams) -> Option<u64> {
pub fn next_block_base_fee(&self, base_fee_params: BaseFeeParams) -> Option<u128> {
Some(calc_next_block_base_fee(
self.gas_used,
self.gas_limit,
Expand All @@ -207,7 +207,7 @@ impl Header {
/// spec.
///
/// Returns a `None` if no excess blob gas is set, no EIP-4844 support
pub fn next_block_excess_blob_gas(&self) -> Option<u64> {
pub fn next_block_excess_blob_gas(&self) -> Option<u128> {
Some(calc_excess_blob_gas(self.excess_blob_gas?, self.blob_gas_used?))
}

Expand All @@ -224,14 +224,14 @@ impl Header {
mem::size_of::<Bloom>() + // logs bloom
mem::size_of::<U256>() + // difficulty
mem::size_of::<BlockNumber>() + // number
mem::size_of::<u64>() + // gas limit
mem::size_of::<u64>() + // gas used
mem::size_of::<u128>() + // gas limit
mem::size_of::<u128>() + // gas used
mem::size_of::<u64>() + // timestamp
mem::size_of::<B256>() + // mix hash
mem::size_of::<u64>() + // nonce
mem::size_of::<Option<u64>>() + // base fee per gas
mem::size_of::<Option<u64>>() + // blob gas used
mem::size_of::<Option<u64>>() + // excess blob gas
mem::size_of::<Option<u128>>() + // base fee per gas
mem::size_of::<Option<u128>>() + // blob gas used
mem::size_of::<Option<u128>>() + // excess blob gas
mem::size_of::<Option<B256>>() + // parent beacon block root
self.extra_data.len() // extra data
}
Expand Down Expand Up @@ -396,9 +396,9 @@ impl Decodable for Header {
receipts_root: Decodable::decode(buf)?,
logs_bloom: Decodable::decode(buf)?,
difficulty: Decodable::decode(buf)?,
number: U256::decode(buf)?.to::<u64>(),
gas_limit: U256::decode(buf)?.to::<u64>(),
gas_used: U256::decode(buf)?.to::<u64>(),
number: u64::decode(buf)?,
gas_limit: u128::decode(buf)?,
gas_used: u128::decode(buf)?,
timestamp: Decodable::decode(buf)?,
extra_data: Decodable::decode(buf)?,
mix_hash: Decodable::decode(buf)?,
Expand All @@ -414,7 +414,7 @@ impl Decodable for Header {
if buf.first().map(|b| *b == EMPTY_LIST_CODE).unwrap_or_default() {
buf.advance(1)
} else {
this.base_fee_per_gas = Some(U256::decode(buf)?.to::<u64>());
this.base_fee_per_gas = Some(U256::decode(buf)?.to::<u128>());
}
}

Expand All @@ -432,15 +432,15 @@ impl Decodable for Header {
if buf.first().map(|b| *b == EMPTY_LIST_CODE).unwrap_or_default() {
buf.advance(1)
} else {
this.blob_gas_used = Some(U256::decode(buf)?.to::<u64>());
this.blob_gas_used = Some(U256::decode(buf)?.to::<u128>());
}
}

if started_len - buf.len() < rlp_head.payload_length {
if buf.first().map(|b| *b == EMPTY_LIST_CODE).unwrap_or_default() {
buf.advance(1)
} else {
this.excess_blob_gas = Some(U256::decode(buf)?.to::<u64>());
this.excess_blob_gas = Some(U256::decode(buf)?.to::<u128>());
}
}

Expand Down
2 changes: 1 addition & 1 deletion crates/consensus/src/receipt/any.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ impl AnyReceiptEnvelope {
}

/// Returns the cumulative gas used at this receipt.
pub const fn cumulative_gas_used(&self) -> u64 {
pub const fn cumulative_gas_used(&self) -> u128 {
self.inner.receipt.cumulative_gas_used
}

Expand Down
2 changes: 1 addition & 1 deletion crates/consensus/src/receipt/envelope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ impl<T> ReceiptEnvelope<T> {
}

/// Returns the cumulative gas used at this receipt.
pub fn cumulative_gas_used(&self) -> u64 {
pub fn cumulative_gas_used(&self) -> u128 {
self.as_receipt().unwrap().cumulative_gas_used
}

Expand Down
6 changes: 3 additions & 3 deletions crates/consensus/src/receipt/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ pub trait TxReceipt {
}

/// Returns the cumulative gas used in the block after this transaction was executed.
fn cumulative_gas_used(&self) -> u64;
fn cumulative_gas_used(&self) -> u128;

/// Returns the logs emitted by this transaction.
fn logs(&self) -> &[Log];
Expand All @@ -47,7 +47,7 @@ mod tests {
let receipt =
ReceiptEnvelope::Legacy(ReceiptWithBloom {
receipt: Receipt {
cumulative_gas_used: 0x1u64,
cumulative_gas_used: 0x1u128,
logs: vec![Log {
address: address!("0000000000000000000000000000000000000011"),
data: LogData::new_unchecked(
Expand Down Expand Up @@ -79,7 +79,7 @@ mod tests {
let expected =
ReceiptWithBloom {
receipt: Receipt {
cumulative_gas_used: 0x1u64,
cumulative_gas_used: 0x1u128,
logs: vec![Log {
address: address!("0000000000000000000000000000000000000011"),
data: LogData::new_unchecked(
Expand Down
8 changes: 4 additions & 4 deletions crates/consensus/src/receipt/receipts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ pub struct Receipt<T = Log> {
#[cfg_attr(feature = "serde", serde(with = "alloy_serde::quantity_bool"))]
pub status: bool,
/// Gas used
#[cfg_attr(feature = "serde", serde(with = "alloy_serde::u64_hex"))]
pub cumulative_gas_used: u64,
#[cfg_attr(feature = "serde", serde(with = "alloy_serde::u128_hex_or_decimal"))]
pub cumulative_gas_used: u128,
/// Log send from contracts.
pub logs: Vec<T>,
}
Expand Down Expand Up @@ -46,7 +46,7 @@ impl TxReceipt for Receipt {
self.bloom_slow()
}

fn cumulative_gas_used(&self) -> u64 {
fn cumulative_gas_used(&self) -> u128 {
self.cumulative_gas_used
}

Expand Down Expand Up @@ -85,7 +85,7 @@ impl TxReceipt for ReceiptWithBloom {
Some(self.logs_bloom)
}

fn cumulative_gas_used(&self) -> u64 {
fn cumulative_gas_used(&self) -> u128 {
self.receipt.cumulative_gas_used
}

Expand Down
10 changes: 6 additions & 4 deletions crates/eips/src/eip1559/basefee.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,19 @@ use crate::eip1559::constants::{
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct BaseFeeParams {
/// The base_fee_max_change_denominator from EIP-1559
pub max_change_denominator: u64,
#[cfg_attr(feature = "serde", serde(with = "alloy_serde::num::u128_hex_or_decimal"))]
pub max_change_denominator: u128,
/// The elasticity multiplier from EIP-1559
pub elasticity_multiplier: u64,
#[cfg_attr(feature = "serde", serde(with = "alloy_serde::num::u128_hex_or_decimal"))]
pub elasticity_multiplier: u128,
}

impl BaseFeeParams {
/// Get the base fee parameters for Ethereum mainnet
pub const fn ethereum() -> BaseFeeParams {
BaseFeeParams {
max_change_denominator: DEFAULT_BASE_FEE_MAX_CHANGE_DENOMINATOR,
elasticity_multiplier: DEFAULT_ELASTICITY_MULTIPLIER,
max_change_denominator: DEFAULT_BASE_FEE_MAX_CHANGE_DENOMINATOR as u128,
elasticity_multiplier: DEFAULT_ELASTICITY_MULTIPLIER as u128,
}
}
}
19 changes: 9 additions & 10 deletions crates/eips/src/eip1559/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,11 @@ use crate::eip1559::BaseFeeParams;
///
/// For more information, refer to the [EIP-1559 spec](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md).
pub fn calc_next_block_base_fee(
gas_used: u64,
gas_limit: u64,
base_fee: u64,
gas_used: u128,
gas_limit: u128,
base_fee: u128,
base_fee_params: BaseFeeParams,
) -> u64 {
) -> u128 {
// Calculate the target gas by dividing the gas limit by the elasticity multiplier.
let gas_target = gas_limit / base_fee_params.elasticity_multiplier;

Expand All @@ -44,18 +44,17 @@ pub fn calc_next_block_base_fee(
+ (core::cmp::max(
// Ensure a minimum increase of 1.
1,
base_fee as u128 * (gas_used - gas_target) as u128
/ (gas_target as u128 * base_fee_params.max_change_denominator as u128),
) as u64)
base_fee * (gas_used - gas_target)
/ (gas_target * base_fee_params.max_change_denominator),
))
}
// If the gas used in the current block is less than the gas target, calculate a new
// decreased base fee.
core::cmp::Ordering::Less => {
// Calculate the decrease in base fee based on the formula defined by EIP-1559.
base_fee.saturating_sub(
(base_fee as u128 * (gas_target - gas_used) as u128
/ (gas_target as u128 * base_fee_params.max_change_denominator as u128))
as u64,
base_fee * (gas_target - gas_used)
/ (gas_target * base_fee_params.max_change_denominator),
)
}
}
Expand Down
31 changes: 14 additions & 17 deletions crates/eips/src/eip4844/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ pub const MAX_BLOBS_PER_BLOCK: usize = (MAX_DATA_GAS_PER_BLOCK / DATA_GAS_PER_BL
pub const TARGET_BLOBS_PER_BLOCK: u64 = TARGET_DATA_GAS_PER_BLOCK / DATA_GAS_PER_BLOB; // 393216 / 131072 = 3

/// Determines the maximum rate of change for blob fee
pub const BLOB_GASPRICE_UPDATE_FRACTION: u64 = 3_338_477u64; // 3338477
pub const BLOB_GASPRICE_UPDATE_FRACTION: u128 = 3_338_477u128; // 3338477

/// Minimum gas price for a data blob
pub const BLOB_TX_MIN_BLOB_GASPRICE: u128 = 1u128;
Expand All @@ -80,21 +80,21 @@ pub type Bytes48 = FixedBytes<48>;
/// See also [the EIP-4844 helpers](https://eips.ethereum.org/EIPS/eip-4844#helpers)
/// (`calc_excess_blob_gas`).
#[inline]
pub const fn calc_excess_blob_gas(parent_excess_blob_gas: u64, parent_blob_gas_used: u64) -> u64 {
(parent_excess_blob_gas + parent_blob_gas_used).saturating_sub(TARGET_DATA_GAS_PER_BLOCK)
pub const fn calc_excess_blob_gas(
parent_excess_blob_gas: u128,
parent_blob_gas_used: u128,
) -> u128 {
(parent_excess_blob_gas + parent_blob_gas_used)
.saturating_sub(TARGET_DATA_GAS_PER_BLOCK as u128)
}

/// Calculates the blob gas price from the header's excess blob gas field.
///
/// See also [the EIP-4844 helpers](https://eips.ethereum.org/EIPS/eip-4844#helpers)
/// (`get_blob_gasprice`).
#[inline]
pub fn calc_blob_gasprice(excess_blob_gas: u64) -> u128 {
fake_exponential(
BLOB_TX_MIN_BLOB_GASPRICE as u64,
excess_blob_gas,
BLOB_GASPRICE_UPDATE_FRACTION,
)
pub fn calc_blob_gasprice(excess_blob_gas: u128) -> u128 {
fake_exponential(BLOB_TX_MIN_BLOB_GASPRICE, excess_blob_gas, BLOB_GASPRICE_UPDATE_FRACTION)
}

/// Approximates `factor * e ** (numerator / denominator)` using Taylor expansion.
Expand All @@ -108,11 +108,8 @@ pub fn calc_blob_gasprice(excess_blob_gas: u64) -> u128 {
///
/// This function panics if `denominator` is zero.
#[inline]
fn fake_exponential(factor: u64, numerator: u64, denominator: u64) -> u128 {
fn fake_exponential(factor: u128, numerator: u128, denominator: u128) -> u128 {
assert_ne!(denominator, 0, "attempt to divide by zero");
let factor = factor as u128;
let numerator = numerator as u128;
let denominator = denominator as u128;

let mut i = 1;
let mut output = 0;
Expand Down Expand Up @@ -164,8 +161,8 @@ mod tests {
),
(DATA_GAS_PER_BLOB - 1, (TARGET_DATA_GAS_PER_BLOCK / DATA_GAS_PER_BLOB) - 1, 0),
] {
let actual = calc_excess_blob_gas(excess, blobs * DATA_GAS_PER_BLOB);
assert_eq!(actual, expected, "test: {t:?}");
let actual = calc_excess_blob_gas(excess as u128, (blobs * DATA_GAS_PER_BLOB) as u128);
assert_eq!(actual, expected as u128, "test: {t:?}");
}
}

Expand Down Expand Up @@ -213,9 +210,9 @@ mod tests {
(1, 5, 2, 11), // approximate 12.18
(2, 5, 2, 23), // approximate 24.36
(1, 50000000, 2225652, 5709098764),
(1, 380928, BLOB_GASPRICE_UPDATE_FRACTION, 1),
(1, 380928, BLOB_GASPRICE_UPDATE_FRACTION.try_into().unwrap(), 1),
] {
let actual = fake_exponential(factor, numerator, denominator);
let actual = fake_exponential(factor as u128, numerator as u128, denominator as u128);
assert_eq!(actual, expected, "test: {t:?}");
}
}
Expand Down
Loading

0 comments on commit cd5a2c7

Please sign in to comment.