use dig_keystore::{
opaque, BackendKey, BlsSigning, KdfParams, KeyScheme, KeychainBackend, KeystoreError, Password,
};
use zeroize::Zeroizing;
use crate::master_seed::ENTROPY_LEN;
use crate::{Result, SessionError};
const VERSION_V1: u8 = 0x01;
const ENVELOPE_LEN: usize = 2 + ENTROPY_LEN;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Kind {
Bip39Entropy = 0x01,
}
impl Kind {
fn from_byte(byte: u8) -> Result<Self> {
match byte {
x if x == Kind::Bip39Entropy as u8 => Ok(Kind::Bip39Entropy),
unknown => Err(SessionError::UnsupportedSeedKind(unknown)),
}
}
}
pub(crate) fn write_bip39_entropy(
backend: &dyn KeychainBackend,
path: &BackendKey,
password: &Password,
entropy: &[u8; ENTROPY_LEN],
) -> Result<()> {
if backend.exists(path)? {
return Err(KeystoreError::AlreadyExists(path.as_str().to_string()).into());
}
let mut plaintext = Zeroizing::new(Vec::with_capacity(ENVELOPE_LEN));
plaintext.push(VERSION_V1);
plaintext.push(Kind::Bip39Entropy as u8);
plaintext.extend_from_slice(entropy);
let blob = opaque::seal(password, &plaintext, KdfParams::DEFAULT)?;
backend.write(path, &blob)?;
Ok(())
}
pub(crate) fn read_bip39_entropy(
backend: &dyn KeychainBackend,
path: &BackendKey,
password: &Password,
) -> Result<Zeroizing<[u8; ENTROPY_LEN]>> {
let blob = backend.read(path)?;
if blob.starts_with(&BlsSigning::MAGIC) {
return Err(SessionError::LegacySeedFormat);
}
let plaintext = opaque::open(password, &blob)?;
if plaintext.len() != ENVELOPE_LEN {
return Err(KeystoreError::InvalidPlaintext {
expected: ENVELOPE_LEN,
got: plaintext.len(),
}
.into());
}
if plaintext[0] != VERSION_V1 {
return Err(SessionError::UnsupportedEnvelopeVersion(plaintext[0]));
}
Kind::from_byte(plaintext[1])?;
let mut entropy = Zeroizing::new([0u8; ENTROPY_LEN]);
entropy.copy_from_slice(&plaintext[2..]);
Ok(entropy)
}