Skip to main content

cfx_executor/executive/
mod.rs

1// Copyright 2019 Conflux Foundation. All rights reserved.
2// Conflux is free software and distributed under GNU General Public License.
3// See http://www.gnu.org/licenses/
4pub mod executed;
5pub mod execution_outcome;
6mod fresh_executive;
7mod pre_checked_executive;
8#[cfg(test)]
9mod tests;
10pub mod transact_options;
11
12use cfx_rpc_eth_types::BlockOverrides;
13use cfx_statedb::Result as DbResult;
14use cfx_types::{SpaceMap, U256};
15use cfx_vm_types::{ConsensusGasSpec, Env, Spec};
16use primitives::{AccessList, SignedTransaction};
17
18use fresh_executive::FreshExecutive;
19use pre_checked_executive::PreCheckedExecutive;
20
21pub use executed::Executed;
22pub use execution_outcome::{
23    ExecutionError, ExecutionOutcome, ToRepackError, TxDropError,
24};
25pub use transact_options::{
26    ChargeCollateral, TransactOptions, TransactSettings,
27};
28
29use crate::{
30    executive_observer::ExecutiveObserver,
31    machine::Machine,
32    state::{burnt_gas_price, State},
33};
34
35/// Transaction executor.
36pub struct ExecutiveContext<'a> {
37    state: &'a mut State,
38    env: &'a Env,
39    machine: &'a Machine,
40    spec: &'a Spec,
41}
42
43impl<'a> ExecutiveContext<'a> {
44    pub fn new(
45        state: &'a mut State, env: &'a Env, machine: &'a Machine,
46        spec: &'a Spec,
47    ) -> Self {
48        ExecutiveContext {
49            state,
50            env,
51            machine,
52            spec,
53        }
54    }
55
56    #[inline(never)]
57    pub fn transact<O: ExecutiveObserver>(
58        self, tx: &SignedTransaction, options: TransactOptions<O>,
59    ) -> DbResult<ExecutionOutcome> {
60        // Transaction should execute on an empty cache
61        assert!(self.state.cache.get_mut().is_empty());
62
63        let fresh_exec = FreshExecutive::new(self, tx, options);
64
65        Ok(match fresh_exec.check_all()? {
66            Ok(executive) => executive.execute_transaction()?,
67            Err(execution_outcome) => execution_outcome,
68        })
69    }
70
71    pub fn apply_env_overrides(
72        env: &mut Env, block_override: Box<BlockOverrides>, base_fee_prop: U256,
73    ) {
74        if let Some(number) = block_override.number {
75            env.number = number.as_u64();
76        }
77        if let Some(difficulty) = block_override.difficulty {
78            env.difficulty = difficulty;
79        }
80        if let Some(timestamp) = block_override.time {
81            env.timestamp = timestamp;
82        }
83        if let Some(gas_limit) = block_override.gas_limit {
84            env.gas_limit = U256::from(gas_limit);
85        }
86        if let Some(author) = block_override.coinbase {
87            env.author = author;
88        }
89        if let Some(_random) = block_override.random {
90            // conflux doesn't have random(prevRandao)
91        }
92        if let Some(base_fee) = block_override.base_fee {
93            env.base_gas_price = SpaceMap::new(base_fee, base_fee); // use same base_fee for both spaces
94            let burnt = burnt_gas_price(base_fee, base_fee_prop);
95            env.burnt_gas_price = SpaceMap::new(burnt, burnt);
96        }
97
98        if let Some(_block_hash) = &block_override.block_hash {
99            // TODO impl
100        }
101    }
102}
103
104#[inline]
105pub fn gas_required_for(
106    is_create: bool, data: &[u8], access_list: Option<&AccessList>,
107    authorization_len: usize, spec: &ConsensusGasSpec,
108) -> u64 {
109    let init_gas = (if is_create {
110        spec.tx_create_gas
111    } else {
112        spec.tx_gas
113    }) as u64;
114
115    let byte_gas = |b: &u8| {
116        (match *b {
117            0 => spec.tx_data_zero_gas,
118            _ => spec.tx_data_non_zero_gas,
119        }) as u64
120    };
121    let data_gas: u64 = data.iter().map(byte_gas).sum();
122    let data_word = (data.len() as u64 + 31) / 32;
123
124    // CIP-645i: EIP-3860: Limit and meter initcode
125    let initcode_gas = if spec.cip645.eip3860 && is_create {
126        data_word * spec.init_code_word_gas as u64
127    } else {
128        0
129    };
130
131    let access_gas: u64 = if let Some(acc) = access_list {
132        let address_gas =
133            acc.len() as u64 * spec.access_list_address_gas as u64;
134
135        let storage_key_num =
136            acc.iter().map(|e| e.storage_keys.len() as u64).sum::<u64>();
137        let storage_key_gas =
138            storage_key_num * spec.access_list_storage_key_gas as u64;
139
140        address_gas + storage_key_gas
141    } else {
142        0
143    };
144
145    let authorization_gas = spec.per_empty_account_cost as u64
146        * spec.evm_gas_ratio as u64
147        * authorization_len as u64;
148
149    init_gas + data_gas + access_gas + authorization_gas + initcode_gas
150}
151
152pub fn eip7623_required_gas(data: &[u8], spec: &ConsensusGasSpec) -> u64 {
153    if !spec.eip7623 {
154        return 0;
155    }
156
157    let byte_floor_gas = |b: &u8| {
158        (match *b {
159            0 => spec.tx_data_floor_zero_gas,
160            _ => spec.tx_data_floor_non_zero_gas,
161        }) as u64
162    };
163
164    spec.tx_gas as u64 + data.iter().map(byte_floor_gas).sum::<u64>()
165}
166
167#[cfg(test)]
168pub mod test_util {
169    use crate::{
170        executive_observer::TracerTrait, stack::accrue_substate,
171        substate::Substate,
172    };
173    use cfx_statedb::Result as DbResult;
174    use cfx_vm_interpreter::FinalizationResult;
175    use cfx_vm_types::{self as vm, ActionParams};
176
177    use super::{pre_checked_executive::exec_vm, ExecutiveContext};
178
179    impl<'a> ExecutiveContext<'a> {
180        pub fn call_for_test(
181            &mut self, params: ActionParams, substate: &mut Substate,
182            tracer: &mut dyn TracerTrait,
183        ) -> DbResult<vm::Result<FinalizationResult>> {
184            let mut frame_result = exec_vm(self, params, tracer)?;
185            accrue_substate(substate, &mut frame_result);
186
187            Ok(frame_result.map(Into::into))
188        }
189    }
190}