mirror of
https://github.com/logos-blockchain/logos-execution-zone.git
synced 2026-03-24 03:03:09 +00:00
55 lines
1.2 KiB
Rust
55 lines
1.2 KiB
Rust
use rand::{Rng, rngs::OsRng};
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
use crate::error::NssaError;
|
|
|
|
// TODO: Remove Debug, Clone, Serialize, Deserialize, PartialEq and Eq for security reasons
|
|
// TODO: Implement Zeroize
|
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
|
pub struct PrivateKey([u8; 32]);
|
|
|
|
impl PrivateKey {
|
|
pub fn new_os_random() -> Self {
|
|
let mut rng = OsRng;
|
|
|
|
loop {
|
|
match Self::try_new(rng.r#gen()) {
|
|
Ok(key) => break key,
|
|
Err(_) => continue,
|
|
};
|
|
}
|
|
}
|
|
|
|
fn is_valid_key(value: [u8; 32]) -> bool {
|
|
secp256k1::SecretKey::from_byte_array(value).is_ok()
|
|
}
|
|
|
|
pub fn try_new(value: [u8; 32]) -> Result<Self, NssaError> {
|
|
if Self::is_valid_key(value) {
|
|
Ok(Self(value))
|
|
} else {
|
|
Err(NssaError::InvalidPrivateKey)
|
|
}
|
|
}
|
|
|
|
pub fn value(&self) -> &[u8; 32] {
|
|
&self.0
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
#[test]
|
|
fn test_value_getter() {
|
|
let key = PrivateKey::try_new([1; 32]).unwrap();
|
|
assert_eq!(key.value(), &key.0);
|
|
}
|
|
|
|
#[test]
|
|
fn test_produce_key() {
|
|
let key = PrivateKey::new_os_random();
|
|
println!("{:?}", key.0);
|
|
}
|
|
}
|