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

Commit

Permalink
replace unsafe code with lazy_static
Browse files Browse the repository at this point in the history
  • Loading branch information
ordian committed Feb 3, 2019
1 parent 89819ae commit 7dd399a
Show file tree
Hide file tree
Showing 14 changed files with 68 additions and 41 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ pretty_assertions = "0.1"
ipnetwork = "0.12.6"
tempdir = "0.3"
fake-fetch = { path = "util/fake-fetch" }
lazy_static = "1.2.0"

[target.'cfg(windows)'.dependencies]
winapi = { version = "0.3.4", features = ["winsock2", "winuser", "shellapi"] }
Expand Down
1 change: 1 addition & 0 deletions accounts/ethstore/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ dir = { path = "../../util/dir" }
smallvec = "0.6"
parity-wordlist = "1.0"
tempdir = "0.3"
lazy_static = "1.2.0"

[dev-dependencies]
matches = "0.1"
Expand Down
14 changes: 8 additions & 6 deletions accounts/ethstore/src/account/crypto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,29 +162,31 @@ mod tests {
use ethkey::{Generator, Random};
use super::{Crypto, Error, NonZeroU32};

const ITERATIONS: NonZeroU32 = unsafe { NonZeroU32::new_unchecked(10240) };
lazy_static! {
static ref ITERATIONS: NonZeroU32 = NonZeroU32::new(10240).expect("10240 > 0; qed");
}

#[test]
fn crypto_with_secret_create() {
let keypair = Random.generate().unwrap();
let passwd = "this is sparta".into();
let crypto = Crypto::with_secret(keypair.secret(), &passwd, ITERATIONS).unwrap();
let crypto = Crypto::with_secret(keypair.secret(), &passwd, *ITERATIONS).unwrap();
let secret = crypto.secret(&passwd).unwrap();
assert_eq!(keypair.secret(), &secret);
}

#[test]
fn crypto_with_secret_invalid_password() {
let keypair = Random.generate().unwrap();
let crypto = Crypto::with_secret(keypair.secret(), &"this is sparta".into(), ITERATIONS).unwrap();
let crypto = Crypto::with_secret(keypair.secret(), &"this is sparta".into(), *ITERATIONS).unwrap();
assert_matches!(crypto.secret(&"this is sparta!".into()), Err(Error::InvalidPassword))
}

#[test]
fn crypto_with_null_plain_data() {
let original_data = b"";
let passwd = "this is sparta".into();
let crypto = Crypto::with_plain(&original_data[..], &passwd, ITERATIONS).unwrap();
let crypto = Crypto::with_plain(&original_data[..], &passwd, *ITERATIONS).unwrap();
let decrypted_data = crypto.decrypt(&passwd).unwrap();
assert_eq!(original_data[..], *decrypted_data);
}
Expand All @@ -193,7 +195,7 @@ mod tests {
fn crypto_with_tiny_plain_data() {
let original_data = b"{}";
let passwd = "this is sparta".into();
let crypto = Crypto::with_plain(&original_data[..], &passwd, ITERATIONS).unwrap();
let crypto = Crypto::with_plain(&original_data[..], &passwd, *ITERATIONS).unwrap();
let decrypted_data = crypto.decrypt(&passwd).unwrap();
assert_eq!(original_data[..], *decrypted_data);
}
Expand All @@ -202,7 +204,7 @@ mod tests {
fn crypto_with_huge_plain_data() {
let original_data: Vec<_> = (1..65536).map(|i| (i % 256) as u8).collect();
let passwd = "this is sparta".into();
let crypto = Crypto::with_plain(&original_data, &passwd, ITERATIONS).unwrap();
let crypto = Crypto::with_plain(&original_data, &passwd, *ITERATIONS).unwrap();
let decrypted_data = crypto.decrypt(&passwd).unwrap();
assert_eq!(&original_data, &decrypted_data);
}
Expand Down
11 changes: 7 additions & 4 deletions accounts/ethstore/src/account/safe_account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,14 +203,17 @@ mod tests {
use ethkey::{Generator, Random, verify_public, Message};
use super::{SafeAccount, NonZeroU32};

const ITERATIONS: NonZeroU32 = unsafe { NonZeroU32::new_unchecked(10240) };
lazy_static! {
static ref ITERATIONS: NonZeroU32 = NonZeroU32::new(10240).expect("10240 > 0; qed");
}


#[test]
fn sign_and_verify_public() {
let keypair = Random.generate().unwrap();
let password = "hello world".into();
let message = Message::default();
let account = SafeAccount::create(&keypair, [0u8; 16], &password, ITERATIONS, "Test".to_owned(), "{}".to_owned());
let account = SafeAccount::create(&keypair, [0u8; 16], &password, *ITERATIONS, "Test".to_owned(), "{}".to_owned());
let signature = account.unwrap().sign(&password, &message).unwrap();
assert!(verify_public(keypair.public(), &signature, &message).unwrap());
}
Expand All @@ -221,8 +224,8 @@ mod tests {
let first_password = "hello world".into();
let sec_password = "this is sparta".into();
let message = Message::default();
let account = SafeAccount::create(&keypair, [0u8; 16], &first_password, ITERATIONS, "Test".to_owned(), "{}".to_owned()).unwrap();
let new_account = account.change_password(&first_password, &sec_password, ITERATIONS).unwrap();
let account = SafeAccount::create(&keypair, [0u8; 16], &first_password, *ITERATIONS, "Test".to_owned(), "{}".to_owned()).unwrap();
let new_account = account.change_password(&first_password, &sec_password, *ITERATIONS).unwrap();
assert!(account.sign(&first_password, &message).is_ok());
assert!(account.sign(&sec_password, &message).is_err());
assert!(new_account.sign(&first_password, &message).is_err());
Expand Down
20 changes: 11 additions & 9 deletions accounts/ethstore/src/accounts_dir/disk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -362,7 +362,9 @@ mod test {
use ethkey::{Random, Generator};
use self::tempdir::TempDir;

const ITERATIONS: NonZeroU32 = unsafe { NonZeroU32::new_unchecked(1024) };
lazy_static! {
static ref ITERATIONS: NonZeroU32 = NonZeroU32::new(1024).expect("1024 > 0; qed");
}

#[test]
fn should_create_new_account() {
Expand All @@ -374,7 +376,7 @@ mod test {
let directory = RootDiskDirectory::create(dir.clone()).unwrap();

// when
let account = SafeAccount::create(&keypair, [0u8; 16], &password, ITERATIONS, "Test".to_owned(), "{}".to_owned());
let account = SafeAccount::create(&keypair, [0u8; 16], &password, *ITERATIONS, "Test".to_owned(), "{}".to_owned());
let res = directory.insert(account.unwrap());

// then
Expand All @@ -395,7 +397,7 @@ mod test {
let directory = RootDiskDirectory::create(dir.clone()).unwrap();

// when
let account = SafeAccount::create(&keypair, [0u8; 16], &password, ITERATIONS, "Test".to_owned(), "{}".to_owned()).unwrap();
let account = SafeAccount::create(&keypair, [0u8; 16], &password, *ITERATIONS, "Test".to_owned(), "{}".to_owned()).unwrap();
let filename = "test".to_string();
let dedup = true;

Expand Down Expand Up @@ -431,15 +433,15 @@ mod test {

// and when
let before_root_items_count = fs::read_dir(&dir).unwrap().count();
let vault = directory.as_vault_provider().unwrap().create(vault_name, VaultKey::new(&password, ITERATIONS));
let vault = directory.as_vault_provider().unwrap().create(vault_name, VaultKey::new(&password, *ITERATIONS));

// then
assert!(vault.is_ok());
let after_root_items_count = fs::read_dir(&dir).unwrap().count();
assert!(after_root_items_count > before_root_items_count);

// and when
let vault = directory.as_vault_provider().unwrap().open(vault_name, VaultKey::new(&password, ITERATIONS));
let vault = directory.as_vault_provider().unwrap().open(vault_name, VaultKey::new(&password, *ITERATIONS));

// then
assert!(vault.is_ok());
Expand All @@ -456,9 +458,9 @@ mod test {
let temp_path = TempDir::new("").unwrap();
let directory = RootDiskDirectory::create(&temp_path).unwrap();
let vault_provider = directory.as_vault_provider().unwrap();
const ITER: NonZeroU32 = unsafe { NonZeroU32::new_unchecked(1) };
vault_provider.create("vault1", VaultKey::new(&"password1".into(), ITER)).unwrap();
vault_provider.create("vault2", VaultKey::new(&"password2".into(), ITER)).unwrap();
let iter = NonZeroU32::new(1).expect("1 > 0; qed");
vault_provider.create("vault1", VaultKey::new(&"password1".into(), iter)).unwrap();
vault_provider.create("vault2", VaultKey::new(&"password2".into(), iter)).unwrap();

// then
let vaults = vault_provider.list_vaults().unwrap();
Expand All @@ -480,7 +482,7 @@ mod test {

let keypair = Random.generate().unwrap();
let password = "test pass".into();
let account = SafeAccount::create(&keypair, [0u8; 16], &password, ITERATIONS, "Test".to_owned(), "{}".to_owned());
let account = SafeAccount::create(&keypair, [0u8; 16], &password, *ITERATIONS, "Test".to_owned(), "{}".to_owned());
directory.insert(account.unwrap()).expect("Account should be inserted ok");

let new_hash = directory.files_hash().expect("New files hash should be calculated ok");
Expand Down
17 changes: 10 additions & 7 deletions accounts/ethstore/src/accounts_dir/vault.rs
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,10 @@ mod test {
use super::{VAULT_FILE_NAME, check_vault_name, make_vault_dir_path, create_vault_file, read_vault_file, VaultDiskDirectory};
use self::tempdir::TempDir;

const ITERATIONS: NonZeroU32 = unsafe { NonZeroU32::new_unchecked(1024) };

lazy_static! {
static ref ITERATIONS: NonZeroU32 = NonZeroU32::new(1024).expect("1024 > 0; qed");
}

#[test]
fn check_vault_name_succeeds() {
Expand Down Expand Up @@ -328,7 +331,7 @@ mod test {
fn create_vault_file_succeeds() {
// given
let temp_path = TempDir::new("").unwrap();
let key = VaultKey::new(&"password".into(), ITERATIONS);
let key = VaultKey::new(&"password".into(), *ITERATIONS);
let mut vault_dir: PathBuf = temp_path.path().into();
vault_dir.push("vault");
fs::create_dir_all(&vault_dir).unwrap();
Expand All @@ -347,7 +350,7 @@ mod test {
fn read_vault_file_succeeds() {
// given
let temp_path = TempDir::new("").unwrap();
let key = VaultKey::new(&"password".into(), ITERATIONS);
let key = VaultKey::new(&"password".into(), *ITERATIONS);
let vault_file_contents = r#"{"crypto":{"cipher":"aes-128-ctr","cipherparams":{"iv":"758696c8dc6378ab9b25bb42790da2f5"},"ciphertext":"54eb50683717d41caaeb12ea969f2c159daada5907383f26f327606a37dc7168","kdf":"pbkdf2","kdfparams":{"c":1024,"dklen":32,"prf":"hmac-sha256","salt":"3c320fa566a1a7963ac8df68a19548d27c8f40bf92ef87c84594dcd5bbc402b6"},"mac":"9e5c2314c2a0781962db85611417c614bd6756666b6b1e93840f5b6ed895f003"}}"#;
let dir: PathBuf = temp_path.path().into();
let mut vault_file_path: PathBuf = dir.clone();
Expand All @@ -368,7 +371,7 @@ mod test {
fn read_vault_file_fails() {
// given
let temp_path = TempDir::new("").unwrap();
let key = VaultKey::new(&"password1".into(), ITERATIONS);
let key = VaultKey::new(&"password1".into(), *ITERATIONS);
let dir: PathBuf = temp_path.path().into();
let mut vault_file_path: PathBuf = dir.clone();
vault_file_path.push(VAULT_FILE_NAME);
Expand Down Expand Up @@ -397,7 +400,7 @@ mod test {
fn vault_directory_can_be_created() {
// given
let temp_path = TempDir::new("").unwrap();
let key = VaultKey::new(&"password".into(), ITERATIONS);
let key = VaultKey::new(&"password".into(), *ITERATIONS);
let dir: PathBuf = temp_path.path().into();

// when
Expand All @@ -417,7 +420,7 @@ mod test {
fn vault_directory_cannot_be_created_if_already_exists() {
// given
let temp_path = TempDir::new("").unwrap();
let key = VaultKey::new(&"password".into(), ITERATIONS);
let key = VaultKey::new(&"password".into(), *ITERATIONS);
let dir: PathBuf = temp_path.path().into();
let mut vault_dir = dir.clone();
vault_dir.push("vault");
Expand All @@ -434,7 +437,7 @@ mod test {
fn vault_directory_cannot_be_opened_if_not_exists() {
// given
let temp_path = TempDir::new("").unwrap();
let key = VaultKey::new(&"password".into(), ITERATIONS);
let key = VaultKey::new(&"password".into(), *ITERATIONS);
let dir: PathBuf = temp_path.path().into();

// when
Expand Down
9 changes: 6 additions & 3 deletions accounts/ethstore/src/ethstore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,10 @@ use json::{self, Uuid, OpaqueKeyFile};
use {import, Error, SimpleSecretStore, SecretStore, SecretVaultRef, StoreAccountRef, Derivation, OpaqueSecret};


const KEY_ITERATIONS: NonZeroU32 = unsafe { NonZeroU32::new_unchecked(crypto::KEY_ITERATIONS as u32) };
lazy_static! {
static ref KEY_ITERATIONS: NonZeroU32 =
NonZeroU32::new(crypto::KEY_ITERATIONS as u32).expect("KEY_ITERATIONS > 0; qed");
}

/// Accounts store.
pub struct EthStore {
Expand All @@ -40,7 +43,7 @@ pub struct EthStore {
impl EthStore {
/// Open a new accounts store with given key directory backend.
pub fn open(directory: Box<KeyDirectory>) -> Result<Self, Error> {
Self::open_with_iterations(directory, KEY_ITERATIONS)
Self::open_with_iterations(directory, *KEY_ITERATIONS)
}

/// Open a new account store with given key directory backend and custom number of iterations.
Expand Down Expand Up @@ -276,7 +279,7 @@ struct Timestamp {
impl EthMultiStore {
/// Open new multi-accounts store with given key directory backend.
pub fn open(directory: Box<KeyDirectory>) -> Result<Self, Error> {
Self::open_with_iterations(directory, KEY_ITERATIONS)
Self::open_with_iterations(directory, *KEY_ITERATIONS)
}

/// Open new multi-accounts store with given key directory backend and custom number of iterations for new keys.
Expand Down
8 changes: 5 additions & 3 deletions accounts/ethstore/src/json/vault_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,9 @@ mod test {
use json::{VaultFile, Crypto, Cipher, Aes128Ctr, Kdf, Pbkdf2, Prf};
use std::num::NonZeroU32;

const ITERATIONS: NonZeroU32 = unsafe { NonZeroU32::new_unchecked(1024) };
lazy_static! {
static ref ITERATIONS: NonZeroU32 = NonZeroU32::new(1024).expect("1024 > 0; qed");
}

#[test]
fn to_and_from_json() {
Expand All @@ -54,7 +56,7 @@ mod test {
}),
ciphertext: "4d6938a1f49b7782".into(),
kdf: Kdf::Pbkdf2(Pbkdf2 {
c: ITERATIONS,
c: *ITERATIONS,
dklen: 32,
prf: Prf::HmacSha256,
salt: "b6a9338a7ccd39288a86dba73bfecd9101b4f3db9c9830e7c76afdbd4f6872e5".into(),
Expand All @@ -79,7 +81,7 @@ mod test {
}),
ciphertext: "4d6938a1f49b7782".into(),
kdf: Kdf::Pbkdf2(Pbkdf2 {
c: ITERATIONS,
c: *ITERATIONS,
dklen: 32,
prf: Prf::HmacSha256,
salt: "b6a9338a7ccd39288a86dba73bfecd9101b4f3db9c9830e7c76afdbd4f6872e5".into(),
Expand Down
8 changes: 5 additions & 3 deletions accounts/ethstore/src/json/vault_key_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,9 @@ mod test {
insert_vault_name_to_json_meta, remove_vault_name_from_json_meta};
use std::num::NonZeroU32;

const ITERATIONS: NonZeroU32 = unsafe { NonZeroU32::new_unchecked(10240) };
lazy_static! {
static ref ITERATIONS: NonZeroU32 = NonZeroU32::new(10240).expect("10240 > 0; qed");
}

#[test]
fn to_and_from_json() {
Expand All @@ -121,7 +123,7 @@ mod test {
}),
ciphertext: "4befe0a66d9a4b6fec8e39eb5c90ac5dafdeaab005fff1af665fd1f9af925c91".into(),
kdf: Kdf::Pbkdf2(Pbkdf2 {
c: ITERATIONS,
c: *ITERATIONS,
dklen: 32,
prf: Prf::HmacSha256,
salt: "f17731e84ecac390546692dbd4ccf6a3a2720dc9652984978381e61c28a471b2".into(),
Expand All @@ -134,7 +136,7 @@ mod test {
}),
ciphertext: "fef0d113d7576c1702daf380ad6f4c5408389e57991cae2a174facd74bd549338e1014850bddbab7eb486ff5f5c9c5532800c6a6d4db2be2212cd5cd3769244ab230e1f369e8382a9e6d7c0a".into(),
kdf: Kdf::Pbkdf2(Pbkdf2 {
c: ITERATIONS,
c: *ITERATIONS,
dklen: 32,
prf: Prf::HmacSha256,
salt: "aca82865174a82249a198814b263f43a631f272cbf7ed329d0f0839d259c652a".into(),
Expand Down
2 changes: 2 additions & 0 deletions accounts/ethstore/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ extern crate ethereum_types;
extern crate ethkey as _ethkey;
extern crate parity_wordlist;

#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
#[macro_use]
Expand Down
4 changes: 2 additions & 2 deletions accounts/ethstore/src/presale.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,8 @@ impl PresaleWallet {
let mut derived_key = [0u8; 32];
let salt = pbkdf2::Salt(password.as_bytes());
let sec = pbkdf2::Secret(password.as_bytes());
const ITER: NonZeroU32 = unsafe { NonZeroU32::new_unchecked(2000) };
pbkdf2::sha256(ITER, salt, sec, &mut derived_key);
let iter = NonZeroU32::new(2000).expect("2000 > 0; qed");
pbkdf2::sha256(iter, salt, sec, &mut derived_key);

let mut key = vec![0; self.ciphertext.len()];
let len = crypto::aes::decrypt_128_cbc(&derived_key[0..16], &self.iv, &self.ciphertext, &mut key)
Expand Down
8 changes: 5 additions & 3 deletions parity/configuration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1217,7 +1217,9 @@ mod tests {

use super::*;

const ITERATIONS: NonZeroU32 = unsafe { NonZeroU32::new_unchecked(10240) };
lazy_static! {
static ref ITERATIONS: NonZeroU32 = NonZeroU32::new(10240).expect("10240 > 0; qed");
}

#[derive(Debug, PartialEq)]
struct TestPasswordReader(&'static str);
Expand All @@ -1240,7 +1242,7 @@ mod tests {
let args = vec!["parity", "account", "new"];
let conf = parse(&args);
assert_eq!(conf.into_command().unwrap().cmd, Cmd::Account(AccountCmd::New(NewAccount {
iterations: ITERATIONS,
iterations: *ITERATIONS,
path: Directories::default().keys,
password_file: None,
spec: SpecType::default(),
Expand Down Expand Up @@ -1275,7 +1277,7 @@ mod tests {
let args = vec!["parity", "wallet", "import", "my_wallet.json", "--password", "pwd"];
let conf = parse(&args);
assert_eq!(conf.into_command().unwrap().cmd, Cmd::ImportPresaleWallet(ImportWallet {
iterations: ITERATIONS,
iterations: *ITERATIONS,
path: Directories::default().keys,
wallet_path: "my_wallet.json".into(),
password_file: Some("pwd".into()),
Expand Down
4 changes: 4 additions & 0 deletions parity/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,10 @@ extern crate pretty_assertions;
#[cfg(test)]
extern crate tempdir;

#[cfg(test)]
#[macro_use]
extern crate lazy_static;

mod account;
mod blockchain;
mod cache;
Expand Down
2 changes: 1 addition & 1 deletion parity/params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ pub struct AccountsConfig {
impl Default for AccountsConfig {
fn default() -> Self {
AccountsConfig {
iterations: unsafe { NonZeroU32::new_unchecked(10240) },
iterations: NonZeroU32::new(10240).expect("10240 > 0; qed"),
refresh_time: 5,
testnet: false,
password_files: Vec::new(),
Expand Down

0 comments on commit 7dd399a

Please sign in to comment.