use crate::crypto::pbkdf2;
use crate::keyphrase::KeyPhrase;
use std::fmt;
#[derive(Clone)]
pub struct Seed {
bytes: Vec<u8>,
}
impl Seed {
pub fn new(keyphrase: &KeyPhrase, password: &str) -> Self {
let salt: String = format!("keyphrase{}", password);
let bytes: Vec<u8> = pbkdf2(keyphrase.entropy(), &salt);
Self { bytes }
}
pub fn as_bytes(&self) -> &[u8] {
&self.bytes
}
}
impl AsRef<[u8]> for Seed {
fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
}
impl fmt::Debug for Seed {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:#X}", self)
}
}
impl fmt::LowerHex for Seed {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if f.alternate() {
f.write_str("0x")?;
}
for byte in &self.bytes {
write!(f, "{:02x}", byte)?;
}
Ok(())
}
}
impl fmt::UpperHex for Seed {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if f.alternate() {
f.write_str("0x")?;
}
for byte in &self.bytes {
write!(f, "{:02X}", byte)?;
}
Ok(())
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn should_print_upper_hex_correctly() {
let seed = Seed {
bytes: vec![1, 10, 16, 255],
};
let hex = format!("{:?}", seed);
assert_eq!(hex, "0x010A10FF")
}
#[test]
fn should_print_lower_hex_correctly() {
let seed = Seed {
bytes: vec![255, 16, 10, 1],
};
let hex = format!("{:x}", seed);
assert_eq!(hex, "ff100a01")
}
}