Skip to content

Commit

Permalink
changes, optimizations
Browse files Browse the repository at this point in the history
  • Loading branch information
anupsv committed Jan 23, 2025
1 parent 522e8cc commit 08cf9f5
Show file tree
Hide file tree
Showing 13 changed files with 165 additions and 85 deletions.
28 changes: 28 additions & 0 deletions .github/workflows/rust.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
name: Rust

on:
push:
branches: [ "master" ]
pull_request:
branches: [ "*" ]

env:
CARGO_TERM_COLOR: always

jobs:
build:

runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
- name: Build
run: cargo build --verbose
- name: Fmt check
run: cargo fmt --all -- --check
- name: Clippy Format test
run: cargo clippy --all --manifest-path Cargo.toml -- -D warnings
- name: Run tests
run: cargo test --verbose


2 changes: 1 addition & 1 deletion Cargo.lock

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

17 changes: 13 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ version = "0.2.1"
edition = "2021"
license = "MIT"
readme = "README.md"
rust-version = "1.79"
rust-version = "1.81"
keywords = ["cryptography", "BLS", "BN254", "ethereum", "signature"]
categories = ["cryptography"]
exclude = [
Expand Down Expand Up @@ -69,8 +69,17 @@ path = "tests/tree_tests.rs"
name = "path"
path = "tests/path_tests.rs"




[workspace]
members = ["."]

[profile.test]
opt-level = 3
debug = true
strip = "none"
debug-assertions = false
overflow-checks = false
lto = false
panic = 'unwind'
incremental = false
codegen-units = 16
rpath = false
5 changes: 5 additions & 0 deletions rust-toolchain
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
[toolchain]
channel = '1.81'
profile = 'minimal'
components = ['clippy', 'rustfmt']
targets = ["x86_64-unknown-linux-gnu", "x86_64-pc-windows-gnu", "wasm32-unknown-unknown", "aarch64-apple-darwin"]
2 changes: 1 addition & 1 deletion src/consts.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
pub const BITS: usize = 254;
pub const BN254_CURVE_ORDER: &str =
"52435875175126190479447740508185965837690552500527637822603658699938581184513"; // change to actual
"52435875175126190479447740508185965837690552500527637822603658699938581184513";
pub const SUPPORTED_LANGUAGES: [&str; 8] = [
"english",
"chinese_simplified",
Expand Down
71 changes: 31 additions & 40 deletions src/errors.rs
Original file line number Diff line number Diff line change
@@ -1,87 +1,78 @@
use std::{error::Error, fmt, io};
use std::fmt;

use hex::FromHexError;
use serde_json::Error as SerdeError;
use thiserror::Error as ErrorThis;
use thiserror::Error;

#[derive(Debug)]
#[derive(Debug, Error)]
pub enum BLSError {
#[error("Signature not in subgroup")]
SignatureNotInSubgroup,
#[error("Signature array is empty")]
SignatureListEmpty,
#[error("Public key not in subgroup")]
PublicKeyNotInSubgroup,
#[error("The public key list is empty")]
PublicKeyListEmpty,
}

impl Error for BLSError {}

impl fmt::Display for BLSError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
BLSError::SignatureNotInSubgroup => write!(f, "Signature not in subgroup"),
BLSError::PublicKeyNotInSubgroup => write!(f, "Public key not in subgroup"),
BLSError::SignatureListEmpty => write!(f, "Signature array is empty"),
BLSError::PublicKeyListEmpty => write!(f, "The public key list is empty"),
}
}
}

