use super::Grade;
pub mod claim;
pub mod store;
pub(crate) mod wire;
pub const ALPHABET: &[u8; 32] = b"ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
pub const CODE_LEN: usize = 8;
pub const WORD_LEN: usize = 6;
pub const LIFE: i64 = 600;
pub const PATH: &str = "/yog/register/";
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Verb {
Mint {
workspace: String,
name: String,
grade: Grade,
},
List { workspace: String },
Approve { workspace: String, name: String },
Decline { workspace: String, name: String },
}
impl Verb {
pub(crate) fn workspace_slot(&mut self) -> &mut String {
match self {
Self::Mint { workspace, .. }
| Self::List { workspace }
| Self::Approve { workspace, .. }
| Self::Decline { workspace, .. } => workspace,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum State {
Open,
Claimed,
Proved,
}
const STATES: [(State, &str); 3] = [
(State::Open, "open"),
(State::Claimed, "claimed"),
(State::Proved, "proved"),
];
impl State {
pub(crate) fn word(self) -> &'static str {
STATES
.iter()
.find(|(state, _)| *state == self)
.map_or("", |(_, word)| word)
}
pub(crate) fn of(word: &str) -> Option<Self> {
STATES
.iter()
.find(|(_, w)| *w == word)
.map(|(state, _)| *state)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Row {
pub name: String,
pub grade: Grade,
pub state: State,
pub expires: i64,
pub word: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Answer {
Offered { url: String, expires: i64 },
Offers(Vec<Row>),
Approved,
Declined,
}
pub(crate) fn code() -> Option<String> {
use ring::rand::SecureRandom;
let mut raw = [0u8; CODE_LEN];
ring::rand::SystemRandom::new().fill(&mut raw).ok()?;
Some(raw.iter().map(|byte| symbol(u32::from(*byte))).collect())
}
pub fn word(public_key_der: &[u8], ca_der: &[u8]) -> String {
let mut hashed = ring::digest::Context::new(&ring::digest::SHA256);
hashed.update(public_key_der);
hashed.update(ca_der);
let digest = hashed.finish();
let head = digest
.as_ref()
.iter()
.take(4)
.fold(0u32, |bits, byte| (bits << 8) | u32::from(*byte));
(0..WORD_LEN)
.map(|i| symbol(head >> (27 - 5 * i)))
.collect()
}
fn symbol(bits: u32) -> char {
let index = usize::try_from(bits & 31).unwrap_or_default();
ALPHABET.get(index).copied().map_or('A', char::from)
}
#[cfg(test)]
mod tests;