use std::fmt;
use crate::alphabets::{self, ResolvedAlphabet};
use crate::ff1::{self, AesCipher};
use crate::{Error, Key, COUNTER_BOUND, NO_NUMERAL};
const CYCLE_TWEAK_PREFIX: &str = "dealcode/v1c/";
#[derive(Clone, Debug)]
#[must_use = "call .build() to construct the codec"]
pub struct CyclingBuilder {
key: Key,
alphabet: String,
length: usize,
domain: String,
}
impl CyclingBuilder {
pub fn alphabet(mut self, alphabet: impl Into<String>) -> Self {
self.alphabet = alphabet.into();
self
}
pub fn length(mut self, length: usize) -> Self {
self.length = length;
self
}
pub fn domain(mut self, domain: impl Into<String>) -> Self {
self.domain = domain.into();
self
}
pub fn build(self) -> Result<CyclingDealcode, Error> {
CyclingDealcode::from_builder(self)
}
}
#[derive(Clone)]
pub struct CyclingDealcode {
alphabet: ResolvedAlphabet,
char_index: [u8; 128],
radix: u32,
length: usize,
domain: String,
capacity: u64,
max_cycle: u64,
cipher: AesCipher,
}
impl CyclingDealcode {
pub fn new(key: impl Into<Key>) -> Result<Self, Error> {
Self::builder(key).build()
}
pub fn builder(key: impl Into<Key>) -> CyclingBuilder {
CyclingBuilder {
key: key.into(),
alphabet: "hex".to_owned(),
length: 6,
domain: String::new(),
}
}
fn from_builder(builder: CyclingBuilder) -> Result<Self, Error> {
let aes_key = builder.key.resolve()?;
let alphabet = alphabets::resolve(&builder.alphabet).map_err(Error::Config)?;
let radix = alphabet.chars.chars().count() as u32;
let r = u128::from(radix);
let length = builder.length;
if !(2..=128).contains(&length) {
return Err(Error::Config("length must be in [2, 128]".to_owned()));
}
let capacity = match r.checked_pow(length as u32) {
Some(c) if c < 100 => {
return Err(Error::Config(
"radix^length must be at least 100 (FF1 minimum domain)".to_owned(),
))
}
Some(c) if c <= COUNTER_BOUND => c as u64,
_ => {
return Err(Error::Config(
"radix^length must not exceed 2^63 in cycling mode — a cycle must \
be completable; use Dealcode with min_length == max_length for \
larger fixed spaces"
.to_owned(),
))
}
};
if builder.domain.as_bytes().contains(&0) {
return Err(Error::Config("domain must not contain U+0000".to_owned()));
}
if builder.domain.len() > 255 {
return Err(Error::Config(
"domain must be at most 255 UTF-8 bytes".to_owned(),
));
}
let mut char_index = [NO_NUMERAL; 128];
for (i, c) in alphabet.chars.chars().enumerate() {
char_index[c as usize] = i as u8; }
Ok(CyclingDealcode {
alphabet,
char_index,
radix,
length,
domain: builder.domain,
capacity,
max_cycle: (COUNTER_BOUND - 1) as u64 / capacity,
cipher: AesCipher::new(&aes_key),
})
}
pub fn alphabet(&self) -> &str {
&self.alphabet.chars
}
pub fn radix(&self) -> u32 {
self.radix
}
pub fn length(&self) -> usize {
self.length
}
pub fn domain(&self) -> &str {
&self.domain
}
pub fn capacity(&self) -> u64 {
self.capacity
}
pub fn max_cycle(&self) -> u64 {
self.max_cycle
}
pub fn cycle_of(&self, n: u64) -> Result<u64, Error> {
if n >= COUNTER_BOUND as u64 {
return Err(Error::Range { n, capacity: COUNTER_BOUND as u64 });
}
Ok(n / self.capacity)
}
pub fn encode(&self, n: u64) -> Result<String, Error> {
if n >= COUNTER_BOUND as u64 {
return Err(Error::Range { n, capacity: COUNTER_BOUND as u64 });
}
let cycle = n / self.capacity;
let mut v = n % self.capacity;
let r = u64::from(self.radix);
let mut numerals = vec![0u8; self.length];
for slot in numerals.iter_mut().rev() {
*slot = (v % r) as u8;
v /= r;
}
let params = ff1::params(self.radix, &self.tweak_for(cycle), self.length);
let cipher_text = ff1::encrypt(&self.cipher, ¶ms, self.radix, &numerals);
let alphabet = self.alphabet.chars.as_bytes();
let bytes: Vec<u8> = cipher_text.iter().map(|&x| alphabet[x as usize]).collect();
Ok(String::from_utf8(bytes).expect("alphabet is ASCII"))
}
pub fn decode(&self, code: &str, cycle: u64) -> Result<u64, Error> {
if cycle > self.max_cycle {
return Err(Error::Range { n: cycle, capacity: self.max_cycle + 1 });
}
let d = code.chars().count();
if d != self.length {
return Err(Error::InvalidCode(format!(
"code length {d} != {} (fixed-length mode)",
self.length
)));
}
let mut numerals = Vec::with_capacity(d);
for c in code.chars() {
let c = self.alphabet.normalization.apply(c);
let numeral = if c.is_ascii() { self.char_index[c as usize] } else { NO_NUMERAL };
if numeral == NO_NUMERAL {
return Err(Error::InvalidCode(format!("character {c:?} not in alphabet")));
}
numerals.push(numeral);
}
let params = ff1::params(self.radix, &self.tweak_for(cycle), self.length);
let plain = ff1::decrypt(&self.cipher, ¶ms, self.radix, &numerals);
let v = ff1::num(u128::from(self.radix), &plain);
let n = u128::from(cycle) * u128::from(self.capacity) + v;
if n >= COUNTER_BOUND {
return Err(Error::InvalidCode("code was not issued in this cycle".to_owned()));
}
Ok(n as u64)
}
fn tweak_for(&self, cycle: u64) -> Vec<u8> {
format!("{CYCLE_TWEAK_PREFIX}{cycle}/{}", self.domain).into_bytes()
}
}
impl fmt::Debug for CyclingDealcode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let name = match self.alphabet.name {
Some(name) => name.to_owned(),
None => format!("custom({})", self.radix),
};
f.debug_struct("CyclingDealcode")
.field("alphabet", &name)
.field("length", &self.length)
.field("domain", &self.domain)
.finish_non_exhaustive()
}
}