use std::fmt::Write as _;
use std::path::Path;
use bech32::{Bech32, Hrp};
use stratum_node_core::{NostrSecretKey, ParseKeyError};
use zeroize::Zeroizing;
use crate::private_file::{self, ModePolicy, PrivateFileError};
const NSEC_HRP: &str = "nsec";
const NSEC_LEN: usize = 63;
const KEY_FILE_LIMIT: usize = 128;
const MAX_GENERATE_ATTEMPTS: usize = 8;
pub fn generate_key_file(path: &Path) -> Result<NostrSecretKey, KeyFileError> {
let mut bytes = Zeroizing::new([0u8; 32]);
let mut key = None;
for _ in 0..MAX_GENERATE_ATTEMPTS {
getrandom::fill(bytes.as_mut_slice()).map_err(|_| KeyFileError::RandomUnavailable)?;
if let Ok(candidate) = NostrSecretKey::from_bytes(&bytes) {
key = Some(candidate);
break;
}
}
let key = key.ok_or(KeyFileError::RandomUnavailable)?;
let mut line = Zeroizing::new(String::with_capacity(NSEC_LEN + 1));
let hrp = Hrp::parse_unchecked(NSEC_HRP);
bech32::encode_lower_to_fmt::<Bech32, _>(&mut *line, hrp, bytes.as_slice())
.map_err(|_| KeyFileError::Encoding)?;
line.write_char('\n').map_err(|_| KeyFileError::Encoding)?;
private_file::create(path, line.as_bytes()).map_err(KeyFileError::File)?;
Ok(key)
}
pub fn load_key_file(path: &Path) -> Result<NostrSecretKey, KeyFileError> {
let contents = private_file::read(path, KEY_FILE_LIMIT, ModePolicy::OwnerOnly)
.map_err(KeyFileError::File)?;
let text = std::str::from_utf8(&contents).map_err(|_| KeyFileError::NotOneLine)?;
let line = text
.strip_suffix("\r\n")
.or_else(|| text.strip_suffix('\n'))
.unwrap_or(text);
if line.contains(['\n', '\r']) {
return Err(KeyFileError::NotOneLine);
}
NostrSecretKey::from_nsec(line).map_err(KeyFileError::InvalidKey)
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum KeyFileError {
#[error(transparent)]
File(PrivateFileError),
#[error("key file must hold exactly one nsec line")]
NotOneLine,
#[error("key file does not hold a valid nsec key")]
InvalidKey(#[source] ParseKeyError),
#[error("the system random source is unavailable")]
RandomUnavailable,
#[error("the key could not be encoded as nsec")]
Encoding,
}