fixing issues and moving

This commit is contained in:
Nikolay Volf 2016-02-15 18:01:52 +03:00
parent 31762095b7
commit 017a1adb24
9 changed files with 105 additions and 60 deletions

View File

@ -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<T: fmt::Debug> {
/// 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<T: fmt::Debug> {
/// Minimum allowed value.
pub min: Option<T>,
/// Maximum allowed value.
pub max: Option<T>,
/// 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.

View File

@ -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;

View File

@ -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
}

View File

@ -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<T: fmt::Debug> {
/// 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<T: fmt::Debug> {
/// Minimum allowed value.
pub min: Option<T>,
/// Maximum allowed value.
pub max: Option<T>,
/// Value found.
pub found: T,
}
impl From<FromHexError> for UtilError {
fn from(err: FromHexError) -> UtilError {
UtilError::FromHex(err)

View File

@ -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<u64>),
FileParseError(KeyFileParseError),
FileReadError(::std::io::Error),
enum KeyFileLoadError {
TooLarge(OutOfBounds<u64>),
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<KeyFileContent, KeyLoadError> {
fn load_key(path: &PathBuf) -> Result<KeyFileContent, KeyFileLoadError> {
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<KeyFileContent, KeyLoadError> {
fn load_from_file(file: &mut fs::File) -> Result<KeyFileContent, KeyFileLoadError> {
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());

19
util/src/keys/mod.rs Normal file
View File

@ -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 <http://www.gnu.org/licenses/>.
//! Key management module
pub mod directory;

View File

@ -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;

31
util/src/tests/helpers.rs Normal file
View File

@ -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);
}
}
}

1
util/src/tests/mod.rs Normal file
View File

@ -0,0 +1 @@
pub mod helpers;