From b90612d0c7b13632674491359ecadbae4c9ad9bd Mon Sep 17 00:00:00 2001 From: Eason Gao Date: Mon, 4 Dec 2023 14:39:22 +0800 Subject: [PATCH] refactor!: change many `U256` type to `U64` (#1591) * refactor: change many U256 type to U64 * change some safe as_u64 to low_u64 & cargo fmt * refactor the gas price and limit check * refactor prepay gas calculation * revert max gas limit * fix e2e test * Update eth_getBalance.test.js * remove useless code This PR is substitute for #1539 Some mainly changes: * Change the type of `nonce` from `U256` to `U64` according to the [EIP-2681](https://eips.ethereum.org/EIPS/eip-2681) limit the account nonce to be between `0` and `2^64-1`. * Change the type of `gas_limit` from `U256` to `U64`. According to the current gas cost of the most complex ethereum transaction is on the order of million, `U64` is enough. * Change the type of `chain_id` from `U256` to `U64` according to [metamask limit](https://gist.github.com/rekmarks/a47bd5f2525936c4b8eee31a16345553). The [`ChainId` opcode](https://eips.ethereum.org/EIPS/eip-1344) returns a 256-bit value, so it should not larger than `U256::MAX / 2 - 35`.This issue does not lead to consensus in Ethereum community, however, I think limit the max chain ID to `4503599627370476` is enough currently. Many temporary L2/L3 need a unique chain ID is the demand of variable-lenght chain ID in foreseeable future. But we do not have the demand now. If the day comes, we can change the chain ID type to `U256` even without hardfork. * Set the [`Default Max Price`](https://github.com/ethereum/go-ethereum/blob/be65b47/eth/gasprice/gasprice.go#L38) as `500` Gwei that is same as go-ethereum. Meanwhile, change the type of `gas_price` from `U256` to `U64`. --------- Co-authored-by: sunchengzhu <36075573+sunchengzhu@users.noreply.github.com> Co-authored-by: Flouse <1297478+Flouse@users.noreply.github.com> --- common/config-parser/src/types/spec.rs | 5 +- core/api/src/adapter.rs | 17 +++-- core/api/src/jsonrpc/impl/axon.rs | 4 +- core/api/src/jsonrpc/impl/filter.rs | 4 +- core/api/src/jsonrpc/impl/web3.rs | 66 ++++++++++--------- core/api/src/jsonrpc/web3_types.rs | 52 +++++++-------- core/consensus/src/engine.rs | 6 +- core/consensus/src/tests/mod.rs | 10 +-- core/executor/benches/mock.rs | 4 +- core/executor/benches/revm_adapter.rs | 10 +-- core/executor/src/adapter/backend/apply.rs | 5 +- .../executor/src/adapter/backend/read_only.rs | 6 +- core/executor/src/debugger/create2.rs | 8 +-- core/executor/src/debugger/mod.rs | 9 ++- core/executor/src/debugger/uniswap2.rs | 8 +-- core/executor/src/lib.rs | 24 +++---- core/executor/src/system_contract/utils.rs | 10 +-- core/executor/src/tests/mod.rs | 12 ++-- core/mempool/benches/mock.rs | 12 ++-- core/mempool/src/adapter/mod.rs | 35 +++++----- core/mempool/src/lib.rs | 17 +++-- core/mempool/src/pool.rs | 12 ++-- core/mempool/src/tests/mod.rs | 12 ++-- core/mempool/src/tx_wrapper.rs | 16 ++--- .../peer_store/peer_store_impl.rs | 4 -- core/run/src/components/chain_spec.rs | 3 +- core/run/src/lib.rs | 2 +- devtools/axon-tools/src/rlp_codec.rs | 2 +- devtools/axon-tools/src/tests/verify_proof.rs | 6 +- devtools/axon-tools/src/types.rs | 12 ++-- protocol/src/codec/block.rs | 6 +- protocol/src/codec/transaction.rs | 26 ++++---- protocol/src/constants/configs.rs | 20 ++++++ protocol/src/constants/mod.rs | 3 + protocol/src/lib.rs | 2 - protocol/src/traits/api.rs | 6 +- protocol/src/traits/executor.rs | 6 +- protocol/src/traits/mempool.rs | 6 +- protocol/src/types/block.rs | 22 ++----- protocol/src/types/executor.rs | 6 +- protocol/src/types/mod.rs | 3 + protocol/src/types/primitive.rs | 1 - protocol/src/types/receipt.rs | 10 +-- protocol/src/types/transaction.rs | 47 +++++++------ tests/e2e/src/eth_call.test.js | 8 +-- 45 files changed, 300 insertions(+), 265 deletions(-) create mode 100644 protocol/src/constants/configs.rs diff --git a/common/config-parser/src/types/spec.rs b/common/config-parser/src/types/spec.rs index 310ad6668..2b8971c94 100644 --- a/common/config-parser/src/types/spec.rs +++ b/common/config-parser/src/types/spec.rs @@ -12,7 +12,8 @@ use common_crypto::Secp256k1RecoverablePrivateKey; use protocol::{ codec::{decode_256bits_key, deserialize_address}, types::{ - HardforkInfoInner, Header, Key256Bits, Metadata, H160, H256, RLP_EMPTY_LIST, RLP_NULL, U256, + HardforkInfoInner, Header, Key256Bits, Metadata, H160, H256, RLP_EMPTY_LIST, RLP_NULL, + U256, U64, }, }; @@ -36,7 +37,7 @@ pub struct ChainSpec { pub struct Genesis { pub timestamp: u64, pub hardforks: Vec, - pub base_fee_per_gas: U256, + pub base_fee_per_gas: U64, pub chain_id: u64, } diff --git a/core/api/src/adapter.rs b/core/api/src/adapter.rs index 1a19a5189..a169918d8 100644 --- a/core/api/src/adapter.rs +++ b/core/api/src/adapter.rs @@ -7,10 +7,11 @@ use protocol::trie::Trie as _; use protocol::types::{ Account, BigEndianHash, Block, BlockNumber, Bytes, CkbRelatedInfo, EthAccountProof, EthStorageProof, ExecutorContext, HardforkInfo, HardforkInfoInner, Hash, Header, Hex, Metadata, - Proposal, Receipt, SignedTransaction, TxResp, H160, H256, MAX_BLOCK_GAS_LIMIT, NIL_DATA, - RLP_NULL, U256, + Proposal, Receipt, SignedTransaction, TxResp, H160, H256, NIL_DATA, RLP_NULL, U256, U64, +}; +use protocol::{ + async_trait, codec::ProtocolCodec, constants::MAX_BLOCK_GAS_LIMIT, trie, ProtocolResult, }; -use protocol::{async_trait, codec::ProtocolCodec, trie, ProtocolResult}; use core_executor::{ system_contract::metadata::MetadataHandle, AxonExecutor, AxonExecutorReadOnlyAdapter, MPTTrie, @@ -193,8 +194,8 @@ where _ctx: Context, from: Option, to: Option, - gas_price: Option, - gas_limit: Option, + gas_price: Option, + gas_limit: Option, value: U256, data: Vec, estimate: bool, @@ -203,7 +204,9 @@ where ) -> ProtocolResult { let mut exec_ctx = ExecutorContext::from(mock_header); exec_ctx.origin = from.unwrap_or_default(); - exec_ctx.gas_price = gas_price.unwrap_or_else(U256::one); + exec_ctx.gas_price = gas_price + .map(|p| U256::from(p.low_u64())) + .unwrap_or_else(U256::one); let backend = AxonExecutorReadOnlyAdapter::from_root( state_root, @@ -212,7 +215,7 @@ where exec_ctx, )?; let gas_limit = gas_limit - .map(|gas| gas.as_u64()) + .map(|gas| gas.low_u64()) .unwrap_or(MAX_BLOCK_GAS_LIMIT); Ok(AxonExecutor.call(&backend, gas_limit, from, to, value, data, estimate)) diff --git a/core/api/src/jsonrpc/impl/axon.rs b/core/api/src/jsonrpc/impl/axon.rs index 4e654b486..098a5c941 100644 --- a/core/api/src/jsonrpc/impl/axon.rs +++ b/core/api/src/jsonrpc/impl/axon.rs @@ -30,7 +30,7 @@ impl AxonRpcServer for AxonRpcImpl { BlockId::Hash(hash) => self.adapter.get_block_by_hash(Context::new(), hash).await, BlockId::Num(num) => { self.adapter - .get_block_by_number(Context::new(), Some(num.as_u64())) + .get_block_by_number(Context::new(), Some(num.low_u64())) .await } BlockId::Latest => self.adapter.get_block_by_number(Context::new(), None).await, @@ -52,7 +52,7 @@ impl AxonRpcServer for AxonRpcImpl { async fn get_metadata_by_number(&self, block_number: U256) -> RpcResult { let ret = self .adapter - .get_metadata_by_number(Context::new(), Some(block_number.as_u64())) + .get_metadata_by_number(Context::new(), Some(block_number.low_u64())) .await .map_err(|e| RpcError::Internal(e.to_string()))?; diff --git a/core/api/src/jsonrpc/impl/filter.rs b/core/api/src/jsonrpc/impl/filter.rs index 67f0849b7..bd9e72771 100644 --- a/core/api/src/jsonrpc/impl/filter.rs +++ b/core/api/src/jsonrpc/impl/filter.rs @@ -204,7 +204,7 @@ where match from { BlockId::Num(n) => { - if n.as_u64() < header.number { + if n.low_u64() < header.number { filter.from_block = Some(BlockId::Num(U64::from(header.number + 1))); } } @@ -302,7 +302,7 @@ where let (start, end) = { let convert = |id: &BlockId| -> BlockNumber { match id { - BlockId::Num(n) => n.as_u64(), + BlockId::Num(n) => n.low_u64(), BlockId::Earliest => 0, _ => latest_number, } diff --git a/core/api/src/jsonrpc/impl/web3.rs b/core/api/src/jsonrpc/impl/web3.rs index 8746cf40c..70e2e4baf 100644 --- a/core/api/src/jsonrpc/impl/web3.rs +++ b/core/api/src/jsonrpc/impl/web3.rs @@ -4,15 +4,17 @@ use jsonrpsee::core::RpcResult; use common_apm::metrics_rpc; use core_executor::is_system_contract_address_format; +use protocol::constants::{ + BASE_FEE_PER_GAS, MAX_FEE_HISTORY, MAX_GAS_LIMIT, MAX_GAS_PRICE, MEMPOOL_REFRESH_TIMEOUT, + MIN_TRANSACTION_GAS_LIMIT, +}; use protocol::traits::{APIAdapter, Context}; use protocol::types::{ Block, BlockNumber, Bytes, EthAccountProof, Hash, Header, Hex, Proposal, Receipt, - SignedTransaction, TxResp, UnverifiedTransaction, BASE_FEE_PER_GAS, H160, H256, - MAX_FEE_HISTORY, MAX_RPC_GAS_CAP, MIN_TRANSACTION_GAS_LIMIT, U256, U64, + SignedTransaction, TxResp, UnverifiedTransaction, H160, H256, U256, U64, }; use protocol::{ async_trait, codec::ProtocolCodec, lazy::PROTOCOL_VERSION, tokio::time::sleep, ProtocolResult, - MEMPOOL_REFRESH_TIMEOUT, }; use crate::jsonrpc::web3_types::{ @@ -27,7 +29,7 @@ pub(crate) const MAX_LOG_NUM: usize = 10000; pub struct Web3RpcImpl { adapter: Arc, - max_gas_cap: U256, + max_gas_cap: U64, log_filter_max_block_range: u64, } @@ -92,10 +94,10 @@ impl Web3RpcImpl { async fn calculate_rewards( &self, block_number: u64, - base_fee_par_gas: U256, + base_fee_par_gas: U64, txs: Vec, reward_percentiles: Vec, - reward: &mut Vec>, + reward: &mut Vec>, ) -> Result<(), RpcError> { let receipts = self .adapter @@ -103,17 +105,17 @@ impl Web3RpcImpl { .await .map_err(|e| RpcError::Internal(e.to_string()))?; - let effective_priority_fees: Vec = receipts + let effective_priority_fees: Vec = receipts .iter() .map(|receipt| { receipt .as_ref() .map(|r| r.used_gas.saturating_sub(base_fee_par_gas)) - .unwrap_or(U256::zero()) + .unwrap_or(U64::zero()) }) .collect(); - let reward_vec: Vec = reward_percentiles + let reward_vec: Vec = reward_percentiles .iter() .map(|percentile| { let index = @@ -121,7 +123,7 @@ impl Web3RpcImpl { effective_priority_fees .get(index) .cloned() - .unwrap_or(U256::zero()) + .unwrap_or(U64::zero()) }) .collect(); @@ -135,7 +137,7 @@ impl Web3RpcImpl { height: Option, block_count: U256, reward_percentiles: &Option>, - ) -> Result<(u64, Vec, Vec, Vec>), RpcError> { + ) -> Result<(u64, Vec, Vec, Vec>), RpcError> { let latest_block = self .adapter .get_block_by_number(Context::new(), height) @@ -148,9 +150,9 @@ impl Web3RpcImpl { .saturating_sub(block_count.as_u64()) .saturating_add(1); - let mut bash_fee_per_gases: Vec = Vec::new(); + let mut bash_fee_per_gases: Vec = Vec::new(); let mut gas_used_ratios: Vec = Vec::new(); - let mut reward: Vec> = Vec::new(); + let mut reward: Vec> = Vec::new(); for i in oldest_block_number..=latest_block_number { let block = match self @@ -198,11 +200,11 @@ impl Web3RpcServer for Web3RpcImpl { let gas_price = utx.unsigned.gas_price(); - if gas_price == U256::zero() { + if gas_price == U64::zero() { return Err(RpcError::GasPriceIsZero.into()); } - if gas_price >= U256::from(u64::MAX) { + if gas_price > MAX_GAS_PRICE { return Err(RpcError::GasPriceIsTooLarge.into()); } @@ -414,12 +416,12 @@ impl Web3RpcServer for Web3RpcImpl { #[metrics_rpc("eth_call")] async fn call(&self, req: Web3CallRequest, block_id: Option) -> RpcResult { - if req.gas_price.unwrap_or_default() > U256::from(u64::MAX) { + if req.gas.unwrap_or_default() > MAX_GAS_LIMIT.into() { return Err(RpcError::GasLimitIsTooLarge.into()); } - if req.gas.unwrap_or_default() > U256::from(MAX_RPC_GAS_CAP) { - return Err(RpcError::GasLimitIsTooLarge.into()); + if req.gas_price.unwrap_or_default() > MAX_GAS_PRICE { + return Err(RpcError::GasPriceIsTooLarge.into()); } if let Some(call_addr) = req.to { @@ -451,15 +453,17 @@ impl Web3RpcServer for Web3RpcImpl { #[metrics_rpc("eth_estimateGas")] async fn estimate_gas(&self, req: Web3CallRequest, number: Option) -> RpcResult { if let Some(gas_limit) = req.gas.as_ref() { - if gas_limit == &U256::zero() { + if gas_limit == &U64::zero() { return Err(RpcError::GasPriceIsZero.into()); } } - if let Some(price) = req.gas_price.as_ref() { - if price >= &U256::from(u64::MAX) { - return Err(RpcError::GasPriceIsTooLarge.into()); - } + if req.gas.unwrap_or_default() > MAX_GAS_LIMIT.into() { + return Err(RpcError::GasLimitIsTooLarge.into()); + } + + if req.gas_price.unwrap_or_default() > MAX_GAS_PRICE { + return Err(RpcError::GasPriceIsTooLarge.into()); } if let Some(call_addr) = req.to { @@ -469,7 +473,7 @@ impl Web3RpcServer for Web3RpcImpl { } let num = match number { - Some(BlockId::Num(n)) => Some(n.as_u64()), + Some(BlockId::Num(n)) => Some(n.low_u64()), _ => None, }; let data_bytes = req @@ -688,7 +692,7 @@ impl Web3RpcServer for Web3RpcImpl { let (start, end) = { let convert = |id: BlockId| -> BlockNumber { match id { - BlockId::Num(n) => n.as_u64(), + BlockId::Num(n) => n.low_u64(), BlockId::Earliest => 0, _ => latest_number, } @@ -780,7 +784,7 @@ impl Web3RpcServer for Web3RpcImpl { match newest_block { BlockId::Num(number) => { let (oldest_block_number, bash_fee_per_gases, gas_used_ratios, reward) = self - .inner_fee_history(number.as_u64().into(), blocks_count, &reward_percentiles) + .inner_fee_history(number.low_u64().into(), blocks_count, &reward_percentiles) .await?; match reward_percentiles { @@ -861,7 +865,7 @@ impl Web3RpcServer for Web3RpcImpl { gas_used_ratio, })); } - let mut reward: Vec> = Vec::new(); + let mut reward: Vec> = Vec::new(); self.calculate_rewards( first_block.header.number, first_block.header.base_fee_per_gas, @@ -1064,9 +1068,9 @@ fn check_reward_percentiles(reward_percentiles: &Option>) -> RpcResult< // Calculates the gas used ratio for the block. fn calculate_gas_used_ratio(block: &Block) -> f64 { - (block.header.gas_limit != U256::zero()) + (block.header.gas_limit != U64::zero()) .then(|| { - block.header.gas_used.as_u64() as f64 / block.header.gas_limit.as_u64() as f64 * 100f64 + block.header.gas_used.low_u64() as f64 / block.header.gas_limit.as_u64() as f64 * 100f64 }) .unwrap_or(0f64) } @@ -1075,14 +1079,14 @@ fn calculate_gas_used_ratio(block: &Block) -> f64 { // vector. fn calculate_effective_priority_fees_index( percentile: &f64, - effective_priority_fees: &Vec, + effective_priority_fees: &Vec, ) -> usize { ((percentile * effective_priority_fees.len() as f64 / 100f64).floor() as usize) .saturating_sub(1) } // Get the base fee per gas for the next block. -fn next_block_base_fee_per_gas() -> U256 { +fn next_block_base_fee_per_gas() -> U64 { BASE_FEE_PER_GAS.into() } diff --git a/core/api/src/jsonrpc/web3_types.rs b/core/api/src/jsonrpc/web3_types.rs index 8d3efb611..07ed454a0 100644 --- a/core/api/src/jsonrpc/web3_types.rs +++ b/core/api/src/jsonrpc/web3_types.rs @@ -49,26 +49,26 @@ impl RichTransactionOrHash { pub struct Web3Transaction { #[serde(rename = "type")] pub type_: Option, - pub block_number: Option, + pub block_number: Option, pub block_hash: Option, pub hash: Hash, - pub nonce: U256, - pub transaction_index: Option, + pub nonce: U64, + pub transaction_index: Option, pub from: H160, pub to: Option, pub value: U256, - pub gas: U256, - pub gas_price: U256, + pub gas: U64, + pub gas_price: U64, #[serde(skip_serializing_if = "Option::is_none")] - pub max_fee_per_gas: Option, + pub max_fee_per_gas: Option, #[serde(skip_serializing_if = "Option::is_none")] - pub max_priority_fee_per_gas: Option, + pub max_priority_fee_per_gas: Option, pub raw: Hex, pub input: Hex, pub public_key: Option, #[serde(skip_serializing_if = "Option::is_none")] pub access_list: Option, - pub chain_id: Option, + pub chain_id: Option, #[serde(skip_serializing_if = "Option::is_none")] pub standard_v: Option, pub v: U256, @@ -107,7 +107,7 @@ impl From for Web3Transaction { gas: *stx.transaction.unsigned.gas_limit(), gas_price: stx.transaction.unsigned.gas_price(), max_fee_per_gas: if is_eip1559 { - Some(U256::from(MAX_PRIORITY_FEE_PER_GAS)) + Some(U64::from(MAX_PRIORITY_FEE_PER_GAS)) } else { None }, @@ -162,15 +162,15 @@ pub struct Web3Receipt { pub block_number: U256, pub block_hash: H256, pub contract_address: Option, - pub cumulative_gas_used: U256, - pub effective_gas_price: U256, + pub cumulative_gas_used: U64, + pub effective_gas_price: U64, pub from: H160, - pub gas_used: U256, + pub gas_used: U64, pub logs: Vec, pub logs_bloom: Bloom, #[serde(rename = "root")] pub state_root: Hash, - pub status: U256, + pub status: U64, pub to: Option, pub transaction_hash: Hash, pub transaction_index: Option, @@ -243,16 +243,16 @@ pub struct Web3Block { pub state_root: H256, pub transactions_root: H256, pub receipts_root: H256, - pub number: U256, - pub gas_used: U256, - pub gas_limit: U256, + pub number: U64, + pub gas_used: U64, + pub gas_limit: U64, pub extra_data: Hex, pub logs_bloom: Option, pub timestamp: U256, pub difficulty: U256, pub total_difficulty: Option, pub seal_fields: Vec, - pub base_fee_per_gas: U256, + pub base_fee_per_gas: U64, pub uncles: Vec, pub transactions: Vec, pub size: Option, @@ -308,10 +308,10 @@ pub struct Web3CallRequest { pub from: Option, pub to: Option, #[serde(skip_serializing_if = "Option::is_none")] - pub gas_price: Option, + pub gas_price: Option, #[serde(skip_serializing_if = "Option::is_none")] - pub max_fee_per_gas: Option, - pub gas: Option, + pub max_fee_per_gas: Option, + pub gas: Option, pub value: Option, pub data: Option, pub nonce: Option, @@ -335,7 +335,7 @@ pub enum BlockId { impl From for Option { fn from(id: BlockId) -> Self { match id { - BlockId::Num(num) => Some(num.as_u64()), + BlockId::Num(num) => Some(num.low_u64()), BlockId::Earliest => Some(0), _ => None, } @@ -727,13 +727,13 @@ pub struct FeeHistoryWithReward { /// This includes the next block after the newest of the returned range, /// because this value can be derived from the newest block. Zeroes are /// returned for pre-EIP-1559 blocks. - pub base_fee_per_gas: Vec, + pub base_fee_per_gas: Vec, /// An array of block gas used ratios. These are calculated as the ratio /// of `gasUsed` and `gasLimit`. pub gas_used_ratio: Vec, /// An (optional) array of effective priority fee per gas data points from a /// single block. All zeroes are returned if the block is empty. - pub reward: Vec>, + pub reward: Vec>, } /// Response type for `eth_feeHistory` RPC call with parameter REWARDPERCENTILES @@ -747,7 +747,7 @@ pub struct FeeHistoryWithoutReward { /// This includes the next block after the newest of the returned range, /// because this value can be derived from the newest block. Zeroes are /// returned for pre-EIP-1559 blocks. - pub base_fee_per_gas: Vec, + pub base_fee_per_gas: Vec, /// An array of block gas used ratios. These are calculated as the ratio /// of `gasUsed` and `gasLimit`. pub gas_used_ratio: Vec, @@ -769,8 +769,8 @@ pub struct FeeHistoryEmpty { pub struct Web3Header { pub difficulty: U256, pub extra_data: Hex, - pub gas_limit: U256, - pub gas_used: U256, + pub gas_limit: U64, + pub gas_used: U64, pub logs_bloom: Option, pub miner: H160, pub nonce: U256, diff --git a/core/consensus/src/engine.rs b/core/consensus/src/engine.rs index e87deaf31..37c7a2869 100644 --- a/core/consensus/src/engine.rs +++ b/core/consensus/src/engine.rs @@ -21,11 +21,11 @@ use protocol::constants::endpoints::{ END_GOSSIP_AGGREGATED_VOTE, END_GOSSIP_SIGNED_CHOKE, END_GOSSIP_SIGNED_PROPOSAL, END_GOSSIP_SIGNED_VOTE, }; +use protocol::constants::{BASE_FEE_PER_GAS, MAX_BLOCK_GAS_LIMIT}; use protocol::traits::{ConsensusAdapter, Context, MessageTarget, NodeInfo}; use protocol::types::{ Block, BlockVersion, Bytes, ExecResp, ExtraData, Hash, Hex, Metadata, Proof, Proposal, - SignedTransaction, ValidatorExtend, VecDisplayHelper, BASE_FEE_PER_GAS, MAX_BLOCK_GAS_LIMIT, - RLP_NULL, + SignedTransaction, ValidatorExtend, VecDisplayHelper, RLP_NULL, }; use protocol::{ async_trait, codec::ProtocolCodec, tokio::sync::Mutex as AsyncMutex, types::HardforkInfoInner, @@ -742,7 +742,7 @@ impl ConsensusEngine { ctx, resp.state_root, MAX_BLOCK_GAS_LIMIT, - last_status.max_tx_size.as_u64(), + last_status.max_tx_size.low_u64(), ); if block.header.number != proof.number { diff --git a/core/consensus/src/tests/mod.rs b/core/consensus/src/tests/mod.rs index 8d9c9efdc..f718ce35c 100644 --- a/core/consensus/src/tests/mod.rs +++ b/core/consensus/src/tests/mod.rs @@ -14,7 +14,7 @@ use protocol::{ Address, Block, BlockNumber, Bytes, Eip1559Transaction, ExecResp, Hash, Hasher, Header, Hex, MerkleRoot, Metadata, Proof, Proposal, Public, Receipt, SignatureComponents, SignedTransaction, TransactionAction, UnsignedTransaction, UnverifiedTransaction, - Validator, H160, H256, U256, + Validator, H160, H256, U256, U64, }, ProtocolResult, }; @@ -109,10 +109,10 @@ fn gen_tx(sender: H160, addr: H160, value: u64, data: Vec) -> SignedTransact SignedTransaction { transaction: UnverifiedTransaction { unsigned: UnsignedTransaction::Eip1559(Eip1559Transaction { - nonce: U256::default(), - max_priority_fee_per_gas: U256::default(), - gas_price: U256::default(), - gas_limit: U256::from_str("0x1000000000").unwrap(), + nonce: U64::default(), + max_priority_fee_per_gas: U64::default(), + gas_price: U64::default(), + gas_limit: U64::from_str("0x1000000000").unwrap(), action: TransactionAction::Call(addr), value: value.into(), data: data.into(), diff --git a/core/executor/benches/mock.rs b/core/executor/benches/mock.rs index 55eb25ae9..24a40d05b 100644 --- a/core/executor/benches/mock.rs +++ b/core/executor/benches/mock.rs @@ -9,7 +9,7 @@ use protocol::{ types::{ public_to_address, Account, Address, Bytes, Eip1559Transaction, ExecutorContext, Public, SignedTransaction, TransactionAction, UnsignedTransaction, UnverifiedTransaction, H160, - H512, NIL_DATA, RLP_NULL, U256, + H512, NIL_DATA, RLP_NULL, U256, U64, }, }; @@ -76,7 +76,7 @@ pub fn mock_transactions(n: usize) -> Vec { ) }; let raw_tx = Eip1559Transaction { - nonce: U256::zero(), + nonce: U64::zero(), max_priority_fee_per_gas: 1u64.into(), gas_price: 1u64.into(), gas_limit: 10_000_000u64.into(), diff --git a/core/executor/benches/revm_adapter.rs b/core/executor/benches/revm_adapter.rs index e758de640..86199b4d0 100644 --- a/core/executor/benches/revm_adapter.rs +++ b/core/executor/benches/revm_adapter.rs @@ -52,7 +52,7 @@ where let raw = raw.unwrap(); Ok(Some(Account::decode(raw).map(|a| AccountInfo { balance: U256(a.balance.0), - nonce: a.nonce.as_u64(), + nonce: a.nonce.low_u64(), code_hash: a.code_hash, code: None, })?)) @@ -101,11 +101,11 @@ where fn block_hash(&mut self, number: U256) -> Result { let current_number = self.exec_ctx.block_number; - if number.as_u64() > current_number.as_u64() { + if number.low_u64() > current_number.low_u64() { return Ok(H256::default()); } - let number = number.as_u64(); + let number = number.low_u64(); let res = blocking_async!(self, storage, get_block, Context::new(), number) .map(|b| b.hash()) .unwrap_or_default(); @@ -299,7 +299,7 @@ where .nonce; set_revm( evm, - tx.transaction.unsigned.gas_limit().as_u64(), + tx.transaction.unsigned.gas_limit().low_u64(), Some(tx.sender), tx.transaction.unsigned.to(), *tx.transaction.unsigned.value(), @@ -324,7 +324,7 @@ where exit_reason: evm::ExitReason::Succeed(ExitSucceed::Returned), ret, gas_used: res.gas_used, - remain_gas: tx.transaction.unsigned.gas_limit().as_u64() - res.gas_used, + remain_gas: tx.transaction.unsigned.gas_limit().low_u64() - res.gas_used, fee_cost: res.gas_used.into(), // todo logs: vec![], diff --git a/core/executor/src/adapter/backend/apply.rs b/core/executor/src/adapter/backend/apply.rs index ef5c364ad..73d8dda79 100644 --- a/core/executor/src/adapter/backend/apply.rs +++ b/core/executor/src/adapter/backend/apply.rs @@ -9,6 +9,7 @@ use protocol::traits::{ use protocol::trie::Trie; use protocol::types::{ Account, Bytes, ExecutorContext, Hasher, Log, MerkleRoot, H160, H256, NIL_DATA, RLP_NULL, U256, + U64, }; use protocol::{codec::ProtocolCodec, trie, ProtocolResult}; @@ -114,8 +115,8 @@ where self.inner.exec_ctx.origin = origin; } - fn set_gas_price(&mut self, gas_price: U256) { - self.inner.exec_ctx.gas_price = gas_price; + fn set_gas_price(&mut self, gas_price: U64) { + self.inner.exec_ctx.gas_price = gas_price.low_u64().into(); } fn take_logs(&mut self) -> Vec { diff --git a/core/executor/src/adapter/backend/read_only.rs b/core/executor/src/adapter/backend/read_only.rs index 1c41e626c..0ef57d6f4 100644 --- a/core/executor/src/adapter/backend/read_only.rs +++ b/core/executor/src/adapter/backend/read_only.rs @@ -78,7 +78,7 @@ where return H256::default(); } - let number = number.as_u64(); + let number = number.low_u64(); blocking_async!(self, get_storage, get_block, Context::new(), number) .map(|b| b.hash()) .unwrap_or_default() @@ -97,11 +97,11 @@ where } fn block_gas_limit(&self) -> U256 { - self.exec_ctx.block_gas_limit + U256::from(self.exec_ctx.block_gas_limit.low_u64()) } fn block_base_fee_per_gas(&self) -> U256 { - self.exec_ctx.block_base_fee_per_gas + U256::from(self.exec_ctx.block_base_fee_per_gas.low_u64()) } fn chain_id(&self) -> U256 { diff --git a/core/executor/src/debugger/create2.rs b/core/executor/src/debugger/create2.rs index e8dfce91c..a11ea0c72 100644 --- a/core/executor/src/debugger/create2.rs +++ b/core/executor/src/debugger/create2.rs @@ -1,9 +1,9 @@ use protocol::traits::Backend; use protocol::types::{ LegacyTransaction, SignedTransaction, TransactionAction, UnsignedTransaction, - UnverifiedTransaction, H160, H256, MAX_BLOCK_GAS_LIMIT, U256, + UnverifiedTransaction, H160, H256, U256, U64, }; -use protocol::{codec::hex_decode, tokio}; +use protocol::{codec::hex_decode, constants::MAX_BLOCK_GAS_LIMIT, tokio}; use crate::debugger::EvmDebugger; @@ -29,10 +29,10 @@ async fn test_create2_gas() { let gas_used = resp.tx_resp[0].gas_used; let after_balance = debugger.backend(1).basic(sender).balance; - assert_eq!(gas_used * 8, (init_balance - after_balance).as_u64()); + assert_eq!(gas_used * 8, (init_balance - after_balance).low_u64()); } -fn mock_create2_tx(nonce: U256, sender: H160) -> SignedTransaction { +fn mock_create2_tx(nonce: U64, sender: H160) -> SignedTransaction { let tx = LegacyTransaction { nonce, gas_price: 8u64.into(), diff --git a/core/executor/src/debugger/mod.rs b/core/executor/src/debugger/mod.rs index 70ac9038d..b863ad4a1 100644 --- a/core/executor/src/debugger/mod.rs +++ b/core/executor/src/debugger/mod.rs @@ -6,13 +6,12 @@ use std::time::{SystemTime, UNIX_EPOCH}; use evm::tracing::{Event, EventListener}; -use protocol::codec::ProtocolCodec; use protocol::traits::Backend; -use protocol::trie::Trie as _; use protocol::types::{ Account, Eip1559Transaction, ExecResp, ExecutorContext, Hash, Hasher, SignedTransaction, - UnsignedTransaction, UnverifiedTransaction, H160, H256, NIL_DATA, RLP_NULL, U256, + UnsignedTransaction, UnverifiedTransaction, H160, H256, NIL_DATA, RLP_NULL, U256, U64, }; +use protocol::{codec::ProtocolCodec, trie::Trie as _}; use core_db::RocksAdapter; use core_storage::ImplStorage; @@ -95,8 +94,8 @@ impl EvmDebugger { .unwrap() } - fn nonce(&self, addr: H160) -> U256 { - self.backend(0).basic(addr).nonce + fn nonce(&self, addr: H160) -> U64 { + self.backend(0).basic(addr).nonce.low_u64().into() } } diff --git a/core/executor/src/debugger/uniswap2.rs b/core/executor/src/debugger/uniswap2.rs index 8d9e45769..aa94f3ad1 100644 --- a/core/executor/src/debugger/uniswap2.rs +++ b/core/executor/src/debugger/uniswap2.rs @@ -6,7 +6,7 @@ use evm::{ExitReason, ExitSucceed}; use protocol::codec::hex_decode; use protocol::tokio; -use protocol::types::{Bytes, TransactionAction, H160}; +use protocol::types::{Bytes, TransactionAction, H160, U64}; ethabi_contract::use_contract!(factory, "res/factory.abi"); ethabi_contract::use_contract!(router, "res/router.abi"); @@ -35,9 +35,9 @@ fn read_code(path: &str) -> String { fn construct_tx(action: TransactionAction, value: U256, data: Vec) -> Eip1559Transaction { Eip1559Transaction { - nonce: U256::default(), - max_priority_fee_per_gas: U256::default(), - gas_price: U256::default(), + nonce: U64::default(), + max_priority_fee_per_gas: U64::default(), + gas_price: U64::default(), gas_limit: 10000000000u64.into(), action, value, diff --git a/core/executor/src/lib.rs b/core/executor/src/lib.rs index 0c07dfc5d..b5cf9d5e8 100644 --- a/core/executor/src/lib.rs +++ b/core/executor/src/lib.rs @@ -300,9 +300,14 @@ impl AxonExecutor { ) -> TxResp { // Deduct pre-pay gas let sender = tx.sender; + // The `Backend` trait is imply in + // `core/executor/src/adapter/backend/read_only.rs`. The `gas_price` is never + // larger than u64::MAX. let tx_gas_price = adapter.gas_price(); - let gas_limit = tx.transaction.unsigned.gas_limit(); - let prepay_gas = tx_gas_price * gas_limit; + let gas_limit = tx.transaction.unsigned.gas_limit().low_u64(); + // The overflow check is done in the `check_authorization` function + // of`core/mempool/src/adapter/mod.rs`. + let prepay_gas = tx_gas_price * U256::from(gas_limit); let mut account = adapter.get_account(&sender); let old_nonce = account.nonce; @@ -310,7 +315,7 @@ impl AxonExecutor { account.balance = account.balance.saturating_sub(prepay_gas); adapter.save_account(&sender, &account); - let metadata = StackSubstateMetadata::new(gas_limit.as_u64(), config); + let metadata = StackSubstateMetadata::new(gas_limit, config); let mut executor = StackExecutor::new_with_precompiles( MemoryStackState::new(metadata, adapter), config, @@ -331,14 +336,14 @@ impl AxonExecutor { *addr, *tx.transaction.unsigned.value(), tx.transaction.unsigned.data().to_vec(), - gas_limit.as_u64(), + gas_limit, access_list, ), TransactionAction::Create => executor.transact_create( tx.sender, *tx.transaction.unsigned.value(), tx.transaction.unsigned.data().to_vec(), - gas_limit.as_u64(), + gas_limit, access_list, ), }; @@ -364,9 +369,7 @@ impl AxonExecutor { // Add remain gas if remained_gas != 0 { - let remain_gas = U256::from(remained_gas) - .checked_mul(tx_gas_price) - .unwrap_or_else(U256::max_value); + let remain_gas = U256::from(remained_gas) * tx_gas_price; account.balance = account .balance .checked_add(remain_gas) @@ -380,9 +383,8 @@ impl AxonExecutor { ret: res, remain_gas: remained_gas, gas_used: used_gas, - fee_cost: tx_gas_price - .checked_mul(used_gas.into()) - .unwrap_or(U256::max_value()), + fee_cost: tx_gas_price * U256::from(used_gas), /* used_gas must le transaction + * gas_limit */ logs: vec![], code_address: code_addr, removed: false, diff --git a/core/executor/src/system_contract/utils.rs b/core/executor/src/system_contract/utils.rs index 37bacbe28..48d89bd42 100644 --- a/core/executor/src/system_contract/utils.rs +++ b/core/executor/src/system_contract/utils.rs @@ -1,7 +1,7 @@ use evm::ExitSucceed; use protocol::types::{ - Apply, ApplyBackend, Backend, ExitReason, ExitRevert, TxResp, H160, H256, U256, + Apply, ApplyBackend, Backend, ExitReason, ExitRevert, TxResp, H160, H256, U256, U64, }; use crate::system_contract::{ @@ -10,11 +10,11 @@ use crate::system_contract::{ }; use crate::{CURRENT_HEADER_CELL_ROOT, CURRENT_METADATA_ROOT}; -pub fn revert_resp(gas_limit: U256) -> TxResp { +pub fn revert_resp(gas_limit: U64) -> TxResp { TxResp { exit_reason: ExitReason::Revert(ExitRevert::Reverted), ret: vec![], - gas_used: (gas_limit - 1).as_u64(), + gas_used: (gas_limit - 1).low_u64(), remain_gas: 1u64, fee_cost: U256::one(), logs: vec![], @@ -23,12 +23,12 @@ pub fn revert_resp(gas_limit: U256) -> TxResp { } } -pub fn succeed_resp(gas_limit: U256) -> TxResp { +pub fn succeed_resp(gas_limit: U64) -> TxResp { TxResp { exit_reason: ExitReason::Succeed(ExitSucceed::Stopped), ret: vec![], gas_used: 0u64, - remain_gas: gas_limit.as_u64(), + remain_gas: gas_limit.low_u64(), fee_cost: U256::zero(), logs: vec![], code_address: None, diff --git a/core/executor/src/tests/mod.rs b/core/executor/src/tests/mod.rs index 1c7271fde..c39b55d44 100644 --- a/core/executor/src/tests/mod.rs +++ b/core/executor/src/tests/mod.rs @@ -10,7 +10,7 @@ use evm::Config; use protocol::types::{ Bytes, Eip1559Transaction, ExecutorContext, ExitReason, ExitSucceed, Public, SignatureComponents, SignedTransaction, TransactionAction, UnsignedTransaction, - UnverifiedTransaction, H160, H256, U256, + UnverifiedTransaction, H160, H256, U256, U64, }; use protocol::{codec::hex_decode, tokio, traits::Executor, trie::MemoryDB}; @@ -24,7 +24,7 @@ fn exec_adapter() -> AxonExecutorApplyAdapter, Memory let storage = ImplStorage::new(Arc::new(MemoryAdapter::new()), 20); let ctx = ExecutorContext { block_gas_limit: u32::MAX.into(), - block_base_fee_per_gas: U256::one(), + block_base_fee_per_gas: U64::one(), ..Default::default() }; @@ -50,10 +50,10 @@ fn gen_tx(sender: H160, addr: H160, value: u64, data: Vec) -> SignedTransact SignedTransaction { transaction: UnverifiedTransaction { unsigned: UnsignedTransaction::Eip1559(Eip1559Transaction { - nonce: U256::default(), - max_priority_fee_per_gas: U256::default(), - gas_price: U256::default(), - gas_limit: U256::from_str("0x1000000000").unwrap(), + nonce: U64::default(), + max_priority_fee_per_gas: U64::default(), + gas_price: U64::default(), + gas_limit: U64::from_str("0x1000000000").unwrap(), action: TransactionAction::Call(addr), value: value.into(), data: data.into(), diff --git a/core/mempool/benches/mock.rs b/core/mempool/benches/mock.rs index 4822c524c..7318161ad 100644 --- a/core/mempool/benches/mock.rs +++ b/core/mempool/benches/mock.rs @@ -12,7 +12,7 @@ use protocol::traits::{Context, MemPool, MemPoolAdapter}; use protocol::types::{ public_to_address, recover_intact_pub_key, Bytes, Eip1559Transaction, Hash, PackedTxHashes, Public, SignedTransaction, TransactionAction, UnsignedTransaction, UnverifiedTransaction, H160, - H256, U256, + H256, U256, U64, }; use protocol::{async_trait, tokio, ProtocolResult}; @@ -71,8 +71,8 @@ impl MemPoolAdapter for HashMemPoolAdapter { &self, _ctx: Context, _tx: &SignedTransaction, - ) -> ProtocolResult { - Ok(U256::zero()) + ) -> ProtocolResult { + Ok(U64::zero()) } async fn check_transaction(&self, _ctx: Context, tx: &SignedTransaction) -> ProtocolResult<()> { @@ -135,9 +135,9 @@ pub async fn default_mempool() -> MemPoolImpl { pub fn mock_transaction(nonce: u64, is_call_system_script: bool) -> Eip1559Transaction { Eip1559Transaction { nonce: nonce.into(), - gas_limit: U256::one(), - max_priority_fee_per_gas: U256::one(), - gas_price: U256::one(), + gas_limit: U64::one(), + max_priority_fee_per_gas: U64::one(), + gas_price: U64::one(), action: if is_call_system_script { TransactionAction::Call(NATIVE_TOKEN_ISSUE_ADDRESS) } else { diff --git a/core/mempool/src/adapter/mod.rs b/core/mempool/src/adapter/mod.rs index ede5e6750..866faa5c9 100644 --- a/core/mempool/src/adapter/mod.rs +++ b/core/mempool/src/adapter/mod.rs @@ -17,12 +17,13 @@ use protocol::traits::{ }; use protocol::types::{ recover_intact_pub_key, Backend, BatchSignedTxs, CellDepWithPubKey, Hash, MerkleRoot, - SignedTransaction, H160, U256, + SignedTransaction, H160, U256, U64, }; use protocol::{ async_trait, codec::ProtocolCodec, constants::endpoints::{END_GOSSIP_NEW_TXS, RPC_PULL_TXS}, + constants::MAX_GAS_PRICE, tokio, trie, Display, ProtocolError, ProtocolErrorKind, ProtocolResult, }; @@ -120,7 +121,7 @@ pub struct DefaultMemPoolAdapter { storage: Arc, trie_db: Arc, - addr_nonce: DashMap, + addr_nonce: DashMap, gas_limit: AtomicU64, max_tx_size: AtomicUsize, chain_id: u64, @@ -183,13 +184,13 @@ where &self, ctx: Context, stx: &SignedTransaction, - ) -> ProtocolResult { + ) -> ProtocolResult { let addr = &stx.sender; let block = self.storage.get_latest_block(ctx.clone()).await?; let root = self.executor_backend(ctx).await?.get_metadata_root(); if MetadataHandle::new(root).is_validator(block.header.number + 1, *addr)? { - return Ok(U256::zero()); + return Ok(U64::zero()); } Err(MemPoolError::CheckAuthorization { @@ -243,8 +244,8 @@ where fn verify_gas_price(&self, stx: &SignedTransaction) -> ProtocolResult<()> { let gas_price = stx.transaction.unsigned.gas_price(); - if gas_price == U256::zero() || gas_price >= U256::from(u64::MAX) { - return Err(MemPoolError::InvalidGasPrice(gas_price).into()); + if gas_price == U64::zero() || gas_price >= MAX_GAS_PRICE { + return Err(MemPoolError::InvalidGasPrice(gas_price.low_u64()).into()); } Ok(()) @@ -252,7 +253,7 @@ where fn verify_gas_limit(&self, ctx: Context, stx: &SignedTransaction) -> ProtocolResult<()> { let gas_limit_tx = stx.transaction.unsigned.gas_limit(); - if gas_limit_tx > &U256::from(self.gas_limit.load(Ordering::Acquire)) { + if gas_limit_tx > &U64::from(self.gas_limit.load(Ordering::Acquire)) { if ctx.is_network_origin_txs() { self.network.report( ctx, @@ -264,7 +265,7 @@ where } return Err(MemPoolError::ExceedGasLimit { tx_hash: stx.transaction.hash, - gas_limit_tx: gas_limit_tx.as_u64(), + gas_limit_tx: gas_limit_tx.low_u64(), gas_limit_config: self.gas_limit.load(Ordering::Acquire), } .into()); @@ -371,7 +372,7 @@ where &self, ctx: Context, tx: &SignedTransaction, - ) -> ProtocolResult { + ) -> ProtocolResult { if is_call_system_script(tx.transaction.unsigned.action())? { return self.check_system_script_tx_authorization(ctx, tx).await; } @@ -380,11 +381,11 @@ where if let Some(res) = self.addr_nonce.get(addr) { if tx.transaction.unsigned.nonce() < &res.value().0 { return Err(MemPoolError::InvalidNonce { - current: res.value().0.as_u64(), - tx_nonce: tx.transaction.unsigned.nonce().as_u64(), + current: res.value().0.low_u64(), + tx_nonce: tx.transaction.unsigned.nonce().low_u64(), } .into()); - } else if res.value().1 < tx.transaction.unsigned.may_cost() { + } else if res.value().1 < tx.transaction.unsigned.may_cost()? { return Err(MemPoolError::ExceedBalance { tx_hash: tx.transaction.hash, account_balance: res.value().1, @@ -399,17 +400,17 @@ where let backend = self.executor_backend(ctx).await?; let account = backend.basic(*addr); self.addr_nonce - .insert(*addr, (account.nonce, account.balance)); + .insert(*addr, (account.nonce.low_u64().into(), account.balance)); - if &account.nonce > tx.transaction.unsigned.nonce() { + if account.nonce.low_u64() > tx.transaction.unsigned.nonce().low_u64() { return Err(MemPoolError::InvalidNonce { current: account.nonce.as_u64(), - tx_nonce: tx.transaction.unsigned.nonce().as_u64(), + tx_nonce: tx.transaction.unsigned.nonce().low_u64(), } .into()); } - if account.balance < tx.transaction.unsigned.may_cost() { + if account.balance < tx.transaction.unsigned.may_cost()? { return Err(MemPoolError::ExceedBalance { tx_hash: tx.transaction.hash, account_balance: account.balance, @@ -418,7 +419,7 @@ where .into()); } - Ok(tx.transaction.unsigned.nonce() - account.nonce) + Ok(tx.transaction.unsigned.nonce() - account.nonce.low_u64()) } async fn check_transaction(&self, ctx: Context, stx: &SignedTransaction) -> ProtocolResult<()> { diff --git a/core/mempool/src/lib.rs b/core/mempool/src/lib.rs index 8286890b4..308ee73f6 100644 --- a/core/mempool/src/lib.rs +++ b/core/mempool/src/lib.rs @@ -17,7 +17,9 @@ use futures::future::try_join_all; use common_apm::Instant; use protocol::traits::{Context, MemPool, MemPoolAdapter}; -use protocol::types::{BlockNumber, Hash, PackedTxHashes, SignedTransaction, H160, H256, U256}; +use protocol::types::{ + BlockNumber, Hash, PackedTxHashes, SignedTransaction, H160, H256, U256, U64, +}; use protocol::{async_trait, tokio, Display, ProtocolError, ProtocolErrorKind, ProtocolResult}; use core_executor::is_call_system_script; @@ -87,7 +89,7 @@ where self.adapter .check_storage_exist(ctx.clone(), &stx.transaction.hash) .await?; - self.pool.insert(stx, true, U256::zero()) + self.pool.insert(stx, true, U64::zero()) } async fn insert_tx( @@ -134,7 +136,7 @@ where &self, ctx: Context, txs: Vec, - ) -> ProtocolResult> { + ) -> ProtocolResult> { let inst = Instant::now(); let len = txs.len(); @@ -155,20 +157,21 @@ where }) .collect::>>>(); - let res: Vec = try_join_all(futs) + let res: Vec = try_join_all(futs) .await .map_err(|e| { log::error!("[mempool] verify batch txs error {:?}", e); MemPoolError::VerifyBatchTransactions })? .into_iter() - .collect::, ProtocolError>>()?; + .collect::, ProtocolError>>()?; log::info!( "[mempool] verify txs done, size {} cost {:?}", len, inst.elapsed() ); + Ok(res) } @@ -369,11 +372,11 @@ pub enum MemPoolError { ExceedBalance { tx_hash: Hash, account_balance: U256, - tx_gas_limit: U256, + tx_gas_limit: U64, }, #[display(fmt = "Invalid gas price {:?}", _0)] - InvalidGasPrice(U256), + InvalidGasPrice(u64), #[display( fmt = "Tx: {:?} exceeds size limit, now: {}, limit: {} Bytes", diff --git a/core/mempool/src/pool.rs b/core/mempool/src/pool.rs index c61177a38..69606d844 100644 --- a/core/mempool/src/pool.rs +++ b/core/mempool/src/pool.rs @@ -10,8 +10,10 @@ use dashmap::DashMap; use parking_lot::{Mutex, RwLock}; use protocol::tokio::{self, time::sleep}; -use protocol::types::{BlockNumber, Bytes, Hash, PackedTxHashes, SignedTransaction, H160, U256}; -use protocol::{ProtocolResult, MEMPOOL_REFRESH_TIMEOUT}; +use protocol::types::{ + BlockNumber, Bytes, Hash, PackedTxHashes, SignedTransaction, H160, U256, U64, +}; +use protocol::{constants::MEMPOOL_REFRESH_TIMEOUT, ProtocolResult}; use crate::tx_wrapper::{PendingQueue, TxPtr, TxWrapper}; use crate::MemPoolError; @@ -23,7 +25,7 @@ pub struct PriorityPool { // the replace by fee function. pending_queue: Arc>, // The transactions in this queue have not been processed yet and cannot be packaged. - co_queue: Arc>, + co_queue: Arc>, // Transactions in this queue will be packaged into blocks real_queue: Arc>>, // Record all transactions in the transaction pool @@ -110,7 +112,7 @@ impl PriorityPool { &self, stx: SignedTransaction, check_limit: bool, - check_nonce: U256, + check_nonce: U64, ) -> ProtocolResult<()> { if let Err(n) = self .stock_len @@ -249,7 +251,7 @@ impl PriorityPool { let mut q = self.real_queue.lock(); let mut timeout_gap = self.timeout_gap.lock(); - let mut remove_tip_nonce: HashMap = HashMap::new(); + let mut remove_tip_nonce: HashMap = HashMap::new(); for hash in hashes { if let Some((_, ptr)) = self.tx_map.remove(hash) { match remove_tip_nonce.entry(ptr.sender()) { diff --git a/core/mempool/src/tests/mod.rs b/core/mempool/src/tests/mod.rs index 3b217959b..1d940a9b6 100644 --- a/core/mempool/src/tests/mod.rs +++ b/core/mempool/src/tests/mod.rs @@ -14,7 +14,7 @@ use protocol::traits::{Context, MemPool, MemPoolAdapter}; use protocol::types::{ public_to_address, recover_intact_pub_key, Bytes, Eip1559Transaction, Hash, PackedTxHashes, Public, SignedTransaction, TransactionAction, UnsignedTransaction, UnverifiedTransaction, H160, - H256, U256, + H256, U256, U64, }; use protocol::{async_trait, tokio, ProtocolResult}; @@ -72,8 +72,8 @@ impl MemPoolAdapter for HashMemPoolAdapter { &self, _ctx: Context, _tx: &SignedTransaction, - ) -> ProtocolResult { - Ok(U256::zero()) + ) -> ProtocolResult { + Ok(U64::zero()) } async fn check_transaction(&self, _ctx: Context, tx: &SignedTransaction) -> ProtocolResult<()> { @@ -254,9 +254,9 @@ async fn exec_get_full_txs( fn mock_transaction(nonce: u64, is_call_system_script: bool) -> Eip1559Transaction { Eip1559Transaction { nonce: nonce.into(), - gas_limit: U256::one(), - max_priority_fee_per_gas: U256::one(), - gas_price: U256::one(), + gas_limit: U64::one(), + max_priority_fee_per_gas: U64::one(), + gas_price: U64::one(), action: if is_call_system_script { TransactionAction::Call(NATIVE_TOKEN_ISSUE_ADDRESS) } else { diff --git a/core/mempool/src/tx_wrapper.rs b/core/mempool/src/tx_wrapper.rs index 3d3c9ce9e..08c358c23 100644 --- a/core/mempool/src/tx_wrapper.rs +++ b/core/mempool/src/tx_wrapper.rs @@ -4,7 +4,7 @@ use std::ops::Bound::{Included, Unbounded}; use std::sync::atomic::{AtomicU8, Ordering as AtomicOrdering}; use std::sync::Arc; -use protocol::types::{Hash, SignedTransaction, H160, U256}; +use protocol::types::{Hash, SignedTransaction, H160, U64}; pub type TxPtr = Arc; @@ -54,7 +54,7 @@ impl TxWrapper { self.tx.transaction.hash } - pub fn nonce(&self) -> &U256 { + pub fn nonce(&self) -> &U64 { self.tx.transaction.unsigned.nonce() } @@ -62,7 +62,7 @@ impl TxWrapper { self.tx.sender } - pub fn gas_price(&self) -> U256 { + pub fn gas_price(&self) -> U64 { self.tx.transaction.unsigned.gas_price() } @@ -89,15 +89,15 @@ impl TxWrapper { #[derive(Default)] pub struct PendingQueue { - queue: BTreeMap, + queue: BTreeMap, // already insert to package list tip nonce - pop_tip_nonce: U256, - current_tip_nonce: U256, + pop_tip_nonce: U64, + current_tip_nonce: U64, need_remove: bool, } impl PendingQueue { - pub fn insert(&mut self, tx: TxPtr, nonce_diff: U256) -> bool { + pub fn insert(&mut self, tx: TxPtr, nonce_diff: U64) -> bool { let nonce = *tx.nonce(); let current_tip = nonce - nonce_diff; if self.current_tip_nonce > nonce { @@ -155,7 +155,7 @@ impl PendingQueue { self.queue.retain(|_, v| !v.is_dropped()); } - pub fn set_drop_by_nonce_tip(&mut self, nonce: U256) { + pub fn set_drop_by_nonce_tip(&mut self, nonce: U64) { for (_, v) in self.queue.range((Included(0.into()), Included(nonce))) { v.set_dropped(); } diff --git a/core/network/src/peer_manager/peer_store/peer_store_impl.rs b/core/network/src/peer_manager/peer_store/peer_store_impl.rs index 24b798af0..4640b94d6 100644 --- a/core/network/src/peer_manager/peer_store/peer_store_impl.rs +++ b/core/network/src/peer_manager/peer_store/peer_store_impl.rs @@ -21,10 +21,6 @@ use crate::{ }; /// Peer store -/// -/// | -- choose to identify --| --- choose to feeler --- | -- delete -- -/// | | 1 | 2 | 3 | 4 | 5 | 6 | 7 | More than seven -/// days | #[derive(Default)] pub struct PeerStore { addr_manager: Manager, diff --git a/core/run/src/components/chain_spec.rs b/core/run/src/components/chain_spec.rs index 0d0bf34b5..502de57df 100644 --- a/core/run/src/components/chain_spec.rs +++ b/core/run/src/components/chain_spec.rs @@ -1,7 +1,8 @@ use common_config_parser::types::spec::ChainSpec; +use protocol::constants::BASE_FEE_PER_GAS; use protocol::types::{ - Block, Eip1559Transaction, RichBlock, TransactionAction, UnsignedTransaction, BASE_FEE_PER_GAS, + Block, Eip1559Transaction, RichBlock, TransactionAction, UnsignedTransaction, }; pub(crate) trait ChainSpecExt { diff --git a/core/run/src/lib.rs b/core/run/src/lib.rs index 55c779d40..f536c9ffd 100644 --- a/core/run/src/lib.rs +++ b/core/run/src/lib.rs @@ -345,7 +345,7 @@ where Arc::clone(storage), Arc::clone(trie_db), current_header.chain_id, - current_header.gas_limit.as_u64(), + current_header.gas_limit.low_u64(), config.pool_size as usize, config.broadcast_txs_size, config.broadcast_txs_interval, diff --git a/devtools/axon-tools/src/rlp_codec.rs b/devtools/axon-tools/src/rlp_codec.rs index bf820cce7..70df7082f 100644 --- a/devtools/axon-tools/src/rlp_codec.rs +++ b/devtools/axon-tools/src/rlp_codec.rs @@ -42,7 +42,7 @@ impl Encodable for Proposal { .append(&self.signed_txs_hash) .append(&self.timestamp) .append(&self.number) - .append(&self.gas_limit.as_u64()) + .append(&self.gas_limit.low_u64()) .append_list(&self.extra_data) .append(&self.proof) .append(&self.call_system_script_count) diff --git a/devtools/axon-tools/src/tests/verify_proof.rs b/devtools/axon-tools/src/tests/verify_proof.rs index deb64858c..a3ffd2975 100644 --- a/devtools/axon-tools/src/tests/verify_proof.rs +++ b/devtools/axon-tools/src/tests/verify_proof.rs @@ -5,7 +5,7 @@ use crate::types::{Block, BlockVersion, Metadata, Proof, Proposal, ValidatorExte #[cfg(feature = "proof")] use bytes::Bytes; #[cfg(feature = "proof")] -use ethereum_types::{H160, H256, U256}; +use ethereum_types::{H160, H256, U64}; #[cfg(feature = "proof")] use rlp::Encodable; #[cfg(feature = "proof")] @@ -29,9 +29,9 @@ fn test_proposal() { signed_txs_hash: H256::from([5u8; 32]), timestamp: 0, number: 100, - gas_limit: U256::from(6), + gas_limit: U64::from(6), extra_data: Vec::new(), - base_fee_per_gas: U256::from(7), + base_fee_per_gas: U64::from(7), proof: Proof { number: 0, round: 1, diff --git a/devtools/axon-tools/src/types.rs b/devtools/axon-tools/src/types.rs index e6bf0a7a1..2c0298566 100644 --- a/devtools/axon-tools/src/types.rs +++ b/devtools/axon-tools/src/types.rs @@ -12,7 +12,7 @@ use alloc::vec; use alloc::vec::Vec; use bytes::{Bytes, BytesMut}; use core::cmp::Ordering; -use ethereum_types::{Bloom, H160, H256, U256}; +use ethereum_types::{Bloom, H160, H256, U64}; #[cfg(feature = "impl-serde")] use serde::{Deserialize, Serialize}; @@ -209,13 +209,13 @@ pub struct Header { ) )] pub number: BlockNumber, - pub gas_used: U256, - pub gas_limit: U256, + pub gas_used: U64, + pub gas_limit: U64, /// Extra data for the block header /// The first index of extra_data is used to store hardfork information: /// `HardforkInfoInner` pub extra_data: Vec, - pub base_fee_per_gas: U256, + pub base_fee_per_gas: U64, pub proof: Proof, #[cfg_attr( all(feature = "impl-serde", feature = "std"), @@ -270,9 +270,9 @@ pub struct Proposal { serde(deserialize_with = "decode::deserialize_hex_u64") )] pub number: BlockNumber, - pub gas_limit: U256, + pub gas_limit: U64, pub extra_data: Vec, - pub base_fee_per_gas: U256, + pub base_fee_per_gas: U64, pub proof: Proof, #[cfg_attr( all(feature = "impl-serde", feature = "std"), diff --git a/protocol/src/codec/block.rs b/protocol/src/codec/block.rs index c2368fee7..f19d856ed 100644 --- a/protocol/src/codec/block.rs +++ b/protocol/src/codec/block.rs @@ -3,8 +3,8 @@ use std::error::Error; use overlord::Codec; use rlp::{Decodable, DecoderError, Encodable, Rlp, RlpStream}; -use crate::types::{BlockVersion, Bytes, Proposal, BASE_FEE_PER_GAS}; -use crate::{codec::error::CodecError, lazy::CHAIN_ID, ProtocolError}; +use crate::types::{BlockVersion, Bytes, Proposal}; +use crate::{codec::error::CodecError, constants::BASE_FEE_PER_GAS, lazy::CHAIN_ID, ProtocolError}; impl Encodable for BlockVersion { fn rlp_append(&self, s: &mut RlpStream) { @@ -32,7 +32,7 @@ impl Encodable for Proposal { .append(&self.signed_txs_hash) .append(&self.timestamp) .append(&self.number) - .append(&self.gas_limit.as_u64()) + .append(&self.gas_limit.low_u64()) .append_list(&self.extra_data) .append(&self.proof) .append(&self.call_system_script_count) diff --git a/protocol/src/codec/transaction.rs b/protocol/src/codec/transaction.rs index 9659b5a5d..513a84135 100644 --- a/protocol/src/codec/transaction.rs +++ b/protocol/src/codec/transaction.rs @@ -370,7 +370,7 @@ mod tests { use common_crypto::secp256k1_recover; use crate::codec::hex_decode; - use crate::types::{Public, SignatureS, Witness, H160, U256}; + use crate::types::{Public, SignatureS, Witness, H160, U256, U64}; #[test] fn test_legacy_decode() { @@ -379,9 +379,9 @@ mod tests { assert!(tx.check_hash().is_ok()); assert!(tx.unsigned.data().is_empty()); - assert_eq!(*tx.unsigned.gas_limit(), U256::from(0x5208u64)); - assert_eq!(tx.unsigned.gas_price(), U256::from(0x01u64)); - assert_eq!(*tx.unsigned.nonce(), U256::from(0x00u64)); + assert_eq!(*tx.unsigned.gas_limit(), U64::from(0x5208u64)); + assert_eq!(tx.unsigned.gas_price(), U64::from(0x01u64)); + assert_eq!(*tx.unsigned.nonce(), U64::from(0x00u64)); assert_eq!( tx.unsigned.to().unwrap(), H160::from_slice(&hex_decode("095e7baea6a6c7c4c2dfeb977efac326af552d87").unwrap()) @@ -401,9 +401,9 @@ mod tests { let tx = UnverifiedTransaction::decode(&Rlp::new(&bytes)).unwrap(); assert!(tx.unsigned.data().is_empty()); - assert_eq!(*tx.unsigned.gas_limit(), U256::from(0x5208u64)); - assert_eq!(tx.unsigned.gas_price(), U256::from(0x01u64)); - assert_eq!(*tx.unsigned.nonce(), U256::from(0x00u64)); + assert_eq!(*tx.unsigned.gas_limit(), U64::from(0x5208u64)); + assert_eq!(tx.unsigned.gas_price(), U64::from(0x01u64)); + assert_eq!(*tx.unsigned.nonce(), U64::from(0x00u64)); assert_eq!( tx.unsigned.to().unwrap(), H160::from_slice(&hex_decode("095e7baea6a6c7c4c2dfeb977efac326af552d87").unwrap()) @@ -422,9 +422,9 @@ mod tests { let tx = UnverifiedTransaction::decode(&Rlp::new(&bytes)).unwrap(); assert!(tx.unsigned.data().is_empty()); - assert_eq!(*tx.unsigned.gas_limit(), U256::from(0x5208u64)); - assert_eq!(tx.unsigned.gas_price(), U256::from(0x02540be400u64)); - assert_eq!(*tx.unsigned.nonce(), U256::from(0x05u64)); + assert_eq!(*tx.unsigned.gas_limit(), U64::from(0x5208u64)); + assert_eq!(tx.unsigned.gas_price(), U64::from(0x02540be400u64)); + assert_eq!(*tx.unsigned.nonce(), U64::from(0x05u64)); assert_eq!( tx.unsigned.to().unwrap(), H160::from_slice(&hex_decode("f386573563c3a75dbbd269fce9782620826ddac2").unwrap()) @@ -443,9 +443,9 @@ mod tests { let bytes = hex_decode("0xf90a388085174876e800830c35008080b909e5608060405234801561001057600080fd5b506109c5806100206000396000f3fe608060405234801561001057600080fd5b50600436106100a5576000357c010000000000000000000000000000000000000000000000000000000090048063a41e7d5111610078578063a41e7d51146101d4578063aabbb8ca1461020a578063b705676514610236578063f712f3e814610280576100a5565b806329965a1d146100aa5780633d584063146100e25780635df8122f1461012457806365ba36c114610152575b600080fd5b6100e0600480360360608110156100c057600080fd5b50600160a060020a038135811691602081013591604090910135166102b6565b005b610108600480360360208110156100f857600080fd5b5035600160a060020a0316610570565b60408051600160a060020a039092168252519081900360200190f35b6100e06004803603604081101561013a57600080fd5b50600160a060020a03813581169160200135166105bc565b6101c26004803603602081101561016857600080fd5b81019060208101813564010000000081111561018357600080fd5b82018360208201111561019557600080fd5b803590602001918460018302840111640100000000831117156101b757600080fd5b5090925090506106b3565b60408051918252519081900360200190f35b6100e0600480360360408110156101ea57600080fd5b508035600160a060020a03169060200135600160e060020a0319166106ee565b6101086004803603604081101561022057600080fd5b50600160a060020a038135169060200135610778565b61026c6004803603604081101561024c57600080fd5b508035600160a060020a03169060200135600160e060020a0319166107ef565b604080519115158252519081900360200190f35b61026c6004803603604081101561029657600080fd5b508035600160a060020a03169060200135600160e060020a0319166108aa565b6000600160a060020a038416156102cd57836102cf565b335b9050336102db82610570565b600160a060020a031614610339576040805160e560020a62461bcd02815260206004820152600f60248201527f4e6f7420746865206d616e616765720000000000000000000000000000000000604482015290519081900360640190fd5b6103428361092a565b15610397576040805160e560020a62461bcd02815260206004820152601a60248201527f4d757374206e6f7420626520616e204552433136352068617368000000000000604482015290519081900360640190fd5b600160a060020a038216158015906103b85750600160a060020a0382163314155b156104ff5760405160200180807f455243313832305f4143434550545f4d4147494300000000000000000000000081525060140190506040516020818303038152906040528051906020012082600160a060020a031663249cb3fa85846040518363ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018083815260200182600160a060020a0316600160a060020a031681526020019250505060206040518083038186803b15801561047e57600080fd5b505afa158015610492573d6000803e3d6000fd5b505050506040513d60208110156104a857600080fd5b5051146104ff576040805160e560020a62461bcd02815260206004820181905260248201527f446f6573206e6f7420696d706c656d656e742074686520696e74657266616365604482015290519081900360640190fd5b600160a060020a03818116600081815260208181526040808320888452909152808220805473ffffffffffffffffffffffffffffffffffffffff19169487169485179055518692917f93baa6efbd2244243bfee6ce4cfdd1d04fc4c0e9a786abd3a41313bd352db15391a450505050565b600160a060020a03818116600090815260016020526040812054909116151561059a5750806105b7565b50600160a060020a03808216600090815260016020526040902054165b919050565b336105c683610570565b600160a060020a031614610624576040805160e560020a62461bcd02815260206004820152600f60248201527f4e6f7420746865206d616e616765720000000000000000000000000000000000604482015290519081900360640190fd5b81600160a060020a031681600160a060020a0316146106435780610646565b60005b600160a060020a03838116600081815260016020526040808220805473ffffffffffffffffffffffffffffffffffffffff19169585169590951790945592519184169290917f605c2dbf762e5f7d60a546d42e7205dcb1b011ebc62a61736a57c9089d3a43509190a35050565b600082826040516020018083838082843780830192505050925050506040516020818303038152906040528051906020012090505b92915050565b6106f882826107ef565b610703576000610705565b815b600160a060020a03928316600081815260208181526040808320600160e060020a031996909616808452958252808320805473ffffffffffffffffffffffffffffffffffffffff19169590971694909417909555908152600284528181209281529190925220805460ff19166001179055565b600080600160a060020a038416156107905783610792565b335b905061079d8361092a565b156107c357826107ad82826108aa565b6107b85760006107ba565b815b925050506106e8565b600160a060020a0390811660009081526020818152604080832086845290915290205416905092915050565b6000808061081d857f01ffc9a70000000000000000000000000000000000000000000000000000000061094c565b909250905081158061082d575080155b1561083d576000925050506106e8565b61084f85600160e060020a031961094c565b909250905081158061086057508015155b15610870576000925050506106e8565b61087a858561094c565b909250905060018214801561088f5750806001145b1561089f576001925050506106e8565b506000949350505050565b600160a060020a0382166000908152600260209081526040808320600160e060020a03198516845290915281205460ff1615156108f2576108eb83836107ef565b90506106e8565b50600160a060020a03808316600081815260208181526040808320600160e060020a0319871684529091529020549091161492915050565b7bffffffffffffffffffffffffffffffffffffffffffffffffffffffff161590565b6040517f01ffc9a7000000000000000000000000000000000000000000000000000000008082526004820183905260009182919060208160248189617530fa90519096909550935050505056fea165627a7a72305820377f4a2d4301ede9949f163f319021a6e9c687c292a5e2b2c4734c126b524e6c00291ba01820182018201820182018201820182018201820182018201820182018201820a01820182018201820182018201820182018201820182018201820182018201820").unwrap(); let tx = UnverifiedTransaction::decode(&Rlp::new(&bytes)).unwrap(); - assert_eq!(*tx.unsigned.gas_limit(), U256::from(0x0c3500u64)); - assert_eq!(tx.unsigned.gas_price(), U256::from(0x174876e800u64)); - assert_eq!(*tx.unsigned.nonce(), U256::from(0x00u64)); + assert_eq!(*tx.unsigned.gas_limit(), U64::from(0x0c3500u64)); + assert_eq!(tx.unsigned.gas_price(), U64::from(0x174876e800u64)); + assert_eq!(*tx.unsigned.nonce(), U64::from(0x00u64)); assert_eq!( tx.unsigned.data(), hex_decode("608060405234801561001057600080fd5b506109c5806100206000396000f3fe608060405234801561001057600080fd5b50600436106100a5576000357c010000000000000000000000000000000000000000000000000000000090048063a41e7d5111610078578063a41e7d51146101d4578063aabbb8ca1461020a578063b705676514610236578063f712f3e814610280576100a5565b806329965a1d146100aa5780633d584063146100e25780635df8122f1461012457806365ba36c114610152575b600080fd5b6100e0600480360360608110156100c057600080fd5b50600160a060020a038135811691602081013591604090910135166102b6565b005b610108600480360360208110156100f857600080fd5b5035600160a060020a0316610570565b60408051600160a060020a039092168252519081900360200190f35b6100e06004803603604081101561013a57600080fd5b50600160a060020a03813581169160200135166105bc565b6101c26004803603602081101561016857600080fd5b81019060208101813564010000000081111561018357600080fd5b82018360208201111561019557600080fd5b803590602001918460018302840111640100000000831117156101b757600080fd5b5090925090506106b3565b60408051918252519081900360200190f35b6100e0600480360360408110156101ea57600080fd5b508035600160a060020a03169060200135600160e060020a0319166106ee565b6101086004803603604081101561022057600080fd5b50600160a060020a038135169060200135610778565b61026c6004803603604081101561024c57600080fd5b508035600160a060020a03169060200135600160e060020a0319166107ef565b604080519115158252519081900360200190f35b61026c6004803603604081101561029657600080fd5b508035600160a060020a03169060200135600160e060020a0319166108aa565b6000600160a060020a038416156102cd57836102cf565b335b9050336102db82610570565b600160a060020a031614610339576040805160e560020a62461bcd02815260206004820152600f60248201527f4e6f7420746865206d616e616765720000000000000000000000000000000000604482015290519081900360640190fd5b6103428361092a565b15610397576040805160e560020a62461bcd02815260206004820152601a60248201527f4d757374206e6f7420626520616e204552433136352068617368000000000000604482015290519081900360640190fd5b600160a060020a038216158015906103b85750600160a060020a0382163314155b156104ff5760405160200180807f455243313832305f4143434550545f4d4147494300000000000000000000000081525060140190506040516020818303038152906040528051906020012082600160a060020a031663249cb3fa85846040518363ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018083815260200182600160a060020a0316600160a060020a031681526020019250505060206040518083038186803b15801561047e57600080fd5b505afa158015610492573d6000803e3d6000fd5b505050506040513d60208110156104a857600080fd5b5051146104ff576040805160e560020a62461bcd02815260206004820181905260248201527f446f6573206e6f7420696d706c656d656e742074686520696e74657266616365604482015290519081900360640190fd5b600160a060020a03818116600081815260208181526040808320888452909152808220805473ffffffffffffffffffffffffffffffffffffffff19169487169485179055518692917f93baa6efbd2244243bfee6ce4cfdd1d04fc4c0e9a786abd3a41313bd352db15391a450505050565b600160a060020a03818116600090815260016020526040812054909116151561059a5750806105b7565b50600160a060020a03808216600090815260016020526040902054165b919050565b336105c683610570565b600160a060020a031614610624576040805160e560020a62461bcd02815260206004820152600f60248201527f4e6f7420746865206d616e616765720000000000000000000000000000000000604482015290519081900360640190fd5b81600160a060020a031681600160a060020a0316146106435780610646565b60005b600160a060020a03838116600081815260016020526040808220805473ffffffffffffffffffffffffffffffffffffffff19169585169590951790945592519184169290917f605c2dbf762e5f7d60a546d42e7205dcb1b011ebc62a61736a57c9089d3a43509190a35050565b600082826040516020018083838082843780830192505050925050506040516020818303038152906040528051906020012090505b92915050565b6106f882826107ef565b610703576000610705565b815b600160a060020a03928316600081815260208181526040808320600160e060020a031996909616808452958252808320805473ffffffffffffffffffffffffffffffffffffffff19169590971694909417909555908152600284528181209281529190925220805460ff19166001179055565b600080600160a060020a038416156107905783610792565b335b905061079d8361092a565b156107c357826107ad82826108aa565b6107b85760006107ba565b815b925050506106e8565b600160a060020a0390811660009081526020818152604080832086845290915290205416905092915050565b6000808061081d857f01ffc9a70000000000000000000000000000000000000000000000000000000061094c565b909250905081158061082d575080155b1561083d576000925050506106e8565b61084f85600160e060020a031961094c565b909250905081158061086057508015155b15610870576000925050506106e8565b61087a858561094c565b909250905060018214801561088f5750806001145b1561089f576001925050506106e8565b506000949350505050565b600160a060020a0382166000908152600260209081526040808320600160e060020a03198516845290915281205460ff1615156108f2576108eb83836107ef565b90506106e8565b50600160a060020a03808316600081815260208181526040808320600160e060020a0319871684529091529020549091161492915050565b7bffffffffffffffffffffffffffffffffffffffffffffffffffffffff161590565b6040517f01ffc9a7000000000000000000000000000000000000000000000000000000008082526004820183905260009182919060208160248189617530fa90519096909550935050505056fea165627a7a72305820377f4a2d4301ede9949f163f319021a6e9c687c292a5e2b2c4734c126b524e6c0029").unwrap() diff --git a/protocol/src/constants/configs.rs b/protocol/src/constants/configs.rs new file mode 100644 index 000000000..c09edd2ac --- /dev/null +++ b/protocol/src/constants/configs.rs @@ -0,0 +1,20 @@ +use crate::types::U64; + +/// There is not a standard for the maximum gas limit, as long as the account +/// balance can pay the `gas_limit * gas_price`. For reduce some useless +/// calculation, `30_000_000` is large enough to cover the transaction usage. +pub const MAX_GAS_LIMIT: u64 = 30_000_000; +/// According to [go-ethereum](https://github.com/ethereum/go-ethereum/blob/be65b47/eth/gasprice/gasprice.go#L38), +/// the maximum gas price is 500 Gwei. +pub const MAX_GAS_PRICE: U64 = U64([500 * GWEI]); +pub const MIN_TRANSACTION_GAS_LIMIT: u64 = 21_000; +/// The mempool refresh timeout is 50 milliseconds. +pub const MEMPOOL_REFRESH_TIMEOUT: u64 = 50; +pub const MAX_BLOCK_GAS_LIMIT: u64 = 30_000_000; +// MAX_FEE_HISTORY is the maximum number of blocks that can be retrieved for a +// fee history request. Between 1 and 1024 blocks can be requested in a single +// query. reference: https://docs.infura.io/infura/networks/ethereum/json-rpc-methods/eth_feehistory/ +pub const MAX_FEE_HISTORY: u64 = 1024; +pub const BASE_FEE_PER_GAS: u64 = 0x539; + +const GWEI: u64 = 1_000_000_000; diff --git a/protocol/src/constants/mod.rs b/protocol/src/constants/mod.rs index c4b360f4b..8c5992f31 100644 --- a/protocol/src/constants/mod.rs +++ b/protocol/src/constants/mod.rs @@ -1 +1,4 @@ +mod configs; pub mod endpoints; + +pub use configs::*; diff --git a/protocol/src/lib.rs b/protocol/src/lib.rs index 9bf7d0963..ad1dcd379 100644 --- a/protocol/src/lib.rs +++ b/protocol/src/lib.rs @@ -12,8 +12,6 @@ pub use { trie, }; -pub const MEMPOOL_REFRESH_TIMEOUT: u64 = 50; - #[derive(Copy, Clone, Debug)] pub enum ProtocolErrorKind { // traits diff --git a/protocol/src/traits/api.rs b/protocol/src/traits/api.rs index 0964a1dfc..ae1334710 100644 --- a/protocol/src/traits/api.rs +++ b/protocol/src/traits/api.rs @@ -1,7 +1,7 @@ use crate::types::{ Account, Block, BlockNumber, Bytes, CkbRelatedInfo, EthAccountProof, HardforkInfo, HardforkInfoInner, Hash, Header, Metadata, Proposal, Receipt, SignedTransaction, TxResp, H160, - H256, U256, + H256, U256, U64, }; use crate::{async_trait, traits::Context, ProtocolResult}; @@ -79,8 +79,8 @@ pub trait APIAdapter: Send + Sync { ctx: Context, from: Option, to: Option, - gas_price: Option, - gas_limit: Option, + gas_price: Option, + gas_limit: Option, value: U256, data: Vec, estimate: bool, diff --git a/protocol/src/traits/executor.rs b/protocol/src/traits/executor.rs index f46790d4e..44940f20b 100644 --- a/protocol/src/traits/executor.rs +++ b/protocol/src/traits/executor.rs @@ -2,7 +2,7 @@ pub use evm::backend::{ApplyBackend, Backend, MemoryBackend}; use crate::types::{ Account, Bytes, ExecResp, ExecutorContext, Log, MerkleRoot, SignedTransaction, TxResp, - ValidatorExtend, H160, U256, + ValidatorExtend, H160, U256, U64, }; pub trait ExecutorReadOnlyAdapter: Backend { @@ -16,7 +16,7 @@ pub trait ExecutorReadOnlyAdapter: Backend { pub trait ExecutorAdapter: ExecutorReadOnlyAdapter + ApplyBackend { fn set_origin(&mut self, origin: H160); - fn set_gas_price(&mut self, gas_price: U256); + fn set_gas_price(&mut self, gas_price: U64); fn save_account(&mut self, address: &H160, account: &Account); @@ -65,7 +65,7 @@ impl<'a> ExecutorAdapter for MemoryBackend<'a> { unreachable!() } - fn set_gas_price(&mut self, _gas_price: U256) { + fn set_gas_price(&mut self, _gas_price: U64) { unreachable!() } diff --git a/protocol/src/traits/mempool.rs b/protocol/src/traits/mempool.rs index 9c77c1c9d..c0ddfc89e 100644 --- a/protocol/src/traits/mempool.rs +++ b/protocol/src/traits/mempool.rs @@ -1,4 +1,6 @@ -use crate::types::{BlockNumber, Hash, MerkleRoot, PackedTxHashes, SignedTransaction, H160, U256}; +use crate::types::{ + BlockNumber, Hash, MerkleRoot, PackedTxHashes, SignedTransaction, H160, U256, U64, +}; use crate::{async_trait, traits::Context, ProtocolResult}; #[async_trait] @@ -65,7 +67,7 @@ pub trait MemPoolAdapter: Send + Sync { &self, ctx: Context, tx: &SignedTransaction, - ) -> ProtocolResult; + ) -> ProtocolResult; async fn check_transaction(&self, ctx: Context, tx: &SignedTransaction) -> ProtocolResult<()>; diff --git a/protocol/src/types/block.rs b/protocol/src/types/block.rs index 4dfbd7f0b..0293eb09c 100644 --- a/protocol/src/types/block.rs +++ b/protocol/src/types/block.rs @@ -7,20 +7,12 @@ use serde::{Deserialize, Serialize}; use crate::codec::serialize_uint; use crate::types::{ logs_bloom, Bloom, BloomInput, Bytes, ExecResp, Hash, Hasher, Log, MerkleRoot, Receipt, - SignedTransaction, VecDisplayHelper, H160, U256, + SignedTransaction, VecDisplayHelper, H160, U64, }; use crate::{codec::ProtocolCodec, types::TypesError}; pub type BlockNumber = u64; -pub const MAX_BLOCK_GAS_LIMIT: u64 = 30_000_000; -// MAX_FEE_HISTORY is the maximum number of blocks that can be retrieved for a -// fee history request. Between 1 and 1024 blocks can be requested in a single -// query. reference: https://docs.infura.io/infura/networks/ethereum/json-rpc-methods/eth_feehistory/ -pub const MAX_FEE_HISTORY: u64 = 1024; -pub const MAX_RPC_GAS_CAP: u64 = 50_000_000; -pub const BASE_FEE_PER_GAS: u64 = 0x539; - #[derive(Serialize, Deserialize, Default, Copy, Clone, Debug, PartialEq, Eq, Display)] pub enum BlockVersion { #[default] @@ -81,9 +73,9 @@ pub struct Proposal { pub timestamp: u64, #[cfg_attr(feature = "hex-serialize", serde(serialize_with = "serialize_uint"))] pub number: BlockNumber, - pub gas_limit: U256, + pub gas_limit: U64, pub extra_data: Vec, - pub base_fee_per_gas: U256, + pub base_fee_per_gas: U64, pub proof: Proof, #[cfg_attr(feature = "hex-serialize", serde(serialize_with = "serialize_uint"))] pub chain_id: u64, @@ -217,7 +209,7 @@ impl Block { block_hash: self.hash(), tx_index: idx as u32, state_root: self.header.state_root, - used_gas: U256::from(res.gas_used), + used_gas: U64::from(res.gas_used), logs_bloom: logs_bloom(res.logs.iter()), logs: res.logs.clone(), log_index, @@ -286,13 +278,13 @@ pub struct Header { pub timestamp: u64, #[cfg_attr(feature = "hex-serialize", serde(serialize_with = "serialize_uint"))] pub number: BlockNumber, - pub gas_used: U256, - pub gas_limit: U256, + pub gas_used: U64, + pub gas_limit: U64, /// Extra data for the block header /// The first index of extra_data is used to store hardfork information: /// `HardforkInfoInner` pub extra_data: Vec, - pub base_fee_per_gas: U256, + pub base_fee_per_gas: U64, pub proof: Proof, #[cfg_attr(feature = "hex-serialize", serde(serialize_with = "serialize_uint"))] pub call_system_script_count: u32, diff --git a/protocol/src/types/executor.rs b/protocol/src/types/executor.rs index 9328ef81c..59895b56a 100644 --- a/protocol/src/types/executor.rs +++ b/protocol/src/types/executor.rs @@ -6,7 +6,7 @@ use rlp_derive::{RlpDecodable, RlpEncodable}; use serde::{Deserialize, Serialize}; use crate::types::{ - Bloom, ExtraData, Hash, Hasher, Header, MerkleRoot, Proposal, H160, H256, U256, + Bloom, ExtraData, Hash, Hasher, Header, MerkleRoot, Proposal, H160, H256, U256, U64, }; use super::Hex; @@ -56,8 +56,8 @@ pub struct ExecutorContext { pub chain_id: U256, pub origin: H160, pub gas_price: U256, - pub block_gas_limit: U256, - pub block_base_fee_per_gas: U256, + pub block_gas_limit: U64, + pub block_base_fee_per_gas: U64, pub extra_data: Vec, } diff --git a/protocol/src/types/mod.rs b/protocol/src/types/mod.rs index 1b8fcbce1..34530cf77 100644 --- a/protocol/src/types/mod.rs +++ b/protocol/src/types/mod.rs @@ -87,6 +87,9 @@ pub enum TypesError { #[display(fmt = "Decode interoperation signature R error {:?}", _0)] DecodeInteroperationSigR(rlp::DecoderError), + + #[display(fmt = "Prepay gas is too large")] + PrepayGasIsTooLarge, } impl Error for TypesError {} diff --git a/protocol/src/types/primitive.rs b/protocol/src/types/primitive.rs index eaa1ce78e..5196108e2 100644 --- a/protocol/src/types/primitive.rs +++ b/protocol/src/types/primitive.rs @@ -174,7 +174,6 @@ impl<'de> Deserialize<'de> for Hex { } /// A 256 bits bytes used for sensitive data, such as private keys. -/// /// It's implemented a `Drop` handler which erase its memory when it dropped. /// This ensures that sensitive data is securely erased from memory when it is /// no longer needed. diff --git a/protocol/src/types/receipt.rs b/protocol/src/types/receipt.rs index 4e57289b8..62019dd30 100644 --- a/protocol/src/types/receipt.rs +++ b/protocol/src/types/receipt.rs @@ -1,7 +1,7 @@ pub use ethereum::Log; pub use ethereum_types::BloomInput; -use crate::types::{Bloom, ExitReason, ExitSucceed, Hash, MerkleRoot, H160, U256}; +use crate::types::{Bloom, ExitReason, ExitSucceed, Hash, MerkleRoot, H160, U64}; #[derive(Clone, Debug, PartialEq, Eq)] pub struct Receipt { @@ -10,7 +10,7 @@ pub struct Receipt { pub block_hash: Hash, pub tx_index: u32, pub state_root: MerkleRoot, - pub used_gas: U256, + pub used_gas: U64, pub logs_bloom: Bloom, pub logs: Vec, pub log_index: u32, @@ -41,10 +41,10 @@ impl Default for Receipt { } impl Receipt { - pub fn status(&self) -> U256 { + pub fn status(&self) -> U64 { match self.ret { - ExitReason::Succeed(_) => U256::one(), - _ => U256::zero(), + ExitReason::Succeed(_) => U64::one(), + _ => U64::zero(), } } } diff --git a/protocol/src/types/transaction.rs b/protocol/src/types/transaction.rs index 563ff0ff1..20d2c06b9 100644 --- a/protocol/src/types/transaction.rs +++ b/protocol/src/types/transaction.rs @@ -9,12 +9,11 @@ use common_crypto::secp256k1_recover; use crate::types::{ Bloom, Bytes, BytesMut, CellDepWithPubKey, ExitReason, Hash, Hasher, Public, TxResp, - TypesError, H160, H256, H520, U256, + TypesError, H160, H256, H520, U256, U64, }; use crate::ProtocolResult; pub const MAX_PRIORITY_FEE_PER_GAS: u64 = 1_337; -pub const MIN_TRANSACTION_GAS_LIMIT: u64 = 21_000; #[derive(Serialize, Deserialize, Clone, Debug, Hash, PartialEq, Eq)] pub enum UnsignedTransaction { @@ -32,14 +31,16 @@ impl UnsignedTransaction { } } - pub fn may_cost(&self) -> U256 { - if let Some(res) = self.gas_price().checked_mul(*self.gas_limit()) { - return res + pub fn may_cost(&self) -> ProtocolResult { + if let Some(res) = U256::from(self.gas_price().low_u64()) + .checked_mul(U256::from(self.gas_limit().low_u64())) + { + return Ok(res .checked_add(*self.value()) - .unwrap_or_else(U256::max_value); + .unwrap_or_else(U256::max_value)); } - U256::max_value() + Err(TypesError::PrepayGasIsTooLarge.into()) } pub fn is_legacy(&self) -> bool { @@ -74,7 +75,7 @@ impl UnsignedTransaction { } } - pub fn gas_price(&self) -> U256 { + pub fn gas_price(&self) -> U64 { match self { UnsignedTransaction::Legacy(tx) => tx.gas_price, UnsignedTransaction::Eip2930(tx) => tx.gas_price, @@ -82,7 +83,7 @@ impl UnsignedTransaction { } } - pub fn max_priority_fee_per_gas(&self) -> &U256 { + pub fn max_priority_fee_per_gas(&self) -> &U64 { match self { UnsignedTransaction::Legacy(tx) => &tx.gas_price, UnsignedTransaction::Eip2930(tx) => &tx.gas_price, @@ -135,7 +136,7 @@ impl UnsignedTransaction { } } - pub fn gas_limit(&self) -> &U256 { + pub fn gas_limit(&self) -> &U64 { match self { UnsignedTransaction::Legacy(tx) => &tx.gas_limit, UnsignedTransaction::Eip2930(tx) => &tx.gas_limit, @@ -143,7 +144,7 @@ impl UnsignedTransaction { } } - pub fn nonce(&self) -> &U256 { + pub fn nonce(&self) -> &U64 { match self { UnsignedTransaction::Legacy(tx) => &tx.nonce, UnsignedTransaction::Eip2930(tx) => &tx.nonce, @@ -170,9 +171,11 @@ impl UnsignedTransaction { #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct LegacyTransaction { - pub nonce: U256, - pub gas_price: U256, - pub gas_limit: U256, + /// According to [EIP-2681](https://eips.ethereum.org/EIPS/eip-2681), + /// limit account nonce to 2^64-1. + pub nonce: U64, + pub gas_price: U64, + pub gas_limit: U64, pub action: TransactionAction, pub value: U256, pub data: Bytes, @@ -202,9 +205,11 @@ impl LegacyTransaction { #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct Eip2930Transaction { - pub nonce: U256, - pub gas_price: U256, - pub gas_limit: U256, + /// According to [EIP-2681](https://eips.ethereum.org/EIPS/eip-2681), + /// limit account nonce to 2^64-1. + pub nonce: U64, + pub gas_price: U64, + pub gas_limit: U64, pub action: TransactionAction, pub value: U256, pub data: Bytes, @@ -239,10 +244,10 @@ impl Eip2930Transaction { #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct Eip1559Transaction { - pub nonce: U256, - pub max_priority_fee_per_gas: U256, - pub gas_price: U256, - pub gas_limit: U256, + pub nonce: U64, + pub max_priority_fee_per_gas: U64, + pub gas_price: U64, + pub gas_limit: U64, pub action: TransactionAction, pub value: U256, pub data: Bytes, diff --git a/tests/e2e/src/eth_call.test.js b/tests/e2e/src/eth_call.test.js index 8b04eb8d2..feb31f9f6 100644 --- a/tests/e2e/src/eth_call.test.js +++ b/tests/e2e/src/eth_call.test.js @@ -235,7 +235,7 @@ describe("eth_call", () => { await param1.type(testDataInfo.accountAddress); await param2.type(testDataInfo.contractAddress); await param3.type("0x210000"); - await param4.type("0xfffffffffff"); + await param4.type("0xffff"); await param5.type("0x0"); await param6.type("0x06fdde03"); await param7.type("latest"); @@ -264,7 +264,7 @@ describe("eth_call", () => { await param1.type(testDataInfo.contractAddress); await param2.type(testDataInfo.contractAddress); await param3.type("0x210000"); - await param4.type("0xfffffffffff"); + await param4.type("0xffff"); await param5.type("0x0"); await param6.type("0x06fdde03"); await param7.type("latest"); @@ -293,7 +293,7 @@ describe("eth_call", () => { await param1.type(testDataInfo.contractAddress); await param2.type("0x63010dD4c3164dd0D73eCB518972916161fBACd9"); await param3.type("0x210000"); - await param4.type("0xfffffffffff"); + await param4.type("0xffff"); await param5.type("0x0"); await param6.type("0x06fdde03"); await param7.type("latest"); @@ -322,7 +322,7 @@ describe("eth_call", () => { await param1.type("0x735EaC8A5f3F197799f2FEaEbc0F6B3F6e4c345D"); await param2.type(testDataInfo.contractAddress); await param3.type("0x210000"); - await param4.type("0xfffffffffff"); + await param4.type("0xffff"); await param5.type("0x0"); await param6.type("0x06fdde03"); await param7.type("latest");