openethereum/rpc/src/v1/types/filter.rs

212 lines
6.4 KiB
Rust
Raw Normal View History

// Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.
2016-02-09 17:37:16 +01:00
// Parity Ethereum is free software: you can redistribute it and/or modify
2016-02-09 17:37:16 +01:00
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity Ethereum is distributed in the hope that it will be useful,
2016-02-09 17:37:16 +01:00
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
2016-02-09 17:37:16 +01:00
use ethereum_types::{H160, H256};
use jsonrpc_core::{Error as RpcError};
2017-07-06 11:36:15 +02:00
use serde::de::{Error, DeserializeOwned};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::{Value, from_value};
use types::filter::Filter as EthFilter;
use types::ids::BlockId;
use v1::types::{BlockNumber, Log};
use v1::helpers::errors::invalid_params;
2016-02-09 17:37:16 +01:00
/// Variadic value
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
2017-07-06 11:36:15 +02:00
pub enum VariadicValue<T> where T: DeserializeOwned {
/// Single
2016-02-13 13:05:28 +01:00
Single(T),
/// List
2016-02-13 13:05:28 +01:00
Multiple(Vec<T>),
/// None
2016-02-22 10:11:07 +01:00
Null,
2016-02-09 17:37:16 +01:00
}
2017-07-06 11:36:15 +02:00
impl<'a, T> Deserialize<'a> for VariadicValue<T> where T: DeserializeOwned {
fn deserialize<D>(deserializer: D) -> Result<VariadicValue<T>, D::Error>
2017-07-06 11:36:15 +02:00
where D: Deserializer<'a> {
let v: Value = Deserialize::deserialize(deserializer)?;
2016-02-09 17:37:16 +01:00
if v.is_null() {
2016-02-13 13:05:28 +01:00
return Ok(VariadicValue::Null);
2016-02-09 17:37:16 +01:00
}
from_value(v.clone()).map(VariadicValue::Single)
.or_else(|_| from_value(v).map(VariadicValue::Multiple))
.map_err(|err| D::Error::custom(format!("Invalid variadic value type: {}", err)))
2016-02-09 17:37:16 +01:00
}
}
/// Filter Address
pub type FilterAddress = VariadicValue<H160>;
/// Topic
2016-02-13 13:05:28 +01:00
pub type Topic = VariadicValue<H256>;
/// Filter
#[derive(Debug, PartialEq, Clone, Deserialize, Eq, Hash)]
2016-02-27 13:14:58 +01:00
#[serde(deny_unknown_fields)]
#[serde(rename_all = "camelCase")]
2016-02-09 17:37:16 +01:00
pub struct Filter {
/// From Block
2016-02-09 17:45:39 +01:00
pub from_block: Option<BlockNumber>,
/// To Block
2016-02-09 17:45:39 +01:00
pub to_block: Option<BlockNumber>,
/// Block hash
pub block_hash: Option<H256>,
/// Address
2016-02-13 13:05:28 +01:00
pub address: Option<FilterAddress>,
/// Topics
2016-02-22 10:11:07 +01:00
pub topics: Option<Vec<Topic>>,
/// Limit
pub limit: Option<usize>,
2016-02-09 17:37:16 +01:00
}
impl Filter {
pub fn try_into(self) -> Result<EthFilter, RpcError> {
if self.block_hash.is_some() && (self.from_block.is_some() || self.to_block.is_some()) {
return Err(invalid_params("blockHash", "blockHash is mutually exclusive with fromBlock/toBlock"));
}
`Client` refactoring (#7038) * Improves `BestBlock` comment * Improves `TraceDB` comment * Improves `journaldb::Algorithm` comment. Probably the whole enum should be renamed to `Strategy` or something alike. * Comments some of the `Client`'s fields * Deglobs client imports * Fixes comments * Extracts `import_lock` to `Importer` struct * Extracts `verifier` to `Importer` struct * Extracts `block_queue` to `Importer` struct * Extracts `miner` to `Importer` struct * Extracts `ancient_verifier` to `Importer` struct * Extracts `rng` to `Importer` struct * Extracts `import_old_block` to `Importer` struct * Adds `Nonce` trait * Adds `Balance` trait * Adds `ChainInfo` trait * Fixes imports for tests using `chain_info` method * Adds `BlockInfo` trait * Adds more `ChainInfo` imports * Adds `BlockInfo` imports * Adds `ReopenBlock` trait * Adds `PrepareOpenBlock` trait * Fixes import in tests * Adds `CallContract` trait * Fixes imports in tests using `call_contract` method * Adds `TransactionInfo` trait * Adds `RegistryInfo` trait * Fixes imports in tests using `registry_address` method * Adds `ScheduleInfo` trait * Adds `ImportSealedBlock` trait * Fixes imports in test using `import_sealed_block` method * Adds `BroadcastProposalBlock` trait * Migrates `Miner` to static dispatch * Fixes tests * Moves `calculate_enacted_retracted` to `Importer` * Moves import-related methods to `Importer` * Removes redundant `import_old_block` wrapper * Extracts `import_block*` into separate trait * Fixes tests * Handles `Pending` in `LightFetch` * Handles `Pending` in filters * Handles `Pending` in `ParityClient` * Handles `Pending` in `EthClient` * Removes `BlockId::Pending`, partly refactors dependent code * Adds `StateInfo` trait * Exports `StateOrBlock` and `BlockChain` types from `client` module * Refactors `balance` RPC using generic API * Refactors `storage_at` RPC using generic API * Makes `MinerService::pending_state`'s return type dynamic * Adds `StateOrBlock` and `BlockChain` types * Adds impl of `client::BlockChain` for `Client` * Exports `StateInfo` trait from `client` module * Missing `self` use To be fixed up to "Adds impl of `client::BlockChain` for `Client`" * Adds `number_to_id` and refactors dependent RPC methods * Refactors `code_at` using generic API * Adds `StateClient` trait * Refactors RPC to use `StateClient` trait * Reverts `client::BlockChain` trait stuff, refactors methods to accept `StateOrBlock` * Refactors TestClient * Adds helper function `block_number_to_id` * Uses `block_number_to_id` instead of local function * Handles `Pending` in `list_accounts` and `list_storage_keys` * Attempt to use associated types for state instead of trait objects * Simplifies `state_at_beginning` * Extracts `call` and `call_many` into separate trait * Refactors `build_last_hashes` to accept reference * Exports `Call` type from the module * Refactors `call` and `call_many` to accept state and header * Exports `state_at` in `StateClient` * Exports `pending_block_header` from `MinerService` * Refactors RPC `call` method using new API * Adds missing parentheses * Refactors `parity::call` to use new call API * Update .gitlab-ci.yml fix gitlab lint * Fixes error handling * Refactors `traces::call` and `call_many` to use new call API * Refactors `call_contract` * Refactors `block_header` * Refactors internal RPC method `block` * Moves `estimate_gas` to `Call` trait, refactors parameters * Refactors `estimate_gas` in RPC * Refactors `uncle` * Refactors RPC `transaction` * Covers missing branches * Makes it all compile, fixes compiler grumbles * Adds casts in `blockchain` module * Fixes `PendingBlock` tests, work on `MinerService` * Adds test stubs for StateClient and EngineInfo * Makes `state_db` public * Adds missing impls for `TestBlockChainClient` * Adds trait documentation * Adds missing docs to the `state_db` module * Fixes trivial compilation errors * Moves `code_hash` method to a `BlockInfo` trait * Refactors `Verifier` to be generic over client * Refactors `TransactionFilter` to be generic over client * Refactors `Miner` and `Client` to reflect changes in verifier and txfilter API * Moves `ServiceTransactionChecker` back to `ethcore` * Fixes trait bounds in `Miner` API * Fixes `Client` * Fixes lifetime bound in `FullFamilyParams` * Adds comments to `FullFamilyParams` * Fixes imports in `ethcore` * Fixes BlockNumber handling in `code_at` and `replay_block_transactions` * fix compile issues * First step to redundant trait merge * Fixes compilation error in RPC tests * Adds mock `State` as a stub for `TestClient` * Handles `StateOrBlock::State` in `TestBlockChainClient::balance` * Fixes `transaction_count` RPC * Fixes `transaction_count` * Moves `service_transaction.json` to the `contracts` subfolder * Fixes compilation errors in tests * Refactors client to use `AccountData` * Refactors client to use `BlockChain` * Refactors miner to use aggregate traits * Adds `SealedBlockImporter` trait * Refactors miner to use `SealedBlockImporter` trait * Removes unused imports * Simplifies `RegistryInfo::registry_address` * Fixes indentation * Removes commented out trait bound
2018-03-03 18:42:13 +01:00
let num_to_id = |num| match num {
BlockNumber::Num(n) => BlockId::Number(n),
BlockNumber::Earliest => BlockId::Earliest,
BlockNumber::Latest | BlockNumber::Pending => BlockId::Latest,
};
let (from_block, to_block) = match self.block_hash {
Some(hash) => (BlockId::Hash(hash), BlockId::Hash(hash)),
None =>
(self.from_block.map_or_else(|| BlockId::Latest, &num_to_id),
self.to_block.map_or_else(|| BlockId::Latest, &num_to_id)),
};
Ok(EthFilter {
from_block, to_block,
address: self.address.and_then(|address| match address {
VariadicValue::Null => None,
VariadicValue::Single(a) => Some(vec![a]),
VariadicValue::Multiple(a) => Some(a)
}),
topics: {
let mut iter = self.topics.map_or_else(Vec::new, |topics| topics.into_iter().take(4).map(|topic| match topic {
VariadicValue::Null => None,
VariadicValue::Single(t) => Some(vec![t]),
VariadicValue::Multiple(t) => Some(t)
}).collect()).into_iter();
vec![
iter.next().unwrap_or(None),
iter.next().unwrap_or(None),
iter.next().unwrap_or(None),
iter.next().unwrap_or(None)
]
},
limit: self.limit,
})
2016-02-13 13:05:28 +01:00
}
}
/// Results of the filter_changes RPC.
#[derive(Debug, PartialEq)]
pub enum FilterChanges {
/// New logs.
Logs(Vec<Log>),
/// New hashes (block or transactions)
Hashes(Vec<H256>),
/// Empty result,
Empty,
}
impl Serialize for FilterChanges {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error> where S: Serializer {
match *self {
FilterChanges::Logs(ref logs) => logs.serialize(s),
FilterChanges::Hashes(ref hashes) => hashes.serialize(s),
FilterChanges::Empty => (&[] as &[Value]).serialize(s),
}
}
}
2016-02-09 17:37:16 +01:00
#[cfg(test)]
mod tests {
use serde_json;
use std::str::FromStr;
use ethereum_types::H256;
2016-11-28 17:15:40 +01:00
use super::{VariadicValue, Topic, Filter};
2016-02-09 17:45:39 +01:00
use v1::types::BlockNumber;
use types::filter::Filter as EthFilter;
use types::ids::BlockId;
2016-02-09 17:37:16 +01:00
#[test]
2016-02-09 17:45:39 +01:00
fn topic_deserialization() {
2016-02-09 17:37:16 +01:00
let s = r#"["0x000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b", null, ["0x000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b", "0x0000000000000000000000000aff3454fce5edbc8cca8697c15331677e6ebccc"]]"#;
let deserialized: Vec<Topic> = serde_json::from_str(s).unwrap();
assert_eq!(deserialized, vec![
VariadicValue::Single(H256::from_str("000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b").unwrap().into()),
2016-02-13 13:05:28 +01:00
VariadicValue::Null,
VariadicValue::Multiple(vec![
H256::from_str("000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b").unwrap().into(),
H256::from_str("0000000000000000000000000aff3454fce5edbc8cca8697c15331677e6ebccc").unwrap().into(),
2016-02-09 17:37:16 +01:00
])
]);
}
2016-02-09 17:45:39 +01:00
#[test]
fn filter_deserialization() {
let s = r#"{"fromBlock":"earliest","toBlock":"latest"}"#;
let deserialized: Filter = serde_json::from_str(s).unwrap();
assert_eq!(deserialized, Filter {
from_block: Some(BlockNumber::Earliest),
to_block: Some(BlockNumber::Latest),
block_hash: None,
2016-02-09 17:45:39 +01:00
address: None,
topics: None,
limit: None,
2016-02-09 17:45:39 +01:00
});
}
#[test]
fn filter_conversion() {
let filter = Filter {
from_block: Some(BlockNumber::Earliest),
to_block: Some(BlockNumber::Latest),
block_hash: None,
address: Some(VariadicValue::Multiple(vec![])),
topics: Some(vec![
VariadicValue::Null,
VariadicValue::Single("000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b".into()),
VariadicValue::Null,
]),
limit: None,
};
let eth_filter: EthFilter = filter.try_into().unwrap();
assert_eq!(eth_filter, EthFilter {
from_block: BlockId::Earliest,
to_block: BlockId::Latest,
address: Some(vec![]),
topics: vec![
None,
Some(vec!["000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b".into()]),
None,
None,
],
limit: None,
});
}
2016-02-09 17:37:16 +01:00
}