Skip to content

Commit

Permalink
cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
rakita committed Nov 28, 2024
1 parent b2999ec commit a4fa635
Show file tree
Hide file tree
Showing 25 changed files with 92 additions and 92 deletions.
1 change: 0 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion crates/context/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ database-interface.workspace = true
state.workspace = true
specification.workspace = true
bytecode.workspace = true
database = { workspace = true, optional = true }

# misc
derive-where.workspace = true
Expand Down
1 change: 0 additions & 1 deletion crates/handler/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ primitives.workspace = true
state.workspace = true
specification.workspace = true
bytecode.workspace = true
database = { workspace = true, optional = true }
handler-interface.workspace = true

# Optional
Expand Down
30 changes: 2 additions & 28 deletions crates/handler/interface/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,36 +26,10 @@ all = "warn"
primitives.workspace = true
interpreter.workspace = true


# Optional
serde = { version = "1.0", default-features = false, features = [
"derive",
"rc",
], optional = true }

[dev-dependencies]
database.workspace = true

[features]
default = ["std"]
std = ["serde?/std"]
serde = ["dep:serde", "primitives/serde"]
serde-json = ["serde"]

# Enable additional features for development
# They add functions to Cfg trait.
dev = [
"memory_limit",
"optional_balance_check",
"optional_block_gas_limit",
"optional_eip3607",
"optional_gas_refund",
"optional_no_base_fee",

]
memory_limit = []
optional_balance_check = []
optional_block_gas_limit = []
optional_eip3607 = []
optional_gas_refund = []
optional_no_base_fee = []
std = []
serde = ["std", "primitives/serde", "interpreter/serde"]
3 changes: 2 additions & 1 deletion crates/handler/interface/src/execution.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::util::FrameOrFrameResult;
pub use crate::{Frame, FrameOrResultGen};
pub use std::{vec, vec::Vec};

Expand All @@ -12,7 +13,7 @@ pub trait ExecutionHandler {
&mut self,
context: &mut Self::Context,
gas_limit: u64,
) -> Result<FrameOrResultGen<Self::Frame, <Self::Frame as Frame>::FrameResult>, Self::Error>;
) -> Result<FrameOrFrameResult<Self::Frame>, Self::Error>;

/// Execute create.
fn last_frame_result(
Expand Down
4 changes: 4 additions & 0 deletions crates/handler/interface/src/util.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use crate::Frame;

pub enum FrameOrResultGen<Frame, Result> {
Frame(Frame),
Result(Result),
Expand All @@ -18,3 +20,5 @@ impl<F, R> FrameOrResultGen<F, R> {
}
}
}

pub type FrameOrFrameResult<FRAME> = FrameOrResultGen<FRAME, <FRAME as Frame>::FrameResult>;
7 changes: 3 additions & 4 deletions crates/handler/src/execution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use context_interface::{
result::InvalidTransaction, BlockGetter, Cfg, CfgGetter, ErrorGetter, JournalStateGetter,
JournalStateGetterDBError, Transaction, TransactionGetter,
};
use handler_interface::{ExecutionHandler, Frame as FrameTrait, FrameOrResultGen};
use handler_interface::{util::FrameOrFrameResult, ExecutionHandler, Frame as FrameTrait};
use interpreter::{
interpreter::{EthInstructionProvider, EthInterpreter},
CallInputs, CallScheme, CallValue, CreateInputs, CreateScheme, EOFCreateInputs, EOFCreateKind,
Expand Down Expand Up @@ -49,8 +49,7 @@ where
&mut self,
context: &mut Self::Context,
gas_limit: u64,
) -> Result<FrameOrResultGen<Self::Frame, <Self::Frame as FrameTrait>::FrameResult>, Self::Error>
{
) -> Result<FrameOrFrameResult<Self::Frame>, Self::Error> {
// Make new frame action.
let spec = context.cfg().spec().into();
let tx = context.tx();
Expand Down Expand Up @@ -113,7 +112,7 @@ where
gas.record_refund(refunded);
}

Ok(frame_result.into())
Ok(frame_result)
}
}

Expand Down
8 changes: 3 additions & 5 deletions crates/handler/src/frame.rs
Original file line number Diff line number Diff line change
Expand Up @@ -651,12 +651,10 @@ where
return_revert!() => U256::from(1),
_ => U256::from(2),
}
} else if ins_result.is_ok() {
U256::from(1)
} else {
if ins_result.is_ok() {
U256::from(1)
} else {
U256::ZERO
}
U256::ZERO
}
};
// Safe to push without stack limit check
Expand Down
2 changes: 1 addition & 1 deletion crates/handler/src/pre_execution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ pub fn apply_eip7702_auth_list<
};

