From 017a1adb242981185186fe9ce471efc6017923c4 Mon Sep 17 00:00:00 2001 From: Nikolay Volf Date: Mon, 15 Feb 2016 18:01:52 +0300 Subject: [PATCH] fixing issues and moving --- ethcore/src/error.rs | 36 ++++------------ ethcore/src/lib.rs | 1 - ethcore/src/tests/helpers.rs | 9 ---- util/src/error.rs | 22 ++++++++++ .../src/keys/directory.rs | 42 +++++++++---------- util/src/keys/mod.rs | 19 +++++++++ util/src/lib.rs | 4 ++ util/src/tests/helpers.rs | 31 ++++++++++++++ util/src/tests/mod.rs | 1 + 9 files changed, 105 insertions(+), 60 deletions(-) rename ethcore/src/keys_directory.rs => util/src/keys/directory.rs (96%) create mode 100644 util/src/keys/mod.rs create mode 100644 util/src/tests/helpers.rs create mode 100644 util/src/tests/mod.rs diff --git a/ethcore/src/error.rs b/ethcore/src/error.rs index d441929c5..f75f338bf 100644 --- a/ethcore/src/error.rs +++ b/ethcore/src/error.rs @@ -20,59 +20,39 @@ use util::*; use header::BlockNumber; use basic_types::LogBloom; -#[derive(Debug, PartialEq, Eq)] -/// Error indicating an expected value was not found. -pub struct Mismatch { - /// Value expected. - pub expected: T, - /// Value found. - pub found: T, -} - -#[derive(Debug, PartialEq, Eq)] -/// Error indicating value found is outside of a valid range. -pub struct OutOfBounds { - /// Minimum allowed value. - pub min: Option, - /// Maximum allowed value. - pub max: Option, - /// Value found. - pub found: T, -} - /// Result of executing the transaction. #[derive(PartialEq, Debug)] pub enum ExecutionError { /// Returned when there gas paid for transaction execution is /// lower than base gas required. - NotEnoughBaseGas { + NotEnoughBaseGas { /// Absolute minimum gas required. - required: U256, + required: U256, /// Gas provided. got: U256 }, /// Returned when block (gas_used + gas) > gas_limit. - /// + /// /// If gas =< gas_limit, upstream may try to execute the transaction /// in next block. - BlockGasLimitReached { + BlockGasLimitReached { /// Gas limit of block for transaction. gas_limit: U256, /// Gas used in block prior to transaction. gas_used: U256, /// Amount of gas in block. - gas: U256 + gas: U256 }, /// Returned when transaction nonce does not match state nonce. - InvalidNonce { + InvalidNonce { /// Nonce expected. expected: U256, /// Nonce found. got: U256 }, - /// Returned when cost of transaction (value + gas_price * gas) exceeds + /// Returned when cost of transaction (value + gas_price * gas) exceeds /// current sender balance. - NotEnoughCash { + NotEnoughCash { /// Minimum required balance. required: U512, /// Actual balance. diff --git a/ethcore/src/lib.rs b/ethcore/src/lib.rs index 445cebec0..4cca74319 100644 --- a/ethcore/src/lib.rs +++ b/ethcore/src/lib.rs @@ -108,7 +108,6 @@ pub mod spec; pub mod transaction; pub mod views; pub mod receipt; -pub mod keys_directory; mod common; mod basic_types; diff --git a/ethcore/src/tests/helpers.rs b/ethcore/src/tests/helpers.rs index 77ef57b12..93e3e0a0d 100644 --- a/ethcore/src/tests/helpers.rs +++ b/ethcore/src/tests/helpers.rs @@ -46,15 +46,6 @@ impl RandomTempPath { } } - pub fn create_dir() -> RandomTempPath { - let mut dir = env::temp_dir(); - dir.push(H32::random().hex()); - fs::create_dir_all(dir.as_path()).unwrap(); - RandomTempPath { - path: dir.clone() - } - } - pub fn as_path(&self) -> &PathBuf { &self.path } diff --git a/util/src/error.rs b/util/src/error.rs index 465174b4e..68aa3e648 100644 --- a/util/src/error.rs +++ b/util/src/error.rs @@ -20,6 +20,7 @@ use rustc_serialize::hex::FromHexError; use network::NetworkError; use rlp::DecoderError; use io; +use std::fmt; #[derive(Debug)] /// Error in database subsystem. @@ -55,6 +56,27 @@ pub enum UtilError { BadSize, } + +#[derive(Debug, PartialEq, Eq)] +/// Error indicating an expected value was not found. +pub struct Mismatch { + /// Value expected. + pub expected: T, + /// Value found. + pub found: T, +} + +#[derive(Debug, PartialEq, Eq)] +/// Error indicating value found is outside of a valid range. +pub struct OutOfBounds { + /// Minimum allowed value. + pub min: Option, + /// Maximum allowed value. + pub max: Option, + /// Value found. + pub found: T, +} + impl From for UtilError { fn from(err: FromHexError) -> UtilError { UtilError::FromHex(err) diff --git a/ethcore/src/keys_directory.rs b/util/src/keys/directory.rs similarity index 96% rename from ethcore/src/keys_directory.rs rename to util/src/keys/directory.rs index 1646877b9..c5e17100f 100644 --- a/ethcore/src/keys_directory.rs +++ b/util/src/keys/directory.rs @@ -43,12 +43,11 @@ pub enum Pbkdf2CryptoFunction { } #[derive(Clone)] -#[allow(non_snake_case)] /// Kdf of type `Pbkdf2` /// https://en.wikipedia.org/wiki/PBKDF2 pub struct KdfPbkdf2Params { /// desired length of the derived key, in octets - pub dkLen: u32, + pub dk_len: u32, /// cryptographic salt pub salt: H256, /// number of iterations for derived key @@ -80,14 +79,14 @@ impl KdfPbkdf2Params { Some(unexpected_prf) => { return Err(Pbkdf2ParseError::InvalidPrf(Mismatch { expected: "hmac-sha256".to_owned(), found: unexpected_prf.to_owned() })); }, None => { return Err(Pbkdf2ParseError::InvalidParameter("prf")); }, }, - dkLen: try!(try!(json.get("dklen").ok_or(Pbkdf2ParseError::MissingParameter("dklen"))).as_u64().ok_or(Pbkdf2ParseError::InvalidParameter("dkLen"))) as u32, + dk_len: try!(try!(json.get("dklen").ok_or(Pbkdf2ParseError::MissingParameter("dklen"))).as_u64().ok_or(Pbkdf2ParseError::InvalidParameter("dkLen"))) as u32, c: try!(try!(json.get("c").ok_or(Pbkdf2ParseError::MissingParameter("c"))).as_u64().ok_or(Pbkdf2ParseError::InvalidParameter("c"))) as u32, }) } fn to_json(&self) -> Json { let mut map = BTreeMap::new(); - map.insert("dklen".to_owned(), json_from_u32(self.dkLen)); + map.insert("dklen".to_owned(), json_from_u32(self.dk_len)); map.insert("salt".to_owned(), Json::String(format!("{:?}", self.salt))); map.insert("prf".to_owned(), Json::String("hmac-sha256".to_owned())); map.insert("c".to_owned(), json_from_u32(self.c)); @@ -96,12 +95,11 @@ impl KdfPbkdf2Params { } #[derive(Clone)] -#[allow(non_snake_case)] /// Kdf of type `Scrypt`. /// https://en.wikipedia.org/wiki/Scrypt pub struct KdfScryptParams { /// Desired length of the derived key, in octets. - pub dkLen: u32, + pub dk_len: u32, /// Parallelization parameter. pub p: u32, /// CPU/memory cost parameter. @@ -131,7 +129,7 @@ impl KdfScryptParams { Err(from_hex_error) => { return Err(ScryptParseError::InvalidSaltFormat(from_hex_error)); }, } }, - dkLen: try!(try!(json.get("dklen").ok_or(ScryptParseError::MissingParameter("dklen"))).as_u64().ok_or(ScryptParseError::InvalidParameter("dkLen"))) as u32, + dk_len: try!(try!(json.get("dklen").ok_or(ScryptParseError::MissingParameter("dklen"))).as_u64().ok_or(ScryptParseError::InvalidParameter("dkLen"))) as u32, p: try!(try!(json.get("p").ok_or(ScryptParseError::MissingParameter("p"))).as_u64().ok_or(ScryptParseError::InvalidParameter("p"))) as u32, n: try!(try!(json.get("n").ok_or(ScryptParseError::MissingParameter("n"))).as_u64().ok_or(ScryptParseError::InvalidParameter("n"))) as u32, r: try!(try!(json.get("r").ok_or(ScryptParseError::MissingParameter("r"))).as_u64().ok_or(ScryptParseError::InvalidParameter("r"))) as u32, @@ -140,7 +138,7 @@ impl KdfScryptParams { fn to_json(&self) -> Json { let mut map = BTreeMap::new(); - map.insert("dklen".to_owned(), json_from_u32(self.dkLen)); + map.insert("dklen".to_owned(), json_from_u32(self.dk_len)); map.insert("salt".to_owned(), Json::String(format!("{:?}", self.salt))); map.insert("p".to_owned(), json_from_u32(self.p)); map.insert("n".to_owned(), json_from_u32(self.n)); @@ -267,7 +265,7 @@ impl KeyFileCrypto { cipher_type: CryptoCipherType::Aes128Ctr(iv), cipher_text: cipher_text, kdf: KeyFileKdf::Pbkdf2(KdfPbkdf2Params { - dkLen: dk_len, + dk_len: dk_len, salt: salt, c: c, prf: Pbkdf2CryptoFunction::HMacSha256 @@ -417,10 +415,10 @@ impl KeyFileContent { } #[derive(Debug)] -enum KeyLoadError { - FileTooLarge(OutOfBounds), - FileParseError(KeyFileParseError), - FileReadError(::std::io::Error), +enum KeyFileLoadError { + TooLarge(OutOfBounds), + ParseError(KeyFileParseError), + ReadError(::std::io::Error), } /// Represents directory for saving/loading key files. @@ -510,32 +508,32 @@ impl KeyDirectory { path } - fn load_key(path: &PathBuf) -> Result { + fn load_key(path: &PathBuf) -> Result { match fs::File::open(path.clone()) { Ok(mut open_file) => { match open_file.metadata() { Ok(metadata) => - if metadata.len() > MAX_KEY_FILE_LEN { Err(KeyLoadError::FileTooLarge(OutOfBounds { min: Some(2), max: Some(MAX_KEY_FILE_LEN), found: metadata.len() })) } + if metadata.len() > MAX_KEY_FILE_LEN { Err(KeyFileLoadError::TooLarge(OutOfBounds { min: Some(2), max: Some(MAX_KEY_FILE_LEN), found: metadata.len() })) } else { KeyDirectory::load_from_file(&mut open_file) }, - Err(read_error) => Err(KeyLoadError::FileReadError(read_error)) + Err(read_error) => Err(KeyFileLoadError::ReadError(read_error)) } }, - Err(read_error) => Err(KeyLoadError::FileReadError(read_error)) + Err(read_error) => Err(KeyFileLoadError::ReadError(read_error)) } } - fn load_from_file(file: &mut fs::File) -> Result { + fn load_from_file(file: &mut fs::File) -> Result { let mut buf = String::new(); match file.read_to_string(&mut buf) { Ok(_) => {}, - Err(read_error) => { return Err(KeyLoadError::FileReadError(read_error)); } + Err(read_error) => { return Err(KeyFileLoadError::ReadError(read_error)); } } match Json::from_str(&buf) { Ok(json) => match KeyFileContent::from_json(&json) { Ok(key_file_content) => Ok(key_file_content), - Err(parse_error) => Err(KeyLoadError::FileParseError(parse_error)) + Err(parse_error) => Err(KeyFileLoadError::ParseError(parse_error)) }, - Err(_) => Err(KeyLoadError::FileParseError(KeyFileParseError::InvalidJson)) + Err(_) => Err(KeyFileLoadError::ParseError(KeyFileParseError::InvalidJson)) } } } @@ -1074,7 +1072,7 @@ mod specs { } #[test] - fn csn_store_10_keys() { + fn can_store_10_keys() { let temp_path = RandomTempPath::create_dir(); let mut directory = KeyDirectory::new(&temp_path.as_path()); diff --git a/util/src/keys/mod.rs b/util/src/keys/mod.rs new file mode 100644 index 000000000..d7ffdb0dd --- /dev/null +++ b/util/src/keys/mod.rs @@ -0,0 +1,19 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +//! Key management module + +pub mod directory; diff --git a/util/src/lib.rs b/util/src/lib.rs index 59e9b966c..d4f972800 100644 --- a/util/src/lib.rs +++ b/util/src/lib.rs @@ -141,6 +141,7 @@ pub mod io; pub mod network; pub mod log; pub mod panics; +pub mod keys; pub use common::*; pub use misc::*; @@ -161,3 +162,6 @@ pub use semantic_version::*; pub use network::*; pub use io::*; pub use log::*; + +#[cfg(test)] +mod tests; diff --git a/util/src/tests/helpers.rs b/util/src/tests/helpers.rs new file mode 100644 index 000000000..fee3d2cbb --- /dev/null +++ b/util/src/tests/helpers.rs @@ -0,0 +1,31 @@ +use common::*; +use std::path::PathBuf; +use std::fs::{remove_dir_all}; +use std::env; + +pub struct RandomTempPath { + path: PathBuf +} + +impl RandomTempPath { + pub fn create_dir() -> RandomTempPath { + let mut dir = env::temp_dir(); + dir.push(H32::random().hex()); + fs::create_dir_all(dir.as_path()).unwrap(); + RandomTempPath { + path: dir.clone() + } + } + + pub fn as_path(&self) -> &PathBuf { + &self.path + } +} + +impl Drop for RandomTempPath { + fn drop(&mut self) { + if let Err(e) = remove_dir_all(self.as_path()) { + panic!("failed to remove temp directory, probably something failed to destroyed ({})", e); + } + } +} diff --git a/util/src/tests/mod.rs b/util/src/tests/mod.rs new file mode 100644 index 000000000..1630fabcd --- /dev/null +++ b/util/src/tests/mod.rs @@ -0,0 +1 @@ +pub mod helpers;