Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: change some types from U256 to U64 #1539

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion core/api/src/adapter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,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))
Expand Down
4 changes: 2 additions & 2 deletions core/api/src/jsonrpc/error.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use jsonrpsee::types::{error::ErrorObject, ErrorObjectOwned};

use protocol::types::{ExitReason, TxResp};
use protocol::types::{ExitReason, TxResp, U256};
use protocol::{codec::hex_encode, Display};

use core_executor::decode_revert_msg;
Expand Down Expand Up @@ -42,7 +42,7 @@ pub enum RpcError {
#[display(fmt = "Invalid newest block {:?}", _0)]
InvalidNewestBlock(BlockId),
#[display(fmt = "Invalid position {}", _0)]
InvalidPosition(u64),
InvalidPosition(U256),
#[display(fmt = "Cannot find the block")]
CannotFindBlock,
#[display(fmt = "Invalid reward percentiles {} {}", _0, _1)]
Expand Down
16 changes: 11 additions & 5 deletions core/api/src/jsonrpc/impl/axon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use common_config_parser::types::spec::HardforkName;
use protocol::async_trait;
use protocol::traits::{APIAdapter, Context};
use protocol::types::{
Block, CkbRelatedInfo, HardforkInfoInner, Metadata, Proof, Proposal, H256, U256,
Block, CkbRelatedInfo, HardforkInfoInner, Metadata, Proof, Proposal, H256, U64,
};

use crate::jsonrpc::web3_types::{BlockId, HardforkStatus};
Expand All @@ -28,9 +28,15 @@ impl<Adapter: APIAdapter + 'static> AxonRpcServer for AxonRpcImpl<Adapter> {
async fn get_block_by_id(&self, block_id: BlockId) -> RpcResult<Option<Block>> {
let ret = match block_id {
BlockId::Hash(hash) => self.adapter.get_block_by_hash(Context::new(), hash).await,
// The block number is checked when deserialize
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::Earliest => {
self.adapter
.get_block_by_number(Context::new(), Some(0))
.await
}
BlockId::Latest => self.adapter.get_block_by_number(Context::new(), None).await,
Expand All @@ -49,17 +55,17 @@ impl<Adapter: APIAdapter + 'static> AxonRpcServer for AxonRpcImpl<Adapter> {
Ok(ret)
}

async fn get_metadata_by_number(&self, block_number: U256) -> RpcResult<Metadata> {
async fn get_metadata_by_number(&self, block_number: U64) -> RpcResult<Metadata> {
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()))?;

Ok(ret)
}

async fn get_proposal_by_number(&self, block_number: U256) -> RpcResult<Proposal> {
async fn get_proposal_by_number(&self, block_number: U64) -> RpcResult<Proposal> {
let block_number = block_number.low_u64();

let prev_state_root = if block_number == 0 {
Expand Down
4 changes: 2 additions & 2 deletions core/api/src/jsonrpc/impl/filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)));
}
}
Expand Down Expand Up @@ -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,
}
Expand Down
41 changes: 20 additions & 21 deletions core/api/src/jsonrpc/impl/web3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,16 @@ 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,
MAX_FEE_HISTORY, MAX_RPC_GAS_CAP, MIN_TRANSACTION_GAS_LIMIT, U256, U64,
};
use protocol::{
async_trait, codec::ProtocolCodec, lazy::PROTOCOL_VERSION, tokio::time::sleep, ProtocolResult,
MEMPOOL_REFRESH_TIMEOUT,
};

