Skip to content
This repository has been archived by the owner on Nov 6, 2020. It is now read-only.

[WIP] include raw bytes in Ethcore::BlockError #11493

Closed
wants to merge 14 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions ethcore/client-traits/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,9 @@ impl Tick for () {}
pub trait BadBlocks {
/// Returns a list of blocks that were recently not imported because they were invalid.
fn bad_blocks(&self) -> Vec<(Unverified, String)>;

/// Report a bad block
fn report_bad_block(&self, block: Bytes, message: String);
}


Expand Down
4 changes: 4 additions & 0 deletions ethcore/engines/clique/src/block_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,8 @@ impl CliqueBlockState {
}

// see https://github.com/ethereum/go-ethereum/blob/master/consensus/clique/clique.go#L474
//
// NOTE(niklasad1): might return EthcoreError without `block bytes`
fn verify(&self, header: &Header) -> Result<Address, Error> {
let creator = recover_creator(header)?.clone();

Expand Down Expand Up @@ -167,6 +169,8 @@ impl CliqueBlockState {
}

/// Verify and apply a new header to current state
//
// NOTE(niklasad1): might return EthcoreError without `block bytes`
pub fn apply(&mut self, header: &Header, is_checkpoint: bool) -> Result<Address, Error> {
let creator = self.verify(header)?;
self.recent_signers.push_front(creator);
Expand Down
4 changes: 4 additions & 0 deletions ethcore/engines/clique/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,8 @@ impl Clique {
}

/// Construct an new state from given checkpoint header.
//
// NOTE(niklasad1): might return `BlockErrorWithData` without `block bytes`
fn new_checkpoint_state(&self, header: &Header) -> Result<CliqueBlockState, Error> {
debug_assert_eq!(header.number() % self.epoch_length, 0);

Expand All @@ -279,6 +281,8 @@ impl Clique {
}

/// Get `CliqueBlockState` for given header, backfill from last checkpoint if needed.
//
// NOTE(niklasad1): might return `BlockErrorWithData` without `block bytes`
fn state(&self, header: &Header) -> Result<CliqueBlockState, Error> {
let mut block_state_by_hash = self.block_state_by_hash.write();
if let Some(state) = block_state_by_hash.get_mut(&header.hash()) {
Expand Down
54 changes: 27 additions & 27 deletions ethcore/engines/ethash/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,7 @@ impl Ethash {
}
}

// NOTE(niklasad1): might return `BlockError` without bytes
fn verify_block_unordered(pow: &Arc<EthashManager>, header: &Header) -> Result<(), Error> {
let seal = EthashSeal::parse_seal(header.seal())?;

Expand All @@ -186,20 +187,20 @@ fn verify_block_unordered(pow: &Arc<EthashManager>, header: &Header) -> Result<(
let mix = H256(result.mix_hash);
let difficulty = ethash::boundary_to_difficulty(&H256(result.value));
trace!(target: "miner", "num: {num}, seed: {seed}, h: {h}, non: {non}, mix: {mix}, res: {res}",
num = header.number() as u64,
seed = H256(slow_hash_block_number(header.number() as u64)),
num = header.number(),
seed = H256(slow_hash_block_number(header.number())),
h = header.bare_hash(),
non = seal.nonce.to_low_u64_be(),
mix = H256(result.mix_hash),
res = H256(result.value));
if mix != seal.mix_hash {
return Err(From::from(BlockError::MismatchedH256SealElement(Mismatch {
return Err(Error::Block(BlockError::MismatchedH256SealElement(Mismatch {
expected: mix,
found: seal.mix_hash
})));
}
if &difficulty < header.difficulty() {
return Err(From::from(BlockError::InvalidProofOfWork(OutOfBounds {
return Err(Error::Block(BlockError::InvalidProofOfWork(OutOfBounds {
min: Some(*header.difficulty()),
max: None,
found: difficulty
Expand Down Expand Up @@ -331,11 +332,11 @@ impl Engine for Ethash {
// TODO: consider removing these lines.
let min_difficulty = self.ethash_params.minimum_difficulty;
if header.difficulty() < &min_difficulty {
return Err(From::from(BlockError::DifficultyOutOfBounds(OutOfBounds {
return Err(Error::Block(BlockError::DifficultyOutOfBounds(OutOfBounds {
min: Some(min_difficulty),
max: None,
found: *header.difficulty(),
})))
found: *header.difficulty()
})));
}

let difficulty = ethash::boundary_to_difficulty(&H256(quick_get_difficulty(
Expand All @@ -346,13 +347,12 @@ impl Engine for Ethash {
)));

if &difficulty < header.difficulty() {
return Err(From::from(BlockError::InvalidProofOfWork(OutOfBounds {
return Err(Error::Block(BlockError::InvalidProofOfWork(OutOfBounds {
min: Some(*header.difficulty()),
max: None,
found: difficulty
})));
}

Ok(())
}

Expand All @@ -363,7 +363,7 @@ impl Engine for Ethash {
fn verify_block_family(&self, header: &Header, parent: &Header) -> Result<(), Error> {
// we should not calculate difficulty for genesis blocks
if header.number() == 0 {
return Err(From::from(BlockError::RidiculousNumber(OutOfBounds {
return Err(Error::Block(BlockError::RidiculousNumber(OutOfBounds {
min: Some(1),
max: None,
found: header.number()
Expand All @@ -376,7 +376,7 @@ impl Engine for Ethash {
return Err(From::from(BlockError::InvalidDifficulty(Mismatch {
expected: expected_difficulty,
found: *header.difficulty()
})))
})));
}

Ok(())
Expand Down Expand Up @@ -672,8 +672,8 @@ mod tests {

match verify_result {
Err(Error::Block(BlockError::InvalidSealArity(_))) => {},
Err(_) => { panic!("should be block seal-arity mismatch error (got {:?})", verify_result); },
_ => { panic!("Should be error, got Ok"); },
Err(_) => panic!("should be block seal-arity mismatch error (got {:?})", verify_result),
_ => panic!("Should be error, got Ok"),
}
}

Expand All @@ -687,8 +687,8 @@ mod tests {

match verify_result {
Err(Error::Block(BlockError::DifficultyOutOfBounds(_))) => {},
Err(_) => { panic!("should be block difficulty error (got {:?})", verify_result); },
_ => { panic!("Should be error, got Ok"); },
Err(_) => panic!("should be block difficulty error (got {:?})", verify_result),
_ => panic!("Should be error, got Ok"),
}
}

Expand All @@ -703,8 +703,8 @@ mod tests {

match verify_result {
Err(Error::Block(BlockError::InvalidProofOfWork(_))) => {},
Err(_) => { panic!("should be invalid proof of work error (got {:?})", verify_result); },
_ => { panic!("Should be error, got Ok"); },
Err(_) => panic!("should be invalid proof of work error (got {:?})", verify_result),
_ => panic!("Should be error, got Ok"),
}
}

Expand All @@ -717,8 +717,8 @@ mod tests {

match verify_result {
Err(Error::Block(BlockError::InvalidSealArity(_))) => {},
Err(_) => { panic!("should be block seal-arity mismatch error (got {:?})", verify_result); },
_ => { panic!("Should be error, got Ok"); },
Err(_) => panic!("should be block seal-arity mismatch error (got {:?})", verify_result),
_ => panic!("Should be error, got Ok"),
}
}

Expand All @@ -742,8 +742,8 @@ mod tests {

match verify_result {
Err(Error::Block(BlockError::MismatchedH256SealElement(_))) => {},
Err(_) => { panic!("should be invalid 256-bit seal fail (got {:?})", verify_result); },
_ => { panic!("Should be error, got Ok"); },
Err(_) => panic!("should be invalid 256-bit seal fail (got {:?})", verify_result),
_ => panic!("Should be error, got Ok"),
}
}

Expand All @@ -758,8 +758,8 @@ mod tests {

match verify_result {
Err(Error::Block(BlockError::InvalidProofOfWork(_))) => {},
Err(_) => { panic!("should be invalid proof-of-work fail (got {:?})", verify_result); },
_ => { panic!("Should be error, got Ok"); },
Err(_) => panic!("should be invalid proof-of-work fail (got {:?})", verify_result),
_ => panic!("Should be error, got Ok"),
}
}

Expand All @@ -773,8 +773,8 @@ mod tests {

match verify_result {
Err(Error::Block(BlockError::RidiculousNumber(_))) => {},
Err(_) => { panic!("should be invalid block number fail (got {:?})", verify_result); },
_ => { panic!("Should be error, got Ok"); },
Err(_) => panic!("should be invalid block number fail (got {:?})", verify_result),
_ => panic!("Should be error, got Ok"),
}
}

Expand All @@ -790,8 +790,8 @@ mod tests {

match verify_result {
Err(Error::Block(BlockError::InvalidDifficulty(_))) => {},
Err(_) => { panic!("should be invalid difficulty fail (got {:?})", verify_result); },
_ => { panic!("Should be error, got Ok"); },
Err(_) => panic!("should be invalid difficulty fail (got {:?})", verify_result),
_ => panic!("Should be error, got Ok"),
}
}

Expand Down
24 changes: 15 additions & 9 deletions ethcore/light/src/client/header_chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ use common_types::{
Transition as EpochTransition,
PendingTransition as PendingEpochTransition,
},
errors::{EthcoreError as Error, BlockError, EthcoreResult},
errors::{EthcoreError as Error, BlockError},
header::Header,
ids::BlockId,
};
Expand Down Expand Up @@ -227,6 +227,9 @@ pub struct HeaderChain {

impl HeaderChain {
/// Create a new header chain given this genesis block and database to read from.
//
// NOTE(niklasad1): might return BlockError without `block bytes`,
// but this function is only called at startup so "ok".
pub fn new(
db: Arc<dyn KeyValueDB>,
col: u32,
Expand All @@ -240,7 +243,7 @@ impl HeaderChain {
let decoded_header = spec.genesis_header();

let chain = if let Some(current) = db.get(col, CURRENT_KEY)? {
let curr : BestAndLatest = ::rlp::decode(&current).expect("decoding db value failed");
let curr: BestAndLatest = rlp::decode(&current).expect("decoding db value failed");

let mut cur_number = curr.latest_num;
let mut candidates = BTreeMap::new();
Expand Down Expand Up @@ -322,8 +325,12 @@ impl HeaderChain {

// write the block in the DB.
info!(target: "chain", "Inserting hardcoded block #{} in chain", decoded_header_num);
let pending = chain.insert_with_td(&mut batch, &decoded_header,
hardcoded_sync.total_difficulty, None)?;
let pending = chain.insert_with_td(
&mut batch,
&decoded_header,
hardcoded_sync.total_difficulty,
None
)?;

// check that we have enough hardcoded CHT roots. avoids panicking later.
let cht_num = cht::block_to_cht_number(decoded_header_num - 1)
Expand Down Expand Up @@ -369,7 +376,7 @@ impl HeaderChain {
transaction: &mut DBTransaction,
header: &Header,
transition_proof: Option<Vec<u8>>,
) -> EthcoreResult<PendingChanges> {
) -> Result<PendingChanges, BlockError> {
self.insert_inner(transaction, header, None, transition_proof)
}

Expand All @@ -382,7 +389,7 @@ impl HeaderChain {
header: &Header,
total_difficulty: U256,
transition_proof: Option<Vec<u8>>,
) -> EthcoreResult<PendingChanges> {
) -> Result<PendingChanges, BlockError> {
self.insert_inner(transaction, header, Some(total_difficulty), transition_proof)
}

Expand All @@ -392,7 +399,7 @@ impl HeaderChain {
header: &Header,
total_difficulty: Option<U256>,
transition_proof: Option<Vec<u8>>,
) -> EthcoreResult<PendingChanges> {
) -> Result<PendingChanges, BlockError> {
let hash = header.hash();
let number = header.number();
let parent_hash = *header.parent_hash();
Expand Down Expand Up @@ -420,8 +427,7 @@ impl HeaderChain {
candidates.get(&(number - 1))
.and_then(|entry| entry.candidates.iter().find(|c| c.hash == parent_hash))
.map(|c| c.total_difficulty)
.ok_or_else(|| BlockError::UnknownParent(parent_hash))
.map_err(Error::Block)?
.ok_or_else(|| BlockError::UnknownParent(parent_hash))?
};

parent_td + *header.difficulty()
Expand Down
2 changes: 1 addition & 1 deletion ethcore/light/src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ impl<T: ChainDataFetcher> Client<T> {

/// Import a header to the queue for additional verification.
pub fn import_header(&self, header: Header) -> EthcoreResult<H256> {
self.queue.import(header).map_err(|(e, _)| e)
self.queue.import(header)
}

/// Inquire about the status of a given header.
Expand Down
1 change: 0 additions & 1 deletion ethcore/light/src/client/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ pub enum Error {
}

impl From<CoreError> for Error {
#[inline]
fn from(err: CoreError) -> Error {
Error::Core(err)
}
Expand Down
Loading