#[derive(ErrorThis, Debug)]
#[derive(Error, Debug)]
pub enum KeystoreError {
#[error("Invalid KDF function provided.")]
#[error("Invalid KDF function provided")]
WrongKdfFunction,

#[error("Serde serialization/deserialization error: {0}")]
#[error("Invalid KDF parameters")]
WrongKDFParameters,

#[error(transparent)]
SerdeError(#[from] SerdeError),

#[error("Hex decode error: {0}")]
#[error(transparent)]
FromHexError(#[from] FromHexError),

#[error("IO Error error: {0}")]
IOError(#[from] io::Error),

#[error("Invalid KDF parameters.")]
WrongKDFParameters,
#[error(transparent)]
IOError(#[from] std::io::Error),

#[error("Derive Child Sk Error error: {0}")]
#[error("Failed to derive child secret key: {0}")]
DeriveChildSkError(String),

#[error("Derive Master Sk Error error: {0}")]
#[error("Failed to derive master secret key: {0}")]
DeriveMasterSkError(String),

#[error("Generic error: {0}")]
#[error("{0}")]
GenericError(String),

#[error("Scrypt Error: {0}")]
#[error("Scrypt error: {0}")]
ScryptError(String),

#[error("PBKDF2 Error: {0}")]
#[error("PBKDF2 error: {0}")]
PBKDF2Error(String),

#[error("Encryption Error: {0}")]
#[error("Encryption error: {0}")]
EncryptionError(String),

#[error("Decryption Error: {0}")]
#[error("Decryption error: {0}")]
DecryptionError(String),

#[error("Path to nodes Error: {0}")]
#[error("Invalid path to nodes: {0}")]
PathToNodes(String),

#[error("Reconstruct mnemonic Error: {0}")]
#[error("Failed to reconstruct mnemonic: {0}")]
ReconstructMnemonicError(String),

#[error("Mnemonic Error: {0}")]
#[error("Mnemonic error: {0}")]
MnemonicError(String),
}

impl KeystoreError {
// Function to map other errors to GenericError
pub fn from<E: fmt::Display>(error: E) -> KeystoreError {
KeystoreError::GenericError(error.to_string())
/// Converts any error that implements Display into a KeystoreError::GenericError
pub fn from<E: fmt::Display>(error: E) -> Self {
Self::GenericError(error.to_string())
}
}

impl From<&str> for KeystoreError {
fn from(err: &str) -> KeystoreError {
KeystoreError::GenericError(err.to_string())
fn from(err: &str) -> Self {
Self::GenericError(err.to_string())
}
}
6 changes: 3 additions & 3 deletions src/keystores/base_keystore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ pub struct KeystoreCrypto {
impl KeystoreCrypto {
fn from_json(json_dict: &Map<String, Value>) -> Result<Self, KeystoreError> {
let kdf: KeystoreModule =
serde_json::from_value(json_dict["kdf"].clone()).map_err(|e| KeystoreError::from(e))?;
serde_json::from_value(json_dict["kdf"].clone()).map_err(KeystoreError::from)?;
let checksum: KeystoreModule = serde_json::from_value(json_dict["checksum"].clone())?;
let cipher: KeystoreModule = serde_json::from_value(json_dict["cipher"].clone())?;
Ok(Self {
Expand Down Expand Up @@ -168,9 +168,9 @@ impl Keystore {
}

pub fn from_file(path: &str) -> Result<Self, KeystoreError> {
let file_content = fs::read_to_string(path).map_err(|e| KeystoreError::from(e))?;
let file_content = fs::read_to_string(path).map_err(KeystoreError::from)?;
let json_dict: HashMap<String, serde_json::Value> = serde_json::from_str(&file_content)?;
Ok(Self::from_json(&json_dict)?)
Self::from_json(&json_dict)
}

/// Encode password as NFKD UTF-8 as per:
Expand Down
6 changes: 6 additions & 0 deletions src/keystores/pbkdf2_keystore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@ use std::collections::HashMap;
#[derive(Debug, Serialize, Deserialize)]
pub struct Pbkdf2Keystore(pub(crate) Keystore);

impl Default for Pbkdf2Keystore {
fn default() -> Self {
Self::new()
}
}

impl Pbkdf2Keystore {
pub fn new() -> Self {
let keystore = Keystore {
Expand Down
7 changes: 7 additions & 0 deletions src/keystores/scrypt_keystore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,14 @@ use super::base_keystore::{Keystore, KeystoreCrypto, KeystoreModule};
#[derive(Debug, Serialize, Deserialize)]
pub struct ScryptKeystore(Keystore);

impl Default for ScryptKeystore {
fn default() -> Self {
Self::new()
}
}

impl ScryptKeystore {

pub fn new() -> Self {
let keystore = Keystore {
crypto: KeystoreCrypto {
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -218,8 +218,8 @@ pub fn aggregate_public_keys(public_keys: &[G2Affine]) -> Result<G2Affine, BLSEr
#[cfg(test)]
mod test {
use super::*;
use ark_ec::AdditiveGroup;
use ark_bn254::G2Projective;
use ark_ec::AdditiveGroup;
use ark_ff::UniformRand;
use ark_std::{ops::Mul, test_rng};

Expand Down
21 changes: 10 additions & 11 deletions src/mnemonics/mnemonic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ impl Mnemonic {
fn abbreviate_words(words: &[String]) -> Vec<String> {
words
.iter()
.map(|word| Self::abbreviate_word(word))
.map(Self::abbreviate_word)
.collect()
}

Expand All @@ -85,7 +85,7 @@ impl Mnemonic {
let mut word_language_map: HashMap<String, String> = HashMap::new();

for lang in languages {
let abbrev_word_list = Self::get_word_list(&lang, words_path)?;
let abbrev_word_list = Self::get_word_list(lang, words_path)?;
for word in abbrev_word_list {
word_language_map.insert(word.clone(), lang.to_string());
}
Expand All @@ -112,9 +112,9 @@ impl Mnemonic {
}

if found < mnemonic_list.len() {
return Err(KeystoreError::MnemonicError(format!(
"A Word was not found in any mnemonic word lists."
)));
return Err(KeystoreError::MnemonicError(
"A Word was not found in any mnemonic word lists.".to_string()
));
}

Ok(word_languages.into_iter().collect())
Expand Down Expand Up @@ -150,7 +150,7 @@ impl Mnemonic {
let checksum_length = entropy_length / 32;
let checksum = Self::get_checksum(&entropy);
let mut entropy_bits = BigUint::from_bytes_be(&entropy) << checksum_length;
entropy_bits += BigUint::from(checksum);
entropy_bits += checksum;
let total_length = entropy_length + checksum_length;

let word_list = Self::load_word_list(language, words_path);
Expand Down Expand Up @@ -182,7 +182,7 @@ impl Mnemonic {
let checksum_length = entropy_length / 32;
let checksum = Self::get_checksum(&entropy);
let mut entropy_bits = BigUint::from_bytes_be(&entropy) << checksum_length;
entropy_bits += BigUint::from(checksum);
entropy_bits += checksum;
let total_length = entropy_length + checksum_length;

let word_list = Self::load_word_list_without_path(words_list);
Expand Down Expand Up @@ -213,8 +213,7 @@ impl Mnemonic {
let checksum_length = entropy.len() / 4;
let hash = Sha256::digest(entropy);
let hash_biguint = BigUint::from_bytes_be(&hash);
let checksum = hash_biguint >> (256 - checksum_length);
checksum
hash_biguint >> (256 - checksum_length)
}

/// Given a mnemonic, a reconstructed the full version (incase the
Expand Down Expand Up @@ -277,7 +276,7 @@ impl Mnemonic {
let full_word_list = Self::get_word_list(&language, words_path)?;

if Self::get_checksum(&entropy_bytes) == checksum {
if let Some(_) = reconstructed_mnemonic {
if reconstructed_mnemonic.is_some() {
return Err(KeystoreError::ReconstructMnemonicError(
"Mnemonic is valid in multiple languages.".into(),
));
Expand All @@ -294,7 +293,7 @@ impl Mnemonic {

reconstructed_mnemonic.ok_or_else(|| {
KeystoreError::ReconstructMnemonicError(
format!("Failed to reconstruct mnemonic. {}", mnemonic).into(),
format!("Failed to reconstruct mnemonic. {}", mnemonic),
)
})
}
Expand Down
Loading

0 comments on commit 08cf9f5

Please sign in to comment.