// 2. Verify the chain id is either 0 or the chain's current ID.
if !(authorization.chain_id == 0) && authorization.chain_id != chain_id {
if authorization.chain_id != 0 && authorization.chain_id != chain_id {
continue;
}

Expand Down
17 changes: 6 additions & 11 deletions crates/handler/src/validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,7 @@ where

fn validate_initial_tx_gas(&self, ctx: &Self::Context) -> Result<u64, Self::Error> {
let spec = ctx.cfg().spec().into();
validate_initial_tx_gas::<&Self::Context, InvalidTransaction>(&ctx, spec)
.map_err(Into::into)
validate_initial_tx_gas::<&Self::Context, InvalidTransaction>(ctx, spec).map_err(Into::into)
}
}

Expand Down Expand Up @@ -327,16 +326,12 @@ where

// Check if account has enough balance for `gas_limit * max_fee`` and value transfer.
// Transfer will be done inside `*_inner` functions.
if balance_check > account.info.balance {
if !ctx.cfg().is_balance_check_disabled() {
return Err(InvalidTransaction::LackOfFundForMaxFee {
fee: Box::new(balance_check),
balance: Box::new(account.info.balance),
}
.into());
if balance_check > account.info.balance && !ctx.cfg().is_balance_check_disabled() {
return Err(InvalidTransaction::LackOfFundForMaxFee {
fee: Box::new(balance_check),
balance: Box::new(account.info.balance),
}
// TODO wiring Add transaction cost to balance to ensure execution doesn't fail.
// else { account.info.balance = account.info.balance.saturating_add(balance_check)};
.into());
}

Ok(())
Expand Down
2 changes: 1 addition & 1 deletion crates/inspector/src/eip3155.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ pub trait CloneStack {

impl CloneStack for Stack {
fn clone_from(&self) -> Vec<U256> {
self.data().iter().map(|b| b.clone()).collect()
self.data().to_vec()
}
}

Expand Down
6 changes: 6 additions & 0 deletions crates/inspector/src/gas.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ pub struct GasInspector<CTX, INTR> {
_phantom: core::marker::PhantomData<(CTX, INTR)>,
}

impl<CTX, INTR> Default for GasInspector<CTX, INTR> {
fn default() -> Self {
Self::new()
}
}

impl<CTX, INTR> GasInspector<CTX, INTR> {
pub fn gas_remaining(&self) -> u64 {
self.gas_remaining
Expand Down
22 changes: 15 additions & 7 deletions crates/inspector/src/inspector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,12 @@ pub struct StepPrintInspector<CTX> {
_phantom: core::marker::PhantomData<CTX>,
}

impl<CTX> Default for StepPrintInspector<CTX> {
fn default() -> Self {
Self::new()
}
}

impl<CTX> StepPrintInspector<CTX> {
pub fn new() -> Self {
Self {
Expand Down Expand Up @@ -557,9 +563,7 @@ where
}

fn from_base(instruction: Instruction<Self::Wire, Self::Host>) -> Self {
Self {
instruction: instruction,
}
Self { instruction }
}
}

Expand Down Expand Up @@ -615,14 +619,18 @@ where
unsafe { MaybeUninit::uninit().assume_init() };

for (i, element) in table.iter_mut().enumerate() {
let foo = InspectorInstruction {
let function = InspectorInstruction {
instruction: main_table[i],
};
*element = MaybeUninit::new(foo);
*element = MaybeUninit::new(function);
}

let mut table =
unsafe { core::mem::transmute::<_, [InspectorInstruction<WIRE, HOST>; 256]>(table) };
let mut table = unsafe {
core::mem::transmute::<
[MaybeUninit<InspectorInstruction<WIRE, HOST>>; 256],
[InspectorInstruction<WIRE, HOST>; 256],
>(table)
};

// inspector log wrapper

Expand Down
4 changes: 2 additions & 2 deletions crates/interpreter/src/instructions/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ pub fn return_contract<H: Host + ?Sized>(
let output: Bytes = output.into();

let result = InstructionResult::ReturnContract;
let gas = interpreter.control.gas().clone();
let gas = *interpreter.control.gas();
interpreter.control.set_next_action(
crate::InterpreterAction::Return {
result: InterpreterResult {
Expand Down Expand Up @@ -398,7 +398,7 @@ pub fn create<WIRE: InterpreterTypes, const IS_CREATE2: bool, H: Host + ?Sized>(
let scheme = if IS_CREATE2 {
popn!([salt], interpreter);
// SAFETY: len is reasonable in size as gas for it is already deducted.
gas_or_fail!(interpreter, gas::create2_cost(len.try_into().unwrap()));
gas_or_fail!(interpreter, gas::create2_cost(len));
CreateScheme::Create2 { salt }
} else {
gas!(interpreter, gas::CREATE);
Expand Down
2 changes: 1 addition & 1 deletion crates/interpreter/src/instructions/control.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ fn return_inner(
output = interpreter.memory.slice_len(offset, len).to_vec().into()
}

let gas = interpreter.control.gas().clone();
let gas = *interpreter.control.gas();
interpreter.control.set_next_action(
InterpreterAction::Return {
result: InterpreterResult {
Expand Down
2 changes: 1 addition & 1 deletion crates/interpreter/src/interpreter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ impl<IW: InterpreterTypes> Interpreter<IW> {
result: self.control.instruction_result(),
// return empty bytecode
output: Bytes::new(),
gas: self.control.gas().clone(),
gas: *self.control.gas(),
},
}
}
Expand Down
9 changes: 3 additions & 6 deletions crates/interpreter/src/interpreter/ext_bytecode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,15 +101,13 @@ impl EofCodeInfo for ExtBytecode {
fn code_section_info(&self, idx: usize) -> Option<&TypesSection> {
self.base
.eof()
.map(|eof| eof.body.types_section.get(idx))
.flatten()
.and_then(|eof| eof.body.types_section.get(idx))
}

fn code_section_pc(&self, idx: usize) -> Option<usize> {
self.base
.eof()
.map(|eof| eof.body.eof_code_section_start(idx))
.flatten()
.and_then(|eof| eof.body.eof_code_section_start(idx))
}
}

Expand All @@ -131,8 +129,7 @@ impl EofContainer for ExtBytecode {
fn eof_container(&self, index: usize) -> Option<&Bytes> {
self.base
.eof()
.map(|eof| eof.body.container_section.get(index))
.flatten()
.and_then(|eof| eof.body.container_section.get(index))
}
}

Expand Down
16 changes: 13 additions & 3 deletions crates/interpreter/src/interpreter/stack.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,11 @@ impl Stack {
self.data.get_unchecked_mut(len - 1)
}

/// Pops `N` values from the stack.
///
/// # Safety
///
/// The caller is responsible for checking the length of the stack.
#[inline]
#[cfg_attr(debug_assertions, track_caller)]
pub unsafe fn popn<const N: usize>(&mut self) -> [U256; N] {
Expand All @@ -167,6 +172,11 @@ impl Stack {
result
}

/// Pops `N` values from the stack and returns the top of the stack.
///
/// # Safety
///
/// The caller is responsible for checking the length of the stack.
#[inline]
#[cfg_attr(debug_assertions, track_caller)]
pub unsafe fn popn_top<const POPN: usize>(&mut self) -> ([U256; POPN], &mut U256) {
Expand Down Expand Up @@ -439,23 +449,23 @@ mod tests {
// Test cloning a partially filled stack
let mut partial_stack = Stack::new();
for i in 0..10 {
assert_eq!(partial_stack.push(U256::from(i)), true);
assert!(partial_stack.push(U256::from(i)));
}
let mut cloned_partial = partial_stack.clone();
assert_eq!(partial_stack, cloned_partial);
assert_eq!(cloned_partial.len(), 10);
assert_eq!(cloned_partial.data().capacity(), STACK_LIMIT);

// Test that modifying the clone doesn't affect the original
assert_eq!(cloned_partial.push(U256::from(100)), true);
assert!(cloned_partial.push(U256::from(100)));
assert_ne!(partial_stack, cloned_partial);
assert_eq!(partial_stack.len(), 10);
assert_eq!(cloned_partial.len(), 11);

// Test cloning a full stack
let mut full_stack = Stack::new();
for i in 0..STACK_LIMIT {
assert_eq!(full_stack.push(U256::from(i)), true);
assert!(full_stack.push(U256::from(i)));
}
let mut cloned_full = full_stack.clone();
assert_eq!(full_stack, cloned_full);
Expand Down
9 changes: 9 additions & 0 deletions crates/interpreter/src/interpreter_wiring.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,10 @@ pub trait EofContainer {
pub trait SubRoutineStack {
fn len(&self) -> usize;

fn is_empty(&self) -> bool {
self.len() == 0
}

fn routine_idx(&self) -> usize;

/// Sets new code section without touching subroutine stack.
Expand All @@ -102,6 +106,11 @@ pub trait StackTrait {
/// Returns stack length.
fn len(&self) -> usize;

/// Returns `true` if stack is empty.
fn is_empty(&self) -> bool {
self.len() == 0
}

/// Pushes values to the stack
/// Return `true` if push was successful, `false` if stack overflow.
///
Expand Down
Loading

0 comments on commit a4fa635

Please sign in to comment.