//! Length buckets for chat plaintext. Normative spec: `docs/PROTOCOL.md`, //! “Length buckets”. //! //! Chat bodies are padded to one of eight sizes *before* the ratchet encrypts //! them, so the padding is authenticated by ChaCha20-Poly1305 and by the Noise //! session around it. An observer sees only the bucket. The encoding is //! explicit and never trimmed: //! //! ```text //! uint16 pad_len = big-endian length of the random fill that follows //! uint8 body[..] = the chat line //! uint8 fill[pad_len] = random bytes //! ``` //! //! The padded plaintext is exactly `bucket_for(body.len())` bytes, so //! `pad_len = bucket - 2 - body.len()`. A receiver accepts any total length (a //! peer implementation may use another ladder) but requires a consistent //! `pad_len`; an overrun fails closed instead of rendering a partial body. use rand::RngCore; use rand::rngs::OsRng; /// The explicit padding header: `uint16 pad_len`. pub const PAD_HEADER_LEN: usize = 2; /// The one ladder. Sizes are padded-plaintext lengths, not frame lengths. pub const BUCKETS: [usize; 8] = [256, 512, 1024, 2048, 4096, 8192, 16384, 32768]; /// The largest body that fits the largest bucket (`32768 - 2`). pub const MAX_BODY: usize = BUCKETS[BUCKETS.len() - 1] - PAD_HEADER_LEN; /// The ladder value a body of `body_len` bytes is padded to, or `None` when it /// does not fit the largest bucket. pub fn bucket_for(body_len: usize) -> Option { BUCKETS .iter() .copied() .find(|bucket| bucket - PAD_HEADER_LEN >= body_len) } /// `uint16 pad_len || body || random fill`, sized to one ladder value. pub fn encode(body: &[u8]) -> Result, String> { let bucket = bucket_for(body.len()).ok_or_else(|| { format!("chat message too large for the largest length bucket ({MAX_BODY} bytes)") })?; let pad_len = bucket - PAD_HEADER_LEN - body.len(); let mut out = Vec::with_capacity(bucket); out.extend_from_slice(&(pad_len as u16).to_be_bytes()); out.extend_from_slice(body); out.resize(bucket, 0); OsRng.fill_bytes(&mut out[PAD_HEADER_LEN + body.len()..]); Ok(out) } /// Strip the padding. Total length is not checked against the ladder on /// purpose; only the header and its bound are normative. pub fn decode(padded: &[u8]) -> Result<&[u8], String> { let header = padded .get(..PAD_HEADER_LEN) .ok_or("chat padding: no pad_len header")?; let pad_len = u16::from_be_bytes([header[0], header[1]]) as usize; let body_len = padded .len() .checked_sub(PAD_HEADER_LEN + pad_len) .ok_or("chat padding: pad_len overruns the plaintext")?; Ok(&padded[PAD_HEADER_LEN..PAD_HEADER_LEN + body_len]) }