Skip to content

Commit

Permalink
Merge branch master into evm_queue_state_root_tracking
Browse files Browse the repository at this point in the history
  • Loading branch information
Jouzo committed Sep 6, 2023
2 parents 1277f74 + 865edf1 commit 3e7e5c9
Show file tree
Hide file tree
Showing 65 changed files with 620 additions and 336 deletions.
2 changes: 1 addition & 1 deletion SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ If you’ve found a vulnerability, please submit it privately via `security@defi
We offer a bug bounty of up to **$50,000 USD** worth of DFI for [DeFiCh/ain](https://github.com/defich/ain) critical
vulnerabilities. You must be able to provide significant information for reproducing and fixing the issue.

Only [official releases](https://github.com/DeFiCh/ain/releases), master branch development code are not included.
Bug bounty program is limited to the recent [stable releases](https://github.com/DeFiCh/ain/releases) and it's tags. Any other source origin including `master` branch may not qualify.
1 change: 1 addition & 0 deletions lib/.rustfmt.toml
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
unstable_features = true
group_imports = "StdExternalCrate"
imports_granularity = "Crate"
8 changes: 3 additions & 5 deletions lib/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 lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,6 @@ jsonrpsee-types = "0.16"
ethereum = "0.14"
ethereum-types = "0.14"
keccak-hash = "0.10"
primitive-types = { version = "0.12", default-features = false, features = ["serde"] }
rlp = "0.5"
ethabi = "18.0.0"

Expand Down
2 changes: 1 addition & 1 deletion lib/Makefile.am
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ clippy:
# cause conflicts across toolchains
.PHONY: fmt-check
fmt-check:
$(CARGO) fmt $(CARGO_MANIFEST_ARG) --all --check 2> >(grep -v -E 'group_imports|unstable_features')
$(CARGO) fmt $(CARGO_MANIFEST_ARG) --all --check 2> >(grep -v -E 'group_imports|unstable_features|imports_granularity')

.PHONY: fmt
fmt:
Expand Down
2 changes: 1 addition & 1 deletion lib/ain-contracts/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
primitive-types.workspace = true
ethereum-types.workspace = true
anyhow.workspace = true
ethereum.workspace = true
serde_json.workspace = true
Expand Down
4 changes: 1 addition & 3 deletions lib/ain-contracts/build.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
use std::env;
use std::fs;
use std::path::PathBuf;
use std::{env, fs, path::PathBuf};

use anyhow::format_err;
use ethers_solc::{Project, ProjectPathsConfig, Solc};
Expand Down
10 changes: 9 additions & 1 deletion lib/ain-contracts/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::str::FromStr;

use anyhow::format_err;
use primitive_types::{H160, H256};
use ethereum_types::{H160, H256};
use sp_core::{Blake2Hasher, Hasher};

pub type Result<T> = std::result::Result<T, anyhow::Error>;
Expand All @@ -23,6 +23,14 @@ pub fn dst20_address_from_token_id(token_id: u64) -> Result<H160> {
Ok(H160::from_str(&final_str)?)
}

pub fn intrinsics_address_from_id(id: u64) -> Result<H160> {
let number_str = format!("{:x}", id);
let padded_number_str = format!("{number_str:0>37}");
let final_str = format!("ff1{padded_number_str}");

Ok(H160::from_str(&final_str)?)
}

#[derive(Clone)]
pub struct Contract {
pub codehash: H256,
Expand Down
3 changes: 1 addition & 2 deletions lib/ain-cpp-imports/build.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use std::env;
use std::path::PathBuf;
use std::{env, path::PathBuf};

use anyhow::{format_err, Result};

Expand Down
1 change: 0 additions & 1 deletion lib/ain-evm/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ ain-cpp-imports = { path = "../ain-cpp-imports" }
ain-contracts = { path = "../ain-contracts" }

evm = { workspace = true, default-features = false, features = ["with-serde"] }
primitive-types = { workspace = true, default-features = false, features = ["serde"] }
log.workspace = true
rlp.workspace = true
libsecp256k1.workspace = true
Expand Down
10 changes: 4 additions & 6 deletions lib/ain-evm/src/backend.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,20 @@
use std::error::Error;
use std::sync::Arc;
use std::{error::Error, sync::Arc};

use ethereum::{Account, Log};
use ethereum_types::{H160, H256, U256};
use evm::backend::{Apply, ApplyBackend, Backend, Basic};
use hash_db::Hasher as _;
use log::{debug, trace};
use primitive_types::{H160, H256, U256};
use rlp::{Decodable, Encodable, Rlp};
use sp_core::hexdisplay::AsBytesRef;
use sp_core::Blake2Hasher;
use sp_core::{hexdisplay::AsBytesRef, Blake2Hasher};
use vsdb_trie_db::{MptOnce, MptRo};

use crate::Result;
use crate::{
storage::{traits::BlockStorage, Storage},
traits::BridgeBackend,
transaction::SignedTx,
trie::TrieDBStore,
Result,
};

type Hasher = Blake2Hasher;
Expand Down
14 changes: 9 additions & 5 deletions lib/ain-evm/src/block.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
use std::cmp::{max, Ordering};
use std::sync::Arc;
use std::{
cmp::{max, Ordering},
sync::Arc,
};

use anyhow::format_err;
use ethereum::{BlockAny, TransactionAny};
use ethereum_types::U256;
use keccak_hash::H256;
use log::{debug, trace};
use primitive_types::U256;
use statrs::statistics::{Data, OrderStatistics};

use crate::storage::{traits::BlockStorage, Storage};
use crate::Result;
use crate::{
storage::{traits::BlockStorage, Storage},
Result,
};

pub struct BlockService {
storage: Arc<Storage>,
Expand Down
2 changes: 1 addition & 1 deletion lib/ain-evm/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ pub struct DST20BridgeInfo {
}

/// Returns address, bytecode and storage with incremented count for the counter contract
pub fn counter_contract(
pub fn intrinsics_contract(
backend: &EVMBackend,
dvm_block_number: u64,
evm_block_number: U256,
Expand Down
70 changes: 34 additions & 36 deletions lib/ain-evm/src/core.rs
Original file line number Diff line number Diff line change
@@ -1,29 +1,27 @@
use std::path::PathBuf;
use std::sync::Arc;
use std::{path::PathBuf, sync::Arc};

use anyhow::format_err;
use ethereum::{AccessList, Account, Block, Log, PartialHeader, TransactionV2};
use ethereum_types::{Bloom, BloomInput, H160, U256};
use ethereum_types::{Bloom, BloomInput, H160, H256, U256};
use log::{debug, trace};
use primitive_types::H256;
use vsdb_core::vsdb_set_base_dir;

use crate::backend::{BackendError, EVMBackend, 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;
use crate::receipt::ReceiptService;
use crate::storage::traits::BlockStorage;
use crate::storage::Storage;
use crate::transaction::system::{SystemTx, TransferDirection, TransferDomainData};
use crate::trie::TrieDBStore;
use crate::txqueue::{QueueTx, TransactionQueueMap};
use crate::weiamount::WeiAmount;
use crate::{
executor::AinExecutor,
backend::{BackendError, EVMBackend, InsufficientBalance, Vicinity},
block::INITIAL_BASE_FEE,
executor::{AinExecutor, TxResponse},
fee::calculate_prepay_gas_fee,
gas::check_tx_intrinsic_gas,
receipt::ReceiptService,
storage::{traits::BlockStorage, Storage},
traits::{Executor, ExecutorContext},
transaction::SignedTx,
transaction::{
system::{SystemTx, TransferDirection, TransferDomainData},
SignedTx,
},
trie::TrieDBStore,
txqueue::{QueueTx, TransactionQueueMap},
weiamount::WeiAmount,
Result,
};

Expand Down Expand Up @@ -276,17 +274,6 @@ impl EVMCoreService {
return Err(format_err!("value more than money range").into());
}

let balance = backend.get_balance(&signed_tx.sender);
let prepay_fee = calculate_prepay_gas_fee(&signed_tx)?;
debug!("[validate_raw_tx] Account balance : {:x?}", balance);
debug!("[validate_raw_tx] prepay_fee : {:x?}", prepay_fee);

// Validate tx prepay fees with account balance
if balance < prepay_fee {
debug!("[validate_raw_tx] insufficient balance to pay fees");
return Err(format_err!("insufficient balance to pay fees").into());
}

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

Expand All @@ -299,7 +286,19 @@ impl EVMCoreService {
}

let use_queue = queue_id != 0;
let prepay_fee = calculate_prepay_gas_fee(&signed_tx)?;

debug!("[validate_raw_tx] prepay_fee : {:x?}", prepay_fee);
let (used_gas, state_root) = if use_queue {
// Validate tx prepay fees with account balance
let balance = backend.get_balance(&signed_tx.sender);
debug!("[validate_raw_tx] Account balance : {:x?}", balance);

if balance < prepay_fee {
debug!("[validate_raw_tx] insufficient balance to pay fees");
return Err(format_err!("insufficient balance to pay fees").into());
}

let mut executor = AinExecutor::new(&mut backend);

let (
Expand All @@ -315,13 +314,8 @@ impl EVMCoreService {
debug!("exit_reason : {:#?}", exit_reason);

debug!("[validate_raw_tx] new state_root : {:#x}", state_root);
(used_gas, state_root)
} else {
(u64::default(), H256::default())
};

// Validate total gas usage in queued txs exceeds block size
if use_queue {
// Validate total gas usage in queued txs exceeds block size
debug!("[validate_raw_tx] used_gas: {:#?}", used_gas);
let total_current_gas_used = self
.tx_queues
Expand All @@ -332,7 +326,11 @@ impl EVMCoreService {
if total_current_gas_used + U256::from(used_gas) > U256::from(block_gas_limit) {
return Err(format_err!("Tx can't make it in block. Block size limit {}, pending block gas used : {:x?}, tx used gas : {:x?}, total : {:x?}", block_gas_limit, total_current_gas_used, U256::from(used_gas), total_current_gas_used + U256::from(used_gas)).into());
}
}

(used_gas, state_root)
} else {
(u64::default(), H256::default())
};

Ok(ValidateTxInfo {
signed_tx,
Expand Down
7 changes: 3 additions & 4 deletions lib/ain-evm/src/ecrecover.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use libsecp256k1::Error;
use libsecp256k1::{PublicKey, RecoveryId, Signature};
use primitive_types::{H160, H256};
use ethereum_types::{H160, H256};
use libsecp256k1::{Error, PublicKey, RecoveryId, Signature};
use sha3::Digest;

pub fn recover_public_key(
Expand Down Expand Up @@ -30,8 +29,8 @@ pub fn public_key_to_address(pubkey: &PublicKey) -> H160 {

#[cfg(test)]
mod tests {
use ethereum_types::*;
use hex_literal::hex;
use primitive_types::*;

use super::{public_key_to_address, recover_public_key};

Expand Down
Loading

0 comments on commit 3e7e5c9

Please sign in to comment.