iwlink 0.1.1

IntelliWallet Link - encrypted phone to computer protocol for IntelliWallet for Browser
Documentation
//! Protocol versions.
//!
//! The helper publishes the range it supports in its `info` characteristic,
//! which anyone in Bluetooth range can read. It therefore holds the range and
//! nothing else: no identifier, no name, nothing that tells one helper apart
//! from another.
//!
//! The phone reads the range, picks the highest version both sides support,
//! and binds that choice into the handshake prologue (see [`crate::noise`]), so
//! a man in the middle cannot talk the two sides down to an older version.

use crate::error::{LinkError, Result};

/// Highest protocol version this build speaks.
pub const PROTOCOL_VERSION: u16 = 1;

/// Lowest protocol version this build still speaks.
pub const MIN_PROTOCOL_VERSION: u16 = 1;

/// Magic bytes at the start of the `info` characteristic.
const INFO_MAGIC: [u8; 2] = *b"IW";

/// Length of the encoded `info` characteristic.
pub const INFO_LEN: usize = 6;

/// An inclusive range of protocol versions.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct VersionRange {
    pub min: u16,
    pub max: u16,
}

impl VersionRange {
    /// The range this build supports.
    pub const LOCAL: VersionRange = VersionRange {
        min: MIN_PROTOCOL_VERSION,
        max: PROTOCOL_VERSION,
    };

    /// Highest version in both ranges, or `None` when they do not overlap.
    pub fn negotiate(&self, peer: &VersionRange) -> Option<u16> {
        let high = self.max.min(peer.max);
        let low = self.min.max(peer.min);
        (high >= low).then_some(high)
    }

    /// Whether `version` lies inside this range.
    pub fn contains(&self, version: u16) -> bool {
        (self.min..=self.max).contains(&version)
    }

    /// Encode as the `info` characteristic value.
    pub fn encode_info(&self) -> [u8; INFO_LEN] {
        let mut out = [0u8; INFO_LEN];
        out[..2].copy_from_slice(&INFO_MAGIC);
        out[2..4].copy_from_slice(&self.min.to_be_bytes());
        out[4..6].copy_from_slice(&self.max.to_be_bytes());
        out
    }

    /// Decode an `info` characteristic value.
    ///
    /// Longer values are accepted and the tail ignored, so a later version can
    /// append fields without breaking this one.
    pub fn decode_info(bytes: &[u8]) -> Result<VersionRange> {
        if bytes.len() < INFO_LEN || bytes[..2] != INFO_MAGIC {
            return Err(LinkError::VersionMismatch);
        }
        let min = u16::from_be_bytes([bytes[2], bytes[3]]);
        let max = u16::from_be_bytes([bytes[4], bytes[5]]);
        if min == 0 || min > max {
            return Err(LinkError::VersionMismatch);
        }
        Ok(VersionRange { min, max })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn negotiates_highest_common_version() {
        let a = VersionRange { min: 1, max: 3 };
        let b = VersionRange { min: 2, max: 5 };
        assert_eq!(a.negotiate(&b), Some(3));
        assert_eq!(b.negotiate(&a), Some(3));
    }

    #[test]
    fn disjoint_ranges_do_not_negotiate() {
        let a = VersionRange { min: 1, max: 1 };
        let b = VersionRange { min: 2, max: 2 };
        assert_eq!(a.negotiate(&b), None);
    }

    #[test]
    fn info_round_trips() {
        let range = VersionRange { min: 1, max: 7 };
        assert_eq!(VersionRange::decode_info(&range.encode_info()), Ok(range));
    }

    #[test]
    fn info_accepts_a_longer_value() {
        let mut bytes = VersionRange::LOCAL.encode_info().to_vec();
        bytes.extend_from_slice(&[9, 9, 9]);
        assert_eq!(VersionRange::decode_info(&bytes), Ok(VersionRange::LOCAL));
    }

    #[test]
    fn info_rejects_garbage() {
        assert!(VersionRange::decode_info(b"").is_err());
        assert!(VersionRange::decode_info(b"XX\0\x01\0\x01").is_err());
        assert!(
            VersionRange::decode_info(b"IW\0\x02\0\x01").is_err(),
            "min above max"
        );
        assert!(
            VersionRange::decode_info(b"IW\0\0\0\x01").is_err(),
            "version zero"
        );
    }
}