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

Rename BlockNumber in client side #1172

Merged
Merged
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
34 changes: 21 additions & 13 deletions client/rpc-core/src/eth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ pub trait EthApi {
#[method(name = "eth_getBlockByNumber")]
async fn block_by_number(
&self,
number: BlockNumber,
number_or_hash: BlockNumberOrHash,
full: bool,
) -> RpcResult<Option<RichBlock>>;

Expand All @@ -82,14 +82,14 @@ pub trait EthApi {
#[method(name = "eth_getBlockTransactionCountByNumber")]
async fn block_transaction_count_by_number(
&self,
number: BlockNumber,
number_or_hash: BlockNumberOrHash,
) -> RpcResult<Option<U256>>;

/// Returns the receipts of a block by number or hash.
#[method(name = "eth_getBlockReceipts")]
async fn block_transaction_receipts(
&self,
number: BlockNumber,
number_or_hash: BlockNumberOrHash,
) -> RpcResult<Option<Vec<Receipt>>>;

/// Returns the number of uncles in a block with given hash.
Expand All @@ -98,7 +98,7 @@ pub trait EthApi {

/// Returns the number of uncles in a block with given block number.
#[method(name = "eth_getUncleCountByBlockNumber")]
fn block_uncles_count_by_number(&self, number: BlockNumber) -> RpcResult<U256>;
fn block_uncles_count_by_number(&self, number_or_hash: BlockNumberOrHash) -> RpcResult<U256>;

/// Returns an uncles at given block and index.
#[method(name = "eth_getUncleByBlockHashAndIndex")]
Expand All @@ -112,7 +112,7 @@ pub trait EthApi {
#[method(name = "eth_getUncleByBlockNumberAndIndex")]
fn uncle_by_block_number_and_index(
&self,
number: BlockNumber,
number_or_hash: BlockNumberOrHash,
index: Index,
) -> RpcResult<Option<RichBlock>>;

Expand All @@ -136,7 +136,7 @@ pub trait EthApi {
#[method(name = "eth_getTransactionByBlockNumberAndIndex")]
async fn transaction_by_block_number_and_index(
&self,
number: BlockNumber,
number_or_hash: BlockNumberOrHash,
index: Index,
) -> RpcResult<Option<Transaction>>;

Expand All @@ -150,28 +150,36 @@ pub trait EthApi {

/// Returns balance of the given account.
#[method(name = "eth_getBalance")]
async fn balance(&self, address: H160, number: Option<BlockNumber>) -> RpcResult<U256>;
async fn balance(
&self,
address: H160,
number_or_hash: Option<BlockNumberOrHash>,
) -> RpcResult<U256>;

/// Returns content of the storage at given address.
#[method(name = "eth_getStorageAt")]
async fn storage_at(
&self,
address: H160,
index: U256,
number: Option<BlockNumber>,
number_or_hash: Option<BlockNumberOrHash>,
) -> RpcResult<H256>;

/// Returns the number of transactions sent from given address at given time (block number).
#[method(name = "eth_getTransactionCount")]
async fn transaction_count(
&self,
address: H160,
number: Option<BlockNumber>,
number_or_hash: Option<BlockNumberOrHash>,
) -> RpcResult<U256>;

/// Returns the code at given address at given time (block number).
#[method(name = "eth_getCode")]
async fn code_at(&self, address: H160, number: Option<BlockNumber>) -> RpcResult<Bytes>;
async fn code_at(
&self,
address: H160,
number_or_hash: Option<BlockNumberOrHash>,
) -> RpcResult<Bytes>;

// ########################################################################
// Execute
Expand All @@ -182,7 +190,7 @@ pub trait EthApi {
async fn call(
&self,
request: CallRequest,
number: Option<BlockNumber>,
number_or_hash: Option<BlockNumberOrHash>,
state_overrides: Option<BTreeMap<H160, CallStateOverride>>,
) -> RpcResult<Bytes>;

Expand All @@ -191,7 +199,7 @@ pub trait EthApi {
async fn estimate_gas(
&self,
request: CallRequest,
number: Option<BlockNumber>,
number_or_hash: Option<BlockNumberOrHash>,
) -> RpcResult<U256>;

// ########################################################################
Expand All @@ -207,7 +215,7 @@ pub trait EthApi {
async fn fee_history(
&self,
block_count: U256,
newest_block: BlockNumber,
newest_block: BlockNumberOrHash,
reward_percentiles: Option<Vec<f64>>,
) -> RpcResult<FeeHistory>;

Expand Down
95 changes: 50 additions & 45 deletions client/rpc-core/src/types/block_number.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use serde::{

/// Represents rpc api block number param.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Default, Hash)]
pub enum BlockNumber {
pub enum BlockNumberOrHash {
/// Hash
Hash {
/// block hash
Expand All @@ -51,53 +51,53 @@ pub enum BlockNumber {
Finalized,
}

impl<'a> Deserialize<'a> for BlockNumber {
fn deserialize<D>(deserializer: D) -> Result<BlockNumber, D::Error>
impl<'a> Deserialize<'a> for BlockNumberOrHash {
fn deserialize<D>(deserializer: D) -> Result<BlockNumberOrHash, D::Error>
where
D: Deserializer<'a>,
{
deserializer.deserialize_any(BlockNumberVisitor)
deserializer.deserialize_any(BlockNumberOrHashVisitor)
}
}

impl BlockNumber {
impl BlockNumberOrHash {
/// Convert block number to min block target.
pub fn to_min_block_num(&self) -> Option<u64> {
match *self {
BlockNumber::Num(ref x) => Some(*x),
BlockNumber::Earliest => Some(0),
BlockNumberOrHash::Num(ref x) => Some(*x),
BlockNumberOrHash::Earliest => Some(0),
_ => None,
}
}
}

impl Serialize for BlockNumber {
impl Serialize for BlockNumberOrHash {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match *self {
BlockNumber::Hash {
BlockNumberOrHash::Hash {
hash,
require_canonical,
} => serializer.serialize_str(&format!(
"{{ 'hash': '{}', 'requireCanonical': '{}' }}",
hash, require_canonical
)),
BlockNumber::Num(ref x) => serializer.serialize_str(&format!("0x{:x}", x)),
BlockNumber::Latest => serializer.serialize_str("latest"),
BlockNumber::Earliest => serializer.serialize_str("earliest"),
BlockNumber::Pending => serializer.serialize_str("pending"),
BlockNumber::Safe => serializer.serialize_str("safe"),
BlockNumber::Finalized => serializer.serialize_str("finalized"),
BlockNumberOrHash::Num(ref x) => serializer.serialize_str(&format!("0x{:x}", x)),
BlockNumberOrHash::Latest => serializer.serialize_str("latest"),
BlockNumberOrHash::Earliest => serializer.serialize_str("earliest"),
BlockNumberOrHash::Pending => serializer.serialize_str("pending"),
BlockNumberOrHash::Safe => serializer.serialize_str("safe"),
BlockNumberOrHash::Finalized => serializer.serialize_str("finalized"),
}
}
}

struct BlockNumberVisitor;
struct BlockNumberOrHashVisitor;

impl<'a> Visitor<'a> for BlockNumberVisitor {
type Value = BlockNumber;
impl<'a> Visitor<'a> for BlockNumberOrHashVisitor {
type Value = BlockNumberOrHash;

fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(
Expand Down Expand Up @@ -146,11 +146,11 @@ impl<'a> Visitor<'a> for BlockNumberVisitor {
}

if let Some(number) = block_number {
return Ok(BlockNumber::Num(number));
return Ok(BlockNumberOrHash::Num(number));
}

if let Some(hash) = block_hash {
return Ok(BlockNumber::Hash {
return Ok(BlockNumberOrHash::Hash {
hash,
require_canonical,
});
Expand All @@ -164,17 +164,22 @@ impl<'a> Visitor<'a> for BlockNumberVisitor {
E: Error,
{
match value {
"latest" => Ok(BlockNumber::Latest),
"earliest" => Ok(BlockNumber::Earliest),
"pending" => Ok(BlockNumber::Pending),
"safe" => Ok(BlockNumber::Safe),
"finalized" => Ok(BlockNumber::Finalized),
"latest" => Ok(BlockNumberOrHash::Latest),
"earliest" => Ok(BlockNumberOrHash::Earliest),
"pending" => Ok(BlockNumberOrHash::Pending),
"safe" => Ok(BlockNumberOrHash::Safe),
"finalized" => Ok(BlockNumberOrHash::Finalized),
_ if value.starts_with("0x") => u64::from_str_radix(&value[2..], 16)
.map(BlockNumber::Num)
.map(BlockNumberOrHash::Num)
.map_err(|e| Error::custom(format!("Invalid block number: {}", e))),
_ => value.parse::<u64>().map(BlockNumber::Num).map_err(|_| {
Error::custom("Invalid block number: non-decimal or missing 0x prefix".to_string())
}),
_ => value
.parse::<u64>()
.map(BlockNumberOrHash::Num)
.map_err(|_| {
Error::custom(
"Invalid block number: non-decimal or missing 0x prefix".to_string(),
)
}),
}
}

Expand All @@ -189,36 +194,36 @@ impl<'a> Visitor<'a> for BlockNumberVisitor {
where
E: Error,
{
Ok(BlockNumber::Num(value))
Ok(BlockNumberOrHash::Num(value))
}
}

#[cfg(test)]
mod tests {
use super::*;

fn match_block_number(block_number: BlockNumber) -> Option<u64> {
fn match_block_number(block_number: BlockNumberOrHash) -> Option<u64> {
match block_number {
BlockNumber::Num(number) => Some(number),
BlockNumber::Earliest => Some(0),
BlockNumber::Latest => Some(1000),
BlockNumber::Safe => Some(999),
BlockNumber::Finalized => Some(999),
BlockNumber::Pending => Some(1001),
BlockNumberOrHash::Num(number) => Some(number),
BlockNumberOrHash::Earliest => Some(0),
BlockNumberOrHash::Latest => Some(1000),
BlockNumberOrHash::Safe => Some(999),
BlockNumberOrHash::Finalized => Some(999),
BlockNumberOrHash::Pending => Some(1001),
_ => None,
}
}

#[test]
fn block_number_deserialize() {
let bn_dec: BlockNumber = serde_json::from_str(r#""42""#).unwrap();
let bn_hex: BlockNumber = serde_json::from_str(r#""0x45""#).unwrap();
let bn_u64: BlockNumber = serde_json::from_str(r#"420"#).unwrap();
let bn_tag_earliest: BlockNumber = serde_json::from_str(r#""earliest""#).unwrap();
let bn_tag_latest: BlockNumber = serde_json::from_str(r#""latest""#).unwrap();
let bn_tag_safe: BlockNumber = serde_json::from_str(r#""safe""#).unwrap();
let bn_tag_finalized: BlockNumber = serde_json::from_str(r#""finalized""#).unwrap();
let bn_tag_pending: BlockNumber = serde_json::from_str(r#""pending""#).unwrap();
let bn_dec: BlockNumberOrHash = serde_json::from_str(r#""42""#).unwrap();
let bn_hex: BlockNumberOrHash = serde_json::from_str(r#""0x45""#).unwrap();
let bn_u64: BlockNumberOrHash = serde_json::from_str(r#"420"#).unwrap();
let bn_tag_earliest: BlockNumberOrHash = serde_json::from_str(r#""earliest""#).unwrap();
let bn_tag_latest: BlockNumberOrHash = serde_json::from_str(r#""latest""#).unwrap();
let bn_tag_safe: BlockNumberOrHash = serde_json::from_str(r#""safe""#).unwrap();
let bn_tag_finalized: BlockNumberOrHash = serde_json::from_str(r#""finalized""#).unwrap();
let bn_tag_pending: BlockNumberOrHash = serde_json::from_str(r#""pending""#).unwrap();

assert_eq!(match_block_number(bn_dec).unwrap(), 42);
assert_eq!(match_block_number(bn_hex).unwrap(), 69);
Expand Down
14 changes: 7 additions & 7 deletions client/rpc-core/src/types/filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ use serde::{
};
use serde_json::{from_value, Value};

use crate::types::{BlockNumber, Log};
use crate::types::{BlockNumberOrHash, Log};

/// Variadic value
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
Expand Down Expand Up @@ -136,9 +136,9 @@ impl From<&VariadicValue<Option<H256>>> for Vec<Option<Bloom>> {
#[serde(rename_all = "camelCase")]
pub struct Filter {
/// From Block
pub from_block: Option<BlockNumber>,
pub from_block: Option<BlockNumberOrHash>,
/// To Block
pub to_block: Option<BlockNumber>,
pub to_block: Option<BlockNumberOrHash>,
/// Block hash
pub block_hash: Option<H256>,
/// Address
Expand Down Expand Up @@ -327,19 +327,19 @@ impl FilteredParams {
pub fn filter_block_range(&self, block_number: u64) -> bool {
let mut out = true;
let filter = self.filter.clone().unwrap();
if let Some(BlockNumber::Num(from)) = filter.from_block {
if let Some(BlockNumberOrHash::Num(from)) = filter.from_block {
if from > block_number {
out = false;
}
}
if let Some(to) = filter.to_block {
match to {
BlockNumber::Num(to) => {
BlockNumberOrHash::Num(to) => {
if to < block_number {
out = false;
}
}
BlockNumber::Earliest => {
BlockNumberOrHash::Earliest => {
out = false;
}
_ => {}
Expand Down Expand Up @@ -457,7 +457,7 @@ pub enum FilterType {

#[derive(Clone, Debug)]
pub struct FilterPoolItem {
pub last_poll: BlockNumber,
pub last_poll: BlockNumberOrHash,
pub filter_type: FilterType,
pub at_block: u64,
pub pending_transaction_hashes: HashSet<H256>,
Expand Down
2 changes: 1 addition & 1 deletion client/rpc-core/src/types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ pub use self::txpool::{Get, Summary, TransactionMap, TxPoolResult, TxPoolTransac
pub use self::{
account_info::{AccountInfo, EthAccount, ExtAccountInfo, RecoveredAccount, StorageProof},
block::{Block, BlockTransactions, Header, Rich, RichBlock, RichHeader},
block_number::BlockNumber,
block_number::BlockNumberOrHash,
bytes::Bytes,
call_request::{CallRequest, CallStateOverride},
fee::{FeeHistory, FeeHistoryCache, FeeHistoryCacheItem, FeeHistoryCacheLimit},
Expand Down
Loading
Loading