use crate::jsonrpc::web3_types::{
BlockCount, BlockId, FeeHistoryEmpty, FeeHistoryWithReward, FeeHistoryWithoutReward,
RichTransactionOrHash, Web3Block, Web3CallRequest, Web3FeeHistory, Web3Filter, Web3Log,
Web3Receipt, Web3Transaction,
BlockId, FeeHistoryEmpty, FeeHistoryWithReward, FeeHistoryWithoutReward, RichTransactionOrHash,
Web3Block, Web3CallRequest, Web3FeeHistory, Web3Filter, Web3Log, Web3Receipt, Web3Transaction,
};
use crate::jsonrpc::{error::RpcError, Web3RpcServer};
use crate::APIError;
Expand Down Expand Up @@ -130,7 +129,7 @@ impl<Adapter: APIAdapter> Web3RpcImpl<Adapter> {
async fn inner_fee_history(
&self,
height: Option<u64>,
block_count: U256,
block_count: u64,
reward_percentiles: &Option<Vec<f64>>,
) -> Result<(u64, Vec<U256>, Vec<f64>, Vec<Vec<U256>>), RpcError> {
let latest_block = self
Expand All @@ -142,7 +141,7 @@ impl<Adapter: APIAdapter> Web3RpcImpl<Adapter> {

let latest_block_number = latest_block.header.number;
let oldest_block_number = latest_block_number
.saturating_sub(block_count.as_u64())
.saturating_sub(block_count)
.saturating_add(1);

let mut bash_fee_per_gases: Vec<U256> = Vec::new();
Expand Down Expand Up @@ -209,6 +208,7 @@ impl<Adapter: APIAdapter + 'static> Web3RpcServer for Web3RpcImpl<Adapter> {
return Err(RpcError::GasLimitIsTooLow.into());
}

// The max_gas_cap must be le u64::MAX
if gas_limit > self.max_gas_cap {
return Err(RpcError::GasLimitIsTooLarge.into());
}
Expand Down Expand Up @@ -454,7 +454,7 @@ impl<Adapter: APIAdapter + 'static> Web3RpcServer for Web3RpcImpl<Adapter> {
}

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
Expand Down Expand Up @@ -673,7 +673,7 @@ impl<Adapter: APIAdapter + 'static> Web3RpcServer for Web3RpcImpl<Adapter> {
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,
}
Expand Down Expand Up @@ -741,31 +741,29 @@ impl<Adapter: APIAdapter + 'static> Web3RpcServer for Web3RpcImpl<Adapter> {
#[metrics_rpc("eth_feeHistory")]
async fn fee_history(
&self,
block_count: BlockCount,
block_count: U64,
newest_block: BlockId,
reward_percentiles: Option<Vec<f64>>,
) -> RpcResult<Web3FeeHistory> {
check_reward_percentiles(&reward_percentiles)?;

let mut blocks_count;
match block_count {
BlockCount::U256Type(n) => blocks_count = n,
BlockCount::U64Type(n) => blocks_count = n.into(),
}
let mut blocks_count = block_count.low_u64();
// Between 1 and 1024 blocks can be requested in a single query.
if blocks_count > MAX_FEE_HISTORY.into() {
blocks_count = MAX_FEE_HISTORY.into();
if blocks_count > MAX_FEE_HISTORY {
blocks_count = MAX_FEE_HISTORY;
}
if blocks_count == 0.into() {

if blocks_count == 0 {
return Ok(Web3FeeHistory::ZeroBlockCount(FeeHistoryEmpty {
oldest_block: U256::zero(),
gas_used_ratio: None,
}));
}

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 {
Expand Down Expand Up @@ -891,7 +889,7 @@ impl<Adapter: APIAdapter + 'static> Web3RpcServer for Web3RpcImpl<Adapter> {
position: U256,
) -> RpcResult<Option<Web3Transaction>> {
if position > U256::from(usize::MAX) {
return Err(RpcError::InvalidPosition(position.as_u64()).into());
return Err(RpcError::InvalidPosition(position).into());
}

let mut raw = [0u8; 32];
Expand Down Expand Up @@ -922,7 +920,7 @@ impl<Adapter: APIAdapter + 'static> Web3RpcServer for Web3RpcImpl<Adapter> {
position: U256,
) -> RpcResult<Option<Web3Transaction>> {
if position > U256::from(usize::MAX) {
return Err(RpcError::InvalidPosition(position.as_u64()).into());
return Err(RpcError::InvalidPosition(position).into());
}

let mut raw = [0u8; 32];
Expand Down Expand Up @@ -1047,7 +1045,8 @@ fn check_reward_percentiles(reward_percentiles: &Option<Vec<f64>>) -> RpcResult<
fn calculate_gas_used_ratio(block: &Block) -> f64 {
(block.header.gas_limit != U256::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.low_u64() as f64
* 100f64
})
.unwrap_or(0f64)
}
Expand Down
12 changes: 6 additions & 6 deletions core/api/src/jsonrpc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@ use common_config_parser::types::{spec::HardforkName, Config};
use protocol::traits::APIAdapter;
use protocol::types::{
Block, CkbRelatedInfo, EthAccountProof, Hash, Hex, Metadata, Proof, Proposal, H160, H256, U256,
U64,
};
use protocol::ProtocolResult;

use crate::jsonrpc::web3_types::{
BlockCount, BlockId, FilterChanges, HardforkStatus, RawLoggerFilter, Web3Block,
Web3CallRequest, Web3FeeHistory, Web3Filter, Web3Log, Web3Receipt, Web3SyncStatus,
Web3Transaction,
BlockId, FilterChanges, HardforkStatus, RawLoggerFilter, Web3Block, Web3CallRequest,
Web3FeeHistory, Web3Filter, Web3Log, Web3Receipt, Web3SyncStatus, Web3Transaction,
};
use crate::jsonrpc::ws_subscription::{ws_subscription_module, HexIdProvider};
use crate::APIError;
Expand Down Expand Up @@ -88,7 +88,7 @@ pub trait Web3Rpc {
#[method(name = "eth_feeHistory")]
async fn fee_history(
&self,
block_count: BlockCount,
block_count: U64,
newest_block: BlockId,
reward_percentiles: Option<Vec<f64>>,
) -> RpcResult<Web3FeeHistory>;
Expand Down Expand Up @@ -222,10 +222,10 @@ pub trait AxonRpc {
async fn get_proof_by_id(&self, block_id: BlockId) -> RpcResult<Option<Proof>>;

#[method(name = "axon_getMetadataByNumber")]
async fn get_metadata_by_number(&self, block_number: U256) -> RpcResult<Metadata>;
async fn get_metadata_by_number(&self, block_number: U64) -> RpcResult<Metadata>;

#[method(name = "axon_getProposalByNumber")]
async fn get_proposal_by_number(&self, block_number: U256) -> RpcResult<Proposal>;
async fn get_proposal_by_number(&self, block_number: U64) -> RpcResult<Proposal>;

#[method(name = "axon_getCurrentMetadata")]
async fn get_current_metadata(&self) -> RpcResult<Metadata>;
Expand Down
10 changes: 2 additions & 8 deletions core/api/src/jsonrpc/web3_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -334,7 +334,8 @@ pub enum BlockId {
impl From<BlockId> for Option<u64> {
fn from(id: BlockId) -> Self {
match id {
BlockId::Num(num) => Some(num.as_u64()),
// The BlockId deserialize visitor will ensure that the number is in u64 range.
BlockId::Num(num) => Some(num.low_u64()),
BlockId::Earliest => Some(0),
_ => None,
}
Expand Down Expand Up @@ -690,13 +691,6 @@ pub struct SyncStatus {
pub pulled_states: U256,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
#[serde(deny_unknown_fields, rename_all = "camelCase", untagged)]
pub enum BlockCount {
U64Type(u64),
U256Type(U256),
}

/// Response type for `eth_feeHistory` RPC call.
/// Three types of response are possible:
/// 1. With reward, it returned when request parameter REWARDPERCENTILES is not
Expand Down
2 changes: 1 addition & 1 deletion core/consensus/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -729,7 +729,7 @@ impl<Adapter: ConsensusAdapter + 'static> ConsensusEngine<Adapter> {
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 {
Expand Down
10 changes: 5 additions & 5 deletions core/executor/benches/revm_adapter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
})?))
Expand Down Expand Up @@ -101,11 +101,11 @@ where

fn block_hash(&mut self, number: U256) -> Result<H256, Self::Error> {
let current_number = self.exec_ctx.block_number;
if number.as_u64() > current_number.as_u64() {
if number > current_number {
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();
Expand Down Expand Up @@ -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(),
Expand All @@ -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![],
Expand Down
2 changes: 1 addition & 1 deletion core/executor/src/adapter/backend/read_only.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,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()
Expand Down
2 changes: 1 addition & 1 deletion core/executor/src/debugger/create2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ 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 {
Expand Down
6 changes: 3 additions & 3 deletions core/executor/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,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.low_u64(), config);
let mut executor = StackExecutor::new_with_precompiles(
MemoryStackState::new(metadata, adapter),
config,
Expand All @@ -333,14 +333,14 @@ impl AxonExecutor {
*addr,
*tx.transaction.unsigned.value(),
tx.transaction.unsigned.data().to_vec(),
gas_limit.as_u64(),
gas_limit.low_u64(),
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.low_u64(),
access_list,
),
};
Expand Down
Loading
Loading