pub const METHOD: &str = "raw_rand";
const ARGUMENTS: &[u8] = b"DIDL\0\0";
const HEADER: &[u8] = b"DIDL\x01\x6d\x7b\x01\x00";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Error {
ByteLimit,
Framing,
Length,
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "raw_rand protocol refusal: {self:?}")
}
}
impl std::error::Error for Error {}
pub fn encode(maximum_bytes: usize) -> Result<&'static [u8], Error> {
if maximum_bytes < ARGUMENTS.len() {
Err(Error::ByteLimit)
} else {
Ok(ARGUMENTS)
}
}
pub fn decode(bytes: &[u8], maximum_bytes: usize) -> Result<[u8; 32], Error> {
if bytes.len() > maximum_bytes {
return Err(Error::ByteLimit);
}
if bytes.len() != 42 {
return Err(Error::Length);
}
if !bytes.starts_with(HEADER) {
return Err(Error::Framing);
}
if bytes[9] != 32 {
return Err(Error::Length);
}
let mut seed = [0; 32];
seed.copy_from_slice(&bytes[10..]);
Ok(seed)
}
#[cfg(test)]
mod tests;