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

simplify kvdb error types #8924

Merged
merged 2 commits into from
Jul 2, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 7 additions & 9 deletions ethcore/light/src/client/header_chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ use std::sync::Arc;
use cht;

use ethcore::block_status::BlockStatus;
use ethcore::error::{Error, ErrorKind, BlockImportError, BlockImportErrorKind, BlockError};
use ethcore::error::{Error, BlockImportError, BlockImportErrorKind, BlockError};
use ethcore::encoded;
use ethcore::header::Header;
use ethcore::ids::BlockId;
Expand Down Expand Up @@ -260,7 +260,7 @@ impl HeaderChain {
let best_block = {
let era = match candidates.get(&curr.best_num) {
Some(era) => era,
None => bail!(ErrorKind::Database("Database corrupt: highest block referenced but no data.".into())),
None => bail!("Database corrupt: highest block referenced but no data."),
};

let best = &era.candidates[0];
Expand Down Expand Up @@ -583,27 +583,25 @@ impl HeaderChain {
} else {
let msg = format!("header of block #{} not found in DB ; database in an \
inconsistent state", h_num);
bail!(ErrorKind::Database(msg.into()));
bail!(msg);
};

let decoded = header.decode().expect("decoding db value failed");

let entry: Entry = {
let bytes = self.db.get(self.col, era_key(h_num).as_bytes())?
.ok_or_else(|| {
let msg = format!("entry for era #{} not found in DB ; database \
in an inconsistent state", h_num);
ErrorKind::Database(msg.into())
format!("entry for era #{} not found in DB ; database \
in an inconsistent state", h_num)
})?;
::rlp::decode(&bytes).expect("decoding db value failed")
};

let total_difficulty = entry.candidates.iter()
.find(|c| c.hash == decoded.hash())
.ok_or_else(|| {
let msg = "no candidate matching block found in DB ; database in an \
inconsistent state";
ErrorKind::Database(msg.into())
"no candidate matching block found in DB ; database in an \
inconsistent state"
})?
.total_difficulty;

Expand Down
7 changes: 3 additions & 4 deletions ethcore/src/blockchain/blockchain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,9 @@
//! Blockchain database.

use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::sync::Arc;
use std::mem;
use std::{mem, io};
use itertools::Itertools;
use blooms_db;
use heapsize::HeapSizeOf;
Expand Down Expand Up @@ -47,8 +48,6 @@ use engines::epoch::{Transition as EpochTransition, PendingTransition as Pending
use rayon::prelude::*;
use ansi_term::Colour;
use kvdb::{DBTransaction, KeyValueDB};
use error::Error;
use std::path::Path;

/// Database backing `BlockChain`.
pub trait BlockChainDB: Send + Sync {
Expand All @@ -66,7 +65,7 @@ pub trait BlockChainDB: Send + Sync {
/// predefined config.
pub trait BlockChainDBHandler: Send + Sync {
/// Open the predefined key-value database.
fn open(&self, path: &Path) -> Result<Arc<BlockChainDB>, Error>;
fn open(&self, path: &Path) -> io::Result<Arc<BlockChainDB>>;
}

/// Interface for querying blocks by hash and by number.
Expand Down
4 changes: 2 additions & 2 deletions ethcore/src/client/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -718,7 +718,7 @@ impl Client {
state_db = spec.ensure_db_good(state_db, &factories)?;
let mut batch = DBTransaction::new();
state_db.journal_under(&mut batch, 0, &spec.genesis_header().hash())?;
db.key_value().write(batch).map_err(ClientError::Database)?;
db.key_value().write(batch)?;
}

let gb = spec.genesis_block();
Expand Down Expand Up @@ -821,7 +821,7 @@ impl Client {
}

// ensure buffered changes are flushed.
client.db.read().key_value().flush().map_err(ClientError::Database)?;
client.db.read().key_value().flush()?;
Ok(client)
}

Expand Down
4 changes: 0 additions & 4 deletions ethcore/src/client/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,13 @@

use std::fmt::{Display, Formatter, Error as FmtError};
use util_error::UtilError;
use kvdb;
use trie::TrieError;

/// Client configuration errors.
#[derive(Debug)]
pub enum Error {
/// TrieDB-related error.
Trie(TrieError),
/// Database error
Database(kvdb::Error),
/// Util error
Util(UtilError),
}
Expand Down Expand Up @@ -53,7 +50,6 @@ impl Display for Error {
match *self {
Error::Trie(ref err) => write!(f, "{}", err),
Error::Util(ref err) => write!(f, "{}", err),
Error::Database(ref s) => write!(f, "Database error: {}", s),
}
}
}
5 changes: 1 addition & 4 deletions ethcore/src/client/evm_test_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,6 @@ pub enum EvmTestError {
Evm(vm::Error),
/// Initialization error.
ClientError(::error::Error),
/// Low-level database error.
Database(kvdb::Error),
/// Post-condition failure,
PostCondition(String),
}
Expand All @@ -55,7 +53,6 @@ impl fmt::Display for EvmTestError {
Trie(ref err) => write!(fmt, "Trie: {}", err),
Evm(ref err) => write!(fmt, "EVM: {}", err),
ClientError(ref err) => write!(fmt, "{}", err),
Database(ref err) => write!(fmt, "DB: {}", err),
PostCondition(ref err) => write!(fmt, "{}", err),
}
}
Expand Down Expand Up @@ -135,7 +132,7 @@ impl<'a> EvmTestClient<'a> {
{
let mut batch = kvdb::DBTransaction::new();
state_db.journal_under(&mut batch, 0, &genesis.hash())?;
db.write(batch).map_err(EvmTestError::Database)?;
db.write(batch)?;
}

state::State::from_existing(
Expand Down
14 changes: 6 additions & 8 deletions ethcore/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@

use std::{fmt, error};
use std::time::SystemTime;
use kvdb;
use ethereum_types::{H256, U256, Address, Bloom};
use util_error::{self, UtilError};
use snappy::InvalidInput;
Expand Down Expand Up @@ -237,11 +236,10 @@ error_chain! {
}

links {
Database(kvdb::Error, kvdb::ErrorKind) #[doc = "Database error."];
Util(UtilError, util_error::ErrorKind) #[doc = "Error concerning a utility"];
Import(ImportError, ImportErrorKind) #[doc = "Error concerning block import." ];
}

foreign_links {
Io(IoError) #[doc = "Io create error"];
StdIo(::std::io::Error) #[doc = "Error concerning the Rust standard library's IO subsystem."];
Expand Down Expand Up @@ -271,14 +269,14 @@ error_chain! {
AccountProvider(err: AccountsError) {
description("Accounts Provider error")
display("Accounts Provider error {}", err)
}
}

#[doc = "PoW hash is invalid or out of date."]
PowHashInvalid {
description("PoW hash is invalid or out of date.")
display("PoW hash is invalid or out of date.")
}

#[doc = "The value of the nonce or mishash is invalid."]
PowInvalid {
description("The value of the nonce or mishash is invalid.")
Expand Down Expand Up @@ -311,10 +309,10 @@ impl From<ClientError> for Error {
}
}

impl From<AccountsError> for Error {
fn from(err: AccountsError) -> Error {
impl From<AccountsError> for Error {
fn from(err: AccountsError) -> Error {
ErrorKind::AccountProvider(err).into()
}
}
}

impl From<::rlp::DecoderError> for Error {
Expand Down
7 changes: 3 additions & 4 deletions ethcore/src/test_helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,15 @@
//! Set of different helpers for client tests

use std::path::Path;
use std::fs;
use std::sync::Arc;
use std::{fs, io};
use account_provider::AccountProvider;
use ethereum_types::{H256, U256, Address};
use block::{OpenBlock, Drain};
use blockchain::{BlockChain, BlockChainDB, BlockChainDBHandler, Config as BlockChainConfig, ExtrasInsert};
use bytes::Bytes;
use client::{Client, ClientConfig, ChainInfo, ImportBlock, ChainNotify, ChainMessageType, PrepareOpenBlock};
use ethkey::KeyPair;
use error::Error;
use evm::Factory as EvmFactory;
use factory::Factories;
use hash::keccak;
Expand All @@ -37,7 +37,6 @@ use rlp::{self, RlpStream};
use spec::Spec;
use state_db::StateDB;
use state::*;
use std::sync::Arc;
use transaction::{Action, Transaction, SignedTransaction};
use views::BlockView;
use blooms_db;
Expand Down Expand Up @@ -327,7 +326,7 @@ pub fn restoration_db_handler(config: kvdb_rocksdb::DatabaseConfig) -> Box<Block
}

impl BlockChainDBHandler for RestorationDBHandler {
fn open(&self, db_path: &Path) -> Result<Arc<BlockChainDB>, Error> {
fn open(&self, db_path: &Path) -> io::Result<Arc<BlockChainDB>> {
let key_value = Arc::new(kvdb_rocksdb::Database::open(&self.config, &db_path.to_string_lossy())?);
let blooms_path = db_path.join("blooms");
let trace_blooms_path = db_path.join("trace_blooms");
Expand Down
10 changes: 5 additions & 5 deletions local-store/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,16 +56,16 @@ const UPDATE_TIMEOUT: Duration = Duration::from_secs(15 * 60); // once every 15
/// Errors which can occur while using the local data store.
#[derive(Debug)]
pub enum Error {
/// Database errors: these manifest as `String`s.
Database(kvdb::Error),
/// Io and database errors: these manifest as `String`s.
Io(::std::io::Error),
/// JSON errors.
Json(::serde_json::Error),
}

impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::Database(ref val) => write!(f, "{}", val),
Error::Io(ref val) => write!(f, "{}", val),
Error::Json(ref err) => write!(f, "{}", err),
}
}
Expand Down Expand Up @@ -160,7 +160,7 @@ pub struct LocalDataStore<T: NodeInfo> {
impl<T: NodeInfo> LocalDataStore<T> {
/// Attempt to read pending transactions out of the local store.
pub fn pending_transactions(&self) -> Result<Vec<PendingTransaction>, Error> {
if let Some(val) = self.db.get(self.col, LOCAL_TRANSACTIONS_KEY).map_err(Error::Database)? {
if let Some(val) = self.db.get(self.col, LOCAL_TRANSACTIONS_KEY).map_err(Error::Io)? {
let local_txs: Vec<_> = ::serde_json::from_slice::<Vec<TransactionEntry>>(&val)
.map_err(Error::Json)?
.into_iter()
Expand Down Expand Up @@ -200,7 +200,7 @@ impl<T: NodeInfo> LocalDataStore<T> {
let json_str = format!("{}", local_json);

batch.put_vec(self.col, LOCAL_TRANSACTIONS_KEY, json_str.into_bytes());
self.db.write(batch).map_err(Error::Database)
self.db.write(batch).map_err(Error::Io)
}
}

Expand Down
14 changes: 1 addition & 13 deletions parity/db/rocksdb/migration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use std::fs;
use std::io::{Read, Write, Error as IoError, ErrorKind};
use std::path::{Path, PathBuf};
use std::fmt::{Display, Formatter, Error as FmtError};
use super::migration_rocksdb::{self, Manager as MigrationManager, Config as MigrationConfig, ChangeColumns};
use super::migration_rocksdb::{Manager as MigrationManager, Config as MigrationConfig, ChangeColumns};
use super::kvdb_rocksdb::{CompactionProfile, DatabaseConfig};
use ethcore::client::DatabaseCompactionProfile;
use ethcore::{self, db};
Expand Down Expand Up @@ -62,8 +62,6 @@ pub enum Error {
FutureDBVersion,
/// Migration is not possible.
MigrationImpossible,
/// Internal migration error.
Internal(migration_rocksdb::Error),
/// Blooms-db migration error.
BloomsDB(ethcore::error::Error),
/// Migration was completed succesfully,
Expand All @@ -77,7 +75,6 @@ impl Display for Error {
Error::UnknownDatabaseVersion => "Current database version cannot be read".into(),
Error::FutureDBVersion => "Database was created with newer client version. Upgrade your client or delete DB and resync.".into(),
Error::MigrationImpossible => format!("Database migration to version {} is not possible.", CURRENT_VERSION),
Error::Internal(ref err) => format!("{}", err),
Error::BloomsDB(ref err) => format!("blooms-db migration error: {}", err),
Error::Io(ref err) => format!("Unexpected io error on DB migration: {}.", err),
};
Expand All @@ -92,15 +89,6 @@ impl From<IoError> for Error {
}
}

impl From<migration_rocksdb::Error> for Error {
fn from(err: migration_rocksdb::Error) -> Self {
match err.into() {
migration_rocksdb::ErrorKind::Io(e) => Error::Io(e),
err => Error::Internal(err.into()),
}
}
}

/// Returns the version file path.
fn version_file_path(path: &Path) -> PathBuf {
let mut file_path = path.to_owned();
Expand Down
9 changes: 4 additions & 5 deletions parity/db/rocksdb/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,11 @@
extern crate kvdb_rocksdb;
extern crate migration_rocksdb;

use std::fs;
use std::{io, fs};
use std::sync::Arc;
use std::path::Path;
use blooms_db;
use ethcore::{BlockChainDBHandler, BlockChainDB};
use ethcore::error::Error;
use ethcore::db::NUM_COLUMNS;
use ethcore::client::{ClientConfig, DatabaseCompactionProfile};
use kvdb::KeyValueDB;
Expand Down Expand Up @@ -76,7 +75,7 @@ pub fn restoration_db_handler(client_path: &Path, client_config: &ClientConfig)
}

impl BlockChainDBHandler for RestorationDBHandler {
fn open(&self, db_path: &Path) -> Result<Arc<BlockChainDB>, Error> {
fn open(&self, db_path: &Path) -> io::Result<Arc<BlockChainDB>> {
open_database(&db_path.to_string_lossy(), &self.config)
}
}
Expand All @@ -87,7 +86,7 @@ pub fn restoration_db_handler(client_path: &Path, client_config: &ClientConfig)
}

/// Open a new main DB.
pub fn open_db(client_path: &str, cache_config: &CacheConfig, compaction: &DatabaseCompactionProfile, wal: bool) -> Result<Arc<BlockChainDB>, Error> {
pub fn open_db(client_path: &str, cache_config: &CacheConfig, compaction: &DatabaseCompactionProfile, wal: bool) -> io::Result<Arc<BlockChainDB>> {
let path = Path::new(client_path);

let db_config = DatabaseConfig {
Expand All @@ -100,7 +99,7 @@ pub fn open_db(client_path: &str, cache_config: &CacheConfig, compaction: &Datab
open_database(client_path, &db_config)
}

pub fn open_database(client_path: &str, config: &DatabaseConfig) -> Result<Arc<BlockChainDB>, Error> {
pub fn open_database(client_path: &str, config: &DatabaseConfig) -> io::Result<Arc<BlockChainDB>> {
let path = Path::new(client_path);

let blooms_path = path.join("blooms");
Expand Down
Loading