Skip to content

Commit

Permalink
Merge branch 'master' into v2.0-testnet
Browse files Browse the repository at this point in the history
  • Loading branch information
peilun-conflux committed Jun 11, 2024
2 parents 5267441 + ac8834b commit d88d953
Show file tree
Hide file tree
Showing 21 changed files with 781 additions and 71 deletions.
3 changes: 2 additions & 1 deletion crates/client/src/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ mod traits;
pub mod types;

pub use cfxcore::rpc_errors::{
BoxFuture as RpcBoxFuture, Error as RpcError, ErrorKind as RpcErrorKind,
invalid_params, invalid_params_check, BoxFuture as RpcBoxFuture,
Error as RpcError, ErrorKind as RpcErrorKind,
ErrorKind::JsonRpcError as JsonRpcErrorKind, Result as RpcResult,
};

Expand Down
27 changes: 19 additions & 8 deletions crates/client/src/rpc/impls/cfx/cfx_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use crate::rpc::{
error_codes::{internal_error_msg, invalid_params_msg},
types::{
call_request::rpc_call_request_network,
errors::check_rpc_address_network, pos::PoSEpochReward, FeeHistory,
errors::check_rpc_address_network, pos::PoSEpochReward, CfxFeeHistory,
PoSEconomics, RpcAddress, SponsorInfo, StatOnGasLoad, TokenSupplyInfo,
VoteParamsInfo, WrapTransaction, U64 as HexU64,
},
Expand Down Expand Up @@ -47,7 +47,7 @@ use network::{
};
use parking_lot::Mutex;
use primitives::{
filter::LogFilter, receipt::EVM_SPACE_SUCCESS, Account, Block,
filter::LogFilter, receipt::EVM_SPACE_SUCCESS, Account, Block, BlockHeader,
BlockReceipts, DepositInfo, SignedTransaction, StorageKey, StorageRoot,
StorageValue, Transaction, TransactionIndex, TransactionStatus,
TransactionWithSignature, VoteStakeInfo,
Expand Down Expand Up @@ -115,7 +115,7 @@ pub(crate) struct BlockExecInfo {
pub(crate) block: Arc<Block>,
pub(crate) epoch_number: u64,
pub(crate) maybe_state_root: Option<H256>,
pub(crate) pivot_hash: H256,
pub(crate) pivot_header: Arc<BlockHeader>,
}

pub struct RpcImpl {
Expand Down Expand Up @@ -790,12 +790,23 @@ impl RpcImpl {
bail!("Inconsistent state");
}

let pivot_header = if let Some(x) = self
.consensus
.get_data_manager()
.block_header_by_hash(&pivot_hash)
{
x
} else {
warn!("Cannot find pivot header when get block execution info: pivot hash {:?}", pivot_hash);
return Ok(None);
};

Ok(Some(BlockExecInfo {
block_receipts,
block,
epoch_number,
maybe_state_root,
pivot_hash,
pivot_header,
}))
}

Expand Down Expand Up @@ -840,7 +851,7 @@ impl RpcImpl {
prior_gas_used,
Some(exec_info.epoch_number),
exec_info.block_receipts.block_number,
exec_info.block.block_header.base_price(),
exec_info.pivot_header.base_price(),
exec_info.maybe_state_root.clone(),
tx_exec_error_msg,
*self.sync.network.get_network_type(),
Expand Down Expand Up @@ -900,10 +911,10 @@ impl RpcImpl {
};

// pivot chain reorg
if pivot_assumption != exec_info.pivot_hash {
if pivot_assumption != exec_info.pivot_header.hash() {
bail!(pivot_assumption_failed(
pivot_assumption,
exec_info.pivot_hash
exec_info.pivot_header.hash()
));
}

Expand Down Expand Up @@ -2272,7 +2283,7 @@ impl Cfx for CfxHandler {
fn account_pending_info(&self, addr: RpcAddress) -> BoxFuture<Option<AccountPendingInfo>>;
fn account_pending_transactions(&self, address: RpcAddress, maybe_start_nonce: Option<U256>, maybe_limit: Option<U64>) -> BoxFuture<AccountPendingTransactions>;
fn get_pos_reward_by_epoch(&self, epoch: EpochNumber) -> JsonRpcResult<Option<PoSEpochReward>>;
fn fee_history(&self, block_count: HexU64, newest_block: EpochNumber, reward_percentiles: Vec<f64>) -> BoxFuture<FeeHistory>;
fn fee_history(&self, block_count: HexU64, newest_block: EpochNumber, reward_percentiles: Vec<f64>) -> BoxFuture<CfxFeeHistory>;
fn max_priority_fee_per_gas(&self) -> BoxFuture<U256>;
}

Expand Down
35 changes: 24 additions & 11 deletions crates/client/src/rpc/impls/cfx/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ use crate::rpc::{
types::{
errors::check_rpc_address_network, pos::PoSEpochReward,
AccountPendingInfo, AccountPendingTransactions, Block as RpcBlock,
BlockHashOrEpochNumber, Bytes, CheckBalanceAgainstTransactionResponse,
EpochNumber, FeeHistory, RpcAddress, Status as RpcStatus,
Transaction as RpcTransaction, TxPoolPendingNonceRange, TxPoolStatus,
TxWithPoolInfo, U64 as HexU64,
BlockHashOrEpochNumber, Bytes, CfxFeeHistory,
CheckBalanceAgainstTransactionResponse, EpochNumber, FeeHistory,
RpcAddress, Status as RpcStatus, Transaction as RpcTransaction,
TxPoolPendingNonceRange, TxPoolStatus, TxWithPoolInfo, U64 as HexU64,
},
RpcErrorKind, RpcResult,
};
Expand Down Expand Up @@ -529,17 +529,25 @@ impl RpcImpl {
)
}

// TODO: cache the history to improve performance
pub fn fee_history(
&self, block_count: HexU64, newest_block: EpochNumber,
reward_percentiles: Vec<f64>,
) -> RpcResult<FeeHistory> {
) -> RpcResult<CfxFeeHistory> {
if newest_block == EpochNumber::LatestMined {
return Err(RpcError::invalid_params(
"newestBlock cannot be 'LatestMined'",
)
.into());
}

info!(
"RPC Request: cfx_feeHistory: block_count={}, newest_block={:?}, reward_percentiles={:?}",
block_count, newest_block, reward_percentiles
);

if block_count.as_u64() == 0 {
return Ok(FeeHistory::new());
return Ok(FeeHistory::new().to_cfx_fee_history());
}
// keep read lock to ensure consistent view
let inner = self.consensus_graph().inner.read();
Expand Down Expand Up @@ -594,21 +602,26 @@ impl RpcImpl {
.map_err(|_| RpcError::internal_error())?;

if current_height == 0 {
fee_history.finish(0, None, Space::Native);
return Ok(fee_history);
break;
} else {
current_height -= 1;
}
}

let block = fetch_block(current_height)?;
// Fetch the block after the last block in the history
let block = fetch_block(start_height + 1)?;
let oldest_block = if current_height == 0 {
0
} else {
current_height + 1
};
fee_history.finish(
current_height + 1,
oldest_block,
block.block_header.base_price().as_ref(),
Space::Native,
);

Ok(fee_history)
Ok(fee_history.to_cfx_fee_history())
}

pub fn max_priority_fee_per_gas(&self) -> RpcResult<U256> {
Expand Down
42 changes: 25 additions & 17 deletions crates/client/src/rpc/impls/cfx/light.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,15 @@ use crate::{
pos::{Block as PosBlock, PoSEpochReward},
Account as RpcAccount, AccountPendingInfo,
AccountPendingTransactions, BlameInfo, Block as RpcBlock,
BlockHashOrEpochNumber, Bytes, CallRequest, CfxRpcLogFilter,
CheckBalanceAgainstTransactionResponse, ConsensusGraphStates,
EpochNumber, EstimateGasAndCollateralResponse, FeeHistory,
Log as RpcLog, PoSEconomics, Receipt as RpcReceipt,
RewardInfo as RpcRewardInfo, RpcAddress, SendTxRequest,
SponsorInfo, StatOnGasLoad, Status as RpcStatus,
StorageCollateralInfo, SyncGraphStates, TokenSupplyInfo,
Transaction as RpcTransaction, VoteParamsInfo, WrapTransaction,
U64 as HexU64,
BlockHashOrEpochNumber, Bytes, CallRequest, CfxFeeHistory,
CfxRpcLogFilter, CheckBalanceAgainstTransactionResponse,
ConsensusGraphStates, EpochNumber,
EstimateGasAndCollateralResponse, FeeHistory, Log as RpcLog,
PoSEconomics, Receipt as RpcReceipt, RewardInfo as RpcRewardInfo,
RpcAddress, SendTxRequest, SponsorInfo, StatOnGasLoad,
Status as RpcStatus, StorageCollateralInfo, SyncGraphStates,
TokenSupplyInfo, Transaction as RpcTransaction, VoteParamsInfo,
WrapTransaction, U64 as HexU64,
},
RpcBoxFuture, RpcResult,
},
Expand Down Expand Up @@ -1094,14 +1094,18 @@ impl RpcImpl {
fn fee_history(
&self, block_count: HexU64, newest_block: EpochNumber,
reward_percentiles: Vec<f64>,
) -> RpcBoxFuture<FeeHistory> {
) -> RpcBoxFuture<CfxFeeHistory> {
info!(
"RPC Request: cfx_feeHistory: block_count={}, newest_block={:?}, reward_percentiles={:?}",
block_count, newest_block, reward_percentiles
);

if block_count.as_u64() == 0 {
return Box::new(async { Ok(FeeHistory::new()) }.boxed().compat());
return Box::new(
async { Ok(FeeHistory::new().to_cfx_fee_history()) }
.boxed()
.compat(),
);
}

// clone to avoid lifetime issues due to capturing `self`
Expand Down Expand Up @@ -1145,8 +1149,7 @@ impl RpcImpl {
.map_err(|_| RpcError::internal_error())?;

if current_height == 0 {
fee_history.finish(0, None, Space::Native);
return Ok(fee_history);
break;
} else {
current_height -= 1;
}
Expand All @@ -1155,15 +1158,20 @@ impl RpcImpl {
let block = fetch_block_for_fee_history(
consensus_graph.clone(),
light.clone(),
current_height,
start_height + 1,
)
.await?;
let oldest_block = if current_height == 0 {
0
} else {
current_height + 1
};
fee_history.finish(
current_height + 1,
oldest_block,
block.block_header.base_price().as_ref(),
Space::Native,
);
Ok(fee_history)
Ok(fee_history.to_cfx_fee_history())
};

Box::new(fut.boxed().compat())
Expand Down Expand Up @@ -1240,7 +1248,7 @@ impl Cfx for CfxHandler {
fn transaction_by_hash(&self, hash: H256) -> BoxFuture<Option<RpcTransaction>>;
fn transaction_receipt(&self, tx_hash: H256) -> BoxFuture<Option<RpcReceipt>>;
fn vote_list(&self, address: RpcAddress, num: Option<EpochNumber>) -> BoxFuture<Vec<VoteStakeInfo>>;
fn fee_history(&self, block_count: HexU64, newest_block: EpochNumber, reward_percentiles: Vec<f64>) -> BoxFuture<FeeHistory>;
fn fee_history(&self, block_count: HexU64, newest_block: EpochNumber, reward_percentiles: Vec<f64>) -> BoxFuture<CfxFeeHistory>;
}
}

Expand Down
18 changes: 13 additions & 5 deletions crates/client/src/rpc/impls/eth/eth_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,8 @@ fn block_tx_by_index(

impl EthHandler {
fn exec_transaction(
&self, request: CallRequest, block_number_or_hash: Option<BlockNumber>,
&self, mut request: CallRequest,
block_number_or_hash: Option<BlockNumber>,
) -> CfxRpcResult<(ExecutionOutcome, EstimateExt)> {
let consensus_graph = self.consensus_graph();

Expand All @@ -213,6 +214,9 @@ impl EthHandler {
epoch => epoch.try_into()?,
};

// if gas_price is zero, it is considered as not set
request.unset_zero_gas_price();

let estimate_request = EstimateRequest {
has_sender: request.from.is_some(),
has_gas_limit: request.gas.is_some(),
Expand Down Expand Up @@ -967,16 +971,20 @@ impl Eth for EthHandler {
.map_err(|_| RpcError::internal_error())?;

if current_height == 0 {
fee_history.finish(0, None, Space::Ethereum);
return Ok(fee_history);
break;
} else {
current_height -= 1;
}
}

let block = fetch_block(current_height)?;
let block = fetch_block(start_height + 1)?;
let oldest_block = if current_height == 0 {
0
} else {
current_height + 1
};
fee_history.finish(
current_height + 1,
oldest_block,
block.pivot_header.base_price().as_ref(),
Space::Ethereum,
);
Expand Down
6 changes: 3 additions & 3 deletions crates/client/src/rpc/traits/cfx_space/cfx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
use crate::rpc::types::{
pos::PoSEpochReward, Account as RpcAccount, AccountPendingInfo,
AccountPendingTransactions, Block, BlockHashOrEpochNumber, Bytes,
CallRequest, CfxFilterChanges, CfxRpcLogFilter,
CallRequest, CfxFeeHistory, CfxFilterChanges, CfxRpcLogFilter,
CheckBalanceAgainstTransactionResponse, EpochNumber,
EstimateGasAndCollateralResponse, FeeHistory, Log as RpcLog, PoSEconomics,
EstimateGasAndCollateralResponse, Log as RpcLog, PoSEconomics,
Receipt as RpcReceipt, RewardInfo as RpcRewardInfo, RpcAddress,
SponsorInfo, Status as RpcStatus, StorageCollateralInfo, TokenSupplyInfo,
Transaction, VoteParamsInfo, U64 as HexU64,
Expand Down Expand Up @@ -205,7 +205,7 @@ pub trait Cfx {
fn fee_history(
&self, block_count: HexU64, newest_block: EpochNumber,
reward_percentiles: Vec<f64>,
) -> BoxFuture<FeeHistory>;
) -> BoxFuture<CfxFeeHistory>;

/// Check if user balance is enough for the transaction.
#[rpc(name = "cfx_checkBalanceAgainstTransaction")]
Expand Down
15 changes: 10 additions & 5 deletions crates/client/src/rpc/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ mod account;
mod blame_info;
mod block;
mod bytes;
pub mod call_request;
pub mod cfx;
mod consensus_graph_states;
mod epoch_number;
Expand Down Expand Up @@ -40,11 +39,17 @@ pub use self::{
blame_info::BlameInfo,
block::{Block, BlockTransactions, Header},
bytes::Bytes,
call_request::{
sign_call, CallRequest, CheckBalanceAgainstTransactionResponse,
EstimateGasAndCollateralResponse, SendTxRequest, MAX_GAS_CALL_REQUEST,
cfx::{
address,
address::RpcAddress,
call_request::{
self, sign_call, CallRequest,
CheckBalanceAgainstTransactionResponse,
EstimateGasAndCollateralResponse, SendTxRequest,
MAX_GAS_CALL_REQUEST,
},
CfxFeeHistory,
},
cfx::{address, address::RpcAddress},
consensus_graph_states::ConsensusGraphStates,
epoch_number::{BlockHashOrEpochNumber, EpochNumber},
fee_history::FeeHistory,
Expand Down
File renamed without changes.
35 changes: 35 additions & 0 deletions crates/client/src/rpc/types/cfx/fee_history.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
use cfx_types::U256;
use std::collections::VecDeque;

#[derive(Serialize, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub struct CfxFeeHistory {
/// Oldest epoch
oldest_epoch: U256,
/// An array of pivot block base fees per gas. This includes one block
/// earlier than the oldest block. Zeroes are returned for pre-EIP-1559
/// blocks.
base_fee_per_gas: VecDeque<U256>,
/// In Conflux, 1559 is adjusted by the current block's gas limit of total
/// transactions, instead of parent's gas used
gas_used_ratio: VecDeque<f64>,
/// A two-dimensional array of effective priority fees per gas at the
/// requested block percentiles.
reward: VecDeque<Vec<U256>>,
}

impl CfxFeeHistory {
pub fn new(
oldest_epoch: U256, base_fee_per_gas: VecDeque<U256>,
gas_used_ratio: VecDeque<f64>, reward: VecDeque<Vec<U256>>,
) -> Self {
CfxFeeHistory {
oldest_epoch,
base_fee_per_gas,
gas_used_ratio,
reward,
}
}

pub fn reward(&self) -> &VecDeque<Vec<U256>> { &self.reward }
}
3 changes: 3 additions & 0 deletions crates/client/src/rpc/types/cfx/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
mod access_list;
pub mod address;
pub mod call_request;
mod fee_history;

pub use access_list::*;
pub use address::RpcAddress;
pub use fee_history::*;
Loading

0 comments on commit d88d953

Please sign in to comment.