use std::fmt;
use rand_core::CryptoRng;
use zeroize::Zeroizing;
use crate::{DecryptionKey, Key, SigningKey, VerifyingKey};
const SIGNING_CONTEXT: &str = "nibkeep 2026-11 recovery signing key";
const DECRYPTION_CONTEXT: &str = "nibkeep 2026-11 recovery decryption key";
const SECRETS_DECRYPTION_CONTEXT: &str = "nibkeep 2026-11 recovery secrets decryption key";
const NAME_CONTEXT: &str = "nibkeep 2026-11 recovery names";
const ALPHABET: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
const FORMAT: u8 = 1;
const GROUPS: usize = 13;
const GROUP_DATA: usize = 4;
const SYMBOLS: usize = GROUPS * (GROUP_DATA + 1);
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum NotARecoveryCode {
#[error("a recovery code has 65 letters and digits, in 13 groups of 5, and this has {0}")]
Length(usize),
#[error("group {0} of the recovery code holds a character that no code has")]
Character(usize),
#[error("group {0} of the recovery code is mistyped")]
Group(usize),
#[error("the recovery code is of a format that this version does not read")]
Format,
}
#[derive(Clone)]
pub struct RecoveryCode(Key);
impl RecoveryCode {
#[must_use]
pub fn generate(rng: &mut (impl CryptoRng + ?Sized)) -> Self {
Self(Key::generate(rng))
}
#[must_use]
pub const fn from_bytes(bytes: [u8; 32]) -> Self {
Self(Key::from_bytes(bytes))
}
#[must_use]
pub fn same_as(&self, other: &Self) -> bool {
self.0.same_as(&other.0)
}
#[must_use]
pub fn signing_key(&self) -> SigningKey {
SigningKey::from_bytes(self.0.derive(SIGNING_CONTEXT).expose_bytes())
}
#[must_use]
pub fn decryption_key(&self) -> DecryptionKey {
DecryptionKey::from_seed(self.0.derive(DECRYPTION_CONTEXT).expose_bytes())
}
#[must_use]
pub fn secrets_decryption_key(&self) -> DecryptionKey {
DecryptionKey::from_seed(self.0.derive(SECRETS_DECRYPTION_CONTEXT).expose_bytes())
}
#[must_use]
pub fn name_of(recovery_key: &VerifyingKey) -> String {
let hash = blake3::derive_key(NAME_CONTEXT, recovery_key.as_bytes());
let bits = u32::from_be_bytes([hash[0], hash[1], hash[2], hash[3]]);
(0..4)
.map(|place| char::from(ALPHABET[((bits >> (27 - 5 * place)) & 0x1f) as usize]))
.collect()
}
#[must_use]
pub fn to_text(&self) -> Zeroizing<String> {
let symbols = self.symbols();
let mut text = Zeroizing::new(String::with_capacity(SYMBOLS + GROUPS));
for (group, data) in symbols.as_chunks::<GROUP_DATA>().0.iter().enumerate() {
if group > 0 {
text.push('-');
}
for &symbol in data.iter().chain([&check(group, data)]) {
text.push(char::from(ALPHABET[usize::from(symbol)]));
}
}
text
}
pub fn from_text(text: &str) -> Result<Self, NotARecoveryCode> {
let mut symbols = Zeroizing::new([0_u8; SYMBOLS]);
let mut count = 0;
for character in text.chars() {
if character == '-' || character.is_whitespace() {
continue;
}
if count < SYMBOLS {
symbols[count] = symbol_of(character)
.ok_or(NotARecoveryCode::Character(count / (GROUP_DATA + 1) + 1))?;
}
count += 1;
}
if count != SYMBOLS {
return Err(NotARecoveryCode::Length(count));
}
let mut bits = Zeroizing::new([0_u8; 33]);
for (group, typed) in symbols
.as_chunks::<{ GROUP_DATA + 1 }>()
.0
.iter()
.enumerate()
{
let (data, checked) = typed.split_at(GROUP_DATA);
if check(group, data) != checked[0] {
return Err(NotARecoveryCode::Group(group + 1));
}
for (place, &symbol) in data.iter().enumerate() {
let at = (group * GROUP_DATA + place) * 5;
let shifted = u16::from(symbol) << (11 - at % 8);
bits[at / 8] |= shifted.to_be_bytes()[0];
bits[at / 8 + 1] |= shifted.to_be_bytes()[1];
}
}
if bits[0] >> 4 != FORMAT {
return Err(NotARecoveryCode::Format);
}
let Ok(key) = Key::fill_with(|key| {
for (index, byte) in key.iter_mut().enumerate() {
*byte = (bits[index] << 4) | (bits[index + 1] >> 4);
}
Ok::<(), std::convert::Infallible>(())
});
Ok(Self(key))
}
fn symbols(&self) -> Zeroizing<[u8; GROUPS * GROUP_DATA]> {
let code = self.0.expose_bytes();
let mut bits = Zeroizing::new([0_u8; 33]);
bits[0] = (FORMAT << 4) | (code[0] >> 4);
for index in 1..32 {
bits[index] = (code[index - 1] << 4) | (code[index] >> 4);
}
bits[32] = code[31] << 4;
let mut symbols = Zeroizing::new([0_u8; GROUPS * GROUP_DATA]);
for (index, symbol) in symbols.iter_mut().enumerate() {
let at = index * 5;
let window = u16::from_be_bytes([bits[at / 8], bits[at / 8 + 1]]);
*symbol = ((window >> (11 - at % 8)) & 0x1f) as u8;
}
symbols
}
}
impl fmt::Debug for RecoveryCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("RecoveryCode(..)")
}
}
fn symbol_of(character: char) -> Option<u8> {
let character = match character.to_ascii_uppercase() {
'I' | 'L' => '1',
'O' => '0',
other => other,
};
let place = ALPHABET
.iter()
.position(|&symbol| char::from(symbol) == character)?;
u8::try_from(place).ok()
}
fn check(group: usize, data: &[u8]) -> u8 {
let number = u8::try_from(group + 1).unwrap_or(0);
data.iter().fold(0, |sum, &symbol| times_a(sum ^ symbol)) ^ number
}
const fn times_a(element: u8) -> u8 {
((element << 1) & 0x1f) ^ (0x05 & 0_u8.wrapping_sub((element >> 4) & 1))
}