Make Id/ID and db/Db/DB usage consistent

This commit is contained in:
debris 2016-05-19 11:00:32 +02:00
parent 7d873b2c81
commit 634679966e
17 changed files with 156 additions and 156 deletions

View File

@ -37,7 +37,7 @@ use filter::Filter;
use log_entry::LocalizedLogEntry; use log_entry::LocalizedLogEntry;
use block_queue::{BlockQueue, BlockQueueInfo}; use block_queue::{BlockQueue, BlockQueueInfo};
use blockchain::{BlockChain, BlockProvider, TreeRoute, ImportRoute}; use blockchain::{BlockChain, BlockProvider, TreeRoute, ImportRoute};
use client::{BlockId, TransactionId, UncleId, TraceId, ClientConfig, BlockChainClient, TraceFilter}; use client::{BlockID, TransactionID, UncleID, TraceId, ClientConfig, BlockChainClient, TraceFilter};
use env_info::EnvInfo; use env_info::EnvInfo;
use executive::{Executive, Executed, TransactOptions, contract_address}; use executive::{Executive, Executed, TransactOptions, contract_address};
use receipt::LocalizedReceipt; use receipt::LocalizedReceipt;
@ -371,28 +371,28 @@ impl<V> Client<V> where V: Verifier {
self.chain.configure_cache(pref_cache_size, max_cache_size); self.chain.configure_cache(pref_cache_size, max_cache_size);
} }
fn block_hash(chain: &BlockChain, id: BlockId) -> Option<H256> { fn block_hash(chain: &BlockChain, id: BlockID) -> Option<H256> {
match id { match id {
BlockId::Hash(hash) => Some(hash), BlockID::Hash(hash) => Some(hash),
BlockId::Number(number) => chain.block_hash(number), BlockID::Number(number) => chain.block_hash(number),
BlockId::Earliest => chain.block_hash(0), BlockID::Earliest => chain.block_hash(0),
BlockId::Latest => Some(chain.best_block_hash()) BlockID::Latest => Some(chain.best_block_hash())
} }
} }
fn block_number(&self, id: BlockId) -> Option<BlockNumber> { fn block_number(&self, id: BlockID) -> Option<BlockNumber> {
match id { match id {
BlockId::Number(number) => Some(number), BlockID::Number(number) => Some(number),
BlockId::Hash(ref hash) => self.chain.block_number(hash), BlockID::Hash(ref hash) => self.chain.block_number(hash),
BlockId::Earliest => Some(0), BlockID::Earliest => Some(0),
BlockId::Latest => Some(self.chain.best_block_number()) BlockID::Latest => Some(self.chain.best_block_number())
} }
} }
fn transaction_address(&self, id: TransactionId) -> Option<TransactionAddress> { fn transaction_address(&self, id: TransactionID) -> Option<TransactionAddress> {
match id { match id {
TransactionId::Hash(ref hash) => self.chain.transaction_address(hash), TransactionID::Hash(ref hash) => self.chain.transaction_address(hash),
TransactionId::Location(id, index) => Self::block_hash(&self.chain, id).map(|hash| TransactionAddress { TransactionID::Location(id, index) => Self::block_hash(&self.chain, id).map(|hash| TransactionAddress {
block_hash: hash, block_hash: hash,
index: index index: index
}) })
@ -402,7 +402,7 @@ impl<V> Client<V> where V: Verifier {
impl<V> BlockChainClient for Client<V> where V: Verifier { impl<V> BlockChainClient for Client<V> where V: Verifier {
fn call(&self, t: &SignedTransaction) -> Result<Executed, ExecutionError> { fn call(&self, t: &SignedTransaction) -> Result<Executed, ExecutionError> {
let header = self.block_header(BlockId::Latest).unwrap(); let header = self.block_header(BlockID::Latest).unwrap();
let view = HeaderView::new(&header); let view = HeaderView::new(&header);
let last_hashes = self.build_last_hashes(view.hash()); let last_hashes = self.build_last_hashes(view.hash());
let env_info = EnvInfo { let env_info = EnvInfo {
@ -503,11 +503,11 @@ impl<V> BlockChainClient for Client<V> where V: Verifier {
(Some(b), invalid_transactions) (Some(b), invalid_transactions)
} }
fn block_header(&self, id: BlockId) -> Option<Bytes> { fn block_header(&self, id: BlockID) -> Option<Bytes> {
Self::block_hash(&self.chain, id).and_then(|hash| self.chain.block(&hash).map(|bytes| BlockView::new(&bytes).rlp().at(0).as_raw().to_vec())) Self::block_hash(&self.chain, id).and_then(|hash| self.chain.block(&hash).map(|bytes| BlockView::new(&bytes).rlp().at(0).as_raw().to_vec()))
} }
fn block_body(&self, id: BlockId) -> Option<Bytes> { fn block_body(&self, id: BlockID) -> Option<Bytes> {
Self::block_hash(&self.chain, id).and_then(|hash| { Self::block_hash(&self.chain, id).and_then(|hash| {
self.chain.block(&hash).map(|bytes| { self.chain.block(&hash).map(|bytes| {
let rlp = Rlp::new(&bytes); let rlp = Rlp::new(&bytes);
@ -519,13 +519,13 @@ impl<V> BlockChainClient for Client<V> where V: Verifier {
}) })
} }
fn block(&self, id: BlockId) -> Option<Bytes> { fn block(&self, id: BlockID) -> Option<Bytes> {
Self::block_hash(&self.chain, id).and_then(|hash| { Self::block_hash(&self.chain, id).and_then(|hash| {
self.chain.block(&hash) self.chain.block(&hash)
}) })
} }
fn block_status(&self, id: BlockId) -> BlockStatus { fn block_status(&self, id: BlockID) -> BlockStatus {
match Self::block_hash(&self.chain, id) { match Self::block_hash(&self.chain, id) {
Some(ref hash) if self.chain.is_known(hash) => BlockStatus::InChain, Some(ref hash) if self.chain.is_known(hash) => BlockStatus::InChain,
Some(hash) => self.block_queue.block_status(&hash), Some(hash) => self.block_queue.block_status(&hash),
@ -533,7 +533,7 @@ impl<V> BlockChainClient for Client<V> where V: Verifier {
} }
} }
fn block_total_difficulty(&self, id: BlockId) -> Option<U256> { fn block_total_difficulty(&self, id: BlockID) -> Option<U256> {
Self::block_hash(&self.chain, id).and_then(|hash| self.chain.block_details(&hash)).map(|d| d.total_difficulty) Self::block_hash(&self.chain, id).and_then(|hash| self.chain.block_details(&hash)).map(|d| d.total_difficulty)
} }
@ -541,7 +541,7 @@ impl<V> BlockChainClient for Client<V> where V: Verifier {
self.state().nonce(address) self.state().nonce(address)
} }
fn block_hash(&self, id: BlockId) -> Option<H256> { fn block_hash(&self, id: BlockID) -> Option<H256> {
Self::block_hash(&self.chain, id) Self::block_hash(&self.chain, id)
} }
@ -557,16 +557,16 @@ impl<V> BlockChainClient for Client<V> where V: Verifier {
self.state().storage_at(address, position) self.state().storage_at(address, position)
} }
fn transaction(&self, id: TransactionId) -> Option<LocalizedTransaction> { fn transaction(&self, id: TransactionID) -> Option<LocalizedTransaction> {
self.transaction_address(id).and_then(|address| self.chain.transaction(&address)) self.transaction_address(id).and_then(|address| self.chain.transaction(&address))
} }
fn uncle(&self, id: UncleId) -> Option<Header> { fn uncle(&self, id: UncleID) -> Option<Header> {
let index = id.1; let index = id.1;
self.block(id.0).and_then(|block| BlockView::new(&block).uncle_at(index)) self.block(id.0).and_then(|block| BlockView::new(&block).uncle_at(index))
} }
fn transaction_receipt(&self, id: TransactionId) -> Option<LocalizedReceipt> { fn transaction_receipt(&self, id: TransactionID) -> Option<LocalizedReceipt> {
self.transaction_address(id).and_then(|address| { self.transaction_address(id).and_then(|address| {
let t = self.chain.block(&address.block_hash) let t = self.chain.block(&address.block_hash)
.and_then(|block| BlockView::new(&block).localized_transaction_at(address.index)); .and_then(|block| BlockView::new(&block).localized_transaction_at(address.index));
@ -625,7 +625,7 @@ impl<V> BlockChainClient for Client<V> where V: Verifier {
if self.chain.is_known(&header.sha3()) { if self.chain.is_known(&header.sha3()) {
return Err(x!(ImportError::AlreadyInChain)); return Err(x!(ImportError::AlreadyInChain));
} }
if self.block_status(BlockId::Hash(header.parent_hash())) == BlockStatus::Unknown { if self.block_status(BlockID::Hash(header.parent_hash())) == BlockStatus::Unknown {
return Err(x!(BlockError::UnknownParent(header.parent_hash()))); return Err(x!(BlockError::UnknownParent(header.parent_hash())));
} }
} }
@ -650,7 +650,7 @@ impl<V> BlockChainClient for Client<V> where V: Verifier {
} }
} }
fn blocks_with_bloom(&self, bloom: &H2048, from_block: BlockId, to_block: BlockId) -> Option<Vec<BlockNumber>> { fn blocks_with_bloom(&self, bloom: &H2048, from_block: BlockID, to_block: BlockID) -> Option<Vec<BlockNumber>> {
match (self.block_number(from_block), self.block_number(to_block)) { match (self.block_number(from_block), self.block_number(to_block)) {
(Some(from), Some(to)) => Some(self.chain.blocks_with_bloom(bloom, from, to)), (Some(from), Some(to)) => Some(self.chain.blocks_with_bloom(bloom, from, to)),
_ => None _ => None
@ -721,20 +721,20 @@ impl<V> BlockChainClient for Client<V> where V: Verifier {
let trace_address = trace.address; let trace_address = trace.address;
self.transaction_address(trace.transaction) self.transaction_address(trace.transaction)
.and_then(|tx_address| { .and_then(|tx_address| {
self.block_number(BlockId::Hash(tx_address.block_hash)) self.block_number(BlockID::Hash(tx_address.block_hash))
.and_then(|number| self.tracedb.trace(number, tx_address.index, trace_address)) .and_then(|number| self.tracedb.trace(number, tx_address.index, trace_address))
}) })
} }
fn transaction_traces(&self, transaction: TransactionId) -> Option<Vec<LocalizedTrace>> { fn transaction_traces(&self, transaction: TransactionID) -> Option<Vec<LocalizedTrace>> {
self.transaction_address(transaction) self.transaction_address(transaction)
.and_then(|tx_address| { .and_then(|tx_address| {
self.block_number(BlockId::Hash(tx_address.block_hash)) self.block_number(BlockID::Hash(tx_address.block_hash))
.and_then(|number| self.tracedb.transaction_traces(number, tx_address.index)) .and_then(|number| self.tracedb.transaction_traces(number, tx_address.index))
}) })
} }
fn block_traces(&self, block: BlockId) -> Option<Vec<LocalizedTrace>> { fn block_traces(&self, block: BlockID) -> Option<Vec<LocalizedTrace>> {
self.block_number(block) self.block_number(block)
.and_then(|number| self.tracedb.block_traces(number)) .and_then(|number| self.tracedb.block_traces(number))
} }

View File

@ -48,26 +48,26 @@ use evm::Factory as EvmFactory;
/// Blockchain database client. Owns and manages a blockchain and a block queue. /// Blockchain database client. Owns and manages a blockchain and a block queue.
pub trait BlockChainClient : Sync + Send { pub trait BlockChainClient : Sync + Send {
/// Get raw block header data by block id. /// Get raw block header data by block id.
fn block_header(&self, id: BlockId) -> Option<Bytes>; fn block_header(&self, id: BlockID) -> Option<Bytes>;
/// Get raw block body data by block id. /// Get raw block body data by block id.
/// Block body is an RLP list of two items: uncles and transactions. /// Block body is an RLP list of two items: uncles and transactions.
fn block_body(&self, id: BlockId) -> Option<Bytes>; fn block_body(&self, id: BlockID) -> Option<Bytes>;
/// Get raw block data by block header hash. /// Get raw block data by block header hash.
fn block(&self, id: BlockId) -> Option<Bytes>; fn block(&self, id: BlockID) -> Option<Bytes>;
/// Get block status by block header hash. /// Get block status by block header hash.
fn block_status(&self, id: BlockId) -> BlockStatus; fn block_status(&self, id: BlockID) -> BlockStatus;
/// Get block total difficulty. /// Get block total difficulty.
fn block_total_difficulty(&self, id: BlockId) -> Option<U256>; fn block_total_difficulty(&self, id: BlockID) -> Option<U256>;
/// Get address nonce. /// Get address nonce.
fn nonce(&self, address: &Address) -> U256; fn nonce(&self, address: &Address) -> U256;
/// Get block hash. /// Get block hash.
fn block_hash(&self, id: BlockId) -> Option<H256>; fn block_hash(&self, id: BlockID) -> Option<H256>;
/// Get address code. /// Get address code.
fn code(&self, address: &Address) -> Option<Bytes>; fn code(&self, address: &Address) -> Option<Bytes>;
@ -79,13 +79,13 @@ pub trait BlockChainClient : Sync + Send {
fn storage_at(&self, address: &Address, position: &H256) -> H256; fn storage_at(&self, address: &Address, position: &H256) -> H256;
/// Get transaction with given hash. /// Get transaction with given hash.
fn transaction(&self, id: TransactionId) -> Option<LocalizedTransaction>; fn transaction(&self, id: TransactionID) -> Option<LocalizedTransaction>;
/// Get uncle with given id. /// Get uncle with given id.
fn uncle(&self, id: UncleId) -> Option<Header>; fn uncle(&self, id: UncleID) -> Option<Header>;
/// Get transaction receipt with given hash. /// Get transaction receipt with given hash.
fn transaction_receipt(&self, id: TransactionId) -> Option<LocalizedReceipt>; fn transaction_receipt(&self, id: TransactionID) -> Option<LocalizedReceipt>;
/// Get a tree route between `from` and `to`. /// Get a tree route between `from` and `to`.
/// See `BlockChain::tree_route`. /// See `BlockChain::tree_route`.
@ -112,11 +112,11 @@ pub trait BlockChainClient : Sync + Send {
/// Get the best block header. /// Get the best block header.
fn best_block_header(&self) -> Bytes { fn best_block_header(&self) -> Bytes {
// TODO: lock blockchain only once // TODO: lock blockchain only once
self.block_header(BlockId::Hash(self.chain_info().best_block_hash)).unwrap() self.block_header(BlockID::Hash(self.chain_info().best_block_hash)).unwrap()
} }
/// Returns numbers of blocks containing given bloom. /// Returns numbers of blocks containing given bloom.
fn blocks_with_bloom(&self, bloom: &H2048, from_block: BlockId, to_block: BlockId) -> Option<Vec<BlockNumber>>; fn blocks_with_bloom(&self, bloom: &H2048, from_block: BlockID, to_block: BlockID) -> Option<Vec<BlockNumber>>;
/// Returns logs matching given filter. /// Returns logs matching given filter.
fn logs(&self, filter: Filter) -> Vec<LocalizedLogEntry>; fn logs(&self, filter: Filter) -> Vec<LocalizedLogEntry>;
@ -143,10 +143,10 @@ pub trait BlockChainClient : Sync + Send {
fn trace(&self, trace: TraceId) -> Option<LocalizedTrace>; fn trace(&self, trace: TraceId) -> Option<LocalizedTrace>;
/// Returns traces created by transaction. /// Returns traces created by transaction.
fn transaction_traces(&self, trace: TransactionId) -> Option<Vec<LocalizedTrace>>; fn transaction_traces(&self, trace: TransactionID) -> Option<Vec<LocalizedTrace>>;
/// Returns traces created by transaction from block. /// Returns traces created by transaction from block.
fn block_traces(&self, trace: BlockId) -> Option<Vec<LocalizedTrace>>; fn block_traces(&self, trace: BlockID) -> Option<Vec<LocalizedTrace>>;
/// Get last hashes starting from best block. /// Get last hashes starting from best block.
fn last_hashes(&self) -> LastHashes; fn last_hashes(&self) -> LastHashes;

View File

@ -20,7 +20,7 @@ use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrder};
use util::*; use util::*;
use transaction::{Transaction, LocalizedTransaction, SignedTransaction, Action}; use transaction::{Transaction, LocalizedTransaction, SignedTransaction, Action};
use blockchain::TreeRoute; use blockchain::TreeRoute;
use client::{BlockChainClient, BlockChainInfo, BlockStatus, BlockId, TransactionId, UncleId, TraceId, TraceFilter, LastHashes}; use client::{BlockChainClient, BlockChainInfo, BlockStatus, BlockID, TransactionID, UncleID, TraceId, TraceFilter, LastHashes};
use header::{Header as BlockHeader, BlockNumber}; use header::{Header as BlockHeader, BlockNumber};
use filter::Filter; use filter::Filter;
use log_entry::LocalizedLogEntry; use log_entry::LocalizedLogEntry;
@ -58,7 +58,7 @@ pub struct TestBlockChainClient {
/// Execution result. /// Execution result.
pub execution_result: RwLock<Option<Executed>>, pub execution_result: RwLock<Option<Executed>>,
/// Transaction receipts. /// Transaction receipts.
pub receipts: RwLock<HashMap<TransactionId, LocalizedReceipt>>, pub receipts: RwLock<HashMap<TransactionID, LocalizedReceipt>>,
/// Block queue size. /// Block queue size.
pub queue_size: AtomicUsize, pub queue_size: AtomicUsize,
} }
@ -106,7 +106,7 @@ impl TestBlockChainClient {
} }
/// Set the transaction receipt result /// Set the transaction receipt result
pub fn set_transaction_receipt(&self, id: TransactionId, receipt: LocalizedReceipt) { pub fn set_transaction_receipt(&self, id: TransactionID, receipt: LocalizedReceipt) {
self.receipts.write().unwrap().insert(id, receipt); self.receipts.write().unwrap().insert(id, receipt);
} }
@ -193,8 +193,8 @@ impl TestBlockChainClient {
/// TODO: /// TODO:
pub fn corrupt_block(&mut self, n: BlockNumber) { pub fn corrupt_block(&mut self, n: BlockNumber) {
let hash = self.block_hash(BlockId::Number(n)).unwrap(); let hash = self.block_hash(BlockID::Number(n)).unwrap();
let mut header: BlockHeader = decode(&self.block_header(BlockId::Number(n)).unwrap()); let mut header: BlockHeader = decode(&self.block_header(BlockID::Number(n)).unwrap());
header.parent_hash = H256::new(); header.parent_hash = H256::new();
let mut rlp = RlpStream::new_list(3); let mut rlp = RlpStream::new_list(3);
rlp.append(&header); rlp.append(&header);
@ -210,12 +210,12 @@ impl TestBlockChainClient {
blocks_read[&index].clone() blocks_read[&index].clone()
} }
fn block_hash(&self, id: BlockId) -> Option<H256> { fn block_hash(&self, id: BlockID) -> Option<H256> {
match id { match id {
BlockId::Hash(hash) => Some(hash), BlockID::Hash(hash) => Some(hash),
BlockId::Number(n) => self.numbers.read().unwrap().get(&(n as usize)).cloned(), BlockID::Number(n) => self.numbers.read().unwrap().get(&(n as usize)).cloned(),
BlockId::Earliest => self.numbers.read().unwrap().get(&0).cloned(), BlockID::Earliest => self.numbers.read().unwrap().get(&0).cloned(),
BlockId::Latest => self.numbers.read().unwrap().get(&(self.numbers.read().unwrap().len() - 1)).cloned() BlockID::Latest => self.numbers.read().unwrap().get(&(self.numbers.read().unwrap().len() - 1)).cloned()
} }
} }
} }
@ -225,11 +225,11 @@ impl BlockChainClient for TestBlockChainClient {
Ok(self.execution_result.read().unwrap().clone().unwrap()) Ok(self.execution_result.read().unwrap().clone().unwrap())
} }
fn block_total_difficulty(&self, _id: BlockId) -> Option<U256> { fn block_total_difficulty(&self, _id: BlockID) -> Option<U256> {
Some(U256::zero()) Some(U256::zero())
} }
fn block_hash(&self, _id: BlockId) -> Option<H256> { fn block_hash(&self, _id: BlockID) -> Option<H256> {
unimplemented!(); unimplemented!();
} }
@ -249,19 +249,19 @@ impl BlockChainClient for TestBlockChainClient {
self.storage.read().unwrap().get(&(address.clone(), position.clone())).cloned().unwrap_or_else(H256::new) self.storage.read().unwrap().get(&(address.clone(), position.clone())).cloned().unwrap_or_else(H256::new)
} }
fn transaction(&self, _id: TransactionId) -> Option<LocalizedTransaction> { fn transaction(&self, _id: TransactionID) -> Option<LocalizedTransaction> {
unimplemented!(); unimplemented!();
} }
fn uncle(&self, _id: UncleId) -> Option<BlockHeader> { fn uncle(&self, _id: UncleID) -> Option<BlockHeader> {
unimplemented!(); unimplemented!();
} }
fn transaction_receipt(&self, id: TransactionId) -> Option<LocalizedReceipt> { fn transaction_receipt(&self, id: TransactionID) -> Option<LocalizedReceipt> {
self.receipts.read().unwrap().get(&id).cloned() self.receipts.read().unwrap().get(&id).cloned()
} }
fn blocks_with_bloom(&self, _bloom: &H2048, _from_block: BlockId, _to_block: BlockId) -> Option<Vec<BlockNumber>> { fn blocks_with_bloom(&self, _bloom: &H2048, _from_block: BlockID, _to_block: BlockID) -> Option<Vec<BlockNumber>> {
unimplemented!(); unimplemented!();
} }
@ -281,11 +281,11 @@ impl BlockChainClient for TestBlockChainClient {
Err(block) Err(block)
} }
fn block_header(&self, id: BlockId) -> Option<Bytes> { fn block_header(&self, id: BlockID) -> Option<Bytes> {
self.block_hash(id).and_then(|hash| self.blocks.read().unwrap().get(&hash).map(|r| Rlp::new(r).at(0).as_raw().to_vec())) self.block_hash(id).and_then(|hash| self.blocks.read().unwrap().get(&hash).map(|r| Rlp::new(r).at(0).as_raw().to_vec()))
} }
fn block_body(&self, id: BlockId) -> Option<Bytes> { fn block_body(&self, id: BlockID) -> Option<Bytes> {
self.block_hash(id).and_then(|hash| self.blocks.read().unwrap().get(&hash).map(|r| { self.block_hash(id).and_then(|hash| self.blocks.read().unwrap().get(&hash).map(|r| {
let mut stream = RlpStream::new_list(2); let mut stream = RlpStream::new_list(2);
stream.append_raw(Rlp::new(&r).at(1).as_raw(), 1); stream.append_raw(Rlp::new(&r).at(1).as_raw(), 1);
@ -294,14 +294,14 @@ impl BlockChainClient for TestBlockChainClient {
})) }))
} }
fn block(&self, id: BlockId) -> Option<Bytes> { fn block(&self, id: BlockID) -> Option<Bytes> {
self.block_hash(id).and_then(|hash| self.blocks.read().unwrap().get(&hash).cloned()) self.block_hash(id).and_then(|hash| self.blocks.read().unwrap().get(&hash).cloned())
} }
fn block_status(&self, id: BlockId) -> BlockStatus { fn block_status(&self, id: BlockID) -> BlockStatus {
match id { match id {
BlockId::Number(number) if (number as usize) < self.blocks.read().unwrap().len() => BlockStatus::InChain, BlockID::Number(number) if (number as usize) < self.blocks.read().unwrap().len() => BlockStatus::InChain,
BlockId::Hash(ref hash) if self.blocks.read().unwrap().get(hash).is_some() => BlockStatus::InChain, BlockID::Hash(ref hash) if self.blocks.read().unwrap().get(hash).is_some() => BlockStatus::InChain,
_ => BlockStatus::Unknown _ => BlockStatus::Unknown
} }
} }
@ -442,11 +442,11 @@ impl BlockChainClient for TestBlockChainClient {
unimplemented!(); unimplemented!();
} }
fn transaction_traces(&self, _trace: TransactionId) -> Option<Vec<LocalizedTrace>> { fn transaction_traces(&self, _trace: TransactionID) -> Option<Vec<LocalizedTrace>> {
unimplemented!(); unimplemented!();
} }
fn block_traces(&self, _trace: BlockId) -> Option<Vec<LocalizedTrace>> { fn block_traces(&self, _trace: BlockID) -> Option<Vec<LocalizedTrace>> {
unimplemented!(); unimplemented!();
} }
} }

View File

@ -7,7 +7,7 @@ use header::BlockNumber;
use trace::DatabaseExtras as TraceDatabaseExtras; use trace::DatabaseExtras as TraceDatabaseExtras;
use blockchain::{BlockChain, BlockProvider}; use blockchain::{BlockChain, BlockProvider};
use extras::TransactionAddress; use extras::TransactionAddress;
use super::BlockId; use super::BlockID;
impl TraceDatabaseExtras for BlockChain { impl TraceDatabaseExtras for BlockChain {
fn block_hash(&self, block_number: BlockNumber) -> Option<H256> { fn block_hash(&self, block_number: BlockNumber) -> Option<H256> {
@ -30,7 +30,7 @@ impl TraceDatabaseExtras for BlockChain {
/// Easy to use trace filter. /// Easy to use trace filter.
pub struct Filter { pub struct Filter {
/// Range of filtering. /// Range of filtering.
pub range: Range<BlockId>, pub range: Range<BlockID>,
/// From address. /// From address.
pub from_address: Vec<Address>, pub from_address: Vec<Address>,
/// To address. /// To address.

View File

@ -18,16 +18,16 @@
use util::hash::*; use util::hash::*;
use util::sha3::*; use util::sha3::*;
use client::BlockId; use client::BlockID;
use log_entry::LogEntry; use log_entry::LogEntry;
/// Blockchain Filter. /// Blockchain Filter.
pub struct Filter { pub struct Filter {
/// Blockchain will be searched from this block. /// Blockchain will be searched from this block.
pub from_block: BlockId, pub from_block: BlockID,
/// Till this block. /// Till this block.
pub to_block: BlockId, pub to_block: BlockID,
/// Search addresses. /// Search addresses.
/// ///
@ -102,14 +102,14 @@ mod tests {
use std::str::FromStr; use std::str::FromStr;
use util::hash::*; use util::hash::*;
use filter::Filter; use filter::Filter;
use client::BlockId; use client::BlockID;
use log_entry::LogEntry; use log_entry::LogEntry;
#[test] #[test]
fn test_bloom_possibilities_none() { fn test_bloom_possibilities_none() {
let none_filter = Filter { let none_filter = Filter {
from_block: BlockId::Earliest, from_block: BlockID::Earliest,
to_block: BlockId::Latest, to_block: BlockID::Latest,
address: None, address: None,
topics: [None, None, None, None] topics: [None, None, None, None]
}; };
@ -123,8 +123,8 @@ mod tests {
#[test] #[test]
fn test_bloom_possibilities_single_address_and_topic() { fn test_bloom_possibilities_single_address_and_topic() {
let filter = Filter { let filter = Filter {
from_block: BlockId::Earliest, from_block: BlockID::Earliest,
to_block: BlockId::Latest, to_block: BlockID::Latest,
address: Some(vec![Address::from_str("b372018f3be9e171df0581136b59d2faf73a7d5d").unwrap()]), address: Some(vec![Address::from_str("b372018f3be9e171df0581136b59d2faf73a7d5d").unwrap()]),
topics: [ topics: [
Some(vec![H256::from_str("ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23f9").unwrap()]), Some(vec![H256::from_str("ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23f9").unwrap()]),
@ -139,8 +139,8 @@ mod tests {
#[test] #[test]
fn test_bloom_possibilities_single_address_and_many_topics() { fn test_bloom_possibilities_single_address_and_many_topics() {
let filter = Filter { let filter = Filter {
from_block: BlockId::Earliest, from_block: BlockID::Earliest,
to_block: BlockId::Latest, to_block: BlockID::Latest,
address: Some(vec![Address::from_str("b372018f3be9e171df0581136b59d2faf73a7d5d").unwrap()]), address: Some(vec![Address::from_str("b372018f3be9e171df0581136b59d2faf73a7d5d").unwrap()]),
topics: [ topics: [
Some(vec![H256::from_str("ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23f9").unwrap()]), Some(vec![H256::from_str("ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23f9").unwrap()]),
@ -156,8 +156,8 @@ mod tests {
#[test] #[test]
fn test_bloom_possibilites_multiple_addresses_and_topics() { fn test_bloom_possibilites_multiple_addresses_and_topics() {
let filter = Filter { let filter = Filter {
from_block: BlockId::Earliest, from_block: BlockID::Earliest,
to_block: BlockId::Latest, to_block: BlockID::Latest,
address: Some(vec![ address: Some(vec![
Address::from_str("b372018f3be9e171df0581136b59d2faf73a7d5d").unwrap(), Address::from_str("b372018f3be9e171df0581136b59d2faf73a7d5d").unwrap(),
Address::from_str("b372018f3be9e171df0581136b59d2faf73a7d5d").unwrap(), Address::from_str("b372018f3be9e171df0581136b59d2faf73a7d5d").unwrap(),
@ -185,8 +185,8 @@ mod tests {
#[test] #[test]
fn test_filter_matches() { fn test_filter_matches() {
let filter = Filter { let filter = Filter {
from_block: BlockId::Earliest, from_block: BlockID::Earliest,
to_block: BlockId::Latest, to_block: BlockID::Latest,
address: Some(vec![Address::from_str("b372018f3be9e171df0581136b59d2faf73a7d5d").unwrap()]), address: Some(vec![Address::from_str("b372018f3be9e171df0581136b59d2faf73a7d5d").unwrap()]),
topics: [ topics: [
Some(vec![H256::from_str("ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23f9").unwrap()]), Some(vec![H256::from_str("ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23f9").unwrap()]),

View File

@ -14,7 +14,7 @@
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>. // along with Parity. If not, see <http://www.gnu.org/licenses/>.
use client::{BlockChainClient, Client, ClientConfig, BlockId}; use client::{BlockChainClient, Client, ClientConfig, BlockID};
use block::IsBlock; use block::IsBlock;
use tests::helpers::*; use tests::helpers::*;
use common::*; use common::*;
@ -49,7 +49,7 @@ fn imports_good_block() {
client.flush_queue(); client.flush_queue();
client.import_verified_blocks(&IoChannel::disconnected()); client.import_verified_blocks(&IoChannel::disconnected());
let block = client.block_header(BlockId::Number(1)).unwrap(); let block = client.block_header(BlockID::Number(1)).unwrap();
assert!(!block.is_empty()); assert!(!block.is_empty());
} }
@ -58,7 +58,7 @@ fn query_none_block() {
let dir = RandomTempPath::new(); let dir = RandomTempPath::new();
let client = Client::new(ClientConfig::default(), get_test_spec(), dir.as_path(), IoChannel::disconnected()); let client = Client::new(ClientConfig::default(), get_test_spec(), dir.as_path(), IoChannel::disconnected());
let non_existant = client.block_header(BlockId::Number(188)); let non_existant = client.block_header(BlockID::Number(188));
assert!(non_existant.is_none()); assert!(non_existant.is_none());
} }
@ -66,7 +66,7 @@ fn query_none_block() {
fn query_bad_block() { fn query_bad_block() {
let client_result = get_test_client_with_blocks(vec![get_bad_state_dummy_block()]); let client_result = get_test_client_with_blocks(vec![get_bad_state_dummy_block()]);
let client = client_result.reference(); let client = client_result.reference();
let bad_block:Option<Bytes> = client.block_header(BlockId::Number(1)); let bad_block:Option<Bytes> = client.block_header(BlockID::Number(1));
assert!(bad_block.is_none()); assert!(bad_block.is_none());
} }
@ -87,7 +87,7 @@ fn returns_block_body() {
let client_result = get_test_client_with_blocks(vec![dummy_block.clone()]); let client_result = get_test_client_with_blocks(vec![dummy_block.clone()]);
let client = client_result.reference(); let client = client_result.reference();
let block = BlockView::new(&dummy_block); let block = BlockView::new(&dummy_block);
let body = client.block_body(BlockId::Hash(block.header().hash())).unwrap(); let body = client.block_body(BlockID::Hash(block.header().hash())).unwrap();
let body = Rlp::new(&body); let body = Rlp::new(&body);
assert_eq!(body.item_count(), 2); assert_eq!(body.item_count(), 2);
assert_eq!(body.at(0).as_raw()[..], block.rlp().at(1).as_raw()[..]); assert_eq!(body.at(0).as_raw()[..], block.rlp().at(1).as_raw()[..]);
@ -98,7 +98,7 @@ fn returns_block_body() {
fn imports_block_sequence() { fn imports_block_sequence() {
let client_result = generate_dummy_client(6); let client_result = generate_dummy_client(6);
let client = client_result.reference(); let client = client_result.reference();
let block = client.block_header(BlockId::Number(5)).unwrap(); let block = client.block_header(BlockID::Number(5)).unwrap();
assert!(!block.is_empty()); assert!(!block.is_empty());
} }

View File

@ -24,7 +24,7 @@ use std::collections::VecDeque;
/// Uniquely identifies block. /// Uniquely identifies block.
#[derive(Debug, PartialEq, Clone, Hash, Eq, Binary)] #[derive(Debug, PartialEq, Clone, Hash, Eq, Binary)]
pub enum BlockId { pub enum BlockID {
/// Block's sha3. /// Block's sha3.
/// Querying by hash is always faster. /// Querying by hash is always faster.
Hash(H256), Hash(H256),
@ -38,27 +38,27 @@ pub enum BlockId {
/// Uniquely identifies transaction. /// Uniquely identifies transaction.
#[derive(Debug, PartialEq, Clone, Hash, Eq, Binary)] #[derive(Debug, PartialEq, Clone, Hash, Eq, Binary)]
pub enum TransactionId { pub enum TransactionID {
/// Transaction's sha3. /// Transaction's sha3.
Hash(H256), Hash(H256),
/// Block id and transaction index within this block. /// Block id and transaction index within this block.
/// Querying by block position is always faster. /// Querying by block position is always faster.
Location(BlockId, usize) Location(BlockID, usize)
} }
/// Uniquely identifies Trace. /// Uniquely identifies Trace.
pub struct TraceId { pub struct TraceId {
/// Transaction /// Transaction
pub transaction: TransactionId, pub transaction: TransactionID,
/// Trace address within transaction. /// Trace address within transaction.
pub address: Vec<usize>, pub address: Vec<usize>,
} }
/// Uniquely identifies Uncle. /// Uniquely identifies Uncle.
#[derive(Debug)] #[derive(Debug)]
pub struct UncleId ( pub struct UncleID (
/// Block id. /// Block id.
pub BlockId, pub BlockID,
/// Position in block. /// Position in block.
pub usize pub usize
); );

View File

@ -20,7 +20,7 @@ use std::sync::atomic::AtomicBool;
use util::*; use util::*;
use util::keys::store::{AccountService, AccountProvider}; use util::keys::store::{AccountService, AccountProvider};
use ethcore::views::{BlockView, HeaderView}; use ethcore::views::{BlockView, HeaderView};
use ethcore::client::{BlockChainClient, BlockId}; use ethcore::client::{BlockChainClient, BlockID};
use ethcore::block::{ClosedBlock, IsBlock}; use ethcore::block::{ClosedBlock, IsBlock};
use ethcore::error::*; use ethcore::error::*;
use ethcore::client::{Executive, Executed, EnvInfo, TransactOptions}; use ethcore::client::{Executive, Executed, EnvInfo, TransactOptions};
@ -475,7 +475,7 @@ impl MinerService for Miner {
fn chain_new_blocks(&self, chain: &BlockChainClient, _imported: &[H256], _invalid: &[H256], enacted: &[H256], retracted: &[H256]) { fn chain_new_blocks(&self, chain: &BlockChainClient, _imported: &[H256], _invalid: &[H256], enacted: &[H256], retracted: &[H256]) {
fn fetch_transactions(chain: &BlockChainClient, hash: &H256) -> Vec<SignedTransaction> { fn fetch_transactions(chain: &BlockChainClient, hash: &H256) -> Vec<SignedTransaction> {
let block = chain let block = chain
.block(BlockId::Hash(*hash)) .block(BlockID::Hash(*hash))
// Client should send message after commit to db and inserting to chain. // Client should send message after commit to db and inserting to chain.
.expect("Expected in-chain blocks."); .expect("Expected in-chain blocks.");
let block = BlockView::new(&block); let block = BlockView::new(&block);

View File

@ -75,7 +75,7 @@ impl<C, S, A, M, EM> EthClient<C, S, A, M, EM>
} }
} }
fn block(&self, id: BlockId, include_txs: bool) -> Result<Value, Error> { fn block(&self, id: BlockID, include_txs: bool) -> Result<Value, Error> {
let client = take_weak!(self.client); let client = take_weak!(self.client);
match (client.block(id.clone()), client.block_total_difficulty(id)) { match (client.block(id.clone()), client.block_total_difficulty(id)) {
(Some(bytes), Some(total_difficulty)) => { (Some(bytes), Some(total_difficulty)) => {
@ -114,16 +114,16 @@ impl<C, S, A, M, EM> EthClient<C, S, A, M, EM>
} }
} }
fn transaction(&self, id: TransactionId) -> Result<Value, Error> { fn transaction(&self, id: TransactionID) -> Result<Value, Error> {
match take_weak!(self.client).transaction(id) { match take_weak!(self.client).transaction(id) {
Some(t) => to_value(&Transaction::from(t)), Some(t) => to_value(&Transaction::from(t)),
None => Ok(Value::Null) None => Ok(Value::Null)
} }
} }
fn uncle(&self, id: UncleId) -> Result<Value, Error> { fn uncle(&self, id: UncleID) -> Result<Value, Error> {
let client = take_weak!(self.client); let client = take_weak!(self.client);
match client.uncle(id).and_then(|u| client.block_total_difficulty(BlockId::Hash(u.parent_hash().clone())).map(|diff| (diff, u))) { match client.uncle(id).and_then(|u| client.block_total_difficulty(BlockID::Hash(u.parent_hash().clone())).map(|diff| (diff, u))) {
Some((parent_difficulty, uncle)) => { Some((parent_difficulty, uncle)) => {
let block = Block { let block = Block {
hash: OptionalValue::Value(uncle.hash()), hash: OptionalValue::Value(uncle.hash()),
@ -322,7 +322,7 @@ impl<C, S, A, M, EM> Eth for EthClient<C, S, A, M, EM>
fn block_transaction_count_by_hash(&self, params: Params) -> Result<Value, Error> { fn block_transaction_count_by_hash(&self, params: Params) -> Result<Value, Error> {
from_params::<(H256,)>(params) from_params::<(H256,)>(params)
.and_then(|(hash,)| // match .and_then(|(hash,)| // match
take_weak!(self.client).block(BlockId::Hash(hash)) take_weak!(self.client).block(BlockID::Hash(hash))
.map_or(Ok(Value::Null), |bytes| to_value(&U256::from(BlockView::new(&bytes).transactions_count())))) .map_or(Ok(Value::Null), |bytes| to_value(&U256::from(BlockView::new(&bytes).transactions_count()))))
} }
@ -340,7 +340,7 @@ impl<C, S, A, M, EM> Eth for EthClient<C, S, A, M, EM>
fn block_uncles_count_by_hash(&self, params: Params) -> Result<Value, Error> { fn block_uncles_count_by_hash(&self, params: Params) -> Result<Value, Error> {
from_params::<(H256,)>(params) from_params::<(H256,)>(params)
.and_then(|(hash,)| .and_then(|(hash,)|
take_weak!(self.client).block(BlockId::Hash(hash)) take_weak!(self.client).block(BlockID::Hash(hash))
.map_or(Ok(Value::Null), |bytes| to_value(&U256::from(BlockView::new(&bytes).uncles_count())))) .map_or(Ok(Value::Null), |bytes| to_value(&U256::from(BlockView::new(&bytes).uncles_count()))))
} }
@ -364,7 +364,7 @@ impl<C, S, A, M, EM> Eth for EthClient<C, S, A, M, EM>
fn block_by_hash(&self, params: Params) -> Result<Value, Error> { fn block_by_hash(&self, params: Params) -> Result<Value, Error> {
from_params::<(H256, bool)>(params) from_params::<(H256, bool)>(params)
.and_then(|(hash, include_txs)| self.block(BlockId::Hash(hash), include_txs)) .and_then(|(hash, include_txs)| self.block(BlockID::Hash(hash), include_txs))
} }
fn block_by_number(&self, params: Params) -> Result<Value, Error> { fn block_by_number(&self, params: Params) -> Result<Value, Error> {
@ -378,38 +378,38 @@ impl<C, S, A, M, EM> Eth for EthClient<C, S, A, M, EM>
let miner = take_weak!(self.miner); let miner = take_weak!(self.miner);
match miner.transaction(&hash) { match miner.transaction(&hash) {
Some(pending_tx) => to_value(&Transaction::from(pending_tx)), Some(pending_tx) => to_value(&Transaction::from(pending_tx)),
None => self.transaction(TransactionId::Hash(hash)) None => self.transaction(TransactionID::Hash(hash))
} }
}) })
} }
fn transaction_by_block_hash_and_index(&self, params: Params) -> Result<Value, Error> { fn transaction_by_block_hash_and_index(&self, params: Params) -> Result<Value, Error> {
from_params::<(H256, Index)>(params) from_params::<(H256, Index)>(params)
.and_then(|(hash, index)| self.transaction(TransactionId::Location(BlockId::Hash(hash), index.value()))) .and_then(|(hash, index)| self.transaction(TransactionID::Location(BlockID::Hash(hash), index.value())))
} }
fn transaction_by_block_number_and_index(&self, params: Params) -> Result<Value, Error> { fn transaction_by_block_number_and_index(&self, params: Params) -> Result<Value, Error> {
from_params::<(BlockNumber, Index)>(params) from_params::<(BlockNumber, Index)>(params)
.and_then(|(number, index)| self.transaction(TransactionId::Location(number.into(), index.value()))) .and_then(|(number, index)| self.transaction(TransactionID::Location(number.into(), index.value())))
} }
fn transaction_receipt(&self, params: Params) -> Result<Value, Error> { fn transaction_receipt(&self, params: Params) -> Result<Value, Error> {
from_params::<(H256,)>(params) from_params::<(H256,)>(params)
.and_then(|(hash,)| { .and_then(|(hash,)| {
let client = take_weak!(self.client); let client = take_weak!(self.client);
let receipt = client.transaction_receipt(TransactionId::Hash(hash)); let receipt = client.transaction_receipt(TransactionID::Hash(hash));
to_value(&receipt.map(Receipt::from)) to_value(&receipt.map(Receipt::from))
}) })
} }
fn uncle_by_block_hash_and_index(&self, params: Params) -> Result<Value, Error> { fn uncle_by_block_hash_and_index(&self, params: Params) -> Result<Value, Error> {
from_params::<(H256, Index)>(params) from_params::<(H256, Index)>(params)
.and_then(|(hash, index)| self.uncle(UncleId(BlockId::Hash(hash), index.value()))) .and_then(|(hash, index)| self.uncle(UncleID(BlockID::Hash(hash), index.value())))
} }
fn uncle_by_block_number_and_index(&self, params: Params) -> Result<Value, Error> { fn uncle_by_block_number_and_index(&self, params: Params) -> Result<Value, Error> {
from_params::<(BlockNumber, Index)>(params) from_params::<(BlockNumber, Index)>(params)
.and_then(|(number, index)| self.uncle(UncleId(number.into(), index.value()))) .and_then(|(number, index)| self.uncle(UncleID(number.into(), index.value())))
} }
fn compilers(&self, params: Params) -> Result<Value, Error> { fn compilers(&self, params: Params) -> Result<Value, Error> {
@ -617,7 +617,7 @@ impl<C, M> EthFilter for EthFilterClient<C, M>
// + 1, cause we want to return hashes including current block hash. // + 1, cause we want to return hashes including current block hash.
let current_number = client.chain_info().best_block_number + 1; let current_number = client.chain_info().best_block_number + 1;
let hashes = (*block_number..current_number).into_iter() let hashes = (*block_number..current_number).into_iter()
.map(BlockId::Number) .map(BlockID::Number)
.filter_map(|id| client.block_hash(id)) .filter_map(|id| client.block_hash(id))
.collect::<Vec<H256>>(); .collect::<Vec<H256>>();
@ -641,8 +641,8 @@ impl<C, M> EthFilter for EthFilterClient<C, M>
}, },
PollFilter::Logs(ref mut block_number, ref filter) => { PollFilter::Logs(ref mut block_number, ref filter) => {
let mut filter = filter.clone(); let mut filter = filter.clone();
filter.from_block = BlockId::Number(*block_number); filter.from_block = BlockID::Number(*block_number);
filter.to_block = BlockId::Latest; filter.to_block = BlockID::Latest;
let logs = client.logs(filter) let logs = client.logs(filter)
.into_iter() .into_iter()
.map(From::from) .map(From::from)

View File

@ -19,7 +19,7 @@
use std::sync::{Weak, Arc}; use std::sync::{Weak, Arc};
use jsonrpc_core::*; use jsonrpc_core::*;
use util::H256; use util::H256;
use ethcore::client::{BlockChainClient, TransactionId, TraceId}; use ethcore::client::{BlockChainClient, TransactionID, TraceId};
use v1::traits::Traces; use v1::traits::Traces;
use v1::types::{TraceFilter, Trace, BlockNumber, Index}; use v1::types::{TraceFilter, Trace, BlockNumber, Index};
@ -62,7 +62,7 @@ impl<C> Traces for TracesClient<C> where C: BlockChainClient + 'static {
from_params::<(H256,)>(params) from_params::<(H256,)>(params)
.and_then(|(transaction_hash,)| { .and_then(|(transaction_hash,)| {
let client = take_weak!(self.client); let client = take_weak!(self.client);
let traces = client.transaction_traces(TransactionId::Hash(transaction_hash)); let traces = client.transaction_traces(TransactionID::Hash(transaction_hash));
let traces = traces.map_or_else(Vec::new, |traces| traces.into_iter().map(Trace::from).collect()); let traces = traces.map_or_else(Vec::new, |traces| traces.into_iter().map(Trace::from).collect());
to_value(&traces) to_value(&traces)
}) })
@ -73,7 +73,7 @@ impl<C> Traces for TracesClient<C> where C: BlockChainClient + 'static {
.and_then(|(transaction_hash, address)| { .and_then(|(transaction_hash, address)| {
let client = take_weak!(self.client); let client = take_weak!(self.client);
let id = TraceId { let id = TraceId {
transaction: TransactionId::Hash(transaction_hash), transaction: TransactionID::Hash(transaction_hash),
address: address.into_iter().map(|i| i.value()).collect() address: address.into_iter().map(|i| i.value()).collect()
}; };
let trace = client.trace(id); let trace = client.trace(id);

View File

@ -21,7 +21,7 @@ use jsonrpc_core::IoHandler;
use util::hash::{Address, H256, FixedHash}; use util::hash::{Address, H256, FixedHash};
use util::numbers::{Uint, U256}; use util::numbers::{Uint, U256};
use util::keys::{TestAccount, TestAccountProvider}; use util::keys::{TestAccount, TestAccountProvider};
use ethcore::client::{TestBlockChainClient, EachBlockWith, Executed, TransactionId}; use ethcore::client::{TestBlockChainClient, EachBlockWith, Executed, TransactionID};
use ethcore::log_entry::{LocalizedLogEntry, LogEntry}; use ethcore::log_entry::{LocalizedLogEntry, LogEntry};
use ethcore::receipt::LocalizedReceipt; use ethcore::receipt::LocalizedReceipt;
use ethcore::transaction::{Transaction, Action}; use ethcore::transaction::{Transaction, Action};
@ -562,7 +562,7 @@ fn rpc_eth_transaction_receipt() {
let hash = H256::from_str("b903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238").unwrap(); let hash = H256::from_str("b903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238").unwrap();
let tester = EthTester::default(); let tester = EthTester::default();
tester.client.set_transaction_receipt(TransactionId::Hash(hash), receipt); tester.client.set_transaction_receipt(TransactionID::Hash(hash), receipt);
let request = r#"{ let request = r#"{
"jsonrpc": "2.0", "jsonrpc": "2.0",

View File

@ -16,7 +16,7 @@
use serde::{Deserialize, Deserializer, Error}; use serde::{Deserialize, Deserializer, Error};
use serde::de::Visitor; use serde::de::Visitor;
use ethcore::client::BlockId; use ethcore::client::BlockID;
/// Represents rpc api block number param. /// Represents rpc api block number param.
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
@ -54,20 +54,20 @@ impl Visitor for BlockNumberVisitor {
} }
} }
impl Into<BlockId> for BlockNumber { impl Into<BlockID> for BlockNumber {
fn into(self) -> BlockId { fn into(self) -> BlockID {
match self { match self {
BlockNumber::Num(n) => BlockId::Number(n), BlockNumber::Num(n) => BlockID::Number(n),
BlockNumber::Earliest => BlockId::Earliest, BlockNumber::Earliest => BlockID::Earliest,
// TODO: change this once blockid support pendingst, // TODO: change this once blockid support pendingst,
BlockNumber::Pending | BlockNumber::Latest => BlockId::Latest, BlockNumber::Pending | BlockNumber::Latest => BlockID::Latest,
} }
} }
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use ethcore::client::BlockId; use ethcore::client::BlockID;
use super::*; use super::*;
use serde_json; use serde_json;
@ -80,10 +80,10 @@ mod tests {
#[test] #[test]
fn block_number_into() { fn block_number_into() {
assert_eq!(BlockId::Number(100), BlockNumber::Num(100).into()); assert_eq!(BlockID::Number(100), BlockNumber::Num(100).into());
assert_eq!(BlockId::Earliest, BlockNumber::Earliest.into()); assert_eq!(BlockID::Earliest, BlockNumber::Earliest.into());
assert_eq!(BlockId::Latest, BlockNumber::Latest.into()); assert_eq!(BlockID::Latest, BlockNumber::Latest.into());
assert_eq!(BlockId::Latest, BlockNumber::Pending.into()); assert_eq!(BlockID::Latest, BlockNumber::Pending.into());
} }
} }

View File

@ -20,7 +20,7 @@ use jsonrpc_core::Value;
use util::numbers::*; use util::numbers::*;
use v1::types::BlockNumber; use v1::types::BlockNumber;
use ethcore::filter::Filter as EthFilter; use ethcore::filter::Filter as EthFilter;
use ethcore::client::BlockId; use ethcore::client::BlockID;
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
pub enum VariadicValue<T> where T: Deserialize { pub enum VariadicValue<T> where T: Deserialize {
@ -61,8 +61,8 @@ pub struct Filter {
impl Into<EthFilter> for Filter { impl Into<EthFilter> for Filter {
fn into(self) -> EthFilter { fn into(self) -> EthFilter {
EthFilter { EthFilter {
from_block: self.from_block.map_or_else(|| BlockId::Latest, Into::into), from_block: self.from_block.map_or_else(|| BlockID::Latest, Into::into),
to_block: self.to_block.map_or_else(|| BlockId::Latest, Into::into), to_block: self.to_block.map_or_else(|| BlockID::Latest, Into::into),
address: self.address.and_then(|address| match address { address: self.address.and_then(|address| match address {
VariadicValue::Null => None, VariadicValue::Null => None,
VariadicValue::Single(a) => Some(vec![a]), VariadicValue::Single(a) => Some(vec![a]),

View File

@ -17,7 +17,7 @@
//! Trace filter deserialization. //! Trace filter deserialization.
use util::Address; use util::Address;
use ethcore::client::BlockId; use ethcore::client::BlockID;
use ethcore::client; use ethcore::client;
use super::BlockNumber; use super::BlockNumber;
@ -35,8 +35,8 @@ pub struct TraceFilter {
impl Into<client::TraceFilter> for TraceFilter { impl Into<client::TraceFilter> for TraceFilter {
fn into(self) -> client::TraceFilter { fn into(self) -> client::TraceFilter {
let start = self.from_block.map_or(BlockId::Latest, Into::into); let start = self.from_block.map_or(BlockID::Latest, Into::into);
let end = self.to_block.map_or(BlockId::Latest, Into::into); let end = self.to_block.map_or(BlockID::Latest, Into::into);
client::TraceFilter { client::TraceFilter {
range: start..end, range: start..end,
from_address: self.from_address.unwrap_or_else(Vec::new), from_address: self.from_address.unwrap_or_else(Vec::new),

View File

@ -307,7 +307,7 @@ impl BlockCollection {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use super::BlockCollection; use super::BlockCollection;
use ethcore::client::{TestBlockChainClient, EachBlockWith, BlockId, BlockChainClient}; use ethcore::client::{TestBlockChainClient, EachBlockWith, BlockID, BlockChainClient};
use ethcore::views::HeaderView; use ethcore::views::HeaderView;
use ethcore::header::BlockNumber; use ethcore::header::BlockNumber;
use util::*; use util::*;
@ -328,7 +328,7 @@ mod test {
assert!(is_empty(&bc)); assert!(is_empty(&bc));
let client = TestBlockChainClient::new(); let client = TestBlockChainClient::new();
client.add_blocks(100, EachBlockWith::Nothing); client.add_blocks(100, EachBlockWith::Nothing);
let hashes = (0 .. 100).map(|i| (&client as &BlockChainClient).block_hash(BlockId::Number(i)).unwrap()).collect(); let hashes = (0 .. 100).map(|i| (&client as &BlockChainClient).block_hash(BlockID::Number(i)).unwrap()).collect();
bc.reset_to(hashes); bc.reset_to(hashes);
assert!(!is_empty(&bc)); assert!(!is_empty(&bc));
bc.clear(); bc.clear();
@ -342,7 +342,7 @@ mod test {
let client = TestBlockChainClient::new(); let client = TestBlockChainClient::new();
let nblocks = 200; let nblocks = 200;
client.add_blocks(nblocks, EachBlockWith::Nothing); client.add_blocks(nblocks, EachBlockWith::Nothing);
let blocks: Vec<_> = (0 .. nblocks).map(|i| (&client as &BlockChainClient).block(BlockId::Number(i as BlockNumber)).unwrap()).collect(); let blocks: Vec<_> = (0 .. nblocks).map(|i| (&client as &BlockChainClient).block(BlockID::Number(i as BlockNumber)).unwrap()).collect();
let headers: Vec<_> = blocks.iter().map(|b| Rlp::new(b).at(0).as_raw().to_vec()).collect(); let headers: Vec<_> = blocks.iter().map(|b| Rlp::new(b).at(0).as_raw().to_vec()).collect();
let hashes: Vec<_> = headers.iter().map(|h| HeaderView::new(h).sha3()).collect(); let hashes: Vec<_> = headers.iter().map(|h| HeaderView::new(h).sha3()).collect();
let heads: Vec<_> = hashes.iter().enumerate().filter_map(|(i, h)| if i % 20 == 0 { Some(h.clone()) } else { None }).collect(); let heads: Vec<_> = hashes.iter().enumerate().filter_map(|(i, h)| if i % 20 == 0 { Some(h.clone()) } else { None }).collect();
@ -395,7 +395,7 @@ mod test {
let client = TestBlockChainClient::new(); let client = TestBlockChainClient::new();
let nblocks = 200; let nblocks = 200;
client.add_blocks(nblocks, EachBlockWith::Nothing); client.add_blocks(nblocks, EachBlockWith::Nothing);
let blocks: Vec<_> = (0 .. nblocks).map(|i| (&client as &BlockChainClient).block(BlockId::Number(i as BlockNumber)).unwrap()).collect(); let blocks: Vec<_> = (0 .. nblocks).map(|i| (&client as &BlockChainClient).block(BlockID::Number(i as BlockNumber)).unwrap()).collect();
let headers: Vec<_> = blocks.iter().map(|b| Rlp::new(b).at(0).as_raw().to_vec()).collect(); let headers: Vec<_> = blocks.iter().map(|b| Rlp::new(b).at(0).as_raw().to_vec()).collect();
let hashes: Vec<_> = headers.iter().map(|h| HeaderView::new(h).sha3()).collect(); let hashes: Vec<_> = headers.iter().map(|h| HeaderView::new(h).sha3()).collect();
let heads: Vec<_> = hashes.iter().enumerate().filter_map(|(i, h)| if i % 20 == 0 { Some(h.clone()) } else { None }).collect(); let heads: Vec<_> = hashes.iter().enumerate().filter_map(|(i, h)| if i % 20 == 0 { Some(h.clone()) } else { None }).collect();

View File

@ -33,7 +33,7 @@ use util::*;
use std::mem::{replace}; use std::mem::{replace};
use ethcore::views::{HeaderView}; use ethcore::views::{HeaderView};
use ethcore::header::{BlockNumber, Header as BlockHeader}; use ethcore::header::{BlockNumber, Header as BlockHeader};
use ethcore::client::{BlockChainClient, BlockStatus, BlockId, BlockChainInfo}; use ethcore::client::{BlockChainClient, BlockStatus, BlockID, BlockChainInfo};
use range_collection::{RangeCollection, ToUsize, FromUsize}; use range_collection::{RangeCollection, ToUsize, FromUsize};
use ethcore::error::*; use ethcore::error::*;
use ethcore::transaction::SignedTransaction; use ethcore::transaction::SignedTransaction;
@ -377,7 +377,7 @@ impl ChainSync {
self.highest_block = Some(number); self.highest_block = Some(number);
} }
let hash = info.hash(); let hash = info.hash();
match io.chain().block_status(BlockId::Hash(hash.clone())) { match io.chain().block_status(BlockID::Hash(hash.clone())) {
BlockStatus::InChain | BlockStatus::Queued => { BlockStatus::InChain | BlockStatus::Queued => {
if !self.have_common_block || self.current_base_block() < number { if !self.have_common_block || self.current_base_block() < number {
self.last_imported_block = Some(number); self.last_imported_block = Some(number);
@ -572,7 +572,7 @@ impl ChainSync {
if self.downloading_hashes.contains(&h) { if self.downloading_hashes.contains(&h) {
continue; continue;
} }
match io.chain().block_status(BlockId::Hash(h.clone())) { match io.chain().block_status(BlockID::Hash(h.clone())) {
BlockStatus::InChain => { BlockStatus::InChain => {
trace!(target: "sync", "New block hash already in chain {:?}", h); trace!(target: "sync", "New block hash already in chain {:?}", h);
}, },
@ -670,7 +670,7 @@ impl ChainSync {
self.downloading_hashes.insert(peer_latest.clone()); self.downloading_hashes.insert(peer_latest.clone());
self.request_headers_by_hash(io, peer_id, &peer_latest, 1, 0, false); self.request_headers_by_hash(io, peer_id, &peer_latest, 1, 0, false);
} }
else if self.state == SyncState::Blocks && io.chain().block_status(BlockId::Hash(peer_latest)) == BlockStatus::Unknown { else if self.state == SyncState::Blocks && io.chain().block_status(BlockID::Hash(peer_latest)) == BlockStatus::Unknown {
self.request_blocks(io, peer_id, false); self.request_blocks(io, peer_id, false);
} }
} }
@ -1002,7 +1002,7 @@ impl ChainSync {
// id is a hash // id is a hash
let hash: H256 = try!(r.val_at(0)); let hash: H256 = try!(r.val_at(0));
trace!(target: "sync", "-> GetBlockHeaders (hash: {}, max: {}, skip: {}, reverse:{})", hash, max_headers, skip, reverse); trace!(target: "sync", "-> GetBlockHeaders (hash: {}, max: {}, skip: {}, reverse:{})", hash, max_headers, skip, reverse);
match io.chain().block_header(BlockId::Hash(hash)) { match io.chain().block_header(BlockID::Hash(hash)) {
Some(hdr) => From::from(HeaderView::new(&hdr).number()), Some(hdr) => From::from(HeaderView::new(&hdr).number()),
None => last None => last
} }
@ -1022,7 +1022,7 @@ impl ChainSync {
let mut data = Bytes::new(); let mut data = Bytes::new();
let inc = (skip + 1) as BlockNumber; let inc = (skip + 1) as BlockNumber;
while number <= last && count < max_count { while number <= last && count < max_count {
if let Some(mut hdr) = io.chain().block_header(BlockId::Number(number)) { if let Some(mut hdr) = io.chain().block_header(BlockID::Number(number)) {
data.append(&mut hdr); data.append(&mut hdr);
count += 1; count += 1;
} }
@ -1054,7 +1054,7 @@ impl ChainSync {
let mut added = 0usize; let mut added = 0usize;
let mut data = Bytes::new(); let mut data = Bytes::new();
for i in 0..count { for i in 0..count {
if let Some(mut hdr) = io.chain().block_body(BlockId::Hash(try!(r.val_at::<H256>(i)))) { if let Some(mut hdr) = io.chain().block_body(BlockID::Hash(try!(r.val_at::<H256>(i)))) {
data.append(&mut hdr); data.append(&mut hdr);
added += 1; added += 1;
} }
@ -1193,7 +1193,7 @@ impl ChainSync {
let mut rlp_stream = RlpStream::new_list(route.blocks.len()); let mut rlp_stream = RlpStream::new_list(route.blocks.len());
for block_hash in route.blocks { for block_hash in route.blocks {
let mut hash_rlp = RlpStream::new_list(2); let mut hash_rlp = RlpStream::new_list(2);
let difficulty = chain.block_total_difficulty(BlockId::Hash(block_hash.clone())).expect("Malformed block without a difficulty on the chain!"); let difficulty = chain.block_total_difficulty(BlockID::Hash(block_hash.clone())).expect("Malformed block without a difficulty on the chain!");
hash_rlp.append(&block_hash); hash_rlp.append(&block_hash);
hash_rlp.append(&difficulty); hash_rlp.append(&difficulty);
rlp_stream.append_raw(&hash_rlp.out(), 1); rlp_stream.append_raw(&hash_rlp.out(), 1);
@ -1209,7 +1209,7 @@ impl ChainSync {
/// creates latest block rlp for the given client /// creates latest block rlp for the given client
fn create_latest_block_rlp(chain: &BlockChainClient) -> Bytes { fn create_latest_block_rlp(chain: &BlockChainClient) -> Bytes {
let mut rlp_stream = RlpStream::new_list(2); let mut rlp_stream = RlpStream::new_list(2);
rlp_stream.append_raw(&chain.block(BlockId::Hash(chain.chain_info().best_block_hash)).unwrap(), 1); rlp_stream.append_raw(&chain.block(BlockID::Hash(chain.chain_info().best_block_hash)).unwrap(), 1);
rlp_stream.append(&chain.chain_info().total_difficulty); rlp_stream.append(&chain.chain_info().total_difficulty);
rlp_stream.out() rlp_stream.out()
} }
@ -1219,10 +1219,10 @@ impl ChainSync {
let latest_hash = chain_info.best_block_hash; let latest_hash = chain_info.best_block_hash;
let latest_number = chain_info.best_block_number; let latest_number = chain_info.best_block_number;
self.peers.iter_mut().filter_map(|(&id, ref mut peer_info)| self.peers.iter_mut().filter_map(|(&id, ref mut peer_info)|
match io.chain().block_status(BlockId::Hash(peer_info.latest_hash.clone())) { match io.chain().block_status(BlockID::Hash(peer_info.latest_hash.clone())) {
BlockStatus::InChain => { BlockStatus::InChain => {
if peer_info.latest_number.is_none() { if peer_info.latest_number.is_none() {
peer_info.latest_number = Some(HeaderView::new(&io.chain().block_header(BlockId::Hash(peer_info.latest_hash.clone())).unwrap()).number()); peer_info.latest_number = Some(HeaderView::new(&io.chain().block_header(BlockID::Hash(peer_info.latest_hash.clone())).unwrap()).number());
} }
if peer_info.latest_hash != latest_hash && latest_number > peer_info.latest_number.unwrap() { if peer_info.latest_hash != latest_hash && latest_number > peer_info.latest_number.unwrap() {
Some((id, peer_info.latest_number.unwrap())) Some((id, peer_info.latest_number.unwrap()))
@ -1264,7 +1264,7 @@ impl ChainSync {
fn propagate_new_hashes(&mut self, chain_info: &BlockChainInfo, io: &mut SyncIo) -> usize { fn propagate_new_hashes(&mut self, chain_info: &BlockChainInfo, io: &mut SyncIo) -> usize {
let updated_peers = self.get_lagging_peers(chain_info, io); let updated_peers = self.get_lagging_peers(chain_info, io);
let mut sent = 0; let mut sent = 0;
let last_parent = HeaderView::new(&io.chain().block_header(BlockId::Hash(chain_info.best_block_hash.clone())).unwrap()).parent_hash(); let last_parent = HeaderView::new(&io.chain().block_header(BlockID::Hash(chain_info.best_block_hash.clone())).unwrap()).parent_hash();
for (peer_id, peer_number) in updated_peers { for (peer_id, peer_number) in updated_peers {
let mut peer_best = self.peers.get(&peer_id).unwrap().latest_hash.clone(); let mut peer_best = self.peers.get(&peer_id).unwrap().latest_hash.clone();
if chain_info.best_block_number - peer_number > MAX_PEERS_PROPAGATION as BlockNumber { if chain_info.best_block_number - peer_number > MAX_PEERS_PROPAGATION as BlockNumber {
@ -1704,7 +1704,7 @@ mod tests {
// Add some balance to clients and reset nonces // Add some balance to clients and reset nonces
for h in &[good_blocks[0], retracted_blocks[0]] { for h in &[good_blocks[0], retracted_blocks[0]] {
let block = client.block(BlockId::Hash(*h)).unwrap(); let block = client.block(BlockID::Hash(*h)).unwrap();
let view = BlockView::new(&block); let view = BlockView::new(&block);
client.set_balance(view.transactions()[0].sender().unwrap(), U256::from(1_000_000_000)); client.set_balance(view.transactions()[0].sender().unwrap(), U256::from(1_000_000_000));
client.set_nonce(view.transactions()[0].sender().unwrap(), U256::from(0)); client.set_nonce(view.transactions()[0].sender().unwrap(), U256::from(0));
@ -1721,7 +1721,7 @@ mod tests {
} }
// We need to update nonce status (because we say that the block has been imported) // We need to update nonce status (because we say that the block has been imported)
for h in &[good_blocks[0]] { for h in &[good_blocks[0]] {
let block = client.block(BlockId::Hash(*h)).unwrap(); let block = client.block(BlockID::Hash(*h)).unwrap();
let view = BlockView::new(&block); let view = BlockView::new(&block);
client.set_nonce(view.transactions()[0].sender().unwrap(), U256::from(1)); client.set_nonce(view.transactions()[0].sender().unwrap(), U256::from(1));
} }

View File

@ -15,7 +15,7 @@
// along with Parity. If not, see <http://www.gnu.org/licenses/>. // along with Parity. If not, see <http://www.gnu.org/licenses/>.
use util::*; use util::*;
use ethcore::client::{BlockChainClient, BlockId, EachBlockWith}; use ethcore::client::{BlockChainClient, BlockID, EachBlockWith};
use chain::{SyncState}; use chain::{SyncState};
use super::helpers::*; use super::helpers::*;
@ -26,7 +26,7 @@ fn two_peers() {
net.peer_mut(1).chain.add_blocks(1000, EachBlockWith::Uncle); net.peer_mut(1).chain.add_blocks(1000, EachBlockWith::Uncle);
net.peer_mut(2).chain.add_blocks(1000, EachBlockWith::Uncle); net.peer_mut(2).chain.add_blocks(1000, EachBlockWith::Uncle);
net.sync(); net.sync();
assert!(net.peer(0).chain.block(BlockId::Number(1000)).is_some()); assert!(net.peer(0).chain.block(BlockID::Number(1000)).is_some());
assert_eq!(net.peer(0).chain.blocks.read().unwrap().deref(), net.peer(1).chain.blocks.read().unwrap().deref()); assert_eq!(net.peer(0).chain.blocks.read().unwrap().deref(), net.peer(1).chain.blocks.read().unwrap().deref());
} }
@ -60,7 +60,7 @@ fn empty_blocks() {
net.peer_mut(2).chain.add_blocks(5, with); net.peer_mut(2).chain.add_blocks(5, with);
} }
net.sync(); net.sync();
assert!(net.peer(0).chain.block(BlockId::Number(1000)).is_some()); assert!(net.peer(0).chain.block(BlockID::Number(1000)).is_some());
assert_eq!(net.peer(0).chain.blocks.read().unwrap().deref(), net.peer(1).chain.blocks.read().unwrap().deref()); assert_eq!(net.peer(0).chain.blocks.read().unwrap().deref(), net.peer(1).chain.blocks.read().unwrap().deref());
} }