Merge branch 'master' of github.com:ethcore/parity into io

This commit is contained in:
arkpar
2016-01-22 14:44:17 +01:00
58 changed files with 395 additions and 434 deletions

View File

@@ -103,7 +103,7 @@ impl Account {
/// Get (and cache) the contents of the trie's storage at `key`.
pub fn storage_at(&self, db: &HashDB, key: &H256) -> H256 {
self.storage_overlay.borrow_mut().entry(key.clone()).or_insert_with(||{
(Filth::Clean, H256::from(SecTrieDB::new(db, &self.storage_root).get(key.bytes()).map(|v| -> U256 {decode(v)}).unwrap_or(U256::zero())))
(Filth::Clean, H256::from(SecTrieDB::new(db, &self.storage_root).get(key.bytes()).map_or(U256::zero(), |v| -> U256 {decode(v)})))
}).1.clone()
}
@@ -149,7 +149,7 @@ impl Account {
/// Provide a database to lookup `code_hash`. Should not be called if it is a contract without code.
pub fn cache_code(&mut self, db: &HashDB) -> bool {
// TODO: fill out self.code_cache;
return self.is_cached() ||
self.is_cached() ||
match self.code_hash {
Some(ref h) => match db.lookup(h) {
Some(x) => { self.code_cache = x.to_vec(); true },
@@ -248,8 +248,8 @@ mod tests {
let a = Account::from_rlp(&rlp);
assert_eq!(a.storage_root().unwrap().hex(), "c57e1afb758b07f8d2c8f13a3b6e44fa5ff94ab266facc5a4fd3f062426e50b2");
assert_eq!(a.storage_at(&mut db, &H256::from(&U256::from(0x00u64))), H256::from(&U256::from(0x1234u64)));
assert_eq!(a.storage_at(&mut db, &H256::from(&U256::from(0x01u64))), H256::new());
assert_eq!(a.storage_at(&db, &H256::from(&U256::from(0x00u64))), H256::from(&U256::from(0x1234u64)));
assert_eq!(a.storage_at(&db, &H256::from(&U256::from(0x01u64))), H256::new());
}
#[test]

View File

@@ -15,10 +15,10 @@ pub enum Existance {
impl fmt::Display for Existance {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&Existance::Born => try!(write!(f, "+++")),
&Existance::Alive => try!(write!(f, "***")),
&Existance::Died => try!(write!(f, "XXX")),
match *self {
Existance::Born => try!(write!(f, "+++")),
Existance::Alive => try!(write!(f, "***")),
Existance::Died => try!(write!(f, "XXX")),
}
Ok(())
}
@@ -72,11 +72,11 @@ impl AccountDiff {
code: Diff::new(pre.code.clone(), post.code.clone()),
storage: storage.into_iter().map(|k|
(k.clone(), Diff::new(
pre.storage.get(&k).cloned().unwrap_or(H256::new()),
post.storage.get(&k).cloned().unwrap_or(H256::new())
pre.storage.get(&k).cloned().unwrap_or_else(H256::new),
post.storage.get(&k).cloned().unwrap_or_else(H256::new)
))).collect(),
};
if r.balance.is_same() && r.nonce.is_same() && r.code.is_same() && r.storage.len() == 0 {
if r.balance.is_same() && r.nonce.is_same() && r.code.is_same() && r.storage.is_empty() {
None
} else {
Some(r)
@@ -112,16 +112,15 @@ impl fmt::Display for AccountDiff {
Diff::Changed(ref pre, ref post) => try!(write!(f, "${} ({} {} {})", post, pre, if pre > post {"-"} else {"+"}, *max(pre, post) - *min(pre, post))),
_ => {},
}
match self.code {
Diff::Born(ref x) => try!(write!(f, " code {}", x.pretty())),
_ => {},
if let Diff::Born(ref x) = self.code {
try!(write!(f, " code {}", x.pretty()));
}
try!(write!(f, "\n"));
for (k, dv) in self.storage.iter() {
match dv {
&Diff::Born(ref v) => try!(write!(f, " + {} => {}\n", interpreted_hash(k), interpreted_hash(v))),
&Diff::Changed(ref pre, ref post) => try!(write!(f, " * {} => {} (was {})\n", interpreted_hash(k), interpreted_hash(post), interpreted_hash(pre))),
&Diff::Died(_) => try!(write!(f, " X {}\n", interpreted_hash(k))),
for (k, dv) in &self.storage {
match *dv {
Diff::Born(ref v) => try!(write!(f, " + {} => {}\n", interpreted_hash(k), interpreted_hash(v))),
Diff::Changed(ref pre, ref post) => try!(write!(f, " * {} => {} (was {})\n", interpreted_hash(k), interpreted_hash(post), interpreted_hash(pre))),
Diff::Died(_) => try!(write!(f, " X {}\n", interpreted_hash(k))),
_ => {},
}
}

View File

@@ -1,3 +1,5 @@
#![allow(ptr_arg)] // Because of &LastHashes -> &Vec<_>
use common::*;
use engine::*;
use state::*;
@@ -173,7 +175,7 @@ impl<'x, 'y> OpenBlock<'x, 'y> {
timestamp: self.block.header.timestamp,
difficulty: self.block.header.difficulty.clone(),
last_hashes: self.last_hashes.clone(), // TODO: should be a reference.
gas_used: self.block.archive.last().map(|t| t.receipt.gas_used).unwrap_or(U256::from(0)),
gas_used: self.block.archive.last().map_or(U256::zero(), |t| t.receipt.gas_used),
gas_limit: self.block.header.gas_limit.clone(),
}
}
@@ -204,7 +206,7 @@ impl<'x, 'y> OpenBlock<'x, 'y> {
s.block.header.state_root = s.block.state.root().clone();
s.block.header.receipts_root = ordered_trie_root(s.block.archive.iter().map(|ref e| e.receipt.rlp_bytes()).collect());
s.block.header.log_bloom = s.block.archive.iter().fold(LogBloom::zero(), |mut b, e| {b |= &e.receipt.log_bloom; b});
s.block.header.gas_used = s.block.archive.last().map(|t| t.receipt.gas_used).unwrap_or(U256::from(0));
s.block.header.gas_used = s.block.archive.last().map_or(U256::zero(), |t| t.receipt.gas_used);
s.block.header.note_dirty();
ClosedBlock::new(s, uncle_bytes)
@@ -255,7 +257,7 @@ impl SealedBlock {
let mut block_rlp = RlpStream::new_list(3);
self.block.header.stream_rlp(&mut block_rlp, Seal::With);
block_rlp.append_list(self.block.archive.len());
for e in self.block.archive.iter() { e.transaction.rlp_append(&mut block_rlp); }
for e in &self.block.archive { e.transaction.rlp_append(&mut block_rlp); }
block_rlp.append_raw(&self.uncle_bytes, 1);
block_rlp.out()
}

View File

@@ -153,9 +153,8 @@ impl BlockProvider for BlockChain {
fn block(&self, hash: &H256) -> Option<Bytes> {
{
let read = self.blocks.read().unwrap();
match read.get(hash) {
Some(v) => return Some(v.clone()),
None => ()
if let Some(v) = read.get(hash) {
return Some(v.clone());
}
}
@@ -188,7 +187,7 @@ impl BlockProvider for BlockChain {
const COLLECTION_QUEUE_SIZE: usize = 2;
const MIN_CACHE_SIZE: usize = 1;
const MAX_CACHE_SIZE: usize = 1024 * 1024 * 1;
const MAX_CACHE_SIZE: usize = 1024 * 1024;
impl BlockChain {
/// Create new instance of blockchain from given Genesis
@@ -529,9 +528,8 @@ impl BlockChain {
K: ExtrasSliceConvertable + Eq + Hash + Clone {
{
let read = cache.read().unwrap();
match read.get(hash) {
Some(v) => return Some(v.clone()),
None => ()
if let Some(v) = read.get(hash) {
return Some(v.clone());
}
}
@@ -551,9 +549,8 @@ impl BlockChain {
T: ExtrasIndexable {
{
let read = cache.read().unwrap();
match read.get(hash) {
Some(_) => return true,
None => ()
if let Some(_) = read.get(hash) {
return true;
}
}
@@ -672,6 +669,7 @@ mod tests {
}
#[test]
#[allow(cyclomatic_complexity)]
fn test_small_fork() {
let genesis = "f901fcf901f7a00000000000000000000000000000000000000000000000000000000000000000a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347948888f1f195afa192cfee860698584c030f4c9db1a07dba07d6b448a186e9612e5f737d1c909dce473e53199901a302c00646d523c1a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008302000080832fefd8808454c98c8142a059262c330941f3fe2a34d16d6e3c7b30d2ceb37c6a0e9a994c494ee1a61d2410885aa4c8bf8e56e264c0c0".from_hex().unwrap();
let b1 = "f90261f901f9a05716670833ec874362d65fea27a7cd35af5897d275b31a44944113111e4e96d2a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347948888f1f195afa192cfee860698584c030f4c9db1a0cb52de543653d86ccd13ba3ddf8b052525b04231c6884a4db3188a184681d878a0e78628dd45a1f8dc495594d83b76c588a3ee67463260f8b7d4a42f574aeab29aa0e9244cf7503b79c03d3a099e07a80d2dbc77bb0b502d8a89d51ac0d68dd31313b90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008302000001832fefd882520884562791e580a051b3ecba4e3f2b49c11d42dd0851ec514b1be3138080f72a2b6e83868275d98f8877671f479c414b47f862f86080018304cb2f94095e7baea6a6c7c4c2dfeb977efac326af552d870a801ca09e2709d7ec9bbe6b1bbbf0b2088828d14cd5e8642a1fee22dc74bfa89761a7f9a04bd8813dee4be989accdb708b1c2e325a7e9c695a8024e30e89d6c644e424747c0".from_hex().unwrap();

View File

@@ -94,16 +94,13 @@ pub fn new_builtin_exec(name: &str) -> Option<Box<Fn(&[u8], &mut [u8])>> {
if it.v == H256::from(&U256::from(27)) || it.v == H256::from(&U256::from(28)) {
let s = Signature::from_rsv(&it.r, &it.s, it.v[31] - 27);
if ec::is_valid(&s) {
match ec::recover(&s, &it.hash) {
Ok(p) => {
let r = p.as_slice().sha3();
// NICE: optimise and separate out into populate-like function
for i in 0..min(32, output.len()) {
output[i] = if i < 12 {0} else {r[i]};
}
if let Ok(p) = ec::recover(&s, &it.hash) {
let r = p.as_slice().sha3();
// NICE: optimise and separate out into populate-like function
for i in 0..min(32, output.len()) {
output[i] = if i < 12 {0} else {r[i]};
}
_ => {}
};
}
}
}
})),

View File

@@ -25,8 +25,14 @@ pub struct EnvInfo {
}
impl EnvInfo {
/// TODO [debris] Please document me
/// Create empty env_info initialized with zeros
pub fn new() -> EnvInfo {
EnvInfo::default()
}
}
impl Default for EnvInfo {
fn default() -> Self {
EnvInfo {
number: 0,
author: Address::new(),
@@ -53,11 +59,3 @@ impl FromJson for EnvInfo {
}
}
}
/// TODO: it should be the other way around.
/// `new` should call `default`.
impl Default for EnvInfo {
fn default() -> Self {
EnvInfo::new()
}
}

View File

@@ -32,13 +32,13 @@ impl Ethash {
}
fn u64_param(&self, name: &str) -> u64 {
*self.u64_params.write().unwrap().entry(name.to_string()).or_insert_with(||
self.spec().engine_params.get(name).map(|a| decode(&a)).unwrap_or(0u64))
*self.u64_params.write().unwrap().entry(name.to_owned()).or_insert_with(||
self.spec().engine_params.get(name).map_or(0u64, |a| decode(&a)))
}
fn u256_param(&self, name: &str) -> U256 {
*self.u256_params.write().unwrap().entry(name.to_string()).or_insert_with(||
self.spec().engine_params.get(name).map(|a| decode(&a)).unwrap_or(x!(0)))
*self.u256_params.write().unwrap().entry(name.to_owned()).or_insert_with(||
self.spec().engine_params.get(name).map_or(x!(0), |a| decode(&a)))
}
}
@@ -84,7 +84,7 @@ impl Engine for Ethash {
/// Apply the block reward on finalisation of the block.
/// This assumes that all uncles are valid uncles (i.e. of at least one generation before the current).
fn on_close_block(&self, block: &mut Block) {
let reward = self.spec().engine_params.get("blockReward").map(|a| decode(&a)).unwrap_or(U256::from(0u64));
let reward = self.spec().engine_params.get("blockReward").map_or(U256::from(0u64), |a| decode(&a));
let fields = block.fields();
// Bestow block reward
@@ -153,6 +153,7 @@ impl Engine for Ethash {
}
}
#[allow(wrong_self_convention)] // to_ethash should take self
impl Ethash {
fn calculate_difficuty(&self, header: &Header, parent: &Header) -> U256 {
const EXP_DIFF_PERIOD: u64 = 100000;

View File

@@ -68,10 +68,11 @@ impl Factory {
fn jit() -> Box<Evm> {
unimplemented!()
}
}
impl Default for Factory {
/// Returns jitvm factory
#[cfg(feature = "jit")]
pub fn default() -> Factory {
fn default() -> Factory {
Factory {
evm: VMType::Jit
}
@@ -79,7 +80,7 @@ impl Factory {
/// Returns native rust evm factory
#[cfg(not(feature = "jit"))]
pub fn default() -> Factory {
fn default() -> Factory {
Factory {
evm: VMType::Interpreter
}

View File

@@ -72,7 +72,7 @@ impl<S : Copy> VecStack<S> {
impl<S : fmt::Display> Stack<S> for VecStack<S> {
fn peek(&self, no_from_top: usize) -> &S {
return &self.stack[self.stack.len() - no_from_top - 1];
&self.stack[self.stack.len() - no_from_top - 1]
}
fn swap_with_top(&mut self, no_from_top: usize) {
@@ -157,7 +157,7 @@ impl Memory for Vec<u8> {
}
fn size(&self) -> usize {
return self.len()
self.len()
}
fn read_slice(&self, init_off_u: U256, init_size_u: U256) -> &[u8] {
@@ -228,6 +228,7 @@ struct CodeReader<'a> {
code: &'a Bytes
}
#[allow(len_without_is_empty)]
impl<'a> CodeReader<'a> {
/// Get `no_of_bytes` from code and convert to U256. Move PC
fn read(&mut self, no_of_bytes: usize) -> U256 {
@@ -330,6 +331,7 @@ impl evm::Evm for Interpreter {
}
impl Interpreter {
#[allow(cyclomatic_complexity)]
fn get_gas_cost_mem(&self,
ext: &evm::Ext,
instruction: Instruction,
@@ -716,7 +718,7 @@ impl Interpreter {
let big_id = stack.pop_back();
let id = big_id.low_u64() as usize;
let max = id.wrapping_add(32);
let data = params.data.clone().unwrap_or(vec![]);
let data = params.data.clone().unwrap_or_else(|| vec![]);
let bound = cmp::min(data.len(), max);
if id < bound && big_id < U256::from(data.len()) {
let mut v = data[id..bound].to_vec();
@@ -727,7 +729,7 @@ impl Interpreter {
}
},
instructions::CALLDATASIZE => {
stack.push(U256::from(params.data.clone().unwrap_or(vec![]).len()));
stack.push(U256::from(params.data.clone().map_or(0, |l| l.len())));
},
instructions::CODESIZE => {
stack.push(U256::from(code.len()));
@@ -738,10 +740,10 @@ impl Interpreter {
stack.push(U256::from(len));
},
instructions::CALLDATACOPY => {
self.copy_data_to_memory(mem, stack, &params.data.clone().unwrap_or(vec![]));
self.copy_data_to_memory(mem, stack, &params.data.clone().unwrap_or_else(|| vec![]));
},
instructions::CODECOPY => {
self.copy_data_to_memory(mem, stack, &params.code.clone().unwrap_or(vec![]));
self.copy_data_to_memory(mem, stack, &params.code.clone().unwrap_or_else(|| vec![]));
},
instructions::EXTCODECOPY => {
let address = u256_to_address(&stack.pop_back());
@@ -781,7 +783,7 @@ impl Interpreter {
fn copy_data_to_memory(&self,
mem: &mut Memory,
stack: &mut Stack<U256>,
data: &Bytes) {
data: &[u8]) {
let offset = stack.pop_back();
let index = stack.pop_back();
let size = stack.pop_back();
@@ -1051,7 +1053,7 @@ impl Interpreter {
Ok(())
}
fn find_jump_destinations(&self, code: &Bytes) -> HashSet<CodePosition> {
fn find_jump_destinations(&self, code: &[u8]) -> HashSet<CodePosition> {
let mut jump_dests = HashSet::new();
let mut position = 0;
@@ -1066,7 +1068,7 @@ impl Interpreter {
position += 1;
}
return jump_dests;
jump_dests
}
}

View File

@@ -19,7 +19,7 @@ struct FakeExt {
logs: Vec<FakeLogEntry>,
_suicides: HashSet<Address>,
info: EnvInfo,
_schedule: Schedule
schedule: Schedule
}
impl FakeExt {
@@ -89,7 +89,7 @@ impl Ext for FakeExt {
}
fn schedule(&self) -> &Schedule {
&self._schedule
&self.schedule
}
fn env_info(&self) -> &EnvInfo {
@@ -122,7 +122,7 @@ fn test_stack_underflow() {
};
match err {
evm::Error::StackUnderflow {instruction: _, wanted, on_stack} => {
evm::Error::StackUnderflow {wanted, on_stack, ..} => {
assert_eq!(wanted, 2);
assert_eq!(on_stack, 0);
}

View File

@@ -75,7 +75,7 @@ impl<'a> Executive<'a> {
}
/// Creates `Externalities` from `Executive`.
pub fn to_externalities<'_>(&'_ mut self, origin_info: OriginInfo, substate: &'_ mut Substate, output: OutputPolicy<'_>) -> Externalities {
pub fn as_externalities<'_>(&'_ mut self, origin_info: OriginInfo, substate: &'_ mut Substate, output: OutputPolicy<'_>) -> Externalities {
Externalities::new(self.state, self.info, self.engine, self.depth, origin_info, substate, output)
}
@@ -123,8 +123,8 @@ impl<'a> Executive<'a> {
let mut substate = Substate::new();
let res = match t.action() {
&Action::Create => {
let res = match *t.action() {
Action::Create => {
let new_address = contract_address(&sender, &nonce);
let params = ActionParams {
code_address: new_address.clone(),
@@ -139,7 +139,7 @@ impl<'a> Executive<'a> {
};
self.create(params, &mut substate)
},
&Action::Call(ref address) => {
Action::Call(ref address) => {
let params = ActionParams {
code_address: address.clone(),
address: address.clone(),
@@ -177,7 +177,7 @@ impl<'a> Executive<'a> {
// if destination is builtin, try to execute it
let default = [];
let data = if let &Some(ref d) = &params.data { d as &[u8] } else { &default as &[u8] };
let data = if let Some(ref d) = params.data { d as &[u8] } else { &default as &[u8] };
let cost = self.engine.cost_of_builtin(&params.code_address, data);
match cost <= params.gas {
@@ -198,7 +198,7 @@ impl<'a> Executive<'a> {
let mut unconfirmed_substate = Substate::new();
let res = {
let mut ext = self.to_externalities(OriginInfo::from(&params), &mut unconfirmed_substate, OutputPolicy::Return(output));
let mut ext = self.as_externalities(OriginInfo::from(&params), &mut unconfirmed_substate, OutputPolicy::Return(output));
self.engine.vm_factory().create().exec(params, &mut ext)
};
@@ -230,7 +230,7 @@ impl<'a> Executive<'a> {
self.state.transfer_balance(&params.sender, &params.address, &params.value);
let res = {
let mut ext = self.to_externalities(OriginInfo::from(&params), &mut unconfirmed_substate, OutputPolicy::InitContract);
let mut ext = self.as_externalities(OriginInfo::from(&params), &mut unconfirmed_substate, OutputPolicy::InitContract);
self.engine.vm_factory().create().exec(params, &mut ext)
};
self.enact_result(&res, substate, unconfirmed_substate, backup);
@@ -248,7 +248,7 @@ impl<'a> Executive<'a> {
let refunds_bound = sstore_refunds + suicide_refunds;
// real ammount to refund
let gas_left_prerefund = match &result { &Ok(x) => x, _ => x!(0) };
let gas_left_prerefund = match result { Ok(x) => x, _ => x!(0) };
let refunded = cmp::min(refunds_bound, (t.gas - gas_left_prerefund) / U256::from(2));
let gas_left = gas_left_prerefund + refunded;
@@ -265,7 +265,7 @@ impl<'a> Executive<'a> {
self.state.add_balance(&self.info.author, &fees_value);
// perform suicides
for address in substate.suicides.iter() {
for address in &substate.suicides {
trace!("Killing {}", address);
self.state.kill_account(address);
}
@@ -273,11 +273,7 @@ impl<'a> Executive<'a> {
match result {
Err(evm::Error::Internal) => Err(ExecutionError::Internal),
// TODO [ToDr] BadJumpDestination @debris - how to handle that?
Err(evm::Error::OutOfGas)
| Err(evm::Error::BadJumpDestination { destination: _ })
| Err(evm::Error::BadInstruction { instruction: _ })
| Err(evm::Error::StackUnderflow {instruction: _, wanted: _, on_stack: _})
| Err(evm::Error::OutOfStack {instruction: _, wanted: _, limit: _}) => {
Err(_) => {
Ok(Executed {
gas: t.gas,
gas_used: t.gas,
@@ -302,15 +298,15 @@ impl<'a> Executive<'a> {
fn enact_result(&mut self, result: &evm::Result, substate: &mut Substate, un_substate: Substate, backup: State) {
// TODO: handle other evm::Errors same as OutOfGas once they are implemented
match result {
&Err(evm::Error::OutOfGas)
| &Err(evm::Error::BadJumpDestination { destination: _ })
| &Err(evm::Error::BadInstruction { instruction: _ })
| &Err(evm::Error::StackUnderflow {instruction: _, wanted: _, on_stack: _})
| &Err(evm::Error::OutOfStack {instruction: _, wanted: _, limit: _}) => {
match *result {
Err(evm::Error::OutOfGas)
| Err(evm::Error::BadJumpDestination {..})
| Err(evm::Error::BadInstruction {.. })
| Err(evm::Error::StackUnderflow {..})
| Err(evm::Error::OutOfStack {..}) => {
self.state.revert(backup);
},
&Ok(_) | &Err(evm::Error::Internal) => substate.accrue(un_substate)
Ok(_) | Err(evm::Error::Internal) => substate.accrue(un_substate)
}
}
}

View File

@@ -158,9 +158,10 @@ impl<'a> Ext for Externalities<'a> {
}
fn extcode(&self, address: &Address) -> Bytes {
self.state.code(address).unwrap_or(vec![])
self.state.code(address).unwrap_or_else(|| vec![])
}
#[allow(match_ref_pats)]
fn ret(&mut self, gas: &U256, data: &[u8]) -> Result<U256, evm::Error> {
match &mut self.output {
&mut OutputPolicy::Return(BytesRef::Fixed(ref mut slice)) => unsafe {

View File

@@ -2,7 +2,7 @@ use util::*;
use basic_types::*;
use time::now_utc;
/// TODO [Gav Wood] Please document me
/// Type for Block number
pub type BlockNumber = u64;
/// A block header.
@@ -171,9 +171,10 @@ impl Header {
s.append(&self.gas_used);
s.append(&self.timestamp);
s.append(&self.extra_data);
match with_seal {
Seal::With => for b in self.seal.iter() { s.append_raw(&b, 1); },
_ => {}
if let Seal::With = with_seal {
for b in &self.seal {
s.append_raw(&b, 1);
}
}
}
@@ -236,7 +237,7 @@ impl Encodable for Header {
self.timestamp.encode(e);
self.extra_data.encode(e);
for b in self.seal.iter() {
for b in &self.seal {
e.emit_raw(&b);
}
})

View File

@@ -1,8 +1,11 @@
#![warn(missing_docs)]
#![feature(cell_extras)]
#![feature(augmented_assignments)]
//#![feature(plugin)]
#![feature(plugin)]
//#![plugin(interpolate_idents)]
#![plugin(clippy)]
#![allow(needless_range_loop, match_bool)]
//! Ethcore's ethereum implementation
//!
//! ### Rust version
@@ -73,7 +76,6 @@
//! sudo make install
//! sudo ldconfig
//! ```
#[macro_use]
extern crate log;
extern crate rustc_serialize;

View File

@@ -26,10 +26,10 @@ impl FromJson for PodState {
let code = acc.find("code").map(&Bytes::from_json);
if balance.is_some() || nonce.is_some() || storage.is_some() || code.is_some() {
state.insert(address_from_hex(address), PodAccount{
balance: balance.unwrap_or(U256::zero()),
nonce: nonce.unwrap_or(U256::zero()),
storage: storage.unwrap_or(BTreeMap::new()),
code: code.unwrap_or(Vec::new())
balance: balance.unwrap_or_else(U256::zero),
nonce: nonce.unwrap_or_else(U256::zero),
storage: storage.unwrap_or_else(BTreeMap::new),
code: code.unwrap_or_else(Vec::new)
});
}
state

View File

@@ -36,7 +36,7 @@ impl RlpStandard for Receipt {
// TODO: make work:
//s.append(&self.logs);
s.append_list(self.logs.len());
for l in self.logs.iter() {
for l in &self.logs {
l.rlp_append(s);
}
}

View File

@@ -83,20 +83,17 @@ impl IoHandler<NetSyncMessage> for ClientIoHandler {
}
}
#[allow(match_ref_pats)]
#[allow(single_match)]
fn message(&self, io: &IoContext<NetSyncMessage>, net_message: &NetSyncMessage) {
match net_message {
&UserMessage(ref message) => {
match message {
&SyncMessage::BlockVerified => {
self.client.import_verified_blocks(&io.channel());
},
_ => {}, // ignore other messages
}
if let &UserMessage(ref message) = net_message {
match message {
&SyncMessage::BlockVerified => {
self.client.import_verified_blocks(&io.channel());
},
_ => {}, // ignore other messages
}
_ => {}, // ignore other messages
}
}
}

View File

@@ -10,7 +10,7 @@ pub fn gzip64res_to_json(source: &[u8]) -> Json {
let data = source.from_base64().expect("Genesis block is malformed!");
let data_ref: &[u8] = &data;
let mut decoder = GzDecoder::new(data_ref).expect("Gzip is invalid");
let mut s: String = "".to_string();
let mut s: String = "".to_owned();
decoder.read_to_string(&mut s).expect("Gzip is invalid");
Json::from_str(&s).expect("Json is invalid")
}
@@ -18,14 +18,14 @@ pub fn gzip64res_to_json(source: &[u8]) -> Json {
/// Convert JSON value to equivlaent RLP representation.
// TODO: handle container types.
fn json_to_rlp(json: &Json) -> Bytes {
match json {
&Json::Boolean(o) => encode(&(if o {1u64} else {0})),
&Json::I64(o) => encode(&(o as u64)),
&Json::U64(o) => encode(&o),
&Json::String(ref s) if s.len() >= 2 && &s[0..2] == "0x" && U256::from_str(&s[2..]).is_ok() => {
match *json {
Json::Boolean(o) => encode(&(if o {1u64} else {0})),
Json::I64(o) => encode(&(o as u64)),
Json::U64(o) => encode(&o),
Json::String(ref s) if s.len() >= 2 && &s[0..2] == "0x" && U256::from_str(&s[2..]).is_ok() => {
encode(&U256::from_str(&s[2..]).unwrap())
},
&Json::String(ref s) => {
Json::String(ref s) => {
encode(s)
},
_ => panic!()
@@ -108,6 +108,7 @@ pub struct Spec {
state_root_memo: RwLock<Option<H256>>,
}
#[allow(wrong_self_convention)] // because to_engine(self) should be to_engine(&self)
impl Spec {
/// Convert this object into a boxed Engine of the right underlying type.
// TODO avoid this hard-coded nastiness - use dynamic-linked plugin framework instead.
@@ -185,13 +186,13 @@ impl FromJson for Spec {
builtins.insert(addr.clone(), builtin);
}
}
let balance = acc.find("balance").and_then(|x| match x { &Json::String(ref b) => U256::from_dec_str(b).ok(), _ => None });
let nonce = acc.find("nonce").and_then(|x| match x { &Json::String(ref b) => U256::from_dec_str(b).ok(), _ => None });
let balance = acc.find("balance").and_then(|x| match *x { Json::String(ref b) => U256::from_dec_str(b).ok(), _ => None });
let nonce = acc.find("nonce").and_then(|x| match *x { Json::String(ref b) => U256::from_dec_str(b).ok(), _ => None });
// let balance = if let Some(&Json::String(ref b)) = acc.find("balance") {U256::from_dec_str(b).unwrap_or(U256::from(0))} else {U256::from(0)};
// let nonce = if let Some(&Json::String(ref n)) = acc.find("nonce") {U256::from_dec_str(n).unwrap_or(U256::from(0))} else {U256::from(0)};
// TODO: handle code & data if they exist.
if balance.is_some() || nonce.is_some() {
state.insert(addr, GenesisAccount { balance: balance.unwrap_or(U256::from(0)), nonce: nonce.unwrap_or(U256::from(0)) });
state.insert(addr, GenesisAccount { balance: balance.unwrap_or_else(U256::zero), nonce: nonce.unwrap_or_else(U256::zero) });
}
}
}
@@ -215,8 +216,8 @@ impl FromJson for Spec {
Spec {
name: json.find("name").map(|j| j.as_string().unwrap()).unwrap_or("unknown").to_string(),
engine_name: json["engineName"].as_string().unwrap().to_string(),
name: json.find("name").map_or("unknown", |j| j.as_string().unwrap()).to_owned(),
engine_name: json["engineName"].as_string().unwrap().to_owned(),
engine_params: json_to_rlp_map(&json["params"]),
builtins: builtins,
parent_hash: H256::from_str(&genesis["parentHash"].as_string().unwrap()[2..]).unwrap(),
@@ -242,7 +243,7 @@ impl Spec {
let mut root = H256::new();
{
let mut t = SecTrieDBMut::new(db, &mut root);
for (address, account) in self.genesis_state.iter() {
for (address, account) in &self.genesis_state {
t.insert(address.as_slice(), &account.rlp());
}
}

View File

@@ -88,22 +88,22 @@ impl State {
/// Get the balance of account `a`.
pub fn balance(&self, a: &Address) -> U256 {
self.get(a, false).as_ref().map(|account| account.balance().clone()).unwrap_or(U256::from(0u8))
self.get(a, false).as_ref().map_or(U256::zero(), |account| account.balance().clone())
}
/// Get the nonce of account `a`.
pub fn nonce(&self, a: &Address) -> U256 {
self.get(a, false).as_ref().map(|account| account.nonce().clone()).unwrap_or(U256::from(0u8))
self.get(a, false).as_ref().map_or(U256::zero(), |account| account.nonce().clone())
}
/// Mutate storage of account `a` so that it is `value` for `key`.
pub fn storage_at(&self, a: &Address, key: &H256) -> H256 {
self.get(a, false).as_ref().map(|a|a.storage_at(&self.db, key)).unwrap_or(H256::new())
self.get(a, false).as_ref().map_or(H256::new(), |a|a.storage_at(&self.db, key))
}
/// Mutate storage of account `a` so that it is `value` for `key`.
pub fn code(&self, a: &Address) -> Option<Bytes> {
self.get(a, true).as_ref().map(|a|a.code().map(|x|x.to_vec())).unwrap_or(None)
self.get(a, true).as_ref().map_or(None, |a|a.code().map(|x|x.to_vec()))
}
/// Add `incr` to the balance of account `a`.
@@ -170,6 +170,7 @@ impl State {
/// Commit accounts to SecTrieDBMut. This is similar to cpp-ethereum's dev::eth::commit.
/// `accounts` is mutable because we may need to commit the code or storage and record that.
#[allow(match_ref_pats)]
pub fn commit_into(db: &mut HashDB, root: &mut H256, accounts: &mut HashMap<Address, Option<Account>>) {
// first, commit the sub trees.
// TODO: is this necessary or can we dispense with the `ref mut a` for just `a`?
@@ -186,9 +187,9 @@ impl State {
{
let mut trie = SecTrieDBMut::from_existing(db, root);
for (address, ref a) in accounts.iter() {
match a {
&&Some(ref account) => trie.insert(address, &account.rlp()),
&&None => trie.remove(address),
match **a {
Some(ref account) => trie.insert(address, &account.rlp()),
None => trie.remove(address),
}
}
}
@@ -210,7 +211,7 @@ impl State {
pub fn to_hashmap_pod(&self) -> HashMap<Address, PodAccount> {
// TODO: handle database rather than just the cache.
self.cache.borrow().iter().fold(HashMap::new(), |mut m, (add, opt)| {
if let &Some(ref acc) = opt {
if let Some(ref acc) = *opt {
m.insert(add.clone(), PodAccount::from_account(acc));
}
m
@@ -221,7 +222,7 @@ impl State {
pub fn to_pod(&self) -> PodState {
// TODO: handle database rather than just the cache.
PodState::new(self.cache.borrow().iter().fold(BTreeMap::new(), |mut m, (add, opt)| {
if let &Some(ref acc) = opt {
if let Some(ref acc) = *opt {
m.insert(add.clone(), PodAccount::from_account(acc));
}
m

View File

@@ -15,7 +15,7 @@ impl StateDiff {
impl fmt::Display for StateDiff {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for (add, acc) in self.0.iter() {
for (add, acc) in &self.0 {
try!(write!(f, "{} {}: {}", acc.existance(), add, acc));
}
Ok(())

View File

@@ -218,7 +218,7 @@ impl ChainSync {
self.downloading_bodies.clear();
self.headers.clear();
self.bodies.clear();
for (_, ref mut p) in self.peers.iter_mut() {
for (_, ref mut p) in &mut self.peers {
p.asking_blocks.clear();
}
self.header_ids.clear();
@@ -274,6 +274,7 @@ impl ChainSync {
Ok(())
}
#[allow(cyclomatic_complexity)]
/// Called by peer once it has new block headers during sync
fn on_peer_block_headers(&mut self, io: &mut SyncIo, peer_id: PeerId, r: &UntrustedRlp) -> Result<(), PacketDecodeError> {
self.reset_peer_asking(peer_id, PeerAsking::BlockHeaders);
@@ -381,7 +382,7 @@ impl ChainSync {
transactions_root: tx_root,
uncles: uncles
};
match self.header_ids.get(&header_id).map(|n| *n) {
match self.header_ids.get(&header_id).cloned() {
Some(n) => {
self.header_ids.remove(&header_id);
self.bodies.insert_item(n, body.as_raw().to_vec());
@@ -709,16 +710,13 @@ impl ChainSync {
/// Used to recover from an error and re-download parts of the chain detected as bad.
fn remove_downloaded_blocks(&mut self, start: BlockNumber) {
for n in self.headers.get_tail(&start) {
match self.headers.find_item(&n) {
Some(ref header_data) => {
let header_to_delete = HeaderView::new(&header_data.data);
let header_id = HeaderId {
transactions_root: header_to_delete.transactions_root(),
uncles: header_to_delete.uncles_hash()
};
self.header_ids.remove(&header_id);
},
None => {}
if let Some(ref header_data) = self.headers.find_item(&n) {
let header_to_delete = HeaderView::new(&header_data.data);
let header_id = HeaderId {
transactions_root: header_to_delete.transactions_root(),
uncles: header_to_delete.uncles_hash()
};
self.header_ids.remove(&header_id);
}
self.downloading_bodies.remove(&n);
self.downloading_headers.remove(&n);
@@ -806,12 +804,9 @@ impl ChainSync {
packet.append(&chain.best_block_hash);
packet.append(&chain.genesis_hash);
//TODO: handle timeout for status request
match io.send(peer_id, STATUS_PACKET, packet.out()) {
Err(e) => {
warn!(target:"sync", "Error sending status request: {:?}", e);
io.disable_peer(peer_id);
}
Ok(_) => ()
if let Err(e) = io.send(peer_id, STATUS_PACKET, packet.out()) {
warn!(target:"sync", "Error sending status request: {:?}", e);
io.disable_peer(peer_id);
}
}
@@ -847,12 +842,9 @@ impl ChainSync {
let mut data = Bytes::new();
let inc = (skip + 1) as BlockNumber;
while number <= last && number > 0 && count < max_count {
match io.chain().block_header_at(number) {
Some(mut hdr) => {
data.append(&mut hdr);
count += 1;
}
None => {}
if let Some(mut hdr) = io.chain().block_header_at(number) {
data.append(&mut hdr);
count += 1;
}
if reverse {
if number <= inc {
@@ -884,12 +876,9 @@ impl ChainSync {
let mut added = 0usize;
let mut data = Bytes::new();
for i in 0..count {
match io.chain().block_body(&try!(r.val_at::<H256>(i))) {
Some(mut hdr) => {
data.append(&mut hdr);
added += 1;
}
None => {}
if let Some(mut hdr) = io.chain().block_body(&try!(r.val_at::<H256>(i))) {
data.append(&mut hdr);
added += 1;
}
}
let mut rlp = RlpStream::new_list(added);
@@ -911,12 +900,9 @@ impl ChainSync {
let mut added = 0usize;
let mut data = Bytes::new();
for i in 0..count {
match io.chain().state_data(&try!(r.val_at::<H256>(i))) {
Some(mut hdr) => {
data.append(&mut hdr);
added += 1;
}
None => {}
if let Some(mut hdr) = io.chain().state_data(&try!(r.val_at::<H256>(i))) {
data.append(&mut hdr);
added += 1;
}
}
let mut rlp = RlpStream::new_list(added);
@@ -937,12 +923,9 @@ impl ChainSync {
let mut added = 0usize;
let mut data = Bytes::new();
for i in 0..count {
match io.chain().block_receipts(&try!(r.val_at::<H256>(i))) {
Some(mut hdr) => {
data.append(&mut hdr);
added += 1;
}
None => {}
if let Some(mut hdr) = io.chain().block_receipts(&try!(r.val_at::<H256>(i))) {
data.append(&mut hdr);
added += 1;
}
}
let mut rlp = RlpStream::new_list(added);

View File

@@ -14,7 +14,7 @@ pub trait SyncIo {
/// Send a packet to a peer.
fn send(&mut self, peer_id: PeerId, packet_id: PacketId, data: Vec<u8>) -> Result<(), UtilError>;
/// Get the blockchain
fn chain<'s>(&'s self) -> &'s BlockChainClient;
fn chain(&self) -> &BlockChainClient;
/// Returns peer client identifier string
fn peer_info(&self, peer_id: PeerId) -> String {
peer_id.to_string()
@@ -50,7 +50,7 @@ impl<'s, 'h> SyncIo for NetSyncIo<'s, 'h> {
self.network.send(peer_id, packet_id, data)
}
fn chain<'a>(&'a self) -> &'a BlockChainClient {
fn chain(&self) -> &BlockChainClient {
self.chain
}

View File

@@ -29,7 +29,7 @@ pub trait RangeCollection<K, V> {
/// Remove all elements >= `tail`
fn insert_item(&mut self, key: K, value: V);
/// Get an iterator over ranges
fn range_iter<'c>(&'c self) -> RangeIterator<'c, K, V>;
fn range_iter(& self) -> RangeIterator<K, V>;
}
/// Range iterator. For each range yelds a key for the first element of the range and a vector of values.
@@ -60,7 +60,7 @@ impl<'c, K:'c, V:'c> Iterator for RangeIterator<'c, K, V> where K: Add<Output =
}
impl<K, V> RangeCollection<K, V> for Vec<(K, Vec<V>)> where K: Ord + PartialEq + Add<Output = K> + Sub<Output = K> + Copy + FromUsize + ToUsize {
fn range_iter<'c>(&'c self) -> RangeIterator<'c, K, V> {
fn range_iter(&self) -> RangeIterator<K, V> {
RangeIterator {
range: self.len(),
collection: self
@@ -191,6 +191,7 @@ impl<K, V> RangeCollection<K, V> for Vec<(K, Vec<V>)> where K: Ord + PartialEq +
}
#[test]
#[allow(cyclomatic_complexity)]
fn test_range() {
use std::cmp::{Ordering};

View File

@@ -66,7 +66,7 @@ impl BlockChainClient for TestBlockChainClient {
}
fn block(&self, h: &H256) -> Option<Bytes> {
self.blocks.read().unwrap().get(h).map(|b| b.clone())
self.blocks.read().unwrap().get(h).cloned()
}
fn block_status(&self, h: &H256) -> BlockStatus {
@@ -211,7 +211,7 @@ impl<'p> SyncIo for TestIo<'p> {
Ok(())
}
fn chain<'a>(&'a self) -> &'a BlockChainClient {
fn chain(&self) -> &BlockChainClient {
self.chain
}
}
@@ -268,14 +268,11 @@ impl TestNet {
pub fn sync_step(&mut self) {
for peer in 0..self.peers.len() {
match self.peers[peer].queue.pop_front() {
Some(packet) => {
let mut p = self.peers.get_mut(packet.recipient).unwrap();
trace!("--- {} -> {} ---", peer, packet.recipient);
p.sync.on_packet(&mut TestIo::new(&mut p.chain, &mut p.queue, Some(peer as PeerId)), peer as PeerId, packet.packet_id, &packet.data);
trace!("----------------");
},
None => {}
if let Some(packet) = self.peers[peer].queue.pop_front() {
let mut p = self.peers.get_mut(packet.recipient).unwrap();
trace!("--- {} -> {} ---", peer, packet.recipient);
p.sync.on_packet(&mut TestIo::new(&mut p.chain, &mut p.queue, Some(peer as PeerId)), peer as PeerId, packet.packet_id, &packet.data);
trace!("----------------");
}
let mut p = self.peers.get_mut(peer).unwrap();
p.sync._maintain_sync(&mut TestIo::new(&mut p.chain, &mut p.queue, None));

View File

@@ -168,7 +168,7 @@ fn do_json_test_for(vm: &VMType, json_data: &[u8]) -> Vec<String> {
let mut fail = false;
//let mut fail_unless = |cond: bool| if !cond && !fail { failed.push(name.to_string()); fail = true };
let mut fail_unless = |cond: bool, s: &str | if !cond && !fail {
failed.push(format!("[{}] {}: {}", vm, name.to_string(), s));
failed.push(format!("[{}] {}: {}", vm, name, s));
fail = true
};
@@ -187,15 +187,9 @@ fn do_json_test_for(vm: &VMType, json_data: &[u8]) -> Vec<String> {
BTreeMap::from_json(&s["storage"]).into_iter().foreach(|(k, v)| state.set_storage(&address, k, v));
});
let mut info = EnvInfo::new();
test.find("env").map(|env| {
info.author = xjson!(&env["currentCoinbase"]);
info.difficulty = xjson!(&env["currentDifficulty"]);
info.gas_limit = xjson!(&env["currentGasLimit"]);
info.number = xjson!(&env["currentNumber"]);
info.timestamp = xjson!(&env["currentTimestamp"]);
});
let info = test.find("env").map(|env| {
EnvInfo::from_json(env)
}).unwrap_or_default();
let engine = TestEngine::new(1, vm.clone());
@@ -245,7 +239,7 @@ fn do_json_test_for(vm: &VMType, json_data: &[u8]) -> Vec<String> {
test.find("post").map(|pre| for (addr, s) in pre.as_object().unwrap() {
let address = Address::from(addr.as_ref());
fail_unless(state.code(&address).unwrap_or(vec![]) == Bytes::from_json(&s["code"]), "code is incorrect");
fail_unless(state.code(&address).unwrap_or_else(|| vec![]) == Bytes::from_json(&s["code"]), "code is incorrect");
fail_unless(state.balance(&address) == xjson!(&s["balance"]), "balance is incorrect");
fail_unless(state.nonce(&address) == xjson!(&s["nonce"]), "nonce is incorrect");
BTreeMap::from_json(&s["storage"]).iter().foreach(|(k, v)| fail_unless(&state.storage_at(&address, &k) == v, "storage is incorrect"));
@@ -266,7 +260,7 @@ fn do_json_test_for(vm: &VMType, json_data: &[u8]) -> Vec<String> {
}
for f in failed.iter() {
for f in &failed {
println!("FAILED: {:?}", f);
}
@@ -277,7 +271,7 @@ fn do_json_test_for(vm: &VMType, json_data: &[u8]) -> Vec<String> {
declare_test!{ExecutiveTests_vmArithmeticTest, "VMTests/vmArithmeticTest"}
declare_test!{ExecutiveTests_vmBitwiseLogicOperationTest, "VMTests/vmBitwiseLogicOperationTest"}
// this one crashes with some vm internal error. Separately they pass.
declare_test_ignore!{ExecutiveTests_vmBlockInfoTest, "VMTests/vmBlockInfoTest"}
declare_test!{ExecutiveTests_vmBlockInfoTest, "VMTests/vmBlockInfoTest"}
declare_test!{ExecutiveTests_vmEnvironmentalInfoTest, "VMTests/vmEnvironmentalInfoTest"}
declare_test!{ExecutiveTests_vmIOandFlowOperationsTest, "VMTests/vmIOandFlowOperationsTest"}
// this one take way too long.

View File

@@ -15,7 +15,7 @@ fn do_json_test(json_data: &[u8]) -> Vec<String> {
let mut fail = false;
{
let mut fail_unless = |cond: bool| if !cond && !fail {
failed.push(name.to_string());
failed.push(name.clone());
flush(format!("FAIL\n"));
fail = true;
true

View File

@@ -6,7 +6,7 @@ macro_rules! declare_test {
#[test]
#[allow(non_snake_case)]
fn $id() {
assert!(do_json_test(include_bytes!(concat!("../../res/ethereum/tests/", $name, ".json"))).len() == 0);
assert!(do_json_test(include_bytes!(concat!("../../res/ethereum/tests/", $name, ".json"))).is_empty());
}
};
}
@@ -18,7 +18,7 @@ macro_rules! declare_test_ignore {
#[ignore]
#[allow(non_snake_case)]
fn $id() {
assert!(do_json_test(include_bytes!(concat!("../../res/ethereum/tests/", $name, ".json"))).len() == 0);
assert!(do_json_test(include_bytes!(concat!("../../res/ethereum/tests/", $name, ".json"))).is_empty());
}
};
}

View File

@@ -9,13 +9,13 @@ fn do_json_test(json_data: &[u8]) -> Vec<String> {
let ot = RefCell::new(Transaction::new());
for (name, test) in json.as_object().unwrap() {
let mut fail = false;
let mut fail_unless = |cond: bool| if !cond && !fail { failed.push(name.to_string()); println!("Transaction: {:?}", ot.borrow()); fail = true };
let mut fail_unless = |cond: bool| if !cond && !fail { failed.push(name.clone()); println!("Transaction: {:?}", ot.borrow()); fail = true };
let schedule = match test.find("blocknumber")
.and_then(|j| j.as_string())
.and_then(|s| BlockNumber::from_str(s).ok())
.unwrap_or(0) { x if x < 900000 => &old_schedule, _ => &new_schedule };
let rlp = Bytes::from_json(&test["rlp"]);
let res = UntrustedRlp::new(&rlp).as_val().map_err(|e| From::from(e)).and_then(|t: Transaction| t.validate(schedule, schedule.have_delegate_call));
let res = UntrustedRlp::new(&rlp).as_val().map_err(From::from).and_then(|t: Transaction| t.validate(schedule, schedule.have_delegate_call));
fail_unless(test.find("transaction").is_none() == res.is_err());
if let (Some(&Json::Object(ref tx)), Some(&Json::String(ref expect_sender))) = (test.find("transaction"), test.find("sender")) {
let t = res.unwrap();
@@ -30,11 +30,11 @@ fn do_json_test(json_data: &[u8]) -> Vec<String> {
fail_unless(to == &xjson!(&tx["to"]));
} else {
*ot.borrow_mut() = t.clone();
fail_unless(Bytes::from_json(&tx["to"]).len() == 0);
fail_unless(Bytes::from_json(&tx["to"]).is_empty());
}
}
}
for f in failed.iter() {
for f in &failed {
println!("FAILED: {:?}", f);
}
failed

View File

@@ -117,9 +117,8 @@ impl Transaction {
};
s.append(&self.value);
s.append(&self.data);
match with_seal {
Seal::With => { s.append(&(self.v as u16)).append(&self.r).append(&self.s); },
_ => {}
if let Seal::With = with_seal {
s.append(&(self.v as u16)).append(&self.r).append(&self.s);
}
}
@@ -138,7 +137,7 @@ impl FromJson for Transaction {
gas_price: xjson!(&json["gasPrice"]),
gas: xjson!(&json["gasLimit"]),
action: match Bytes::from_json(&json["to"]) {
ref x if x.len() == 0 => Action::Create,
ref x if x.is_empty() => Action::Create,
ref x => Action::Call(Address::from_slice(x)),
},
value: xjson!(&json["value"]),
@@ -303,4 +302,4 @@ fn signing() {
let key = KeyPair::create().unwrap();
let t = Transaction::new_create(U256::from(42u64), b"Hello!".to_vec(), U256::from(3000u64), U256::from(50_000u64), U256::from(1u64)).signed(&key.secret());
assert_eq!(Address::from(key.public().sha3()), t.sender().unwrap());
}
}

View File

@@ -64,7 +64,7 @@ pub fn verify_block_unordered(header: Header, bytes: Bytes, engine: &Engine) ->
/// Phase 3 verification. Check block information against parent and uncles.
pub fn verify_block_family<BC>(header: &Header, bytes: &[u8], engine: &Engine, bc: &BC) -> Result<(), Error> where BC: BlockProvider {
// TODO: verify timestamp
let parent = try!(bc.block_header(&header.parent_hash).ok_or::<Error>(From::from(BlockError::UnknownParent(header.parent_hash.clone()))));
let parent = try!(bc.block_header(&header.parent_hash).ok_or_else(|| Error::from(BlockError::UnknownParent(header.parent_hash.clone()))));
try!(verify_parent(&header, &parent));
try!(engine.verify_block_family(&header, &parent, Some(bytes)));
@@ -122,7 +122,7 @@ pub fn verify_block_family<BC>(header: &Header, bytes: &[u8], engine: &Engine, b
// cB.p^7 -------------/
// cB.p^8
let mut expected_uncle_parent = header.parent_hash.clone();
let uncle_parent = try!(bc.block_header(&uncle.parent_hash).ok_or::<Error>(From::from(BlockError::UnknownUncleParent(uncle.parent_hash.clone()))));
let uncle_parent = try!(bc.block_header(&uncle.parent_hash).ok_or_else(|| Error::from(BlockError::UnknownUncleParent(uncle.parent_hash.clone()))));
for _ in 0..depth {
match bc.block_details(&expected_uncle_parent) {
Some(details) => {
@@ -284,7 +284,7 @@ mod tests {
/// Get raw block data
fn block(&self, hash: &H256) -> Option<Bytes> {
self.blocks.get(hash).map(|b| b.clone())
self.blocks.get(hash).cloned()
}
/// Get the familial details concerning a block.
@@ -302,7 +302,7 @@ mod tests {
/// Get the hash of given block's number.
fn block_hash(&self, index: BlockNumber) -> Option<H256> {
self.numbers.get(&index).map(|h| h.clone())
self.numbers.get(&index).cloned()
}
}

View File

@@ -141,7 +141,7 @@ impl<'a> BlockView<'a> {
/// Return List of transactions in given block.
pub fn transaction_views(&self) -> Vec<TransactionView> {
self.rlp.at(1).iter().map(|rlp| TransactionView::new_from_rlp(rlp)).collect()
self.rlp.at(1).iter().map(TransactionView::new_from_rlp).collect()
}
/// Return transaction hashes.
@@ -156,7 +156,7 @@ impl<'a> BlockView<'a> {
/// Return List of transactions in given block.
pub fn uncle_views(&self) -> Vec<HeaderView> {
self.rlp.at(2).iter().map(|rlp| HeaderView::new_from_rlp(rlp)).collect()
self.rlp.at(2).iter().map(HeaderView::new_from_rlp).collect()
}
/// Return list of uncle hashes of given block.