Skip to content

Commit

Permalink
Merge branch 'master' into evm/dst20-2
Browse files Browse the repository at this point in the history
  • Loading branch information
Jouzo authored Jul 28, 2023
2 parents ec1c8c1 + ca8b35e commit dbde6ec
Show file tree
Hide file tree
Showing 36 changed files with 125 additions and 480 deletions.
4 changes: 0 additions & 4 deletions lib/ain-cpp-imports/src/bridge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,6 @@ pub mod ffi {
fn getStateInputJSON() -> String;
fn getHighestBlock() -> i32;
fn getCurrentHeight() -> i32;
fn pastChangiIntermediateHeight2() -> bool;
fn pastChangiIntermediateHeight3() -> bool;
fn pastChangiIntermediateHeight4() -> bool;
fn pastChangiIntermediateHeight5() -> bool;
fn CppLogPrintf(message: String);
}
}
28 changes: 0 additions & 28 deletions lib/ain-cpp-imports/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,18 +55,6 @@ mod ffi {
pub fn getCurrentHeight() -> i32 {
unimplemented!("{}", UNIMPL_MSG)
}
pub fn pastChangiIntermediateHeight2() -> bool {
unimplemented!("{}", UNIMPL_MSG)
}
pub fn pastChangiIntermediateHeight3() -> bool {
unimplemented!("{}", UNIMPL_MSG)
}
pub fn pastChangiIntermediateHeight4() -> bool {
unimplemented!("{}", UNIMPL_MSG)
}
pub fn pastChangiIntermediateHeight5() -> bool {
unimplemented!("{}", UNIMPL_MSG)
}

pub fn CppLogPrintf(_message: String) {
// Intentionally left empty, so it can be used from everywhere.
Expand Down Expand Up @@ -147,22 +135,6 @@ pub fn get_sync_status() -> Result<(i32, i32), Box<dyn Error>> {
Ok((current_block, highest_block))
}

pub fn past_changi_intermediate_height_2_height() -> bool {
ffi::pastChangiIntermediateHeight2()
}

pub fn past_changi_intermediate_height_3_height() -> bool {
ffi::pastChangiIntermediateHeight3()
}

pub fn past_changi_intermediate_height_4_height() -> bool {
ffi::pastChangiIntermediateHeight4()
}

pub fn past_changi_intermediate_height_5_height() -> bool {
ffi::pastChangiIntermediateHeight5()
}

pub fn log_print(message: &str) {
// TODO: Switch to u8 to avoid intermediate string conversions
ffi::CppLogPrintf(message.to_owned());
Expand Down
68 changes: 13 additions & 55 deletions lib/ain-evm/src/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,40 +61,7 @@ impl BlockService {
self.storage.put_block(&block);
}

fn pre_changi_intermediate_2_base_fee_calculation(
&self,
parent_gas_used: u64,
parent_gas_target: u64,
parent_base_fee: U256,
base_fee_max_change_denominator: U256,
initial_base_fee: U256,
) -> U256 {
match parent_gas_used.cmp(&parent_gas_target) {
// TODO: incorrect calculation, remove before mainnet launch
Ordering::Less => parent_base_fee,
Ordering::Equal => {
let gas_used_delta = parent_gas_used - parent_gas_target;
let base_fee_per_gas_delta = max(
parent_base_fee * gas_used_delta
/ parent_gas_target
/ base_fee_max_change_denominator,
U256::one(),
);

max(parent_base_fee + base_fee_per_gas_delta, initial_base_fee)
}
Ordering::Greater => {
let gas_used_delta = parent_gas_target - parent_gas_used;
let base_fee_per_gas_delta = parent_base_fee * gas_used_delta
/ parent_gas_target
/ base_fee_max_change_denominator;

max(parent_base_fee - base_fee_per_gas_delta, initial_base_fee)
}
}
}

pub fn post_changi_intermediate_2_base_fee_calculation(
pub fn base_fee_calculation(
&self,
parent_gas_used: u64,
parent_gas_target: u64,
Expand Down Expand Up @@ -134,22 +101,13 @@ impl BlockService {
base_fee_max_change_denominator: U256,
initial_base_fee: U256,
) -> U256 {
match ain_cpp_imports::past_changi_intermediate_height_2_height() {
true => self.post_changi_intermediate_2_base_fee_calculation(
parent_gas_used,
parent_gas_target,
parent_base_fee,
base_fee_max_change_denominator,
initial_base_fee,
),
false => self.pre_changi_intermediate_2_base_fee_calculation(
parent_gas_used,
parent_gas_target,
parent_base_fee,
base_fee_max_change_denominator,
initial_base_fee,
),
}
self.base_fee_calculation(
parent_gas_used,
parent_gas_target,
parent_base_fee,
base_fee_max_change_denominator,
initial_base_fee,
)
}

pub fn calculate_base_fee(&self, parent_hash: H256) -> U256 {
Expand Down Expand Up @@ -365,7 +323,7 @@ mod tests {
let block = BlockService::new(Arc::new(Storage::new()));
assert_eq!(
U256::from(20_000_000_000u64),
block.post_changi_intermediate_2_base_fee_calculation(
block.base_fee_calculation(
15_000_000,
15_000_000,
U256::from(20_000_000_000u64),
Expand All @@ -380,7 +338,7 @@ mod tests {
let block = BlockService::new(Arc::new(Storage::new()));
assert_eq!(
U256::from(22_500_000_000u64), // should increase by 12.5%
block.post_changi_intermediate_2_base_fee_calculation(
block.base_fee_calculation(
30_000_000,
15_000_000,
U256::from(20_000_000_000u64),
Expand All @@ -395,7 +353,7 @@ mod tests {
let block = BlockService::new(Arc::new(Storage::new()));
assert_eq!(
U256::from(20_833_333_333u64), // should increase by ~4.15%
block.post_changi_intermediate_2_base_fee_calculation(
block.base_fee_calculation(
20_000_000,
15_000_000,
U256::from(20_000_000_000u64),
Expand All @@ -410,7 +368,7 @@ mod tests {
let block = BlockService::new(Arc::new(Storage::new()));
assert_eq!(
U256::from(17_500_000_000u64), // should decrease by 12.5%
block.post_changi_intermediate_2_base_fee_calculation(
block.base_fee_calculation(
0,
15_000_000,
U256::from(20_000_000_000u64),
Expand All @@ -425,7 +383,7 @@ mod tests {
let block = BlockService::new(Arc::new(Storage::new()));
assert_eq!(
U256::from(19_166_666_667u64), // should increase by ~4.15%
block.post_changi_intermediate_2_base_fee_calculation(
block.base_fee_calculation(
10_000_000,
15_000_000,
U256::from(20_000_000_000u64),
Expand Down
20 changes: 5 additions & 15 deletions lib/ain-evm/src/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::backend::{EVMBackend, EVMBackendError, InsufficientBalance, Vicinity}
use crate::block::INITIAL_BASE_FEE;
use crate::executor::TxResponse;
use crate::fee::calculate_prepay_gas_fee;
use crate::gas::{check_tx_intrinsic_gas, MIN_GAS_PER_TX};
use crate::gas::check_tx_intrinsic_gas;
use crate::receipt::ReceiptService;
use crate::services::SERVICES;
use crate::storage::traits::{BlockStorage, PersistentStateError};
Expand Down Expand Up @@ -219,24 +219,14 @@ impl EVMCoreService {
debug!("[validate_raw_tx] prepay_fee : {:x?}", prepay_fee);

let gas_limit = signed_tx.gas_limit();
if ain_cpp_imports::past_changi_intermediate_height_4_height() {
if balance < prepay_fee {
debug!("[validate_raw_tx] insufficient balance to pay fees");
return Err(anyhow!("insufficient balance to pay fees").into());
}

if ain_cpp_imports::past_changi_intermediate_height_5_height() {
// Validate tx gas limit with intrinsic gas
check_tx_intrinsic_gas(&signed_tx)?;
} else if gas_limit < MIN_GAS_PER_TX {
debug!("[validate_raw_tx] gas limit is below the minimum gas per tx");
return Err(anyhow!("gas limit is below the minimum gas per tx").into());
}
} else if balance < MIN_GAS_PER_TX || balance < prepay_fee {
if balance < prepay_fee {
debug!("[validate_raw_tx] insufficient balance to pay fees");
return Err(anyhow!("insufficient balance to pay fees").into());
}

// Validate tx gas limit with intrinsic gas
check_tx_intrinsic_gas(&signed_tx)?;

if gas_limit > MAX_GAS_PER_BLOCK {
debug!("[validate_raw_tx] Gas limit higher than MAX_GAS_PER_BLOCK");
return Err(anyhow!("Gas limit higher than MAX_GAS_PER_BLOCK").into());
Expand Down
102 changes: 42 additions & 60 deletions lib/ain-evm/src/evm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ impl EVMServices {
};

let base_fee = self.block.calculate_base_fee(parent_hash);
debug!("[finalize_block] Block base fee: {}", base_fee);

let mut backend = EVMBackend::from_root(
state_root,
Expand Down Expand Up @@ -176,11 +177,9 @@ impl EVMServices {
for queue_item in self.core.tx_queues.get_cloned_vec(queue_id) {
match queue_item.queue_tx {
QueueTx::SignedTx(signed_tx) => {
if ain_cpp_imports::past_changi_intermediate_height_4_height() {
let nonce = executor.get_nonce(&signed_tx.sender);
if signed_tx.nonce() != nonce {
return Err(anyhow!("EVM block rejected for invalid nonce. Address {} nonce {}, signed_tx nonce: {}", signed_tx.sender, nonce, signed_tx.nonce()).into());
}
let nonce = executor.get_nonce(&signed_tx.sender);
if signed_tx.nonce() != nonce {
return Err(anyhow!("EVM block rejected for invalid nonce. Address {} nonce {}, signed_tx nonce: {}", signed_tx.sender, nonce, signed_tx.nonce()).into());
}

let prepay_gas = calculate_prepay_gas_fee(&signed_tx)?;
Expand Down Expand Up @@ -329,57 +328,42 @@ impl EVMServices {
self.filters.add_block_to_filters(block.header.hash());
}

if ain_cpp_imports::past_changi_intermediate_height_4_height() {
let total_burnt_fees = U256::from(total_gas_used) * base_fee;
let total_priority_fees = total_gas_fees - total_burnt_fees;
debug!(
"[finalize_block] Total burnt fees : {:#?}",
total_burnt_fees
);
debug!(
"[finalize_block] Total priority fees : {:#?}",
total_priority_fees
);
let total_burnt_fees = U256::from(total_gas_used) * base_fee;
let total_priority_fees = total_gas_fees - total_burnt_fees;
debug!(
"[finalize_block] Total burnt fees : {:#?}",
total_burnt_fees
);
debug!(
"[finalize_block] Total priority fees : {:#?}",
total_priority_fees
);

if ain_cpp_imports::past_changi_intermediate_height_5_height() {
match self.core.tx_queues.get_total_fees(queue_id) {
Some(total_fees) => {
if (total_burnt_fees + total_priority_fees) != total_fees {
return Err(anyhow!("EVM block rejected because block total fees != (burnt fees + priority fees). Burnt fees: {}, priority fees: {}, total fees: {}", total_burnt_fees, total_priority_fees, total_fees).into());
}
}
None => {
return Err(anyhow!(
"EVM block rejected because failed to get total fees from queue_id: {}",
queue_id
)
.into())
}
match self.core.tx_queues.get_total_fees(queue_id) {
Some(total_fees) => {
if (total_burnt_fees + total_priority_fees) != total_fees {
return Err(anyhow!("EVM block rejected because block total fees != (burnt fees + priority fees). Burnt fees: {}, priority fees: {}, total fees: {}", total_burnt_fees, total_priority_fees, total_fees).into());
}
}

if update_state {
self.core.tx_queues.remove(queue_id);
}

Ok(FinalizedBlockInfo {
block_hash: *block.header.hash().as_fixed_bytes(),
failed_transactions,
total_burnt_fees,
total_priority_fees,
})
} else {
if update_state {
self.core.tx_queues.remove(queue_id);
None => {
return Err(anyhow!(
"EVM block rejected because failed to get total fees from queue_id: {}",
queue_id
)
.into())
}
}

Ok(FinalizedBlockInfo {
block_hash: *block.header.hash().as_fixed_bytes(),
failed_transactions,
total_burnt_fees: U256::from(total_gas_used),
total_priority_fees: U256::zero(),
})
if update_state {
self.core.tx_queues.remove(queue_id);
}

Ok(FinalizedBlockInfo {
block_hash: *block.header.hash().as_fixed_bytes(),
failed_transactions,
total_burnt_fees,
total_priority_fees,
})
}

pub fn verify_tx_fees(&self, tx: &str, use_context: bool) -> Result<(), Box<dyn Error>> {
Expand All @@ -390,17 +374,15 @@ impl EVMServices {
debug!("[verify_tx_fees] TransactionV2 : {:#?}", tx);
let signed_tx: SignedTx = tx.try_into()?;

if ain_cpp_imports::past_changi_intermediate_height_4_height() {
let mut block_fees = self.block.calculate_base_fee(H256::zero());
if use_context {
block_fees = self.block.calculate_next_block_base_fee();
}
let mut block_fee = self.block.calculate_base_fee(H256::zero());
if use_context {
block_fee = self.block.calculate_next_block_base_fee();
}

let tx_gas_price = get_tx_max_gas_price(&signed_tx);
if tx_gas_price < block_fees {
debug!("[verify_tx_fees] tx gas price is lower than block base fee");
return Err(anyhow!("tx gas price is lower than block base fee").into());
}
let tx_gas_price = get_tx_max_gas_price(&signed_tx);
if tx_gas_price < block_fee {
debug!("[verify_tx_fees] tx gas price is lower than block base fee");
return Err(anyhow!("tx gas price is lower than block base fee").into());
}

Ok(())
Expand Down
8 changes: 2 additions & 6 deletions lib/ain-evm/src/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,12 +157,8 @@ impl<'backend> Executor for AinExecutor<'backend> {
let (values, logs) = executor.into_state().deconstruct();
let logs = logs.into_iter().collect::<Vec<_>>();

let past_changi_intermediate3 = ain_cpp_imports::past_changi_intermediate_height_3_height();

if exit_reason.is_succeed() || past_changi_intermediate3 {
ApplyBackend::apply(self.backend, values, logs.clone(), true);
self.backend.commit();
}
ApplyBackend::apply(self.backend, values, logs.clone(), true);
self.backend.commit();

self.backend.refund_unused_gas(
signed_tx.sender,
Expand Down
4 changes: 0 additions & 4 deletions lib/ain-evm/src/gas.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,9 @@ use evm::{
};

use anyhow::anyhow;
use ethereum_types::U256;
use log::debug;
use std::error::Error;

// Changi intermediate constant
pub const MIN_GAS_PER_TX: U256 = U256([21_000, 0, 0, 0]);

fn get_tx_cost(signed_tx: &SignedTx) -> TransactionCost {
let access_list = signed_tx
.access_list()
Expand Down
Loading

0 comments on commit dbde6ec

Please sign in to comment.