teter-core 26.11.7

What teter's clients share without I/O: end-to-end encryption, account crypto, signed commands
Documentation
//! A session's history kept on disk across restarts (#93), as a frontend
//! gets it: the machine seals each chunk of what its terminal printed to the
//! account's public keys ([`crate::account::seal_to`] with [`CHUNK_INFO`]),
//! so it can write them but not read them back; after a restart, the session
//! process sends the chunks it kept before, unopened, with the time it
//! started and its screen, in one replay of kind
//! [`crate::e2e::Kind::History`]; the device opens the chunks with the
//! account's private key.

/// What a history chunk is sealed to the account with.
pub const CHUNK_INFO: &[u8] = b"teter session history v1";

/// A replay with the history from before a restart.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HistoryReplay {
    /// The chunks, oldest first, each sealed to the account.
    pub chunks: Vec<Vec<u8>>,
    /// When the session process started again (Unix seconds).
    pub restarted_at: i64,
    /// The screen now, as a plain replay holds it.
    pub screen: Vec<u8>,
}

/// `replay` as bytes: the number of chunks (u32), each chunk's length (u32)
/// and bytes, the time (i64), then the screen; big-endian.
#[must_use]
pub fn encode_replay(replay: &HistoryReplay) -> Vec<u8> {
    let mut bytes = Vec::new();
    let len = |n: usize| u32::try_from(n).unwrap_or(u32::MAX).to_be_bytes();
    bytes.extend_from_slice(&len(replay.chunks.len()));
    for chunk in &replay.chunks {
        bytes.extend_from_slice(&len(chunk.len()));
        bytes.extend_from_slice(chunk);
    }
    bytes.extend_from_slice(&replay.restarted_at.to_be_bytes());
    bytes.extend_from_slice(&replay.screen);
    bytes
}

/// The replay `bytes` hold, if they are one.
#[must_use]
pub fn decode_replay(bytes: &[u8]) -> Option<HistoryReplay> {
    fn take<'a>(rest: &mut &'a [u8], n: usize) -> Option<&'a [u8]> {
        let (taken, after) = (rest.get(..n)?, rest.get(n..)?);
        *rest = after;
        Some(taken)
    }
    fn number(rest: &mut &[u8]) -> Option<usize> {
        let bytes: [u8; 4] = take(rest, 4)?.try_into().ok()?;
        usize::try_from(u32::from_be_bytes(bytes)).ok()
    }
    let mut rest = bytes;
    let count = number(&mut rest)?;
    let mut chunks = Vec::new();
    for _ in 0..count {
        let n = number(&mut rest)?;
        chunks.push(take(&mut rest, n)?.to_vec());
    }
    let time: [u8; 8] = take(&mut rest, 8)?.try_into().ok()?;
    Some(HistoryReplay {
        chunks,
        restarted_at: i64::from_be_bytes(time),
        screen: rest.to_vec(),
    })
}

#[cfg(test)]
mod tests {
    use super::{HistoryReplay, decode_replay, encode_replay};

    #[test]
    fn a_replay_comes_back_as_it_went_and_a_cut_one_does_not() {
        let replay = HistoryReplay {
            chunks: vec![b"one".to_vec(), Vec::new(), b"three".to_vec()],
            restarted_at: 1_795_737_600,
            screen: b"\x1b[Hscreen".to_vec(),
        };
        let bytes = encode_replay(&replay);
        assert_eq!(decode_replay(&bytes), Some(replay));
        assert_eq!(decode_replay(&bytes[..10]), None);
        assert_eq!(decode_replay(&[0, 0, 0, 9]), None);
    }
}