use crate::duplex::Duplex;
use crate::grumpkin::Point;
use crate::lattice::{Ciphertext, EK_BYTES, Kpke, MlKemKeys, Noise, PqKey};
use crate::poseidon::{Poseidon, Rng};
use crate::{Error, Fr};
pub type Payload<const N: usize> = [Fr; N];
use ark_ff::Zero;
use std::collections::HashMap;
pub struct Ratchet;
impl Ratchet {
fn d(label: &str) -> Fr {
Poseidon::domain(&format!("pq-ratchet/{label}/v1"))
}
pub fn key_payload() -> Fr {
Self::d("key-payload")
}
pub fn key_note() -> Fr {
Self::d("key-note")
}
pub fn tag(shared: Point, pq_commitment: Fr) -> Fr {
Poseidon::hash(&[Self::d("tag"), shared.x, shared.y, pq_commitment])
}
pub fn root(
m: &[u8; 32],
shared: Point,
ephemeral: Point,
ct_commitment: Fr,
pq_commitment: Fr,
) -> Fr {
let h = PqKey::halves(m);
Poseidon::hash(&[
Self::d("root"),
h[0],
h[1],
shared.x,
shared.y,
ephemeral.x,
ephemeral.y,
ct_commitment,
pq_commitment,
])
}
pub fn next(s: Fr) -> Fr {
Poseidon::hash(&[Self::d("ratchet"), s])
}
pub fn commit(s: Fr) -> Fr {
Poseidon::hash(&[Self::d("commit"), s])
}
pub fn key(domain: Fr, s: Fr, ctx: Fr) -> Fr {
Poseidon::hash(&[Self::d("key"), s, ctx, domain])
}
pub fn seal(domain: Fr, s: Fr, ctx: Fr, plaintext: &[Fr]) -> Result<(Fr, Vec<Fr>), Error> {
let c = Self::commit(s);
Ok((
c,
Duplex::seal(Self::key(domain, s, ctx), c, Fr::zero(), ctx, plaintext)?,
))
}
pub fn open(domain: Fr, s: Fr, c: Fr, ctx: Fr, ciphertext: &[Fr]) -> Result<Vec<Fr>, Error> {
Duplex::open(Self::key(domain, s, ctx), c, Fr::zero(), ctx, ciphertext)
}
pub fn payload_commitment<const N: usize>(salt: Fr, payload: &Payload<N>) -> Fr {
let mut v = vec![
Poseidon::domain(&format!("pq-channel/payload/v1/{N}")),
salt,
];
v.extend_from_slice(payload);
Poseidon::hash(&v)
}
pub fn seal_payload<const N: usize>(
key: Fr,
s: Fr,
ctx: Fr,
payload: &Payload<N>,
) -> Result<(Fr, [Fr; N]), Error> {
let (c, ct) = Self::seal(key, s, ctx, payload)?;
Ok((c, ct.try_into().expect("N fields")))
}
pub fn open_payload<const N: usize>(
key: Fr,
s: Fr,
c_t: Fr,
ctx: Fr,
ciphertext: &[Fr; N],
) -> Result<Payload<N>, Error> {
Ok(Self::open(key, s, c_t, ctx, ciphertext)?
.try_into()
.expect("N fields"))
}
}
#[derive(Debug, Clone)]
pub struct ReceiverPublic {
pub grumpkin: Point,
pub ek: [u8; EK_BYTES],
pub pq: PqKey,
pub pq_commitment: Fr,
}
impl ReceiverPublic {
pub fn from_published(grumpkin: Point, ek: &[u8; EK_BYTES]) -> Result<Self, Error> {
if !grumpkin.is_valid() {
return Err(Error::NotOnCurve);
}
let pq = PqKey::expand(ek)?;
Ok(Self {
grumpkin,
ek: *ek,
pq_commitment: pq.commitment(),
pq,
})
}
}
pub struct ReceiverKeys {
pub(crate) v: Fr,
pub(crate) keys: MlKemKeys,
pub public: ReceiverPublic,
}
impl ReceiverKeys {
pub fn generate() -> Self {
Self::from_secrets(Rng::field(), MlKemKeys::generate())
}
pub fn from_secrets(v: Fr, keys: MlKemKeys) -> Self {
let grumpkin = Point::generator_mul(v).expect("nonzero secret");
let public =
ReceiverPublic::from_published(grumpkin, &keys.ek).expect("a fresh ML-KEM key expands");
Self { v, keys, public }
}
pub fn ek(&self) -> &[u8; EK_BYTES] {
&self.keys.ek
}
pub fn secrets(&self) -> (Fr, [u8; 64]) {
(self.v, self.keys.seed)
}
pub fn recognises(&self, ephemeral: Point, tag: Fr) -> bool {
ephemeral
.mul(self.v)
.is_ok_and(|z| Ratchet::tag(z, self.public.pq_commitment) == tag)
}
pub fn handshake_root(
&self,
ephemeral: Point,
tag: Fr,
ct_commitment: Fr,
c0: Fr,
ct: &Ciphertext,
) -> Result<Fr, Error> {
let shared = ephemeral.mul(self.v)?;
if Ratchet::tag(shared, self.public.pq_commitment) != tag {
return Err(Error::NotForUs);
}
if ct.commitment() != ct_commitment {
return Err(Error::CiphertextMismatch);
}
let m = Kpke::decrypt(&self.keys.dk, ct);
let s0 = Ratchet::root(
&m,
shared,
ephemeral,
ct_commitment,
self.public.pq_commitment,
);
if Ratchet::commit(s0) != c0 {
return Err(Error::HandshakeMismatch);
}
Ok(s0)
}
}
#[derive(Debug, Clone)]
pub struct Handshake {
pub ephemeral: Point,
pub tag: Fr,
pub ct_commitment: Fr,
pub root: Fr,
pub ct: Ciphertext,
}
impl Handshake {
pub fn new(to: &ReceiverPublic, e: Fr, noise: &Noise, m: &[u8; 32]) -> Result<Self, Error> {
let shared = to.grumpkin.mul(e)?;
let ephemeral = Point::generator_mul(e)?;
let ct = Kpke::encrypt(&to.pq, noise, m)?;
let ct_commitment = ct.commitment();
Ok(Self {
ephemeral,
tag: Ratchet::tag(shared, to.pq_commitment),
ct_commitment,
root: Ratchet::root(m, shared, ephemeral, ct_commitment, to.pq_commitment),
ct,
})
}
}
#[derive(Debug, Clone)]
pub struct SenderChain {
pub(crate) t: u64,
pub(crate) s: Fr,
}
impl SenderChain {
pub fn after_handshake(s0: Fr) -> Self {
Self {
t: 1,
s: Ratchet::next(s0),
}
}
pub fn index(&self) -> u64 {
self.t
}
pub fn advance(&mut self) -> (u64, Fr) {
let out = (self.t, self.s);
self.s = Ratchet::next(self.s);
self.t += 1;
out
}
}
#[derive(Debug, Clone)]
pub struct Session {
pub(crate) next_t: u64,
pub(crate) next_s: Fr,
pub(crate) window: u64,
pub(crate) highest: u64,
pub(crate) max_skipped: usize,
pub(crate) keys: HashMap<Fr, (u64, Fr)>,
}
impl Session {
pub fn start(s0: Fr, window: u64) -> Self {
Self::start_with(
s0,
window,
usize::try_from(window).expect("window fits usize"),
)
}
pub fn start_with(s0: Fr, window: u64, max_skipped: usize) -> Self {
let mut session = Session {
next_t: 1,
next_s: Ratchet::next(s0),
window,
highest: 0,
max_skipped,
keys: HashMap::new(),
};
session.fill(window);
session
}
fn fill(&mut self, upto: u64) {
while self.next_t <= upto {
self.keys
.insert(Ratchet::commit(self.next_s), (self.next_t, self.next_s));
self.next_s = Ratchet::next(self.next_s);
self.next_t += 1;
}
}
fn expire(&mut self) {
let mut old: Vec<(u64, Fr)> = self
.keys
.iter()
.filter(|(_, (t, _))| *t < self.highest)
.map(|(c, (t, _))| (*t, *c))
.collect();
old.sort();
for (_, c) in old.iter().take(old.len().saturating_sub(self.max_skipped)) {
self.keys.remove(c);
}
}
pub fn peek(&self, c: Fr) -> Option<(u64, Fr)> {
self.keys.get(&c).copied()
}
pub fn take(&mut self, c: Fr) -> Result<(u64, Fr), Error> {
let (t, s) = self.keys.remove(&c).ok_or(Error::UnknownCommitment)?;
self.highest = self.highest.max(t);
self.fill(t + self.window);
self.expire();
Ok((t, s))
}
pub fn held(&self) -> usize {
self.keys.len()
}
pub fn skipped(&self) -> usize {
self.keys
.values()
.filter(|(t, _)| *t < self.highest)
.count()
}
pub fn resync(&mut self, n: u64) {
self.fill(self.next_t - 1 + n);
}
}